text
stringlengths
8
6.88M
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // Copyright (c) 2013 Adrian Serio // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/config/config_strings.hpp> #include <pika/config/version.hpp> #include <pika/prefix/find_prefix.hpp> #include <pika/preprocessor/stringize.hpp> #include <cstdint> #include <string> #include <string_view> /////////////////////////////////////////////////////////////////////////////// namespace pika { // Returns the major pika version. constexpr std::uint8_t major_version() { return PIKA_VERSION_MAJOR; } // Returns the minor pika version. constexpr std::uint8_t minor_version() { return PIKA_VERSION_MINOR; } // Returns the sub-minor/patch-level pika version. constexpr std::uint8_t patch_version() { return PIKA_VERSION_PATCH; } // Returns the full pika version. constexpr std::uint32_t full_version() { return PIKA_VERSION_FULL; } // Returns the full pika version. PIKA_EXPORT std::string full_version_as_string(); // Returns the tag. constexpr std::string_view tag() { return PIKA_VERSION_TAG; } // Return the pika configuration information. PIKA_EXPORT std::string configuration_string(); // Returns the pika version string. PIKA_EXPORT std::string build_string(); // Returns the pika build type ('Debug', 'Release', etc.) constexpr std::string_view build_type() { return PIKA_PP_STRINGIZE(PIKA_BUILD_TYPE); } // Returns the pika build date and time PIKA_EXPORT std::string build_date_time(); // Returns the pika full build information string. PIKA_EXPORT std::string full_build_string(); // Returns the copyright string. constexpr std::string_view copyright() { char const* const copyright = "pika\n\n" "Copyright (c) 2021-2022, ETH Zurich,\n" "https://github.com/pika-org/pika\n\n" "Distributed under the Boost Software License, Version 1.0. (See accompanying\n" "file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n"; return copyright; } // Returns the full version string. PIKA_EXPORT std::string complete_version(); } // namespace pika
void operator()( const ast::file& file ) const { indent() << "<file>" << std::endl; for( const ast::function_definition& func : file.functions ) { recurse( func ); } } void operator()( const ast::function_argument& arg ) { indent() << "<function argument " << static_cast< const std::string& >( arg.name ) << ": " << static_cast< const std::string& >( arg.type ) << std::endl; } void operator()( const ast::void_expression& ) const { indent() << "<void expression>" << std::endl; } void operator()( const ast::string_literal& str ) const { indent() << "<string literal \"" << static_cast< const std::u32string& >( str ) << "\">" << std::endl; } void operator()( std::int32_t n ) const { indent() << "<integer literal " << n << ">" << std::endl; } void operator()( bool b ) const { indent() << "<bool literal " << std::boolalpha << b << ">" << std::endl; } void operator()( const ast::if_expression& exp ) const { indent() << "<if>" << std::endl; recurse( exp.condition ); recurse( exp.then_expression ); recurse( exp.else_expression ); } void operator()( const ast::while_expression& exp ) const { indent() << "<while>" << std::endl; recurse( exp.condition ); recurse( exp.body ); } void operator()( const ast::return_expression& exp ) const { indent() << "<return>" << std::endl; recurse( exp.value ); } void operator()( const ast::block_expression& block ) const { indent() << "<block>" << std::endl; for( const ast::block_member& member : block.body ) { recurse( member ); } }
#ifndef _PQUEUE_CPP #define _PQUEUE_CPP #include "pqueue.h" template <class T> pqueue<T>::pqueue(vector<T> elem) { size = elem.size(); numE = 0; heap = new T[size]; for (int i = 0; i < size; i++) { heap[i] = elem[i]; buildbottomup(i); numE++; } } template <class T> void pqueue<T>::buildbottomup(int index) { if (index == 0) { return; } int p_index = (index - 1) / 2; if (heap[p_index] > heap[index]) { T temp = heap[p_index]; heap[p_index] = heap[index]; heap[index] = temp; buildbottomup(p_index); } } template <class T> void pqueue<T>::minheapify(int index, int size) { if (index >= numE - 1) { return; } int left = 2*index + 1; int right = 2*index + 2; if (right <= numE - 1 && heap[right] < heap[index]) { T temp = heap[right]; heap[right] = heap[index]; heap[index] = temp; minheapify(right, size); } if (left <= numE - 1 && heap[left] < heap[index]) { T temp = heap[left]; heap[left] = heap[index]; heap[index] = temp; minheapify(left, size); } } template <class T> void pqueue<T>::DecreaseKey(T node) { int index = 0; for (int i = 0; i < numE; i++) { if (heap[i]->name == node->name) { index = i; break; } } buildbottomup(index); } template <class T> T pqueue<T>::ExtractMin() { T min = heap[0]; heap[0] = heap[numE - 1]; numE--; minheapify(0, size); return min; } #endif
#include <iostream> #include <thread> #include <future> #include <string> void thFunc(std::promise<std::string> && prm) { std::string str("Hello from future!"); std::this_thread::sleep_for(std::chrono::seconds(1)); prm.set_value(str); } int main() { std::promise<std::string> prm; std::future<std::string> ftr = prm.get_future(); std::thread th(&thFunc, std::move(prm)); std::cout << "Hello from main!" << std::endl; std::string str = ftr.get(); std::cout << str << std::endl; th.join(); return 0; }
// // TexturedOBJObject.cpp // Dev // // Created by Wahid Chowdhury on 6/3/13. // Copyright (c) 2013 Wahid Chowdhury. All rights reserved. // #include "TexturedOBJObject.h" #include "GLJoe.h" using namespace GLJoe; void TexturedOBJObject::initializeOpenGLBuffers() { OBJObject::initializeOpenGLBuffers(); //Load the image we will use for texture mapping imgloader.loadImage(textureFileName, image, imageWidth, imageHeight); //All this state will be present in the vao of the parent class glGenTextures(1, &textureMemory); glBindTexture(GL_TEXTURE_2D, textureMemory); /* GLuint bufferForTextureCoords; glGenBuffers(1, &bufferForTextureCoords); glBindBuffer(GL_ARRAY_BUFFER, bufferForTextureCoords); Vec2 tex[6] = { Vec2(1.0, 0.3), Vec2(1.0, 1.3), Vec2(0.0, 0.3), Vec2(1.0, 1.3), Vec2(0.0, 0.3), Vec2(0.0, 1.3) }; GLsizeiptr numBytesTexCoords = num_vertices * sizeof(GLJoe::Vec2); glBufferData( GL_ARRAY_BUFFER,numBytesNormals + numBytesVertices + numBytesTexCoords, NULL, GL_STATIC_DRAW ); glBufferSubData(GL_ARRAY_BUFFER, 0, numBytesNormals, plane_normals); glBufferSubData(GL_ARRAY_BUFFER,numBytesNormals, numBytesVertices, plane_vertices); glBufferSubData(GL_ARRAY_BUFFER, numBytesNormals + numBytesVertices, numBytesTexCoords, tex_coords); //GLuint vNormal = glGetAttribLocation( program, "vNormal" ); glEnableVertexAttribArray( handles.vNormal ); glVertexAttribPointer(handles.vNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); //GLuint vPosition = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray(handles.vPosition ); glVertexAttribPointer( handles.vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(numBytesNormals) ); //GLuint vPosition = glGetAttribLocation( program, "vTexCoords" ); glEnableVertexAttribArray(handles.vTexCoords ); glVertexAttribPointer( handles.vTexCoords, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(numBytesNormals + numBytesVertices) ); */ /* glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glUniform1i(shaderHandles.tex, 0); */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap( GL_TEXTURE_2D ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glUniform1i(shaderHandles.tex, 0); } void TexturedOBJObject::drawSelf() { #ifdef __APPLE__ //apple glBindVertexArrayAPPLE(vao); #else glBindVertexArray(vao); #endif glBindTexture( GL_TEXTURE_2D, textureMemory ); //Turn on Textures glUniform1i(shaderHandles.EnableTex, 1); glUniform1i(shaderHandles.calculateTexCoordInShader, 1); OBJObject::drawSelf(); glUniform1i(shaderHandles.calculateTexCoordInShader, 0); //Turn off Textures glUniform1i(shaderHandles.EnableTex, 0); }
#include <string> #include <fmt/core.h> int main(int, char**){ using namespace std::literals; const auto x = "Hello"s; const auto y = "World"s; fmt::print("{}, {}!\n", x, y); return 0; }
#include <iostream> #include <limits.h> int main () { int i = 2; while (i + 1 > 0) { i *= 2; }; std:: cout << "Maximum value of int: " << i-1 << " " << INT_MAX << std::endl; std:: cout << "Minimum value of int: " << i << " " << INT_MIN << std::endl; std:: cout << "Maximum value of float: " << i-1 << " " << std::endl; std:: cout << "Minimum value of float: " << i << " " << std::endl; return 0; }
#pragma once #include "proto/data_base.pb.h" #include "proto/data_player.pb.h" #include "proto/ss_base.pb.h" #include "proto/processor.hpp" #include "utils/client_process_base.hpp" #include "proto/ss_login.pb.h" #include "utils/client_process_mgr.hpp" namespace pd = proto::data; namespace ps = proto::ss; namespace nora { namespace login { class scene : public proto::processor<scene, ps::base>, public client_process_base, public enable_shared_from_this<scene> { public: scene(const string& name); static void static_init(const shared_ptr<service_thread>& st = nullptr); friend ostream& operator<<(ostream& os, const scene& s) { return os << s.name_; } static string base_name(); static set<uint32_t> fetch_server_ids(const string& username); private: const string name_; static map<uint32_t, set<string>> server_id2username_; void process_username_sync(const ps::base *msg); }; } }
#pragma once #include <QWidget> #include <QSplitter> class SplitTerm : public QWidget { Q_OBJECT public: SplitTerm(QWidget* parent = NULL); virtual ~SplitTerm(); private: SplitTerm(QWidget* parent, QWidget* konsole); signals: void closed(); private slots: void addSplitTerm(Qt::Orientation dir); void childClosed(); private: QSplitter* s; QWidget* k; };
#include <OGLML/DynamicQuadRender.h> #include <glew.h> #include <glfw3.h> using namespace oglml; DynamicQuadRender::DynamicQuadRender() { const short int VERTEX_NUM = 4; const short int VERTEX_COORD_TEX_COORD_NUM = 5; const short int VERTEX_COORD_NUM = 3; const short int TEX_COORD_NUM = 2; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * VERTEX_NUM * VERTEX_COORD_TEX_COORD_NUM, nullptr, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, VERTEX_COORD_NUM, GL_FLOAT, GL_FALSE, VERTEX_COORD_TEX_COORD_NUM * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, TEX_COORD_NUM, GL_FLOAT, GL_FALSE, VERTEX_COORD_TEX_COORD_NUM * sizeof(float), (void*)(VERTEX_COORD_NUM * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } DynamicQuadRender::~DynamicQuadRender() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); } DynamicQuadRender& DynamicQuadRender::Get() { static DynamicQuadRender quadRender; return quadRender; } void DynamicQuadRender::Draw() { glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); } void DynamicQuadRender::BindVAO() { glBindVertexArray(VAO); } void DynamicQuadRender::BindBuffer() { glBindBuffer(GL_ARRAY_BUFFER, VBO); }
#pragma once #include "sequence.h" namespace u_interface_sort { void sort_interface(); }
#include "metodosOrdenacao.h" #include <fstream> #include "Dados.h" using namespace std; MetodosOrdenacao::MetodosOrdenacao(int n) { tamanhoPreenchido = n; } MetodosOrdenacao::~MetodosOrdenacao() { } void MetodosOrdenacao::Particao(Dados dados[], int Esq, int Dir, int *i, int *j) { Dados pivo, w; *i = Esq; *j = Dir; pivo = dados[(*i + *j) / 2]; do { while (taAntesZe(dados[*i].Nome, (pivo).Nome)){ (*i)++; } while (taAntesZe((pivo).Nome, dados[*j].Nome)){ (*j)--; } if (*i <= *j) { w = dados[*i]; dados[*i] = dados[*j]; dados[*j] = w; (*i)++; (*j)--; } } while (*i <= *j); } void MetodosOrdenacao::Ordena(Dados dados[], int Esq, int Dir) { int i, j; Particao(dados, Esq, Dir, &i, &j); if (Esq < j) Ordena(dados, Esq, j); if (i < Dir) Ordena(dados, i, Dir); } void MetodosOrdenacao::QuickSort(Dados dados[]) { Ordena(dados, 0, tamanhoPreenchido - 1); } bool taAntesZe(string primeiraStr, string segundaStr) { int aux; if (primeiraStr.size() < segundaStr.size()) { aux = primeiraStr.size(); } else { aux = segundaStr.size(); } for (int i = 0; i < aux; i++) { if (primeiraStr[i] != segundaStr[i]) { return primeiraStr[i] < segundaStr[i]; } } return (segundaStr.size() > primeiraStr.size()); } void MetodosOrdenacao::Merge(Dados dados[], int e, int m, int d) { auto const numEsq = m - e + 1; auto const numDir = d - m; Dados *esquerda = new Dados[numEsq]; Dados *direita = new Dados[numDir]; for (int i = 0; i < numEsq; i++) { esquerda[i] = dados[e + i]; } for (int j = 0; j < numDir; j++) { direita[j] = dados[m + 1 + j]; } int i = 0, j = 0, k = e; while (i < numEsq && j < numDir) { if (taAntesZe(esquerda[i].Nome, direita[j].Nome)) { dados[k] = esquerda[i]; i++; } else { dados[k] = direita[j]; j++; } k++; } while (i < numEsq) { dados[k] = esquerda[i]; i++; k++; } while (j < numDir) { dados[k] = direita[j]; j++; k++; } delete esquerda; delete direita; } void MetodosOrdenacao::MergeSort(Dados dados[], int esq, int dir) { if (esq < dir) { int m = esq + (dir - esq) / 2; MergeSort(dados, esq, m); MergeSort(dados, m + 1, dir); Merge(dados, esq, m, dir); } } void MetodosOrdenacao::Heapify(Dados dados[], int n, int i) { int maior = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && dados[l].Numero > dados[maior].Numero) maior = l; if (r < n && dados[r].Numero > dados[maior].Numero) maior = r; if (maior != i) { swap(dados[i], dados[maior]); Heapify(dados, n, maior); } } void MetodosOrdenacao::HeapSort(Dados dados[], int n) { for (int i = n / 2 - 1; i >= 0; i--) Heapify(dados, n, i); for (int i = n - 1; i >= 0; i--) { swap(dados[0], dados[i]); Heapify(dados, i, 0); } } int pegaMax(Dados dados[], int n) { int max = dados[0].Numero; for (int i = 1; i < n; i++) if (dados[i].Numero > max) max = dados[i].Numero; return max; } void countingSort(Dados dados[], int tam, int place) { const int max = 10; int output[tam]; int count[max]; for (int i = 0; i < max; ++i) count[i] = 0; for (int i = 0; i < tam; i++) count[(dados[i].Numero / place) % 10]++; for (int i = 1; i < max; i++) count[i] += count[i - 1]; for (int i = tam - 1; i >= 0; i--) { output[count[(dados[i].Numero / place) % 10] - 1] = dados[i].Numero; count[(dados[i].Numero / place) % 10]--; } for (int i = 0; i < tam; i++) dados[i].Numero = output[i]; } void MetodosOrdenacao::RadixSort(Dados dados[], int tam) { int max = pegaMax(dados, tam); for (int place = 1; max / place > 0; place *= 10) countingSort(dados, tam, place); }
// Copyright (c) 2019 The NavCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef NAVCOINLISTWIDGET_H #define NAVCOINLISTWIDGET_H #include <QFrame> #include <QLabel> #include <QListWidget> #include <QLineEdit> #include <QPushButton> #include <QString> #include <QStringList> #include <QVBoxLayout> #include <QWidget> typedef std::function<bool(QString)> ValidatorFunc; class NavCoinListWidget : public QWidget { Q_OBJECT public: explicit NavCoinListWidget(QWidget *parent, QString title, ValidatorFunc validator); QStringList getEntries(); private: QListWidget* listWidget; QLineEdit* addInput; QPushButton* removeBtn; QLabel* warningLbl; ValidatorFunc validatorFunc; private Q_SLOTS: void onInsert(); void onRemove(); void onSelect(QListWidgetItem*); }; #endif // NAVCOINLISTWIDGET_H
/* * ===================================================================================== * * Filename: fonc_factory_gnu.h * * Description: * * Version: 1.0 * Created: 24/05/2017 21:33:10 * Revision: none * Compiler: gcc * * Author: Jobs (), charlesdavid.blot@fgmail.com * Organization: * * ===================================================================================== */ #ifndef FONC_FACTORY_H #define FONC_FACTORY_H #include <memory> #include "fonc_factory.h" typedef double (*gnu_math_fonc)(double); class fonc_factory_gnu : public fonc_factory { public: fonc_factory_gnu(gnu_math_fonc fc, const char *name); ~fonc_factory_gnu(); std::shared_ptr<fonc> build(); private: const char *name; gnu_math_fonc fc; }; #endif
#include "Cuboid.h" Cuboid::Cuboid(float x, float y, float z, float dX, float dY, float dZ) { position[0] = x; position[1] = y; position[2] = z; dim[0] = dX; dim[1] = dY; dim[2] = dZ; testOType = 0.5f; orientation = glm::mat4(1.0f); GLfloat vertex_array_data[] = { -dX / 2.0f, -dY / 2.0f, dZ / 2.0f, 0.0f, 0.0f, 1.0f, //1 - 0 dX / 2.0f, -dY / 2.0f, dZ / 2.0f, 0.0f, 0.0f, 1.0f, //2 - 1 dX / 2.0f, dY / 2.0f, dZ / 2.0f, 0.0f, 0.0f, 1.0f, //3 - 2 -dX / 2.0f, dY / 2.0f, dZ / 2.0f, 0.0f, 0.0f, 1.0f, //4 - 3 -dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, 0.0f, 0.0f, -1.0f, //5 - 4 dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, 0.0f, 0.0f, -1.0f, //6 - 5 dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 0.0f, 0.0f, -1.0f, //7 - 6 -dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 0.0f, 0.0f, -1.0f, //8 - 7 -dX / 2.0f, -dY / 2.0f, dZ / 2.0f, -1.0f, 0.0f, 0.0f, //1 - 8 dX / 2.0f, -dY / 2.0f, dZ / 2.0f, -1.0f, 0.0f, 0.0f, //2 - 9 dX / 2.0f, dY / 2.0f, dZ / 2.0f, 1.0f, 0.0f, 0.0f, //3 - 10 -dX / 2.0f, dY / 2.0f, dZ / 2.0f, 1.0f, 0.0f, 0.0f, //4 - 11 -dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, -1.0f, 0.0f, 0.0f, //5 - 12 dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, -1.0f, 0.0f, 0.0f, //6 - 13 dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 1.0f, 0.0f, 0.0f, //7 - 14 -dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 1.0f, 0.0f, 0.0f, //8 - 15 -dX / 2.0f, -dY / 2.0f, dZ / 2.0f, 0.0f, -1.0f, 0.0f, //1 - 16 dX / 2.0f, -dY / 2.0f, dZ / 2.0f, 0.0f, 1.0f, 0.0f, //2 - 17 dX / 2.0f, dY / 2.0f, dZ / 2.0f, 0.0f, 1.0f, 0.0f, //3 - 18 -dX / 2.0f, dY / 2.0f, dZ / 2.0f, 0.0f, -1.0f, 0.0f, //4 - 19 -dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, 0.0f, -1.0f, 0.0f, //5 - 20 dX / 2.0f, -dY / 2.0f, -dZ / 2.0f, 0.0f, 1.0f, 0.0f, //6 - 21 dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 0.0f, 1.0f, 0.0f, //7 - 22 -dX / 2.0f, dY / 2.0f, -dZ / 2.0f, 0.0f, -1.0f, 0.0f, //8 - 23 }; static const GLuint index_array_data[] = { 0, 1, 2, //Z-positiv/nära 0, 2, 3, // 7, 5, 4, //Z-negativ/borta 7, 6, 5, // 8, 12, 9, //X-negativ/vänster 13, 9, 12, // 10, 14, 11, //X-positiv/höger 11, 14, 15, // 17, 21, 18, //Y-positiv/ovan 18, 21, 22, // 16, 19, 23, //Y-negativ/under 20, 16, 23, // }; nVerts = 24; nTris = 12; vertexArray = new vertex[nVerts]; // coordinates, normals and texture coordinates //stArray = new texST[nVerts]; indexArray = new triangle[nTris]; int dIndex = 0; for (int i = 0; i < nVerts; i++) { dIndex = i * 6; vertexArray[i].xyz[0] = vertex_array_data[dIndex]; vertexArray[i].xyz[1] = vertex_array_data[dIndex + 1]; vertexArray[i].xyz[2] = vertex_array_data[dIndex + 2]; vertexArray[i].nxyz[0] = vertex_array_data[dIndex + 3]; vertexArray[i].nxyz[1] = vertex_array_data[dIndex + 4]; vertexArray[i].nxyz[2] = vertex_array_data[dIndex + 5]; //stArray[i].st[0] = vertex_array_data[dIndex + 6]; //stArray[i].st[1] = vertex_array_data[dIndex + 7]; } for (int i = 0; i < nTris; i++) { indexArray[i].index[0] = index_array_data[i*3]; indexArray[i].index[1] = index_array_data[i*3 + 1]; indexArray[i].index[2] = index_array_data[i*3 + 2]; } } Cuboid::~Cuboid() { } void Cuboid::createBuffers() { cuboidData* vData; // Generate one vertex array object (VAO) and bind it glGenVertexArrays(1, &(vao)); glBindVertexArray(vao); // Generate two buffer IDs glGenBuffers(1, &vertexbuffer); glGenBuffers(1, &indexbuffer); // Activate the vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); // Present our vertex coordinates to OpenGL glBufferData(GL_ARRAY_BUFFER, nVerts * sizeof(cuboidData), NULL, GL_STATIC_DRAW); vData = (cuboidData*)glMapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(cuboidData) *nVerts, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_UNSYNCHRONIZED_BIT); for (int i = 0; i < nVerts; i++) { vData[i].x = vertexArray[i].xyz[0]; vData[i].y = vertexArray[i].xyz[1]; vData[i].z = vertexArray[i].xyz[2]; vData[i].nx = vertexArray[i].nxyz[0]; vData[i].ny = vertexArray[i].nxyz[1]; vData[i].nz = vertexArray[i].nxyz[2]; //vData[i].s = stArray[i].st[0]; //vData[i].t = stArray[i].st[1]; } glUnmapBuffer(GL_ARRAY_BUFFER); // Specify how many attribute arrays we have in our VAO glEnableVertexAttribArray(0); // Vertex coordinates glEnableVertexAttribArray(1); // Normals glEnableVertexAttribArray(2); // Texture coordinates // Specify how OpenGL should interpret the vertex buffer data: // Attributes 0, 1, 2 (must match the lines above and the layout in the shader) // Number of dimensions (3 means vec3 in the shader, 2 means vec2) // Type GL_FLOAT // Not normalized (GL_FALSE) // Stride 8 floats (interleaved array with 8 floats per vertex) // Array buffer offset 0, 3 or 6 floats (offset into first vertex) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(cuboidData), (void*)0); // xyz coordinates glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(cuboidData), (void*)(3 * sizeof(GLfloat))); // normals //glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, // sizeof(cuboidData), (void*)(6 * sizeof(GLfloat))); // texcoords // Activate the index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer); // Present our vertex indices to OpenGL glBufferData(GL_ELEMENT_ARRAY_BUFFER, nTris * sizeof(triangle), NULL, GL_STATIC_DRAW); triangle* tData; tData = (triangle*)glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(triangle) * nTris, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_UNSYNCHRONIZED_BIT); for (int i = 0; i < nTris; i++) { tData[i].index[0] = indexArray[i].index[0]; tData[i].index[1] = indexArray[i].index[1]; tData[i].index[2] = indexArray[i].index[2]; } glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); // Deactivate (unbind) the VAO and the buffers again. // Do NOT unbind the index buffer while the VAO is still bound. // The index buffer is an essential part of the VAO state. glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void Cuboid::render() { glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, nVerts, GL_UNSIGNED_INT, (void*)0); // (mode, vertex count, type, element array buffer offset) glBindVertexArray(0); }
// // Created by Marklar on 2017/5/19. // #include <list> #include <string> #include <sstream> #include <iostream> #include "command_line/CommandLine.hpp" #include "alpha/alpha.hpp" int main(int argc, char **argv) { std::string cmd_name(argv[0]); std::list<std::string> items; std::stringstream cl_ss; cl_ss << argv[0]; for (int i = 1; i < argc; i++) { items.push_back(std::string(argv[i])); cl_ss << ' ' << argv[i]; } auto cl_str = cl_ss.str(); std::string err; CommandLine alpha_cl( { {'h', "help"}, {'v', "version"}, {'e', "evaluate"}, {'c', "console"}, {'f', "file"}, {'p', "print"} }, { {"evaluate", [&](const auto &try_bind) { try_bind([&](const auto &name, const auto &do_bind) { if (!name.size()) err = "--evaluate requires an argument"; else do_bind(); }); }}, {"file", [&](const auto &try_bind) { try_bind([&](const auto &name, const auto &do_bind) { if (!name.size()) err = "--file requires an argument"; else do_bind(); }); }} } ); auto clp = alpha_cl.parse(items, err); if (!err.size()) { auto options = std::get<0>(clp); auto arguments = std::get<1>(clp); if (options.find("help") != options.end()) { std::cout << "Usage: " << cmd_name << " [options]\n" << '\n' << "Options:\n" << " -h, --help\n" << " -v, --version\t\t\tprint alpha-interpreter version\n" << " -e, --evaluate {script}\tevaluate script\n" << " -c, --console\n" << " -f, --file {file_path}\n" << " -p, --print\t\t\tprint result\n" << "\nDocumentation can be found at https://github.com/ai-artisan/cpp-alpha_interpreter\n"; } else if (options.find("version") != options.end()) { std::cout << "x.x.x\n"; } else { alpha::Process process; process.commandLine(cl_str); auto print = (options.find("print") != options.end()); auto i = options.find("evaluate"); if (i != options.end()) { std::stringstream ss; ss << *i->second.cbegin(); alpha::Process::within(&process, [&](const auto &eval) { auto result = eval(ss); if (process.escapeType() && process.escapeType() != alpha::EscapeType::EXIT) std::cout << "# uncaught " << alpha::Functions::Literal::toCString(result) << '\n'; else if (print) std::cout << alpha::Functions::Literal::toCString(result) << '\n'; }); } else if ((!options.size() && !arguments.size()) || (i = options.find("console")) != options.end()) { if (!options.size()) print = true; do { std::cout << "> "; alpha::Process::within(&process, [&](const auto &eval) { auto result = eval(std::cin); if (process.escapeType() && process.escapeType() != alpha::EscapeType::EXIT) std::cout << "# uncaught " << alpha::Functions::Literal::toCString(result) << '\n'; else if (print) std::cout << alpha::Functions::Literal::toCString(result) << '\n'; }); } while (process.escapeType() != alpha::EscapeType::EXIT); } else { std::string file_name = ""; if ((i = options.find("file")) != options.end()) file_name = *i->second.cbegin(); else if (arguments.size()) file_name = *arguments.cbegin(); if (file_name.size()) { std::ifstream ifs(file_name); if (!ifs.is_open()) err = "cannot load script file '" + file_name + "'"; else { alpha::Process::within(&process, [&](const auto &eval) { auto result = eval(ifs); if (process.escapeType() && process.escapeType() != alpha::EscapeType::EXIT) std::cout << "# uncaught " << alpha::Functions::Literal::toCString(result) << '\n'; else if (print) std::cout << alpha::Functions::Literal::toCString(result) << '\n'; }); } } } } } if (err.size()) std::cout << "alpha: " << err << '\n'; return 0; }
#ifndef BASE_CHECK_H_ #define BASE_CHECK_H_ #include <assert.h> #include "base/scheduling/scheduling_handles.h" #include "base/threading/thread.h" namespace base { #define CHECK(condition) assert(condition) #define CHECK_EQ(actual, expected) CHECK(actual == expected) #define CHECK_GE(actual, expected) CHECK(actual >= expected) #define CHECK_LT(actual, expected) CHECK(actual < expected) #define NOTREACHED() CHECK(false) // Threading and scheduling. #define CHECK_ON_THREAD(thread_type) \ switch (thread_type) { \ case ThreadType::UI: \ CHECK(base::GetCurrentThreadTaskLoop()); \ CHECK_EQ(base::GetUIThreadTaskLoop(), base::GetCurrentThreadTaskLoop()); \ break; \ case ThreadType::IO: \ CHECK(base::GetCurrentThreadTaskLoop()); \ CHECK_EQ(base::GetIOThreadTaskLoop(), base::GetCurrentThreadTaskLoop()); \ break; \ case ThreadType::WORKER: \ NOTREACHED(); \ break; \ } } // namespace base #endif // BASE_CHECK_H_
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const LL mod = 1e9 + 7; int a[100100]; int main() { int t,n; scanf("%d",&t); while (t--) { scanf("%d",&n); for (int i = 1;i < n; i++) scanf("%d",&a[i]);a[n] = 0; LL ans = 26; for (int i = n-1;i >= 1; i--) { if (!a[i]) ans = ans*25%mod; else if (a[i] != a[i+1]+1) { ans = 0; break; } } printf("%d\n",ans); } return 0; }
#ifndef APP_HH #define APP_HH #include <sys/resource.h> #include <iostream> #include <fstream> #include <boost/program_options.hpp> #include <boost/program_options/parsers.hpp> #include "task.hh" #include "logging.hh" #include "descriptors.hh" namespace ten { static int set_maxrlimit(int resource, rlim_t &max) { struct rlimit rl; if (getrlimit(resource, &rl) == -1) { return -1; } VLOG(3) << "resource: " << resource << " rlim_cur: " << rl.rlim_cur << " rlim_max: " << rl.rlim_max; max = rl.rlim_cur = rl.rlim_max; return setrlimit(resource, &rl); } //! inherit application config from this struct app_config { std::string config_path; rlim_t min_fds; // google glog options std::string glog_log_dir; int glog_minloglevel; int glog_v; std::string glog_vmodule; int glog_max_log_size; }; namespace po = boost::program_options; //! setup basic options for all applications struct options { po::options_description generic; po::options_description configuration; po::options_description hidden; po::positional_options_description pdesc; po::options_description cmdline_options; po::options_description config_file_options; po::options_description visible; options(const char *appname, app_config &c) : generic("Generic options"), configuration("Configuration"), hidden("Hidden options"), visible("Allowed options") { generic.add_options() ("version,v", "Show version") ("help", "Show help message") ; std::string conffile(appname); conffile += ".conf"; configuration.add_options() ("config", po::value<std::string>(&c.config_path)->default_value(conffile), "config file path") ("min-fds", po::value<rlim_t>(&c.min_fds)->default_value(0), "minimum number of file descriptors required to run") ("glog-log-dir", po::value<std::string>(&c.glog_log_dir)->default_value(""), "log files will be written to this directory") ("glog-minloglevel", po::value<int>(&c.glog_minloglevel)->default_value(0), "log messages at or above this level") ("glog-v", po::value<int>(&c.glog_v)->default_value(0), "show vlog messages for <= to value") ("glog-vmodule", po::value<std::string>(&c.glog_vmodule), "comma separated <module>=<level>. overides glog-v") ("glog-max-log-size", po::value<int>(&c.glog_max_log_size)->default_value(1800), "max log size (in MB)") ; } void setup() { cmdline_options.add(generic).add(configuration).add(hidden); config_file_options.add(configuration).add(hidden); visible.add(generic).add(configuration); } }; class application { public: options opts; po::variables_map vm; std::string name; std::string version; std::string usage; std::string usage_example; application(const char *version_, app_config &c, const char *name_= program_invocation_short_name) : opts(name_, c), name(name_), version(version_), _conf(c), sigpi(O_NONBLOCK) { if (global_app != 0) { throw errorx("there can be only one application"); } global_app = this; } ~application() { google::ShutdownGoogleLogging(); } void showhelp(std::ostream &os = std::cerr) { if (!usage.empty()) std::cerr << usage << std::endl; std::cerr << opts.visible << std::endl; if (!usage_example.empty()) std::cerr << usage_example << std::endl; } void parse_args(int argc, char *argv[]) { try { opts.setup(); po::store(po::command_line_parser(argc, argv) .options(opts.cmdline_options).positional(opts.pdesc).run(), vm); po::notify(vm); if (vm.count("help")) { showhelp(); exit(1); } std::ifstream config_stream(_conf.config_path.c_str()); po::store(po::parse_config_file(config_stream, opts.config_file_options), vm); po::notify(vm); if (vm.count("version")) { std::cerr << version << std::endl; exit(1); } // configure glog since we use our own command line/config parsing // instead of the google arg parsing if (_conf.glog_log_dir.empty()) { FLAGS_logtostderr = true; } FLAGS_log_dir = _conf.glog_log_dir; FLAGS_minloglevel = _conf.glog_minloglevel; FLAGS_v = _conf.glog_v; FLAGS_vmodule = _conf.glog_vmodule; FLAGS_max_log_size = _conf.glog_max_log_size; // setrlimit to increase max fds // http://www.kernel.org/doc/man-pages/online/pages/man2/getrlimit.2.html rlim_t rmax = 0; if (set_maxrlimit(RLIMIT_NOFILE, rmax)) { PLOG(ERROR) << "setting fd limit failed"; } // add 1 because NOFILE is 0 indexed and min_fds is a count if (rmax+1 < _conf.min_fds) { LOG(ERROR) << "could not set RLIMIT_NOFILE high enough: " << rmax+1 << " < " << _conf.min_fds; exit(1); } // turn on core dumps if (set_maxrlimit(RLIMIT_CORE, rmax)) { PLOG(ERROR) << "setting max core size limit failed"; } } catch (std::exception &e) { std::cerr << "Error: " << e.what() << std::endl << std::endl; showhelp(); exit(1); } } template <typename ConfigT> const ConfigT &conf() const { return static_cast<ConfigT &>(_conf); } int run() { struct sigaction act; memset(&act, 0, sizeof(act)); // install SIGINT handler THROW_ON_ERROR(sigaction(SIGINT, NULL, &act)); if (act.sa_handler == SIG_DFL) { act.sa_sigaction = application::signal_handler; act.sa_flags = SA_RESTART | SA_SIGINFO; THROW_ON_ERROR(sigaction(SIGINT, &act, NULL)); taskspawn(std::bind(&application::signal_task, this), 4*1024); } return p.main(); } void quit() { procshutdown(); } private: app_config &_conf; procmain p; pipe_fd sigpi; static application *global_app; void signal_task() { taskname("app::signal_task"); tasksystem(); int sig_num = 0; for (;;) { fdwait(sigpi.r.fd, 'r'); ssize_t nr = sigpi.read(&sig_num, sizeof(sig_num)); if (nr != sizeof(sig_num)) abort(); LOG(WARNING) << strsignal(sig_num) << " received"; switch (sig_num) { case SIGINT: quit(); break; } } } static void signal_handler(int sig_num, siginfo_t *info, void *ctxt) { ssize_t nw = global_app->sigpi.write(&sig_num, sizeof(sig_num)); (void)nw; // not much we can do if this fails } }; application *application::global_app = 0; } // end namespace ten #endif // APP_HH
#pragma once #include "plbase/PluginBase.h" #pragma pack(push, 1) class PLUGIN_API CPickupText { public: float m_fX; float m_fY; int field_8; float m_fW; float m_fH; class RwRGBA m_Color; char flags; char field_19; char __padding[2]; int m_dwPrice; int m_dwTextMessage; }; #pragma pack(pop)
#ifndef PROJECTILE_HPP #define PROJECTILE_HPP #include "box2d/box2d.h" #include "body.hpp" #include <vector> #include "agent.hpp" class Projectile : public Body { public: Projectile(b2World& world, float posX = 0.f, float posY = 0.f, b2Shape* shape = nullptr); void Update(float fElapsedTime) override; // void Render(olc::PixelGameEngine& pge); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2005-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Partially stolen from Emil's code in libgogi. */ #ifndef _OP_REGION_H #define _OP_REGION_H #include "modules/util/adt/opvector.h" class OpRect; class OpRegion; class OpRegionIterator { public: OpRegionIterator(const OpRegion* region) : m_region(region), m_idx(UINT_MAX) {} BOOL First(); BOOL Next(); const OpRect& GetRect() const; private: const OpRegion* m_region; unsigned int m_idx; }; class OpRegion { friend class OpRegionIterator; public: OpRegion(); ~OpRegion(); /** * Remove a rectangle from the region. */ BOOL RemoveRect(const OpRect& rect); /** * Add a rectangle to the region. If the rectangle is * overlapping other rectangles in the region, rect will be * sliced up so the region contains no overlapping * rectangles. returns true if success. * * @param rect The rect to include in the region. Must not be * empty. */ BOOL IncludeRect(const OpRect& rect); /** * Make this region the union of itself and another region. * The result will not contain overlapping rectangles. * * @param region The region to include. * * @return TRUE on success. */ BOOL IncludeRegion(const OpRegion& region); /** * Checks if a point is a member of the region. */ BOOL Includes(int x, int y) const; /** * Checks if the region is empty. */ BOOL IsEmpty() const { return m_num_rects == 0; } /** * Get a count of non-overlapping rectangles. * * @return Count of non-overlapping rectangles. */ int GetRectCount() const { return m_num_rects; } /** * Empties the region. */ void Empty(); #ifdef SVG_EXTENDED_OP_REGION_API /** * Allocates a copy of the current region and assigns newRegion * to this copy. * @param newRegion A pointer that will point to the newly * allocated OpRegion on return * @return OpStatus::OK on success, OpStatus::ERR_NO_MEMORY on OOM */ OP_STATUS Duplicate(OpRegion* &newRegion) const; #endif // SVG_EXTENDED_OP_REGION_API /** * Intersect each of the rectangles in the region with the given * rectangle. */ void IntersectWith(const OpRect& r); #ifndef SVG_OPTIMIZE_RENDER_MULTI_PASS /** * This method intersects |rect| with every part of the region and * then returns the union of the results. It can be compared to an * |Intersect| method but does not have the guarantee that the * returned rect will only contain points in both the opregion and * the rect. */ OpRect GetUnionOfIntersectingRects(const OpRect& rect) const; #endif // !SVG_OPTIMIZE_RENDER_MULTI_PASS /** * This method returns the union of the all parts of the region. * The result will be a rect enclosing the region. */ OpRect GetUnionOfRects() const; /** Return region's intersection with a rectangle. * * @param rect The rectangle with which to intersect this region. * * @param rect_list An empty vector to which to add OpRect pointers, which * the caller shall be responsible for deleting on success (e.g. by using an * OpAutoVector as rect_list); on failure, rect_list shall be emptied using * DeleteAll(). * * @return See OpStatus; may OOM. */ OP_STATUS GetArrayOfIntersectingRects(const OpRect& rect, OpVector<OpRect>& rect_list) const; /** * Optimize the region's representation. */ void CoalesceRects(); /** * Translate the region. */ void Translate(int tx, int ty); /** * Get an iterator able to iterate the rects making up the region. * The rects can be in any order, but are guaranteed to be * non-overlapping. */ OpRegionIterator GetIterator() const { return OpRegionIterator(this); } private: OpRect *m_rects; int m_num_rects; int m_max_rects; /** * Remove a rectangle from the region. */ void RemoveRect(int index); /** * Resize the rect array to contain to specified amount */ BOOL Resize(unsigned int new_capacity); /** * Increase capacity to hold atleast extra_capacity more rects */ BOOL Expand(unsigned int extra_capacity); /** * Try to shrink the rect array */ BOOL TryShrink(); /** * Increase capacity to hold atleast one more rect */ BOOL GrowIfNeeded() { return (m_num_rects != m_max_rects) || Expand(m_max_rects == 0 ? 1 : 4); } /** * Add a rectangle to the region. returns true if success. */ BOOL AddRect(const OpRect& rect); /** * Will split up the existing rectangles into smaller * rectangles to exclude remove. returns TRUE if success. */ BOOL ExcludeRect(const OpRect& rect, const OpRect& remove); /** * Partition the rectangles into intersecting / non-intersecting * based on input rect. The start index of the intersecting half * and an estimated amount to grow the rectangle array is returned. * * @returns FALSE if the rect is contained by a rectangle in the region, otherwise TRUE */ BOOL Partition(const OpRect& rect, unsigned int& isect_start, unsigned int& grow_with); /** * Remove the overlap between rect and the region. Assumes that * data is partitioned, and that the overlapping rectangles start * at isect_start * * @returns FALSE on OOM, otherwise TRUE */ BOOL RemoveOverlap(const OpRect& rect, unsigned int isect_start); #ifdef _DEBUG int m_debug_allowed_to_conflict; #endif // _DEBUG }; inline BOOL OpRegionIterator::First() { m_idx = 0; return !m_region->IsEmpty(); } inline BOOL OpRegionIterator::Next() { m_idx++; return m_idx < (unsigned int)m_region->m_num_rects; } inline const OpRect& OpRegionIterator::GetRect() const { return m_region->m_rects[m_idx]; } #endif // _OP_REGION_H
#include "PLayerThrowClimb.h" #include "Player.h" #include "PlayerClimbState.h" PLayerThrowClimb::PLayerThrowClimb(PlayerData *playerData) { this->mPlayerData = playerData; } PLayerThrowClimb::~PLayerThrowClimb() { } void PLayerThrowClimb::Update(float dt) { int curFrame = mPlayerData->player->GetCurrentAnimation()->GetCurrentFrame(); if (curFrame == 4) { this->mPlayerData->player->GetCurrentAnimation()->Reset(); this->mPlayerData->player->SetState(new PlayerFallingState(mPlayerData)); } } void PLayerThrowClimb::HandleKeyboard(std::map<int, bool> keys) { } PlayerState::StateName PLayerThrowClimb::GetState() { return PlayerState::ThrowCLimb; } void PLayerThrowClimb::OnCollision(Entity *impactor, Entity::SideCollisions side, Entity::CollisionReturn data) { return; }
#pragma once #include "COMALG.h" #include <windows.h> #include <msclr/marshal.h> namespace Zipper_winForms_ { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::OpenFileDialog^ openFileDialog2; private: protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MyForm::typeid)); this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->openFileDialog2 = (gcnew System::Windows::Forms::OpenFileDialog()); this->SuspendLayout(); // // openFileDialog1 // this->openFileDialog1->FileName = L"openFileDialog1"; // // button2 // this->button2->BackColor = System::Drawing::SystemColors::ControlLightLight; this->button2->Font = (gcnew System::Drawing::Font(L"Vineta BT", 18, System::Drawing::FontStyle::Italic, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button2->Location = System::Drawing::Point(12, 12); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(294, 50); this->button2->TabIndex = 1; this->button2->Text = L"COMPRESS"; this->button2->UseVisualStyleBackColor = false; this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click); // // button3 // this->button3->BackColor = System::Drawing::SystemColors::ControlLightLight; this->button3->Font = (gcnew System::Drawing::Font(L"Vineta BT", 18, System::Drawing::FontStyle::Italic, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button3->Location = System::Drawing::Point(12, 80); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(294, 51); this->button3->TabIndex = 2; this->button3->Text = L"DECOMPRESS"; this->button3->UseVisualStyleBackColor = false; this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click); // // label1 // this->label1->Font = (gcnew System::Drawing::Font(L"Lucida Fax", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label1->Location = System::Drawing::Point(25, 155); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(271, 29); this->label1->TabIndex = 3; this->label1->Text = L"Press compress/decompress and chose the File"; this->label1->Click += gcnew System::EventHandler(this, &MyForm::label1_Click); // // openFileDialog2 // this->openFileDialog2->FileName = L"openFileDialog2"; this->openFileDialog2->Filter = L"(*.lzw)|*.lzw"; // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(7, 14); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"$this.BackgroundImage"))); this->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Center; this->ClientSize = System::Drawing::Size(318, 346); this->Controls->Add(this->label1); this->Controls->Add(this->button3); this->Controls->Add(this->button2); this->Font = (gcnew System::Drawing::Font(L"Showcard Gothic", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); //this->Name = L"MyForm"; this->Text = L"LZW"; this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load); this->ResumeLayout(false); } #pragma endregion public: String^ Name_file_input; char* Name; float index; const char* str2; public: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) { CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW", NULL); CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW\\Uncompressed", NULL); CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW\\Compressed", NULL); System::IO::StreamReader ^ sr = gcnew System::IO::StreamReader(openFileDialog1->FileName); OpenFileDialog^ ofDlg = gcnew OpenFileDialog(); ofDlg->Multiselect = false; Name_file_input = openFileDialog1->FileName; using namespace msclr::interop; marshal_context ^ context = gcnew marshal_context(); const char* str2 = context->marshal_as<const char*>(Name_file_input); label1->Text = "Wait please, compression in progress"; index = com(str2); if (index > 0) { label1->Text = "Compression complete! Archive size decrease in " + index + "%"; } else { label1->Text = "Compression complete! No or minimal size decrease"; } } } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { if (openFileDialog2->ShowDialog() == System::Windows::Forms::DialogResult::OK) { CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW", NULL); CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW\\Uncompressed", NULL); CreateDirectoryW(L"C:\\Users\\Public\\Documents\\LZW\\Compressed", NULL); System::IO::StreamReader ^ sr = gcnew System::IO::StreamReader(openFileDialog2->FileName); OpenFileDialog^ ofDlg = gcnew OpenFileDialog(); ofDlg->Multiselect = false; Name_file_input = openFileDialog2->FileName; using namespace msclr::interop; marshal_context ^ context = gcnew marshal_context(); const char* str2 = context->marshal_as<const char*>(Name_file_input); // label1->Text-> label1->Text = "Wait please, decompression in progress"; decom(str2); label1->Text = "Decompression complete!"; } } private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) { } private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) { } }; } //184
#pragma once #include"stdfax.h" class Penalty_method { private: vector_2d X0; double r, C, eps; void input(string Filename); double F(double X, double Y,double Rk); //4Gaus vector<double> Xk, Xk_1; function<double(double)> F_1; double eps0, eps1; void Check_Interval(pair<double, double> &Interval, int n_var); pair<double, double> Find_Interval(double x0); double Arg_min(int n_var, bool method); double Dichotomy(double &a0, double &b0); vector<double> FindMin(vector<double> X, double e0, double e1,bool method); public: int Num_iteration = 0; int Num_calculation = 0; Penalty_method(string Filename); Penalty_method(vector_2d X, double R, double c, double e); vector_2d Calc_Penalty(); vector_2d Calc_Barrier(); static double f(double X,double Y); static double P(double X, double Y, double Rk); static double P_Barrier(double X, double Y, double Rk); };
#include <iostream> #include <algorithm> #include <iterator> #include <vector> using namespace std; class Solution{ public: vector<vector<int> > subsets(vector<int>& nums){ sort(nums.begin(), nums.end()); vector<vector<int> > result; vector<int> empty; result.push_back(empty); for(int i = 0; i < nums.size(); ++i){ int tempResultSize = result.size(); for(int j = 0; j < tempResultSize; ++j){ vector<int> tempSet; tempSet = result[j]; tempSet.push_back(nums[i]); result.push_back(tempSet); } } return result; } }; int main(int argc, char const *argv[]) { Solution sol; ostream_iterator<int> out_iter(cout, " "); //int ia[] = {1, 4, 3, 2}; //vector<int> nums(ia, sizeof(ia)/sizeof(int)); vector<int> nums = {1, 4, 2, 3}; auto res = sol.subsets(nums); for(int i = 0; i < res.size(); ++i){ copy(res[i].begin(), res[i].end(), out_iter); cout << endl; } return 0; }
#ifndef _GetPlayerListProc_H_ #define _GetPlayerListProc_H_ #include "BaseProcess.h" class GetPlayerListProc : public BaseProcess { public: GetPlayerListProc(); virtual ~GetPlayerListProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ; }; #endif
// // Created by fab on 31/05/2020. // #ifndef DUMBERENGINE_MESH_HPP #define DUMBERENGINE_MESH_HPP #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <vector> #include "../../utils/Vertex.hpp" #include "../../rendering/helper/Shader.hpp" #include "../../rendering/renderer/opengl/Texture2D.hpp" #include <cereal/archives/portable_binary.hpp> class Mesh { public: Mesh(std::vector<Vertex>& vertices, std::vector<unsigned int>& indices, std::vector<Texture2D*>& textures); void draw(Shader* shader); void drawShadows(); ~Mesh() { glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ebo); for(auto tex : textures) delete tex; }; template<class Archive> void serialize(Archive & archive) { archive(vertices, indices); //TODO: make this possible by serializing textures , textures); } std::vector<Texture2D*>& getTextures() { return textures; } Texture2D* getTextureByType(Texture2D::ETextureType type); void addTexture(Texture2D* tex) { textures.push_back(tex); } void addTexture(const std::string_view& path, ITexture::ETextureType type) { auto* tex = new Texture2D(); tex->loadFrom(path.data(), type); textures.push_back(tex); } private: // render data unsigned int vao; unsigned int vbo; unsigned int ebo; // mesh data std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<Texture2D*> textures; }; #endif //DUMBERENGINE_MESH_HPP
#ifndef APPLICATION_INCLUDED #define APPLICATION_INCLUDED #include <Window.hpp> #include <Renderer.hpp> class Application { public: Application(HINSTANCE instance) : _instance(instance), _window(*this), _renderer(_window) { } HINSTANCE instance() const { return _instance; } Renderer& renderer() { return _renderer; } void run(); private: HINSTANCE _instance; Window _window; Renderer _renderer; }; #endif
//Declaración de constantes const int pinLectura = 1; //La lectura analógica la reslizaremos en el pin A0 const int pinLed = 6; int contadorFade = 0; int sentidoDeFade = 0; int contadorDeCiclos = 0; unsigned long milisActual =0; unsigned long milisAnterior = 0; void setup() { //Inicializa la comunicación serial a 9600 bits por segundo Serial.begin(115200);//Aumentamos la velocidad de transferencia d elos datos para consumir menos tiempo al //imprimir en el monitor serie. //Recuerda modificar la velocidad del monitor serie en la esquina inferior derecha de la ventana //para que conicida con la velocidad con la que se inicializa el puerto serie de la tarjeta Resistor UNO pinMode(pinLed, OUTPUT); } void loop() { //Almacena la información de la entrada analógica en la variable “valorSensor” Serial.print("Coclo loop#: ");//Comenta esta línea para que el efecto fade sea un poco más rápido Serial.println(contadorDeCiclos++);//Comenta esta línea para que el efecto fade sea un poco más rápido int valorSensor = analogRead(pinLectura);//la función devuelve un número que se encuentra entre 0 y 1023 donde 0 corresponde a 0V y 1023 a 5v int tiempoDelay = map(valorSensor,0,1023, 1, 10);//Escalamos el "valorSensor" a un valor que se encuentre entre 0 y 10 milisActual = millis();//Obtenemos el tiempo en ms que ha transcurrido desde que el programa inicio if ((milisActual - milisAnterior) > tiempoDelay ){//Si el tiempo trancurrido desde la pultima vriación a la variable "contadorFade" milisAnterior = milisActual;//Actualizamos el tiempo transcurrido desde que el programa inició hasta la última actualización if (sentidoDeFade ==0){ //Sentido ascendente if(contadorFade<255){//Si no se ha alcanzado el límeite superior analogWrite(pinLed, contadorFade); contadorFade++; } else{ //Si ya se alcanzó el límite superior sentidoDeFade = 1; } } else{ //Sentido descendente if(contadorFade>0){//Si no se ha alcanzado el límite inferior analogWrite(pinLed, contadorFade); contadorFade--; } else{ //Si ya se alzanzó el sentido descendente sentidoDeFade = 0; } } } }
// Created on: 1998-10-29 // Created by: Jean Yves LEBEY // Copyright (c) 1998-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 _TopOpeBRep_Hctxee2d_HeaderFile #define _TopOpeBRep_Hctxee2d_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Edge.hxx> #include <Geom2dAdaptor_Curve.hxx> #include <IntRes2d_Domain.hxx> #include <Standard_Transient.hxx> #include <Standard_Integer.hxx> class BRepAdaptor_Surface; class TopoDS_Shape; class TopOpeBRep_Hctxee2d; DEFINE_STANDARD_HANDLE(TopOpeBRep_Hctxee2d, Standard_Transient) class TopOpeBRep_Hctxee2d : public Standard_Transient { public: Standard_EXPORT TopOpeBRep_Hctxee2d(); Standard_EXPORT void SetEdges (const TopoDS_Edge& E1, const TopoDS_Edge& E2, const BRepAdaptor_Surface& BAS1, const BRepAdaptor_Surface& BAS2); Standard_EXPORT const TopoDS_Shape& Edge (const Standard_Integer I) const; Standard_EXPORT const Geom2dAdaptor_Curve& Curve (const Standard_Integer I) const; Standard_EXPORT const IntRes2d_Domain& Domain (const Standard_Integer I) const; DEFINE_STANDARD_RTTIEXT(TopOpeBRep_Hctxee2d,Standard_Transient) protected: private: TopoDS_Edge myEdge1; Geom2dAdaptor_Curve myCurve1; IntRes2d_Domain myDomain1; TopoDS_Edge myEdge2; Geom2dAdaptor_Curve myCurve2; IntRes2d_Domain myDomain2; }; #endif // _TopOpeBRep_Hctxee2d_HeaderFile
// // Created by Yujing Shen on 28/05/2017. // #ifndef TENSORGRAPH_SESSIONOPTIMIZER_H #define TENSORGRAPH_SESSIONOPTIMIZER_H #include "TensorGraph.h" namespace sjtu{ class SessionOptimizer { public: SessionOptimizer(Session* sess); SessionOptimizer(const SessionOptimizer &rhs); virtual ~SessionOptimizer(); virtual Optimizer subscribe(Node node); virtual Optimizer run(Node node) = 0; virtual Optimizer init(int Itype) = 0; protected: Tensor tensor_like(Node node); map<Node, int> subjects; int _sz; Session* _sess; }; } #endif //TENSORGRAPH_SESSIONOPTIMIZER_H
#include "BMPHEAD.h" #include "PIXELDATA.h" #include <string> using namespace std; class image { public: BMPHEAD info; PIXELDATA **bitmap; }; class readImage:public image{ void readInfoHeader(image&,FILE*); public: image read(const char*); }; class resizeImage :public image { public: image resize(image&, double); }; class saveImage :public image { void saveInfoHeader(image&,FILE*); public: void save(image&, const char*); };
void setup() { Serial.begin(115200); delay(20); // Give port time to initalize // mpu_setup(); // Lidarsetup() Armsetup(); } void loop() { String data = Serial.readStringUntil('\n'); //------------Sensor data--------------- //getlidardata(); //getlidardata2(); //motion_sense(); //--------------------------------- delay(10); Serial.println(" ok "+data); }
// Author: Andrew Edwards // Email: ancedwar@ucsc.edu // ID: 1253060 // Date: 2015 Jan 18 #include <iostream> #include <sstream> #include <stdexcept> #include <iomanip> using namespace std; #include "debug.h" #include "inode.h" int inode::next_inode_nr {1}; inode::inode(inode_t init_type): inode_nr (next_inode_nr++), type (init_type) { switch (type) { case PLAIN_INODE: contents = make_shared<plain_file>(); break; case DIR_INODE: contents = make_shared<directory>(); break; } DEBUGF ('i', "inode " << inode_nr << ", type = " << type); } int inode::get_inode_nr() const { DEBUGF ('i', "inode = " << inode_nr); return inode_nr; } int inode::get_type() const { return type; } file_base_ptr inode::get_contents() const{ return contents; } size_t inode::size() const { if (type == PLAIN_INODE) return plain_file_ptr_of(contents)->size(); else return directory_ptr_of(contents)->size(); } void inode::set_name(const string& iname) { name = iname; } string inode::get_name() const { return name; } plain_file_ptr plain_file_ptr_of (file_base_ptr ptr) { plain_file_ptr pfptr = dynamic_pointer_cast<plain_file> (ptr); if (pfptr == nullptr) throw invalid_argument ("plain_file_ptr_of"); return pfptr; } directory_ptr directory_ptr_of (file_base_ptr ptr) { directory_ptr dirptr = dynamic_pointer_cast<directory> (ptr); if (dirptr == nullptr) throw invalid_argument ("directory_ptr_of"); return dirptr; } size_t plain_file::size() const { size_t size {0}; size = data.size(); for (auto word = data.begin(); word != data.end(); word++) { size += word->size(); } if (size > 1) size -= 1; DEBUGF ('i', "size = " << size); return size; } const wordvec& plain_file::readfile() const { DEBUGF ('i', data); return data; } void plain_file::writefile (const wordvec& words) { DEBUGF ('i', words); data = words; } size_t directory::size() const { size_t size {0}; size = dirents.size(); DEBUGF ('i', "size = " << size); return size; } void directory::remove (const string& filename, const string& pathname) { auto it = dirents.find(filename); if (it == dirents.end()) throw yshell_exn ("rm: " + pathname + ": no such file or directory"); if (it->second->get_type() == PLAIN_INODE) dirents.erase(it); else { inode_ptr p = it->second; directory_ptr dp = directory_ptr_of(p->get_contents()); if (dp->size() != 2) throw yshell_exn ("rm: " + pathname + ": directory must be empty"); dirents.erase(it); } DEBUGF ('i', filename); } void directory::remove_r (const string& filename, const string& pathname) { auto it = dirents.find(filename); directory_ptr dp; if (it == dirents.end()) throw yshell_exn ("rmr: " + pathname + ": no such directory"); dp = directory_ptr_of(it->second->get_contents()); dp->rec_empty(); dirents.erase(it->first); DEBUGF ('i', filename); } void directory::rec_empty() { inode_ptr p; directory_ptr dp; for (auto it = dirents.begin(); it != dirents.end(); ) { p = it->second; DEBUGF ('i', it->first); if (it->first == "." || it->first == "..") { dirents.erase(it++); continue; } if (p->get_type() == PLAIN_INODE) dirents.erase(it++); else { dp = directory_ptr_of(p->get_contents()); dp->rec_empty(); dirents.erase(it++); } } } vector<inode_ptr> directory::subdirs() { vector<inode_ptr> subdirs; for (auto it = dirents.begin(); it != dirents.end(); ++it) { if (it->second->get_type() == DIR_INODE && it->first != "." && it->first != "..") subdirs.push_back(it->second); } return subdirs; } inode_ptr directory::mkdir(const string& dirname) { DEBUGF ('i', dirname); if (dirents.find(dirname) != dirents.end()) throw yshell_exn ("mkdir: " + dirname + ": dirname exists"); inode_ptr parent = dirents.at("."); inode_ptr dirnode = make_shared<inode>(DIR_INODE); dirnode->set_name(dirname); directory_ptr dir = directory_ptr_of(dirnode->get_contents()); dir->set_parent_child(parent, dirnode); dirents.insert(make_pair(dirname, dirnode)); return dirnode; } inode_ptr directory::mkfile (const string& filename) { DEBUGF ('i', filename); if (dirents.find(filename) != dirents.end()) throw logic_error ("filename exists"); inode_ptr file = make_shared<inode>(PLAIN_INODE); dirents.insert(make_pair(filename, file)); return file; } void directory::set_root(inode_ptr root) { dirents.insert(make_pair(".", root)); dirents.insert(make_pair("..", root)); root->set_name("/"); } void directory::set_parent_child(inode_ptr parent, inode_ptr child) { dirents.insert(make_pair("..", parent)); dirents.insert(make_pair(".", child)); } inode_ptr directory::lookup(const string& name) { auto it = dirents.find(name); if (it == dirents.end()) return nullptr; return it->second; } void directory::ls(ostream& out) { string suffix; for (auto it = dirents.begin(); it != dirents.end(); it++) { if (it->second->get_type() == DIR_INODE && it->first != "." && it->first != "..") suffix = "/"; else suffix = ""; out << setw(6) << it->second->get_inode_nr() << setw(6) << it->second->size() << "\t" << it->first + suffix << endl; } } const wordvec& directory::cat(const string& name, const string& pathname) { auto it = dirents.find(name); if (it == dirents.end()) { throw yshell_exn ("cat: " + pathname + ": No such file"); } else if (it->second->get_type() == DIR_INODE) { throw yshell_exn ("cat: " + pathname + ": Not a file"); } else { plain_file_ptr fp = plain_file_ptr_of( it->second->get_contents()); return fp->readfile(); } } void directory::make(const string& name, const string& pathname) { inode_ptr np; auto it = dirents.find(name); if (it == dirents.end()) { mkfile(name); } else if (it->second->get_type() == DIR_INODE) { throw yshell_exn ("make: " + pathname + ": filename exists as directory"); } else { wordvec v; plain_file_ptr fp = plain_file_ptr_of( it->second->get_contents()); fp->writefile(v); } } void directory::make(const string& name, const string& pathname, wordvec& data) { inode_ptr np; auto it = dirents.find(name); if (it == dirents.end()) { np = mkfile(name); plain_file_ptr fp = plain_file_ptr_of(np->get_contents()); fp->writefile(data); } else if (it->second->get_type() == DIR_INODE) { throw yshell_exn ("make: " + pathname + ": filename exists as directory"); } else { plain_file_ptr fp = plain_file_ptr_of( it->second->get_contents()); fp->writefile(data); } } inode_state::inode_state() { root = make_shared<inode>(DIR_INODE); cwd = root; directory_ptr_of(root->contents)->set_root(root); DEBUGF ('i', "root = " << root << ", cwd = " << cwd << ", prompt = \"" << prompt << "\""); } inode_ptr inode_state::resolve_pathname(const string& pathname) { inode_ptr p; size_t from = 0, found = 0; if (pathname.at(0) == '/') { p = root; from = 1; } else { p = cwd; } directory_ptr dir; while (true) { found = pathname.find_first_of("/", from); DEBUGF ('i', "pathname: \"" << pathname << "\", from: \"" << from << "\", found: \"" << found << "\""); if (found == string::npos) { break; } dir = directory_ptr_of(p->get_contents()); p = dir->lookup(pathname.substr(from, found - from)); if (p == nullptr) return p; from = found + 1; } return p; } void inode_state::cat(const string& pathname, ostream& out) { inode_ptr p = resolve_pathname(pathname); if (p == nullptr) throw yshell_exn("cat: " + pathname + "No such file"); string name; size_t found = pathname.find_last_of("/"); if (found == string::npos) name = pathname; else name = pathname.substr(found + 1); wordvec data = directory_ptr_of(p->contents)->cat(name, pathname); if (data.size() > 0) out << data << endl; } void inode_state::cd() { cwd = root; } void inode_state::cd(const string& pathname) { inode_ptr p; if (pathname.back() != '/') p = resolve_pathname(pathname + '/'); else p = resolve_pathname(pathname); if (p == nullptr) throw yshell_exn("cd: " + pathname + "No such directory"); cwd = p; } void inode_state::ls(ostream& out) { out << ".:" << endl; directory_ptr dir = directory_ptr_of(cwd->contents); dir->ls(out); } void inode_state::ls(const string& pathname, ostream& out) { inode_ptr p = resolve_pathname(pathname); if (p == nullptr) throw yshell_exn ("ls: " + pathname + ": No such file or directory"); if (pathname.back() != '/' || pathname == "/") out << pathname << ":" << endl; else out << pathname.substr(0, pathname.size() - 1) << ":" << endl; if (p->get_type() == PLAIN_INODE) { out << setw(6) << p->get_inode_nr() << setw(6) << p->size() << "\t" << pathname << endl; return; } directory_ptr dir = directory_ptr_of(p->contents); if (pathname.back() != '/') { size_t found = pathname.find_last_of("/"); if (found == string::npos) p = dir->lookup(pathname); else p = dir->lookup(pathname.substr(found+1)); if (p == nullptr) { throw yshell_exn ("ls: " + pathname + ": No such file or directory"); } dir = directory_ptr_of(p->contents); } dir->ls(out); } void inode_state::lsr(ostream& out) { ls(out); directory_ptr dir = directory_ptr_of(cwd->contents); vector<inode_ptr> subdirs (dir->subdirs()); for (size_t i = 0; i < subdirs.size(); i++) lsr("./" + subdirs.at(i)->get_name() + "/", out); } void inode_state::lsr(const string& pathname, ostream& out) { string suffix; inode_ptr p; if (pathname.back() == '/') suffix = ""; else suffix = "/"; p = resolve_pathname(pathname + suffix); if (p == nullptr) throw yshell_exn ("lsr: " + pathname + ": No such file or directory"); ls(pathname, out); directory_ptr dir = directory_ptr_of(p->contents); vector<inode_ptr> subdirs (dir->subdirs()); for (size_t i = 0; i < subdirs.size(); i++) lsr(pathname + suffix + subdirs.at(i)->get_name() + '/', out); } void inode_state::make(const string& pathname) { inode_ptr p = resolve_pathname(pathname); if (p == nullptr) throw yshell_exn ("make: " + pathname + ": invalid path"); string name; size_t found = pathname.find_last_of("/"); if (found == string::npos) name = pathname; else name = pathname.substr(found + 1); directory_ptr_of(p->contents)->make(name, pathname); } void inode_state::make(const string& pathname, wordvec& data) { inode_ptr p = resolve_pathname(pathname); if (p == nullptr) throw yshell_exn ("make: " + pathname + ": invalid path"); string name; size_t found = pathname.find_last_of("/"); if (found == string::npos) name = pathname; else name = pathname.substr(found + 1); directory_ptr_of(p->contents)->make(name, pathname, data); } void inode_state::mkdir(const string& pathname) { string name; if (pathname.back() == '/') name = pathname.substr(0, pathname.size() - 1); else name = pathname; inode_ptr p = resolve_pathname(name); if (p == nullptr) throw yshell_exn ("mkdir: " + pathname + ": invalid path"); directory_ptr dir = directory_ptr_of(p->get_contents()); size_t found = name.find_last_of("/"); if (found == string::npos) dir->mkdir(name); else dir->mkdir(name.substr(found+1)); } string inode_state::get_prompt () const { return prompt; } void inode_state::set_prompt(const wordvec& words) { if (words.size() == 1) prompt = "% "; else { prompt = ""; for (size_t i = 1; i < words.size(); i++) prompt += words.at(i) + " "; } } void inode_state::pwd(ostream& out) { wordvec name_stack; inode_ptr p = cwd; directory_ptr dp; while (p != root) { name_stack.push_back(p->name); dp = directory_ptr_of(p->contents); p = dp->lookup(".."); } if (name_stack.size() == 0) { out << '/' << endl; return; } while (name_stack.size() > 0) { out << '/'; out << name_stack.back(); name_stack.pop_back(); } out << endl; } void inode_state::rm(const string& pathname) { string target_name, pname; bool is_dir; if (pathname.back() == '/') { pname = pathname.substr(0, pathname.size() - 1); is_dir = true; } else { pname = pathname; } inode_ptr p = resolve_pathname(pname); size_t found = pname.find_last_of("/"); if (found == string::npos) target_name = pname; else target_name = pathname.substr(found + 1); directory_ptr dir = directory_ptr_of(p->contents); p = dir->lookup(target_name); if (p == nullptr) throw yshell_exn ("rm: " + pathname + ": No such file or directory"); if (p->type == PLAIN_INODE && is_dir) throw yshell_exn ("rm: " + pathname + ": is not a directory"); dir->remove(target_name, pathname); } void inode_state::rmr(const string& pathname) { string target_name, pname; if (pathname.back() == '/') { pname = pathname.substr(0, pathname.size() - 1); } else { pname = pathname; } inode_ptr p = resolve_pathname(pname); size_t found = pname.find_last_of("/"); if (found == string::npos) target_name = pname; else target_name = pathname.substr(found + 1); directory_ptr dir = directory_ptr_of(p->contents); p = dir->lookup(target_name); if (p == nullptr) throw yshell_exn ("rmr: " + pathname + ": No such file or directory"); if (p->type == PLAIN_INODE) throw yshell_exn ("rmr: " + pathname + ": is not a directory"); dir->remove_r(target_name, pathname); } void inode_state::terminate() { directory_ptr dp = directory_ptr_of(root->contents); dp->rec_empty(); } ostream& operator<< (ostream& out, const inode_state& state) { out << "inode_state: root = " << state.root << ", cwd = " << state.cwd; return out; }
#include "StdAfx.h" #include "Anime.h" /*------------------------------------------- コンストラクタ 引数:読む込むAnime(XML)ファイルパス --------------------------------------------*/ Anime::Anime(char* file_name) :isMirror(false), animeNo(0), count(0) { // XML読み込み ReadXML(file_name); } /*------------------------------------------- デストラクタ --------------------------------------------*/ Anime::~Anime() { } bool Anime::ReadXML(char* file_name) { // COMの初期化 CoInitialize(NULL); // Documentの作成 MSXML2::IXMLDOMDocument2Ptr pDocument; HRESULT hr = pDocument.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER); if (FAILED(hr)) return false; try { // パーサの設定 pDocument->async = VARIANT_FALSE; pDocument->validateOnParse = VARIANT_FALSE; pDocument->resolveExternals = VARIANT_FALSE; pDocument->preserveWhiteSpace = VARIANT_FALSE; // xmlファイルを読み込む if (pDocument->load(file_name) == VARIANT_TRUE) { // 読みだし MSXML2::IXMLDOMNodeListPtr pList; MSXML2::IXMLDOMElementPtr pRoot; // pList = objectリスト pList = pDocument->selectNodes("object"); // pRoot = object[0] if (pList->length > 0) pRoot = pList->item[0]; else return false; // pList = animationリスト pList = pRoot->selectNodes("//animation"); for (int i = 0; i < pList->length; i++) { pRoot = pList->item[i]; FrameList frameList = GetAnimation(pRoot); animation.push_back(frameList); } /* // pList = animationリスト pList = pRoot->selectNodes("//animation"); for (int i = 0; i < pList->length; i++) { // animation MSXML2::IXMLDOMElementPtr pRoot = pList->item[i]; MSXML2::IXMLDOMNodeListPtr pList = pRoot->selectNodes("frame"); for (int j = 0; j < pList->length; j++) { MSXML2::IXMLDOMElementPtr pRoot = pList->item[j]; // メッセージボックス表示 char data[256]; sprintf(data, "animationNum = %s", pRoot->getAttribute("x")); MessageBox(0, data, 0, 0); } } /* // BSTR → char 変換 WideCharToMultiByte( CP_ACP, // コードページ ANSI コードページ 0, // 処理速度とマッピング方法を決定するフラグ (OLECHAR*)pRoot->getAttribute("image").bstrVal, // ワイド文字列のアドレス -1, // ワイド文字列の文字数 texturePath, // 新しい文字列を受け取るバッファのアドレス sizeof(texturePath) - 1, // 新しい文字列を受け取るバッファのサイズ NULL, // マップできない文字の既定値のアドレス NULL // 既定の文字を使ったときにセットするフラグのアドレス ); // テクスチャの初期化 LoadTexture(texturePath); /* // メッセージボックス表示 char data[256]; sprintf(data, "image=%s x=%d w=%d", texturePath, _wtoi(pRoot->getAttribute("x").bstrVal), _wtoi(pRoot->getAttribute("w").bstrVal)); MessageBox(0, data, 0, 0); */ } else { char data[256]; sprintf_s(data, "%d行\n%s", pDocument->parseError->line, pDocument->parseError->srcText); MessageBox(NULL, data, "XMLパース Error!!", MB_OK); return false; } } // Error catch (_com_error error) { MessageBox(NULL, error.ErrorMessage(), "COM Error!!", MB_OK); return false; } return true; } /*------------------------------------------- --------------------------------------------*/ Frame Anime::GetFrame(MSXML2::IXMLDOMElementPtr pRoot) { Frame frame; frame.imagePath = ToStr(pRoot->getAttribute("image").bstrVal); frame.x = ToInt(pRoot->getAttribute("x").bstrVal); frame.y = ToInt(pRoot->getAttribute("y").bstrVal); frame.w = ToInt(pRoot->getAttribute("w").bstrVal); frame.h = ToInt(pRoot->getAttribute("h").bstrVal); frame.gap = ToInt(pRoot->getAttribute("gap").bstrVal); // TODO 音声の指定も行えるようにしたい //frame.soundPath = ToStr(pRoot->getAttribute("image").bstrVal); return frame; } /*------------------------------------------- --------------------------------------------*/ FrameList Anime::GetAnimation(MSXML2::IXMLDOMElementPtr pRoot) { MSXML2::IXMLDOMNodeListPtr pList = pRoot->selectNodes("frame"); FrameList frameList; for (int i = 0; i < pList->length; i++) { Frame frame = GetFrame(pList->item[i]); frameList.push_back(frame); } return frameList; } /*------------------------------------------- アニメーション描画 引数:x:X座標, y:Y座標 --------------------------------------------*/ void Anime::Draw(long x, long y) { FrameList frameList = animation[animeNo % animation.size()]; if (frameList.size() > 0) { Frame frame = frameList.at((long)count % frameList.size()); count += frame.gap / 60.0f; RECT rect = { frame.x, frame.y, frame.x + frame.w, frame.y + frame.h }; LPDIRECT3DTEXTURE9 texture = DirectXLib::GetInstance()->LoadTexture(frame.imagePath.c_str()); DirectXLib::GetInstance()->DrawTexture(texture, x, y, rect, isMirror); #ifdef _DEBUG_ // 当たり判定を描画 DirectXLib::GetInstance()->DrawBox(D3DXVECTOR2(x, y), D3DXVECTOR2(x+frame.w, y+frame.h)); #endif // _DEBUG_ } } /*------------------------------------------- アニメーション回転描画 引数:x:X座標, y:Y座標 --------------------------------------------*/ void Anime::SpinDraw(long x, long y, float spinSpeed) { FrameList frameList = animation[animeNo % animation.size()]; if (frameList.size() > 0) { Frame frame = frameList.at((long)count % frameList.size()); count += frame.gap / 60.0f; RECT rect = { frame.x, frame.y, frame.x + frame.w, frame.y + frame.h }; LPDIRECT3DTEXTURE9 texture = DirectXLib::GetInstance()->LoadTexture(frame.imagePath.c_str()); DirectXLib::GetInstance()->DrawSpinTexture(texture, x, y, rect, isMirror, spinSpeed); } }
void polymorphic(){ ; } int polymorphic(float p, float z){ polymorphic(); polymorphic(1.0,p); } int polymorphic(float p, int z){ z = 1.0; polymorphic(); polymorphic(1.0,p); } int polymorphic(float p, int z, float j){ p = 1.0; polymorphic(1.0,p); polymorphic(1.0,p,p); } void polymorphic(float p, int z, void j){ p = 1.0; polymorphic(1.0,p); polymorphic(1.0,p,p); } void array_function(float a[10]){ ; } void array_function(float a[10][10]){ ; } void array_function(int a[10]){ ; } void array_function(int a[10][20]){ ; } void fail_cases(){ ; } void fail_cases(int p1,int p2,int p3){ ; } void fail_cases(int p1,float p2,float p3){ ; } void fail_cases(int p1){ int arr[10.0]; int a,b,a; float b; int p1; arr[10.0] = 1; arr[10] = 1; arr[1][10] = 1; arr = 1; undeclared_function(); undeclared_var = 10; a(); undeclared_var(); b = "Hello"; fail_cases(p1,p1,p1); fail_cases(p1,p1,1.0); fail_cases(p1,2.0,2.0); return 10; } void fail_cases(int param){ ; } int fail_cases(int param){ ; } void printf(int a){ ; } void print_functions(){ int a; a = printf("Hello"); printf(); } void fail_cases_test(){ int z1[10]; int z2[100]; float z3[10]; float z4[10][10]; int a; void b; a = fail_cases("Hello World!"); fail_cases(10,10); array_function(z1); array_function(z2); array_function(z3); array_function(z4); print_functions(); } int not_main(){ int a,b; int x[1][1]; float c; a = 1; a = (a < b); b = (a < c); b = (a && c); a = (c != b); for(a = 0; a < 10; a++){ ; } } void main(){ ; } int main(){ int a,b; int z[10][20]; a = 10; array_function(z); }
#include <string> #include <cmath> #include <iostream> #include <sstream> #include "field.hh" using namespace std; const int RED = 0; const int BLUE = 1; std::string number_to_string(int num) { ostringstream convert; convert << num; return std::string(convert.str()); } void print_color(std::string t, int color) { cout << std::string("\033[1;3") + number_to_string(color) + "m" + t + std::string("\033[0m"); } void print_field(field Field){ for(int i=1;i<N+1;i++){ for(int k=0;k<abs(i-(N-1)/2-1);k++){ cout <<" "; } for(int j=1;j<N+1;j++){ if(abs(j-i)<5){ print_color(number_to_string(i) + number_to_string(j), Field.get_stone(i,j)); cout << " "; } } cout<<endl; } }
// // main.cpp for main.cpp in /home/dupil_l/Module_C++/cpp_indie_studio/sources // // Made by Loïc Dupil // Login <dupil_l@epitech.net> // // Started on Wed May 3 16:39:31 2017 Loïc Dupil // Last update Wed May 31 14:33:38 2017 Stanislas Deneubourg // #include <ctime> #include "Core.hpp" int main() { std::unique_ptr<ICore> core(new Core); std::srand(std::time(nullptr)); core->fillSaves(); core->launch(); return (0); }
#ifndef BUTTON_H #define BUTTON_H #include <QtWidgets> class Button : public QGraphicsItem { public: Button(int w, int h); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void mousePressEvent(QGraphicsSceneMouseEvent *event); void setText(QString txt); void setLeft(bool l); private: int width; int height; bool left; QString text; }; #endif // BUTTON_H
#include <iostream> using namespace std; int main() { int t; cin>>t; while(t--){ long long n,k; cin>>n>>k; long long ans = 1; k--; while(k%2){ ans++; k/=2; } cout<<ans<<endl; } return 0; }
#include "mocker_vas.h" #include <Windows.h> #include <Winsock2.h> #include <gmock/gmock.h> #include <stdio.h> using namespace ::testing; //gbkÖÐÎÄ int main(int argc, char *argv[]) { auto mocker = TestMocker::getMocker(); //gbkÖÐÎÄ EXPECT_CALL(*mocker, bind(::testing::_, ::testing::_, ::testing::_)) .WillOnce(Return(500)) .WillOnce(Return(200)) .WillOnce(Return(300)); //auto vasMocker = hhtest::MockerVas::getMocker(); //EXPECT_CALL(*vasMocker, GetVersion()) // .WillOnce(Return(vas::Version(1, 2, 3))) // .WillOnce(Return(vas::Version(3, 2, 1))); printf("%d\n", ::bind(1, nullptr, 1)); printf("%d\n", ::bind(1, nullptr, 1)); printf("%d\n", ::bind(1, nullptr, 1)); auto v123 = vas::fd::GetVersion(); auto v321 = vas::fd::GetVersion(); return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifdef ANDROID #include "AndroidCmdDispatcher.h" namespace Event { bool AndroidCmdDispatcher::pollAndDispatch (Model::IModel *m, Event::EventIndex const &modeliIndex, Event::PointerInsideIndex *pointerInsideIndex) { } bool AndroidCmdDispatcher::dispatch (Model::IModel *m, EventIndex const &modeliIndex, PointerInsideIndex *pointerInsideIndex, void *platformDependentData) { } void AndroidCmdDispatcher::reset () { } IEvent *AndroidCmdDispatcher::translate (void *platformDependentEvent) { } } /* namespace Event */ #endif
#ifndef UTILS_H #define UTILS_H #include <iostream> #include <string> using std::stoul; using std::string; #include <cctype> #include <vector> using std::vector; #include "DataStructure.h" int parseInsertStatement(const string& target, Row& insertRow) { string buffer{}; vector<string> words; for (int i = 0; i < target.length(); i++) { if (isgraph(target[i])) { buffer.push_back(target[i]); continue; } if (buffer.length()) { string tmp = buffer; words.push_back(tmp); buffer.clear(); } } // append very last group words.push_back(buffer); insertRow.id = stoul(words[1], nullptr, 0); words[2].copy(insertRow.username, COLUMN_USERNAME_SIZE); words[3].copy(insertRow.email, COLUMN_EMAIL_SIZE); return 3; } #endif
/** @file */ #ifndef __TREEMAP_H #define __TREEMAP_H #include "ElementNotExist.h" #include <ctime> #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> /** * TreeMap is the balanced-tree implementation of map. The iterators must * iterate through the map in the natural order (operator<) of the key. */ template<class K, class V> class TreeMap { public: struct Entry; private: struct node { K key; V value; Entry en; int rd, sz; node *lson, *rson; node (K k, V v, int r, int s = 1, node *l = NULL, node *rs = NULL):en(k, v) { key = k; value = v; rd = r; sz = s; lson = l; rson = rs; } node () { lson = NULL; rson = NULL; } ~node() {} }; node *root; int elemnum; int seed; int random() { seed = int((long long) seed * 48271ll % 2147483647); return seed; } bool checkvalue(node *p, const V &value) const { if (p == NULL) return false; if (p->value == value) return true; return checkvalue(p->lson, value) || checkvalue(p->rson, value); } void clearnode(node *&p) { if (p == NULL) return; clearnode(p->lson); clearnode(p->rson); delete p; } bool checkelem(node *p, const K &key) const { if (p == NULL) return false; if (p->key == key) return true; if (key < p->key) return checkelem(p->lson, key); else return checkelem(p->rson, key); } void update(node *&x){ if (x == NULL) return; int num1, num2; num1 = x->lson == NULL? 0: x->lson->sz; num2 = x->rson == NULL? 0: x->rson->sz; x->sz = num1 + num2 + 1; } void rotr(node *&x) { node *y = x->lson; x->lson = y->rson; y->rson = x; update(y); update(x); x = y; } void rotl(node *&x) { node *y = x->rson; x->rson = y->lson; y->lson = x; update(x); update(y); x = y; } void addelem(node *&p, K key, V value) { if (p == NULL) { p = new node(key, value, random(), 1); elemnum++; //printf("**%d\n", elemnum); return; } if (p->key == key) { p->value = value; return; } if (key < p->key) { addelem(p->lson, key, value); if (p->rd > p->lson->rd) rotr(p); } else { addelem(p->rson, key, value); if (p->rd > p->rson->rd) rotl(p); } update(p); } void removeelem(node *&p, K key) { if (p == NULL) return; if (key < p->key) removeelem(p->lson, key); else if (p->key < key) removeelem(p->rson, key); else { if (p->lson == NULL && p->rson == NULL) {delete p; p = NULL; elemnum--;} else if (p->lson == NULL) { node *tmp = p; p = p->rson; delete tmp; elemnum--; } else if (p->rson == NULL) { node *tmp = p; p = p->lson; delete tmp; elemnum--; } else { if (p->lson->rd < p->rson->rd) { rotr(p); removeelem(p->rson, key); } else { rotl(p); removeelem(p->lson, key); } } } update(p); } public: class Entry { K key; V value; public: Entry(K k, V v) { key = k; value = v; } const K &getKey() const { return key; } const V &getValue() const { return value; } }; const Entry &elemrank(node *p, int k) const { //printf("----\n"); int num1 = (p->lson == NULL? 0 : p->lson->sz); if (num1 + 1 == k) { return p->en = Entry(p->key, p->value); } if (k <= num1) return elemrank(p->lson, k); else return elemrank(p->rson, k - num1 - 1); } const Entry &elemrank(int k) const { //if (root == NULL) printf("yes\n"); return elemrank(root, k); } public: class Iterator { private: const TreeMap* cur; int index; public: Iterator() {} Iterator(const TreeMap* p):cur(p) { index = 0; } /** * TODO Returns true if the iteration has more elements. */ bool hasNext() { if (index + 1 <= cur->size()) return true; else return false; } /** * TODO Returns the next element in the iteration. * @throw ElementNotExist exception when hasNext() == false */ const Entry &next() { if (!hasNext()) throw ElementNotExist(); return cur->elemrank(++index); /*node *p = cur->root; if (p->lson != NULL) printf("ohhh\n"); int k = ++index, num1 ; printf("yes\n"); while (p != NULL) { printf("yes\n"); //if (p->sz == ) printf("youarer\n"); printf("%d\n", p->sz); num1 = (p->lson == NULL ? 0 : p->lson->sz); printf("%d\n", num1); if (num1 + 1 == k) return Entry(p->key, p->value); if (k <= num1) p = p->lson; else {k -= num1 + 1, p = p->rson;} }*/ } }; /** * TODO Constructs an empty tree map. */ TreeMap() { root = NULL; elemnum = 0; //srand(time(0)); seed = 1542; } /** * TODO Destructor */ ~TreeMap() { clearnode(root); } void copynode(node *&p1,node *p2) { if (p2 == NULL) { p1 = p2;return; } //printf("Hello!\n"); //if (p1 != NULL) printf("yes\n"); p1 = new node(p2->key, p2->value, p2->rd, p2->sz); copynode(p1->lson, p2->lson); copynode(p1->rson, p2->rson); } /** * TODO Assignment operator */ TreeMap &operator=(const TreeMap &x) { if (this == &x) return *this; clearnode(root); root = NULL; copynode(root, x.root); elemnum = x.elemnum; return *this; } /** * TODO Copy-constructor */ TreeMap(const TreeMap &x) { root = NULL; //if (x.root == NULL) printf("yeso\n"); copynode(root, x.root); elemnum = x.elemnum; seed = 1542; } /** * TODO Returns an iterator over the elements in this map. */ Iterator iterator() const { Iterator itr(this); return itr; } /** * TODO Removes all of the mappings from this map. */ void clear() { clearnode(root); root = NULL; elemnum = 0; } /** * TODO Returns true if this map contains a mapping for the specified key. */ bool containsKey(const K &key) const { return checkelem(root, key); } /** * TODO Returns true if this map maps one or more keys to the specified value. */ bool containsValue(const V &value) const { return checkvalue(root, value); } /** * TODO Returns a const reference to the value to which the specified key is mapped. * If the key is not present in this map, this function should throw ElementNotExist exception. * @throw ElementNotExist */ const V &get(const K &key) const { node *p = root; while (p != NULL) { if (p->key == key) return p->value; if (key < p->key) p = p->lson; else p = p->rson; } throw ElementNotExist(); } /** * TODO Returns true if this map contains no key-value mappings. */ bool isEmpty() const { return elemnum == 0; } /** * TODO Associates the specified value with the specified key in this map. */ void put(const K &key, const V &value) { addelem(root, key, value); } /** * TODO Removes the mapping for the specified key from this map if present. * If there is no mapping for the specified key, throws ElementNotExist exception. * @throw ElementNotExist */ void remove(const K &key) { removeelem(root, key); } /** * TODO Returns the number of key-value mappings in this map. */ int size() const { return elemnum;} }; #endif
#include <gflags/gflags.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <assert.h> #include "rlib/tests/random.hh" #include "./gen_addr.hh" #include "two_sided/core.hh" #include "two_sided/r740.hh" #include "../huge_region.hh" #include "../nvm_region.hh" #include "./statucs.hh" #include "./thread.hh" #include "./nt_memcpy.hh" DEFINE_string(nvm_file, "/dev/dax1.6", "Abstracted NVM device"); DEFINE_uint64(nvm_sz, 10, "Mapped sz (in GB), should be larger than 2MB"); DEFINE_int64(threads, 1, "Number of threads used."); DEFINE_int64(payload, 256, "Number of bytes to write"); DEFINE_bool(clflush, true, "whether to flush write content"); DEFINE_bool(use_nvm, true, "whether to use NVM."); DEFINE_bool(random, false, ""); DEFINE_bool(round_up, true, ""); DEFINE_uint32(round_payload, 256, "Roundup of the write payload"); using namespace nvm; using namespace test; template <typename Nat> Nat align(const Nat &x, const Nat &a) { auto r = x % a; return r ? (x + a - r) : x; } volatile bool running = true; int NO_OPT main(int argc, char **argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); LOG(4) << "Hello NVM!, using file: " << FLAGS_nvm_file; u64 sz = static_cast<u64>(FLAGS_nvm_sz) * (1024 * 1024 * 1024L); using TThread = Thread<int>; std::vector<std::unique_ptr<TThread>> threads; std::vector<Statics> statics(FLAGS_threads); for (uint thread_id = 0; thread_id < FLAGS_threads; ++thread_id) { threads.push_back(std::make_unique<TThread>([thread_id, &statics, sz]() { Arc<MemoryRegion> nvm_region = nullptr; if (FLAGS_use_nvm) { RDMA_LOG(4) << "server uses NVM with size: " << FLAGS_nvm_sz << " GB"; u64 sz = static_cast<u64>(FLAGS_nvm_sz) * (1024 * 1024 * 1024L); nvm_region = NVMRegion::create(FLAGS_nvm_file, sz).value(); } else { RDMA_LOG(4) << "server uses DRAM (huge page)"; u64 sz = static_cast<u64>(FLAGS_nvm_sz) * (1024 * 1024 * 1024L); // nvm_region = std::make_shared<DRAMRegion>(FLAGS_nvm_sz); nvm_region = HugeRegion::create(sz).value(); } // auto nvm_region = NVMRegion::create(FLAGS_nvm_file, sz).value(); // bind_to_core(thread_id + per_socket_cores) ; bind_to_core(thread_id); char *local_buf = new char[4096 * 2]; FastRandom rand(0xdeadbeaf + thread_id * 73); u64 total_sz = (sz - FLAGS_payload - 4096); ASSERT(total_sz < sz); u64 per_thread_sz = sz / FLAGS_threads; ASSERT(per_thread_sz >= (4096 + FLAGS_payload)); per_thread_sz -= (4096 + FLAGS_payload); u64 sum = 0; u64 off = 0; // main evaluation loop RandomAddr rgen(sz, 0); // random generator const usize access_gra = 1024 * 1024; while (running) { const usize nslots = 100 * 1024; const int fourK = 4 * 1024; const usize slot_span = 6 * fourK; // 6 DIMMs usize slot_num = 0; usize naddr = 0, addr = 0; if (FLAGS_random) { // total visiting space: 100K * 24KB = 2.4GB slot_num = rand.next() % nslots; auto base = fourK - FLAGS_payload * 2; ASSERT(base > 0); naddr = rand.next() % base; if (FLAGS_round_up) { naddr = round_up<u64>(addr, FLAGS_round_payload); } addr = slot_num * slot_span + naddr; ASSERT(addr % FLAGS_round_payload == 0); } else { addr = slot_num * slot_span + naddr; addr = round_up<u64>(addr, FLAGS_round_payload); naddr += FLAGS_payload; if (naddr + FLAGS_payload > fourK) { slot_num++; naddr = 0; } } if (addr + FLAGS_payload >= sz) { ASSERT(false); addr = sz - FLAGS_payload - 4096; } LOG(2) << "Addr " << addr; sleep(1); char *server_buf_ptr = reinterpret_cast<char *>(nvm_region->addr) + addr; #if 0 *((u64 *)local_buf) = 73; nt_memcpy(local_buf,64,server_buf_ptr); asm volatile("sfence" : : : "memory"); ASSERT(*((u64 *)server_buf_ptr) == 73) << " server buf value: " << *((u64 *)server_buf_ptr); #endif // randomly init the local buf //for (uint i = 0; i < FLAGS_payload; ++i) { // local_buf[i] = addr + i; //} #if 1 if (FLAGS_clflush) { ASSERT(nt_write(local_buf, FLAGS_payload, server_buf_ptr) >= FLAGS_payload) << "nvm write payload: " << FLAGS_payload; //nvm_write(local_buf,FLAGS_payload, server_buf_ptr); } else{ //ASSERT(memcpy_flush_write(local_buf, FLAGS_payload, server_buf_ptr) //>= FLAGS_payload); memcpy(server_buf_ptr, local_buf, FLAGS_payload); } #endif // ASSERT(nvm_read(local_buf, FLAGS_payload, server_buf_ptr) >= // FLAGS_payload); off += FLAGS_payload; r2::compile_fence(); statics[thread_id].inc(1); } LOG(4) << "total off: " << off; return 0; })); } for (auto &t : threads) t->start(); LOG(2) << "all bench threads started"; Reporter::report_thpt(statics, 60); running = false; for (auto &t : threads) { t->join(); } sleep(1); return 0; }
/* * Copyright (C) 2013 Tom Wong. All rights reserved. */ #ifndef __GT_DOC_MODEL_H__ #define __GT_DOC_MODEL_H__ #include "gtobject.h" #include <QtCore/QObject> GT_BEGIN_NAMESPACE class GtDocMeta; class GtDocument; class GtBookmarks; class GtDocNotes; class GtDocModelPrivate; class GT_BASE_EXPORT GtDocModel : public QObject, public GtSharedObject { Q_OBJECT public: explicit GtDocModel(QObject *parent = 0); ~GtDocModel(); public: GtDocMeta* meta() const; void setMeta(GtDocMeta *meta); GtDocument* document() const; void setDocument(GtDocument *document); GtBookmarks* bookmarks() const; void setBookmarks(GtBookmarks *bookmarks); GtDocNotes* notes() const; void setNotes(GtDocNotes *notes); int page() const; void setPage(int page); double scale() const; void setScale(double scale); double maxScale() const; void setMaxScale(double maxScale); double minScale() const; void setMinScale(double minScale); int rotation() const; void setRotation(int rotation); bool continuous() const; void setContinuous(bool continuous); enum LayoutMode { SinglePage, EvenPageLeft, OddPageLeft }; LayoutMode layoutMode() const; void setLayoutMode(LayoutMode mode); enum SizingMode { FreeSize, BestFit, FitWidth }; SizingMode sizingMode() const; void setSizingMode(SizingMode mode); enum MouseMode { BrowseMode, SelectText, SelectRect }; MouseMode mouseMode() const; void setMouseMode(MouseMode mode); public Q_SLOTS: void loadOutline(); Q_SIGNALS: void metaChanged(GtDocMeta *meta); void documentChanged(GtDocument *document); void bookmarksChanged(GtBookmarks *bookmarks); void notesChanged(GtDocNotes *notes); void pageChanged(int page); void scaleChanged(double scale); void rotationChanged(int rotation); void continuousChanged(bool continuous); void layoutModeChanged(int mode); void sizingModeChanged(int mode); void mouseModeChanged(int mode); private: QScopedPointer<GtDocModelPrivate> d_ptr; private: Q_DISABLE_COPY(GtDocModel) Q_DECLARE_PRIVATE(GtDocModel) }; GT_END_NAMESPACE #endif /* __GT_DOC_MODEL_H__ */
//Given an array of strings, return all groups of strings that are anagrams. //Note: All inputs will be in lower-case. vector<string> anagrams(vector<string> &strs) { vector<string> result; if(strs.size() < 2) return result; //-1 for already in result unordered_map<string, int> cache; for(int i=0; i < strs.size(); i++){ string s = strs[i]; sort(s.begin(), s.end()); auto it = cache.find(s); if(it == cache.end()){ cache[s] = i; } else { //hit result.push_back(strs[i]); if( it->second >=0){ result.push_back(strs[it->second]); it->second = -1; } } } return result; }
#include "sfmlBitmap.h" #include "sfmlDrawManager.h" SFMLBitmap::SFMLBitmap(Point<int> size, Color color) { fillWithColor(size, color); } SFMLBitmap::SFMLBitmap(sf::Image image) : image(image) { } int SFMLBitmap::getWidth() { return image.getSize().x; } int SFMLBitmap::getHeight() { return image.getSize().y; } Color SFMLBitmap::getPixelColor(int x, int y) { auto color = image.getPixel(x, y); return Color(color.r, color.g, color.b); } void SFMLBitmap::setPixelColor(int x, int y, Color color) { auto sfColor = sf::Color(color.r, color.g, color.b); image.setPixel(x, y, sfColor); } void SFMLBitmap::fillWithColor(Color color) { auto size = image.getSize(); image.create(size.x, size.y, sf::Color(color.r, color.g, color.b)); } void SFMLBitmap::fillWithColor(Point<int> size, Color color) { image.create(size.x, size.y, sf::Color(color.r, color.g, color.b)); } void SFMLBitmap::draw(Point<float> pos, SFMLDrawManager *drawManager) { drawManager->drawSFMLImage(pos, &image); } const sf::Image *SFMLBitmap::getImage() { return &image; }
#include "sudoku/BlockSplit.h" static cv_bridge::CvImageConstPtr cv_ptr; static ros::Publisher led_rect_pub; static ros::Publisher sudoku_rect_pub; static BlockSplit block_split; static bool sudoku_run; void sudokuParamCallback(const std_msgs::Int16MultiArray& msg) { block_split.setParam(msg.data[0], msg.data[1]); } void imageCallback(const sensor_msgs::ImageConstPtr& msg) { //ROS_INFO("Sudoku Image Call"); if (!sudoku_run) { ROS_INFO("Ignore Sudoku!"); return; } try { cv_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::MONO8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } static Mat gray, binary; Rect led_rect, sudoku_rect; gray = cv_ptr->image.clone(); if (gray.empty()) return; if (block_split.processMnist(gray, led_rect, sudoku_rect)) { //ROS_INFO_STREAM("Led Rect: " << led_rect); std_msgs::Int16MultiArray led_rect_msg; led_rect_msg.data.push_back(led_rect.x); led_rect_msg.data.push_back(led_rect.y); led_rect_msg.data.push_back(led_rect.width); led_rect_msg.data.push_back(led_rect.height); led_rect_pub.publish(led_rect_msg); //ROS_INFO_STREAM("Sudoku Rect: " << sudoku_rect); std_msgs::Int16MultiArray sudoku_rect_msg; sudoku_rect_msg.data.push_back(sudoku_rect.x); sudoku_rect_msg.data.push_back(sudoku_rect.y); sudoku_rect_msg.data.push_back(sudoku_rect.width); sudoku_rect_msg.data.push_back(sudoku_rect.height); sudoku_rect_pub.publish(sudoku_rect_msg); sudoku_run = false; } else { ROS_INFO("No Sudoku Found!"); } } void sudokuCtrCallback(const std_msgs::Bool& msg) { sudoku_run = msg.data; ROS_INFO_STREAM("Get Sudoku Ctr: " << sudoku_run); } void waitkeyTimerCallback(const ros::TimerEvent&) { waitKey(1); } int main(int argc, char* argv[]) { ros::init(argc, argv, "sudoku"); ros::NodeHandle nh; ros::Timer waitkey_timer = nh.createTimer(ros::Duration(0.1), waitkeyTimerCallback); ROS_INFO("Sudoku Start!"); led_rect_pub = nh.advertise<std_msgs::Int16MultiArray>("buff/led_rect", 1); sudoku_rect_pub = nh.advertise<std_msgs::Int16MultiArray>("buff/sudoku_rect", 1, true); image_transport::ImageTransport it(nh); image_transport::Subscriber sub = it.subscribe("camera/gray", 1, imageCallback); ros::Subscriber sudoku_param_sub = nh.subscribe("buff/sudoku_param", 1, sudokuParamCallback); ros::Subscriber sudoku_ctr_sub = nh.subscribe("buff/sudoku_ctr", 1, sudokuCtrCallback); sudoku_run = false; block_split.init(); ros::spin(); return 0; }
#include <omp.h> #include <stdio.h> #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <algorithm> #include <string> using namespace std; #ifdef __cplusplus extern "C" { #endif void generateMergeSortData (int* arr, size_t n); void checkMergeSortResult (int* arr, size_t n); #ifdef __cplusplus } #endif void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ #pragma omp parallel for schedule(runtime) for (i = 0; i < n1; i++) L[i] = arr[l + i]; #pragma omp parallel for schedule(runtime) for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l+(r-l)/2; // Sort first and second halves #pragma omp parallel { #pragma omp single { #pragma omp task mergeSort(arr, l, m); #pragma omp task mergeSort(arr, m+1, r); } } merge(arr, l, m, r); } } int main (int argc, char* argv[]) { //forces openmp to create the threads beforehand #pragma omp parallel { int fd = open (argv[0], O_RDONLY); if (fd != -1) { close (fd); } else { std::cerr<<"something is amiss"<<std::endl; } } if (argc < 3) { std::cerr<<"Usage: "<<argv[0]<<" <n> <nbthreads>"<<std::endl; return -1; } int n = atoi(argv[1]); int * arr = new int [atoi(argv[1])]; generateMergeSortData (arr, n); omp_set_schedule(omp_sched_static , -1); omp_set_num_threads(atoi(argv[2])); for (int i =0;i<n;i++){ cout<<"[ "<<arr[i]<<" ]"<<endl; } mergeSort(arr , 0 , n-1); /* -------------------------- for (int i =0;i<n;i++){ cout<<"[ "<<arr[i]<<" ]"<<endl; } //write code here for (int i=2;i<n/2;i+=i){ for (int j=0;j<n;j+i){ int index=j; cout<<index<<endl; for (int k = j ; k<j+i;k++){ for (int m=j; m<j+i;j++){ if(arr[k]>arr[m]){ index=m; cout<<"moving "<<k<<" to "<<m<<endl; } } buffer[index] = arr[k]; } } #pragma omp parallel for schedule(runtime) for (int i=0;i<n;i++){ arr[i]=buffer[i]; } for (int i =0;i<n;i++){ cout<<"[ "<<arr[i]<<" ]"<<endl; } } */ for (int i =0;i<n;i++){ cout<<"[ "<<arr[i]<<" ]"<<endl; } checkMergeSortResult (arr, atoi(argv[1])); delete[] arr; return 0; }
// // imautotest.cpp // AutoCaller // // Created by Micheal Chen on 2017/7/26. // // #include "imautotest.hpp" #include "autocontroller.hpp" #include "imcases.hpp" USING_NS_CC; using namespace ui; IMAutoTests::IMAutoTests() { ADD_TEST_CASE(IMAutoTest); } IMAutoTest::IMAutoTest() { btn_start = Button::create(); btn_start->setPosition(VisibleRect::center()); btn_start->setTitleText("Start"); btn_start->addClickEventListener(CC_CALLBACK_1(IMAutoTest::start, this)); addChild(btn_start); } void IMAutoTest::start(cocos2d::Ref *pSender) { AutoTestController::instance()->start(); }
#pragma once #include <SFML/Window/Event.hpp> #include "EventSubscriber.h" namespace Game { class MouseSubscriber: public EventSubscriber { public: virtual void onMouseClick(sf::Event::MouseButtonEvent event) = 0; virtual void onMouseMove(sf::Event::MouseMoveEvent event) = 0; void onEvent(sf::Event event) override; }; }
#include "../command.hpp" void stop(void) { theGraph.clear(); response::clean(); }
#include <string> #include "../headers/Leaf.hpp" using namespace std; Leaf::Leaf(string value) { this->className = "leaf"; this->value = value; } Leaf::Leaf(string value, string type) { this->value = value; this->type = type; } string Leaf::getValue() { return value; } string Leaf::getType() { return type; } void Leaf::printTree() { printf("%s", value.c_str()); } string Leaf::printCheck(ClassNode *classNode) { string retString = value + " : "; string type_ = classNode->getVariableTable()->getVariable(value); if (value == "self") { type = classNode->getVariableTable()->getFirstVariable(); retString += type; } else { if (type_ == "none") retString += type; else { type = type_; retString += type_; } } return retString; }
/* * Utils.cpp * * Created on: Jan 2, 2018 * Author: robert */ #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <termios.h> #include <iostream> #include "../inc/Utils.h" int Initport(int fd) { struct termios options; // Get the current options for the port... tcgetattr(fd, &options); // Set the baud rates to 115200... cfsetospeed(&options, B2000000); // Enable the receiver and set local mode... options.c_cflag |= (CLOCAL | CREAD); //disable hardware flow control options.c_cflag &= ~CRTSCTS; //disable software flow control options.c_iflag &= ~(IXON | IXOFF | IXANY); //raw input options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw output options.c_oflag &= ~OPOST; //No parity - 8N1 options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; // Set the new options for the port... tcsetattr(fd, TCSANOW, &options); return 1; } int OpenPort(std::string port) { int fd = open(port.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { perror(("open_port: Unable to open"+port).c_str()); std::cout << "!!!error!!!" << std::endl; } else fcntl(fd, F_SETFL, 0); return (fd); } void SendFrame(std::string port,std::string command) { int fd = OpenPort(port); Initport(fd); write(fd, command.c_str(), command.size()); close(fd); } void SendFrame(std::string port,int blue,int red,int fan,int crio,int time) { std::cout<<port<<std::endl; int fd = OpenPort(port); Initport(fd); char buffer[50]; int length = sprintf(buffer,"NASTAWA%03d-%02d:%03d-%02d:%01d:%01d\r\n", red,time,blue,time,fan,crio); write(fd, buffer, length); #ifdef DEBUG std::cout<<buffer<<std::endl; #endif close(fd); } void PrepareFile(std::string path, int HotCold, int time) { std::ofstream file (path, std::ios::out | std::ios::trunc); // clear contents std::string buffer=std::to_string(time)+"\r\n"; file.write(buffer.c_str(),buffer.size()); std::vector<std::string>signals; int timeRed, timeBlue; timeRed = (ceil(float(HotCold) / float(10))) *(time/10); timeBlue = (1-(ceil(float(HotCold) / float(10))))*(time/10); //std::cout<<"timeRED: "<<timeRed<<std::endl; //std::cout<<"timeBLUE: "<<timeBlue<<std::endl; for(int i=0;i<10;i++) { char buf[100]; signals.push_back(std::to_string(timeRed) + "\r\n"); sprintf(buf, "NASTAWA%03d-%02d:%03d-%02d:%01d:%01d\r\n", 100, 5, 0, 5, 0, 0); signals.push_back(buf); signals.push_back(std::to_string(timeBlue) + "\r\n"); sprintf(buf, "NASTAWA%03d-%02d:%03d-%02d:%01d:%01d\r\n", 0, 5, 100, 5, 1, 1); signals.push_back(buf); } for(int i=0;i<signals.size();i++) { file.write(signals[i].c_str(),signals[i].size()); } file.close(); }
/** * @file macs-internals.hpp * * Internal include file. Contains global variables in the internal namespace * used to track the global status. */ #ifndef MACS_INTERNALS_HPP #define MACS_INTERNALS_HPP #include <cstdio> #ifdef __WIN32 #include <GL/glew.h> #endif #include <GL/gl.h> #ifndef __WIN32 #include <GL/glext.h> #endif #include "macs-config.hpp" #include "macs-exceptions.hpp" #ifdef DEBUG /// Puts quotation marks around its argument. #define quote(x) #x /// Evalutes its argument before quoting it. #define eval(x) quote(x) /// Debugging printf (no-op on !defined(DEBUG)) #define dbgprintf(format, ...) fprintf(stderr, "libmacs:" __FILE__ ":%s():" eval(__LINE__) ": " format, __func__, ##__VA_ARGS__) #else /// Debugging printf (no-op on !defined(DEBUG)) #define dbgprintf(...) #endif namespace macs { class in; class out; class textures_in; class texture; class texture_array; /** * Internal MACS namespace. None of its contents should be used from * external applications. */ namespace internals { /// OpenGL major version extern int ogl_maj; /// OpenGL minor version extern int ogl_min; /// Draw buffer count allowed extern int draw_bufs; /// Color buffer attachment count for FBOs extern int col_attach; /// Minimum of draw_bufs and col_attach (number of output units). extern int out_units; /// Texture units available extern int tex_units; /// Width for every render element extern int width; /// Height for every render element extern int height; class program; /** * Shader object. A standard OpenGL shader object, either vertex or * fragment shader. */ class shader { public: /** * Shader type. Either it is a vertex or a fragment shader. */ enum type { /// Fragment shader fragment = GL_FRAGMENT_SHADER, /// Vertex shader vertex = GL_VERTEX_SHADER }; /** * Creates a new shader of the desired type. * * @param t Shader type (fragment or vertex). */ shader(type t); /** * Deletes a shader. If it is still in use by a program, it * won't be actually deleted until that program has been * unloaded. */ ~shader(void); /** * Loads GLSL code. This will load the given string as GLSL code * and attach it to this shader. * * @param src GLSL code to be loaded */ void load(const char *src); /** * Loads GLSL code from a file. This will read the whole file * given by the I/O stream and use the content as this shader's * GLSL code. * * @note The I/O stream must support seeking. * * @param fp I/O stream to read from */ void load(FILE *fp); /** * Compiles this shader. Recompiles the shader's current GLSL * code. * * @return true iff the compilation has been successful. */ bool compile(void); friend class program; private: /// OpenGL shader ID unsigned id; /// Shader source copy char *src; }; /** * Program uniform. Used in order to communicate with shader variables. */ class prg_uniform { public: /** * Creates a uniform object from its ID. * * @param id OpenGL uniform location ID. */ prg_uniform(unsigned id); /** * Sets this uniform. * * @param obj Object to be loaded into this uniform. * * @note Textures must be already assigned to a texture unit * and that unit may not be used otherwise before the * shader uses this sampler. */ void operator=(const in *obj) throw(exc::invalid_type, exc::texture_not_assigned); private: /// OpenGL uniform location ID unsigned id; }; /** * Program object. A GLSL program object which combines several shaders * and especially joins vertex and fragment shaders. */ class program { public: /** * Creates an empty program. */ program(void); /** * Unloads the program. Deletes this program and releases all * attached shaders. */ ~program(void); /** * Attach a shader. Attaches the given shader to this program so * it will be included upon linkage. * * @param sh Shader to be attached. */ void attach(shader *sh); /** * Link the program. Links all attached shaders and thus makes * this program usable. * * @return true iff the linking has been successful. */ bool link(void); /** * Puts this shader into use. Calling this function will lead to * this program being used by subsequent render operations. */ void use(void); /** * Returns a uniform. Searches the given uniform and returns an * object to access it. * * @param name Uniform identifier */ prg_uniform uniform(const char *name); private: /// OpenGL program ID unsigned id; }; /** * Represents a texture mapping unit. Every input texture has to be * assigned to a TMU. This class is used for managing one such slot. */ class tmu { public: /** * Simple constructor. * * @param unit Hardware texture unit index. */ tmu(int unit = 0); /** * Assigns a texture to this unit. * * @param tex Texture to be assigned. */ void operator=(const textures_in *tex); /** * Converts this TMU to the assigned texture. * * @return Assigned texture. */ operator const textures_in *(void) const { return assigned; } /** * Changes the physical TMU this object correspondends to. * * @param tmu_i Physical TMU index. */ void reassign(int tmu_i) { unit = tmu_i; } private: /// Hardware TMU index. int unit; /// Texture which has been assigned. const textures_in *assigned; }; /** * Manages all TMUs. This class is used for managing all those input * slots. */ class tmu_manager { public: /** * Initializes the manager and all TMUs. * * @param units Number of units to be managed. */ tmu_manager(int units); /// Basic deconstructor. ~tmu_manager(void); /** * Marks all TMUs as loosely assigned. */ void loosen(void); /** * Tries to assign this texture to a TMU. If a unit is found * which is already assigned to this texture, this will mark * that TMU as definitely assigned. * * @param tex Texture to assign a TMU to. * * @return True, iff a TMU has been found which has already been * assigned to it. */ bool operator&=(const textures_in *tex); /** * Assigns this texture to a TMU. Finds a loosely assigned TMU * and assigns it to that texture. * * @param tex Texture to assign a TMU to. * * @note This function will also find a new TMU if another has * already been set to the given texture, so you should * use <tt>operator&=</tt> before. */ void operator+=(const textures_in *tex); /** * The last function in the managing cycle. It essentially * just disables loosely assigned units. */ void update(void); /** * Indexing function. * * @param index TMU to be accessed. * * @return Pointer to TMU object. */ tmu &operator[](int index) { return tmus[index]; } private: /// TMU count int units; /// TMU array tmu *tmus; /// True iff definitely assigned bool *definitely; }; /// Simple vertex shader which just pipes input XY to output. extern shader *basic_vertex_shader; /** * Simple program. It uses the basic vertex shader and a standard * fragment shader. */ extern program *basic_pipeline; /// Central TMU manager. extern tmu_manager *tmu_mgr; /** * Draws a quad. Draws a textured quad to the whole framebuffer * (implying that the modelview and projection matrices are both * identity matrices or a shader is used which circumvents this). */ void draw_quad(void); } } #include "macs.hpp" #include "macs-root.hpp" #endif
#include "WebServer.h" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "Steganography.h" #include "Certificate.h" #include "Rsa.h" using namespace cv; FILE * _jobFile; FILE * _messageFile; FILE * _doneFile; #define DWORD int void openFile() { _jobFile = fopen("/var/www/html/motion/job", "w+"); _messageFile = fopen("/var/www/html/motion/message", "w+"); _doneFile = fopen("/var/www/html/motion/done", "w+"); } void WriteBusy() { fseek(_doneFile, 0, SEEK_SET); fprintf(_doneFile, "0"); fflush(_doneFile); } void WriteReady() { fseek(_doneFile, 0, SEEK_SET); fprintf(_doneFile, "1"); fflush(_doneFile); } void CheckWebServer() { DWORD jobCommand; DWORD doorCommand; Embedder embedder; Steganography steg; char text[5000]; int data2[5000]; strcpy(text,"Testul suprem este acela care functioneaza corect indifrente de circumstante"); DWORD changes; char data[2000]; Mat imgOriginal; jobCommand = 0; doorCommand = 0; if (0 == _jobFile) { openFile(); } while(1) { fseek(_jobFile, 0, SEEK_SET); fscanf(_jobFile, "%d", &jobCommand); if(jobCommand == 2) { WriteBusy(); //read message from file fseek(_messageFile, 0, SEEK_END); long size = ftell(_messageFile); fseek(_messageFile, 0, SEEK_SET); fread(text, 1, size, _messageFile); text[size] = '\0'; printf("messagul este %s\n", text); if(strlen(text) == 0) { goto done2; } Certificate *cert = Certificate::FromFile("/var/www/html/motion/public.rsa"); imgOriginal=imread("/var/www/html/motion/image.png"); imwrite("/var/www/html/motion/out.png", steg.Embed(imgOriginal, cert, text, strlen(text))); printf("Image written \n"); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); WriteReady(); } else if (jobCommand == 1) { WriteBusy(); imgOriginal = imread("/var/www/html/motion/image.png"); int length = 0; //Certificate::FromFile("sagfsagsa"); Certificate *cert = Certificate::FromFile("/var/www/html/motion/private.rsa"); char *te = steg.Extract(imgOriginal, cert, &length); printf("In the image was detected %x bytes %s \n", length, te); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); fseek(_messageFile, 0, SEEK_SET); fprintf(_messageFile, "%s", te); fflush(_messageFile); WriteReady(); } else if (jobCommand == 3) { Certificate::GenerateRandomCertificate("/var/www/html/motion/private.rsa", "/var/www/html/motion/public.rsa"); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); } else if(jobCommand == 4) { WriteBusy(); //read message from file fseek(_messageFile, 0, SEEK_END); long size = ftell(_messageFile); fseek(_messageFile, 0, SEEK_SET); fread(text, 1, size, _messageFile); text[size] = '\0'; printf("messagul este %s\n", text); Certificate *cert = Certificate::FromFile("/var/www/html/motion/public.rsa"); imgOriginal=imread("/var/www/html/motion/image.png"); AudioFile *audio = new AudioFile("/var/www/html/motion/audioIn.wav"); steg.EmbedInAudio(audio, cert, text, strlen(text)); audio->WriteToFile("/var/www/html/motion/audioOut.wav"); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); WriteReady(); } else if (jobCommand == 5) { WriteBusy(); int length = 0; AudioFile *audio = new AudioFile("/var/www/html/motion/audioIn.wav"); Certificate *cert = Certificate::FromFile("/var/www/html/motion/private.rsa"); char *te = steg.ExtractFromAudio(audio, cert, &length); printf("In the image was detected %x bytes %s \n", length, te); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); fseek(_messageFile, 0, SEEK_SET); fprintf(_messageFile, "%s", te); fflush(_messageFile); WriteReady(); } else if(jobCommand == 6) { WriteBusy(); //read message from file fseek(_messageFile, 0, SEEK_END); long size = ftell(_messageFile); fseek(_messageFile, 0, SEEK_SET); fread(text, 1, size, _messageFile); text[size] = '\0'; printf("messagul este %s\n", text); Certificate *cert = Certificate::FromFile("/var/www/html/motion/public.rsa"); //imgOriginal=imread("/var/www/html/motion/image.png"); Rsa::GetInstance()->Encrypt(data, cert, data2, size); fseek(_messageFile, 0, SEEK_SET); fwrite(data2, size * 4, 1, _messageFile); fflush(_messageFile); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); WriteReady(); } else if(jobCommand == 7) { WriteBusy(); //read message from file FILE *input = fopen("/var/www/html/motion/textIn.txt", "r"); long size = ftell(input); fread(data2, 1, size, input); data2[size] = '\0'; //imgOriginal=imread("/var/www/html/motion/image.png"); Certificate *cert = Certificate::FromFile("/var/www/html/motion/public.rsa"); printf("start decrypting with %d size\n", size); Rsa::GetInstance()->Decrypt(data2, cert, data, size); fseek(_messageFile, 0, SEEK_SET); fwrite(data, size * 4, 1, _messageFile); fflush(_messageFile); fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); fclose(input); WriteReady(); printf("Done!\n"); } continue; done2: fseek(_jobFile, 0, SEEK_SET); fprintf(_jobFile, "0"); fflush(_jobFile); WriteReady(); } } void WriteTemperatureToWebServer(double Temperature) { /*if (0 == _temperatureFile) { openFile(); } fseek(_temperatureFile, 0, SEEK_SET); fprintf(_temperatureFile, "%f", Temperature);*/ }
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { if(nums.size()*nums[0].size()!=r*c){ return nums; }else{ vector<int> temp; for(int i=0;i<nums.size();++i){ for(int j=0;j<nums[0].size();++j){ temp.push_back(nums[i][j]); } } int count = 0; vector<vector<int>> result; for(int i=0;i<r;++i){ vector<int> row; for(int j=0;j<c;++j){ row.push_back(temp[count++]); } result.push_back(row); } return result; } } };
// Created: 2009-01-09 // // Copyright (c) 2009-2013 OPEN CASCADE SAS // // This file is part of commercial software by OPEN CASCADE SAS, // furnished in accordance with the terms and conditions of the contract // and with the inclusion of this copyright notice. // This file or any part thereof may not be provided or otherwise // made available to any third party. // // No ownership title to the software is transferred hereby. // // OPEN CASCADE SAS makes no representation or warranties with respect to the // performance of this software, and specifically disclaims any responsibility // for any damages, special or consequential, connected with its use. #ifndef _Geom2dConvert_SequenceOfPPoint_HeaderFile #define _Geom2dConvert_SequenceOfPPoint_HeaderFile #include <NCollection_Sequence.hxx> class Geom2dConvert_PPoint; typedef NCollection_Sequence<Geom2dConvert_PPoint> Geom2dConvert_SequenceOfPPoint; #endif
#include "stdafx.h" #include "Wall.h" Wall::Wall(int width, int height, float x, float y) : width(width) , height(height) , image(sf::Vector2f(width, height)) { image.setOrigin(width / 2, height / 2); image.setPosition(x, y); } float Wall::getTopY() { return image.getPosition().y - (height / 2); } float Wall::getBottomY() { return image.getPosition().y + (height / 2); } float Wall::getLeftX() { return image.getPosition().x - (width / 2); } float Wall::getRightX() { return image.getPosition().x + (width / 2); } sf::RectangleShape Wall::getImage() { return image; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H // Qt cabeceras #include <QMainWindow> #include <QMessageBox> #include <QTimer> #include <QDir> // Librerias estandar de C++ #include <fstream> // Cabeceras OpenCV #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/objdetect/objdetect.hpp> // Cabeceras de intraface //#include <intraface/FaceAlignment.h> //#include <intraface/XXDescriptor.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include <bits/stdc++.h> using namespace std; /** * 面积树 * 四叉树 * **/ int str_to_int(string a){ int sum = 0; for(int i = 0; i < a.length(); i ++){ sum = sum * 10 + (a[i] - '0'); } return sum; } int tot = 0; const int MAXN = 1e6 + 5; struct AREA_tree{ struct NODE{ int lx, ly, rx, ry, sum; int son[4]; /* 0 <xmid + 1, ymid + 1> <rx, ry> 1 <lx, ymid + 1> <xmid, ry> 2 <lx, ly> <xmid, ymid> 3 <xmid + 1, ly> <rx, ymid> */ }tree[MAXN]; void Init_NODE(NODE x){ memset(x.son, -1, sizeof(x.son)); } void Init(){ tot = 0; } int add(int lx, int ly, int rx, int ry){ tree[tot].lx = lx, tree[tot].rx = rx, tree[tot].ly = ly, tree[tot].ry = ry; Init_NODE(tree[tot]); tree[tot].sum = 0; return tot ++; } void update(int root, int x, int y, int value){ if(tree[root].lx <= x && tree[root].ly <= y && tree[root].rx >= x && tree[root].ry >= y){ tree[root].sum += value; return ; } int xmid = (tree[root].lx + tree[root].rx) >> 1; int ymid = (tree[root].ly + tree[root].ry) >> 1; /* 0 <xmid + 1, ymid + 1> <rx, ry> 1 <lx, ymid + 1> <xmid, ry> 2 <lx, ly> <xmid, ymid> 3 <xmid + 1, ly> <rx, ymid> */ int rx, ry, lx, ly; rx = tree[root].rx, ry = tree[root].ry, lx = tree[root].lx, ly = tree[root].ly; if(x <= rx && y <= ry && x >= xmid + 1 && y >= ymid + 1){ if(tree[root].son[0] == -1){ tree[root].son[0] = add(xmid + 1, ymid + 1, rx, ry); } update(tree[root].son[0], x, y, value); } else if(x <= xmid && y <= ry && x >= lx && y >= ymid + 1){ if(tree[root].son[1] == -1){ tree[root].son[1] = add(lx, ymid + 1, xmid, ry); } update(tree[root].son[1], x, y, value); } else if(x <= xmid && y <= ymid && x >= lx && y >= ly){ if(tree[root].son[2] == -1){ tree[root].son[2] = add(lx, ly, xmid, ymid); } update(tree[root].son[2], x, y, value); } else if(x <= rx && y <= ymid && x >= xmid + 1 && y >= ly){ if(tree[root].son[3] == -1){ tree[root].son[3] = add(xmid + 1, ly, rx, ymid); } update(tree[root].son[3], x, y, value); } for(int i = 0; i < 4; i ++){ if(tree[root].son[i] != -1){ tree[root].sum += tree[tree[root].son[i]].sum; } } return ; } int query(int root, int xmin, int ymin, int xmax, int ymax){ if(tree[root].lx >= xmin && tree[root].ly >= ymin && tree[root].rx <= xmax && tree[root].ry <= ymax){ return tree[root].sum; } int xmid = (tree[root].lx + tree[root].rx) >> 1; int ymid = (tree[root].ly + tree[root].ry) >> 1; /* 0 <xmid + 1, ymid + 1> <rx, ry> 1 <lx, ymid + 1> <xmid, ry> 2 <lx, ly> <xmid, ymid> 3 <xmid + 1, ly> <rx, ymid> */ int rx, ry, lx, ly; rx = tree[root].rx, ry = tree[root].ry, lx = tree[root].lx, ly = tree[root].ly; int re = 0; if(xmin <= xmid && ymin <= ymid){ if(tree[root].son[2] != -1) re += query(tree[root].son[2], xmin, ymin, xmax, ymax); } if(xmax > xmid && ymin <= ymid){ if(tree[root].son[3] != -1) re += query(tree[root].son[3], xmin, ymin, xmax, ymax); } if(xmin <= xmid && ymax > ymid){ if(tree[root].son[1] != -1) re += query(tree[root].son[1], xmin, ymin, xmax, ymax); } if(xmax > xmid && ymax > ymid){ if(tree[root].son[0] != -1) re += query(tree[root].son[0], xmin, ymin, xmax, ymax); } cout << re << endl; return re; } }area_tree; int main(){ ios::sync_with_stdio(false); string str; int flag = 0;///0 - I 1 - Q area_tree.Init(); area_tree.add(1, 1, 20005, 20005); while(cin >> str){ if(str[0] == 'E') break; if(str[0] == 'I') { flag = 0; continue; } if(str[0] == 'Q') { flag = 1; continue; } if(flag == 0){ int x = str_to_int(str); int y, z; cin >> y >> z; area_tree.update(0, x, y, z); } else if(flag == 1){ int x1, y1, x2, y2; x1 = str_to_int(str); cin >> y1 >> x2 >> y2; cout << area_tree.query(0, x1, y1, x2, y2) << endl; } } return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main () { vector<int> vet(6); vector<int> lott(6); vector<int>::iterator it; for (int i = 0; i < 6; i++) { cin >> vet[i]; } for (int i = 0; i < 6; i++) { cin >> lott[i]; } int cont = 0; for (auto i = lott.begin(); i != lott.end(); i++) { it = find(vet.begin(), vet.end(), *i); if (it != vet.end()) { cont += 1; } } switch (cont) { case 3: cout << "terno" << endl; break; case 4: cout << "quadra" << endl; break; case 5: cout << "quina" << endl; break; case 6: cout << "sena" << endl; break; default: cout << "azar" << endl; } return 0; }
// // Created by Alex on 06/09/2018. // #ifndef CAPM_TIMESERIESDATA_H #define CAPM_TIMESERIESDATA_H #include <string> #include <vector> #include "Tools/CustomDate.h" #include "TimeSeriesHeaderReader.h" class TimeSeriesData { public: enum Variable{ OPEN, CLOSE, HIGH, LOW, VOLUME, EXDIVIDEND, SPLITRATIO, OPENADJ, CLOSEADJ, HIGHADJ, LOWADJ, VOLUMEADJ }; //// Constructors //// TimeSeriesData(); TimeSeriesData(std::string DataLine_, TimeSeriesHeaderReader Header_, std::string Source_); //// Get Methods //// long double GetDataMember(Variable Var_) const; bool IsInitialised() const; CustomDate GetDate() const; long double GetOpen() const; long double GetClose() const; long double GetHigh() const; long double GetLow() const; long double GetVolume() const; long double GetExDividend() const; long double GetSplitRatio() const; long double GetOpenAdj() const; long double GetCloseAdj() const; long double GetHighAdj() const; long double GetLowAdj() const; long double GetVolumeAdj() const; friend std::ostream & operator << (std::ostream & os, const TimeSeriesData & data); private: //// Private Members //// bool Initialised; CustomDate Date; long double Open; long double Close; long double High; long double Low; long double Volume; long double ExDividend; long double SplitRatio; long double OpenAdj; long double CloseAdj; long double HighAdj; long double LowAdj; long double VolumeAdj; //// Defaults //// CustomDate DefaultDate = CustomDate(1,1,1900); long double DefaultOpen = 0; long double DefaultClose = 0; long double DefaultHigh = 0; long double DefaultLow = 0; long double DefaultVolume = 0; long double DefaultExDividend = 0; long double DefaultSplitRatio = 0; long double DefaultOpenAdj = 0; long double DefaultCloseAdj = 0; long double DefaultHighAdj = 0; long double DefaultLowAdj = 0; long double DefaultVolumeAdj = 0; }; #endif //CAPM_TIMESERIESDATA_H
#include "ball.h" #include "main.h" Ball::Ball(float x, float y, double xspeed, double yspeed) { this->position = glm::vec3(x, y, 0); this->rotation = 0; this->xspeed = xspeed; this->yspeed = yspeed; GLfloat vertex_buffer_data[8][400]; int i,j=1,k,l=0; for(i=0;i<120;i++) { if(i%20 == 0 && i!=0) { j++; l=0; } for(k=9*l;k<9*l+3;k++) vertex_buffer_data[j][k]=0.0f; vertex_buffer_data[j][9*l+3]=0.2*cos(i*3.14159/60); vertex_buffer_data[j][9*l+4]=0.2*sin(i*3.14159/60); vertex_buffer_data[j][9*l+5]=0.0f; vertex_buffer_data[j][9*l+6]=0.2*cos((i+1)*3.14159/60); vertex_buffer_data[j][9*l+7]=0.2*sin((i+1)*3.14159/60); vertex_buffer_data[j][9*l+8]=0.0f; l++; } this->object1 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[1], COLOR_RED, GL_FILL); this->object2 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[2], COLOR_ORANGE, GL_FILL); this->object3 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[3], COLOR_YELLOW, GL_FILL); this->object4 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[4], COLOR_GREEN, GL_FILL); this->object5 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[5], COLOR_BLUE, GL_FILL); this->object6 = create3DObject(GL_TRIANGLES, 60, vertex_buffer_data[6], COLOR_VIOLET, GL_FILL); } void Ball::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1)); //draw something else in the circle so that it looks like rotating rotate = rotate * glm::translate(glm::vec3(0, 0, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object1); draw3DObject(this->object2); draw3DObject(this->object3); draw3DObject(this->object4); draw3DObject(this->object5); draw3DObject(this->object6); } void Ball::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } float Ball::get_y() { if((this->position.x > -2.9f && this->position.x < -2.7f) || (this->position.x > -1.7f && this->position.x < -1.5f)) { return -2.2f; } else if((this->position.x >= -2.7f) && (this->position.x <= -1.7f)) { return (-1.0f * (sqrt(0.25f - pow(this->position.x + 2.2f, 2)))) - 2.2f; } /*else if(this->position.x >= 1.65f && this->position.x <= 2.35f) { return -1.75f; }*/ else if(this->position.x <= -2.9f || this->position.x >= -1.5f) { return -2.0f; } } void Ball::tick() { this->position.x += this->xspeed; if(this->position.x > 3.75f) { this->position.x = 3.75f; } if(this->position.x < -3.75f) { this->position.x = -3.75f; } } bounding_box_t Ball::bounding_box() { float x = this->position.x, y = this->position.y; double r = 0.2; bounding_box_t bbox = { x, y, r}; return bbox; }
#include <iostream> #include <vector> #include <map> #include <queue> #include <stack> #include <string> #include <ctype.h> #include <stdio.h> #include <unordered_set> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *addTwoNumbersR(ListNode *l1, ListNode *l2, int carry) { //both l1 and l2 could be null if(l1== NULL && l2 == NULL && carry == 0) return NULL; int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; ListNode* ret = new ListNode(sum % 10); ret->next = addTwoNumbersR(l1?l1->next:NULL, l2?l2->next:NULL, sum/10); return ret; } ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode* result = addTwoNumbersR(l1, l2,0); return result; } int main() { ListNode *node1 = new ListNode(0); ListNode *node2 = new ListNode(8); ListNode *node3 = new ListNode(1); // node1->next = node2; ListNode* ret = addTwoNumbers(node1, node3); cout << ret->val << endl; return 0; }
const int N = 300; struct Dinic { struct Edge{ int from, to; ll flow, cap; }; vector<Edge> edge; vector<int> g[N]; int ne = 0; int lvl[N], vis[N], pass; int qu[N], px[N], qt; ll run(int s, int sink, ll minE) { if(s == sink) return minE; ll ans = 0; for(; px[s] < (int)g[s].size(); px[s]++) { int e = g[s][ px[s] ]; auto &v = edge[e], &rev = edge[e^1]; if(lvl[v.to] != lvl[s]+1 || v.flow >= v.cap) continue; // v.cap - v.flow < lim ll tmp = run(v.to, sink,min(minE, v.cap-v.flow)); v.flow += tmp, rev.flow -= tmp; ans += tmp, minE -= tmp; if(minE == 0) break; } return ans; } bool bfs(int source, int sink) { qt = 0; qu[qt++] = source; lvl[source] = 1; vis[source] = ++pass; for(int i = 0; i < qt; i++) { int u = qu[i]; px[u] = 0; if(u == sink) return true; for(auto& ed : g[u]) { auto v = edge[ed]; if(v.flow >= v.cap || vis[v.to] == pass) continue; // v.cap - v.flow < lim vis[v.to] = pass; lvl[v.to] = lvl[u]+1; qu[qt++] = v.to; } } return false; } ll flow(int source, int sink) { reset_flow(); ll ans = 0; //for(lim = (1LL << 62); lim >= 1; lim /= 2) while(bfs(source, sink)) ans += run(source, sink, LLINF); return ans; } void addEdge(int u, int v, ll c, ll rc) { Edge e = {u, v, 0, c}; edge.pb(e); g[u].push_back(ne++); e = {v, u, 0, rc}; edge.pb(e); g[v].push_back(ne++); } void reset_flow() { for(int i = 0; i < ne; i++) edge[i].flow = 0; memset(lvl, 0, sizeof(lvl)); memset(vis, 0, sizeof(vis)); memset(qu, 0, sizeof(qu)); memset(px, 0, sizeof(px)); qt = 0; pass = 0; } };
/********************************* * Lab 02 * Created by Kenneth Hobday & Elvet Potter II 01/21/2020 *********************************/ #include <iostream> using namespace std; #include "Bushel.h" // Main program void main() { class bushel a,b,c; // Initialize bushels a = bushel(3,8); b = bushel(2,6); /* Step 9 // Get bushels cout << "Enter bushel A (apples,oranges):"; a.get(cin); cout << "Enter bushel B (apples,oranges):"; b.get(cin); */ // Output bushels cout << "A: "; a.put(cout); cout << endl; cout << "B: "; b.put(cout); cout << endl; // Bushel compare 1 if(a==b) cout << "Bushel A == B" << endl; else cout << "Bushel A != B" << endl; // Bushel compare 2 if(a.lesser(b)) cout << "Bushel A < B" << endl; else if(a.greater(b)) cout << "Bushel A > B" << endl; else cout << "Bushel A ? B" << endl; }
#ifndef CPASSWDCONFIG_H #define CPASSWDCONFIG_H #include <QDialog> class CTitleWidget; class QTableWidget; class QDialogButtonBox; #define SEMIRPASSWD ("smfwk") #define BALABALAPASSWD ("balaitbalait") class CPasswdConfig : public QDialog { Q_OBJECT public: CPasswdConfig(QWidget *parent = 0); ~CPasswdConfig(); void SetBrands(const QStringList& brands); public Q_SLOTS: void acceptPasswd(); void dataChanged(); protected: virtual void mousePressEvent(QMouseEvent *); virtual void mouseMoveEvent(QMouseEvent *); virtual void mouseReleaseEvent(QMouseEvent *); private: void setItem(const QString& brand); private: CTitleWidget* m_titleWidget; QTableWidget* m_tableWidget; QDialogButtonBox* m_buttonBox; bool m_bPressed; QPoint m_movePoint; QStringList m_pBrandList; bool m_bAnyChanged; }; #endif // CPASSWDCONFIG_H
#ifndef TREEFACE_POST_SURFACE_H #define TREEFACE_POST_SURFACE_H #include <treecore/RefCountObject.h> #include "treecore/ClassUtils.h" #include "treeface/gl/Enums.h" namespace treeface { class PostNetwork; class PostProcess; class PostTarget; class Framebuffer; class PostSurface: public treecore::RefCountObject { friend class PostNetwork; friend class PostTarget; friend class PostProcess; public: PostSurface(); TREECORE_DECLARE_NON_COPYABLE( PostSurface ) TREECORE_DECLARE_NON_MOVABLE( PostSurface ) virtual ~PostSurface(); protected: virtual void attach_to( Framebuffer* fbo, GLFramebufferAttachment attach ) = 0; struct Guts; Guts* m_guts; }; } // namespace treeface #endif // TREEFACE_POST_SURFACE_H
//============================================================================ // Name : UnorderedMultimap.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include<unordered_map> using namespace std; int main() { unordered_multimap<int,int> ummap; ummap.insert(pair<int,int>(2,23)); ummap.insert(pair<int,int>(2,23)); ummap.insert(pair<int,int>(23,23)); ummap.insert(pair<int,int>(2,23)); ummap.insert(pair<int,int>(21,23)); ummap.insert(pair<int,int>(2,23)); for(pair<int,int> e:ummap){ cout<<e.first<<" "<<e.second<<endl; } return 0; }
#include "mini/BlackJack/blackjacktile.h" BlackJackTile::BlackJackTile(int index, const char *a, QWidget* parent) :QPushButton(parent) { this->index=index; this->a = a; } BlackJackTile::~BlackJackTile() { } int BlackJackTile::getIndex() { return this->index; }
/* * pod serializer requirements: * - allocate memory when needed; * - named blocks with pod types defined by user; */ #include <cstring> #include <cstdlib> #include <cerrno> #include <iostream> #include <fstream> #ifndef _SERIALIZER_H #define _SERIALIZER_H namespace csys { class serializer { /* * * block structure * * |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|0|_|_|_|_|_|_|_|_| * | dev_id | len | | | | * | cstring | size_t| int | cstring | float | * |s i g n a t u r e| b l o c k b o d y | * * beg - points to the beginning of the block * len - message length * hlen - length of dev_id */ private: int message_len_; char* buf_; bool head_; /* current position */ char* pos_; /* begininng of current block */ char* beg_; /* current block length */ size_t block_len_; /* size of buffer */ size_t size_; /* * length of dev_id header * must be the same for each user */ const size_t hlen_; void out_of_mem(size_t sizein) { /* realloc preserving old data */ size_ = (sizein) ? sizein + 1 : 2*size_; size_t shift1 = pos_ - buf_; size_t shift2 = beg_ - buf_; char* buf_new; buf_new = (char*)malloc(size_); if(!buf_new) { char err[64] = {0}; sprintf(err, "[%s] malloc failed: %s\n", __func__, strerror(errno)); fwrite(err, 1, strlen(err), stderr); } memset(buf_new, 0x00, size_); memcpy(buf_new, buf_, size_/2); free(buf_); buf_ = buf_new; pos_ = buf_ + shift1; beg_ = buf_ + shift2; // std::cout << "out_of_mem: " << size_ << std::endl; } public: serializer(): size_(32), hlen_(4) { buf_ = (char*)malloc(size_); if(!buf_) { /* malloc failed */} memset(buf_, 0x00, size_); message_len_ = 0; pos_ = buf_ + hlen_ + sizeof(block_len_); beg_ = buf_; block_len_ = 0; head_ = true; } ~serializer() { free(buf_); } bool empty() { return (0 == size_) ? 1 : 0; } size_t get_size() { return size_; } size_t length() { return message_len_; } size_t get_hlen() { return hlen_; } const char* buffer_fetch() { return buf_; } void buffer_update(const char* bufin, size_t sizein) { if(size_ <= sizein) { out_of_mem(sizein); } memcpy(buf_, bufin, sizein); message_len_ = (int)sizein; } void clear() { reset(); memset(buf_, 0x00, size_); message_len_ = 0; } void reset() { pos_ = buf_ + hlen_ + sizeof(block_len_); beg_ = buf_; block_len_ = 0; head_ = true; } /* call when device serialization is done */ void sign_block(const char* id) { block_len_ = (pos_ - beg_) - hlen_ - sizeof(block_len_); message_len_ += (pos_ - beg_); memcpy(beg_, id, hlen_); memcpy(beg_ + hlen_, &block_len_, sizeof(block_len_)); beg_ = pos_; if(size_ - (pos_ - buf_) <= (hlen_ + sizeof(block_len_))) { out_of_mem(0); } pos_ += hlen_ + sizeof(block_len_); } bool read_block(char* id) { if(message_len_ <= pos_ - beg_) { return false; } if(!head_) { beg_ += block_len_ + hlen_ + sizeof(block_len_); } if(0x00 == *beg_) { return false; } pos_ = beg_ + hlen_ + sizeof(block_len_); memcpy(id, beg_, hlen_); memcpy(&block_len_, beg_ + hlen_, sizeof(block_len_)); head_ = false; return true; } void serialize_cstring(const char* str) { if(strlen(str) >= size_ - (pos_ - buf_) - 1) { out_of_mem(0); } memcpy(pos_, str, strlen(str)); pos_ += strlen(str); *pos_ = 0x00; pos_ += 1; } void deserialize_cstring(char* str) { memcpy((void*)str, pos_, strlen(pos_)); pos_ += strlen(pos_) + 1; } template <class T> void serialize(T var) { if(sizeof(T) >= size_ - (pos_ - buf_)) { out_of_mem(0); } memcpy(pos_, &var, sizeof(T)); pos_ += sizeof(T); } template <class T> void deserialize(T* var) { memcpy((void*)var, pos_, sizeof(T)); pos_ += sizeof(T); } void dump() { std::ofstream file("buf.bin", std::ios::out | std::ios::binary); file.write(buf_, size_); file.close(); } }; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifndef NS4P_COMPONENT_PLUGINS #include "modules/pi/OpPluginDetectionListener.h" #include "modules/prefs/prefsmanager/collections/pc_app.h" #include "platforms/mac/File/FileUtils_Mac.h" #include "platforms/mac/util/CTextConverter.h" #include "platforms/mac/util/systemcapabilities.h" #include "platforms/mac/util/macutils.h" // MacHacksIncluded: Mac Hacks #ifdef _PLUGIN_SUPPORT_ CFBundleRef CreatePluginPackageBundle(const FSRef *inFile) { CFURLRef pluginURLRef = NULL; CFBundleRef pluginBundleRef = NULL; pluginURLRef = CFURLCreateFromFSRef(NULL, inFile); if (pluginURLRef != NULL) { pluginBundleRef = CFBundleCreate(NULL, pluginURLRef); CFRelease(pluginURLRef); } return pluginBundleRef; } Boolean IsPluginPackage(const FSRef *inFile) { UInt8 path8[MAX_PATH+1]; OSStatus ret = FSRefMakePath(inFile, path8, MAX_PATH+1); if (ret != noErr) return false; CFBundleRef pluginBundle = CreatePluginPackageBundle(inFile); if(pluginBundle != NULL) { OSType type; OSType creator; CFBundleGetPackageInfo(pluginBundle, &type, &creator); CFRelease(pluginBundle); if(type == 'BRPL') { return true; } } return false; } class PluginCallbackContext { public: PluginCallbackContext(OpPluginDetectionListener* listener, uni_char* name, uni_char* location) : m_listener(listener), m_name(name), m_location(location), m_token(NULL) { } public: OpPluginDetectionListener* m_listener; uni_char* m_name; uni_char* m_location; void* m_token; }; void InsertPluginDictionary(const void *key, const void *value, void *context) { CFStringRef mime = (CFStringRef) key; if(CFGetTypeID(mime) != CFStringGetTypeID()) return; CFDictionaryRef data = (CFDictionaryRef) value; if(CFGetTypeID(data) != CFDictionaryGetTypeID()) return; CFArrayRef exts = (CFArrayRef) CFDictionaryGetValue(data, CFSTR("WebPluginExtensions")); if(exts && CFGetTypeID(exts) != CFArrayGetTypeID()) return; CFStringRef desc = (CFStringRef) CFDictionaryGetValue(data, CFSTR("WebPluginTypeDescription")); if(desc && CFGetTypeID(desc) != CFStringGetTypeID()) return; CFBooleanRef enable = (CFBooleanRef) CFDictionaryGetValue(data, CFSTR("WebPluginTypeEnabled")); if(enable && CFGetTypeID(enable) != CFBooleanGetTypeID()) return; PluginCallbackContext *ctxt = (PluginCallbackContext *)context; if (!enable || CFBooleanGetValue(enable)) { OpString mime_type; OpString extension, extensions, description; int i, count; if(exts) { count = CFArrayGetCount(exts); for(i=0; i<count; i++) { CFStringRef ext = (CFStringRef)CFArrayGetValueAtIndex(exts, i); if(CFGetTypeID(ext) != CFStringGetTypeID()) continue; SetOpString(extension, ext); if (i) extensions.Append(UNI_L(",")); extensions.Append(extension); } } if (desc) { SetOpString(description, desc); } if (SetOpString(mime_type, mime)) { if(ctxt->m_token) { if (OpStatus::IsSuccess(ctxt->m_listener->OnAddContentType(ctxt->m_token, mime_type))) { OpStatus::Ignore(ctxt->m_listener->OnAddExtensions(ctxt->m_token, mime_type, extensions, description)); } } } } } void InsertWebPluginPackage(OpPluginDetectionListener* listener, CFBundleRef bundle) { OpString fileLocation; OpString pluginName; OpString pluginDesc; OpString pluginVersion; CFURLRef pluginURLRef = CFBundleCopyBundleURL(bundle); if(pluginURLRef) { CFStringRef str = CFURLCopyFileSystemPath(pluginURLRef, kCFURLPOSIXPathStyle); if(str) { SetOpString(fileLocation, str); CFRelease(str); } CFRelease(pluginURLRef); } CFURLRef supportFilesCFURLRef = CFBundleCopySupportFilesDirectoryURL(bundle); CFURLRef versionURLRef = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, supportFilesCFURLRef, CFSTR("Info.plist"),false); CFRelease(supportFilesCFURLRef); // Read the XML file. CFDataRef xmlCFDataRef; SInt32 errorCode; if(!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, versionURLRef, &xmlCFDataRef, NULL, NULL, &errorCode)) { CFRelease(versionURLRef); return; } CFStringRef errorString; // Reconstitute the dictionary using the XML data. CFPropertyListRef myCFPropertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, xmlCFDataRef, kCFPropertyListImmutable, &errorString); if(myCFPropertyListRef && CFDictionaryGetTypeID() == CFGetTypeID(myCFPropertyListRef)) { CFStringRef plugin_name; if(CFDictionaryGetValueIfPresent((CFDictionaryRef)myCFPropertyListRef, (const void*)CFSTR("WebPluginName"), (const void**) &plugin_name)) SetOpString(pluginName, plugin_name); CFStringRef plugin_description; if(CFDictionaryGetValueIfPresent((CFDictionaryRef)myCFPropertyListRef, (const void*)CFSTR("WebPluginDescription"), (const void**) &plugin_description)) if(plugin_description && CFGetTypeID(plugin_description) == CFStringGetTypeID()) SetOpString(pluginDesc, plugin_description); } CFStringRef plugin_version; if(CFDictionaryGetValueIfPresent((CFDictionaryRef)myCFPropertyListRef, (const void*)CFSTR("CFBundleShortVersionString"), (const void**) &plugin_version)) if(plugin_version && CFGetTypeID(plugin_version) == CFStringGetTypeID()) SetOpString(pluginVersion, plugin_version); CFDictionaryRef mime_list; if(myCFPropertyListRef && CFDictionaryGetValueIfPresent((CFDictionaryRef)myCFPropertyListRef, (const void*)CFSTR("WebPluginMIMETypes"), (const void**) &mime_list)) { if (CFGetTypeID(mime_list) == CFDictionaryGetTypeID()) { PluginCallbackContext context(listener, pluginName, fileLocation.CStr()); if(OpStatus::IsSuccess(listener->OnPrepareNewPlugin(OpStringC(context.m_location), OpStringC(context.m_name), OpStringC(pluginDesc), OpStringC(pluginVersion), COMPONENT_SINGLETON, TRUE, context.m_token))) { CFDictionaryApplyFunction(mime_list, InsertPluginDictionary, &context); OpStatus::Ignore(listener->OnCommitPreparedPlugin(context.m_token)); } } } if (myCFPropertyListRef) CFRelease(myCFPropertyListRef); if (errorString) CFRelease(errorString); CFRelease(xmlCFDataRef); CFRelease(versionURLRef); } bool IsBadJavaPlugin() { bool bad_java_plugin = false; if(GetOSVersion() < 0x1070) { // This code is here to detect an early version of the Java Plugin 2 plugin, which didn't work well. // If this version is detected (JVMVersion 1.6.0_20 and less), we will avoid loading the plugin. // TODO: This code should probably be removed in the future. CFURLRef url_path = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Resources/Info.plist"), kCFURLPOSIXPathStyle, false); if(url_path) { // Read the XML file. CFDataRef xmlCFDataRef; SInt32 errorCode; if(CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, url_path, &xmlCFDataRef, NULL, NULL, &errorCode)) { CFStringRef errorString; // Reconstitute the dictionary using the XML data. CFPropertyListRef myCFPropertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, xmlCFDataRef, kCFPropertyListImmutable, &errorString); if(myCFPropertyListRef) { if(CFDictionaryGetTypeID() == CFGetTypeID(myCFPropertyListRef)) { CFDictionaryRef java_vm; if(CFDictionaryGetValueIfPresent((CFDictionaryRef)myCFPropertyListRef, (const void*)CFSTR("JavaVM"), (const void**) &java_vm) && CFDictionaryGetTypeID() == CFGetTypeID(java_vm)) { CFStringRef java_version; if(CFDictionaryGetValueIfPresent(java_vm, (const void*)CFSTR("JVMVersion"), (const void**) &java_version) && CFStringGetTypeID() == CFGetTypeID(java_version)) { int len = CFStringGetLength(java_version); OpString ver; if(ver.Reserve(len + 1)) { CFStringGetCharacters(java_version, CFRangeMake(0,len), (UniChar*)ver.CStr()); ver[len] = 0; int minor_version = 0; if(uni_sscanf(ver.CStr(), UNI_L("1.6.0_%d"), &minor_version) == 1) { if(minor_version < 20) { bad_java_plugin = true; } } } } } } CFRelease(myCFPropertyListRef); } CFRelease(xmlCFDataRef); } CFRelease(url_path); } } return bad_java_plugin; } void InsertPluginPackage(OpPluginDetectionListener* listener, CFBundleRef pluginBundle) { short resFileID; int mimeCount; OpString fileLocation; uni_char fileName[256]; uni_char plugName[256]; uni_char desc[256]; uni_char mime[256]; uni_char exts[256]; Handle buf; unsigned char *bufPtr = NULL; short strCount; CFURLRef pluginURLRef = CFBundleCopyBundleURL(pluginBundle); if(pluginURLRef) { CFStringRef str = CFURLCopyFileSystemPath(pluginURLRef, kCFURLPOSIXPathStyle); if(str) { SetOpString(fileLocation, str); CFRelease(str); } CFRelease(pluginURLRef); } BOOL java_plugin = fileLocation.HasContent() && uni_strstr(fileLocation.CStr(), UNI_L("JavaPlugin2_NPAPI.plugin")); if (java_plugin && IsBadJavaPlugin()) return; OpString pluginVersion; if (CFStringRef plugin_version = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(pluginBundle, CFSTR("CFBundleShortVersionString"))) if (plugin_version && CFGetTypeID(plugin_version) == CFStringGetTypeID()) SetOpString(pluginVersion, plugin_version); resFileID = CFBundleOpenBundleResourceMap(pluginBundle); if (resFileID > 0) { short oldResFileID = CurResFile(); UseResFile(resFileID); if (noErr == ResError()) { //it's a resource file //if (IsGoodFragment(resFileID)) { desc[0] = '\0'; plugName[0] = '\0'; buf = Get1Resource('STR#', 126); if (buf) { HLock(buf); strCount = *(short *) *buf; if (strCount >= 1) { bufPtr = (unsigned char *) *buf + 2; gTextConverter->ConvertStringFromMacP(bufPtr, desc, 256); } if (strCount >= 2) { bufPtr += bufPtr[0] + 1; gTextConverter->ConvertStringFromMacP(bufPtr, plugName, 256); } HUnlock(buf); ReleaseResource(buf); } buf = Get1Resource('STR#', 128); if (buf && *buf && *(short *) *buf) { BOOL mime_types_parsed = FALSE; // Quicktime has an extra function that hold extra mimetypes we need to look in // This should not exist for other plugins if NP_GetMIMEDescriptionUPP does exist we should get the // mime types from here rather than from the resource BOOL quicktime_plugin = uni_strcmp(fileLocation.CStr(), UNI_L("/Library/Internet Plug-Ins/QuickTime Plugin.plugin")) == 0; if(quicktime_plugin) { CFDictionaryRef mime_list = (CFDictionaryRef) CFPreferencesCopyAppValue(CFSTR("WebPluginMIMETypes"), CFSTR("com.apple.quicktime.plugin.preferences")); if (mime_list) { if (CFGetTypeID(mime_list) == CFDictionaryGetTypeID()) { PluginCallbackContext context(listener, (*plugName) ? plugName : fileName, fileLocation.CStr()); if(OpStatus::IsSuccess(listener->OnPrepareNewPlugin(OpStringC(context.m_location), OpStringC(context.m_name), OpStringC(NULL), OpStringC(pluginVersion), COMPONENT_SINGLETON, TRUE, context.m_token))) { CFDictionaryApplyFunction(mime_list, InsertPluginDictionary, &context); OpStatus::Ignore(listener->OnCommitPreparedPlugin(context.m_token)); } mime_types_parsed = true; } CFRelease(mime_list); } } // If NP_GetMIMEDescriptionUPP failed to get the mimetypes parse the resource if (!mime_types_parsed) { mimeCount = *(short *) *buf >> 1; HLock(buf); bufPtr = (unsigned char *) *buf + 2; void *token; if(OpStatus::IsSuccess(listener->OnPrepareNewPlugin(OpStringC(fileLocation), OpStringC((*plugName) ? plugName : fileName), OpStringC(desc), OpStringC(pluginVersion), COMPONENT_SINGLETON, TRUE, token))) { while (mimeCount--) { gTextConverter->ConvertStringFromMacP(bufPtr, mime, 256); bufPtr += bufPtr[0] + 1; gTextConverter->ConvertStringFromMacP(bufPtr, exts, 256); bufPtr += bufPtr[0] + 1; if(OpStatus::IsSuccess(listener->OnAddContentType(token, mime))) { OpStatus::Ignore(listener->OnAddExtensions(token, mime, exts)); } } OpStatus::Ignore(listener->OnCommitPreparedPlugin(token)); } } HUnlock(buf); ReleaseResource(buf); } } } UseResFile(oldResFileID); CFBundleCloseBundleResourceMap(pluginBundle, resFileID); } else InsertWebPluginPackage(listener, pluginBundle); } class ScanFolderForPlugins { OpPluginDetectionListener* listener; Boolean m_recurse; public: explicit ScanFolderForPlugins(OpPluginDetectionListener* pl, Boolean recurse = true) : listener(pl), m_recurse(recurse) { } void operator()(ItemCount count, const FSCatalogInfo* inCatInfo, const FSRef* ref) { Boolean isFolder, wasAlias; if (noErr == FSResolveAliasFile(const_cast<FSRef*>(ref), NULL, &isFolder, &wasAlias)) { BOOL ignore_plugin = FALSE; OpString name; OpFileUtils::ConvertFSRefToUniPath(ref, &name); if(g_pcapp->IsPluginToBeIgnored(name)) { ignore_plugin = TRUE; } else { // Also check name without suffix. int index = name.FindLastOf('.'); if(index >= 0) { name[index] = 0; if(g_pcapp->IsPluginToBeIgnored(name)) { ignore_plugin = TRUE; } } } if(!ignore_plugin) { //We found another thing in the Plugins folder if (isFolder) { // This "folder" might just be a package... if(IsPluginPackage(ref)) { BOOL universal_plugin = TRUE; /* MacHack: Ignore Flash Player Enabler plugin on Intel Macs Ignores the Flash Player Enabler plugin on Intel Macs. We need to skip this plugin on Intel Mac's because it has been built for PPC only and thus when it is picked up the real flash player is ignored and doesn't run. It also seems to serve no purpose as using the Flash Player plugin directly works fine. */ if (uni_strstr(uni_strupr(name), UNI_L("FLASH PLAYER ENABLER.PLUGIN"))) { universal_plugin = FALSE; } if (universal_plugin) { CFBundleRef plugin_bundle = CreatePluginPackageBundle(ref); if(plugin_bundle) { InsertPluginPackage(listener, plugin_bundle); CFRelease(plugin_bundle); } } } else { //It's a folder... if (m_recurse) { MacForEachItemInFolder(*ref, ScanFolderForPlugins(listener, false)); } } } else { //It's a file... Not supported! } } } } }; OP_STATUS DetectMacPluginViewers(const OpStringC& suggested_plugin_paths, OpPluginDetectionListener* listener) { FSRef plugin_folder; // Apple TN 2020 says we should use kLocalDomain under OS X. if (noErr == ::FSFindFolder( kLocalDomain, kInternetPlugInFolderType, kCreateFolder, &plugin_folder)) { MacForEachItemInFolder(plugin_folder, ScanFolderForPlugins(listener)); } // Bug 187806 says we should also use user domain if (noErr == ::FSFindFolder( kUserDomain, kInternetPlugInFolderType, kCreateFolder, &plugin_folder)) { MacForEachItemInFolder(plugin_folder, ScanFolderForPlugins(listener)); } return OpStatus::OK; } #endif //_PLUGIN_SUPPORT_ #endif // NS4P_COMPONENT_PLUGINS
// // File: CLedBuf.cpp // Author: Andy Shepherd // email: seg7led@bytecode.co.uk // License: Public Domain // #define __TEST__ #ifdef __TEST__ #include <stdio.h> #include <stdlib.h> #endif #include "CLedBuf.h" CLEDBuf::CLEDBuf() { clear(); } void CLEDBuf::clear() { for(uint8_t x = 0; x < sizeof( m_buf ); x++ ) { m_buf[x] = 0; m_buf_dp[x] = 0; } m_bufPos = 0; } /** * Add Decimal point to buffer */ uint8_t CLEDBuf::addDP() { if( m_bufPos < sizeof( m_buf_dp ) ) { m_buf_dp[m_bufPos - 1] = 1; } // m_bufPos++; return 1; } bool CLEDBuf::setCharAt( uint8_t pos, char ch, bool dp ) { if( pos >=0 && pos < getNumDigits() ) { m_buf[pos] = ch; m_buf_dp[pos] = dp; return true; } return false; } bool CLEDBuf::setDpAt( uint8_t pos, bool dp ) { if( pos >=0 && pos < getNumDigits() ) { m_buf_dp[pos] = dp; return true; } return false; } void CLEDBuf::shiftLeft( char ch, bool dp) { for(int x = 0; x < sizeof(m_buf)-1; x++) { m_buf[x] = m_buf[x+1]; m_buf_dp[x] = m_buf_dp[x+1]; } setCharAt( sizeof(m_buf)-1, ch, dp ); } void CLEDBuf::shiftRight( char ch, bool dp) { for(int x = sizeof(m_buf)-1; x > 0 ; x--) { m_buf[x] = m_buf[x-1]; m_buf_dp[x] = m_buf_dp[x-1]; } setCharAt( 0, ch, dp ); } /** * Add unsigned long to buffer * @param l number to be added * @return length added to buffer */ uint8_t CLEDBuf::addULong( unsigned long l ) { char sBuf[18]; int len = sprintf( sBuf,"%ld", l ); int lenToCountDown = len; int pos = 0; while( lenToCountDown > 0 ) { addChar( sBuf[pos++] ); lenToCountDown--; } return len; } /** * Add single digit int to buffer * @param i number to be added * @return length added to buffer. Always 1 if successful else 0. */ uint8_t CLEDBuf::addInt( int i ) { if( i < 10 && i >= 0) { char itoaBuf[2]; itoa( i, itoaBuf, 10 ); addChar( itoaBuf[0] ); return 1; } return 0; } /** * Add single char to buffer * @param c char to be added * @return length added to buffer. Always 1 if successful else 0. */ uint8_t CLEDBuf::addChar( char c ) { if( m_bufPos < sizeof( m_buf ) ) { m_buf[ m_bufPos ] = c; m_bufPos++; return 1; } return 0; } uint8_t CLEDBuf::getCurrentDigitPos() { return m_bufPos; } uint8_t CLEDBuf::getNumDigits() { return (uint8_t) CLEDBUF_NUMDIGITS; } char * CLEDBuf::getBuf() { uint8_t x; uint8_t buf_pos = 0; // Clear buf for(x = 0; x < sizeof( m_bufCombined ); x++) { m_bufCombined[x] = 0; } for(int x = 0; x < sizeof( m_buf ); x++) { m_bufCombined[buf_pos++] = m_buf[x]; if( m_buf_dp[x] != 0 ) { m_bufCombined[buf_pos++] = '.'; } } return m_bufCombined; }
#include <iostream> #include <vector> using namespace std; #define int long long int #define pb push_back #define endl '\n' const int N = 4e1 + 5; vector <string> Graph; int vis[N][N]; int n, m, spike; int ans = 0; int row[4] = { -1, 1, 0, 0}; int col[4] = {0, 0, -1, 1}; bool is_safe(int i, int j) { if (i < 0 || i >= n || j < 0 || j >= m || vis[i][j]) return false; else return true; } bool can_go(int i, int j, int &sp) { if (Graph[i][j] == '#') return false; if (Graph[i][j] == '.' || Graph[i][j] == 'x') return true; if (sp > 0 && Graph[i][j] == 's') { sp--; return true; } return false; } void dfs(int i, int j, int &spk) { vis[i][j] = 1; if (Graph[i][j] == 'x' && (2 * (spike - spk) <= spike)) { ans = 1; return ; } else { for (int it = 0; it < 4; it++) { int temp = spk; int x = i + row[it]; int y = j + col[it]; if (is_safe(x, y) && can_go(x, y, temp)) dfs(x, y, temp); } } vis[i][j] = 0; return ; } void solve() { cin >> n >> m >> spike; int s = spike; string ch; for (int i = 0; i < n; i++) { cin >> ch; Graph.pb(ch); } int x, y; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (Graph[i][j] == '@') { x = i; y = j; break; } } } dfs(x, y, spike); if (ans) cout << "SUCCESS" << endl; else cout << "IMPOSSIBLE" << 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 // code starts solve(); return 0; }
#ifndef PHYSICS_SCENE_CPP #define PHYSICS_SCENE_CPP #include <component/MeshRenderer.h> #include <component/Rigidbody.h> #include <component/SphereCollider.h> #include <component/BoxCollider.h> #include <resource/Scene.h> #include <resource/Texture.h> #include <resource/shader/GShader.h> #include "../PostProcessors/SSAOProcessor.cpp" #include "../PostProcessors/SSReflectionProcessor.cpp" #include "../PostProcessors/AutoExposureProcessor.cpp" #include "../PostProcessors/BloomProcessor.cpp" #include "../PostProcessors/ToneMappingProcessor.cpp" #include "../Scripts/CameraControllerScript.cpp" #include "../Scripts/StateControllerScript.cpp" #ifdef PB_MEM_DEBUG #include "PhotonBox/util/MEMDebug.h" #define new DEBUG_NEW #endif class PhysicsScene : public Scene { public: void Load() { /* --------------------------- RESOURCES --------------------------- */ std::vector<std::string> nightSky = { Resources::ENGINE_RESOURCES + "/default_roughness.png", Resources::ENGINE_RESOURCES + "/default_roughness.png", Resources::ENGINE_RESOURCES + "/default_roughness.png", Resources::ENGINE_RESOURCES + "/default_roughness.png", Resources::ENGINE_RESOURCES + "/default_roughness.png", Resources::ENGINE_RESOURCES + "/default_roughness.png", }; Renderer::setSkyBox(createResource<CubeMap>(nightSky)); Renderer::getSkyBox()->intensity = 1; /* --------------------------- POST PROCESSING --------------------------- */ SSAOProcessor * p_ssao = new SSAOProcessor(0); SSReflectionProcessor* p_ssreflection = new SSReflectionProcessor(1); AutoExposureProcessor* p_autoExposure = new AutoExposureProcessor(2); BloomProcessor* p_bloom = new BloomProcessor(3); ToneMappingProcessor* p_tonemapping = new ToneMappingProcessor(4); /* --------------------------- OBJ --------------------------- */ Mesh* planeMesh = createResource<Mesh>(Resources::ENGINE_RESOURCES + "/primitives/plane.obj"); Mesh* sphereMesh = createResource<Mesh>(Resources::ENGINE_RESOURCES + "/primitives/sphere.obj"); Mesh* boxMesh = createResource<Mesh>(Resources::ENGINE_RESOURCES + "/primitives/cube.obj"); /* --------------------------- TEXTURES --------------------------- */ Texture* default_normal = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/default_normal.png"), false); Texture* default_specular = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/default_specular.png"), false); Texture* default_emission = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/default_emission.png"), false); Texture* default_ao = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/default_ao.png"), false); Texture* default_roughness = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/default_roughness.png"), false); Texture* gradient = createResource<Texture>(std::string(Resources::ENGINE_RESOURCES + "/gradient.png"), false); /* --------------------------- SHADERS --------------------------- */ GShader* defaultShader = GShader::getInstance(); /* --------------------------- MATERIALS --------------------------- */ Material* def = createResource<Material>(defaultShader); def->setTexture("albedoMap", default_ao); def->setTexture("normalMap", default_normal); def->setTexture("roughnessMap", default_specular); def->setTexture("aoMap", default_ao); def->setTexture("metallicMap", default_emission); def->setTexture("emissionMap", default_emission); /* --------------------------- CAMERA --------------------------- */ Entity* cam = instanciate("Camera"); cam->addComponent<Camera>(); cam->getComponent<Transform>()->setPosition(Vector3f(0, 6, -30)); cam->getComponent<Transform>()->setRotation(Vector3f(0, 0, 0)); cam->addComponent<CameraControllerScript>(); cam->addComponent<StateControllerScript>(); /* --------------------------- LIGHTS --------------------------- */ Entity* ambient = instanciate("Ambient"); ambient->addComponent<AmbientLight>(); Entity* sun = instanciate("Sun"); sun->addComponent<DirectionalLight>(); sun->getComponent<DirectionalLight>()->color = Vector3f(0.93f, 0.92f, 0.94f); sun->getComponent<DirectionalLight>()->direction = Vector3f(1, -1, 1); sun->getComponent<DirectionalLight>()->intensity = 40.0f; for (size_t i = 0; i < 100; i++) { float scale = rand() % 100 * 0.04f + 1; //float scale = 1.5f; std::cout << scale << std::endl; Entity* sphere = instanciate("Sphere" + std::to_string(i)); sphere->getComponent<Transform>()->setPosition(Vector3f(rand() % 20 - 10, rand() % 20 + 10, rand() % 20-10)); //sphere->getComponent<Transform>()->setScale(Vector3f(scale, scale, scale)); sphere->addComponent<MeshRenderer>()->setMesh(sphereMesh); sphere->getComponent<MeshRenderer>()->setMaterial(def); sphere->addComponent<SphereCollider>()->setRadius(1); sphere->addComponent<Rigidbody>()->setMass(scale); } /* for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 4; j++) { for (size_t z = 0; z < 4; z++) { Entity* box = instanciate("Box" + std::to_string(i) + std::to_string(j) + std::to_string(z)); //box->getComponent<Transform>()->setPosition(Vector3f(0, 9, 0)); box->getComponent<Transform>()->setPosition(Vector3f(i * 3 + (rand() % 2), 6 + z * 3 + (rand() % 2), j * 3 + (rand() % 2))); box->addComponent<MeshRenderer>()->setMesh(boxMesh); box->getComponent<MeshRenderer>()->setMaterial(def); box->addComponent<Rigidbody>(); //box->addComponent<PointLight>()->color = Vector3f((i/4.0f * 255.0f), (j / 4.0f * 255.0f), (z / 4.0f * 255.0f)); box->addComponent<BoxCollider>()->setHalfExtents(Vector3f(1)); } } } */ Entity* quad = instanciate("Plane"); quad->getComponent<Transform>()->setPosition(Vector3f(0, 0, -3)); quad->getComponent<Transform>()->setScale(Vector3f(200, 200, 200)); quad->addComponent<MeshRenderer>(); quad->getComponent<MeshRenderer>()->setMesh(planeMesh); quad->getComponent<MeshRenderer>()->setMaterial(def); } void OnUnload() {} }; #endif // PHYSICS_SCENE_CPP
#include "pcbwindow.h" #include "ui_pcbwindow.h" #include <QtDebug> pcbWindow::pcbWindow(QWidget *parent) : QWidget(parent), ui(new Ui::pcbWindow) { qDebug()<<"begining of pcbWindow constructor"; ui->setupUi(this); control = new QPCBController(); scheduler = new processSchedulers; ticketWindow = new ticketDefine; quantumWindow = new QuantumDefineWindow; //button to pointer //createButton = ui->createButton; //deleteButton = ui->deleteButton; //blockButton = ui->blockButton; //unblockButton = ui->unblockButton; suspendButton = ui->suspendButton; resumeButton = ui->resumeButton; priorityButton = ui->priorityButton; pcbShowButton = ui->pcbShower; quitButton = ui->quitButton; showBlockedButton = ui->showBlocked; showReadyButton = ui->showReady; timeRemainingSBox = ui->timeRemainingSBox; schedulerButton = ui->schedulerButton; //line edit to pointer nameLEdit = ui->nameLEdit; classLEdit = ui->classLEdit; prioritySBox = ui->prioritySBox; fileNameLEdit = ui->fileNameLEdit; readFileButton = ui->readFileButton; reqMemSBox = ui->reqMemSBox; //connecting buttons to function calls //connect(createButton, SIGNAL(clicked()),this,SLOT(createPCB())); //connect(deleteButton, SIGNAL(clicked()),this,SLOT(deletePCB())); //connect(blockButton, SIGNAL(clicked()),this,SLOT(block())); //connect(unblockButton,SIGNAL(clicked()),this,SLOT(unblock())); connect(suspendButton,SIGNAL(clicked()),this,SLOT(suspend())); connect(resumeButton, SIGNAL(clicked()),this,SLOT(resume())); connect(priorityButton,SIGNAL(clicked()),this,SLOT(setPriority())); connect(pcbShowButton,SIGNAL(clicked()),this,SLOT(showPCBList())); connect(quitButton,SIGNAL(clicked()),this,SLOT(hide())); connect(priorityButton,SIGNAL(clicked()),this,SLOT(setPriority())); connect(showBlockedButton,SIGNAL(clicked()),this,SLOT(showBlockedPCB())); connect(showReadyButton,SIGNAL(clicked()),this,SLOT(showReadyPCB())); connect(readFileButton,SIGNAL(clicked()),this,SLOT(readFile())); connect(schedulerButton,SIGNAL(clicked()),this,SLOT(showSchedulers())); qDebug()<<"before fuckup?"; connect(scheduler->SJHButton,SIGNAL(clicked()),control,SLOT(setSchedulerSFJ())); connect(scheduler->FIFO_button,SIGNAL(clicked()),control,SLOT(setSchedulerFIFO())); connect(scheduler->STCF_button,SIGNAL(clicked()),control,SLOT(setSchedulerSTCF())); connect(scheduler->FPPS_button,SIGNAL(clicked()),control,SLOT(setSchedulerFPPS())); connect(scheduler->RR__button,SIGNAL(clicked()),control,SLOT(setSchedulerRR())); connect(scheduler->MLFQ_button,SIGNAL(clicked()),control,SLOT(setSchedulerMLFQ())); connect(scheduler->LS_button,SIGNAL(clicked()),control,SLOT(setSchedulerLS())); connect(scheduler->NONE_button,SIGNAL(clicked()),control,SLOT(setSchedulerNOTSET())); connect(quantumWindow->Accept_button, SIGNAL(clicked()),this,SLOT(setQuantum())); connect(ticketWindow->Accept_button, SIGNAL(clicked()),this,SLOT(setTickets())); connect(scheduler->RR__button,SIGNAL(clicked()),quantumWindow,SLOT(show())); connect(scheduler->MLFQ_button,SIGNAL(clicked()),quantumWindow,SLOT(show())); connect(scheduler->LS_button,SIGNAL(clicked()),ticketWindow,SLOT(show())); connect(quantumWindow->Accept_button, SIGNAL(clicked()),quantumWindow,SLOT(hide())); connect(ticketWindow->Accept_button, SIGNAL(clicked()),ticketWindow,SLOT(hide())); connect(ui->Run_button,SIGNAL(clicked()),this,SLOT(run())); qDebug()<<"end of pcbWindow constructor"; } pcbWindow::~pcbWindow() { delete ui; //delete createButton; //delete deleteButton; //delete blockButton; //delete unblockButton; delete suspendButton; delete resumeButton; delete priorityButton; delete pcbShowButton; delete nameLEdit; delete classLEdit; delete prioritySBox; delete quitButton; delete timeRemainingSBox; delete readFileButton; delete showBlockedButton; delete showReadyButton; delete fileNameLEdit; delete reqMemSBox; } void pcbWindow::run() { qDebug()<<"made it inside pcbwindow::run"; if((control->currentScheduler==RR || control->currentScheduler==MLFQ) && control->quantum>0) { qDebug()<<"inside first if statement"; while(control->readyList.listLength()>0 || control->blockedList.listLength()>0) { qDebug()<<"another step executed"; control->step(); } } if(control->currentScheduler!=MLFQ || control->currentScheduler!=RR) { qDebug()<<"inside second if statement"; while(control->readyList.firstNode!=NULL || control->blockedList.firstNode!=NULL) { qDebug()<<"another step executed"; control->step(); } } } void pcbWindow::setQuantum() { control->quantum = quantumWindow->Quantum_SpinBox->value(); qDebug()<<control->quantum; } void pcbWindow::setTickets() { control->tickets = ticketWindow->Ticket_SpinBox->value(); qDebug()<<control->tickets; } void pcbWindow::showPCBList() { showWindow.updateDisplay(control->findPCB(nameLEdit->text())); showWindow.show(); } void pcbWindow::createPCB() { if(control->findPCB(nameLEdit->text())==NULL) { if(classLEdit->text().toStdString()=="APPLICATION" || classLEdit->text().toStdString()=="SYSTEM") { control->insertPCB(control->setupPCB(nameLEdit->text(),classLEdit->text(),prioritySBox->value(), reqMemLEdit->text().toInt(),timeRemainingSBox->value(),0,1)); } } } bool pcbWindow::deletePCB() { PCB* toDelete; toDelete = control->findPCB(nameLEdit->text()); if(toDelete !=NULL) { control->removePCB(toDelete); control->freePCB(toDelete); return true; } return false; } bool pcbWindow::block() { PCB* toBlock; toBlock = control->findPCB(nameLEdit->text()); if(toBlock!=NULL) { if(toBlock->getState()==READY || toBlock->getState()==SUSPENDEDREADY) { qDebug()<<toBlock->getState(); control->removePCB(toBlock); if(toBlock->getState()==READY) { qDebug()<<"attempting block"; toBlock->setState(BLOCKED); qDebug()<<"now blocked"; } if(toBlock->getState()==SUSPENDEDREADY) { toBlock->setState(SUSPENDEDBLOCKED); } control->insertPCB(toBlock); return true; } return false; } return false; } bool pcbWindow::unblock() { PCB* toUnblock; toUnblock = control->findPCB(nameLEdit->text()); if(toUnblock != NULL) { if(toUnblock->getState()==BLOCKED || toUnblock->getState()==SUSPENDEDBLOCKED) { control->removePCB(toUnblock); if(toUnblock->getState()==BLOCKED) { toUnblock->setState(READY); } if(toUnblock->getState()==SUSPENDEDBLOCKED) { toUnblock->setState(SUSPENDEDREADY); } control->insertPCB(toUnblock); return true; } return false; } return false; } bool pcbWindow::suspend() { PCB* toSuspend; toSuspend = control->findPCB(nameLEdit->text()); if(toSuspend!=NULL) { if(toSuspend->getState()==READY) { toSuspend->setState(SUSPENDEDREADY); return true; } if(toSuspend->getState()==BLOCKED) { toSuspend->setState(SUSPENDEDBLOCKED); return true; } return false; } return false; } bool pcbWindow::resume() { PCB* toResume; toResume = control->findPCB(nameLEdit->text()); if(toResume!=NULL) { if(toResume->getState()==SUSPENDEDREADY) { toResume->setState(READY); return true; } if(toResume->getState()==SUSPENDEDBLOCKED) { toResume->setState(BLOCKED); return true; } return false; } return false; } bool pcbWindow::setPriority() { PCB* toChange; toChange = control->findPCB(nameLEdit->text()); if(toChange!=NULL) { toChange->setPriority(prioritySBox->value()); return true; } return false; } void pcbWindow::showBlockedPCB() { showWindow.updateDisplay(control->blockedList.firstNode); showWindow.show(); } void pcbWindow::showReadyPCB() { showWindow.updateDisplay(control->readyList.firstNode); showWindow.show(); } void pcbWindow::readFile() { if (fileNameLEdit->text()!="") { qDebug()<<fileNameLEdit->text(); control->readFile(fileNameLEdit->text()); } } void pcbWindow::showSchedulers() { scheduler->show(); }
#include "Merchant.h" Merchant::Merchant() { //ctor } Merchant::~Merchant() { //dtor } Merchant::Merchant(const Merchant& other) { for(unsigned int i=0; i < other.merchandises.size(); i++) { add(other.merchandises[i]); } } Merchant& Merchant::operator=(const Merchant& rhs) { if (this == &rhs) return *this; // handle self assignment for(unsigned int i=0; i < merchandises.size(); i++) { merchandises.pop_back(); } merchandises.clear(); for(unsigned int i=0; i < rhs.merchandises.size(); i++) { merchandises.push_back(rhs.merchandises[i]); } return *this; } void Merchant::add(Weapon* w) { for(unsigned int i=0; i < merchandises.size(); i++) { if(w == merchandises[i]) { return; } } merchandises.push_back(w); } void Merchant::remove(Weapon* w) { for(unsigned int i=0; i< merchandises.size(); i++) { if(w == merchandises[i]) { merchandises.erase(merchandises.begin()+i); return; } } } string Merchant::str()const { stringstream result; for(unsigned int i=0 ; i < merchandises.size(); i++) { result << merchandises[i]->getName() << " " << merchandises[i]->getWorth() << endl; } return result.str(); }
/* * Copyright (c) 2016 Morwenn * SPDX-License-Identifier: MIT */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef CPPSORT_DETAIL_PARTITION_H_ #define CPPSORT_DETAIL_PARTITION_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <iterator> #include <type_traits> #include <utility> #include <cpp-sort/utility/iter_move.h> #include "iterator_traits.h" namespace cppsort { namespace detail { template<typename Predicate, typename ForwardIterator> auto partition_impl(ForwardIterator first, ForwardIterator last, Predicate pred, std::forward_iterator_tag) -> ForwardIterator { while (true) { if (first == last) return first; if (!pred(*first)) break; ++first; } for (ForwardIterator p = first; ++p != last;) { if (pred(*p)) { using utility::iter_swap; iter_swap(first, p); ++first; } } return first; } template<typename Predicate, typename BidirectionalIterator> auto partition_impl(BidirectionalIterator first, BidirectionalIterator last, Predicate pred, std::bidirectional_iterator_tag) -> BidirectionalIterator { while (true) { while (true) { if (first == last) return first; if (!pred(*first)) break; ++first; } do { if (first == --last) return first; } while (!pred(*last)); using utility::iter_swap; iter_swap(first, last); ++first; } } template<typename ForwardIterator, typename Predicate> auto partition(ForwardIterator first, ForwardIterator last, Predicate pred) -> ForwardIterator { return partition_impl<std::add_lvalue_reference_t<Predicate>>( std::move(first), std::move(last), pred, iterator_category_t<ForwardIterator>{} ); } }} #endif // CPPSORT_DETAIL_PARTITION_H_
/*Source: Combining Fuzzy Information: An Overview. Ronald Fagin. A Survey of Top-k Query Processing Techniques in Relational Database Systems. Ilyas, Beskales and Soliman. http://alumni.cs.ucr.edu/~skulhari/Top-k-Query.pdf */ /* * Threshold Algorithm 1. Access the elements sequentially and at each sequential access (Step 1) (a) Set the threshold t to be the aggregate of the scores seen in this access. (b) Do random accesses and compute the scores of the seen objects. (c) Maintain a list of top-k objects seen so far (d) Stop, when the scores of the top-k are greater or equal to the threshold. 2. Return the top-k seen so far (Step 2) * */ #include "utility.h" #include "TA.h" #include <iostream> #include <algorithm> #include <vector> #include <map> #include <iterator> #include <deque> #include <numeric> using namespace std; inline bool sortinrev(const TA::TS &a,const TA::TS &b){ return ((a.score > b.score) ||(a.score == b.score && a.d<b.d)); } void TA::removeC(int k) { sort(C.begin(),C.end(),sortinrev); while((int)C.size()>k){ C.erase(C.end()-1); } } double TA::calculScore(TF pl,vector<vector<TF>> &tab){ double sum = 0.0; for ( const auto &row : tab ){ for ( const auto &s : row ){ if(s.d==pl.d){ sum += s.frequency; } } } return sum/tab.size(); } void TA::InsertC(TF pl, vector<vector<TF>> &tab) { bool flag=true; for(TS itPL:C){ if(itPL.d==pl.d){ flag=false; } } if(flag){ TS TS={pl.d,calculScore(pl,tab)}; C.push_back(TS); } } void TA::display_vector(const vector<int> &v){ if (outputOnlyJSON) return; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout<<std::endl; } void TA::displayC(){ if (outputOnlyJSON) return; for(int i=0;i<(int)C.size();i++){ std::cout<<C.at(i).d<<" "<<C.at(i).score<<"; "; } std::cout<<std::endl; } void TA::displayTab(vector<vector<TF>> &tab){ if (outputOnlyJSON) return; for(vector<TF> vpl: tab){ for(TF pl: vpl){ std::cout<<pl.d<<" "<<pl.frequency<<"; "; } } std::cout<<std::endl; } bool TA::kDocT(int k){ int i=0; for(TS TS: C){ if(TS.score>=t){ i++; } if (i>=k) return false; } return true; } void TA::sortedAccess(int row,vector<vector<TF>> &tab){ t=0; for(vector<TF> vpl:tab){ t=t+vpl.at(row).frequency; } t=t/tab.size(); } void TA::step1(unsigned int k,vector<vector<TF>> &tab){ int row=0; if (k>tab.at(0).size()){ for (TF tf1:tab.at(0)){ C.push_back({tf1.d,calculScore(tf1,tab)}); } } else{ while(kDocT(k)){ TF pl; sortedAccess(row,tab); for (vector<TF> qt: tab){ pl=qt.at(row); InsertC(pl,tab); } removeC(k); row++; } } } void TA::step2(unsigned int k){ result.clear(); sort(C.begin(), C.end(), sortinrev); for(unsigned int i=0;i<k;i++){ if(i<C.size()){ result.push_back(C.at(i)); } } C.clear(); C=result; } vector<TA::TS> TA::TAlgo(int k,vector<vector<TF>> &tab){ step1(k,tab); step2(k); //return result; return C; }
#include <vector> //二分查找(循环) bool binary_search(std::vector<int> &sort_array, int target){ int begin=0; int end=sort_array.size()-1; while(begin<end){ int mid=(begin+end)/2; if(target==sort_array[mid]) return true; else if(target<sort_array[mid]) end=mid-1; else if(target>sort_array[mid]) begin=mid+1; } return false; } //二分查找(递归) bool binary_search(std::vector<int> &sort_array, int begin ,int end,int target){ if(begin > end) return false; int mid=(begin+end)/2; if(target ==sort_array[mid]) return true; else if(target<sort_array[mid]) return binary_search(sort_array, begin, mid-1, target); else if(target>sort_array[mid]) return binary_search(sort_array, mid+1, end, target); }
// // Created by peachy_ash on 15.09.2021. // #include "../lib/folium_of_Descartes.hpp" #include "gtest/gtest.h" using namespace fancyCurve; TEST(Constructors, DefaultConstructor){ foliumOfDescartes f; ASSERT_EQ(1, f.get_n()); } TEST(Constructors, InitConstructor){ foliumOfDescartes f (3); ASSERT_EQ(3, f.get_n()); } TEST(Constructors, TestException){ ASSERT_ANY_THROW(foliumOfDescartes f (-1)); } TEST(Methods, Setter){ foliumOfDescartes f; f.set_n(3); ASSERT_EQ(3, f.get_n()); } TEST(Methods, SetterException){ foliumOfDescartes f; ASSERT_ANY_THROW(f.set_n(-1)); } TEST(Methods, Side){ foliumOfDescartes f (sqrt(2)); ASSERT_DOUBLE_EQ(1, f.getSide()); } TEST(Methods, distanceToCenter){ foliumOfDescartes f; double angle = M_PI; ASSERT_NEAR(0, f.distanceToCenter(angle), 0.000001); } TEST(Methods, distanceToCenterException1){ foliumOfDescartes f; double angle = 7; ASSERT_ANY_THROW(f.distanceToCenter(angle)); } TEST(Methods, distanceToCenterException2){ foliumOfDescartes f; double angle = 7 * M_PI / 4; ASSERT_ANY_THROW(f.distanceToCenter(angle)); } TEST(Methods, topRadius){ foliumOfDescartes f; ASSERT_NEAR(0.0883883, f.topRadius(), 0.0000001); } TEST(Methods, nodeRadius){ foliumOfDescartes f; ASSERT_DOUBLE_EQ(0.5, f.nodeRadius()); } TEST(Methods, square){ foliumOfDescartes f; ASSERT_NEAR(0.166666667, f.squareOfLoop(), 0.0000001); } TEST(Methods, diameter){ foliumOfDescartes f; ASSERT_NEAR(0.321144348, f.diameterOfLoop(), 0.0000001); } TEST(Methods, distanceToDiameter){ foliumOfDescartes f; ASSERT_NEAR(0.40824829, f.distanceToDiameter(), 0.0000001); } int main(int argc, char* argv[]){ ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
$NetBSD$ * put inclusion of asiolonk first so that map from net/if.h on illumos won't confict with std::map --- src/bin/dhcp6/tests/parser_unittest.cc.orig 2020-01-02 23:01:48.000000000 +0000 +++ src/bin/dhcp6/tests/parser_unittest.cc @@ -6,9 +6,9 @@ #include <config.h> +#include <dhcpsrv/parsers/simple_parser6.h> #include <gtest/gtest.h> #include <dhcp6/parser_context.h> -#include <dhcpsrv/parsers/simple_parser6.h> #include <testutils/io_utils.h> #include <testutils/user_context_utils.h>
// // Created by cirkul on 27.11.2020. // #include "Lion.h" Animal *Lion::spawn(Playground &pg, int i, int j) { Lion *newAnimal = new Lion(pg, i, j); ++newAnimal->home->creatureCount; newAnimal->pg->newCreatures[newAnimal] = 1; newAnimal->pg->allAnimals.push_back(newAnimal); newAnimal->home->animals.push_back(newAnimal); return newAnimal; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2004 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef CSS_PROPERTY_LIST_H #define CSS_PROPERTY_LIST_H class TempBuffer; #include "modules/util/simset.h" class CSS_decl; class CSS_property_list { OP_ALLOC_ACCOUNTED_POOLING OP_ALLOC_ACCOUNTED_POOLING_SMO_DOCUMENT public: /** Flags describing certain features of a declaration block. The features for a CSS_property_list is a union of these flags. */ enum Flag { /** No flags set. */ HAS_NONE = 0, /** Property list has a content property. */ HAS_CONTENT = 1, /** Property list has a property that takes url() values. */ HAS_URL_PROPERTY = 2, /** Property list has a property that will enable CSS transitions. */ HAS_TRANSITIONS = 4, /** Property list has a property that will enable CSS animations. */ HAS_ANIMATIONS = 8, }; CSS_property_list() : ref_count(0) { } ~CSS_property_list(); void Ref() { ref_count++; } void Unref() { OP_ASSERT(ref_count > 0); if (--ref_count == 0) OP_DELETE(this); } CSS_decl* GetFirstDecl() { return (CSS_decl*)decl_list.First(); } CSS_decl* GetLastDecl() { return (CSS_decl*)decl_list.Last(); } unsigned GetLength() { return decl_list.Cardinal(); } BOOL IsEmpty() { return decl_list.Empty(); } void AddDecl(CSS_decl* decl, BOOL important, CSS_decl::DeclarationOrigin origin); /** Find and a replace the last occurrence of a declaration. This function looks for a declaration with the same property as the incoming declaration, searching last to first. If one is found, that declaration is removed, and replaced with the incoming declaration. If no matching declaration is found, the declaration is added to the end of the list. @param decl The declaration to find and replace. @param important TRUE if 'decl' is "!important", FALSE otherwise. @param origin The origin of the declaration. @see CSS_decl::DeclarationOrigin */ void ReplaceDecl(CSS_decl* decl, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, const uni_char* value, int value_len, BOOL important, CSS_decl::DeclarationOrigin origin, CSS_string_decl::StringType type, BOOL source_local); void AddDeclL(int property, uni_char* value, BOOL important, CSS_decl::DeclarationOrigin origin, CSS_string_decl::StringType type, BOOL source_local); void AddDeclL(int property, short* val_array, int val_array_len, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, CSS_generic_value* val_array, int val_array_len, int layer_count, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, const CSS_generic_value_list& val_list, int layer_count, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, float val, int val_type, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, float val1, float val2, int val1_type, int val2_type, BOOL important, CSS_decl::DeclarationOrigin origin); void AddDeclL(int property, short types[4], float values[4], BOOL important, CSS_decl::DeclarationOrigin origin); void AddLongDeclL(int property, long value, BOOL important, CSS_decl::DeclarationOrigin origin); void AddColorDeclL(int property, COLORREF value, BOOL important, CSS_decl::DeclarationOrigin origin); void AddTypeDeclL(int property, CSSValue value, BOOL important, CSS_decl::DeclarationOrigin origin); CSS_decl* RemoveDecl(int property); /** Post-process the property list after declarations have been added/removed. The actual processing done is decided by the parameters. @param delete_duplicates Remove and delete declarations that are overridden by other declarations in the same property list. @param get_flags Calculate the set of Flag values for this property list. @return The set of Flag values if get_flags is TRUE. */ unsigned int PostProcess(BOOL delete_duplicates, BOOL get_flags); BOOL AddList(CSS_property_list* list, BOOL force_important=FALSE); CSS_property_list* GetCopyL(); void AppendPropertiesAsStringL(TempBuffer* tmp_buf); #ifdef STYLE_PROPNAMEANDVALUE_API /** Appends the property name of declaration idx to name, and the property value of declaration idx to value, and sets the important flag. @param idx Index of the declaration to get the name and value for. First declaration has index 0. @param name TempBuffer that the property name of the declaration will be appended to. @param value TempBuffer the the property value of the declaration will be appended to. @param important Set to TRUE by this method if the declaration is !important, otherwise set to FALSE. @return OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetPropertyNameAndValue(unsigned int idx, TempBuffer* name, TempBuffer* value, BOOL& important); #endif // STYLE_PROPNAMEANDVALUE_API private: /** Return the property flags for a given declaration. @param decl The declaration to get the flags for. @return A union of flags from the Flag enum */ static unsigned int GetPropertyFlags(CSS_decl* decl); /** Linked list of CSS_decl objects */ Head decl_list; /** Reference count */ int ref_count; }; #endif // CSS_PROPERTY_LIST_H
// // Created by drunkgranny on 13.04.16. // #include <iostream> using namespace std; void thePowerOfThor() { int lightX; // the X position of the light of power int lightY; // the Y position of the light of power int initialTX; // Thor's starting X position int initialTY; // Thor's starting Y position cin >> lightX >> lightY >> initialTX >> initialTY; cin.ignore(); int thorX = initialTX; int thorY = initialTY; // game loop while (1) { int remainingTurns; cin >> remainingTurns; cin.ignore(); string direction = ""; if (thorY > lightY) { direction += "N"; thorY--; } else if (thorY < lightY) { direction += "S"; thorY++; } if (thorX > lightX) { direction += "W"; thorX--; } else if (thorX < lightX) { direction += "E"; thorX++; } //std::string result = std::string(directionY) + std::string(directionX); //cout « directionY « directionX « endl; cout << direction << endl; } }
///**************************************************************************** // * * // * Author : lukasz.iwaszkiewicz@gmail.com * // * ~~~~~~~~ * // * License : see COPYING file for details. * // * ~~~~~~~~~ * // ****************************************************************************/ // //#ifdef ANDROID //#ifndef RESOURCEMANAGER_H_ //#define RESOURCEMANAGER_H_ // //#include <Pointer.h> //#include "resource/IResourceManager.h" // //struct AAssetManager; // //namespace View { // ///** // * // */ //class ResourceManager : public IResourceManager { //public: // // ResourceManager (AAssetManager *a) : assetManager (a) {} // virtual ~ResourceManager () {} // // Ptr <std::string> getText (std::string const &id) const; // //private: // // AAssetManager *assetManager; // //}; // //} /* namespace View */ // //#endif /* RESOURCEMANAGER_H_ */ //#endif
#include<bits/stdc++.h> using namespace std; map<int,int> mp; int main() { int n; int cnt=0; int t=0; scanf("%d",&n); for(int i=0; i<n; i++) { int a; scanf("%d",&a); if(i+1==a) { cnt++; } else mp[a]++; } map<int,int>::iterator it; for(it=mp.begin(); it!=mp.end(); it++) { if(it->second>=1) { t++; } } cnt+=t/2; printf("%d",cnt); return 0; }
#include "windows.h" #include "NuiApi.h" #include <string> namespace NuiErrorsStringInterface { std::string NuiFusionDepthToDepthFloatFrameError(HRESULT hr); }
#include "ImageManager.h" //------------------------------------------------- //コンストラクタ・デストラクタ ImageManager::ImageManager( ) { LoadResource( ); } ImageManager::~ImageManager( ) { } //------------------------------------------------- //------------------------------------------------- //------------------------------------------------- //ゲッター int ImageManager::GetResourceHandle( ResourceData name ) { return _resourceHandle[ name ]; } //------------------------------------------------- //------------------------------------------------- //------------------------------------------------- //--セッター //------------------------------------------------- //------------------------------------------------- //--画像データを読み込む関数 void ImageManager::LoadResource( ) { _resourceHandle[ GAME_OVER_IMAGE ] = LoadGraph( "Resource/gameover.png" ); _resourceHandle[ HIKARI_IMAGE ] = LoadGraph( "Resource/hikari.png" ); _resourceHandle[ GAME_CLEAR_TEXT ] = LoadGraph( "Resource/GAME-CLEAR-.png" ); _resourceHandle[ AKA_IMAGE ] = LoadGraph( "Resource/aka.png" ); _resourceHandle[ CURSOR_IMAGE ] = LoadGraph( "Resource/cursor.png" ); _resourceHandle[ GAME_OVER_TEXT ] = LoadGraph( "Resource/GAME-OVER-.png" ); _resourceHandle[ PUSH_BUTTON_TEXT ] = LoadGraph( "Resource/PUSH-BUTTON.png" ); _resourceHandle[ YAMIOTO_TEXT ] = LoadGraph( "Resource/yamioto.png" ); }
/* Prac9 Q2 - histogram by Alan Agon a1636896 */ #include <iostream> #include <malloc.h> using namespace std; void histPrint(int bins[], int nrBins); int* histGen(double data[], int nrPts, double lo, double hi, int nrBins); int main() { cout << "histPrint and histGen outputs: " << endl; double data[]={4.1, 1.5, 4.5, 8.3, 10, 11.4,13.1, 20}; histPrint(histGen(data, 8, 1.5, 20, 5),5); cout << endl; return 0; } void histPrint(int bins[], int nrBins){ for( int i=0; i<nrBins; i++ ){ for( int j=0; j<bins[i]; j++ ){ cout << "#"; } cout << endl; } } int* histGen(double data[], int nrPts, double lo, double hi, int nrBins){ int* bins=(int *)malloc(nrBins*sizeof(int)); int delta=(hi-lo)/nrBins+1; for( int i=0; i<nrPts; i++ ){ if( data[i] > hi || data[i] < lo ){break;} int binIndex = data[i]/delta; if( binIndex*delta == data[i] ){ bins[binIndex-1]++; } bins[binIndex]++; } return bins; }
#include "Common.h" #include "ARP.h" class Device { private: pcap_if_t* alldevs; pcap_if_t* d; pcap_t* adhandle; public: int obtainDeviceList(); int openAdapter(const char* nam); int setFilter(const char* packet_filter); void sendPacket(const BYTE* packet); pcap_t* getHandle() const; };
#pragma once #include "AAModel.h" class MyCube : public AAModel { public: MyCube(char * name); ~MyCube(); void update(); private: AAModel* front_left_wheel; AAModel* front_right_wheel; AAModel* rear_left_wheel; AAModel* rear_right_wheel; };
enum class Orientacion:int{ NORTE=0, SUR=1, ESTE=2, OESTE=3 };
// -*- C++ -*- // // Package: L1Trigger/L1TCaloLayer1Spy // Class: L1TCaloLayer1Spy // /**\class L1TCaloLayer1Spy L1TCaloLayer1Spy.cc L1Trigger/L1TCaloLayer1Spy/plugins/L1TCaloLayer1Spy.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Sridhara Rao Dasu // Created: Fri, 09 Oct 2015 10:22:41 GMT // // // system include files #include <memory> #include <stdexcept> #include <stdio.h> #include <iostream> #include <string> #include <vector> // CTP7 TCP/IP Client #include <UCT2016Layer1.hh> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EcalDigi/interface/EcalTriggerPrimitiveDigi.h" #include "DataFormats/EcalDigi/interface/EcalTriggerPrimitiveSample.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" #include "DataFormats/HcalDigi/interface/HcalTriggerPrimitiveDigi.h" #include "DataFormats/HcalDigi/interface/HcalTriggerPrimitiveSample.h" #include "DataFormats/HcalDetId/interface/HcalTrigTowerDetId.h" #include "DataFormats/L1TCalorimeter/interface/CaloTower.h" using namespace l1t; // // class declaration // class L1TCaloLayer1Spy : public edm::one::EDProducer<> { public: explicit L1TCaloLayer1Spy(const edm::ParameterSet&); ~L1TCaloLayer1Spy(); static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: virtual void beginJob() override; virtual void produce(edm::Event&, const edm::EventSetup&) override; virtual void endJob() override; //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; // ----------member data --------------------------- std::string setupString; uint32_t selectedBXNumber; bool verbose; uint32_t eventNumber; std::unique_ptr<UCT2016Layer1> layer1; std::vector< std::vector< std::vector< uint32_t> > > negativeEtaInputData; std::vector< std::vector< std::vector< uint32_t> > > positiveEtaInputData; std::vector< std::vector< std::vector< uint32_t> > > negativeEtaOutputData; std::vector< std::vector< std::vector< uint32_t> > > positiveEtaOutputData; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // L1TCaloLayer1Spy::L1TCaloLayer1Spy(const edm::ParameterSet& iConfig) : setupString(iConfig.getUntrackedParameter<std::string>("setupString")), selectedBXNumber(iConfig.getUntrackedParameter<uint32_t>("SelectedBXNumber")), verbose(iConfig.getUntrackedParameter<bool>("verbose")), eventNumber(0), layer1(new UCT2016Layer1(setupString)), negativeEtaInputData(nLayer1Cards, std::vector< std::vector<uint32_t> >(nInputLinks, std::vector<uint32_t>(nInputWordsPerCapturePerLink))), positiveEtaInputData(nLayer1Cards, std::vector< std::vector<uint32_t> >(nInputLinks, std::vector<uint32_t>(nInputWordsPerCapturePerLink))), negativeEtaOutputData(nLayer1Cards, std::vector< std::vector<uint32_t> >(nTMTLinks, std::vector<uint32_t>(nOutputWordsPerCapturePerLink))), positiveEtaOutputData(nLayer1Cards, std::vector< std::vector<uint32_t> >(nTMTLinks, std::vector<uint32_t>(nOutputWordsPerCapturePerLink))) { produces<HcalTrigPrimDigiCollection>(); produces<EcalTrigPrimDigiCollection>(); produces<CaloTowerBxCollection>(); } L1TCaloLayer1Spy::~L1TCaloLayer1Spy() { } // // member functions // // ------------ method called to produce the data ------------ void L1TCaloLayer1Spy::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { static std::string theRunConfiguration; using namespace edm; std::unique_ptr<EcalTrigPrimDigiCollection> ecalTPGs(new EcalTrigPrimDigiCollection); std::unique_ptr<HcalTrigPrimDigiCollection> hcalTPGs(new HcalTrigPrimDigiCollection); std::unique_ptr<CaloTowerBxCollection> towersColl (new CaloTowerBxCollection); // Determine if we need to take action getting data from layer1, and if so do! if((eventNumber % nInputEventsPerCapture) == 0) { std::cout << "Calling getRunMode() " << std::endl; std::cout.flush(); // Skip processing if layer-1 is in inappropriate mode // getRunMode also verifies that the mode is useable for captures UCT2016Layer1CTP7::RunMode mode; if(!layer1->getRunMode(mode)) { std::cerr << "L1TCaloLayer1Spy: Inappropriate mode set for Layer-1; Set mode = " << mode << std::endl; return; } // Get configuration for record // getConfiguration ensures that the entire layer-1 system is in same configuration std::cout << "Calling getConfiguration() " << std::endl; std::cout.flush(); std::string configuration; if(!layer1->getConfiguration(configuration)) { std::cerr << "L1TCaloLayer1Spy: Could not read configuration from CTP7 " << std::endl; return; } if(theRunConfiguration == "") theRunConfiguration = configuration; if(configuration != theRunConfiguration) { std::cerr << "L1TCaloLayer1Spy: Layer1 configuration changed midstream; Will stop processing from now on" << "; configuration = " << configuration << " != " << theRunConfiguration << std::endl; return; } std::cout << "getNextCapture() " << std::endl; std::cout.flush(); UCT2016Layer1CTP7::CaptureMode captureMode; UCT2016Layer1CTP7::CaptureStatus captureStatus; uint32_t nCaptured = layer1->getNextCapture(captureMode, selectedBXNumber, captureStatus, negativeEtaInputData, positiveEtaInputData, negativeEtaOutputData, positiveEtaOutputData); if(nCaptured != nInputEventsPerCapture) { std::cerr << "L1TCaloLayer1Spy: Layer1 could not make a capture" << std::endl; return; } } // Trigger system processes one BX per "event", and the // users of this products should expect the hit BX data only. // Use data for the event from the layer1 buffers incrementing // to pick the next BX int theBX = 0; // Produce input data // Loop over all cards for(uint32_t cardPhi = 0; cardPhi < 18; cardPhi++) { // Loop over both sides for(int cardSide = -1; cardSide <= 1; cardSide+=2) { uint32_t offset = (eventNumber % nInputEventsPerCapture) * 4; // Loop over all input links for(uint32_t link = 0; link < 14; link++) { // Each event eats four words of input buffers uint32_t *ecalLinkData = 0; uint32_t *hcalLinkData = 0; if(cardSide == 1) { ecalLinkData = &(positiveEtaInputData[cardPhi][2*link].data())[offset]; hcalLinkData = &(positiveEtaInputData[cardPhi][2*link+1].data())[offset]; } else { ecalLinkData = &(negativeEtaInputData[cardPhi][2*link].data())[offset]; hcalLinkData = &(negativeEtaInputData[cardPhi][2*link+1].data())[offset]; } // Bottom eight bits of the third word contain ECAL finegrain feature bits // Store them for later access in the loop uint8_t ecalFBits = (ecalLinkData[2] & 0xFF); // The third 32-bit word + bottom 16 bits of the fourth word make up // 6-bit feature word for each of the eight towers. They are stitched // together in a 64-bit word here to be pealed of as needed later in loops uint64_t hcalFBits = hcalLinkData[2]; hcalFBits |= (((uint64_t) (hcalLinkData[3] & 0xFFFF)) << 32); // Process all Eta in a link for(uint32_t dEta = 0; dEta < 2; dEta++) { uint32_t ecalDataWord = ecalLinkData[dEta]; uint32_t hcalDataWord = hcalLinkData[dEta]; // Process all Phi in a link for(uint32_t dPhi = 0; dPhi < 4; dPhi++) { // Determine tower data and location in (caloEta, caloPhi) int absCaloEta = link*2 + dEta + 1; int caloEta = cardSide * absCaloEta; int caloPhi = cardPhi * 4 + dPhi - 1; if(caloPhi <= 0)caloPhi += 72; // Make ECALTriggerPrimitive uint32_t em = (ecalDataWord >> (dPhi * 8)) & (0xFF); bool efb = ((ecalFBits & (0x1 << (dEta * 4 + dPhi))) != 0); uint16_t towerDatum = em; if(efb) towerDatum |= 0x0100; EcalTriggerPrimitiveSample sample(towerDatum); EcalSubdetector ecalTriggerTower = EcalSubdetector::EcalTriggerTower; EcalTrigTowerDetId id(cardSide, ecalTriggerTower, absCaloEta, caloPhi); EcalTriggerPrimitiveDigi etpg(id); etpg.setSize(1); etpg.setSample(0, sample); ecalTPGs->push_back(etpg); // Make HCALTriggerPrimitive uint32_t hd = (hcalDataWord >> (dPhi * 8)) & (0xFF); uint8_t hfb = (hcalFBits >> (dEta * 4 + dPhi)*6) & 0x3F; towerDatum = (hd + (hfb << 8)); HcalTriggerPrimitiveSample hSample(towerDatum); HcalTrigTowerDetId hid(caloEta, caloPhi); HcalTriggerPrimitiveDigi htpg(hid); htpg.setSize(1); htpg.setSample(0, hSample); hcalTPGs->push_back(htpg); } } } // HF Data for(uint32_t abPhi=0; abPhi<2; ++abPhi) { uint32_t *hfData; if(cardSide == 1) { hfData = &(positiveEtaInputData[cardPhi][28+abPhi].data())[offset]; } else { hfData = &(negativeEtaInputData[cardPhi][28+abPhi].data())[offset]; } for(uint32_t hfEta=0; hfEta<12; ++hfEta) { if ( abPhi == 0 && hfEta == 11 ) continue; if ( abPhi == 1 && hfEta == 10 ) continue; size_t word = hfEta/4; size_t shift = 8 * (hfEta%4); if ( hfEta > 10 ) shift = 16; uint32_t et = (hfData[word]>>shift) & 0xff; int iEta = cardSide * (hfEta+30); int iPhi = 1 + cardPhi*4 + abPhi*2; if(std::abs(iEta) == 41) iPhi -= 2; // Last two HF are 3, 7, 11, ... iPhi = (iPhi+69)%72 + 1; // iPhi -= 2 mod 72 std::cout << iEta << ", " << iPhi << ", " << et << std::endl; HcalTriggerPrimitiveSample sample(et); HcalTrigTowerDetId id(iEta, iPhi); id.setVersion(1); // To not process these 1x1 HF TPGs with RCT HcalTriggerPrimitiveDigi tpg(id); tpg.setSize(1); tpg.setSample(0, sample); hcalTPGs->push_back(tpg); } } // Output data // Make caloTower collection just for Barrel and Endcap for the moment uint32_t nHeader = 1; uint32_t nBEDataWords = 28; for(uint32_t tEta = 0; tEta < nBEDataWords; tEta++) { for(uint32_t dPhi = 0; dPhi < 4; dPhi++) { uint32_t outputLink = (eventNumber % nTMTCards)*2 + (dPhi/2); // uint32_t offset = ((eventNumber % nOutputEventsPerCapturePerLinkPair) / nTMTCards) * nOutputEventWords + nHeader + tEta; uint32_t offset = (eventNumber/nTMTCards) * nOutputEventWords + nHeader + tEta; uint16_t dataWord; if(cardSide == -1) { dataWord = (((negativeEtaOutputData[cardPhi][outputLink].data())[offset]) >> ((dPhi%2) * 16)) & 0xFFFF; } else { dataWord = (((positiveEtaOutputData[cardPhi][outputLink].data())[offset]) >> ((dPhi%2) * 16)) & 0xFFFF; } CaloTower caloTower; caloTower.setHwPt(dataWord & 0x1FF); // Bits 0-8 of the 16-bit word per the interface protocol document caloTower.setHwEtRatio((dataWord >> 9) & 0x7); // Bits 9-11 of the 16-bit word per the interface protocol document caloTower.setHwQual((dataWord >> 12) & 0xF); // Bits 12-15 of the 16-bit word per the interface protocol document // Determine tower data and location in (caloEta, caloPhi) int absCaloEta = tEta + 1; int caloEta = cardSide * absCaloEta; int caloPhi = cardPhi * 4 + dPhi - 1; if(caloPhi <= 0)caloPhi += 72; caloTower.setHwEta(caloEta); caloTower.setHwPhi(caloPhi); // Push the tower in towersColl->push_back(theBX, caloTower); } } } } iEvent.put(std::move(ecalTPGs)); iEvent.put(std::move(hcalTPGs)); iEvent.put(std::move(towersColl)); eventNumber++; } // ------------ method called once each job just before starting event loop ------------ void L1TCaloLayer1Spy::beginJob() { } // ------------ method called once each job just after ending the event loop ------------ void L1TCaloLayer1Spy::endJob() { } // ------------ method called when starting to processes a run ------------ /* void L1TCaloLayer1Spy::beginRun(edm::Run const&, edm::EventSetup const&) { } */ // ------------ method called when ending the processing of a run ------------ /* void L1TCaloLayer1Spy::endRun(edm::Run const&, edm::EventSetup const&) { } */ // ------------ method called when starting to processes a luminosity block ------------ /* void L1TCaloLayer1Spy::beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) { } */ // ------------ method called when ending the processing of a luminosity block ------------ /* void L1TCaloLayer1Spy::endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) { } */ // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void L1TCaloLayer1Spy::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } //define this as a plug-in DEFINE_FWK_MODULE(L1TCaloLayer1Spy);
// Created on: 1998-05-12 // Created by: Philippe NOUAILLE // Copyright (c) 1998-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 _BRepBlend_AppFuncRstRst_HeaderFile #define _BRepBlend_AppFuncRstRst_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <BRepBlend_AppFuncRoot.hxx> #include <math_Vector.hxx> class BRepBlend_Line; class Blend_RstRstFunction; class Blend_AppFunction; class Blend_Point; class BRepBlend_AppFuncRstRst; DEFINE_STANDARD_HANDLE(BRepBlend_AppFuncRstRst, BRepBlend_AppFuncRoot) //! Function to approximate by AppSurface for Edge/Face (Curve/Curve contact). class BRepBlend_AppFuncRstRst : public BRepBlend_AppFuncRoot { public: Standard_EXPORT BRepBlend_AppFuncRstRst(Handle(BRepBlend_Line)& Line, Blend_RstRstFunction& Func, const Standard_Real Tol3d, const Standard_Real Tol2d); Standard_EXPORT void Point (const Blend_AppFunction& Func, const Standard_Real Param, const math_Vector& Sol, Blend_Point& Pnt) const Standard_OVERRIDE; Standard_EXPORT void Vec (math_Vector& Sol, const Blend_Point& Pnt) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(BRepBlend_AppFuncRstRst,BRepBlend_AppFuncRoot) protected: private: }; #endif // _BRepBlend_AppFuncRstRst_HeaderFile
#include <bits/stdc++.h> #define MAX 110 using namespace std; int peso[MAX], wss[3]={}, memo[MAX], n, k, cont=0; int solve(int i, int p1, int p2, int p3); int main() { for(int i=0;i<MAX;i++) memo[i] = -1; scanf("%d %d", &n, &k); for(int i=0;i<n;i++) scanf("%d", &peso[i]); for(int i=0;i<k;i++) scanf("%d", &wss[i]); printf("%d\n", solve(0, 0, 0, 0)); return 0; } int solve(int i, int p1, int p2, int p3) { int m1=0; if(cont>=4500000 && memo[i]>0) return memo[i]; if(i<n) { if(p1+peso[i]<=wss[0]) m1 = peso[i] + solve(i+1, p1+peso[i], p2, p3); if(p2+peso[i]<=wss[1]) m1 = max(m1, peso[i] + solve(i+1, p1, p2+peso[i], p3)); if(p3+peso[i]<=wss[2]) m1 = max(m1, peso[i] + solve(i+1, p1, p2, p3+peso[i])); memo[i] = m1 = max(m1, solve(i+1, p1, p2, p3)); } else//ok cont++; return m1; }
#ifndef HOSTID_H #define HOSTID_H #include <QHostAddress> typedef QHostAddress ID_TYPE; class HostID { friend uint qHash(const HostID & key); private: ID_TYPE m_id; quint32 m_ipAddr; public: HostID(const ID_TYPE & id); HostID(const HostID & rhs); ~HostID(); HostID & operator=(const HostID & rhs); inline bool operator==(const HostID & rhs) const; const ID_TYPE & GetID() const { return m_id; } }; uint qHash(const HostID & key); //inline bool HostID::operator==(const HostID & rhs) const { return (m_id == rhs.m_id); } #endif