text
stringlengths
8
6.88M
#include "acceptorlist_p.hpp" #include "server_p.hpp" #include "monitor_connection_p.hpp" #include <boost/bind.hpp> #include <iostream> #include <sys/stat.h> namespace ioremap { namespace thevoid { enum { MAX_CONNECTIONS_COUNT = 128 }; template <typename Endpoint> static void complete_socket_creation(Endpoint endpoint) { (void) endpoint; } static void complete_socket_creation(boost::asio::local::stream_protocol::endpoint endpoint) { chmod(endpoint.path().c_str(), 0666); } template <typename Connection> void acceptors_list<Connection>::add_acceptor(const std::string &address) { io_services.emplace_back(new boost::asio::io_service); acceptors.emplace_back(new acceptor_type(*io_services.back())); auto &acceptor = acceptors.back(); try { endpoint_type endpoint = create_endpoint(*acceptor, address); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::socket_base::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(data.backlog_size); complete_socket_creation(endpoint); } catch (boost::system::system_error &error) { std::cerr << "Can not bind socket \"" << address << "\": " << error.what() << std::endl; std::cerr.flush(); throw; } start_acceptor(acceptors.size() - 1); } template <typename Connection> void acceptors_list<Connection>::start_acceptor(size_t index) { acceptor_type &acc = *acceptors[index]; auto conn = std::make_shared<connection_type>(acc.get_io_service()); acc.async_accept(conn->socket(), boost::bind( &acceptors_list::handle_accept, this, index, conn, _1)); } template <typename Connection> void acceptors_list<Connection>::handle_accept(size_t index, const connection_ptr_type &conn, const boost::system::error_code &err) { if (!err) { if (auto server = data.server.lock()) { conn->start(server); } else { throw std::logic_error("server::m_data->server is null"); } } start_acceptor(index); } template <typename Connection> void acceptors_list<Connection>::start_threads(int thread_count, std::vector<std::thread> &threads) { for (size_t i = 0; i < io_services.size(); ++i) { auto functor = boost::bind(&boost::asio::io_service::run, io_services[i].get()); for (int j = 0; j < thread_count; ++j) { threads.emplace_back(functor); } } } template <typename Connection> void acceptors_list<Connection>::handle_stop() { for (size_t i = 0; i < io_services.size(); ++i) { io_services[i]->stop(); } } template <typename Connection> typename acceptors_list<Connection>::endpoint_type acceptors_list<Connection>::create_endpoint(acceptor_type &acc, const std::string &host) { size_t delim = host.find(':'); std::string address = host.substr(0, delim); std::string port = host.substr(delim + 1); boost::asio::ip::tcp::resolver resolver(acc.get_io_service()); boost::asio::ip::tcp::resolver::query query(address, port); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); return endpoint; } template <> acceptors_list<unix_connection>::~acceptors_list() { for (size_t i = 0; i < acceptors.size(); ++i) { auto &acceptor = *acceptors[i]; auto path = acceptor.local_endpoint().path(); unlink(path.c_str()); } } template <> acceptors_list<unix_connection>::endpoint_type acceptors_list<unix_connection>::create_endpoint(acceptor_type &acc, const std::string &host) { return boost::asio::local::stream_protocol::endpoint(host); } template class acceptors_list<tcp_connection>; template class acceptors_list<unix_connection>; template class acceptors_list<monitor_connection>; } }
#include "HSRIFF.hpp" bool HSMakeRiffChunkFourCC ( char * lpChunkBaseName , std::string * lpChunkFourCC ){ if ( lpChunkBaseName == nullptr ) return false; if ( lpChunkFourCC == nullptr ) return false; char name [ 5 ]; name [ 4 ] = 0; size_t paramLen = strlen ( lpChunkBaseName ); memcpy ( name , lpChunkBaseName , ( paramLen > 4 ) ? 4 : paramLen ); if ( paramLen < 4 ) memset ( name + paramLen , ' ' , 4 - paramLen ); *lpChunkFourCC = name; return true; } int HSScanRiffChunkTable ( char * lpChunkName , CHSRiffChunkTable * pTable ){ std::string name; if ( HSMakeRiffChunkFourCC ( lpChunkName , &name ) == false ) return -1; if ( pTable == nullptr ) return -1; uint32_t base = *reinterpret_cast< const uint32_t* >( name.c_str ( ) ); uint32_t target; int len = pTable->size ( ); for ( int i = 0; i < len; i++ ) { target = *reinterpret_cast< uint32_t* >( pTable->at ( i ).Header.Name ); if ( base == target ) { return i; } } return -1; }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2009 Hauke Heibel <hauke.heibel@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or1 FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/LU> // required for MatrixBase::determinant #include <Eigen/SVD> // required for SVD using namespace Eigen; // Constructs a random matrix from the unitary group U(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixUnitary(int size) { typedef T Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; MatrixType Q; int max_tries = 40; double is_unitary = false; while (!is_unitary && max_tries > 0) { // initialize random matrix Q = MatrixType::Random(size, size); // orthogonalize columns using the Gram-Schmidt algorithm for (int col = 0; col < size; ++col) { typename MatrixType::ColXpr colVec = Q.col(col); for (int prevCol = 0; prevCol < col; ++prevCol) { typename MatrixType::ColXpr prevColVec = Q.col(prevCol); colVec -= colVec.dot(prevColVec)*prevColVec; } Q.col(col) = colVec.normalized(); } // this additional orthogonalization is not necessary in theory but should enhance // the numerical orthogonality of the matrix for (int row = 0; row < size; ++row) { typename MatrixType::RowXpr rowVec = Q.row(row); for (int prevRow = 0; prevRow < row; ++prevRow) { typename MatrixType::RowXpr prevRowVec = Q.row(prevRow); rowVec -= rowVec.dot(prevRowVec)*prevRowVec; } Q.row(row) = rowVec.normalized(); } // final check is_unitary = Q.isUnitary(); --max_tries; } if (max_tries == 0) ei_assert(false && "randMatrixUnitary: Could not construct unitary matrix!"); return Q; } // Constructs a random matrix from the special unitary group SU(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixSpecialUnitary(int size) { typedef T Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; // initialize unitary matrix MatrixType Q = randMatrixUnitary<Scalar>(size); // tweak the first column to make the determinant be 1 Q.col(0) *= ei_conj(Q.determinant()); return Q; } template <typename MatrixType> void run_test(int dim, int num_elements) { typedef typename ei_traits<MatrixType>::Scalar Scalar; typedef Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX; typedef Matrix<Scalar, Eigen::Dynamic, 1> VectorX; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = ei_abs(ei_random<Scalar>()); MatrixX R = randMatrixSpecialUnitary<Scalar>(dim); VectorX t = Scalar(50)*VectorX::Random(dim,1); MatrixX cR_t = MatrixX::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; MatrixX cR_t_umeyama = umeyama(src.block(0,0,dim,num_elements), dst.block(0,0,dim,num_elements)); const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum(); VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon()); } template<typename Scalar, int Dimension> void run_fixed_size_test(int num_elements) { typedef Matrix<Scalar, Dimension+1, Dynamic> MatrixX; typedef Matrix<Scalar, Dimension+1, Dimension+1> HomMatrix; typedef Matrix<Scalar, Dimension, Dimension> FixedMatrix; typedef Matrix<Scalar, Dimension, 1> FixedVector; const int dim = Dimension; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = ei_abs(ei_random<Scalar>()); FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim); FixedVector t = Scalar(50)*FixedVector::Random(dim,1); HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; Block<MatrixX, Dimension, Dynamic> src_block(src,0,0,dim,num_elements); Block<MatrixX, Dimension, Dynamic> dst_block(dst,0,0,dim,num_elements); HomMatrix cR_t_umeyama = umeyama(src_block, dst_block); const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum(); VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon()); } void test_umeyama() { for (int i=0; i<g_repeat; ++i) { const int num_elements = ei_random<int>(40,500); // works also for dimensions bigger than 3... for (int dim=2; dim<8; ++dim) { CALL_SUBTEST_1(run_test<MatrixXd>(dim, num_elements)); CALL_SUBTEST_2(run_test<MatrixXf>(dim, num_elements)); } CALL_SUBTEST_3((run_fixed_size_test<float, 2>(num_elements))); CALL_SUBTEST_4((run_fixed_size_test<float, 3>(num_elements))); CALL_SUBTEST_5((run_fixed_size_test<float, 4>(num_elements))); CALL_SUBTEST_6((run_fixed_size_test<double, 2>(num_elements))); CALL_SUBTEST_7((run_fixed_size_test<double, 3>(num_elements))); CALL_SUBTEST_8((run_fixed_size_test<double, 4>(num_elements))); } // Those two calls don't compile and result in meaningful error messages! // umeyama(MatrixXcf(),MatrixXcf()); // umeyama(MatrixXcd(),MatrixXcd()); }
#include "../headers/Inventory.h" //#include "../headers/player.h" //#include "../headers/skill.h" #include "../headers/item.h" #include "../headers/Safe_Input.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <assert.h> using namespace std; Inventory::Inventory() { inv_size = 0; inventory = NULL; } Inventory::Inventory(int A) { inv_size = A; inventory = new item*[inv_size]; for (int i=0; i<inv_size; i++) inventory[i] = NULL; } Inventory::~Inventory() { for (int i=0; i<inv_size; i++) { if (inventory[i] != NULL) delete inventory[i]; } if (inventory != NULL) delete [] inventory; } void Inventory::printInventory() { printf("Inventory\n"); printf("-----------------------------\n"); printf("ID Name Stock Equip\n"); printf("=== ==================== ====== =======\n"); for (int k=0; k<inv_size; k++) { if (inventory[k] != NULL) { printf("%2d. %-20s x%-5d ", k+1, inventory[k]->getName(), inventory[k]->getStock()); if (inventory[k]->getType() == 4) printf("Yes\n"); else printf("No\n"); } else printf("%2d. %-20s %-6s N/A\n", k+1, "<Empty Slot>", "N/A"); } printf("\n"); } int Inventory::printInventoryPage() { // int pages = inv_size/10 + 1; int pages = (inv_size-1)/10 + 1; printf("Select an inventory page to view (1-%d): ", pages); int page_sel = getSel(pages); printf("Inventory\n"); printf("-----------------------------\n"); printf("ID Name Stock Equip\n"); printf("==== ==================== ====== =======\n"); int start = (page_sel-1)*10; int end = start+10; if (end > inv_size) end = inv_size; for (int k=start; k<end; k++) { if (inventory[k] != NULL) { printf("%3d. %-20s x%-5d ", k+1, inventory[k]->getName(), inventory[k]->getStock()); if (inventory[k]->getType() == 4) printf("Yes\n"); else printf("No\n"); } else printf("%3d. %-20s %-6s N/A\n", k+1, "<Empty Slot>", "N/A"); } printf("\n"); return (end); } bool Inventory::inventoryFull() { bool full = true; for (int i=0; i < inv_size; i++) { if (inventory[i] != NULL) { if (inventory[i]->getStock() == 0) { delete inventory[i]; inventory[i] = NULL; } } if (inventory[i] == NULL) { full = false; } } return full; } bool Inventory::checkStock(int idx, int num) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return false; } if (inventory[idx] != NULL) { int stk = inventory[idx]->getStock(); if (stk >= num) return true; else return false; } else { printf("You did not select anything to remove\n"); return false; } } bool Inventory::checkItem(int idx) { bool valid_item = true; if ((idx < 0)||(idx >= inv_size)) valid_item = false; if (inventory[idx] == NULL) valid_item = false; return valid_item; } char* Inventory::getItemName(int idx) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return NULL; } if (inventory[idx] != NULL) { return inventory[idx]->getName(); } else { printf("You did not select anything to remove\n"); return NULL; } } int Inventory::getItemValue(int idx) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return -1; } if (inventory[idx] != NULL) { return inventory[idx]->getGoldValue(); } else { printf("You did not select anything to remove\n"); return -1; } } void Inventory::recieveItem(item *loot) { if (loot == NULL) { printf("Invalid item\n"); return; } bool loop = true; fprintf(stderr, "DEBUG: Item's name is %s\n", loot->getName()); for (int i=0; i<inv_size; i++) { if (inventory[i] != NULL) { if (inventory[i]->getID() == loot->getID()) { int newStock = inventory[i]->getStock() + loot->getStock(); inventory[i]->setStock(newStock); delete loot; loop = false; break; } } } if (loop) { for (int i=0; i<inv_size; i++) { if (inventory[i] == NULL) { inventory[i] = loot; loop = false; break; } } } if (loop) { for (int i=0; i<inv_size; i++) { if (inventory[i] == NULL) { inventory[i] = loot; loop = false; break; } } } if (loop) { printf("Inventory is full, what would you like to do?\n"); char sel1[128], sel2[128]; sprintf(sel1, "1. Swap %s for item in inventory", loot->getName()); sprintf(sel2, "2. Discard %s", loot->getName()); int sel = getSel(sel1, sel2); if (sel == 1) { item *temp = swapItem(loot); recieveItem(temp); } else { printf("%s was discarded...\n", loot->getName()); delete loot; fprintf(stderr, "Stack, why you get smashed!!\n"); } } } item* Inventory::removeItem(int idx) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return NULL; } if (inventory[idx] != NULL) { printf("Removing %s...\n", inventory[idx]->getName()); item *temp = inventory[idx]; inventory[idx] = NULL; return temp; } else { printf("You did not select anything to remove\n"); return NULL; } } item* Inventory::removeOneItem(int idx) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return NULL; } if (inventory[idx] != NULL) { printf("Removing one %s...\n", inventory[idx]->getName()); item *temp; if (inventory[idx]->getStock() == 1) { temp = inventory[idx]; inventory[idx] = NULL; } else { temp = getItem(inventory[idx]->getID()); inventory[idx]->decrementStock(); } return temp; } else { printf("You did not select anything to remove\n"); return NULL; } } item* Inventory::removeItems(int idx, int num) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return NULL; } if (inventory[idx] != NULL) { printf("Removing %d %ss...\n", num, inventory[idx]->getName()); item *temp; if (inventory[idx]->getStock() == num) { temp = inventory[idx]; inventory[idx] = NULL; } else { temp = getItem(inventory[idx]->getID()); temp->setStock(num); inventory[idx]->removeStock(num); } return temp; } else { printf("You did not select anything to remove\n"); return NULL; } } void Inventory::discardItem(int idx) { if ((idx < 0)||(idx >= inv_size)) { printf("Invalid selection\n"); return; } item *temp = removeItem(idx); if (temp != NULL) { printf("Discard %s?\n", temp->getName()); int sel = getSel("1. Yes", "2. No"); if (sel == 1) { delete temp; } else { printf("Cancelling action...\n"); recieveItem(temp); } } else { printf("You did not select anything to discard.\n"); } } item* Inventory::swapItem(item *loot) { printInventory(); printf("Swap %s for which item:", loot->getName()); int sel = getSel(inv_size); sel--; printf("Swapping %s for %s...\n", inventory[sel]->getName(), loot->getName()); item *temp = inventory[sel]; inventory[sel] = loot; return temp; } void Inventory::viewItemInfo(int itm_idx) { if ((itm_idx < 0)||(itm_idx >= inv_size)) { printf("Invalid selection...\n"); return; } if (inventory[itm_idx] == NULL) { printf("You did not select an item...\n"); return; } inventory[itm_idx]->printInfo(); } void Inventory::manageInventory() { bool manageInventory = true; while(manageInventory) { printf("Inventory Management\n"); printf("-------------------------------------\n"); int man_sel = getSel("1. View Inventory", "2. View Item Description", "3. Discard Item", "4. Cancel"); switch (man_sel) { case 1://View Inventory { printInventory(); break; } // case 2://Use Item // { // useItem_OB();//Not a working function in Inventory class // break; // } case 2: { viewItemInfo_OB(); break; } case 3://Discard Item { printInventory(); printf("\n%d. Cancel\n", inv_size+1); printf("Select Item to discard: "); int discard_sel = getSel(inv_size+1); if (discard_sel < inv_size+1) { discard_sel--; discardItem(discard_sel); } else { printf("Cancelling action...\n"); } break; } case 4://Cancel { printf("Cancelling action...\n"); manageInventory = false; break; } } } } void Inventory::viewItemInfo_OB() { int item_sel; printf("Select an item: \n"); printInventory(); printf("%d. Cancel action\n", inv_size+1); item_sel = getSel(inv_size+1); item_sel--; if (item_sel < inv_size) { viewItemInfo(item_sel); } else printf("Cancelling action...\n"); } void Inventory::saveInventory(FILE *fp) { assert(fp != NULL); for (int i=0; i<inv_size; i++) { if (inventory[i] != NULL) { fprintf(fp, "%d %d \n", inventory[i]->getID(), inventory[i]->getStock()); } else fprintf(fp, "0 \n"); } } void Inventory::loadInventory(FILE *fp) { assert(fp != NULL); for (int i=0; i<inv_size; i++) { int temp_id, temp_stock; fscanf(fp, " %d ", &temp_id); if (temp_id != 0) { fscanf(fp, " %d ", &temp_stock); inventory[i] = getItem(temp_id); inventory[i]->setStock(temp_stock); } else inventory[i] = NULL; } }
#include "InputHandler.h" InputHandler::InputHandler(GameEngine* e) { engine = e; } InputHandler::~InputHandler() { } void InputHandler::checkKeyboard() { if (engine != NULL) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { engine->player->Move(DIRECTION_UP); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { engine->player->Move(DIRECTION_DOWN); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { engine->player->Move(DIRECTION_LEFT); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { engine->player->Move(DIRECTION_RIGHT); } } } void InputHandler::checkMouse(sf::Vector2f pos) { if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { printf("%d %d\n", sf::Mouse::getPosition().x, sf::Mouse::getPosition().y); if (pos.y >= 960 && pos.x > 1285 && pos.x < 1349) { if (pos.y >= 992) { engine->saveButton->OnClick(); } else { engine->loadButton->OnClick(); } } if (pos.x >= 1280) { engine->SelectSprite(pos.x, pos.y); } else { engine->SetNode(pos.x,pos.y); } } } void InputHandler::scrollMouse(sf::Vector2f pos,float delta) { if (pos.x > 1285) { //scroll time! //offset y += delta? sprites->UpdateOffset(sprites->offset + 5*delta); } }
#include "ofxCommandProcessorThreadMac.h" bool ofxCommandProcessorThreadMac::start() { thread_ptr = boost::shared_ptr<boost::thread>(new boost::thread( boost::bind(&ofxCommandProcessorThreadMac::run, this) )); return true; } void ofxCommandProcessorThreadMac::join() { thread_ptr->join(); } void ofxCommandProcessorThreadMac::sleep(int nMillis) { boost::mutex::scoped_lock sl(mutex_); ofSleepMillis(nMillis); //boost::thread::sleep(nMillis); } void ofxCommandProcessorThreadMac::run() { while(true) { ofxCommandProcessor::update(); } } //-- void ofxCommandProcessorThreadMac::enqueue(boost::shared_ptr<ofxCommand> pCommand) { boost::mutex::scoped_lock sl(mutex_); ofxCommandProcessor::enqueue(pCommand); } void ofxCommandProcessorThreadMac::remove(std::string sName) { boost::mutex::scoped_lock sl(mutex_); ofxCommandProcessor::remove(sName); } void ofxCommandProcessorThreadMac::clear() { boost::mutex::scoped_lock sl(mutex_); ofxCommandProcessor::clear(); } bool ofxCommandProcessorThreadMac::isReady() { boost::mutex::scoped_lock sl(mutex_); bool ready = ofxCommandProcessor::isReady(); return ready; } void ofxCommandProcessorThreadMac::update() { } boost::shared_ptr<ofxCommand> ofxCommandProcessorThreadMac::take() { boost::mutex::scoped_lock sl(mutex_); return ofxCommandProcessor::take(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/opdata/OpDataFragmentIterator.h" void OpDataCharIterator::MoveToIndex(size_t index) { OP_ASSERT(m_index <= index); while (m_index < index) { if (m_index + m_current_length-1 >= index) { m_current_index = index-m_index; m_index = index; OP_ASSERT(IsValid()); } else { m_index += m_current_length; StepToNextFragment(); } } } bool OpDataCharIterator::NextWithFragment() { OP_ASSERT(m_current_index+1 >= m_current_length); if (IsAtEnd()) return false; OP_ASSERT(m_itr.IsValid() && m_current_index < m_current_length); ++m_index; if (++m_current_index == m_current_length) { if (!m_itr.HasNext()) return false; // we hit the end of the buffer StepToNextFragment(); } return true; } void OpDataCharIterator::StepToNextFragment() { OP_ASSERT(m_itr.HasNext()); ++m_itr; m_current_length = m_itr.GetLength(); m_current_data = m_itr.GetData(); m_current_index = 0; OP_ASSERT(m_itr.IsValid() && m_current_index < m_current_length); } bool OpDataCharIterator::PreviousWithFragment() { OP_ASSERT(m_current_index == 0); if (m_index == 0) return false; OP_ASSERT(IsValid()); OP_ASSERT(m_itr.HasPrev()); --m_index; --m_itr; m_current_data = m_itr.GetData(); OP_ASSERT(m_current_data); m_current_length = m_itr.GetLength(); m_current_index = m_current_length-1; OP_ASSERT(IsValid()); return true; }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2019 jtgrassie <https://github.com/jtgrassie> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <cinttypes> #include <iterator> #include <cstdio> #include <cstring> #include <utility> #ifdef XMRIG_FEATURE_TLS # include <openssl/ssl.h> # include <openssl/err.h> # include "base/net/stratum/Tls.h" #endif #include "base/net/stratum/Client.h" #include "3rdparty/rapidjson/document.h" #include "3rdparty/rapidjson/error/en.h" #include "3rdparty/rapidjson/stringbuffer.h" #include "3rdparty/rapidjson/writer.h" #include "base/io/json/Json.h" #include "base/io/json/JsonRequest.h" #include "base/io/log/Log.h" #include "base/kernel/interfaces/IClientListener.h" #include "base/net/dns/Dns.h" #include "base/net/dns/DnsRecords.h" #include "base/net/stratum/Socks5.h" #include "base/net/tools/NetBuffer.h" #include "base/tools/Chrono.h" #include "base/tools/Cvt.h" #include "net/JobResult.h" #ifdef _MSC_VER # define strncasecmp(x,y,z) _strnicmp(x,y,z) #endif namespace xmrig { Storage<Client> Client::m_storage; } /* namespace xmrig */ #ifdef APP_DEBUG static const char *states[] = { "unconnected", "host-lookup", "connecting", "connected", "closing", "reconnecting" }; #endif xmrig::Client::Client(int id, const char *agent, IClientListener *listener) : BaseClient(id, listener), m_agent(agent), m_sendBuf(1024) { m_reader.setListener(this); m_key = m_storage.add(this); } xmrig::Client::~Client() { delete m_socket; } bool xmrig::Client::disconnect() { m_keepAlive = 0; m_expire = 0; m_failures = -1; return close(); } bool xmrig::Client::isTLS() const { # ifdef XMRIG_FEATURE_TLS return m_pool.isTLS() && m_tls; # else return false; # endif } const char *xmrig::Client::tlsFingerprint() const { # ifdef XMRIG_FEATURE_TLS if (isTLS() && m_pool.fingerprint() == nullptr) { return m_tls->fingerprint(); } # endif return nullptr; } const char *xmrig::Client::tlsVersion() const { # ifdef XMRIG_FEATURE_TLS if (isTLS()) { return m_tls->version(); } # endif return nullptr; } int64_t xmrig::Client::send(const rapidjson::Value &obj, Callback callback) { assert(obj["id"] == sequence()); m_callbacks.insert({ sequence(), std::move(callback) }); return send(obj); } int64_t xmrig::Client::send(const rapidjson::Value &obj) { using namespace rapidjson; StringBuffer buffer(nullptr, 512); Writer<StringBuffer> writer(buffer); obj.Accept(writer); const size_t size = buffer.GetSize(); if (size > kMaxSendBufferSize) { LOG_ERR("%s " RED("send failed: ") RED_BOLD("\"max send buffer size exceeded: %zu\""), tag(), size); close(); return -1; } if (size > (m_sendBuf.size() - 2)) { m_sendBuf.resize(((size + 1) / 1024 + 1) * 1024); } memcpy(m_sendBuf.data(), buffer.GetString(), size); m_sendBuf[size] = '\n'; m_sendBuf[size + 1] = '\0'; return send(size + 1); } int64_t xmrig::Client::submit(const JobResult &result) { if (m_rpcId.isNull()) return 0; // ignore leftout benchmark jobs # ifndef XMRIG_PROXY_PROJECT if (result.clientId != m_rpcId || m_rpcId.isNull() || m_state != ConnectedState) { return -1; } # endif if (result.diff == 0) { close(); return -1; } using namespace rapidjson; # ifdef XMRIG_PROXY_PROJECT const char *nonce = result.nonce; const char *data = result.result; # else char *nonce = m_sendBuf.data(); char *data = m_sendBuf.data() + 16; Cvt::toHex(nonce, sizeof(uint32_t) * 2 + 1, reinterpret_cast<const uint8_t *>(&result.nonce), sizeof(uint32_t)); Cvt::toHex(data, 65, result.result(), 32); # endif Document doc(kObjectType); auto &allocator = doc.GetAllocator(); Value params(kObjectType); params.AddMember("id", StringRef(m_rpcId.data()), allocator); params.AddMember("job_id", StringRef(result.jobId.data()), allocator); params.AddMember("nonce", StringRef(nonce), allocator); params.AddMember("result", StringRef(data), allocator); if (has<EXT_ALGO>() && result.algorithm.isValid()) { params.AddMember("algo", StringRef(result.algorithm.shortName()), allocator); } JsonRequest::create(doc, m_sequence, "submit", params); # ifdef XMRIG_PROXY_PROJECT m_results[m_sequence] = SubmitResult(m_sequence, result.diff, result.actualDiff(), result.id, 0); # else m_results[m_sequence] = SubmitResult(m_sequence, result.diff, result.actualDiff(), 0, result.backend); # endif return send(doc); } void xmrig::Client::connect() { if (m_pool.proxy().isValid()) { m_socks5 = new Socks5(this); resolve(m_pool.proxy().host()); return; } # ifdef XMRIG_FEATURE_TLS if (m_pool.isTLS()) { m_tls = new Tls(this); } # endif resolve(m_pool.host()); } void xmrig::Client::connect(const Pool &pool) { setPool(pool); connect(); } void xmrig::Client::deleteLater() { if (!m_listener) { return; } m_listener = nullptr; if (!disconnect()) { m_storage.remove(m_key); } } void xmrig::Client::tick(uint64_t now) { if (m_state == ConnectedState) { if (m_expire && now > m_expire) { LOG_DEBUG_ERR("[%s] timeout", url()); close(); } else if (m_keepAlive && now > m_keepAlive) { ping(); } return; } if (m_state == ReconnectingState && m_expire && now > m_expire) { return connect(); } if (m_state == ConnectingState && m_expire && now > m_expire) { close(); } } void xmrig::Client::onResolved(const DnsRecords &records, int status, const char *error) { m_dns.reset(); assert(m_listener != nullptr); if (!m_listener) { return reconnect(); } if (status < 0 && records.isEmpty()) { if (!isQuiet()) { LOG_ERR("%s " RED("DNS error: ") RED_BOLD("\"%s\""), tag(), error); } return reconnect(); } const auto &record = records.get(); m_ip = record.ip(); connect(record.addr(m_socks5 ? m_pool.proxy().port() : m_pool.port())); } bool xmrig::Client::close() { if (m_state == ClosingState) { return m_socket != nullptr; } if (m_state == UnconnectedState || m_socket == nullptr) { return false; } setState(ClosingState); if (uv_is_closing(reinterpret_cast<uv_handle_t*>(m_socket)) == 0) { uv_close(reinterpret_cast<uv_handle_t*>(m_socket), Client::onClose); } return true; } bool xmrig::Client::isCriticalError(const char *message) { if (!message) { return false; } if (strncasecmp(message, "Unauthenticated", 15) == 0) { return true; } if (strncasecmp(message, "your IP is banned", 17) == 0) { return true; } if (strncasecmp(message, "IP Address currently banned", 27) == 0) { return true; } if (strncasecmp(message, "Invalid job id", 14) == 0) { return true; } return false; } bool xmrig::Client::parseJob(const rapidjson::Value &params, int *code) { if (!params.IsObject()) { *code = 2; return false; } Job job(has<EXT_NICEHASH>(), m_pool.algorithm(), m_rpcId); if (!job.setId(params["job_id"].GetString())) { *code = 3; return false; } const char *algo = Json::getString(params, "algo"); const char *blobData = Json::getString(params, "blob"); if (algo) { job.setAlgorithm(algo); } else if (m_pool.coin().isValid()) { uint8_t blobVersion = 0; if (blobData) { Cvt::fromHex(&blobVersion, 1, blobData, 2); } job.setAlgorithm(m_pool.coin().algorithm(blobVersion)); } # ifdef XMRIG_FEATURE_HTTP if (m_pool.mode() == Pool::MODE_SELF_SELECT) { job.setExtraNonce(Json::getString(params, "extra_nonce")); job.setPoolWallet(Json::getString(params, "pool_wallet")); if (job.extraNonce().isNull() || job.poolWallet().isNull()) { *code = 4; return false; } } else # endif { if (!job.setBlob(blobData)) { *code = 4; return false; } } if (!job.setTarget(params["target"].GetString())) { *code = 5; return false; } job.setHeight(Json::getUint64(params, "height")); if (!verifyAlgorithm(job.algorithm(), algo)) { *code = 6; return false; } if (m_pool.mode() != Pool::MODE_SELF_SELECT && job.algorithm().family() == Algorithm::RANDOM_X && !job.setSeedHash(Json::getString(params, "seed_hash"))) { *code = 7; return false; } m_job.setClientId(m_rpcId); if (m_job != job) { m_jobs++; m_job = std::move(job); return true; } if (m_jobs == 0) { // https://github.com/xmrig/xmrig/issues/459 return false; } if (!isQuiet()) { LOG_WARN("%s " YELLOW("duplicate job received, reconnect"), tag()); } close(); return false; } bool xmrig::Client::send(BIO *bio) { # ifdef XMRIG_FEATURE_TLS uv_buf_t buf; buf.len = BIO_get_mem_data(bio, &buf.base); if (buf.len == 0) { return true; } LOG_DEBUG("[%s] TLS send (%d bytes)", url(), static_cast<int>(buf.len)); bool result = false; if (state() == ConnectedState && uv_is_writable(stream())) { result = write(buf); } else { LOG_DEBUG_ERR("[%s] send failed, invalid state: %d", url(), m_state); } (void) BIO_reset(bio); return result; # else return false; # endif } bool xmrig::Client::verifyAlgorithm(const Algorithm &algorithm, const char *algo) const { if (!algorithm.isValid()) { if (!isQuiet()) { if (algo == nullptr) { LOG_ERR("%s " RED("unknown algorithm, make sure you set \"algo\" or \"coin\" option"), tag(), algo); } else { LOG_ERR("%s " RED("unsupported algorithm ") RED_BOLD("\"%s\" ") RED("detected, reconnect"), tag(), algo); } } return false; } bool ok = true; m_listener->onVerifyAlgorithm(this, algorithm, &ok); if (!ok && !isQuiet()) { LOG_ERR("%s " RED("incompatible/disabled algorithm ") RED_BOLD("\"%s\" ") RED("detected, reconnect"), tag(), algorithm.shortName()); } return ok; } bool xmrig::Client::write(const uv_buf_t &buf) { const int rc = uv_try_write(stream(), &buf, 1); if (static_cast<size_t>(rc) == buf.len) { return true; } if (!isQuiet()) { LOG_ERR("%s " RED("write error: ") RED_BOLD("\"%s\""), tag(), uv_strerror(rc)); } close(); return false; } int xmrig::Client::resolve(const String &host) { setState(HostLookupState); m_reader.reset(); if (m_failures == -1) { m_failures = 0; } m_dns = Dns::resolve(host, this); return 0; } int64_t xmrig::Client::send(size_t size) { //LOG_INFO("[%s] send (%d bytes): \"%.*s\"", url(), size, static_cast<int>(size) - 1, m_sendBuf.data()); # ifdef XMRIG_FEATURE_TLS if (isTLS()) { if (!m_tls->send(m_sendBuf.data(), size)) { return -1; } } else # endif { if (state() != ConnectedState || !uv_is_writable(stream())) { LOG_DEBUG_ERR("[%s] send failed, invalid state: %d", url(), m_state); return -1; } uv_buf_t buf = uv_buf_init(m_sendBuf.data(), (unsigned int) size); if (!write(buf)) { return -1; } } m_expire = Chrono::steadyMSecs() + kResponseTimeout; return m_sequence++; } void xmrig::Client::connect(const sockaddr *addr) { setState(ConnectingState); auto req = new uv_connect_t; req->data = m_storage.ptr(m_key); m_socket = new uv_tcp_t; m_socket->data = m_storage.ptr(m_key); uv_tcp_init(uv_default_loop(), m_socket); uv_tcp_nodelay(m_socket, 1); # ifndef WIN32 uv_tcp_keepalive(m_socket, 1, 60); # endif uv_tcp_connect(req, m_socket, addr, onConnect); } void xmrig::Client::handshake() { if (m_socks5) { return m_socks5->handshake(); } # ifdef XMRIG_FEATURE_TLS if (isTLS()) { m_expire = Chrono::steadyMSecs() + kResponseTimeout; m_tls->handshake(); } else # endif { login(); } } bool xmrig::Client::parseLogin(const rapidjson::Value &result, int *code) { setRpcId(Json::getString(result, "id")); if (rpcId().isNull()) { *code = 1; return false; } parseExtensions(result); const bool rc = parseJob(result["job"], code); m_jobs = 0; return rc; } void xmrig::Client::login() { using namespace rapidjson; m_results.clear(); Document doc(kObjectType); auto &allocator = doc.GetAllocator(); Value params(kObjectType); params.AddMember("login", m_user.toJSON(), allocator); params.AddMember("pass", m_password.toJSON(), allocator); params.AddMember("agent", StringRef(m_agent), allocator); if (!m_rigId.isNull()) { params.AddMember("rigid", m_rigId.toJSON(), allocator); } m_listener->onLogin(this, doc, params); JsonRequest::create(doc, 1, "login", params); send(doc); } void xmrig::Client::onClose() { delete m_socket; m_socket = nullptr; setState(UnconnectedState); # ifdef XMRIG_FEATURE_TLS if (m_tls) { delete m_tls; m_tls = nullptr; } # endif reconnect(); } void xmrig::Client::parse(char *line, size_t len) { startTimeout(); //LOG_INFO("[%s] received (%d bytes): \"%.*s\"", url(), len, static_cast<int>(len), line); if (len < 32 || line[0] != '{') { if (!isQuiet()) { LOG_ERR("%s " RED("JSON decode failed"), tag()); } return; } rapidjson::Document doc; if (doc.ParseInsitu(line).HasParseError()) { if (!isQuiet()) { LOG_ERR("%s " RED("JSON decode failed: ") RED_BOLD("\"%s\""), tag(), rapidjson::GetParseError_En(doc.GetParseError())); } return; } if (!doc.IsObject()) { return; } const auto &id = Json::getValue(doc, "id"); const auto &error = Json::getValue(doc, "error"); if (id.IsInt64()) { return parseResponse(id.GetInt64(), Json::getValue(doc, "result"), error); } const char *method = Json::getString(doc, "method"); if (!method) { return; } if (error.IsObject()) { if (!isQuiet()) { LOG_ERR("%s " RED("error: ") RED_BOLD("\"%s\"") RED(", code: ") RED_BOLD("%d"), tag(), Json::getString(error, "message"), Json::getInt(error, "code")); } return; } parseNotification(method, Json::getValue(doc, "params"), error); } void xmrig::Client::parseExtensions(const rapidjson::Value &result) { m_extensions.reset(); if (!result.HasMember("extensions")) { return; } const rapidjson::Value &extensions = result["extensions"]; if (!extensions.IsArray()) { return; } for (const rapidjson::Value &ext : extensions.GetArray()) { if (!ext.IsString()) { continue; } const char *name = ext.GetString(); if (strcmp(name, "algo") == 0) { setExtension(EXT_ALGO, true); } else if (strcmp(name, "nicehash") == 0) { setExtension(EXT_NICEHASH, true); } else if (strcmp(name, "connect") == 0) { setExtension(EXT_CONNECT, true); } else if (strcmp(name, "keepalive") == 0) { setExtension(EXT_KEEPALIVE, true); startTimeout(); } # ifdef XMRIG_FEATURE_TLS else if (strcmp(name, "tls") == 0) { setExtension(EXT_TLS, true); } # endif } } void xmrig::Client::parseNotification(const char *method, const rapidjson::Value &params, const rapidjson::Value &) { if (strcmp(method, "job") == 0) { int code = -1; if (parseJob(params, &code)) { m_listener->onJobReceived(this, m_job, params); } else { close(); } return; } } void xmrig::Client::parseResponse(int64_t id, const rapidjson::Value &result, const rapidjson::Value &error) { if (handleResponse(id, result, error)) { return; } if (error.IsObject()) { const char *message = error["message"].GetString(); if (!handleSubmitResponse(id, message) && !isQuiet()) { LOG_ERR("%s " RED("error: ") RED_BOLD("\"%s\"") RED(", code: ") RED_BOLD("%d"), tag(), message, Json::getInt(error, "code")); } if (m_id == 1 || isCriticalError(message)) { close(); } return; } if (!result.IsObject()) { return; } if (id == 1) { int code = -1; if (!parseLogin(result, &code)) { if (!isQuiet()) { LOG_ERR("%s " RED("login error code: ") RED_BOLD("%d"), tag(), code); } close(); return; } m_failures = 0; m_listener->onLoginSuccess(this); if (m_job.isValid()) { m_listener->onJobReceived(this, m_job, result["job"]); } return; } handleSubmitResponse(id); } void xmrig::Client::ping() { send(snprintf(m_sendBuf.data(), m_sendBuf.size(), "{\"id\":%" PRId64 ",\"jsonrpc\":\"2.0\",\"method\":\"keepalived\",\"params\":{\"id\":\"%s\"}}\n", m_sequence, m_rpcId.data())); m_keepAlive = 0; } void xmrig::Client::read(ssize_t nread, const uv_buf_t *buf) { const auto size = static_cast<size_t>(nread); if (nread < 0) { if (!isQuiet()) { LOG_ERR("%s " RED("read error: ") RED_BOLD("\"%s\""), tag(), uv_strerror(static_cast<int>(nread))); } close(); return; } assert(m_listener != nullptr); if (!m_listener) { return reconnect(); } if (m_socks5) { m_socks5->read(buf->base, size); if (m_socks5->isReady()) { delete m_socks5; m_socks5 = nullptr; # ifdef XMRIG_FEATURE_TLS if (m_pool.isTLS() && !m_tls) { m_tls = new Tls(this); } # endif handshake(); } return; } # ifdef XMRIG_FEATURE_TLS if (isTLS()) { LOG_DEBUG("[%s] TLS received (%d bytes)", url(), static_cast<int>(nread)); m_tls->read(buf->base, size); } else # endif { m_reader.parse(buf->base, size); } } void xmrig::Client::reconnect() { if (!m_listener) { m_storage.remove(m_key); return; } m_keepAlive = 0; if (m_failures == -1) { return m_listener->onClose(this, -1); } setState(ReconnectingState); m_failures++; m_listener->onClose(this, static_cast<int>(m_failures)); } void xmrig::Client::setState(SocketState state) { LOG_DEBUG("[%s] state: \"%s\" -> \"%s\"", url(), states[m_state], states[state]); if (m_state == state) { return; } switch (state) { case HostLookupState: m_expire = 0; break; case ConnectingState: m_expire = Chrono::steadyMSecs() + kConnectTimeout; break; case ReconnectingState: m_expire = Chrono::steadyMSecs() + m_retryPause; break; default: break; } m_state = state; } void xmrig::Client::startTimeout() { m_expire = 0; if (has<EXT_KEEPALIVE>()) { const uint64_t ms = static_cast<uint64_t>(m_pool.keepAlive() > 0 ? m_pool.keepAlive() : Pool::kKeepAliveTimeout) * 1000; m_keepAlive = Chrono::steadyMSecs() + ms; } } void xmrig::Client::onClose(uv_handle_t *handle) { auto client = getClient(handle->data); if (!client) { return; } client->onClose(); } void xmrig::Client::onConnect(uv_connect_t *req, int status) { auto client = getClient(req->data); delete req; if (!client) { return; } if (status < 0) { if (!client->isQuiet()) { LOG_ERR("%s " RED("connect error: ") RED_BOLD("\"%s\""), client->tag(), uv_strerror(status)); } if (client->state() == ReconnectingState || client->state() == ClosingState) { return; } if (client->state() != ConnectingState) { return; } client->close(); return; } if (client->state() == ConnectedState) { return; } client->setState(ConnectedState); uv_read_start(client->stream(), NetBuffer::onAlloc, onRead); client->handshake(); } void xmrig::Client::onRead(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { auto client = getClient(stream->data); if (client) { client->read(nread, buf); } NetBuffer::release(buf); }
#include "../gl_framework.h" using namespace glmock; extern "C" { DLL_EXPORT void CALL_CONV glCullFace(GLenum mode) { } }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #define p printf void random(int arr[10][10], int row, int col) { srand(time(NULL)); int i,j; for(i=0;i<row;i++) { for(j=0;j<col;j++) { arr[i][j]=(rand()%20)+1; if(arr[i][j]<10) p("0%d ",arr[i][j]); else p("%d ",arr[i][j]); } p("\n"); } } bool add(int R1[10][10],int R2[10][10],int r1, int c1, int r2, int c2) { int R3[10][10],i,j; if(c1==c2 && r1==r2) { for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { R3[i][j]=R2[i][j]+R1[i][j]; if(R3[i][j]>9) p("%d ",R3[i][j]); else p("0%d ",R3[i][j]); } p("\n"); } } else { system("cls"); return false; } } bool subt(int R1[10][10],int R2[10][10],int r1, int c1, int r2, int c2) { int R3[10][10],i,j; if(c1==c2 && r1==r2) { for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { R3[i][j]=R1[i][j]-R2[i][j]; p("%d ",R3[i][j]); } p("\n"); } return true; } else return false; } void display(int R[10][10], int row, int col) { int i,j; for(i=0;i<row;i++) { for(j=0;j<col;j++) { if(R[i][j]>9) p("%d ",R[i][j]); else p("0%d ",R[i][j]); } p("\n"); } } void scalar(int R[10][10], int row, int col, int sc) { int i,j; for(i=0;i<row;i++) { for(j=0;j<col;j++) { if(((R[i][j])*sc)<10) p("0%d ",(R[i][j])*sc); else p("%d ",(R[i][j])*sc); } p("\n"); } } bool multiply(int r1[10][10], int r2[10][10], int ro2, int co1, int ro1, int co2) { int i=0,j=0,k; int r3[10][10]; if(co1==ro2) { for(k=0;k<ro1;k++) { printf("\n"); for(i=0;i<ro1;i++) { r3[k][i]=0; for(j=0;j<co1;j++) { r3[k][i]+= r1[k][j] * r2[j][i]; } printf("%d ",r3[k][i]); } printf("\n"); } } else return false; } void trans(int R[10][10], int x, int y) { int T[10][10]; int i,j; int temp; for(i=0;i<x;i++) for(j=0;j<y;j++) { temp=R[i][j]; T[j][i]=temp; } for(i=0;i<y;i++) { for(j=0;j<x;j++) { if(T[i][j]<10) p("0%d ",T[i][j]); else p("%d ",T[i][j]); } p("\n"); } }
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; for(int i=0;i<s.size();i++){ if(s[i]>='A'&&s[i]<='Z'){ s[i]+=32; } } string str=""; str+="."; for(int i=0;i<s.size();i++){ if(s[i]!= 'u' && s[i] != 'e' && s[i] != 'o' && s[i] != 'a' && s[i] != 'i' && s[i] != 'y'){ str+=s[i]; str+="."; } } for(int i=0;i<str.size()-1;i++){ cout << str[i]; } return 0; }
//这个是第一道leetcode题吧 那天和吴同学长 种奇龙学长一起值班的时候开始做的 瞬间想出归并排序还是可以的 //其他的话 那天能想到类型转换导致一直不对多亏了寒假看的C++ primer // 52 ms 63.63% class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int nums1Size = nums1.size(); int nums2Size = nums2.size(); int * nums3 = new int[nums1Size+nums2Size+10]; int num1_index = 0; int num2_index = 0; int num3_index = 0; while(num1_index<nums1Size&&num2_index<nums2Size){ if(nums1[num1_index]<=nums2[num2_index]){ nums3[num3_index++] = nums1[num1_index++]; }else{ nums3[num3_index++] = nums2[num2_index++]; } } while(num1_index<nums1Size){ nums3[num3_index++] = nums1[num1_index++]; } while(num2_index<nums2Size){ nums3[num3_index++] = nums2[num2_index++]; } if(num3_index%2 != 0){ return nums3[num3_index/2]; }else{ double a = nums3[num3_index/2 - 1]; double b = nums3[num3_index/2]; double temp = (a+b)/2; return temp; } } };
/************************************************************************ * @project : sloth * @class : FontType * @version : v1.0.0 * @description : 存储着字体纹理和数据文件 * @author : Oscar Shen * @creat : 2017年2月27日21:30:07 * @revise : ************************************************************************ * Copyright @ OscarShen 2017. All rights reserved. ************************************************************************/ #pragma once #ifndef SLOTH_FONT_TYPE_HPP #define SLOTH_FONT_TYPE_HPP #include <sloth.h> namespace sloth { class TextMeshCreator; class TextMeshData; class GUIText; class FontType { private: unsigned int m_TexAtlas; std::shared_ptr<TextMeshCreator> m_Loader; public: /*********************************************************************** * @description : 初始化,存储着字体纹理和数据文件 * @author : Oscar Shen * @creat : 2017年2月27日21:22:59 ***********************************************************************/ FontType(unsigned int texAtlas, const std::string &fontFilePath); ~FontType() {} /*********************************************************************** * @description : 返回字体位图纹理 * @author : Oscar Shen * @creat : 2017年2月27日21:27:10 ***********************************************************************/ inline unsigned int getTextureAtlas() const { return m_TexAtlas; } /*********************************************************************** * @description : 加载指定的文本并产生片元数据 * @author : Oscar Shen * @creat : 2017年2月27日21:29:07 ***********************************************************************/ std::shared_ptr<TextMeshData> loadText(std::shared_ptr<GUIText> text); }; } #endif // !SLOTH_FONT_TYPE_HPP
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #ifdef _NATIVE_SSL_SUPPORT_ #ifdef _SSL_USE_PKCS11_ #include "modules/libssl/sslbase.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/pi/OpDLL.h" #include "modules/libssl/external/p11/p11_man.h" #include "modules/libssl/external/p11/p11_pubk.h" #include "modules/url/url_man.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #define PKCS11_MECH_RSA_FLAG (0x1<<0) #define PKCS11_MECH_DSA_FLAG (0x1<<1) #define PKCS11_MECH_RC2_FLAG (0x1<<2) #define PKCS11_MECH_RC4_FLAG (0x1<<3) #define PKCS11_MECH_DES_FLAG (0x1<<4) #define PKCS11_MECH_DH_FLAG (0x1<<5) #define PKCS11_MECH_SKIPJACK_FLAG (0x1<<6) #define PKCS11_MECH_RC5_FLAG (0x1<<7) #define PKCS11_MECH_SHA1_FLAG (0x1<<8) #define PKCS11_MECH_MD5_FLAG (0x1<<9) #define PKCS11_MECH_MD2_FLAG (0x1<<10) #define PKCS11_MECH_RANDOM_FLAG (0x1<<27) #define PKCS11_PUB_READABLE_CERT_FLAG (0x1<<28) #define PKCS11_DISABLE_FLAG (0x1<<30) class ES_RestartObject; PKCS_11_Manager::PKCS_11_Manager(OpDLL *driver) : p11_driver(driver), functions(NULL_PTR), certificate_login(TRUE) { } OP_STATUS PKCS_11_Manager::Init(uni_char **arguments, int max_args) { CK_C_GetFunctionList p11_getfuntion_list = NULL_PTR; CK_RV ret; // Arg 1 : type // Arg 2 : Name // Arg 3 : Mechanism_flags: Hexadecimal format /* From Netscape pkcs11.addmodule documentation PKCS11_MECH_RSA_FLAG = 0x1<<0; PKCS11_MECH_DSA_FLAG = 0x1<<1; PKCS11_MECH_RC2_FLAG = 0x1<<2; PKCS11_MECH_RC4_FLAG = 0x1<<3; PKCS11_MECH_DES_FLAG = 0x1<<4; PKCS11_MECH_DH_FLAG = 0x1<<5; //Diffie-Hellman PKCS11_MECH_SKIPJACK_FLAG = 0x1<<6; //SKIPJACK algorithm as in Fortezza cards PKCS11_MECH_RC5_FLAG = 0x1<<7; PKCS11_MECH_SHA1_FLAG = 0x1<<8; PKCS11_MECH_MD5_FLAG = 0x1<<9; PKCS11_MECH_MD2_FLAG = 0x1<<10; PKCS11_MECH_RANDOM_FLAG = 0x1<<27; //Random number generator PKCS11_PUB_READABLE_CERT_FLAG = 0x1<<28; //Stored certs can be read off the token w/o logging in PKCS11_DISABLE_FLAG = 0x1<<30; //tell Navigator to disable this slot by default Only PKCS11_PUB_READABLE_CERT_FLAG and PKCS11_DISABLE_FLAG is heeded at the moment */ if(arguments && max_args>=3) { if(arguments[2]) { unsigned long arg = uni_strtoul(arguments[2], NULL, 16); if(arg & PKCS11_DISABLE_FLAG) return OpSmartcardStatus::DISABLED_MODULE; if(arg & PKCS11_PUB_READABLE_CERT_FLAG) certificate_login = FALSE; } } if(!p11_driver) return OpStatus::ERR_NULL_POINTER; if(!p11_driver->IsLoaded()) return OpStatus::ERR; p11_getfuntion_list = (CK_C_GetFunctionList) p11_driver->GetSymbolAddress("C_GetFunctionList"); if(p11_getfuntion_list == NULL_PTR) return OpStatus::ERR_NULL_POINTER; ret = p11_getfuntion_list(&functions); if(ret != CKR_OK) return TranslateToOP_STATUS(ret); if(functions != NULL_PTR && functions->version.major != 2) return OpSmartcardStatus::UNSUPPORTED_VERSION; if(functions == NULL_PTR || functions->C_Initialize == NULL_PTR || functions->C_Finalize == NULL_PTR || functions->C_GetInfo == NULL_PTR || functions->C_GetSlotList == NULL_PTR || functions->C_GetSlotInfo == NULL_PTR || functions->C_GetTokenInfo == NULL_PTR || functions->C_GetMechanismList == NULL_PTR || functions->C_GetMechanismInfo == NULL_PTR || functions->C_OpenSession == NULL_PTR || functions->C_CloseSession == NULL_PTR || functions->C_GetSessionInfo == NULL_PTR || functions->C_Login == NULL_PTR || functions->C_Logout == NULL_PTR || functions->C_Encrypt == NULL_PTR || functions->C_Decrypt == NULL_PTR || functions->C_Sign == NULL_PTR || functions->C_Verify == NULL_PTR) { functions = NULL_PTR; return OpStatus::ERR_NULL_POINTER; } ret = functions->C_Initialize(NULL_PTR); if(ret != CKR_OK) { functions = NULL_PTR; return TranslateToOP_STATUS(ret); } return OpStatus::OK; } PKCS_11_Manager::~PKCS_11_Manager() { active_tokens.Clear(); temp_tokens.Clear(); OP_ASSERT(Get_Reference_Count() == 0); if(functions) functions->C_Finalize(NULL_PTR); if(p11_driver) { p11_driver->Unload(); OP_DELETE(p11_driver); } functions = NULL_PTR; } void PKCS_11_Manager::ConfirmCardsPresent() { PKCS_11_Token *next_token, *token; CK_RV status; CK_SLOT_ID slot=0; do{ status = functions->C_WaitForSlotEvent(CKF_DONT_BLOCK, &slot, NULL_PTR); if(status != CKR_OK) // CKR_NO_EVENT or ignored errors break; next_token = active_tokens.First(); while(next_token) { token = next_token; next_token = token->Suc(); if(token->GetSlot() == slot) { if(!token->CheckCardPresent()) { if(token->Get_Reference_Count() == 0) { token->Out(); OP_DELETE(token); } } break; } } } while(1); // loop until CKR_NO_EVENT next_token = active_tokens.First(); while(next_token) { token = next_token; next_token = token->Suc(); if(token->TimedOut()) { token->TerminateSession(); token->Out(); token->Into(&temp_tokens); } } next_token = temp_tokens.First(); while(next_token) { token = next_token; next_token = token->Suc(); if(token->Get_Reference_Count() == 0) { token->Out(); OP_DELETE(token); } } } OP_STATUS PKCS_11_Manager::GetAvailableCards(SSL_CertificateHandler_ListHead *cipherlist) { if(functions == NULL_PTR || cipherlist == NULL) return OpStatus::ERR_NULL_POINTER; CK_RV status; CK_ULONG slot_count=0; CK_SLOT_ID_PTR slots = NULL_PTR; ANCHOR_ARRAY(CK_SLOT_ID, slots); status = functions->C_GetSlotList(TRUE, NULL_PTR, &slot_count); RETURN_IF_ERROR(TranslateToOP_STATUS(status)); if(slot_count == 0) return OpStatus::OK; slots = OP_NEWA(CK_SLOT_ID, slot_count); if(slots == NULL) { g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); return OpStatus::ERR_NO_MEMORY; } status = functions->C_GetSlotList(TRUE, slots, &slot_count); if(status != CKR_OK) { return TranslateToOP_STATUS(status); } CK_ULONG i; for(i=0; i< slot_count; i++) { RETURN_IF_ERROR(GetAvailableCardsFromSlot(slots[i], cipherlist)); } ANCHOR_ARRAY_DELETE(slots); return OpStatus::OK; } OP_STATUS PKCS_11_Manager::GetAvailableCardsFromSlot(CK_SLOT_ID slot, SSL_CertificateHandler_ListHead *cipherlist) { CK_RV status; CK_ULONG method_count=0; CK_ULONG j; CK_MECHANISM_TYPE_PTR methods = NULL_PTR; ANCHOR_ARRAY(CK_MECHANISM_TYPE, methods); status = functions->C_GetMechanismList(slot, NULL_PTR, &method_count); RETURN_IF_ERROR(TranslateToOP_STATUS(status)); if(method_count == 0) return OpStatus::OK; methods = OP_NEWA(CK_MECHANISM_TYPE, method_count); if(methods == NULL) { g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); return OpStatus::ERR_NO_MEMORY; } status = functions->C_GetMechanismList(slot, methods, &method_count); RETURN_IF_ERROR(TranslateToOP_STATUS(status)); for(j = 0;j < method_count; j++) { CK_MECHANISM_TYPE current_method = methods[j]; if(current_method == CKM_RSA_PKCS) { RETURN_IF_ERROR(SetUpCardFromSlot(slot, cipherlist, SSL_RSA)); break; } } ANCHOR_ARRAY_DELETE(methods); return OpStatus::OK; } OP_STATUS PKCS_11_Manager::SetUpCardFromSlot(CK_SLOT_ID slot, SSL_CertificateHandler_ListHead *cipherlist, SSL_BulkCipherType ctyp) { CK_RV status; CK_TOKEN_INFO token_info; OpString16 label; OpString16 serial; SSL_ASN1Cert_list certificate; PKCS_11_Token *token = NULL; OpStackAutoPtr<SSL_PublicKeyCipher> key = NULL; status = functions->C_GetTokenInfo(slot, &token_info); RETURN_IF_ERROR(TranslateToOP_STATUS(status)); RETURN_IF_ERROR(label.SetFromUTF8((const char *) token_info.label, sizeof(token_info.label))); RETURN_IF_ERROR(serial.SetFromUTF8((const char *) token_info.serialNumber, sizeof(token_info.serialNumber))); token = active_tokens.FindToken(slot,label, serial); if(!token) token = temp_tokens.FindToken(slot, label, serial); if(!token) { OpStackAutoPtr<PKCS_11_Token> new_token = NULL; new_token.reset(OP_NEW(PKCS_11_Token, (this, functions, slot, ctyp))); if(!new_token.get()) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(new_token->Construct()); new_token->Into(&temp_tokens); token = new_token.release(); } certificate = token->GetCertificate(); if(certificate.Error()) return OpStatus::ERR; if(certificate.Count() == 0 || certificate[0].GetLength() == 0) return OpStatus::OK; key.reset(token->GetKey()); if(key.get() == NULL) return OpStatus::ERR_NO_MEMORY; if(key->Error()) return OpStatus::ERR; return SetupCertificateEntry(cipherlist, label, serial, certificate, key.release()); } OP_STATUS PKCS_11_Manager::TranslateToOP_STATUS(CK_RV val) const { return (val == CKR_OK ? OpStatus::OK : OpStatus::ERR); } BOOL PKCS_11_Manager::TranslateToSSL_Alert(CK_RV val, SSL_Alert &msg) const { switch(val) { case CKR_OK: msg.Set(SSL_NoError, SSL_No_Description); return FALSE; case CKR_PIN_INCORRECT: case CKR_PIN_INVALID: case CKR_PIN_LEN_RANGE: case CKR_PIN_EXPIRED: case CKR_PIN_LOCKED: msg.Set(SSL_Fatal, SSL_Bad_PIN); return TRUE; } msg.Set(SSL_Fatal, SSL_InternalError); return TRUE; } BOOL PKCS_11_Manager::TranslateToSSL_Alert(CK_RV val, SSL_Error_Status *msg) const { SSL_Alert code; if(!TranslateToSSL_Alert(val, code)) return FALSE; if(msg) msg->RaiseAlert(code); return TRUE; } void PKCS_11_Manager::ActivateToken(PKCS_11_Token *tokn) { if(!tokn) return; if(tokn->InList()) tokn->Out(); tokn->Into(&active_tokens); } SmartCard_Master *SmartCard_Manager::CreatePKCS11_MasterL(OpDLL *dll) { return OP_NEW_L(PKCS_11_Manager, (dll)); } PKCS_11_Token* PKCS_11_Token_Head::FindToken(CK_SLOT_ID slot, OpStringC &label, OpStringC &serial) { PKCS_11_Token *token = First(); while(token) { if(slot == token->GetSlot() && token->GetLabel().Compare(label) == 0 && token->GetSerialNumber().Compare(serial) == 0) break; token = token->Suc(); } return token; } PKCS_11_Token::PKCS_11_Token(PKCS_11_Manager *mstr, CK_FUNCTION_LIST_PTR func, CK_SLOT_ID slot, SSL_BulkCipherType ctype) : master(mstr), functions(func), slot_id(slot), ciphertype(ctype) { session = CK_INVALID_HANDLE; enabled = FALSE; logged_in = FALSE; need_login = TRUE; need_pin = TRUE; logged_in_time = 0; last_used = 0; confirmed_present = FALSE; } PKCS_11_Token::~PKCS_11_Token() { OP_ASSERT(Get_Reference_Count() == 0); CloseSession(); if(InList()) Out(); } OP_STATUS PKCS_11_Token::Construct() { CK_RV status; CK_TOKEN_INFO token_info; SSL_ASN1Cert_list certificate; OpStackAutoPtr<PKCS11_PublicKeyCipher> key = NULL; status = functions->C_GetTokenInfo(slot_id, &token_info); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); RETURN_IF_ERROR(label.SetFromUTF8((const char *) token_info.label, sizeof(token_info.label))); RETURN_IF_ERROR(serialnumber.SetFromUTF8((const char *) token_info.serialNumber, sizeof(token_info.serialNumber))); need_login = (token_info.flags & CKF_LOGIN_REQUIRED ? TRUE : FALSE); need_pin = (token_info.flags & CKF_PROTECTED_AUTHENTICATION_PATH? FALSE : TRUE); return GetCertificateFromToken(); } SSL_PublicKeyCipher *PKCS_11_Token::GetKey() { return OP_NEW(PKCS11_PublicKeyCipher, (master, this, functions, slot_id, ciphertype)); } void PKCS_11_Token::Activate() { master->ActivateToken(this); enabled = TRUE; } void PKCS_11_Token::UsedNow() { last_used = prefsManager->CurrentTime(); } BOOL PKCS_11_Token::TimedOut() { if(!enabled) return FALSE; time_t timeout = prefsManager->GetIntegerPrefDirect(PrefsManager::SmartCardTimeOutMinutes)*60; return (last_used && last_used + timeout >= prefsManager->CurrentTime() ? FALSE : TRUE); } BOOL PKCS_11_Token::CheckCardPresent() { if(!TimedOut() && IsTokenPresent()) return TRUE; TerminateSession(); return FALSE; } void PKCS_11_Token::TerminateSession() { enabled = FALSE; CloseSession(); // Disabled, as there is no connection to the actual use of a smartcard based SSL session // This will only disable the current session for the card, and any SSL sessions based on it //if(prefsManager->GetIntegerPrefDirect(PrefsManager::StrictSmartCardSecurityLevel)>0) // windowManager->CloseAllWindows(TRUE); // Invalidate Sessions for certificate, etc. urlManager->InvalidateSmartCardSessions(certificate); urlManager->CloseAllConnections(); } BOOL PKCS_11_Token::IsTokenPresent() { CK_RV status; CK_TOKEN_INFO token_info; OpString16 lbl; OpString16 srl; status = functions->C_GetTokenInfo(slot_id, &token_info); RETURN_VALUE_IF_ERROR(master->TranslateToOP_STATUS(status), FALSE); RETURN_VALUE_IF_ERROR(lbl.SetFromUTF8((const char *) token_info.label, sizeof(token_info.label)), FALSE); RETURN_VALUE_IF_ERROR(srl.SetFromUTF8((const char *) token_info.serialNumber, sizeof(token_info.serialNumber)), FALSE); if(label.Compare(lbl) != 0 || serialnumber.Compare(srl) != 0) return FALSE; return TRUE; } CK_RV PKCS_11_Token::Login(SSL_secure_varvector32 &password) { if(!CheckSession()) return CKR_FUNCTION_FAILED; if(!logged_in) { CK_RV status; status = functions->C_Login(session, CKU_USER, password.GetDirect(), password.GetLength()); if(status != CKR_OK) return status; logged_in = TRUE; logged_in_time = prefsManager->CurrentTime(); } return CKR_OK; } BOOL PKCS_11_Token::LoggedIn() { if(!logged_in || session == CK_INVALID_HANDLE) return FALSE; CK_RV status; CK_SESSION_INFO info; status = functions->C_GetSessionInfo(session, &info); if(OpStatus::IsError(master->TranslateToOP_STATUS(status))) return FALSE; if(info.state == CKS_RO_USER_FUNCTIONS || info.state == CKS_RW_USER_FUNCTIONS || info.state == CKS_RW_SO_FUNCTIONS) return TRUE; return FALSE; } BOOL PKCS_11_Token::CheckSession() { CK_RV status; status = CreateSession(&session); RETURN_VALUE_IF_ERROR(master->TranslateToOP_STATUS(status), FALSE); return TRUE; } CK_RV PKCS_11_Token::CreateSession(CK_SESSION_HANDLE_PTR session_ptr) const { CK_RV status; if(master == NULL || functions == NULL_PTR) return CKR_GENERAL_ERROR; if(*session_ptr != CK_INVALID_HANDLE) return CKR_OK; status = functions->C_OpenSession(slot_id, CKF_SERIAL_SESSION, NULL_PTR, (CK_NOTIFY) NULL_PTR, session_ptr); return status; } void PKCS_11_Token::CloseSession() { if(logged_in) { CK_RV status; status = functions->C_Logout(session); // Ignore status; logged_in = FALSE; } CloseSession(&session); } void PKCS_11_Token::CloseSession(CK_SESSION_HANDLE_PTR session_ptr) const { CK_RV status; if(master == NULL || functions == NULL_PTR) return; if(*session_ptr != CK_INVALID_HANDLE) return; status = functions->C_CloseSession(*session_ptr); // ignore error code *session_ptr = CK_INVALID_HANDLE; } OP_STATUS PKCS_11_Token::GetCertificateFromToken() { CK_RV status; CK_CERTIFICATE_TYPE cert_type; CK_ULONG cert_object_type = CKO_CERTIFICATE; //CK_ULONG key_class, key_alg; //CK_BBOOL key_signflag, key_signrflag; CK_ATTRIBUTE search_for[] = { {CKA_CLASS, &cert_object_type, sizeof(cert_object_type)} }; CK_ATTRIBUTE get_type[] = { {CKA_CERTIFICATE_TYPE, &cert_type, sizeof(CK_CERTIFICATE_TYPE)} }; CK_ATTRIBUTE certificate_value[] = { {CKA_VALUE, NULL_PTR, 0} }; /* CK_ATTRIBUTE key_att[] = { {CKA_CLASS, &key_class, sizeof(key_class)}, {CKA_KEY_TYPE, &key_alg, sizeof(key_alg)} }; CK_ATTRIBUTE key_flags[] = { {CKA_SIGN, &key_signflag, sizeof(key_signflag)}, {CKA_SIGN_RECOVER, &key_signrflag, sizeof(key_signrflag)} }; */ //CK_OBJECT_HANDLE key = CK_INVALID_HANDLE; CK_OBJECT_HANDLE object = CK_INVALID_HANDLE; CK_ULONG object_count=0; //CK_ULONG key_count=0; if(!CheckSession()) return OpStatus::ERR; if(master->MustLoginForCertificate() && NeedLogIn()) { SSL_secure_varvector32 password; #define MSG_SECURE_ASK_PINCODE Str::SI_MSG_SECURE_ASK_PASSWORD if(!NeedPin() || AskPassword(MSG_SECURE_ASK_PINCODE, password, SSL_present_hwnd)) { RETURN_IF_ERROR(Login(password)); } } /* key_class = CKO_PRIVATE_KEY; key_alg = CKK_RSA; status = functions->C_FindObjectsInit(session, key_att, ARRAY_SIZE(key_att)); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); status = functions->C_FindObjects(session, &key, 1, &key_count); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); if(key_count == 0) return OpStatus::OK; key_signflag = FALSE; key_signrflag = FALSE; status = functions->C_GetAttributeValue(session, key, key_flags, ARRAY_SIZE(key_flags)); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); status = functions->C_FindObjectsFinal(session); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); if(!key_signflag) return OpStatus::OK; */ status = functions->C_FindObjectsInit(session, search_for, ARRAY_SIZE(search_for)); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); do{ status = functions->C_FindObjects(session, &object, 1, &object_count); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); if(object_count) { status = functions->C_GetAttributeValue(session, object, get_type, 1); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); if(cert_type != CKC_X_509 && cert_type != CKC_X_509_ATTR_CERT) continue; // Do not handle unsupported certificates status = functions->C_GetAttributeValue(session, object, certificate_value, 1); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); if(((CK_LONG) certificate_value[0].ulValueLen) == -1 || certificate_value[0].ulValueLen ==0) continue; certificate.Resize(1); if(certificate.Error()) return OpStatus::ERR; certificate[0].Resize(certificate_value[0].ulValueLen); if(certificate.Error()) return OpStatus::ERR; certificate_value[0].pValue = certificate[0].GetDirect(); certificate_value[0].ulValueLen = certificate[0].GetLength(); status = functions->C_GetAttributeValue(session, object, certificate_value, 1); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); break; } }while(object_count); status = functions->C_FindObjectsFinal(session); RETURN_IF_ERROR(master->TranslateToOP_STATUS(status)); return OpStatus::OK; } OP_STATUS PKCS11_AddModuleL(OpString &Module_name, OpString &DLL_path, unsigned long methods, unsigned long ciphers #ifdef SMC_ES_THREAD , ES_RestartObject* restartobject #endif ) { if(Module_name.IsEmpty() || DLL_path.IsEmpty()) return OpStatus::ERR; if(DLL_path.FindFirstOf(',') != KNotFound) return OpStatus::ERR; OpString value; ANCHOR(OpString,value); OpString ininame; ANCHOR(OpString,ininame); RETURN_IF_ERROR(prefsManager->GetSmartCardDriverL(Module_name, value)); if(!value.IsEmpty()) return OpStatus::OK; Install_PKCS(NULL, DLL_path, #ifdef SMC_ES_THREAD restartobject, #endif methods, ciphers, &Module_name); return OpStatus::OK; } OP_STATUS PKCS11_AddModule(OpString &Module_name, OpString &DLL_path, unsigned long methods, unsigned long ciphers #ifdef SMC_ES_THREAD , ES_RestartObject* restartobject #endif ) { OP_STATUS op_err = OpStatus::OK; #ifdef SMC_ES_THREAD TRAP(op_err, op_err = PKCS11_AddModuleL(Module_name, DLL_path, methods, ciphers, restartobject)) #else TRAP(op_err, op_err = PKCS11_AddModuleL(Module_name, DLL_path, methods, ciphers)); #endif return op_err; } OP_STATUS PKCS11_DeleteModuleL(OpString &Module_name #ifdef SMC_ES_THREAD , ES_RestartObject* restartobject #endif ) { if(Module_name.IsEmpty()) return OpStatus::ERR; OpString value; ANCHOR(OpString,value); OpString ininame; ANCHOR(OpString,ininame); RETURN_IF_ERROR(prefsManager->GetSmartCardDriverL(Module_name, value)); if(value.IsEmpty()) return OpStatus::OK; int i = value.FindFirstOf(','); if(i != KNotFound) value.Delete(i); Uninstall_PKCS(NULL, value, #ifdef SMC_ES_THREAD restartobject, #endif &Module_name); return OpStatus::OK; } OP_STATUS PKCS11_DeleteModule(OpString &Module_name #ifdef SMC_ES_THREAD , ES_RestartObject* restartobject #endif ) { OP_STATUS op_err = OpStatus::OK; #ifdef SMC_ES_THREAD TRAP(op_err, op_err = PKCS11_DeleteModuleL(Module_name, restartobject)); #else TRAP(op_err, op_err = PKCS11_DeleteModuleL(Module_name)); #endif return op_err; } #endif void SSL_ExternalKeyManager::SetUpMasterL(OpStringC type, OpStringC path, uni_char **arguments, int max_args) { #if defined(_SSL_USE_PKCS11_) OpStackAutoPtr<OpDLL> dll = NULL; OpStackAutoPtr<SmartCard_Master > driver = NULL; OpDLL *temp_dll=NULL; LEAVE_IF_ERROR(g_factory->CreateOpDLL(&temp_dll)); dll.reset(temp_dll); temp_dll = NULL; LEAVE_IF_ERROR(dll->Load(path)); OP_ASSERT(dll->IsLoaded()); #ifdef _SSL_USE_PKCS11_ if(type.CompareI(UNI_L("CryptoKi")) == 0 || type.CompareI(UNI_L("pkcs11")) == 0 ) { driver.reset(CreatePKCS11_MasterL(dll.get())); } #endif if(driver.get() != NULL) { dll.release(); OP_STATUS op_err = driver->Init(arguments, max_args); if(op_err == OpSmartcardStatus::UNSUPPORTED_VERSION) { driver.reset(); // Unsupported version: Delete it. return; } else if(OpStatus::IsError(op_err)) LEAVE(op_err); driver->Into(&smartcard_masters); driver.release(); } dll.reset(); driver.reset(); #endif } #if defined(_SSL_USE_PKCS11_) OpString key, value; ANCHOR(OpString,key); ANCHOR(OpString,value); BOOL first = TRUE; const int TOKENS_ON_A_LINE = 4; // # of tokens on a line in the ini-file int tokens; uni_char* tokenArr[TOKENS_ON_A_LINE]; OpString ininame; ANCHOR(OpString,ininame); while(prefsManager->ReadSmartCardDriversL(key, value, op_err, first)) { if(OpStatus::IsError(op_err)) return op_err; first = FALSE; if(key.IsEmpty() || value.IsEmpty()) continue; // format of section name=dll-path,api, [apispecific attributes] // API: one of CryptoKi, pkcs11 // Commas are not allowed in the dll-path tokens = GetStrTokens(value.CStr(), UNI_L(","), UNI_L("\" \t"), tokenArr, TOKENS_ON_A_LINE); TRAP(op_err, SetUpMasterL(tokenArr[1], tokenArr[0], tokenArr, tokens)); if(op_err != OpSmartcardStatus::DISABLED_MODULE && OpStatus::IsError(op_err)) { return op_err; } } //TRAP_AND_RETURN(op_err, SetUpMasterL(UNI_L("CryptoKi"), UNI_L("C:\\WinNT\\system32\\SmartP11.dll"))); #endif #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Tomasz Gólczyński */ #ifndef QUICK_COMPOSE_EDIT_H #define QUICK_COMPOSE_EDIT_H #include "adjunct/quick_toolkit/widgets/QuickTextWidget.h" #include "adjunct/quick/widgets/OpComposeEdit.h" class QuickComposeEdit: public QuickEditableTextWidgetWrapper<OpComposeEdit> { IMPLEMENT_TYPEDOBJECT(QuickEditableTextWidgetWrapper<OpComposeEdit>); }; #endif//QUICK_COMPOSE_EDIT_H
#include "Statement.h" Statement::Statement() { Var=new Variable; Var->name=""; Var->value=0; Var->repeat=1; ID=0; Text = ""; Comment=""; StatType="None"; Selected = false; } void Statement::SetSelected(bool s) { Selected = s; } bool Statement::IsSelected() const { return Selected; } string Statement::GetStatType() { return StatType; } void Statement::SetID(int I) { ID=I; } int Statement:: GetID() { return ID; } void Statement::AddComment(string C) { Comment= C; } string Statement::GetComment() { return Comment; } bool Statement::CheckVar(string t) { if(((int)t[0]>=65&&(int)t[0]<=90)||((int)t[0]>=97&&(int)t[0]<=122)) { for(int i=1;i<t.length();i++) if((int)t[i]<48||((int)t[i]>57&&(int)t[i]<65)||((int)t[i]>90&&(int)t[i]<97)||(int)t[i]>122) return false; return true; } return false; } bool Statement::CheckVal(string Str) { int count=0; for(int i=0;i<Str.length();i++) if(Str[i]=='.') count++; if(count>1) return false; for(int i=0;i<Str.length();i++) if(((int)Str[i]<48||(int)Str[i]>57)&&Str[i]!='.') return false; return true; } void Statement::PrintInfo(Output *pOut) { pOut->PrintMessage(Text + " // " + Comment ); } void Statement::UpdateStatementText() { return ; } void Statement::Resize(char R) { return ; } Statement* Statement::Copy(Point P) { return NULL; } void Statement::setVar(Variable *V,int i) { Var=V; } Variable* Statement::getVar(int i) { return Var ; } void Statement::Simulate(Output *pOut,Input *pIn) { return; }
//entry.hpp //Entry point for the program. //Created by Lewis Hosie //16-11-11 void killprogram();
#include <iostream> #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include "TFile.h" #include "TTree.h" #include "TH1.h" #include "TH2.h" #include "TGraph.h" #include "TGraphAsymmErrors.h" #include "TVectorT.h" #include "Nuclear_Info.h" #include "fiducials.h" #include "helpers.h" #include "AccMap.h" using namespace std; const double pmiss_cut=0.4; const double acc_thresh=0.8; int main(int argc, char ** argv) { if (argc != 5) { cerr << "Wrong number of arguments. Instead try:\n" << " make_hists /path/to/1p/file /path/to/2p/file /path/to/map/file /path/to/output/file\n\n"; exit(-1); } TFile * f1p = new TFile(argv[1]); TFile * f2p = new TFile(argv[2]); TFile * fo = new TFile(argv[4],"RECREATE"); // We'll need to get acceptance maps in order to do a fiducial cut on minimum acceptance AccMap proton_map(argv[3], "p"); TGraph * lead_fail = new TGraph(); lead_fail->SetNameTitle("lead_fail","lead_fail"); TGraph * lead_pass = new TGraph(); lead_pass->SetNameTitle("lead_pass","lead_pass"); TGraph * rec_fail = new TGraph(); rec_fail->SetNameTitle("rec_fail","rec_fail"); TGraph * rec_pass = new TGraph(); rec_pass->SetNameTitle("rec_pass","rec_pass"); TGraph * ep_theta_p_fail = new TGraph(); ep_theta_p_fail->SetNameTitle("ep_theta_p_fail","ep_theta_p_fail"); TGraph * ep_theta_p_pass = new TGraph(); ep_theta_p_pass->SetNameTitle("ep_theta_p_pass","ep_theta_p_pass"); TGraph * epp_theta_p_fail = new TGraph(); epp_theta_p_fail->SetNameTitle("epp_theta_p_fail","epp_theta_p_fail"); TGraph * epp_theta_p_pass = new TGraph(); epp_theta_p_pass->SetNameTitle("epp_theta_p_pass","epp_theta_p_pass"); TGraph * epp_theta_p_fail_rec = new TGraph(); epp_theta_p_fail_rec->SetNameTitle("epp_theta_p_fail_rec","epp_theta_p_fail_rec"); TGraph * epp_theta_p_pass_rec = new TGraph(); epp_theta_p_pass_rec->SetNameTitle("epp_theta_p_pass_rec","epp_theta_p_pass_rec"); TH1D * ep_pmiss = new TH1D("ep_pmiss","ep;pmiss;Counts",6,0.4,1.0); TH1D * epp_pmiss = new TH1D("epp_pmiss","epp;pmiss;Counts",6,0.4,1.0); ep_pmiss->Sumw2(); epp_pmiss->Sumw2(); // Loop over 1p tree cerr << " Looping over 1p tree...\n"; TTree * t1p = (TTree*)f1p->Get("T"); Float_t Xb, Q2, Pmiss_size[2], Pp[2][3], Rp[2][3], Pp_size[2], Pmiss_q_angle[2], Pe[3], q[3]; Double_t weight = 1.; t1p->SetBranchAddress("Pmiss_q_angle",Pmiss_q_angle); t1p->SetBranchAddress("Xb",&Xb); t1p->SetBranchAddress("Q2",&Q2); t1p->SetBranchAddress("Pmiss_size",Pmiss_size); t1p->SetBranchAddress("Pp_size",Pp_size); t1p->SetBranchAddress("Rp",Rp); t1p->SetBranchAddress("Pp",Pp); t1p->SetBranchAddress("Pe",Pe); t1p->SetBranchAddress("q",q); // See if there is a weight branch TBranch * weight_branch = t1p->GetBranch("weight"); if (weight_branch) { t1p->SetBranchAddress("weight",&weight); } for (int event =0 ; event < t1p->GetEntries() ; event++) { t1p->GetEvent(event); // Do necessary cuts if (fabs(Rp[0][2]+22.25)>2.25) continue; if (Pp_size[0]>2.4) continue; if (Pmiss_size[0]<pmiss_cut) continue; // Apply fiducial cuts TVector3 ve(Pe[0],Pe[1],Pe[2]); if (!accept_electron(ve)) continue; TVector3 vp(Pp[0][0],Pp[0][1],Pp[0][2]); double phi1_deg = vp.Phi() * 180./M_PI; if (phi1_deg < -30.) phi1_deg += 360.; double theta1_deg = vp.Theta() * 180./M_PI; if (!accept_proton(vp)) { lead_fail->SetPoint(lead_fail->GetN(),theta1_deg,phi1_deg); ep_theta_p_fail->SetPoint(ep_theta_p_fail->GetN(),theta1_deg,vp.Mag()); continue; } lead_pass->SetPoint(lead_pass->GetN(),theta1_deg,phi1_deg); ep_theta_p_pass->SetPoint(ep_theta_p_pass->GetN(),theta1_deg,vp.Mag()); if ( proton_map.accept(vp) > acc_thresh ) ep_pmiss->Fill(Pmiss_size[0]); } // Loop over 2p tree cerr << " Looping over 2p tree...\n"; TTree * t2p = (TTree*)f2p->Get("T"); t2p->SetBranchAddress("Pmiss_q_angle",Pmiss_q_angle); t2p->SetBranchAddress("Xb",&Xb); t2p->SetBranchAddress("Q2",&Q2); t2p->SetBranchAddress("Pmiss_size",Pmiss_size); t2p->SetBranchAddress("Pp_size",Pp_size); t2p->SetBranchAddress("Rp",Rp); t2p->SetBranchAddress("Pp",Pp); t2p->SetBranchAddress("Pe",Pe); t2p->SetBranchAddress("q",q); // See if there is a weight branch weight=1.; weight_branch = t2p->GetBranch("weight"); if (weight_branch) { t2p->SetBranchAddress("weight",&weight); } for (int event =0 ; event < t2p->GetEntries() ; event++) { t2p->GetEvent(event); // Do necessary cuts if (fabs(Rp[0][2]+22.25)>2.25) continue; if (Pp_size[0]>2.4) continue; if (Pmiss_size[0]<pmiss_cut) continue; // Apply fiducial cuts TVector3 ve(Pe[0],Pe[1],Pe[2]); if (!accept_electron(ve)) continue; TVector3 vlead(Pp[0][0],Pp[0][1],Pp[0][2]); double phi1_deg = vlead.Phi() * 180./M_PI; if (phi1_deg < -30.) phi1_deg += 360.; double theta1_deg = vlead.Theta() * 180./M_PI; if (!accept_proton(vlead)) { lead_fail->SetPoint(lead_fail->GetN(),theta1_deg,phi1_deg); epp_theta_p_fail->SetPoint(epp_theta_p_fail->GetN(),theta1_deg,vlead.Mag()); continue; } lead_pass->SetPoint(lead_pass->GetN(),theta1_deg,phi1_deg); epp_theta_p_pass->SetPoint(epp_theta_p_pass->GetN(),theta1_deg,vlead.Mag()); if ( proton_map.accept(vlead) > acc_thresh ) { ep_pmiss->Fill(Pmiss_size[0]); } // Make a check on the recoils if (fabs(Rp[1][2]+22.25)>2.25) continue; if (Pp_size[1] < 0.35) continue; TVector3 vrec(Pp[1][0],Pp[1][1],Pp[1][2]); double phi2_deg = vrec.Phi() * 180./M_PI; if (phi2_deg < -30.) phi2_deg += 360.; int sector2 = clas_sector(phi2_deg); double theta2_deg = vrec.Theta() * 180./M_PI; if (!accept_proton(vrec)) { rec_fail->SetPoint(rec_fail->GetN(),theta2_deg,phi2_deg); epp_theta_p_fail_rec->SetPoint(epp_theta_p_fail_rec->GetN(),theta2_deg,vrec.Mag()); continue; } rec_pass->SetPoint(rec_pass->GetN(),theta2_deg,phi2_deg); epp_theta_p_pass_rec->SetPoint(epp_theta_p_pass_rec->GetN(),theta2_deg,vrec.Mag()); if ( proton_map.accept(vlead) > acc_thresh and proton_map.accept(vrec) > acc_thresh ) { epp_pmiss->Fill(Pmiss_size[0]); } } f1p->Close(); f2p->Close(); // Write out fo -> cd(); lead_fail->Write(); lead_pass->Write(); rec_fail->Write(); rec_pass->Write(); ep_theta_p_fail->Write(); ep_theta_p_pass->Write(); epp_theta_p_fail->Write(); epp_theta_p_pass->Write(); epp_theta_p_fail_rec->Write(); epp_theta_p_pass_rec->Write(); ep_pmiss->Write(); epp_pmiss->Write(); fo->Close(); cerr << "The ep and epp integrals are: " << ep_pmiss->Integral() << " " << epp_pmiss->Integral() << "\n"; return 0; }
#include "scrollinterfacemagicmissile.h" #include "scroll.h" ScrollInterfaceMagicMissile::ScrollInterfaceMagicMissile() {}
#pragma once #include <iostream> #include <string> #include <sstream> #include <ostream> /** * Class stores pupil details */ class Student { private: // Instance variables std::string name; int age; int attendance; float gpa; std::string comment; public: Student(std::string name, int age, int attendance, float gpa, std::string comment); // parameterised constructor Student(); // Default constructor ~Student(); // Destructor // Getters and setters are inlined to allow compiler // Getter methods are set to const to stop changes made to getters // as we use our setters to modify our instance variables inline std::string get_name() const { return name; } inline int get_age() const { return age; } inline int get_attendance() const { return attendance; } inline float get_gpa() const { return gpa; } inline std::string get_comment() const { return comment; } // inline methods tell the compiler to use the code in the body of the method // instead of calling the method, for one line methods this can use less overhead // Depending on what compiler is used inline void set_name(std::string name) { this->name = name; } inline void set_age(int age) { this->age = age; } inline void set_attendance(int attendance) { this->attendance = attendance; } inline void set_gpa(float gpa) { this->gpa = gpa; } inline void set_comment(std::string comment) { this->comment = comment; } // Returns student string in HTML tags (used for webpage function in Student_Store) std::string to_html(); // Overridden operators, implementation is in 'Student.cpp' // friend keyword is used to allow implementation access to private members of Student.h friend std::ostream& operator<<(std::ostream& output_stream, const Student& s); friend std::istream& operator>>(std::istream& input_stream, Student& s); friend bool operator<(const Student& s1, const Student& s2); friend float operator+=(float& x,Student& s); };
#include <iostream> #include <vector> #include <queue> #include <fstream> using namespace std; const long long N = INT_MAX; int main() { ifstream fin("salesman.in"); ofstream fout("salesman.out"); int n, m; fin >> n >> m; vector<vector<int>> d(1 << n, vector<int>(n, -1)); vector<vector<int>> w(n, vector<int>(n, -1)); for (int i = 0; i < m; i++) { int a, b, wg; fin >> a >> b >> wg; w[a - 1][b - 1] = wg; w[b - 1][a - 1] = wg; } for (int i = 0; i < n; i++) { d[1 << i][i] = 0; } queue<pair<int, int>> q; int mask, ind; q.push(make_pair(0, -1)); while (!q.empty()) { mask = q.front().first; ind = q.front().second + 1; for (int j = 0; j < n; j++) { if (mask & (1 << j)) { int b = mask ^(1 << j); int mini = INT_MAX; for (int k = 0; k < n; k++) { if (b & (1 << k) && w[k][j] != -1 && d[b][k] != -1) { mini = min(mini, d[b][k] + w[k][j]); } } if (mini != INT_MAX) d[mask][j] = mini; } } for (; ind < n; ind++) { q.push(make_pair(mask | (1 << ind), ind)); } q.pop(); } int p = INT_MAX; for (int i = 0; i < n; i++) { if (d[(1 << n) - 1][i] != -1) { p = min(p, d[(1 << n) - 1][i]); } } if (p == INT_MAX) { fout << -1; } else { fout << p << endl; } return 0; }
#include<iostream> #include<list> #include<vector> #include<map> #include<utility> #include<cmath> #include <algorithm> #include <cstdlib> /* 亂數相關函數 */ #include <ctime> /* 時間相關函數 */ #include"AStar.h" using namespace std; int point::dist(const point &T) { return 10 * sqrt(pow((T.x - x), 2) + pow((T.y - y), 2)); } void point::SetF(int f_){ f = f_; } void point::SetG(int g_){ g = g_; } void point::SetH(int h_){ h = h_; } void Map::init(int row, int col) { this->row = row; this->col = col; for(int i = 0; i < row; ++i) { for(int j = 0; j < col; ++j) array_row.emplace_back(i, j, 99999, 99999, 0, 0); M.push_back(array_row); array_row.clear(); } } void Map::G(point &now, point &start) { now.g = start.g + now.dist(start); } void Map::H(point &now, point &end) { now.h = now.h + end.dist(now); } void Map::obstacle(point &obs) { M[obs.x][obs.y].obstacle = 1; } void AStar::initialize() { start_pt = point(2, 2); goal = point(20,60); MAP.init(30, 70); } void AStar::initialize(int x, int y) { start_pt = point(x, y); goal = point(45,45); MAP.init(50, 50); } bool AStar::cmp_f(const point &a, const point &b) { return a.f < b.f; } void AStar::start() { MAP.M[2][2].SetG(0); MAP.M[2][2].SetH(goal.dist(current)); MAP.M[2][2].SetF(goal.dist(current)); start_pt = MAP.M[2][2]; openlist.push_back(start_pt); while(!openlist.empty()) { current = openlist.front(); //find smallest f value for(auto &i:openlist) { if(i.f < current.f) current = i; } if(current == goal) { finish(); //reconstruct path return; } openlist.erase(find(openlist.begin(), openlist.end(), current)); closelist.push_back(current); // print(current); steps++; int tmp; list<point>::iterator it; for(int x = current.x-1; x<=current.x+1; ++x) { for(int y = current.y-1; y<=current.y+1; ++y) { if(x<=0 || y<=0 || x>=MAP.row-1 || y>=MAP.col-1)// edge detect continue; it = find(closelist.begin(), closelist.end(), MAP.M[x][y]); if(it != closelist.end()) continue;// Ignore the neighbor which is already evaluated(or obstacle). tmp = current.g + MAP.M[x][y].dist(current); it = find(openlist.begin(), openlist.end(), MAP.M[x][y]); if(it == openlist.end()) //not in openlist { openlist.push_back(MAP.M[x][y]); } else if(tmp > MAP.M[x][y].g) continue; // MAP.M[x][y].prev = &current; cameFrom.insert(pair<point, point>(current, MAP.M[x][y])); //(key, next->value) MAP.M[x][y].g = tmp; MAP.M[x][y].h = MAP.M[x][y].dist(goal); MAP.M[x][y].f = MAP.M[x][y].g + MAP.M[x][y].h; } } } } void AStar::finish() { vector<vector<int>> B(MAP.row, vector<int>(MAP.col, 0)); iter = cameFrom.end(); while(iter!=cameFrom.begin()) { if(iter->second == current) { cout << iter->second.x << "\t" << iter->second.y << endl; current = iter->first; total_path.push_back(current); } iter--; } /* int count = 0; while(current.prev != NULL) { count++; B[current.prev->x][current.prev->y] = 1; cout << "step " << count << ": " << "X-> " << current.prev->x << "\tY-> " << current.prev->y <<endl; } */ for(auto &i:total_path) { B[i.x][i.y] = 1; } cout << "\nReach target after " << steps << "searches\n\n"; for(int i=0; i<MAP.row; ++i) { for(int j = 0; j<MAP.col; ++j) { if(MAP.M[i][j].obstacle) cout << "#"; else if(MAP.M[i][j] == start_pt) cout << "X"; else if(MAP.M[i][j] == goal) cout << "!"; else if(B[i][j]) cout << 1; else cout << " "; } cout << endl; } } void AStar::obs_setup(point &pt) { MAP.obstacle(pt); closelist.push_back(pt); } void AStar::print(const point &pt) { cout << "X: " << pt.x << "\tY: " << pt.y << "\tf: " << pt.f << "\tg: " << pt.g << "\th: " << pt.h <<"\tObs: " << pt.obstacle << endl; } void AStar::print_obs() { for(int i=0; i<MAP.M.size(); ++i) { for(int j=0; j<MAP.M[0].size(); ++j) cout << MAP.M[i][j].obstacle; cout << endl; } cout << "\n\n"; } int main() { AStar S; S.initialize(); srand( time(NULL) ); for(int i=0; i<29; ++i) { int x = rand() % 100; point a(i,x); S.obs_setup(a); } for(int i=0; i<10; ++i) { point a(i,3); S.obs_setup(a); } point b(4,4); point c(5,4); S.obs_setup(b); S.obs_setup(c); // S.print_obs(); S.start(); return 0; }
#include "bricks/audio/ffmpegaudiodecoder.h" #if BRICKS_CONFIG_AUDIO_FFMPEG #include "bricks/core/exception.h" extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> } using namespace Bricks; using namespace Bricks::IO; using namespace Bricks::Audio; namespace Bricks { namespace Audio { FFmpegAudioDecoder::FFmpegAudioDecoder(FFmpegDecoder* decoder) : decoder(decoder) { Initialize(); } FFmpegAudioDecoder::FFmpegAudioDecoder(Stream* ioStream) : decoder(autonew FFmpegDecoder(ioStream)) { Initialize(); } void FFmpegAudioDecoder::Initialize() { AVFormatContext* format = decoder->GetFormatContext(); for (streamIndex = 0; streamIndex < format->nb_streams; streamIndex++) { stream = format->streams[streamIndex]; if (!stream) continue; if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) break; } if (streamIndex >= format->nb_streams) BRICKS_FEATURE_THROW(FormatException()); codec = decoder->OpenStream(streamIndex); channels = stream->codec->channels; samplerate = stream->codec->sample_rate; if (stream->duration < 0) samples = INT64_MAX; else samples = stream->time_base.num * stream->duration * samplerate / stream->time_base.den; bufferSize = 129000; buffer = av_malloc(bufferSize); cache = av_malloc(bufferSize); cacheLength = 0; // TODO: Handle stream->codec->sample_fmt } FFmpegAudioDecoder::~FFmpegAudioDecoder() { av_free(cache); av_free(buffer); } void FFmpegAudioDecoder::Seek(s64 sample) { decoder->SeekFrame(av_rescale(sample, stream->time_base.den, stream->time_base.num) / samplerate); cacheLength = 0; AudioCodec<s16>::Seek(sample); } int FFmpegAudioDecoder::ReadCache(AudioBuffer<s16>& buffer, int count, int offset) { count = Math::Min((size_t)count, cacheLength / sizeof(AudioBuffer<s16>::AudioSample) / channels); buffer.DeinterlaceFrom((AudioBuffer<s16>::AudioSample*)cache, count, offset); cacheLength -= sizeof(AudioBuffer<s16>::AudioSample) * channels * count; memmove(cache, (u8*)cache + sizeof(AudioBuffer<s16>::AudioSample) * channels * count, cacheLength); return count; } u32 FFmpegAudioDecoder::Read(AudioBuffer<s16>& buffer, u32 count, u32 boffset) { int offset = ReadCache(buffer, count, boffset); count -= offset; while (count > 0) { AVPacket originalPacket; if (!decoder->ReadPacket(&originalPacket, streamIndex)) break; AVPacket packet = originalPacket; cacheLength = 0; while (packet.size > 0) { int datasize = bufferSize; int used = avcodec_decode_audio3(stream->codec, (s16*)this->buffer, &datasize, &packet); if (used < 0) break; packet.size -= used; packet.data += used; if (datasize <= 0) break; int read = Math::Min((u32)datasize, count * 2 * channels); int left = datasize - read; if (read > 0) { int samples = read / sizeof(AudioBuffer<s16>::AudioSample) / channels; buffer.DeinterlaceFrom((AudioBuffer<s16>::AudioSample*)this->buffer, samples, boffset + offset); offset += samples; count -= samples; } if (left > 0) { memcpy((u8*)cache + cacheLength, (u8*)this->buffer + read, left); cacheLength += left; } } decoder->FreePacket(&originalPacket); } AudioCodec<s16>::Read(buffer, offset); return offset; } } } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Adam Minchinton and Karianne Ekern */ #include "core/pch.h" #ifdef SUPPORT_DATA_SYNC #include "adjunct/quick/dialogs/SyncMainUserSwitchDialog.h" #include "adjunct/quick/managers/SyncManager.h" #include "adjunct/quick_toolkit/widgets/OpLabel.h" ////////////////////////////////////////////////////////////////////////////////////////////////// SyncMainUserSwitchDialog::SyncMainUserSwitchDialog(BOOL *ok) { m_ok = ok; // Force default it to FALSE; *m_ok = FALSE; } ////////////////////////////////////////////////////////////////////////////////////////////////// SyncMainUserSwitchDialog::~SyncMainUserSwitchDialog() { } ////////////////////////////////////////////////////////////////////////////////////////////////// void SyncMainUserSwitchDialog::OnInit() { // Make the text a label OpLabel* label_sync = (OpLabel*)GetWidgetByName("label_text"); if (label_sync) label_sync->SetWrap(TRUE); } ////////////////////////////////////////////////////////////////////////////////////////////////// BOOL SyncMainUserSwitchDialog::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_GET_ACTION_STATE: { OpInputAction* child_action = action->GetChildAction(); switch (child_action->GetAction()) { case OpInputAction::ACTION_OK: case OpInputAction::ACTION_CANCEL: { // I'm not really sure why this is necessary, but I need to explicitly set // the action state to TRUE to make sure the OK/Cancel buttons are always enabled child_action->SetEnabled(TRUE); return TRUE; } } break; } } return Dialog::OnInputAction(action); } ////////////////////////////////////////////////////////////////////////////////////////////////// UINT32 SyncMainUserSwitchDialog::OnOk() { // Set OK to true *m_ok = TRUE; return 0; } #endif // SUPPORT_DATA_SYNC
/******************************************************/ // THIS IS A GENERATED FILE - DO NOT EDIT // /******************************************************/ #include "Particle.h" #line 1 "/Users/jcarouth/projects/personal/particle-counter/src/particle-counter.ino" /* * Project particle-counter * Description: * Author: * Date: */ #include "Grove_ChainableLED.h" #include "Grove_4Digit_Display.h" void setup(); void loop(); #line 10 "/Users/jcarouth/projects/personal/particle-counter/src/particle-counter.ino" int pinButton = D2; int pinLed = D7; ChainableLED leds(A4, A5, 1); TM1637 tm1637(D4, D5); int pushCount = 9990; int currentState = 0; int lastState = 0; void setup() { pinMode(pinButton, INPUT); pinMode(pinLed, OUTPUT); leds.init(); leds.setColorHSB(0, 0.0, 0.0, 0.0); tm1637.init(); tm1637.set(BRIGHT_TYPICAL); tm1637.point(POINT_OFF); tm1637.display(0, 9); tm1637.display(1, 9); tm1637.display(2, 9); tm1637.display(3, 0); } void loop() { int buttonPressed = digitalRead(pinButton); if(buttonPressed) { currentState = 1; } else { currentState = 0; } if (currentState != lastState) { if(buttonPressed) { int colorSeed = pushCount % 20; double color = 0.05 * colorSeed; pushCount++; pushCount = pushCount % 10000; //digitalWrite(pinLed, HIGH); leds.setColorHSB(0, color, 1.0, 0.5); int countCopy = pushCount; tm1637.display(3, countCopy % 10); countCopy /= 10; tm1637.display(2, countCopy % 10); countCopy /= 10; tm1637.display(1, countCopy % 10); countCopy /= 10; tm1637.display(0, countCopy % 10); } else { //digitalWrite(pinLed, LOW); leds.setColorHSB(0, 0.0, 0.0, 0.0); } lastState = currentState; } delay(10); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * George Refseth, rfz@opera.com */ #include "core/pch.h" #ifdef M2_SUPPORT # include "adjunct/desktop_util/file_utils/folder_recurse.h" # include "adjunct/desktop_util/opfile/desktop_opfile.h" # include "adjunct/m2/src/engine/engine.h" # include "adjunct/m2/src/engine/message.h" # include "adjunct/m2/src/engine/store/mboxstore.h" # include "adjunct/m2/src/import/ImporterModel.h" # include "adjunct/m2/src/import/MboxImporter.h" # include "modules/locale/locale-enum.h" # include "modules/locale/oplanguagemanager.h" MboxImporter::MboxImporter() : m_mboxFile(NULL), m_raw(NULL), m_raw_length(0), m_raw_capacity(0), m_one_line_ahead(NULL), m_two_lines_ahead(NULL), m_finished_reading(TRUE), m_found_start_of_message(FALSE), m_found_start_of_next_message(FALSE), m_found_valid_message(FALSE), m_folder_recursor(NULL) { } MboxImporter::~MboxImporter() { if (m_mboxFile) OP_DELETE(m_mboxFile); OP_DELETEA(m_raw); OP_DELETEA(m_one_line_ahead); OP_DELETEA(m_two_lines_ahead); } OP_STATUS MboxImporter::InitLookAheadBuffers() { if (!m_one_line_ahead) { m_one_line_ahead = OP_NEWA(char, LOOKAHEAD_BUF_LEN+1); if (!m_one_line_ahead) return OpStatus::ERR_NO_MEMORY; m_one_line_ahead[0] = m_one_line_ahead[LOOKAHEAD_BUF_LEN] = 0; } if (!m_two_lines_ahead) { m_two_lines_ahead = OP_NEWA(char, LOOKAHEAD_BUF_LEN+1); if (!m_two_lines_ahead) { OP_DELETEA(m_one_line_ahead); return OpStatus::ERR_NO_MEMORY; } m_two_lines_ahead[0] = m_two_lines_ahead[LOOKAHEAD_BUF_LEN] = 0; } m_finished_reading = FALSE; return OpStatus::OK; } OP_STATUS MboxImporter::Init() { OpFileInfo::Mode test_for_dir_mode; OpFile* test_for_dir_file = NULL; GetModel()->DeleteAll(); GetModel()->SetSortListener(this); if (m_file_list.GetCount() == 0) return OpStatus::ERR; RETURN_IF_ERROR(InitLookAheadBuffers()); for (UINT32 i = 0; i < m_file_list.GetCount(); i++) { test_for_dir_file = OP_NEW(OpFile, ()); if(test_for_dir_file && OpStatus::IsSuccess(test_for_dir_file->Construct(m_file_list.Get(i)->CStr())) ) { if( OpStatus::IsSuccess(test_for_dir_file->GetMode(test_for_dir_mode)) ) { OP_DELETE(test_for_dir_file); if(test_for_dir_mode == OpFileInfo::DIRECTORY) { OpString rootString; rootString.Set(m_file_list.Get(i)->CStr()); if (rootString.Length() > 1 && rootString[rootString.Length() - 1] == PATHSEPCHAR) rootString.Delete(rootString.Length() - 1); SetRecursorRoot(rootString); while (m_folder_recursor) { OpFile* file_runner; OP_STATUS sts = m_folder_recursor->GetNextFile(file_runner); if (OpStatus::IsSuccess(sts)) { if (file_runner) { OpString mbox; sts = mbox.Set(file_runner->GetFullPath()); if (OpStatus::IsError(sts)) { OP_DELETE(m_folder_recursor); m_folder_recursor = NULL; OP_DELETE(file_runner); } if (IsValidMboxFile(mbox.CStr())) { OpString virtual_path; INT32 index = GetOrCreateFolder(rootString, *file_runner, virtual_path); InitSingleMbox(mbox, virtual_path, index); } OP_DELETE(file_runner); } else { OP_DELETE(m_folder_recursor); m_folder_recursor = NULL; } } else { OP_DELETE(m_folder_recursor); m_folder_recursor = NULL; } } continue; } } else OP_DELETE(test_for_dir_file); } OpString empty; InitSingleMbox(*m_file_list.Get(i), empty); } return OpStatus::OK; } void MboxImporter::InitSingleMbox(const OpString& mbox, OpString& virtual_path, INT32 index /*=-1*/) { if (IsValidMboxFile(mbox.CStr())) { int sep = mbox.FindLastOf(PATHSEPCHAR); if (KNotFound == sep) return; OpString name; name.Set(mbox.CStr() + sep + 1); OpString path; path.Set(mbox.CStr()); if (virtual_path.IsEmpty()) virtual_path.Set(name.CStr()); OpString virtual_folder; virtual_folder.Set(virtual_path.CStr()); #ifdef MSWIN uni_char * backslash = virtual_folder.CStr(); while((backslash = uni_strchr(backslash, PATHSEPCHAR)) != NULL) { *backslash = (uni_char)'/'; } #endif /* OpString imported; RETURN_VOID_IF_ERROR(g_languageManager->GetString(Str::S_IMPORTED, imported)); OpStatus::Ignore(imported.Insert(0, UNI_L(" ("))); OpStatus::Ignore(imported.Append(UNI_L(")"))); OpStatus::Ignore(virtual_path.Append(imported)); RFZTODO: Discuss the need for this... */ ImporterModelItem* item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_MAILBOX_TYPE, name, path, virtual_folder, UNI_L(""))); if (item) /*INT32 branch = */ GetModel()->AddSorted(item, index); } } void MboxImporter::SetImportItems(const OpVector<ImporterModelItem>& items) { GetModel()->EmptySequence(m_sequence); UINT32 count = items.GetCount(); for (UINT32 i = 0; i < count; i++) { ImporterModelItem* item = items.Get(i); GetModel()->MakeSequence(m_sequence, item, TRUE); } } OP_STATUS MboxImporter::ImportMessages() { OpenPrefsFile(); return StartImport(); } BOOL MboxImporter::OnContinueImport() { OP_NEW_DBG("MboxImporter::OnContinueImport", "m2"); if (m_stopImport) return FALSE; if (m_mboxFile) { ImportMboxAsync(); return TRUE; } if (GetModel()->SequenceIsEmpty(m_sequence)) return FALSE; ImporterModelItem* item = GetModel()->PullItem(m_sequence); if (!item) return FALSE; m_moveCurrentToSent = m_moveToSentItem ? (item == m_moveToSentItem) : FALSE; if (item->GetType() != OpTypedObject::IMPORT_MAILBOX_TYPE) return TRUE; OP_DBG(("MboxImporter::OnContinueImport() box = %S", item->GetName().CStr())); m_m2FolderPath.Set(item->GetVirtualPath()); OpString acc; GetImportAccount(acc); m_currInfo.Empty(); m_currInfo.Set(acc); m_currInfo.Append(UNI_L(" - ")); m_currInfo.Append(item->GetName()); OpString progressInfo; progressInfo.Set(m_currInfo); if (InResumeCache(m_m2FolderPath)) { if (m_mboxFile) { OP_DELETE(m_mboxFile); m_mboxFile = NULL; } OpString already_imported; RETURN_IF_ERROR(g_languageManager->GetString(Str::S_ALREADY_IMPORTED, already_imported)); OpStatus::Ignore(progressInfo.Append(UNI_L(" "))); OpStatus::Ignore(progressInfo.Append(already_imported)); MessageEngine::GetInstance()->OnImporterProgressChanged(this, progressInfo, 0, 0, TRUE); return TRUE; } OP_ASSERT(!m_mboxFile); m_mboxFile = OP_NEW(OpFile, ()); if (m_mboxFile && OpStatus::IsSuccess(m_mboxFile->Construct(item->GetPath().CStr()))) InitMboxFile(); else { OP_DELETE(m_mboxFile); m_mboxFile = NULL; } return TRUE; } OP_STATUS MboxImporter::InitMboxFile() { OP_STATUS sts; OP_ASSERT(m_mboxFile); sts = m_mboxFile->Open(OPFILE_READ|OPFILE_SHAREDENYWRITE); if (OpStatus::IsError(sts)) { OP_DELETE(m_mboxFile); m_mboxFile = NULL; return sts; } m_finished_reading = FALSE; m_one_line_ahead[0] = m_two_lines_ahead[0] = 0; struct stat buf; if (DesktopOpFileUtils::Stat(m_mboxFile, &buf) != OpStatus::OK) m_totalCount = 0; else m_totalCount = buf.st_size; m_count = 0; OP_DELETEA(m_raw); m_raw_capacity = min(IMPORT_CHUNK_CAPACITY, m_totalCount + 1); m_raw = OP_NEWA(char, m_raw_capacity); if (m_raw) m_raw[0] = '\0'; else return OpStatus::ERR_NO_MEMORY; m_raw_length = 0; MessageEngine::GetInstance()->OnImporterProgressChanged(this, m_currInfo, m_count, m_totalCount, TRUE); return OpStatus::OK; } void MboxImporter::OnCancelImport() { OP_NEW_DBG("MboxImporter::OnCancelImport", "m2"); OP_DBG(("MboxImporter::OnCancelImport()")); OP_DELETEA(m_raw); m_raw = NULL; if (m_mboxFile) { OP_DELETE(m_mboxFile); m_mboxFile = NULL; } } void MboxImporter::ImportMboxAsync() { OP_NEW_DBG("MboxImporter::ImportMboxAsync", "m2"); if (!m_one_line_ahead || !m_two_lines_ahead) { OP_ASSERT(0); return; } static INT32 old = 0; strcpy(m_one_line_ahead, m_two_lines_ahead); m_two_lines_ahead[0] = 0; if (m_finished_reading || DesktopOpFileUtils::ReadLine(m_two_lines_ahead, LOOKAHEAD_BUF_LEN, m_mboxFile)!=OpStatus::OK) { m_two_lines_ahead[0] = 0; } //Check if this really is start of a new message, or simply an invalid mbox-file (where "From " is not space-stuffed) if (strlen(m_one_line_ahead) > 5 && ((m_one_line_ahead[0] == 'F' && strni_eq(m_one_line_ahead, "FROM ", 5)))) { if (m_found_valid_message) m_found_start_of_next_message = TRUE; else m_found_start_of_message = TRUE; } //Check if the next line most likely is not a header if (m_found_start_of_message || m_found_start_of_next_message) { if (*m_two_lines_ahead && (*m_two_lines_ahead=='<' || (*m_two_lines_ahead=='>' && !strni_eq(m_two_lines_ahead, ">FROM ", 6)) || strni_eq(m_two_lines_ahead, "HTTP:", 5)) ) { if (m_found_start_of_message) m_found_start_of_message = FALSE; else m_found_start_of_next_message = FALSE; } } //Check if the next line is a header. If not, don't save it (we're in the middle of a message body) if (m_found_start_of_message || m_found_start_of_next_message) { char* header_name_ptr = m_two_lines_ahead; while (*header_name_ptr && *header_name_ptr!=':' && *header_name_ptr>=33 && *header_name_ptr<=126) header_name_ptr++; if ((*header_name_ptr==':' && header_name_ptr!=m_two_lines_ahead) || (*header_name_ptr==0 && header_name_ptr==m_two_lines_ahead) || strni_eq(m_two_lines_ahead, ">FROM ", 6)) //To avoid bug#141122 { if (m_found_start_of_message) { m_found_start_of_message = FALSE; m_found_valid_message = TRUE; } } else if (m_found_valid_message) m_found_start_of_next_message = FALSE; } BOOL save_message = m_found_valid_message && (m_found_start_of_next_message || m_finished_reading); //Append line to buffer (make sure the last line of the mbox file is also appended) if (m_found_valid_message && (!save_message || m_finished_reading)) { int space_stuffs = (*m_one_line_ahead==' ' && strni_eq(m_one_line_ahead+1, "FROM ", 5)) ? 1 : 0; INT32 buflen = strlen(m_one_line_ahead) - space_stuffs; if (m_raw_length + buflen >= m_raw_capacity) // brute force realloc { m_raw_capacity = (m_raw_length + buflen) * 2; char* _raw = OP_NEWA(char, m_raw_capacity); if (_raw) op_memcpy(_raw, m_raw, m_raw_length); OP_DELETEA(m_raw); m_raw = _raw; OP_DBG(("MBoxImporter::ImportMboxAsync() REALLOCATION, m_raw_capacity=%u", m_raw_capacity)); } if (m_raw) { op_memcpy(m_raw + m_raw_length, m_one_line_ahead + space_stuffs, buflen); m_raw_length += buflen; } } //Yes, we should save it. Really! if (m_raw && save_message) { Message m2_message; if (m2_message.Init(m_accountId) == OpStatus::OK) { if (!m_finished_reading && m_raw_length>0 && m_raw[m_raw_length-1]=='\n') m_raw_length--; //Skip linefeed preceding "From " if (!m_finished_reading && m_raw_length>0 && m_raw[m_raw_length-1]=='\r') m_raw_length--; m_raw[m_raw_length] = '\0'; m2_message.SetRawMessage(m_raw); Header::HeaderValue header_value; OpString x_opera_status; BOOL skip_message = FALSE; BOOL opera_header_found = OpStatus::IsSuccess(m2_message.GetHeaderValue("X-Opera-Status", header_value)); if (opera_header_found && header_value.HasContent()) { RETURN_VOID_IF_ERROR(x_opera_status.Set(header_value)); // cut out the message id from the status header x_opera_status.Delete(0, 10); x_opera_status[8] = '\0'; skip_message = (x_opera_status.Compare(UNI_L("00000000")) == 0); // this message has been marked as deleted, do not import } BOOL xuidl_header_found = OpStatus::IsSuccess(m2_message.GetHeaderValue("X-UIDL", header_value)); if (xuidl_header_found && header_value.HasContent()) { OpString8 loc; RETURN_VOID_IF_ERROR(loc.Set(header_value.CStr())); // Need to test if acount is POP IMAP or NNTP RETURN_VOID_IF_ERROR(m2_message.SetInternetLocation(loc)); } BOOL ximap_header_found = OpStatus::IsSuccess(m2_message.GetHeaderValue("X-IMAP", header_value)); if (ximap_header_found && header_value.HasContent()) { OpString8 imap_id; RETURN_VOID_IF_ERROR(imap_id.Set(header_value.CStr())); OpString8 relpath; OpString8 loc; if (relpath.HasContent()) { RETURN_VOID_IF_ERROR(loc.AppendFormat("%s:%s", relpath.CStr(), imap_id.CStr())); // Need to test if acount is POP IMAP or NNTP RETURN_VOID_IF_ERROR(m2_message.SetInternetLocation(loc)); } } if (!skip_message) { m2_message.SetFlag(Message::IS_READ, TRUE); if (MessageEngine::GetInstance()->ImportMessage(&m2_message, m_m2FolderPath, m_moveCurrentToSent) != OpStatus::OK) { OP_ASSERT(0); } } } m_raw[0] = '\0'; m_raw_length = 0; m_found_valid_message = m_found_start_of_next_message; m_found_start_of_next_message = FALSE; m_grandTotal++; MessageEngine::GetInstance()->OnImporterProgressChanged(this, m_currInfo, m_count, m_totalCount, TRUE); } OpFileLength file_pos; if (m_mboxFile->GetFilePos(file_pos) == OpStatus::OK && file_pos > 0) { m_count = (INT32)file_pos; } else { OP_DBG(("MBoxImporter::ImportMboxAsync() GetFilePos() failed")); } if (m_count - old >= 1000) { MessageEngine::GetInstance()->OnImporterProgressChanged(this, m_currInfo, m_count, m_totalCount, TRUE); old = m_count; } if (m_finished_reading) { OP_DELETEA(m_raw); m_raw = NULL; OP_DELETE(m_mboxFile); m_mboxFile = NULL; AddToResumeCache(m_m2FolderPath); OP_DBG(("MBoxImporter::ImportMboxAsync() m_count=%u, m_totalCount=%u", m_count, m_totalCount)); } else if (m_mboxFile->Eof()) { m_finished_reading=TRUE; } } BOOL MboxImporter::IsValidMboxFile(const uni_char* file_name) { BOOL valid = FALSE; struct stat st; OpFile * mbox_file = OP_NEW(OpFile, ()); if (!mbox_file || OpStatus::IsError(mbox_file->Construct(file_name))) { OP_DELETE(mbox_file); return FALSE; } if (DesktopOpFileUtils::Stat(mbox_file, &st) == OpStatus::OK && st.st_size > 5) { const int BUF_LEN = 6; char buf[BUF_LEN]; OpFileLength bytes_read = 0; if (mbox_file->Open(OPFILE_READ) != OpStatus::OK || mbox_file->Read(buf, BUF_LEN, &bytes_read) != OpStatus::OK) { OP_DELETE(mbox_file); return FALSE; } if (op_strncmp(buf, "From ", 5) == 0) { valid = TRUE; } } OP_DELETE(mbox_file); return valid; } OP_STATUS MboxImporter::SetRecursorRoot(const OpString& root) { // Define import store path OP_DELETE(m_folder_recursor); m_folder_recursor = OP_NEW(FolderRecursor, ()); if (!m_folder_recursor) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError(m_folder_recursor->SetRootFolder(root))) { OP_DELETE(m_folder_recursor); m_folder_recursor = NULL; } return OpStatus::OK; } INT32 MboxImporter::GetOrCreateFolder(const OpString& root, OpFile& mbox, OpString& virtual_path) { OpString mboxDir; OpString name; INT32 index = -1; OpFile sub_dirs; OP_STATUS sts = mbox.GetDirectory(mboxDir); if (OpStatus::IsError(sts)) { return index; } if (mboxDir.Length() > 1 && mboxDir[mboxDir.Length() - 1] == PATHSEPCHAR) { mboxDir.Delete(mboxDir.Length() - 1); } sts = sub_dirs.Construct(mboxDir.CStr()); if (OpStatus::IsError(sts)) { return index; } sts = name.Set(sub_dirs.GetName()); if (OpStatus::IsError(sts)) { return index; } if (root.Compare(mboxDir) == 0) { virtual_path.Set(name.CStr()); // Find match on top level or // add root and // set index on match or new entry int first_index = 0; ImporterModelItem * item = GetModel()->GetItemByIndex(first_index); while (item) { if (name.Compare(item->GetName()) == 0) { if (index == -1) index = first_index; break; } else { index = item->GetSiblingIndex(); if (index >= 0) item = GetModel()->GetItemByIndex(index); else item = NULL; } } if (!item || index == -1) { // Define name, path and virtual_path OpString virtual_folder; virtual_folder.Set(mboxDir.CStr()); #ifdef MSWIN uni_char * backslash = virtual_folder.CStr(); while((backslash = uni_strchr(backslash, PATHSEPCHAR)) != NULL) { *backslash = (uni_char)'/'; } #endif item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_FOLDER_TYPE, name, mboxDir, virtual_folder, UNI_L(""))); if (item) { /*INT32 branch = */ index = GetModel()->AddSorted(item); } else { // RFZTODO: OOM } } } else { index = GetOrCreateFolder(root, sub_dirs, virtual_path); // define folder by picking out mbox->GetName(); // see if there is a match among index children if // not add and put it into index // set new element index virtual_path.Append(PATHSEP); virtual_path.Append(name); if (GetModel()->GetItemByIndex(index) == NULL) { OP_ASSERT(!"There are no items available to test for children of.., should not GetOrCreateFolder always return an index?"); } else { INT32 t_child_index = GetModel()->GetItemByIndex(index)->GetChildIndex(); for ( int i = 0; i < GetModel()->GetItemByIndex(index)->GetChildCount(); i++) { ImporterModelItem * item = GetModel()->GetItemByIndex(t_child_index); if (name.Compare(item->GetName()) == 0) { return t_child_index; } t_child_index = item->GetSiblingIndex(); } if (!GetModel()->GetItemByIndex(index)->GetChildCount() || t_child_index == -1) { // Define name, path and virtual_path OpString virtual_folder; virtual_folder.Set(mboxDir.CStr()); #ifdef MSWIN uni_char * backslash = virtual_folder.CStr(); while((backslash = uni_strchr(backslash, PATHSEPCHAR)) != NULL) { *backslash = (uni_char)'/'; } #endif ImporterModelItem* item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_FOLDER_TYPE, name, mboxDir, virtual_folder, UNI_L(""))); if (item) /*INT32 branch = */ index = GetModel()->AddSorted(item, index); } else index = t_child_index; } } return index; } INT32 MboxImporter::OnCompareItems(OpTreeModel* tree_model, OpTreeModelItem* item0, OpTreeModelItem* item1) { return static_cast<ImporterModelItem*>(item0)->GetName().Compare(static_cast<ImporterModelItem*>(item1)->GetName()); } #endif //M2_SUPPORT
/* * This program mux a video bitstream(H.264) and a audio bitstream(AAC) together * into a MP4 format file. */ #include <stdio.h> #define __STDC_CONSTANT_MACROS extern "C" { #include "libavformat/avformat.h" }; int main(int argc, char* argv[]) { /* Step 1: Init FFmepg */ av_register_all(); /* Step 2: Set up input Audio stream and Video stream. */ AVFormatContext *pInFmtCtxV = NULL; AVFormatContext *pInFmtCtxA = NULL; AVFormatContext *pOutFmtCtx = NULL; const char *pInFileNameV = "c://work//cuc_ieschool.h264"; const char *pInFileNameA = "c://work//gowest.aac"; const char *pOutFileName = "d://cuc_ieschool.mp4"; int ret = 1; if ((ret = avformat_open_input(&pInFmtCtxV, pInFileNameV, 0, 0)) < 0) { printf( "Can't open input file.\n"); goto end; } if ((ret = avformat_find_stream_info(pInFmtCtxV, 0)) < 0) { printf( "Failed to retrieve input stream information.\n"); goto end; } if ((ret = avformat_open_input(&pInFmtCtxA, pInFileNameA, 0, 0)) < 0) { printf( "Can't open input file.\n"); goto end; } if ((ret = avformat_find_stream_info(pInFmtCtxA, 0)) < 0) { printf( "Failed to retrieve input stream information.\n"); goto end; } /* Step 3: Copy input A/V stream parameter to AVCodecContext of the output. */ printf("===========Input Information==========\n"); av_dump_format(pInFmtCtxV, 0, pInFileNameV, 0); av_dump_format(pInFmtCtxA, 0, pInFileNameA, 0); printf("======================================\n"); avformat_alloc_output_context2(&pOutFmtCtx, NULL, NULL, pOutFileName); if (!pOutFmtCtx) { printf( "Can't create output context.\n"); ret = AVERROR_UNKNOWN; goto end; } int videoIndexV = -1, videoIndexOut = -1; int audioIndexA = -1, audioIndexOut = -1; // Copy input video stream parameter to AVCodecContext of the output. for (int i = 0; i < pInFmtCtxV->nb_streams; i++) { //Create output AVStream according to input AVStream if (pInFmtCtxV->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { AVStream *pInStream = pInFmtCtxV->streams[i]; AVStream *pOutStream = avformat_new_stream(pOutFmtCtx, pInStream->codec->codec); videoIndexV = i; if (!pOutStream) { printf( "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; goto end; } videoIndexOut = pOutStream->index; //Copy the settings of AVCodecContext if (avcodec_copy_context(pOutStream->codec, pInStream->codec) < 0) { printf( "Failed to copy context from input to output stream codec context.\n"); goto end; } pOutStream->codec->codec_tag = 0; if (pOutFmtCtx->oformat->flags & AVFMT_GLOBALHEADER) { pOutStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } break; } } // Copy input audio stream parameter to AVCodecContext of the output. for (int i = 0; i < pInFmtCtxA->nb_streams; i++) { //Create output AVStream according to input AVStream if(pInFmtCtxA->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { AVStream *pInStream = pInFmtCtxA->streams[i]; AVStream *pOutStream = avformat_new_stream(pOutFmtCtx, pInStream->codec->codec); audioIndexA = i; if (!pOutStream) { printf( "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; goto end; } audioIndexOut = pOutStream->index; //Copy the settings of AVCodecContext if (avcodec_copy_context(pOutStream->codec, pInStream->codec) < 0) { printf( "Failed to copy context from input to output stream codec context\n"); goto end; } pOutStream->codec->codec_tag = 0; if (pOutFmtCtx->oformat->flags & AVFMT_GLOBALHEADER) { pOutStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } break; } } printf("==========Output Information==========\n"); av_dump_format(pOutFmtCtx, 0, pOutFileName, 1); printf("======================================\n"); /* Step 4: Write file header. */ //Open output file AVOutputFormat *pOutputFmt = NULL; pOutputFmt = pOutFmtCtx->oformat; if (!(pOutputFmt->flags & AVFMT_NOFILE)) { if (avio_open(&pOutFmtCtx->pb, pOutFileName, AVIO_FLAG_WRITE) < 0) { printf( "Can't open output file '%s'", pOutFileName); goto end; } } //Write file header if (avformat_write_header(pOutFmtCtx, NULL) < 0) { printf( "Error occurred when opening output file\n"); goto end; } /* Step 5: Get the AVPakcet from A/V stream and write into the output file. */ AVPacket packet; int frameIndex = 0; int64_t curPtsV = 0, curPtsA = 0; AVBitStreamFilterContext* h264bsfc = av_bitstream_filter_init("h264_mp4toannexb"); AVBitStreamFilterContext* aacbsfc = av_bitstream_filter_init("aac_adtstoasc"); while (1) { AVFormatContext *pInputFromat = NULL; int streamIndex = 0; AVStream *pInStream = NULL, *pOutStream = NULL; //Get an AVPacket if (av_compare_ts(curPtsV, pInFmtCtxV->streams[videoIndexV]->time_base, curPtsA, pInFmtCtxA->streams[audioIndexA]->time_base) <= 0) { pInputFromat = pInFmtCtxV; streamIndex = videoIndexOut; if (av_read_frame(pInputFromat, &packet) >= 0) { do { pInStream = pInputFromat->streams[packet.stream_index]; pOutStream = pOutFmtCtx->streams[streamIndex]; if (packet.stream_index == videoIndexV) { // FIX£ºNo PTS (Example: Raw H.264) // Simple Write PTS if (packet.pts == AV_NOPTS_VALUE) { // Write PTS AVRational time_base1 = pInStream->time_base; // Duration between 2 frames (us) int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(pInStream->r_frame_rate); // Parameters packet.pts = (double)(frameIndex*calc_duration) / (double)(av_q2d(time_base1) * AV_TIME_BASE); packet.dts = packet.pts; packet.duration = (double)calc_duration / (double)(av_q2d(time_base1) * AV_TIME_BASE); frameIndex++; } curPtsV = packet.pts; break; } } while (av_read_frame(pInputFromat, &packet) >= 0); } else { break; } } else { pInputFromat = pInFmtCtxA; streamIndex = audioIndexOut; if (av_read_frame(pInputFromat, &packet) >= 0) { do { pInStream = pInputFromat->streams[packet.stream_index]; pOutStream = pOutFmtCtx->streams[streamIndex]; if (packet.stream_index == audioIndexA) { // FIX£ºNo PTS // Simple Write PTS if (packet.pts == AV_NOPTS_VALUE) { // Write PTS AVRational time_base1 = pInStream->time_base; // Duration between 2 frames (us) int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(pInStream->r_frame_rate); // Parameters packet.pts = (double)(frameIndex * calc_duration) / (double)(av_q2d(time_base1) * AV_TIME_BASE); packet.dts = packet.pts; packet.duration = (double)calc_duration / (double)(av_q2d(time_base1) * AV_TIME_BASE); frameIndex++; } curPtsA = packet.pts; break; } } while (av_read_frame(pInputFromat, &packet) >= 0); } else { break; } } av_bitstream_filter_filter(h264bsfc, pInStream->codec, NULL, &packet.data, &packet.size, packet.data, packet.size, 0); av_bitstream_filter_filter(aacbsfc, pOutStream->codec, NULL, &packet.data, &packet.size, packet.data, packet.size, 0); // Convert PTS/DTS packet.pts = av_rescale_q_rnd(packet.pts, pInStream->time_base, pOutStream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); packet.dts = av_rescale_q_rnd(packet.dts, pInStream->time_base, pOutStream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); packet.duration = av_rescale_q(packet.duration, pInStream->time_base, pOutStream->time_base); packet.pos = -1; packet.stream_index = streamIndex; printf("Write 1 Packet. size:%5d\tpts:%lld\n", packet.size, packet.pts); // Write if (av_interleaved_write_frame(pOutFmtCtx, &packet) < 0) { printf( "Error muxing packet\n"); break; } av_free_packet(&packet); } /* Step 6: Write file tailer. */ av_write_trailer(pOutFmtCtx); /* Step 7: Clean up. */ av_bitstream_filter_close(h264bsfc); av_bitstream_filter_close(aacbsfc); end: avformat_close_input(&pInFmtCtxV); avformat_close_input(&pInFmtCtxA); if (pOutFmtCtx && !(pOutputFmt->flags & AVFMT_NOFILE)) { avio_close(pOutFmtCtx->pb); } avformat_free_context(pOutFmtCtx); if (ret < 0 && ret != AVERROR_EOF) { printf( "Error occurred.\n"); return -1; } return 0; }
// $Id$ // // Copyright (C) 2002-2012 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <RDGeneral/utils.h> #include <GraphMol/RankAtoms.h> #include <boost/cstdint.hpp> #include <boost/foreach.hpp> #include <boost/dynamic_bitset.hpp> #include <RDGeneral/hash/hash.hpp> #include <boost/lambda/lambda.hpp> #include <list> #include <algorithm> using namespace boost::lambda; //#define VERBOSE_CANON 1 //#define VERYVERBOSE_CANON 1 namespace RankAtoms{ using namespace RDKit; // -------------------------------------------------- // // grabs the corresponding primes for the rank vector ranks // // -------------------------------------------------- void getPrimes(const INT_VECT &ranks,INT_VECT &res){ PRECONDITION(res.size()==0,""); res.reserve(ranks.size()); for(INT_VECT_CI ivCIt=ranks.begin();ivCIt!=ranks.end();++ivCIt){ res.push_back(firstThousandPrimes[(*ivCIt)%NUM_PRIMES_AVAIL]); } } // -------------------------------------------------- // // blows out any indices in indicesInPlay which correspond to unique ranks // // -------------------------------------------------- void updateInPlayIndices(const INT_VECT &ranks,INT_LIST &indicesInPlay){ INT_LIST::iterator ivIt=indicesInPlay.begin(); while(ivIt!=indicesInPlay.end()){ // find the first instance of this rank: INT_VECT::const_iterator pos=std::find(ranks.begin(),ranks.end(),ranks[*ivIt]); ++pos; // now check to see if there is at least one more: if( std::find(pos,ranks.end(),ranks[*ivIt])==ranks.end()){ INT_LIST::iterator tmpIt = ivIt; ++ivIt; indicesInPlay.erase(tmpIt); } else { ++ivIt; } } } // -------------------------------------------------- // // for each index in indicesInPlay, generate the products of the adjacent // elements // // The products are weighted by the order of the bond connecting the atoms. // // -------------------------------------------------- void calcAdjacentProducts(unsigned int nAtoms, const INT_VECT &valVect, double const *adjMat, const INT_LIST &indicesInPlay, DOUBLE_VECT &res, bool useSelf=true, double tol=1e-6){ PRECONDITION(valVect.size() >= nAtoms,""); PRECONDITION(res.size() == 0,""); PRECONDITION(adjMat,""); for(INT_LIST::const_iterator idxIt=indicesInPlay.begin(); idxIt != indicesInPlay.end(); ++idxIt){ double accum; if(useSelf) accum=valVect[*idxIt]; else accum=1.0; const unsigned int iTab = (*idxIt)*nAtoms; for(unsigned int j=0;j<nAtoms;++j){ double elem=adjMat[iTab+j]; if(elem>tol){ if(elem<2.-tol){ accum *= valVect[j]; } else { accum *= pow(static_cast<double>(valVect[j]), static_cast<int>(elem)); } } } res.push_back(accum); } } template <typename T> void debugVect(const std::vector<T> arg){ typename std::vector<T>::const_iterator viIt; for(viIt=arg.begin();viIt!=arg.end();++viIt){ BOOST_LOG(rdDebugLog)<< *viIt << " "; } BOOST_LOG(rdDebugLog)<< std::endl; } // -------------------------------------------------- // // This is one round of the process from Step III in the Daylight // paper // // -------------------------------------------------- unsigned int iterateRanks(unsigned int nAtoms,INT_VECT &primeVect, DOUBLE_VECT &atomicVect, INT_LIST &indicesInPlay, double *adjMat, INT_VECT &ranks, VECT_INT_VECT *rankHistory,unsigned int stagnantTol){ PRECONDITION(!rankHistory||rankHistory->size()>=nAtoms,"bad rankHistory size"); bool done = false; unsigned int numClasses = countClasses(ranks); unsigned int lastNumClasses = 0; unsigned int nCycles = 0; unsigned int nStagnant=0; // // loop until either we finish or no improvement is seen // #ifdef VERBOSE_CANON for(unsigned int i=0;i<nAtoms;i++) { BOOST_LOG(rdDebugLog)<< "\t\t>:" << i << " " << ranks[i] << std::endl; } BOOST_LOG(rdDebugLog)<< "\t\t-*-*-*-*-" << std::endl; #endif while(!done && nCycles < nAtoms){ // determine which atomic indices are in play (which have duplicate ranks) if(rankHistory){ for(INT_LIST_CI idx=indicesInPlay.begin();idx!=indicesInPlay.end();++idx){ (*rankHistory)[*idx].push_back(ranks[*idx]); } } updateInPlayIndices(ranks,indicesInPlay); if(indicesInPlay.empty()) break; #ifdef VERYVERBOSE_CANON BOOST_LOG(rdDebugLog)<< "IN PLAY:" << std::endl; BOOST_LOG(rdDebugLog)<< "\t\t->"; for(INT_LIST::const_iterator tmpI=indicesInPlay.begin();tmpI != indicesInPlay.end();tmpI++){ BOOST_LOG(rdDebugLog)<< " " << *tmpI; } BOOST_LOG(rdDebugLog)<< std::endl; BOOST_LOG(rdDebugLog)<< "\t\t---------" << std::endl; #endif //------------------------- // Step (2): // Get the products of adjacent primes //------------------------- primeVect.resize(0); getPrimes(ranks,primeVect); atomicVect.resize(0); calcAdjacentProducts(nAtoms,primeVect,adjMat,indicesInPlay,atomicVect,false); #ifdef VERYVERBOSE_CANON BOOST_LOG(rdDebugLog)<< "primes: "; debugVect(primeVect); BOOST_LOG(rdDebugLog)<< "products: "; debugVect(atomicVect); #endif //------------------------- // Steps (3) and (4) // sort the products and count classes //------------------------- sortAndRankVect(nAtoms,atomicVect,indicesInPlay,ranks); lastNumClasses = numClasses; numClasses = countClasses(ranks); if(numClasses == lastNumClasses) nStagnant++; #ifdef VERYVERBOSE_CANON int tmpOff=0; for(unsigned int i=0;i<nAtoms;i++){ //for(INT_LIST::const_iterator tmpI=indicesInPlay.begin();tmpI != indicesInPlay.end();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\ti:" << i << "\t" << ranks[i] << "\t" << primeVect[i]; if(std::find(indicesInPlay.begin(),indicesInPlay.end(),i)!=indicesInPlay.end()){ BOOST_LOG(rdDebugLog)<< "\t" << atomicVect[tmpOff]; tmpOff++; } BOOST_LOG(rdDebugLog)<< std::endl; } BOOST_LOG(rdDebugLog)<< "\t\t---------" << std::endl; #endif // terminal condition, we'll allow a single round of stagnancy if(numClasses == nAtoms || nStagnant > stagnantTol) done = 1; nCycles++; } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< ">>>>>> done inner iteration. static: "<< nStagnant << " "; BOOST_LOG(rdDebugLog)<< nCycles << " " << nAtoms << " " << numClasses << std::endl; #ifdef VERYVERBOSE_CANON for(unsigned int i=0;i<nAtoms;i++) { BOOST_LOG(rdDebugLog)<< "\t" << i << " " << ranks[i] << std::endl; } #endif if(nCycles == nAtoms){ BOOST_LOG(rdWarningLog) << "WARNING: ranking bottomed out" << std::endl; } #endif return numClasses; } unsigned int iterateRanks2(unsigned int nAtoms,INT_VECT &primeVect, DOUBLE_VECT &atomicVect, INT_LIST &indicesInPlay, double *adjMat, INT_VECT &ranks,VECT_DOUBLE_VECT &nRanks, VECT_INT_VECT *rankHistory,unsigned int stagnantTol){ PRECONDITION(!rankHistory||rankHistory->size()>=nAtoms,"bad rankHistory size"); bool done = false; unsigned int numClasses = countClasses(ranks); unsigned int lastNumClasses = 0; unsigned int nCycles = 0; unsigned int nStagnant=0; // // loop until either we finish or no improvement is seen // #ifdef VERBOSE_CANON for(unsigned int i=0;i<nAtoms;i++) { BOOST_LOG(rdDebugLog)<< "\t\t>:" << i << " " << ranks[i] << std::endl; } BOOST_LOG(rdDebugLog)<< "\t\t-*-*-*-*-" << std::endl; #endif while(!done && nCycles < nAtoms){ // determine which atomic indices are in play (which have duplicate ranks) if(rankHistory){ BOOST_FOREACH(int idx,indicesInPlay){ (*rankHistory)[idx].push_back(ranks[idx]); } } updateInPlayIndices(ranks,indicesInPlay); if(indicesInPlay.empty()) break; #ifdef VERYVERBOSE_CANON BOOST_LOG(rdDebugLog)<< "IN PLAY:" << std::endl; BOOST_LOG(rdDebugLog)<< "\t\t->"; for(INT_LIST::const_iterator tmpI=indicesInPlay.begin();tmpI != indicesInPlay.end();tmpI++){ BOOST_LOG(rdDebugLog)<< " " << *tmpI; } BOOST_LOG(rdDebugLog)<< std::endl; BOOST_LOG(rdDebugLog)<< "\t\t---------" << std::endl; #endif //------------------------- // Step (2): // Get the products of adjacent primes //------------------------- primeVect.resize(0); getPrimes(ranks,primeVect); atomicVect.resize(0); calcAdjacentProducts(nAtoms,primeVect,adjMat,indicesInPlay,atomicVect,false); #ifdef VERYVERBOSE_CANON BOOST_LOG(rdDebugLog)<< "primes: "; debugVect(primeVect); BOOST_LOG(rdDebugLog)<< "products: "; debugVect(atomicVect); #endif unsigned int p=0; BOOST_FOREACH(int idx,indicesInPlay){ nRanks[idx].push_back(atomicVect[p++]); } #ifdef VERYVERBOSE_CANON for(int idx=0;idx<nAtoms;++idx){ std::cerr<<" nranks["<<idx<<"]: "; std::copy(nRanks[idx].begin(),nRanks[idx].end(),std::ostream_iterator<double>(std::cerr," ")); std::cerr<<"\n"; } #endif //------------------------- // Steps (3) and (4) // sort the products and count classes //------------------------- rankVect(nRanks,ranks); //sortAndRankVect2(nRanks,indicesInPlay,ranks); lastNumClasses = numClasses; numClasses = countClasses(ranks); if(numClasses == lastNumClasses) nStagnant++; #ifdef VERYVERBOSE_CANON int tmpOff=0; for(unsigned int i=0;i<nAtoms;i++){ //for(INT_LIST::const_iterator tmpI=indicesInPlay.begin();tmpI != indicesInPlay.end();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\ti:" << i << "\t" << ranks[i] << "\t" << primeVect[i]; if(std::find(indicesInPlay.begin(),indicesInPlay.end(),i)!=indicesInPlay.end()){ BOOST_LOG(rdDebugLog)<< "\t" << atomicVect[tmpOff]; tmpOff++; } BOOST_LOG(rdDebugLog)<< std::endl; } BOOST_LOG(rdDebugLog)<< "\t\t---------" << std::endl; #endif // terminal condition, we'll allow a single round of stagnancy if(numClasses == nAtoms || nStagnant > stagnantTol) done = 1; nCycles++; } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< ">>>>>> done inner iteration. static: "<< nStagnant << " "; BOOST_LOG(rdDebugLog)<< nCycles << " " << nAtoms << " " << numClasses << std::endl; #ifdef VERYVERBOSE_CANON for(unsigned int i=0;i<nAtoms;i++) { BOOST_LOG(rdDebugLog)<< "\t" << i << " " << ranks[i] << std::endl; } #endif if(nCycles == nAtoms){ BOOST_LOG(rdWarningLog) << "WARNING: ranking bottomed out" << std::endl; } #endif return numClasses; } // -------------------------------------------------- // // Calculates invariants for the atoms of a molecule // // NOTE: if the atom has not had chirality info pre-calculated, it doesn't // much matter what value includeChirality has! // -------------------------------------------------- void buildAtomInvariants(const ROMol &mol,INVAR_VECT &res, bool includeChirality, bool includeIsotopes){ PRECONDITION(res.size()>=mol.getNumAtoms(),"res vect too small"); unsigned int atsSoFar=0; std::vector<boost::uint64_t> tres(mol.getNumAtoms()); for(ROMol::ConstAtomIterator atIt=mol.beginAtoms();atIt!=mol.endAtoms();atIt++){ Atom const *atom = *atIt; int nHs = atom->getTotalNumHs() % 8; int chg = abs(atom->getFormalCharge()) % 8; int chgSign = atom->getFormalCharge() > 0; int num = atom->getAtomicNum() % 128; int nConns = atom->getDegree() % 8; int deltaMass=0; if(includeIsotopes && atom->getIsotope()){ deltaMass = static_cast<int>(atom->getIsotope() - PeriodicTable::getTable()->getMostCommonIsotope(atom->getAtomicNum())); deltaMass += 128; if(deltaMass < 0) deltaMass = 0; else deltaMass = deltaMass % 256; } // figure out the minimum-sized ring we're involved in int inRing = 0; if(atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())){ RingInfo *ringInfo=atom->getOwningMol().getRingInfo(); inRing=3; while(inRing<256){ if(ringInfo->isAtomInRingOfSize(atom->getIdx(),inRing)){ break; } else { inRing++; } } } inRing = inRing % 16; boost::uint64_t invariant = 0; invariant = (invariant << 3) | nConns; // we used to include the number of explicitHs, but that // didn't make much sense. TotalValence is another possible // discriminator here, but the information is essentially // redundant with nCons, num, and nHs. // invariant = (invariant << 4) | totalVal; invariant = (invariant << 7) | num; invariant = (invariant << 8) | deltaMass; invariant = (invariant << 3) | nHs; invariant = (invariant << 4) | inRing; invariant = (invariant << 3) | chg; invariant = (invariant << 1) | chgSign; if(includeChirality ){ int isR=0; if( atom->hasProp("_CIPCode")){ std::string cipCode; atom->getProp("_CIPCode",cipCode); if(cipCode=="R"){ isR=1; } else { isR=2; } } invariant = (invariant << 2) | isR; } // now deal with cis/trans - this is meant to address issue 174 // loop over the bonds on this atom and check if we have a double bond with // a chiral code marking if (includeChirality) { ROMol::OBOND_ITER_PAIR atomBonds = atom->getOwningMol().getAtomBonds(atom); int isT=0; while (atomBonds.first != atomBonds.second){ BOND_SPTR tBond = atom->getOwningMol()[*(atomBonds.first)]; if( (tBond->getBondType() == Bond::DOUBLE) && (tBond->getStereo()>Bond::STEREOANY )) { if (tBond->getStereo()==Bond::STEREOE) { isT = 1; } else if(tBond->getStereo()==Bond::STEREOZ) { isT=2; } break; } atomBonds.first++; } invariant = (invariant << 2) | isT; } tres[atsSoFar++] = invariant; } if(includeChirality){ // ring stereochemistry boost::dynamic_bitset<> adjusted(mol.getNumAtoms()); for(ROMol::ConstAtomIterator atIt=mol.beginAtoms();atIt!=mol.endAtoms();atIt++){ Atom const *atom = *atIt; tres[atom->getIdx()] = tres[atom->getIdx()]<<2; } for(ROMol::ConstAtomIterator atIt=mol.beginAtoms();atIt!=mol.endAtoms();atIt++){ Atom const *atom = *atIt; if((atom->getChiralTag()==Atom::CHI_TETRAHEDRAL_CW || atom->getChiralTag()==Atom::CHI_TETRAHEDRAL_CCW) && atom->hasProp("_ringStereoAtoms")){ //atom->hasProp("_CIPRank") && //!atom->hasProp("_CIPCode")){ ROMol::ADJ_ITER beg,end; boost::tie(beg,end) = mol.getAtomNeighbors(atom); unsigned int nCount=0; while(beg!=end){ unsigned int nbrIdx=mol[*beg]->getIdx(); if(!adjusted[nbrIdx]){ tres[nbrIdx] |= nCount%4; adjusted.set(nbrIdx); } ++nCount; ++beg; } } } } for(unsigned int i=0;i<mol.getNumAtoms();++i) res[i]=tres[i]; } void buildFragmentAtomInvariants(const ROMol &mol,INVAR_VECT &res, bool includeChirality, const boost::dynamic_bitset<> &atomsToUse, const boost::dynamic_bitset<> &bondsToUse, const std::vector<std::string> *atomSymbols ){ PRECONDITION(res.size()>=mol.getNumAtoms(),"res vect too small"); std::vector<int> degrees(mol.getNumAtoms(),0); for(unsigned int i=0;i<bondsToUse.size();++i){ if(bondsToUse[i]){ const Bond *bnd=mol.getBondWithIdx(i); degrees[bnd->getBeginAtomIdx()]++; degrees[bnd->getEndAtomIdx()]++; } } for(ROMol::ConstAtomIterator atIt=mol.beginAtoms();atIt!=mol.endAtoms();++atIt){ Atom const *atom = *atIt; int aIdx=atom->getIdx(); if(!atomsToUse[aIdx]){ res[aIdx] = 0; continue; } boost::uint64_t invariant = 0; int nConns = degrees[aIdx]% 8; invariant = (invariant << 3) | nConns; if(!atomSymbols){ int chg = abs(atom->getFormalCharge()) % 8; int chgSign = atom->getFormalCharge() > 0; int num = atom->getAtomicNum() % 128; int deltaMass=0; if(atom->getIsotope()){ deltaMass = static_cast<int>(atom->getIsotope() - PeriodicTable::getTable()->getMostCommonIsotope(atom->getAtomicNum())); deltaMass += 128; if(deltaMass < 0) deltaMass = 0; else deltaMass = deltaMass % 256; } invariant = (invariant << 7) | num; invariant = (invariant << 8) | deltaMass; invariant = (invariant << 3) | chg; invariant = (invariant << 1) | chgSign; invariant = (invariant << 1) | atom->getIsAromatic(); } else { const std::string &symb=(*atomSymbols)[aIdx]; boost::uint32_t hsh=gboost::hash_range(symb.begin(),symb.end()); invariant = (invariant << 20) | (hsh%(1<<20)); } // figure out the minimum-sized ring we're involved in int inRing = mol.getRingInfo()->minAtomRingSize(aIdx); inRing = inRing % 16; invariant = (invariant << 4) | inRing; if(includeChirality ){ int isR=0; if( atom->hasProp("_CIPCode")){ std::string cipCode; atom->getProp("_CIPCode",cipCode); if(cipCode=="R"){ isR=1; } else { isR=2; } } invariant = (invariant << 2) | isR; } // now deal with cis/trans - this is meant to address issue 174 // loop over the bonds on this atom and check if we have a double bond with // a chiral code marking if (includeChirality) { ROMol::OBOND_ITER_PAIR atomBonds = mol.getAtomBonds(atom); int isT=0; while (atomBonds.first != atomBonds.second){ BOND_SPTR tBond = mol[*(atomBonds.first)]; atomBonds.first++; if(!bondsToUse[tBond->getIdx()]) continue; if( (tBond->getBondType() == Bond::DOUBLE) && (tBond->getStereo()>Bond::STEREOANY )) { if (tBond->getStereo()==Bond::STEREOE) { isT = 1; } else if(tBond->getStereo()==Bond::STEREOZ) { isT=2; } break; } } invariant = (invariant << 2) | isT; } res[aIdx] = invariant; } } }// end of RankAtoms namespace namespace RDKit{ namespace MolOps { // -------------------------------------------------- // // Daylight canonicalization, loosely based up on algorithm described in // JCICS 29, 97-101, (1989) // When appropriate, specific references are made to the algorithm // description in that paper. Steps refer to Table III of the paper // // -------------------------------------------------- void rankAtoms(const ROMol &mol,INT_VECT &ranks, bool breakTies, bool includeChirality, bool includeIsotopes, VECT_INT_VECT *rankHistory){ unsigned int i; unsigned int nAtoms = mol.getNumAtoms(); PRECONDITION(ranks.size()>=nAtoms,""); PRECONDITION(!rankHistory||rankHistory->size()>=nAtoms,"bad rankHistory size"); unsigned int stagnantTol=1; if(!mol.getRingInfo()->isInitialized()){ MolOps::findSSSR(mol); } if(nAtoms > 1){ double *adjMat = MolOps::getAdjacencyMatrix(mol, true); // ---------------------- // generate atomic invariants, Step (1) // ---------------------- INVAR_VECT invariants; invariants.resize(nAtoms); RankAtoms::buildAtomInvariants(mol,invariants,includeChirality,includeIsotopes); #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "invariants:" << std::endl; for(i=0;i<nAtoms;i++){ BOOST_LOG(rdDebugLog)<< i << " " << (long)invariants[i]<< std::endl; } #endif DOUBLE_VECT atomicVect; atomicVect.resize(nAtoms); // ---------------------- // iteration 1: Steps (3) and (4) // ---------------------- // Unlike the original paper, we're going to keep track of the // ranks at each iteration and use those vectors to rank // atoms. This seems to lead to more stable evolution of the // ranks by avoiding ranks oscillating back and forth across // iterations. VECT_DOUBLE_VECT nRanks(nAtoms); for(i=0;i<nAtoms;i++) nRanks[i].push_back(invariants[i]); // start by ranking the atoms using the invariants ranks.resize(nAtoms); RankAtoms::rankVect(nRanks,ranks); if(rankHistory){ for(i=0;i<nAtoms;i++){ (*rankHistory)[i].push_back(ranks[i]); } } // how many classes are present? unsigned int numClasses = RankAtoms::countClasses(ranks); if(numClasses != nAtoms){ INT_VECT primeVect; primeVect.reserve(nAtoms); DOUBLE_VECT atomicVect; atomicVect.reserve(nAtoms); // indicesInPlay is used to track the atoms with non-unique ranks // (we'll be modifying these in each step) INT_LIST indicesInPlay; for(i=0;i<nAtoms;i++) indicesInPlay.push_back(i); // if we aren't breaking ties here, allow the rank iteration to // go the full number of atoms: if(!breakTies) stagnantTol=nAtoms; bool done=indicesInPlay.empty(); while(!done){ // // do one round of iterations // numClasses = RankAtoms::iterateRanks2(nAtoms,primeVect,atomicVect, indicesInPlay,adjMat,ranks,nRanks, rankHistory,stagnantTol); #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "************************ done outer iteration" << std::endl; #endif #ifdef VERBOSE_CANON unsigned int tmpI; BOOST_LOG(rdDebugLog)<< "RANKS:" << std::endl; for(tmpI=0;tmpI<ranks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << tmpI << " " << ranks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif // // This is the tiebreaker stage of things // if( breakTies && !indicesInPlay.empty() && numClasses<nAtoms){ INT_VECT newRanks = ranks; // Add one to all ranks and multiply by two BOOST_FOREACH(int &nr,newRanks) { nr=(nr+1)*2; } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "postmult:" << std::endl; for(tmpI=0;tmpI<newRanks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << newRanks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif // // find lowest duplicate rank with lowest invariant: // int lowestIdx=indicesInPlay.front(); double lowestInvariant = invariants[lowestIdx]; int lowestRank=newRanks[lowestIdx]; BOOST_FOREACH(int ilidx,indicesInPlay){ if(newRanks[ilidx]<=lowestRank){ if(newRanks[ilidx]<lowestRank || invariants[ilidx] <= lowestInvariant){ lowestRank = newRanks[ilidx]; lowestIdx = ilidx; lowestInvariant = invariants[ilidx]; } } } // // subtract one from the lowest index, rerank and proceed // newRanks[lowestIdx] -= 1; RankAtoms::rankVect(newRanks,ranks); BOOST_FOREACH(int ilidx,indicesInPlay){ nRanks[ilidx].push_back(ranks[ilidx]); } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "RE-RANKED ON:" << lowestIdx << std::endl; for(tmpI=0;tmpI<newRanks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << newRanks[tmpI] << " " << ranks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif } else { done = true; } } } } } // end of function rankAtoms void rankAtomsInFragment(const ROMol &mol,INT_VECT &ranks, const boost::dynamic_bitset<> &atomsToUse, const boost::dynamic_bitset<> &bondsToUse, const std::vector<std::string> *atomSymbols, const std::vector<std::string> *bondSymbols, bool breakTies, VECT_INT_VECT *rankHistory){ unsigned int nAtoms = mol.getNumAtoms(); unsigned int nActiveAtoms = atomsToUse.count(); PRECONDITION(ranks.size()>=nAtoms,""); PRECONDITION(!atomSymbols||atomSymbols->size()>=nAtoms,"bad atomSymbols"); PRECONDITION(!rankHistory||rankHistory->size()>=nAtoms,"bad rankHistory size"); PRECONDITION(mol.getRingInfo()->isInitialized(),"no ring information present"); PRECONDITION(!rankHistory,"rankHistory not currently supported."); unsigned int stagnantTol=1; if(nActiveAtoms > 1){ // ---------------------- // generate atomic invariants, Step (1) // ---------------------- INVAR_VECT invariants; invariants.resize(nAtoms); RankAtoms::buildFragmentAtomInvariants(mol,invariants,true, atomsToUse,bondsToUse, atomSymbols); INVAR_VECT tinvariants; tinvariants.resize(nActiveAtoms); unsigned int activeIdx=0; for(unsigned int aidx=0;aidx<nAtoms;++aidx){ if(atomsToUse[aidx]){ tinvariants[activeIdx++]=invariants[aidx]; } } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "invariants:" << std::endl; for(unsigned int i=0;i<nActiveAtoms;i++){ BOOST_LOG(rdDebugLog)<< i << " " << (long)tinvariants[i]<< std::endl; } #endif // ---------------------- // iteration 1: Steps (3) and (4) // ---------------------- // start by ranking the atoms using the invariants VECT_DOUBLE_VECT nRanks(nActiveAtoms); for(unsigned int i=0;i<nActiveAtoms;i++) nRanks[i].push_back(tinvariants[i]); INT_VECT tranks(nActiveAtoms,0); RankAtoms::rankVect(nRanks,tranks); #if 0 if(rankHistory){ for(unsigned int i=0;i<nAtoms;i++){ (*rankHistory)[i].push_back(ranks[i]); } } #endif // how many classes are present? unsigned int numClasses = RankAtoms::countClasses(tranks); if(numClasses != nActiveAtoms){ double *tadjMat = new double[nActiveAtoms*nActiveAtoms]; memset(static_cast<void *>(tadjMat),0,nActiveAtoms*nActiveAtoms*sizeof(double)); if(!bondSymbols){ double *adjMat = MolOps::getAdjacencyMatrix(mol,true,0,true,0,&bondsToUse); activeIdx=0; for(unsigned int aidx=0;aidx<nAtoms;++aidx){ if(atomsToUse[aidx]){ unsigned int activeIdx2=activeIdx+1; for(unsigned int aidx2=aidx+1;aidx2<nAtoms;++aidx2){ if(atomsToUse[aidx2]){ tadjMat[activeIdx*nActiveAtoms+activeIdx2]=adjMat[aidx*nAtoms+aidx2]; tadjMat[activeIdx2*nActiveAtoms+activeIdx]=adjMat[aidx2*nAtoms+aidx]; ++activeIdx2; } } ++activeIdx; } } } else { // rank the bond symbols we have: std::vector<boost::uint32_t> tbranks(bondsToUse.size(), 0); for(unsigned int bidx=0;bidx<bondsToUse.size();++bidx){ if(!bondsToUse[bidx]) continue; const std::string &symb=(*bondSymbols)[bidx]; boost::uint32_t hsh=gboost::hash_range(symb.begin(),symb.end()); tbranks[bidx]=hsh; } INT_VECT branks(bondsToUse.size(),1000000); #ifdef VERBOSE_CANON std::cerr<<" tbranks:"; std::copy(tbranks.begin(),tbranks.end(),std::ostream_iterator<boost::uint32_t>(std::cerr," ")); std::cerr<<std::endl; #endif RankAtoms::rankVect(tbranks,branks); #ifdef VERBOSE_CANON std::cerr<<" branks:"; std::copy(branks.begin(),branks.end(),std::ostream_iterator<int>(std::cerr," ")); std::cerr<<std::endl; #endif for(unsigned int bidx=0;bidx<bondsToUse.size();++bidx){ if(!bondsToUse[bidx]) continue; const Bond *bond=mol.getBondWithIdx(bidx); unsigned int aidx1=bond->getBeginAtomIdx(); unsigned int aidx2=bond->getEndAtomIdx(); unsigned int tidx1=0; for(unsigned int iidx=0;iidx<aidx1;++iidx){ if(atomsToUse[iidx]) ++tidx1; } unsigned int tidx2=0; for(unsigned int iidx=0;iidx<aidx2;++iidx){ if(atomsToUse[iidx]) ++tidx2; } //const std::string &symb=(*bondSymbols)[bidx]; //boost::uint32_t hsh=gboost::hash_range(symb.begin(),symb.end()); //std::cerr<<" ::: "<<bidx<<"->"<<branks[bidx]<<std::endl; tadjMat[tidx1*nActiveAtoms+tidx2]=branks[bidx]; tadjMat[tidx2*nActiveAtoms+tidx1]=branks[bidx]; } } INT_VECT primeVect; primeVect.reserve(nActiveAtoms); DOUBLE_VECT atomicVect; atomicVect.reserve(nActiveAtoms); #ifdef VERBOSE_CANON for(unsigned int aidx1=0;aidx1<nActiveAtoms;++aidx1){ std::cerr<<aidx1<<" : "; for(unsigned int aidx2=aidx1+1;aidx2<nActiveAtoms;++aidx2){ std::cerr<< tadjMat[aidx1*nActiveAtoms+aidx2]<<" "; } std::cerr<<std::endl; } #endif // indicesInPlay is used to track the atoms with non-unique ranks // (we'll be modifying these in each step) INT_LIST indicesInPlay; for(unsigned int i=0;i<nActiveAtoms;i++) indicesInPlay.push_back(i); // if we aren't breaking ties here, allow the rank iteration to // go the full number of atoms: if(!breakTies) stagnantTol=nActiveAtoms; bool done=indicesInPlay.empty(); while(!done){ // // do one round of iterations // numClasses = RankAtoms::iterateRanks2(nActiveAtoms,primeVect,atomicVect, indicesInPlay,tadjMat,tranks,nRanks, rankHistory,stagnantTol); #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "************************ done outer iteration" << std::endl; #endif #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "RANKS:" << std::endl; for(unsigned int tmpI=0;tmpI<tranks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << tmpI << " " << tranks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif // // This is the tiebreaker stage of things // if( breakTies && !indicesInPlay.empty() && numClasses<nActiveAtoms){ INT_VECT newRanks = tranks; // Add one to all ranks and multiply by two std::for_each(newRanks.begin(),newRanks.end(),_1=(_1+1)*2); #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "postmult:" << std::endl; for(unsigned tmpI=0;tmpI<newRanks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << newRanks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif // // find lowest duplicate rank with lowest invariant: // int lowestIdx=indicesInPlay.front(); double lowestInvariant = tinvariants[lowestIdx]; int lowestRank=newRanks[lowestIdx]; for(INT_LIST_I ilIt=indicesInPlay.begin(); ilIt!=indicesInPlay.end(); ++ilIt){ if(newRanks[*ilIt]<=lowestRank){ if(newRanks[*ilIt]<lowestRank || tinvariants[*ilIt] <= lowestInvariant){ lowestRank = newRanks[*ilIt]; lowestIdx = *ilIt; lowestInvariant = tinvariants[*ilIt]; } } } // // subtract one from the lowest index, rerank and proceed // newRanks[lowestIdx] -= 1; RankAtoms::rankVect(newRanks,tranks); BOOST_FOREACH(int ilidx,indicesInPlay){ nRanks[ilidx].push_back(ranks[ilidx]); } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog)<< "RE-RANKED ON:" << lowestIdx << std::endl; for(unsigned int tmpI=0;tmpI<newRanks.size();tmpI++){ BOOST_LOG(rdDebugLog)<< "\t\t" << newRanks[tmpI] << " " << tranks[tmpI] << std::endl; } BOOST_LOG(rdDebugLog)<< std::endl; #endif } else { done = true; } } delete [] tadjMat; } unsigned int tidx=0; for(unsigned int aidx=0;aidx<nAtoms;++aidx){ ranks[aidx]=0; if(atomsToUse[aidx]){ ranks[aidx]=tranks[tidx++]; } } } } // end of function rankAtomsInFragment } // end of namespace MolOps } // End Of RDKit namespace
/* XMRig * Copyright (c) 2018-2019 tevador <tevador@gmail.com> * Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "crypto/rx/RxDataset.h" #include "backend/cpu/Cpu.h" #include "base/io/log/Log.h" #include "base/io/log/Tags.h" #include "base/kernel/Platform.h" #include "crypto/common/VirtualMemory.h" #include "crypto/randomx/randomx.h" #include "crypto/rx/RxAlgo.h" #include "crypto/rx/RxCache.h" #include <thread> #include <uv.h> namespace xmrig { static void init_dataset_wrapper(randomx_dataset *dataset, randomx_cache *cache, unsigned long startItem, unsigned long itemCount, int priority) { Platform::setThreadPriority(priority); if (Cpu::info()->hasAVX2() && (itemCount % 5)) { randomx_init_dataset(dataset, cache, startItem, itemCount - (itemCount % 5)); randomx_init_dataset(dataset, cache, startItem + itemCount - 5, 5); } else { randomx_init_dataset(dataset, cache, startItem, itemCount); } } } // namespace xmrig xmrig::RxDataset::RxDataset(bool hugePages, bool oneGbPages, bool cache, RxConfig::Mode mode, uint32_t node) : m_mode(mode), m_node(node) { allocate(hugePages, oneGbPages); if (isOneGbPages()) { m_cache = new RxCache(m_memory->raw() + VirtualMemory::align(maxSize())); return; } if (cache) { m_cache = new RxCache(hugePages, node); } } xmrig::RxDataset::RxDataset(RxCache *cache) : m_node(0), m_cache(cache) { } xmrig::RxDataset::~RxDataset() { randomx_release_dataset(m_dataset); delete m_cache; delete m_memory; } bool xmrig::RxDataset::init(const Buffer &seed, uint32_t numThreads, int priority) { if (!m_cache || !m_cache->get()) { return false; } m_cache->init(seed); if (!get()) { return true; } const uint64_t datasetItemCount = randomx_dataset_item_count(); if (numThreads > 1) { std::vector<std::thread> threads; threads.reserve(numThreads); for (uint64_t i = 0; i < numThreads; ++i) { const uint32_t a = (datasetItemCount * i) / numThreads; const uint32_t b = (datasetItemCount * (i + 1)) / numThreads; threads.emplace_back(init_dataset_wrapper, m_dataset, m_cache->get(), a, b - a, priority); } for (uint32_t i = 0; i < numThreads; ++i) { threads[i].join(); } } else { init_dataset_wrapper(m_dataset, m_cache->get(), 0, datasetItemCount, priority); } return true; } bool xmrig::RxDataset::isHugePages() const { return m_memory && m_memory->isHugePages(); } bool xmrig::RxDataset::isOneGbPages() const { return m_memory && m_memory->isOneGbPages(); } xmrig::HugePagesInfo xmrig::RxDataset::hugePages(bool cache) const { auto pages = m_memory ? m_memory->hugePages() : HugePagesInfo(); if (cache && m_cache) { pages += m_cache->hugePages(); } return pages; } size_t xmrig::RxDataset::size(bool cache) const { size_t size = 0; if (m_dataset) { size += maxSize(); } if (cache && m_cache) { size += RxCache::maxSize(); } return size; } uint8_t *xmrig::RxDataset::tryAllocateScrathpad() { auto p = reinterpret_cast<uint8_t *>(raw()); if (!p) { return nullptr; } const size_t offset = m_scratchpadOffset.fetch_add(RANDOMX_SCRATCHPAD_L3_MAX_SIZE); if (offset + RANDOMX_SCRATCHPAD_L3_MAX_SIZE > m_scratchpadLimit) { return nullptr; } return p + offset; } void *xmrig::RxDataset::raw() const { return m_dataset ? randomx_get_dataset_memory(m_dataset) : nullptr; } void xmrig::RxDataset::setRaw(const void *raw) { if (!m_dataset) { return; } volatile size_t N = maxSize(); memcpy(randomx_get_dataset_memory(m_dataset), raw, N); } void xmrig::RxDataset::allocate(bool hugePages, bool oneGbPages) { if (m_mode == RxConfig::LightMode) { LOG_ERR(CLEAR "%s" RED_BOLD_S "fast RandomX mode disabled by config", Tags::randomx()); return; } if (m_mode == RxConfig::AutoMode && uv_get_total_memory() < (maxSize() + RxCache::maxSize())) { LOG_ERR(CLEAR "%s" RED_BOLD_S "not enough memory for RandomX dataset", Tags::randomx()); return; } m_memory = new VirtualMemory(maxSize(), hugePages, oneGbPages, false, m_node); if (m_memory->isOneGbPages()) { m_scratchpadOffset = maxSize() + RANDOMX_CACHE_MAX_SIZE; m_scratchpadLimit = m_memory->capacity(); } m_dataset = randomx_create_dataset(m_memory->raw()); # ifdef XMRIG_OS_LINUX if (oneGbPages && !isOneGbPages()) { LOG_ERR(CLEAR "%s" RED_BOLD_S "failed to allocate RandomX dataset using 1GB pages", Tags::randomx()); } # endif }
/* * Complete the function below. */ int function(int x) { int sq = x*x; return sq; }
#include "iocoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QThread> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <QDesktopWidget> #include <QVBoxLayout> #include "stdlib.h" #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif const string BOOTSTRAP_LOCATION = "/home/argon/bootstrap.dat"; // Need a global reference for the notifications to find the GUI static IocoinGUI *guiref; static QSplashScreen *splashref; //static SplashScreen *splashref; // static string sha256(const string str) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, str.c_str(), str.size()); SHA256_Final(hash, &sha256); stringstream ss; for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) { ss << hex << setw(2) << setfill('0') << (int)hash[i]; } return ss.str(); } static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignVCenter|Qt::AlignHCenter, QColor(33,120,185)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", IocoinGUI::tr("A fatal error occurred. I/OCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } static int argc_; static char** argv_; extern "C" int setup_application(IocoinGUI& window, std::string directory) { bool init = true; boost::filesystem::path p(directory); boost::filesystem::directory_iterator end_itr; boost::filesystem::directory_iterator it(p); for(; it != end_itr; it++) { if(boost::filesystem::is_regular_file(it->path())) { string f = it->path().filename().string(); if(f == "iocoin.conf") { init=false; } } } if(init) { boost::filesystem::ofstream ofs(p / "iocoin.conf"); srand(time(NULL)); unsigned int r = rand(); string rStr = std::to_string(r); string defaultUser = sha256(rStr); r = rand(); string passStr = std::to_string(r); string pass = sha256(passStr); ofs << "rpcuser=" << defaultUser << endl; ofs << "rpcpassword=" << pass << endl; ofs << endl; ofs << endl; ofs << "addnode=amer.supernode.iocoin.io" << endl; ofs << "addnode=emea.supernode.iocoin.io" << endl; ofs << "addnode=apac.supernode.iocoin.io" << endl; } mapArgs["-datadir"] = directory.c_str(); ReadConfigFile(mapArgs, mapMultiArgs); AppInit2(); return 0; } extern "C" int app_init() { AppInit2(); return 0; } int main(int argc, char *argv[]) { Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); argc_=argc; argv_=argv; // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); app.setOrganizationName("I/OCoin"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("I/OCoin-Qt-testnet"); else app.setApplicationName("I/OCoin-Qt"); // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { IocoinGUI window; guiref = &window; { { if (splashref) splash.finish(&window); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } Shutdown(NULL); } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; }
#ifndef CREDITS_SCREEN #define CREDITS_SCREEN #include "game.h" #include "raylib.h" using namespace g_var; void updateCredits(); void drawCredits(); #endif // !CREDITS_SCREEN
#ifndef ACCES_INIT_H #define ACCES_INIT_H #include <QMainWindow> #include <QSqlDatabase> #include <QSqlQuery> #include <QDebug> #include <QtSql> #include <QSqlTableModel> #include <QMessageBox> class acces_init : public QMainWindow { Q_OBJECT public: explicit acces_init(QWidget *parent = nullptr); void initialisationBDD(QSqlDatabase database); protected: signals: void problemeConnexion(); public slots: }; #endif // ACCES_INIT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2000-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Yngve Pettersen */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #ifdef USE_SSL_CERTINSTALLER #include "modules/libssl/sslbase.h" #include "modules/libssl/sslrand.h" #include "modules/libssl/ssl_api.h" #include "modules/url/url2.h" #include "modules/cache/url_stream.h" #include "modules/libssl/certs/certinstaller.h" #include "modules/libssl/ui/certinst.h" #include "modules/windowcommander/src/SSLSecurtityPasswordCallbackImpl.h" #include "modules/util/opautoptr.h" OP_STATUS ExtractCertificates(SSL_varvector32 &input, const OpStringC8 &pkcs12_password, SSL_ASN1Cert_list &certificate_list, SSL_secure_varvector32 &private_key, SSL_varvector16 &pub_key_hash, uint16 &bits, SSL_BulkCipherType &type); BOOL load_PEM_certificates2(SSL_varvector32 &data_source, SSL_varvector32 &pem_content); OP_STATUS ParseCommonName(const OpString_list &info, OpString &title); SSL_Certificate_Installer_Base *SSL_API::CreateCertificateInstallerL(URL &source, const SSL_Certificate_Installer_flags &install_flags, SSL_dialog_config *config, SSL_Options *optManager) { if(config == NULL) { // Non-interactive SSL_Certificate_Installer *result = OP_NEW_L(SSL_Certificate_Installer, ()); OP_STATUS op_err = result->Construct(source, install_flags, optManager); if(OpStatus::IsError(op_err)) { OP_DELETE(result); LEAVE(op_err); } return result; } else { // Interactive SSL_Interactive_Certificate_Installer *result = OP_NEW_L(SSL_Interactive_Certificate_Installer, ()); OP_STATUS op_err = result->Construct(source, install_flags, *config, optManager); if(OpStatus::IsError(op_err)) { OP_DELETE(result); LEAVE(op_err); } return result; } } SSL_Certificate_Installer_Base *SSL_API::CreateCertificateInstallerL(SSL_varvector32 &source, const SSL_Certificate_Installer_flags &install_flags, SSL_dialog_config *config, SSL_Options *optManager) { if(config == NULL) { // Non-interactive SSL_Certificate_Installer *result = OP_NEW_L(SSL_Certificate_Installer, ()); OP_STATUS op_err = result->Construct(source, install_flags, optManager); if(OpStatus::IsError(op_err)) { OP_DELETE(result); LEAVE(op_err); } return result; } else { // Interactive SSL_Interactive_Certificate_Installer *result = OP_NEW_L(SSL_Interactive_Certificate_Installer, ()); OP_STATUS op_err = result->Construct(source, install_flags, *config, optManager); if(OpStatus::IsError(op_err)) { OP_DELETE(result); LEAVE(op_err); } return result; } } SSL_Certificate_Installer::SSL_Certificate_Installer() : decoded_data(FALSE), bits(0), type(SSL_RSA), certificate(NULL), optionsManager(NULL), created_manager(FALSE), store(SSL_Unknown_Store), warn_before_use(TRUE), forbid_use(TRUE), overwrite_exisiting(FALSE), set_preshipped(FALSE), is_pem(FALSE), finished_basic_install(FALSE), basic_install_success(FALSE), external_options(FALSE) { } SSL_Certificate_Installer::~SSL_Certificate_Installer() { OP_DELETE(certificate); certificate = NULL; if(optionsManager && optionsManager->dec_reference() == 0) OP_DELETE(optionsManager); optionsManager = NULL; password_import_key.Wipe(); } OP_STATUS SSL_Certificate_Installer::StartInstallation() { finished_basic_install = FALSE; basic_install_success = FALSE; OP_STATUS op_err; op_err = PrepareInstallation(); if(OpStatus::IsSuccess(op_err)) { SSL_dialog_config config; // Empty, no action op_err = PerformInstallation(config); } if(OpStatus::IsError(op_err)) { finished_basic_install = TRUE; basic_install_success = FALSE; return op_err; } basic_install_success = TRUE; InstallationLastStep(); finished_basic_install = TRUE; return InstallerStatus::INSTALL_FINISHED; } BOOL SSL_Certificate_Installer::Finished() { return finished_basic_install; } BOOL SSL_Certificate_Installer::InstallSuccess() { return basic_install_success; } Str::LocaleString SSL_Certificate_Installer::ErrorStrings(OpString &info) { info.Empty(); Install_errors *message = (Install_errors *) install_messages.First(); if(!message) return Str::S_NOT_A_STRING; Str::LocaleString msg = message->message; info.TakeOver(message->info); message->Out(); OP_DELETE(message); return msg; } OP_STATUS SSL_Certificate_Installer::Construct(URL &source, const SSL_Certificate_Installer_flags &inst_flags, SSL_Options *optManager) { SSL_varvector32 data; // Load the certificate URL_DataStream source_stream(source, TRUE); TRAPD(op_err, data.AddContentL(&source_stream)); if(OpStatus::IsError(op_err)) { basic_install_success = FALSE; finished_basic_install = TRUE; return op_err; } if(data.ErrorRaisedFlag || data.GetLength() == 0) { //AddErrorString(Str::SI_MSG_SECURE_ILLEGAL_FORMAT, NULL); basic_install_success = FALSE; finished_basic_install = TRUE; return OpStatus::ERR_PARSING_FAILED; } return Construct(data, inst_flags, optManager); } OP_STATUS SSL_Certificate_Installer::Construct(DataStream_ByteArray_Base &source1, const SSL_Certificate_Installer_flags &inst_flags, SSL_Options *optManager) { SSL_varvector32 data; data.Set(source1); RETURN_IF_ERROR(data.GetOPStatus()); return Construct(data, inst_flags, optManager); } OP_STATUS SSL_Certificate_Installer::PreprocessVector(SSL_varvector32& source, SSL_varvector32& target) { target.Resize(0); uint32 source_length = source.GetLength(); if (source_length == 0) return OpStatus::ERR; // The PEM parser expects to have a trailing '\0' in the // buffer, however it might not be present - and it can // not be added to the original SSL_varvector32 instance // if its payload has been set from elsewhere. Therefore // we clone it so we can append the trailing '\0' ourselves // and be sure that string-related functions will not bring // the process down with a crash. SSL_varvector32 clone; clone.Set(source); RETURN_IF_ERROR(clone.GetOPStatus()); clone.Append("\0", 1); RETURN_IF_ERROR(clone.GetOPStatus()); // Detect PEM source uint32 pos = 0; byte *data = clone.GetDirect(); BOOL pem_found = FALSE; while (pos +10 <= source_length) { if(!op_isspace(data[pos])) { if(op_strnicmp((char *) data+pos, "-----BEGIN",10) == 0) { if (!load_PEM_certificates2(clone, target)) return OpStatus::ERR_PARSING_FAILED; if (target.GetLength() == 0) return OpStatus::ERR_PARSING_FAILED; pem_found = TRUE; // Stop after the first certificate break; } } pos ++; } if (!pem_found) { target.Set(source); RETURN_IF_ERROR(target.GetOPStatus()); } return OpStatus::OK; } OP_STATUS SSL_Certificate_Installer::Construct(SSL_varvector32& source, const SSL_Certificate_Installer_flags &inst_flags, SSL_Options *optManager) { if(optManager != NULL) { optionsManager = optManager; optionsManager->inc_reference(); external_options = TRUE; } else { optionsManager = g_ssl_api->CreateSecurityManager(TRUE); if(optionsManager == NULL) return OpStatus::ERR_NO_MEMORY; external_options = FALSE; } OP_STATUS status = PreprocessVector(source, original_data); if (OpStatus::IsError(status)) { original_data.Resize(0); basic_install_success = FALSE; finished_basic_install = TRUE; return status; } store = inst_flags.store; warn_before_use = inst_flags.warn_before_use; forbid_use = inst_flags.forbid_use; return OpStatus::OK; } OP_STATUS SSL_Certificate_Installer::AddErrorString(Str::LocaleString msg, const OpStringC &info) { if(msg == Str::S_NOT_A_STRING) return OpStatus::OK; Install_errors *message = OP_NEW(Install_errors, ()); if(message == NULL) return OpStatus::ERR_NO_MEMORY; message->message = msg; OpStatus::Ignore(message->info.Set(info)); // OOM usually not serious in this case message->Into(&install_messages); return OpStatus::OK; } OP_STATUS SSL_Certificate_Installer::PrepareInstallation() { OP_STATUS op_err = ExtractCertificates(original_data, password_import_key, original_cert, private_key, pub_key_hash, bits, type); if(OpStatus::IsError(op_err)) { switch(op_err) { case InstallerStatus::ERR_UNSUPPORTED_KEY_ENCRYPTION : AddErrorString(Str::S_MSG_SECURE_INSTALL_UNSUPPORTED_ENCRYPTION, NULL); return op_err; case InstallerStatus::ERR_PASSWORD_NEEDED: #ifndef SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION return InstallerStatus::ERR_PASSWORD_NEEDED; #else op_err = InstallerStatus::ERR_INSTALL_FAILED; #endif // Fall through if support is disabled default : AddErrorString(Str::SI_MSG_SECURE_INSTALL_FAILED, NULL); return op_err; } } if(original_cert.Count() == 0) return private_key.GetLength() ? OpStatus::OK : InstallerStatus::ERR_PARSING_FAILED; if(private_key.GetLength() != 0) store = SSL_ClientStore; op_err = VerifyCertificate(); RETURN_IF_ERROR(op_err); if(op_err == InstallerStatus::VERIFYING_CERT) return op_err; return CheckClientCert(); } OP_STATUS SSL_Certificate_Installer::VerifyCertificate() { uint32 i, count; certificate = g_ssl_api->CreateCertificateHandler(); if(certificate == NULL) return OpStatus::ERR_NO_MEMORY; certificate->LoadCertificate(original_cert); SSL_Alert msg; if(!certificate->VerifySignatures((store == SSL_ClientStore ? SSL_Purpose_Client_Certificate : SSL_Purpose_Any), &msg #ifdef LIBSSL_ENABLE_CRL_SUPPORT , NULL #endif // LIBSSL_ENABLE_CRL_SUPPORT , optionsManager, TRUE // The certificate may be new. No reason to trigger an error, so this is a "standalone" verification )) { switch(msg.GetDescription()) { case SSL_Certificate_Expired: AddErrorString(Str::SI_MSG_HTTP_SSL_Certificate_Expired, NULL); return InstallerStatus::ERR_PARSING_FAILED; default : AddErrorString(Str::SI_MSG_SECURE_INSTALL_FAILED, NULL); return InstallerStatus::ERR_PARSING_FAILED; } } // Check that the certificate chain is correctly ordered so that the user does not have to // parse the chain, and that there is only one chain, not multiple chains. SSL_ASN1Cert_list val_certs; certificate->GetValidatedCertificateChain(val_certs); if(val_certs.Error()) { return val_certs.GetOPStatus(); } count = certificate->CertificateCount(); if(count >val_certs.Count()) { AddErrorString(Str::SI_MSG_SECURE_INVALID_CHAIN, NULL); return InstallerStatus::ERR_PARSING_FAILED; } OP_ASSERT(val_certs.Count() > 0); for(i = 0; i< count; i++) { if(val_certs[i] != original_cert[i]) { AddErrorString(Str::SI_MSG_SECURE_INVALID_CHAIN, NULL); return InstallerStatus::ERR_PARSING_FAILED; } } SSL_CertificateHandler *val_certificate = g_ssl_api->CreateCertificateHandler(); if(val_certificate == NULL) return OpStatus::ERR_NO_MEMORY; val_certificate->LoadCertificate(val_certs); if(!val_certificate->SelfSigned(count-1)) { // Incomplete chain // TO-DO: Action } OP_DELETE(val_certificate); return InstallerStatus::OK; } OP_STATUS SSL_Certificate_Installer::CheckClientCert() { SSL_varvector16 key_hash; if(store == SSL_ClientOrCA_Store) { certificate->GetPublicKeyHash(0,key_hash); RETURN_IF_ERROR(optionsManager->Init(SSL_ClientStore)); SSL_CertificateItem *clientcert = optionsManager->FindClientCertByKey(key_hash); store = (clientcert == NULL ? SSL_CA_Store : SSL_ClientStore); } #ifdef SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION if(store == SSL_ClientStore) { AddErrorString(Str::SI_MSG_SECURE_INSTALL_FAILED, NULL); return InstallerStatus::ERR_INSTALL_FAILED; } #else // !SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION if(store == SSL_ClientStore && private_key.GetLength() == 0) { certificate->GetPublicKeyHash(0,key_hash); RETURN_IF_ERROR(optionsManager->Init(SSL_ClientStore)); SSL_CertificateItem *clientcert = optionsManager->FindClientCertByKey(key_hash); if(clientcert == NULL) { AddErrorString(Str::SI_MSG_SECURE_NO_KEY, NULL); return InstallerStatus::ERR_PARSING_FAILED; } if(clientcert->certificate.GetLength() != 0) { if(clientcert->certificate != original_cert[0]) { AddErrorString(Str::SI_MSG_SECURE_DIFFERENTCLIENT, NULL); return InstallerStatus::ERR_PARSING_FAILED; } return InstallerStatus::INSTALL_FINISHED; } } #endif // SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION return InstallerStatus::OK; } OP_STATUS SSL_Certificate_Installer::PerformInstallation(SSL_dialog_config &config) { #ifndef SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION if(private_key.GetLength() != 0) { RETURN_IF_ERROR(optionsManager->Init(SSL_ClientStore)); RETURN_IF_ERROR(optionsManager->AddPrivateKey(type, bits, private_key, pub_key_hash, (const uni_char *) NULL, config)); } #endif SSL_varvector16 key_hash, key_hash2; SSL_DistinguishedName subject, issuer, issuer2; OpString_list info; uint24 count = original_cert.Count(); if(count) { SSL_CertificateStore current_store = store; uint24 i; for(i = 0; i< count; i++) { if(current_store == SSL_ClientStore) { RETURN_IF_ERROR(optionsManager->Init(SSL_ClientStore)); certificate->GetPublicKeyHash(0,key_hash); SSL_CertificateItem *clientcert = optionsManager->FindClientCertByKey(key_hash); if(clientcert == NULL || clientcert->certificate.GetLength() != 0) { if (clientcert && (clientcert->certificate.GetLength() != 0)) return InstallerStatus::ERR_CERTIFICATE_ALREADY_PRESENT; return InstallerStatus::ERR_INSTALL_FAILED; } clientcert->certificatetype = certificate->CertificateType(0); clientcert->certificate = original_cert[0]; certificate->GetSubjectName(0,clientcert->name); clientcert->cert_title.Empty(); if ( OpStatus::IsError(certificate->GetSubjectName(0,info)) || OpStatus::IsError(ParseCommonName(info, clientcert->cert_title) )) { return InstallerStatus::ERR_INSTALL_FAILED; } if(optionsManager->register_updates && clientcert->cert_status != Cert_Inserted) clientcert->cert_status = Cert_Updated; current_store = SSL_CA_Store; } else { certificate->GetSubjectName(i, subject); SSL_CertificateStore use_store = current_store; if(use_store == SSL_CA_Store && !certificate->SelfSigned(i)) use_store = SSL_IntermediateCAStore; RETURN_IF_ERROR(optionsManager->Init(use_store)); SSL_CertificateItem *last_item = NULL; SSL_CertificateItem *cert_item; do{ cert_item = optionsManager->Find_Certificate(use_store, subject, last_item); if(cert_item == NULL && use_store != current_store) cert_item = optionsManager->Find_Certificate(current_store, subject, last_item); last_item = cert_item; if(cert_item) { SSL_CertificateHandler *handler = cert_item->GetCertificateHandler(); if(handler) { certificate->GetIssuerName(i, issuer); handler->GetIssuerName(i, issuer2); if(issuer != issuer2) continue; certificate->GetPublicKeyHash(i,key_hash); handler->GetPublicKeyHash(i,key_hash2); if(key_hash != key_hash2) continue; if(!overwrite_exisiting) break; // Do not overwrite exisiting // Delete the old object; commit is not able to override the old. if(optionsManager->register_updates) { cert_item->cert_status = Cert_Deleted; OP_DELETE(cert_item->handler); cert_item->handler = NULL; } else { cert_item->Out(); OP_DELETE(cert_item); } cert_item = NULL; } else continue; } if(cert_item == NULL) { cert_item = OP_NEW(SSL_CertificateItem, ()); if(cert_item == NULL) { return InstallerStatus::ERR_INSTALL_FAILED; } if(optionsManager->register_updates) cert_item->cert_status = Cert_Inserted; } else if(optionsManager->register_updates) cert_item->cert_status = Cert_Updated; cert_item->certificate = original_cert[i]; cert_item->certificatetype = certificate->CertificateType(i); cert_item->WarnIfUsed = (i != count-1 || warn_before_use); cert_item->DenyIfUsed = (i == count-1 && forbid_use); cert_item->cert_title.Set(suggested_name); if(set_preshipped) cert_item->PreShipped = TRUE; OP_STATUS ParseCommonName(const OpString_list &info, OpString &title); certificate->GetSubjectName(i,cert_item->name); if ( OpStatus::IsError(certificate->GetSubjectName(i,info)) || (cert_item->cert_title.IsEmpty() && OpStatus::IsError(ParseCommonName(info, cert_item->cert_title))) ) { if(!cert_item->InList()) OP_DELETE(cert_item); return InstallerStatus::ERR_INSTALL_FAILED; } if(!cert_item->InList()) optionsManager->AddCertificate(use_store, cert_item); break; }while(cert_item != NULL); } } } return InstallerStatus::OK; } void SSL_Certificate_Installer::InstallationLastStep() { if(InstallSuccess() && !external_options) g_ssl_api->CommitOptionsManager(optionsManager); } OP_STATUS SSL_Certificate_Installer::SetImportPassword(const char *pass) { return password_import_key.Set(pass); } #endif // USE_SSL_CERTINSTALLER #endif // relevant support
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ /** * @file gadgets_module.h * Global declarations for the gadgets module. * * @author Lasse Magnussen <lasse@opera.com> */ #ifndef GADGETS_MODULE_H #define GADGETS_MODULE_H #ifdef GADGET_SUPPORT #include "modules/hardcore/opera/module.h" #define NUMBER_OF_DEFAULT_START_FILES 5 #define NUMBER_OF_DEFAULT_ICONS 5 class OpGadgetManager; class OpGadgetParsers; struct widget_namespace; class GadgetsModule : public OperaModule { public: GadgetsModule(); void InitL(const OperaInitInfo& info); void Destroy(); OpGadgetManager* m_gadget_manager; OpGadgetParsers* m_gadget_parsers; #ifndef HAS_COMPLEX_GLOBALS const char *m_gadget_start_file[NUMBER_OF_DEFAULT_START_FILES]; const char *m_gadget_start_file_type[NUMBER_OF_DEFAULT_START_FILES]; const char *m_gadget_default_icon[NUMBER_OF_DEFAULT_ICONS]; /*static const char *m_gadget_default_icon_type[NUMBER_OF_DEFAULT_ICONS];*/ #endif }; /** Singleton global instance of OpGadgetParsers */ #define g_gadget_parsers (g_opera->gadgets_module.m_gadget_parsers) #ifndef HAS_COMPLEX_GLOBALS /* Internal arrays */ # define g_gadget_start_file (g_opera->gadgets_module.m_gadget_start_file) # define g_gadget_start_file_type (g_opera->gadgets_module.m_gadget_start_file_type) # define g_gadget_default_icon (g_opera->gadgets_module.m_gadget_default_icon) # define g_gadget_default_icon_type (g_opera->gadgets_module.m_gadget_default_icon_type) #endif #define GADGETS_MODULE_REQUIRED #endif // GADGET_SUPPORT #endif // !GADGETS_MODULE_H
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/GameMode.h" #include "DuranteGameMode.generated.h" UCLASS(minimalapi) class ADuranteGameMode : public AGameMode { GENERATED_BODY() public: ADuranteGameMode(const FObjectInitializer& ObjectInitializer); };
#include "DataProcessor.h" #include "SQLiteManager.h" #include "PredicateConstructor.h" #include "TransitionGenerator.h" #include "Situation.h" #include "Transition.h" #include "PredicateVehicle.h" #include "VehicleData.h" #include <iostream> #include <map> #include <thread> using std::make_unique; using std::make_shared; using std::shared_ptr; using std::unique_ptr; using std::string; using std::move; using std::cout; using std::endl; using std::map; using std::thread; using std::mutex; DataProcessor::DataProcessor(unique_ptr<DataManager> dm) : currentSituation(nullptr) , dataManager(move(dm)) , predicateCreator() , transitionGenerator() , stopped(false) { } DataProcessor::~DataProcessor() { stop(); } void DataProcessor::processData(std::vector<unique_ptr<VehicleData>> data) { std::unique_lock<mutex> lck(mtx); workingQueue.push(move(data)); if(processingThread.get_id() == thread::id()) { processingThread = std::thread([this] { processingTask(); }); } cv.notify_all(); } DataProcessor::DataProcessor() { } void DataProcessor::processingTask() { while(!stopped || !workingQueue.empty()) { std::unique_lock<mutex> lck(mtx); while(!stopped && workingQueue.empty()) { cv.wait(lck); } if(stopped && workingQueue.empty()) { return; } std::vector<unique_ptr<VehicleData>> data = move(workingQueue.front()); workingQueue.pop(); lck.unlock(); std::vector<shared_ptr<PredicateVehicle>> pVehicles = predicateCreator.transform(move(data)); shared_ptr<PredicateVehicle> vut = pVehicles[0]; pVehicles.erase(pVehicles.begin()); shared_ptr<Situation> newSituation = make_shared<Situation>(vut, pVehicles, false); //Initial Situation of the recording session if(currentSituation == nullptr) { currentSituation = move(newSituation); } //do not record transitions between stable situations else if(newSituation->isStable() && currentSituation->isStable()) { currentSituation = move(newSituation); } //Initial situation of the next sequence else if(currentSituation->isStable() && !newSituation->isStable()) { currentSituation->markInitial(); unique_ptr<Transition> trans = move(transitionGenerator.generate(currentSituation, newSituation)); if(trans) { currentSituation = newSituation; dataManager->storeTransition(*trans); } } //transition between two unstable Situation or from an unstable to a stable Situation else { unique_ptr<Transition> trans = move(transitionGenerator.generate(currentSituation, newSituation)); if(trans) { currentSituation = newSituation; dataManager->storeTransition(*trans); } } } } std::unique_ptr<DataManager> const & DataProcessor::getDataManager() { return dataManager; } shared_ptr<Situation> const & DataProcessor::getCurrentSituation() { std::unique_lock<mutex>(mtx); return currentSituation; } void DataProcessor::stop() { cout << "Stopping Simulation, processing queued data points: " << workingQueue.size() << endl; stopped = true; cv.notify_all(); if(processingThread.joinable()) { processingThread.join(); } }
// // Created by Stephen Clyde on 1/19/17. // #ifndef FORMATTEDTABLE_FORMATTEDCELL_H #define FORMATTEDTABLE_FORMATTEDCELL_H #include <ostream> #include <string> #include "ColumnDefinition.hpp" class FormattedCell { private: enum allocatedDataType { Unknown, String, Integer, Float}; allocatedDataType m_dataType = allocatedDataType::Unknown; void* m_value = nullptr; std::string m_formattedValue; ColumnDefinition* m_columnDefinition = nullptr; public: FormattedCell(std::string value); FormattedCell(int value); FormattedCell(float value); ~FormattedCell(); void setColumnDefinition(ColumnDefinition* columnDefinition); void write(std::ostream& outputStream); private: void setupFormattedValue(std::ostream& outputStream); void setupWidthAndJustification(std::ostream &outputStream); }; #endif //FORMATTEDTABLE_FORMATTEDCELL_H
#include "mouseeventholder.cpp" frmMain::frmMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::frmMain) { ui->setupUi(this); PalletScene = new QGraphicsScene(0, 0, ui->graphicsView->geometry().width(), ui->graphicsView->geometry().height(), this); dx = ui->graphicsView->geometry().x(); dy = ui->graphicsView->geometry().y(); flag = 0; lboxSelected = 0; setFlag(); points = QVector<geometry::Point>(); segments = QVector<QPair<int, int> >(); temp = points; } void frmMain::fixSegments(int from , int to) { for (auto &i : segments) { if (i.first == from) i.first = to; if (i.second == from) i.second = to; } } frmMain::~frmMain() { delete ui; } void frmMain::clearPalletScene() { PalletScene = new QGraphicsScene(0, 0, ui->graphicsView->geometry().width(), ui->graphicsView->geometry().height(), this); } void frmMain::setPalletScene() { clearPalletScene(); geometry::Segment::drawSegments(PalletScene, points, segments); geometry::Point::drawPoints(PalletScene, points); ui->graphicsView->setScene(PalletScene); } void frmMain::on_cmbPoint_activated(int index) { lboxSelected = 0; flag = index; setFlag(); } void frmMain::on_leType_returnPressed() { if (flag == 21) { bool isDone; double angleDeg = ui->leType->text().toDouble(&isDone); // QString t = ui->lblType->text(); if (isDone) { flag = 2; geometry::Point pp = geometry::Point::rotate(points[selected[0]], points[selected[1]], angleDeg * M_PI / 180.0); geometry::Point::insertPoint(points, pp); setPalletScene(); setFlag(); ui->leType->setEnabled(false); ui->lblType->setEnabled(false); selected.clear(); } } } void frmMain::on_cmbSegm_activated(int index) { lboxSelected = 1; flag = index + 1; setFlag(); } void frmMain::on_pushButton_clicked() { points.clear(); segments.clear(); selected.clear(); setPalletScene(); // flag = 0; // lboxSelected = 0; }
#pragma once #include "bricks/collections/array.h" namespace Bricks { namespace Collections { template<typename T> class AutoArray : public Array<T*> { protected: static void Retain(T* value) { AutoPointer<>::Retain(value); } static void Release(T* value) { AutoPointer<>::Release(value); } void RetainAll() { BRICKS_FOR_EACH (T*const& item, this) Retain(item); } void ReleaseAll() { BRICKS_FOR_EACH (T*const& item, this) Release(item); } public: AutoArray(const AutoArray<T>& array, ValueComparison<T*>* comparison = NULL) : Array<T*>(array, comparison) { RetainAll(); } AutoArray(ValueComparison<T*>* comparison = autonew OperatorValueComparison<T*>()) : Array<T*>(comparison) { } AutoArray(Iterable<T*>* iterable, ValueComparison<T*>* comparison = autonew OperatorValueComparison<T*>()) : Array<T*>(iterable, comparison) { RetainAll(); } ~AutoArray() { ReleaseAll(); } AutoArray& operator =(const AutoArray<T>& array) { Array<T*> toRelease(*this); Array<T*>::operator=(array); RetainAll(); BRICKS_FOR_EACH (T*const& item, toRelease) Release(item); return *this; } void AddItem(T*const& value) { Array<T*>::AddItem(value); Retain(value); } bool RemoveItem(T*const& value) { long index = Array<T*>::IndexOfItem(value); if (index >= 0) { T* item = Array<T*>::GetItem(index); Array<T*>::RemoveItemAt(index); Release(item); return true; } return false; } void RemoveItems(T*const& value) { Retain(value); while (RemoveItem(value)) ; Release(value); } void Clear() { ReleaseAll(); Array<T*>::Clear(); } void SetItem(long index, T*const& value) { T* item = Array<T*>::GetItem(index);Array<T*>::SetItem(index, value); Release(item); Retain(value); } void InsertItem(long index, T*const& value) { Array<T*>::InsertItem(index, value); Retain(value); } void RemoveItemAt(long index) { T* item = Array<T*>::GetItem(index); Array<T*>::RemoveItemAt(index); Release(item); } }; } }
#include <iostream> #include <algorithm> #include <numeric> using namespace std; using ll = long long; int main() { int n, m; cin >> n >> m; ll a[n], c[n]; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) cin >> c[i]; int order[n]; iota(order, order + n, 0); sort(order, order + n, [&](int i, int j) { return c[i] < c[j]; }); int itr = 0; for (int i = 0; i < m; ++i) { int t; ll d; cin >> t >> d; --t; ll ans = 0; while (d > 0 && itr < n) { ll g = min(d, a[t]); // tを出せる最大枚数 ans += c[t] * g; d -= g, a[t] -= g; if (t != order[itr]) { t = order[itr]; // 最初だけ例外処理 } else if (a[t] == 0) { t = order[++itr]; // 次に安い料理へ } } // d > 0なら客は怒って帰ったので0 cout << (d == 0 ? ans : 0) << endl; } return 0; }
#include "widget.h" #include <QVBoxLayout> //垂直布局 #include <QHBoxLayout> //水平布局 #include <QGridLayout> //网状布局 Widget::Widget(QWidget *parent) : QWidget(parent) { //this->setMinimumSize(640, 480); //设置this窗口的最小大小 b1 = new QPushButton("OK", this);//按键依附于this窗口 b2 = new QPushButton("Cancel", this); b3 = new QPushButton("up", this); le = new MyQLineEdit(this); #if 1 //布局layout,按先后添加关系布局 QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(le); vbox->addWidget(b1); //将需要布局的控件放入该布局 vbox->addWidget(b2); vbox->addWidget(b3); this->setLayout(vbox); //设置主窗口的布局 #else //网状布局 QGridLayout *gbox = new QGridLayout; gbox->addWidget(le, 0, 0, 1, 1); //0行0裂占1行1格 gbox->addWidget(b1, 1, 1, 1, 1); gbox->addWidget(b2, 2, 1, 1, 1); this->setLayout(gbox); #endif //连接信号与曹 connect(b2, SIGNAL(clicked()), le, SLOT(clear())); connect(b3, SIGNAL(clicked()), le, SLOT(touper())); } Widget::~Widget() { }
//******************************************** // Student Name : // Student ID : // Student Email Address: //******************************************** // // Instructor: Sai-Keung WONG // Email: cswingo@cs.nctu.edu.tw // wingo.wong@gmail.com // // National Chiao Tung University, Taiwan // Computer Science // Date: 2017/02 // #include <iostream> #include "mySystem_GraphSystem.h" #include <time.h> using namespace std; GRAPH_SYSTEM::GRAPH_SYSTEM( ) { mFlgAutoNodeDeletion = false; createDefaultGraph(); // // Implement your own stuff // } void GRAPH_SYSTEM::reset( ) { stopAutoNodeDeletion(); mPassiveSelectedNode = 0; mSelectedNode = 0; // // Implement your own stuff // } void GRAPH_SYSTEM::createDefaultGraph( ) { reset( ); // // Implement your own stuff // } void GRAPH_SYSTEM::createRandomGraph_DoubleCircles(int n) { reset( ); float dx = 5.0; float dz = 5.0; float r = 15; // radius float d = 10; // layer distance float offset_x = 15.; float offset_z = 15.; // // Implement your own stuff // } void GRAPH_SYSTEM::createNet_Circular( int n, int num_layers ) { reset( ); float dx = 5.0; float dz = 5.0; float r = 5; // radius float d = 5; // layer distance float offset_x = 15.; float offset_z = 15.; // // Implement your own stuff // } void GRAPH_SYSTEM::createNet_Square( int n, int num_layers ) { reset( ); float dx = 5.0; float dz = 5.0; float r = 5; // radius float d = 5; // layer distance float offset_x = 5.; float offset_z = 5.; // // Implement your own stuff // } void GRAPH_SYSTEM::createNet_RadialCircular( int n ) { reset( ); float offset_x = 15.0; float offset_z = 15.0; float r = 15; // radius // // Implement your own stuff // } // return node id int GRAPH_SYSTEM::addNode( float x, float y, float z, float r ) { // // Implement your own stuff // return -1; } // return edge id int GRAPH_SYSTEM::addEdge( int nodeID_0, int nodeID_1 ) { // // Implement your own stuff // return -1; } void GRAPH_SYSTEM::askForInput( ) { // // Implement your own stuff // } GRAPH_NODE *GRAPH_SYSTEM::findNearestNode( double x, double z, double &cur_distance2 ) const { GRAPH_NODE *n = 0; // // Implement your own stuff // return n; } // // compute mSelectedNode // void GRAPH_SYSTEM::clickAt(double x, double z) { // // Implement your own stuff // // mSelectedNode = n; } void GRAPH_SYSTEM::deleteNode( int nodeID ) { // // Implement your own stuff // } void GRAPH_SYSTEM::deleteSelectedNode( ) { // // Implement your own stuff // } bool GRAPH_SYSTEM::isSelectedNode( ) const { // // mSelectedNode != 0; // // Implement your own stuff // return false; } void GRAPH_SYSTEM::getInfoOfSelectedPoint( double &r, vector3 &p ) const { // r = mSelectedNode->r; // p = mSelectedNode->p; // // Implement your own stuff // } void GRAPH_SYSTEM::handleKeyPressedEvent( unsigned char key ) { switch( key ) { case 127: // delete mFlgAutoNodeDeletion = false; deleteSelectedNode( ); break; case '1': mFlgAutoNodeDeletion = false; createDefaultGraph( ); mSelectedNode = 0; break; case '2': mFlgAutoNodeDeletion = false; createNet_Circular(12, 3); mSelectedNode = 0; break; case '3': mFlgAutoNodeDeletion = false; createNet_Square(5, 4); // you can modify this mSelectedNode = 0; break; case '4': mFlgAutoNodeDeletion = false; createNet_RadialCircular(24); mSelectedNode = 0; break; case '5': mFlgAutoNodeDeletion = false; createRandomGraph_DoubleCircles(24); mSelectedNode = 0; break; case ' ': mFlgAutoNodeDeletion = false; mSelectedNode = 0; break; case 'g': mFlgAutoNodeDeletion = !mFlgAutoNodeDeletion; break; } } void GRAPH_SYSTEM::handlePassiveMouseEvent( double x, double z ) { double cur_d2; GRAPH_NODE *n = findNearestNode( x, z, cur_d2 ); if ( n == 0 ) return; if ( cur_d2 > n->r*n->r ) { mPassiveSelectedNode = 0; return; } mPassiveSelectedNode = n; } // // get the number of nodes // int GRAPH_SYSTEM::getNumOfNodes( ) const { // // Implement your own stuff // return 0; } void GRAPH_SYSTEM::getNodeInfo( int nodeIndex, double &r, vector3 &p ) const { // // Implement your own stuff // } // // return the number of edges // int GRAPH_SYSTEM::getNumOfEdges( ) const { // // Implement your own stuff // return 0; } // // an edge should have two nodes: index 0 and index 1 // return the position of node with nodeIndex // vector3 GRAPH_SYSTEM::getNodePositionOfEdge( int edgeIndex, int nodeIndex ) const { vector3 p; // // Implement your own stuff // return p; } void GRAPH_SYSTEM::stopAutoNodeDeletion() { mFlgAutoNodeDeletion = false; } // // For every frame, update( ) function is called. // // void GRAPH_SYSTEM::update( ) { if (!mFlgAutoNodeDeletion) { return; } mSelectedNode = 0; mPassiveSelectedNode = 0; Sleep(250); // // // Implement your own stuff // }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef WEBFEEDS_BACKEND_SUPPORT #include "modules/dom/src/feeds/domfeedentry.h" #include "modules/dom/src/feeds/domfeedcontent.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/webfeeds/webfeeds_api.h" /* virtual */ DOM_FeedEntry::~DOM_FeedEntry() { if (m_entry) { OP_ASSERT(m_entry->GetDOMObject(GetEnvironment()) == *this); m_entry->SetDOMObject(NULL, GetEnvironment()); m_entry->DecRef(); } } /* static */ OP_STATUS DOM_FeedEntry::Make(DOM_FeedEntry *&out_entry, OpFeedEntry *entry, DOM_Runtime *runtime) { // Check that there isn't already a DOM object for // this OpFeedEntry. One is more than enough. OP_ASSERT(!entry->GetDOMObject(runtime->GetEnvironment())); RETURN_IF_ERROR(DOMSetObjectRuntime(out_entry = OP_NEW(DOM_FeedEntry, ()), runtime, runtime->GetPrototype(DOM_Runtime::FEEDENTRY_PROTOTYPE), "FeedEntry")); entry->IncRef(); out_entry->m_entry = entry; entry->SetDOMObject(*out_entry, runtime->GetEnvironment()); return OpStatus::OK; } /* virtual */ ES_GetState DOM_FeedEntry::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch (property_name) { case OP_ATOM_author: DOMSetString(value, m_entry->GetAuthor()); return GET_SUCCESS; case OP_ATOM_id: DOMSetNumber(value, m_entry->GetId()); return GET_SUCCESS; case OP_ATOM_keep: DOMSetBoolean(value, m_entry->GetKeep()); return GET_SUCCESS; case OP_ATOM_publicationDate: { ES_Value date_value; // double arithmetics DOMSetNumber(&date_value, m_entry->GetPublicationDate()); ES_Object* date_obj; GET_FAILED_IF_ERROR(GetRuntime()->CreateNativeObject(date_value, ENGINE_DATE_PROTOTYPE, &date_obj)); DOMSetObject(value, date_obj); } return GET_SUCCESS; case OP_ATOM_title: case OP_ATOM_content: { OpFeedContent *content = property_name == OP_ATOM_title ? m_entry->GetTitle() : m_entry->GetContent(); if (content) { DOM_HOSTOBJECT_SAFE(dom_content, content->GetDOMObject(GetEnvironment()), DOM_TYPE_FEEDCONTENT, DOM_FeedContent); if (!dom_content) GET_FAILED_IF_ERROR(DOM_FeedContent::Make(dom_content, content, GetRuntime())); DOMSetObject(value, dom_content); return GET_SUCCESS; } DOMSetNull(value); } return GET_SUCCESS; case OP_ATOM_status: DOMSetNumber(value, m_entry->GetReadStatus()); return GET_SUCCESS; case OP_ATOM_uri: { URL pri_link = m_entry->GetPrimaryLink(); DOMSetString(value, pri_link.GetAttribute(URL::KUniName_With_Fragment_Escaped).CStr()); } return GET_SUCCESS; } return GET_FAILED; } /* virtual */ ES_PutState DOM_FeedEntry::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch (property_name) { case OP_ATOM_author: case OP_ATOM_content: case OP_ATOM_id: case OP_ATOM_publicationDate: case OP_ATOM_title: case OP_ATOM_uri: return PUT_READ_ONLY; case OP_ATOM_keep: if (value->type != VALUE_BOOLEAN) return PUT_NEEDS_BOOLEAN; m_entry->SetKeep(value->value.boolean); return PUT_SUCCESS; case OP_ATOM_status: if (value->type != VALUE_NUMBER) return PUT_NEEDS_NUMBER; int intvalue = (int) value->value.number; if (intvalue >= OpFeedEntry::STATUS_UNREAD && intvalue <= OpFeedEntry::STATUS_DELETED) m_entry->SetReadStatus((OpFeedEntry::ReadStatus) intvalue); return PUT_SUCCESS; } return PUT_FAILED; } /* static */ int DOM_FeedEntry::getProperty(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(entry, DOM_TYPE_FEEDENTRY, DOM_FeedEntry); DOM_CHECK_ARGUMENTS("s"); DOMSetString(return_value, entry->m_entry->GetProperty(argv[0].value.string)); return ES_VALUE; } /* static */ void DOM_FeedEntry::ConstructFeedEntryObjectL(ES_Object *object, DOM_Runtime *runtime) { PutNumericConstantL(object, "STATUS_UNREAD", OpFeedEntry::STATUS_UNREAD, runtime); PutNumericConstantL(object, "STATUS_READ", OpFeedEntry::STATUS_READ, runtime); PutNumericConstantL(object, "STATUS_DELETED", OpFeedEntry::STATUS_DELETED, runtime); } #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_START(DOM_FeedEntry) DOM_FUNCTIONS_FUNCTION(DOM_FeedEntry, DOM_FeedEntry::getProperty, "getProperty", "s-") DOM_FUNCTIONS_END(DOM_FeedEntry) #endif // WEBFEEDS_BACKEND_SUPPORT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SVG_MARKER_H #define SVG_MARKER_H #if defined(SVG_SUPPORT) && defined(SVG_SUPPORT_MARKERS) #include "modules/svg/svg_number.h" #include "modules/svg/src/SVGRect.h" #include "modules/svg/src/SVGMatrix.h" #include "modules/svg/src/SVGNumberPair.h" #include "modules/svg/src/SVGPoint.h" #include "modules/svg/src/SVGTraverse.h" #include "modules/svg/src/OpBpath.h" #include "modules/svg/src/SVGValue.h" #include "modules/util/simset.h" class OpBpath; class PathSegListIterator; class SVGPathSeg; class SVGVector; class LayoutProperties; class HTML_Element; /** * Iterate through the marker positions on a (graphic) element */ class SVGMarkerPosIterator { public: virtual ~SVGMarkerPosIterator() {} /** * Move to first marker position * @return OpStatus::OK if successful, OpStatus::ERR_* as appropriate otherwise */ virtual OP_STATUS First() = 0; /** * Move to the next marker position * @return TRUE if next marker found, FALSE otherwise */ virtual BOOL Next() = 0; /** * Indicates if the iterator is at the 'start' marker * (i.e. the first marker) */ virtual BOOL IsStart() = 0; /** * Indicates if the iterator is at the 'end' marker * (i.e. the last marker) */ virtual BOOL IsEnd() = 0; /** * Get the position of the current marker */ virtual SVGNumberPair GetCurrentPosition() const = 0; /** * Get the slope of the current marker */ virtual SVGNumber GetCurrentSlope() = 0; protected: // Shared utility method static SVGNumber VectorToAngle(const SVGNumberPair& v) { return v.x.atan2(v.y) * 180 / SVGNumber::pi(); } }; /** * Marker position iterator for paths */ class SVGMarkerPathPosIterator : public SVGMarkerPosIterator { public: SVGMarkerPathPosIterator(OpBpath* p) : m_prev_seg(NULL), m_next_seg(NULL), m_path(p), m_path_iter(NULL) {} ~SVGMarkerPathPosIterator() { OP_DELETE(m_path_iter); } OP_STATUS First(); BOOL Next(); BOOL IsStart() { return (m_prev_seg == NULL); } BOOL IsEnd() { return (m_next_seg == NULL); } SVGNumberPair GetCurrentPosition() const { SVGNumberPair ret; if (m_curr_seg) { ret.x = m_curr_seg->x; ret.y = m_curr_seg->y; } return ret; } SVGNumber GetCurrentSlope(); private: void GetNextSeg(); static BOOL IsConvertedArc(const SVGPathSeg* seg) { return seg->info.type == SVGPathSeg::SVGP_CURVETO_CUBIC_ABS && (seg->info.large == 1 && seg->info.sweep == 1); } SVGNumberPair m_first_subpath_seg_v; const SVGPathSeg* m_prev_seg; const SVGPathSeg* m_curr_seg; const SVGPathSeg* m_next_seg; OpBpath* m_path; PathSegListIterator* m_path_iter; }; /** * Marker position iterator for point lists */ class SVGMarkerPointListPosIterator : public SVGMarkerPosIterator { public: SVGMarkerPointListPosIterator(SVGVector* l, BOOL is_closed) : m_list(l), m_current_list_pos(0), m_is_closed(is_closed) {} SVGNumberPair GetCurrentPosition() const { return m_curr_pos; } SVGNumber GetCurrentSlope(); BOOL IsStart() { return (m_current_list_pos == 0); } BOOL IsEnd() { return (m_is_closed && m_current_list_pos == m_list->GetCount()) || (!m_is_closed && m_current_list_pos == m_list->GetCount() - 1); } OP_STATUS First(); BOOL Next(); private: SVGNumberPair m_curr_pos; SVGVector* m_list; unsigned int m_current_list_pos; BOOL m_is_closed; }; #endif // SVG_SUPPORT && SVG_SUPPORT_MARKERS #endif // SVG_MARKER_H
#include "api/FRCNN_OLD/Faster_Inference.hpp" using namespace caffe::FRCNN_OLD; int main(int argc , char **argv){ google::InitGoogleLogging(argv[0]); LOG(ERROR) << "In Main function !"; CHECK( argc == 5 ) << "[Inputfile] [Outputfile] [Detection_Config] [GPU_ID] " << " not " << argc; std::stringstream ids( argv[4] ); int GPU_ID ; ids >> GPU_ID ; if( GPU_ID < 0 ){ LOG(ERROR) << "SET CPU MODEL"; caffe::Caffe::set_mode(caffe::Caffe::CPU); }else{ LOG(ERROR) << "SET GPU MODEL , ID: " << GPU_ID; caffe::Caffe::SetDevice( GPU_ID ); caffe::Caffe::set_mode(caffe::Caffe::GPU); } FasterDetector detector ; detector.Set_Conf( argv[3] ); const std::string outputfile( argv[2] ); const std::string image_path( argv[1] ); LOG(INFO) << "Image : " << image_path ; vector<BBox> ans = detector.Predict( image_path ); for(size_t i = 0 ; i < ans.size() ; i ++ ){ LOG(INFO) << ans[i].Print( true ) ; } cv::Mat image = cv::imread( image_path ); showImage( image , ans ); cv::imwrite( outputfile.c_str() , image ); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_BAR_H #define OP_BAR_H #include "modules/widgets/OpWidget.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" /*********************************************************************************** ** ** OpBar ** ** OpBar is a superclass for all bar classes and gives the user ** of a bar different ways to layout a bar. For example: ** ** Just call SetRect to put it somewhere ** or call LayoutToAvailableRect() to make the bar take what it needs ** or call any of the Get() functions to find out what it wants.. (TODO) ** ** In other words, choose what makes your code the simplest. ** ** The real bar subclasses, however, only implements the OnLayout hook, nothing more. ** ***********************************************************************************/ class OpBar : public OpWidget { public: enum Alignment { ALIGNMENT_OFF = 0, ALIGNMENT_LEFT, ALIGNMENT_TOP, ALIGNMENT_RIGHT, ALIGNMENT_BOTTOM, ALIGNMENT_FLOATING, ALIGNMENT_OLD_VISIBLE }; enum Wrapping { WRAPPING_OFF = 0, WRAPPING_NEWLINE, WRAPPING_EXTENDER }; enum Collapse { COLLAPSE_SMALL = 0, COLLAPSE_NORMAL }; enum SettingsType { ALL = 0xffff, ALIGNMENT = 0x0001, STYLE = 0x0002, CONTENTS = 0x0004 }; OpBar(PrefsCollectionUI::integerpref prefs_setting = PrefsCollectionUI::DummyLastIntegerPref, PrefsCollectionUI::integerpref autoalignment_prefs_setting = PrefsCollectionUI::DummyLastIntegerPref); void SetMaster(BOOL master) {m_master = master;} BOOL GetMaster() {return m_master;} void SetSupportsReadAndWrite(BOOL read_and_write) {m_supports_read_and_write = read_and_write;} BOOL GetSupportsReadAndWrite() {return m_supports_read_and_write;} virtual Collapse TranslateCollapse(Collapse collapse) {return collapse;} virtual BOOL SetAlignment(Alignment alignment, BOOL write_to_prefs = FALSE); BOOL SetAutoAlignment(BOOL auto_alignment, BOOL write_to_prefs = FALSE); Alignment GetAlignment() {return m_alignment;} BOOL GetAutoAlignment() const {return m_auto_alignment;} Alignment GetNonFullscreenAlignment() {return IsFullscreen() ? m_non_fullscreen_alignment : GetAlignment();} BOOL GetNonFullscreenAutoAlignment() {return IsFullscreen() ? m_non_fullscreen_auto_alignment : GetAutoAlignment();} Alignment GetOldVisibleAlignment() {return m_old_visible_alignment;} Alignment GetResultingAlignment(); // Should we sync the alignment setting for this toolbar between windows, this should // be true for fixed-position bars like bookmark bar, address bar etc, and false for // appear-on-demand bar like find bar, content block bar etc. virtual BOOL SyncAlignment() {return m_alignment_prefs_setting != PrefsCollectionUI::DummyLastIntegerPref;} BOOL SetAutoVisible(BOOL auto_visible); BOOL GetAutoVisible() {return m_auto_visible;} BOOL IsVertical(); BOOL IsHorizontal(); BOOL IsOff(); BOOL IsOn() {return !IsOff();} INT32 GetWidthFromHeight(INT32 height, INT32* used_height = NULL); INT32 GetHeightFromWidth(INT32 width, INT32* used_width = NULL); virtual void GetRequiredSize(INT32& width, INT32& height); void GetRequiredSize(INT32 max_width, INT32 max_height, INT32& width, INT32& height); void WriteContent(); void RestoreToDefaults(); // Let the bar eat a portion of the rect passed according to its alignment, and return // a shrunken rect that does not contain the area this bar took. If the bar is set to be // off, it will eat nothing and instead ensure that it is not visible. virtual OpRect LayoutToAvailableRect(const OpRect& rect, BOOL compute_rect_only = FALSE, INT32 banner_x = 0, INT32 banner_y = 0); OpRect LayoutChildToAvailableRect(OpBar* child, const OpRect& rect, BOOL compute_rect_only = FALSE, INT32 banner_x = 0, INT32 banner_y = 0) { return child->LayoutToAvailableRect(AdjustForDirection(rect), compute_rect_only, banner_x, banner_y); } virtual void OnSettingsChanged(DesktopSettings* settings); virtual void OnRelayout(); virtual void OnLayout(); virtual void OnLayout(BOOL compute_size_only, INT32 available_width, INT32 available_height, INT32& used_width, INT32& used_height) {used_width = available_width; used_height = available_height;} virtual void OnFullscreen( BOOL fullscreen, Alignment fullscreen_alignment = ALIGNMENT_OFF ); virtual void OnDirectionChanged(); /** * Implementing OpWidget::OnNameSet so that OpBar will be * notified when the name of the widget is set - when it * is, we can read in the configuration of the bar. */ virtual void OnNameSet(); // Implementing the OpWidgetListener interface virtual void OnRelayout(OpWidget* widget); // == OpInputContext ====================== virtual BOOL OnInputAction(OpInputAction* action); protected: BOOL SetCollapse(Collapse collapse, BOOL write_to_prefs = FALSE); Collapse GetCollapse() {return m_collapse;} void ReadAlignment(BOOL master); void WriteStyle(); virtual void OnReadAlignment(PrefsSection* section); virtual void OnWriteAlignment(PrefsFile* prefs_file, const char* name); // // Hooks // virtual void OnReadStyle(PrefsSection *section) {} virtual void OnReadContent(PrefsSection *section) {} virtual void OnWriteStyle(PrefsFile* prefs_file, const char* name) {} virtual void OnWriteContent(PrefsFile* prefs_file, const char* name) {} virtual void OnSettingsChanged() {} virtual void OnAlignmentChanged() {} virtual void OnAutoAlignmentChanged() {} private: void Read(SettingsType settings = OpBar::ALL, BOOL master = FALSE); void ReadStyle(BOOL master); void ReadContents(BOOL master); void Write() {WriteAlignment(); WriteStyle(); WriteContent();} void WriteAlignment(); OP_STATUS GetSectionName(const OpStringC8& suffix, OpString8& section_name); INT32 m_used_width; INT32 m_used_height; Alignment m_used_alignment; Collapse m_used_collapse; Alignment m_alignment; BOOL m_auto_alignment; Alignment m_non_fullscreen_alignment; BOOL m_non_fullscreen_auto_alignment; Alignment m_old_visible_alignment; BOOL m_auto_visible; PrefsCollectionUI::integerpref m_alignment_prefs_setting; PrefsCollectionUI::integerpref m_auto_alignment_prefs_setting; Collapse m_collapse; BOOL m_changed_alignment_while_customizing; BOOL m_changed_style_while_customizing; BOOL m_changed_content_while_customizing; BOOL m_master; BOOL m_supports_read_and_write; }; #endif // OP_BAR_H
// // Main.cpp // // Created by Yajun Shi // // The main class for running the game #include "stdafx.h" #include "BangManager.h" int main(int argc, char* argv[]) { theWorld.Initialize(1024, 768, "Bang!"); theWorld.SetGameManager(new BangManager()); theWorld.StartGame(); theWorld.Destroy(); return 0; }
#include <Adafruit_NeoPixel.h> #include "MovingAnimation.h" MovingAnimation::MovingAnimation(void) { } void MovingAnimation::reset(variables_t *vars) { Serial.println("changing to moving"); int i; for(i = 0; i < vars->color_len; i++) { vars->color_store[i] = Adafruit_NeoPixel::Color(0, 0, rand()%64+64); vars->color_pos[i] = rand()%vars->color_len; } vars->lastTime = 0; } void MovingAnimation::loop(variables_t *vars) { int i; if(millis() > vars->lastTime + 25) { vars->lastTime = millis(); for (i = 0; i < vars->color_len; i++) {//clear vars->color[i] = Adafruit_NeoPixel::Color(0,127,0); } for (i=0; i< vars->color_len; i++) {//set vars->color[vars->color_pos[i]] = vars->color_store[i]; } for (i=0; i< vars->color_len; i++) {//move vars->color_pos[i] = vars->color_pos[i]+(rand()%2); if(vars->color_pos[i] > (vars->color_len-1)) { vars->color_pos[i] = vars->color_pos[i]-vars->color_len; } } } }
//*************************************************************************** // CSS 1 Spring 2017 Lab # 5 // Dror Manor // This program will translate 0-9 and aA-zZ to ICAO phonetic codes //*************************************************************************** #include <iostream> #include <string> using namespace std; //Prototyping the functions void displayLine(); void translateICAO(char c); void translateICAONumbers(int num); void makeLines(); int main () { //declaring and initilizing the variables and the messages to be used in the application string title = "\tThe International Civil Aviation Organization (ICAO) Translator\n"; string message = "Please enter a letter: "; string endMessage = "If you want to terminate the program, please enter \'$\'\n"; string errorMessage = "No codes is associated with the letter: "; string goodByeMessage = "Thank you for using the ICAO Translator"; char entry = ' '; //printing the title. displayLine(); cout << endl<< title << endl; displayLine(); //using do while loop to ensure that the program will run at least once // user will enter '$' to terminate do { //printing instructions and capturing input cout << endl << endMessage << endl << endl << message; cin >> entry; cout << endl; //termitation clause if (entry == '$') { continue; } // if the entry is alphabetical will use the corrosponding function else if ((entry >= 'A' || entry >= 'a') && ( entry >= 'Z' || entry <= 'z')){ displayLine(); translateICAO(entry); displayLine(); } // will use the numeric function if 0-9 else if (entry >= '0' && entry <= '9') { displayLine(); // casting to int and substracting 48 to convert back to the number from ASCI translateICAONumbers(static_cast<int>(entry)-48); displayLine(); } //error checking else { displayLine(); cout << errorMessage << "\'" << entry << "\'" << endl; displayLine(); } makeLines(); } while ( entry != '$'); //termination statment //printing goodbye message displayLine(); cout << endl << goodByeMessage << endl << endl; displayLine(); return 0; } void displayLine() { for (int i = 1; i <= 80; i++) { cout << '#'; } cout << endl; } void translateICAO(char c) { //will take an arrgument of a char form a to z either lower case or upper and will output the corrosponding ICAO code //will output an error message if entry is invalid string translation = ""; switch (c){ case 'A': case 'a': translation = "Alfa"; break; case 'B': case 'b': translation = "Bravo"; break; case 'C': case 'c': translation = "Charlie"; break; case 'D': case 'd': translation = "Delta"; break; case 'E': case 'e': translation = "Echo"; break; case 'F': case 'f': translation = "Foxtrot"; break; case 'G': case 'g': translation = "Golf"; break; case 'H': case 'h': translation = "Hotel"; break; case 'I': case 'i': translation = "India"; break; case 'J': case 'j': translation = "Juliett"; break; case 'K': case 'k': translation = "Kilo"; break; case 'L': case 'l': translation = "Lima"; break; case 'm': case 'M': translation = "Mike"; break; case 'N': case 'n': translation = "November"; break; case 'O': case 'o': translation = "Oscar"; break; case 'P': case 'p': translation = "Papa"; break; case 'Q': case 'q': translation = "Quebec"; break; case 'R': case 'r': translation = "Romeo"; break; case 'S': case 's': translation = "Sierra"; break; case 'T': case 't': translation = "Tango"; break; case 'U': case 'u': translation = "Uniform"; break; case 'V': case 'v': translation = "Victor"; break; case 'W': case 'w': translation = "Whiskey"; break; case 'X': case 'x': translation = "X-ray"; break; case 'Y': case 'y': translation = "Yankee"; break; case 'Z': case 'z': translation = "Zulu"; break; default: translation = "Invalid"; } //second error check if ( translation == "Invalid") { cout << endl << c << " is not a valid input, please try again." << endl << endl; } else { cout << endl << "The ICAO codes associated with the letter \'" << c << "\' corresponds to " << translation << endl << endl; } } void translateICAONumbers(int num) { //will take an arrgument of an int form 0-9 and will output the corrosponding ICAO code //will output an error message if entry is invalid string translation = ""; switch (num){ case 0: translation = "Zero"; break; case 1: translation = "One"; break; case 2: translation = "Two"; break; case 3: translation = "Three"; break; case 4: translation = "Fo-wer"; break; case 5: translation = "Five"; break; case 6: translation = "Six"; break; case 7: translation = "Seven"; break; case 8: translation = "Ait"; break; case 9: translation = "Niner"; break; default: translation = "Invalid"; } //second error check if ( translation == "Invalid") { cout << endl << num << " is not a valid input, please try again." << endl << endl; } else { cout << endl << "The ICAO codes associated with the letter \'" << num << "\' corresponds to " << translation << endl << endl; } } void makeLines() { //will loop a number of endl to make space between cycles for (int i = 0; i < 8; i++) { cout << endl; } }
#include <math.h> #include <iomanip> #include <sstream> #include "LVRdataConverter.hh" #include <xdaq/ApplicationDescriptor.h> #include "ecal/tools/exception/Exception.hh" LVRdataConverter::LVRdataConverter(xdaq::ApplicationContext* appContext, DipFactory* _dip, const std::string& dip_path) { NumberOfConverted_ = 0; appContext_ = appContext; EnablePVSS = false; TestMode = false; appPVSS = NULL; appDCU = NULL; nCCU = 0; converterTag = dip_path + "LVRTemperature"; dip = _dip; } LVRdataConverter::~LVRdataConverter() { if (EnablePVSS) { for (std::vector<DipPublication*>::iterator it = pubArray.begin(); it != pubArray.end(); it++) { try { dip->destroyDipPublication(*it); } catch (const DipInternalError &) { } delete data[it - pubArray.begin()]; } } } void LVRdataConverter::setConversion(std::string& DataPath_, std::string& SMnumber_, std::string& SMxPVSS_, bool EnablePVSS_, bool TestMode_, xdaq::ApplicationDescriptor* appPVSS_, xdaq::ApplicationDescriptor* appDCU_, unsigned int nCCU_) { DataPath = DataPath_; SMnumber = SMnumber_; SMxPVSS = SMxPVSS_; EnablePVSS = EnablePVSS_; TestMode = TestMode_; appPVSS = appPVSS_; appDCU = appDCU_; nCCU = nCCU_; } void LVRdataConverter::Convert(const std::string& TimeStamp, std::vector<float>& result) { int dipIndex = -1; if (EnablePVSS) { dipIndex = -1; std::vector<std::string>::iterator found = std::find(usedSector.begin(), usedSector.end(), SMxPVSS); if (found != usedSector.end()) { dipIndex = found - usedSector.begin(); } else { // The sector wasn't found already: create new pub, data and push_back in found sectors pubArray.push_back(dip->createDipPublication((converterTag + "/" + SMxPVSS).c_str(), new pubErrorHandler())); data.push_back(dip->createDipData()); usedSector.push_back(SMxPVSS); dipIndex = pubArray.size() - 1; } } int rawt[100]; char line[256]; int ccu; std::string dcudata_file = DataPath + std::string("/raw_new/") + SMnumber + std::string("/LVRdata_") + TimeStamp; std::string rawfile_done = DataPath + std::string("/raw_new/") + SMnumber + std::string("/done/LVRdata_") + TimeStamp; // opening dcudata file FILE* inpDcuFile = fopen(dcudata_file.c_str(), "r"); if (!inpDcuFile) { std::cout << "*** Can not open file: " << dcudata_file << std::endl; return; } // Read AdcCounts of the DCUs of each LVR int TT_DcuAdc[68][18]; // DCU channels 0 to 5 for each of the 3 DCUs (use 1 to 18) for each TT (use 1 to 68) int TT_num[68]; unsigned int nlines = 0; for (int i = 0; i <= 67; i++) { // initialize variable TT_num[i] = 0; for (int j = 0; j <= 17; j++) { TT_DcuAdc[i][j] = 0; result.push_back(0.0); } } fgets(line, 255, inpDcuFile); // skip header line int TimeStamp_int; fgets(line, 255, inpDcuFile); // get TimeStamp_int sscanf(&line[15], "%d", &TimeStamp_int); fgets(line, 255, inpDcuFile); // skip header line while (fgets(line, 255, inpDcuFile)) { sscanf(&line[4], "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d ", &ccu, &rawt[1], &rawt[2], &rawt[3], &rawt[4], &rawt[5], &rawt[6], &rawt[7], &rawt[8], &rawt[9], &rawt[10], &rawt[11], &rawt[12], &rawt[13], &rawt[14], &rawt[15], &rawt[16], &rawt[17], &rawt[18]); TT_num[nlines] = ccu; for (int i = 0; i <= 17; i++) { TT_DcuAdc[nlines][i] = rawt[i + 1]; } nlines++; } fclose(inpDcuFile); // close dcudata file // Convert TT_DcuAdc data into temperatures, analog/digital voltages, etc. float TT_Conv[68][18]; // DCu data after Conversion float sorted_conv[68][18]; // DCU channels 0 to 5 for each of the 3 DCUs (use 1 to 18) for each TT (use 1 to 68) // general DCU and LVR parameters float LSBperV = 2220.; // DCU gain: LSBs per Volt float DcuCurr = 0.00001923; // DCU current source (Amperes) float Vdcu; // Voltage measured by DCU const float V25Scale = 0.24025; // 6.04 Kohm / (6.04 Kohm + 19.1 Kohm) const float V43Scale = 0.06971; // 6.04 Kohm / (6.04 Kohm + 80.6 Kohm) const float OCMScale = 0.24025; // Over Current Monitor const float GOHScale = 0.24025; // GHz Optical Hybrid const float INHScale = 0.24025; // Inhibit float Res = 0; // Resistance of thermistor std::string dplist[18]; dplist[0] = "LVRTemperature1"; dplist[1] = "VFE1voltage"; dplist[2] = "VFE2voltage"; dplist[3] = "VFE3voltage"; dplist[4] = "VFE4voltage"; dplist[5] = "VFE5voltage"; dplist[6] = "LVRTemperature2"; dplist[7] = "LVRVcc"; dplist[8] = "LVR45"; dplist[9] = "LVR1to3"; dplist[10] = "LVRbuff"; dplist[11] = "LVRfenx"; dplist[12] = "LVRTemperature3"; dplist[13] = "LVR43A"; dplist[14] = "LVROCM"; dplist[15] = "LVRGOH"; dplist[16] = "LVRInhibit"; dplist[17] = "LVR43D"; for (unsigned int TT = 0; TT < 68; TT++) { //TODO: Double-check this is equivalent to the above for (unsigned int i = 0; i < 18; i++) { if (TT_DcuAdc[TT][i] >= 0 && TT_DcuAdc[TT][i] <= 4095) { // channel 0 of DCU1, 2 and 3: // temperature of the 3 thermistors on LVR board if (i == 0 || i == 6 || i == 12) { Vdcu = TT_DcuAdc[TT][i] / LSBperV; Res = Vdcu / DcuCurr; // Fit from Homer Neal TT_Conv[TT][i] = (-0.251 + sqrt(0.251 * 0.251 - 4 * 0.0053 * (18.127 - 4068.5 * pow(Res, -0.4642)))) / (2 * 0.0053); } // DCU1 channels 1-5: VFE 1-5 ANALOG // DCU2 channels 1-5: VCC; VFE4&5digital; VFE1,2,3digital; VFEbuffer; FENIX // All these channels should measure 2.5 Volts else if (i >= 1 && i <= 11 && i != 6) TT_Conv[TT][i] = TT_DcuAdc[TT][i] / (LSBperV * V25Scale); // DCU3 channels 1 and 5: 4.3V Analog and 4.3V Digital else if (i == 13 || i == 17) TT_Conv[TT][i] = TT_DcuAdc[TT][i] / (LSBperV * V43Scale); // DCU3 channels 2: OCM (Analog and Digital are merged) else if (i == 14) TT_Conv[TT][i] = TT_DcuAdc[TT][i] / (LSBperV * OCMScale); // DCU3 channels 3: GOH else if (i == 15) TT_Conv[TT][i] = TT_DcuAdc[TT][i] / (LSBperV * GOHScale); // DCU3 channels 4: Inhibit else if (i == 16) TT_Conv[TT][i] = TT_DcuAdc[TT][i] / (LSBperV * INHScale); } else TT_Conv[TT][i] = -1.0; sorted_conv[TT_num[TT]][i] = TT_Conv[TT][i]; unsigned int index; index = TT_num[TT] - 1; if (index >= 0 && index < 68) result.at(index * 18 + i) = (float) TT_Conv[TT][i]; //Send data through DIP protocol } } if (dip != NULL and EnablePVSS) { for (int j = 0; j < 68; j++) { for (int i = 0; i < 18; i++) { std::stringstream dipstring; dipstring << "TT_" << j << "/" << dplist[i]; data[dipIndex]->insert(floor(sorted_conv[j][i] * 100.00 + 0.5) / 100.00, dipstring.str().c_str()); } } } if (dip != NULL and EnablePVSS) pubArray[dipIndex]->send(*data[dipIndex], DipTimestamp()); // Open LVR data File and write the converted values std::string outfile = DataPath + std::string("/conv/") + SMnumber + std::string("/LVRdataConverted_") + TimeStamp; std::ofstream outLvrDataFile(outfile.c_str()); outLvrDataFile << "TimeStamp= " << TimeStamp << std::endl; outLvrDataFile << "TimeStamp_int= " << TimeStamp_int << std::endl; outLvrDataFile << "SM= " << SMnumber << std::endl; outLvrDataFile << " ----------------- DCU 0x10 -------------- ------------ DCU 0x20 ------------------ --------------- DCU 0x40 -------------" << std::endl; outLvrDataFile << " VfeDigit. Vfe ------VFEs Analog------ " << std::endl; outLvrDataFile << "TrTw Temp. Vcc 4&5 1to3 Buff Fenx Temp. Vfe1 Vfe2 Vfe3 Vfe4 Vfe5 Temp. 4.3A OCM GOH Inhbt 4.3D" << std::endl; std::cout << " LVRdata Output file to " << outfile.c_str() << std::endl; for (unsigned int jj = 0; jj < nlines; jj++) { // write trigger tower number outLvrDataFile << std::setw(3) << TT_num[jj]; // write a line with the 18 values of a TT for (int ii = 0; ii <= 17; ii++) { outLvrDataFile.precision(3); // temperature of thermistors if (ii == 0 || ii == 6 || ii == 12) { outLvrDataFile << " "; if (TT_Conv[jj][ii] < -274 || TT_Conv[jj][ii] > 999) TT_Conv[jj][ii] = 0; } if (ii == 16) outLvrDataFile.precision(2); outLvrDataFile << std::setw(7) << std::fixed << std::showpoint << TT_Conv[jj][ii]; } outLvrDataFile << std::endl; } outLvrDataFile.close(); NumberOfConverted_++; if (!TestMode) RawFileRename(dcudata_file, rawfile_done); return; }
/*==================================================================== Copyright(c) 2018 Adam Rankin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================*/ #pragma once // Local includes #include "Configuration.h" #include "IConfigurable.h" #include "IStabilizedComponent.h" #include "IVoiceInput.h" // IGT includes #include <IGTCommon.h> // OS includes #include <ppltasks.h> // STL includes #include <array> namespace DX { class StepTimer; } namespace HoloIntervention { namespace Algorithm { class LandmarkRegistration; } namespace Rendering { class ModelRenderer; class Model; } namespace Input { class VoiceInput; } namespace Network { class IGTConnector; } namespace UI { class Icons; } namespace System { class NetworkSystem; class NotificationSystem; class RegistrationSystem; namespace Tasks { class RegisterModelTask : public IStabilizedComponent, public Input::IVoiceInput, public IConfigurable { public: virtual concurrency::task<bool> WriteConfigurationAsync(Windows::Data::Xml::Dom::XmlDocument^ document); virtual concurrency::task<bool> ReadConfigurationAsync(Windows::Data::Xml::Dom::XmlDocument^ document); public: virtual Windows::Foundation::Numerics::float3 GetStabilizedPosition(Windows::UI::Input::Spatial::SpatialPointerPose^ pose) const; virtual Windows::Foundation::Numerics::float3 GetStabilizedVelocity() const; virtual float GetStabilizePriority() const; public: virtual void RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap); virtual void Update(Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem, DX::StepTimer& stepTimer); RegisterModelTask(HoloInterventionCore& core, NotificationSystem& notificationSystem, NetworkSystem& networkSystem, RegistrationSystem& registrationSystem, Rendering::ModelRenderer& modelRenderer, UI::Icons& icons); ~RegisterModelTask(); protected: // Cached system variables NotificationSystem& m_notificationSystem; NetworkSystem& m_networkSystem; RegistrationSystem& m_registrationSystem; Rendering::ModelRenderer& m_modelRenderer; UI::Icons& m_icons; std::shared_ptr<Rendering::Model> m_modelEntry = nullptr; std::wstring m_modelName = L""; std::wstring m_connectionName = L""; uint64 m_hashedConnectionName = 0; UWPOpenIGTLink::TransformName^ m_modelToReferenceName = ref new UWPOpenIGTLink::TransformName(); double m_latestTimestamp = 0.0; uint32 m_commandId = 0; std::atomic_bool m_cancelled = false; // Registration variables std::vector<Windows::Foundation::Numerics::float3> m_points; std::shared_ptr<Algorithm::LandmarkRegistration> m_landmarkRegistration; // Phantom task behaviour std::atomic_bool m_taskStarted = false; UWPOpenIGTLink::TrackedFrame^ m_trackedFrame = nullptr; UWPOpenIGTLink::Polydata^ m_polydata = nullptr; UWPOpenIGTLink::Transform^ m_transform = nullptr; UWPOpenIGTLink::TransformName^ m_stylusTipTransformName = ref new UWPOpenIGTLink::TransformName(); UWPOpenIGTLink::TransformRepository^ m_transformRepository = ref new UWPOpenIGTLink::TransformRepository(); Platform::String^ MODEL_REGISTRATION_COORDINATE_FRAME = L"ModelSpace"; }; } } }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "494" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif char symbol; int number=0; while( ~scanf("%c",&symbol) ){ if( isalpha(symbol) ){ while( scanf("%c",&symbol) ){ if( !isalpha(symbol) ){ if( symbol == '\n' ){ printf("%d\n",number+1 ); number = 0; } number++; break; } } } else if( symbol == '\n' ){ printf("%d\n",number ); number = 0; } } return 0; }
// // Particle.cpp // w05_h01_strings // // Created by Kris Li on 10/5/16. // // #include "Particle.hpp" Particle::Particle() { pos.x = ofRandom(ofGetWindowWidth()); pos.y = ofRandom(ofGetHeight()); vel.set(0,0); acc.set(0,0); damp = 0.90; // damping force--resistance radius = 5; bFix = false; color = ofColor(ofRandom(100, 250),ofRandom(100, 250),ofRandom(0, 120)); } void Particle::setInit(ofPoint _pos, ofPoint _vel){ pos = _pos; vel = _vel; acc.set(0,0); } void Particle::update() { vel += acc; vel *= damp; pos += vel; acc *= 0.0; // vel = ofPoint(ofRandom(-5,5),ofRandom(-5,5)); // ofPoint dir = 0.005*ofPoint(ofGetWidth()/2, ofGetHeight()/2)-ofPoint(ofGetMouseX(),ofGetMouseY()); ofPoint dir = ofPoint(ofGetMouseX(),ofGetMouseY())-ofPoint(pos.x, pos.y); dir = dir/(ofRandom(1,20)); dir.normalize(); acc= dir; } void Particle::bounding(){ // if( pos.x < 0.0+radius || pos.x > ofGetWidth()-radius ){ // pos.x -= vel.x; // vel.x *= -0.5; // come back at a slower speed // } // // if( pos.y < 0.0+radius || pos.y > ofGetHeight()-radius ){ // pos.y -= vel.y; // vel.y *= -0.5; // } if( pos.x < 0.0 || pos.x > ofGetWidth()){ pos.x -= vel.x; vel.x *= -0.5; // come back at a slower speed } if( pos.y < 0.0 || pos.y > ofGetHeight()){ pos.y -= vel.y; vel.y *= -0.5; } } void Particle::avoid(ofPoint ball){ if(ofDist(ball.x, ball.y,pos.x, pos.y)< 50){ ofPoint f = ofPoint(ball.x - pos.x, ball.y - pos.y); vel -= f; } } ofPoint Particle::getPosition(){ return pos; } ofPoint Particle::getVelocity(){ return vel; } ofColor Particle::getColor(){ return color; } float Particle::getRadius(){ return radius; } void Particle::addForce(ofPoint _force){ acc += _force; } void Particle::draw() { ofSetColor(color); ofDrawCircle(pos, radius); }
//将意外异常转化成意料中的异常 void unexpected() { cout<<"Unexpected exception.\n"; throw runtime_error(""); } //标准异常层次体系 void readIntegerFile(const string& filename,vector<int>& dest) throw(invalid_argment,runtime_error) { ifstream istr; int temp; istr.open(filename.cstr()); if(istr.fail()) { //Failed to open the file: throw an exception. string error="Unable to open file"+filename; throw invalid_argument(error); } //Read the integers one by one and add them to the vector. while(istr>>temp) { dest.push_back(temp); } if(istr.eof()) { //We reach the end-of-file. istr.close(); } else { string error="Unable to read file "+filename; throw runtime_error(error); } } int main(int argc,char** argv) { //Code omitted for brevity. try { readIntegerFile(filename,myInts); } catch (const invalid_argument& e) { cerr<<e.what()<<endl; exit(1); } catch (const runtime_error& e) { cerr<<e.what()<<endl; exit(1); } //Code omitted for brevity. }
// // Generated file. Do not edit. // #include "generated_plugin_registrant.h" #include <flutter_bluetooth/flutter_bluetooth_plugin.h> void RegisterPlugins(flutter::PluginRegistry* registry) { FlutterBluetoothPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterBluetoothPlugin")); }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; string simplifyPath(string path){ path = '/' + path + '/'; vector<string> mstack; string res = "/"; int i=0; while(i<path.length()-1){ i++; string temp; while(path[i] != '/'){ temp.push_back(path[i]); i++; } if(temp == ".." && !mstack.empty()){ mstack.pop_back(); } if(temp != "." && temp != ".." && !temp.empty()){ temp = temp + '/'; mstack.push_back(temp); } } for(auto x : mstack) res += x; if(!mstack.empty()) res.pop_back(); return res; } int main(){ string s; cin >> s; cout << simplifyPath(s) << endl; }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "backend/opencl/runners/OclBaseRunner.h" #include "backend/opencl/cl/OclSource.h" #include "backend/opencl/OclCache.h" #include "backend/opencl/OclLaunchData.h" #include "backend/opencl/runners/tools/OclSharedState.h" #include "backend/opencl/wrappers/OclError.h" #include "backend/opencl/wrappers/OclLib.h" #include "base/io/log/Log.h" #include "base/net/stratum/Job.h" #include "crypto/common/VirtualMemory.h" constexpr size_t oneGiB = 1024 * 1024 * 1024; xmrig::OclBaseRunner::OclBaseRunner(size_t id, const OclLaunchData &data) : m_ctx(data.ctx), m_algorithm(data.algorithm), m_source(OclSource::get(data.algorithm)), m_data(data), m_align(OclLib::getUint(data.device.id(), CL_DEVICE_MEM_BASE_ADDR_ALIGN)), m_threadId(id), m_intensity(data.thread.intensity()) { m_deviceKey = data.device.name(); # ifdef XMRIG_STRICT_OPENCL_CACHE m_deviceKey += ":"; m_deviceKey += data.platform.version(); m_deviceKey += ":"; m_deviceKey += OclLib::getString(data.device.id(), CL_DRIVER_VERSION); # endif # if defined(__x86_64__) || defined(_M_AMD64) || defined (__arm64__) || defined (__aarch64__) m_deviceKey += ":64"; # endif } xmrig::OclBaseRunner::~OclBaseRunner() { OclLib::release(m_program); OclLib::release(m_input); OclLib::release(m_output); OclLib::release(m_buffer); OclLib::release(m_queue); } size_t xmrig::OclBaseRunner::bufferSize() const { return align(Job::kMaxBlobSize) + align(sizeof(cl_uint) * 0x100); } uint32_t xmrig::OclBaseRunner::deviceIndex() const { return data().thread.index(); } void xmrig::OclBaseRunner::build() { m_program = OclCache::build(this); if (m_program == nullptr) { throw std::runtime_error(OclError::toString(CL_INVALID_PROGRAM)); } } void xmrig::OclBaseRunner::init() { m_queue = OclLib::createCommandQueue(m_ctx, data().device.id()); size_t size = align(bufferSize()); const size_t limit = data().device.freeMemSize(); if (size < oneGiB && data().device.vendorId() == OCL_VENDOR_AMD && limit >= oneGiB) { m_buffer = OclSharedState::get(data().device.index()).createBuffer(m_ctx, size, m_offset, limit); } if (!m_buffer) { m_buffer = OclLib::createBuffer(m_ctx, CL_MEM_READ_WRITE, size); } m_input = createSubBuffer(CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, Job::kMaxBlobSize); m_output = createSubBuffer(CL_MEM_READ_WRITE, sizeof(cl_uint) * 0x100); } cl_mem xmrig::OclBaseRunner::createSubBuffer(cl_mem_flags flags, size_t size) { auto mem = OclLib::createSubBuffer(m_buffer, flags, m_offset, size); m_offset += align(size); return mem; } size_t xmrig::OclBaseRunner::align(size_t size) const { return VirtualMemory::align(size, m_align); } void xmrig::OclBaseRunner::enqueueReadBuffer(cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void *ptr) { const cl_int ret = OclLib::enqueueReadBuffer(m_queue, buffer, blocking_read, offset, size, ptr, 0, nullptr, nullptr); if (ret != CL_SUCCESS) { throw std::runtime_error(OclError::toString(ret)); } } void xmrig::OclBaseRunner::enqueueWriteBuffer(cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, const void *ptr) { const cl_int ret = OclLib::enqueueWriteBuffer(m_queue, buffer, blocking_write, offset, size, ptr, 0, nullptr, nullptr); if (ret != CL_SUCCESS) { throw std::runtime_error(OclError::toString(ret)); } } void xmrig::OclBaseRunner::finalize(uint32_t *hashOutput) { enqueueReadBuffer(m_output, CL_TRUE, 0, sizeof(cl_uint) * 0x100, hashOutput); uint32_t &results = hashOutput[0xFF]; if (results > 0xFF) { results = 0xFF; } }
#include<stdio.h> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> void key_callback(GLFWwindow *win, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(win, GL_TRUE); else printf("key:%d\n", key); } int main() { // glfw glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow *win = glfwCreateWindow(800, 600, "J.C.LearnOpenGL", NULL, NULL); glfwMakeContextCurrent(win); if (win == NULL) { //std::cout  << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwSetKeyCallback(win, key_callback); // glew glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) return -1; glViewport(0, 0, 800, 600); while (!glfwWindowShouldClose(win)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(win); } glfwTerminate(); }
#include "Engine.hpp" Engine::Engine() { m_window = NULL; m_devMode = false; m_width = 640; m_height = 480; srand(time(NULL)); } Engine::~Engine() { SDL_Quit(); } bool Engine::Initialize(const char* title, int width, int height, bool fullScreen) { #ifdef NDEBUG m_devMode = false; #else m_devMode = true; #endif Debug& dbg = Debug::GetInstance(); dbg.Print("Initializing Engine:"); dbg.Print("Initializing video subsystem"); if (SDL_Init(SDL_INIT_VIDEO) < 0) { dbg.Print("Failed to initilize video subsystem"); dbg.Print(SDL_GetError()); return false; } dbg.Print("Initializing audio subsystem"); if (SDL_Init(SDL_INIT_AUDIO) < 0) { dbg.Print("Failed to initilize audio subsystem"); dbg.Print(SDL_GetError()); return false; } dbg.Print("Initializing timer subsystem"); if (SDL_Init(SDL_INIT_TIMER) < 0) { dbg.Print("Failed to initilize timer subsystem"); dbg.Print(SDL_GetError()); return false; } dbg.Print("Initializing event subsystem"); if (SDL_Init(SDL_INIT_EVENTS) < 0) { dbg.Print("Failed to initilize events subsystem"); dbg.Print(SDL_GetError()); return false; } dbg.Print("Initializing SDL_IMG [PNG,JPG] subsystem"); if (IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG) < 0) { dbg.Print("Failed to initilize SDL_IMG"); dbg.Print(IMG_GetError()); return false; } dbg.Print("Initializing SDL_TTF subsystem"); if (TTF_Init() < 0) { dbg.Print("Failed to initilize SDL_TTF"); dbg.Print(TTF_GetError()); return false; } TTF_Init(); dbg.Print("Creating application window"); if (fullScreen) m_window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN); else m_window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL); if (m_window == NULL) { dbg.Print("Failed to create game window"); return false; } m_context = SDL_GL_CreateContext(m_window); glewInit(); dbg.Print("Enabling Double Buffer Mode"); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); std::string applicationTitle; #ifdef NDEBUG applicationTitle = "Release Build: "; #else applicationTitle = "Debug Build: "; #endif applicationTitle += __DATE__; applicationTitle += " - "; applicationTitle += __TIME__; if (m_devMode) { SDL_SetWindowTitle(m_window, applicationTitle.c_str()); } dbg.Print("Engine initialization complete"); Core test; test.run(m_window, m_luaState); return true; } bool Engine::RunConfigAndInitilize(const char* file) { Debug& dbg = Debug::GetInstance(); m_luaState = lua_createState(); if (m_luaState == NULL) { dbg.Print("Failed to create Lua state."); return false; } if (luaL_dofile(m_luaState, file) == 0) { lua_getglobal(m_luaState, "Window_Width"); lua_getglobal(m_luaState, "Window_Height"); lua_getglobal(m_luaState, "Fullscreen"); lua_getglobal(m_luaState, "Window_Title"); int width = lua_tointeger(m_luaState, 1); int height = lua_tointeger(m_luaState, 2); bool fullscreen = bool(lua_toboolean(m_luaState, 3)); const char* title = lua_tostring(m_luaState, 4); lua_pop(m_luaState, 4); m_width = width; m_height = height; dbg.Print("Resolution: %ix%i Fullscreen: %s", m_width, m_height, ((fullscreen) ? "Enabled" : "Disabled")); return Initialize(title, width, height, fullscreen); } dbg.Print("Failed to read config file, applying defaults"); dbg.Print("Error: %s", lua_tostring(m_luaState, 1)); lua_pop(m_luaState, 1); dbg.Print("Resolution: 640x480 Fullscreen: Disabled"); return Initialize("Application", 640, 480, false); }
#include "Etudiant.hpp" #include <cstdio> namespace enseirb{ static Chaine g("Etudiant"); Etudiant::Etudiant(): Personne(""), _filiere(""), _enseignement(""){ printf("%s (%d): %s\n", __FILE__,__LINE__,__func__);} Etudiant::Etudiant(const Etudiant &s): Personne(s.nom()), _filiere(s.filiere()), _enseignement(s.enseignement()) { printf("%s (%d): %s\n", __FILE__,__LINE__,__func__);} Etudiant::Etudiant(const Chaine &a, const Chaine &b, const Chaine &c): Personne(a), _filiere(b), _enseignement(c){ printf("%s (%d): %s\n", __FILE__,__LINE__,__func__);} Chaine Etudiant::nom()const{ return g + Personne::nom(); } Chaine Etudiant::filiere() const{ return _filiere; } Chaine Etudiant::enseignement() const{ return _enseignement; } void Etudiant::setEnseignement(const Chaine &s){ _enseignement = s; } }
// Copyright (c) 2021 ETH Zurich // Copyright (c) 2020 John Biddiscombe // Copyright (c) 2016 Thomas Heller // Copyright (c) 2016 Hartmut Kaiser // // 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/async_cuda/detail/cuda_event_callback.hpp> #include <pika/runtime/runtime_fwd.hpp> #include <pika/threading_base/thread_pool_base.hpp> #include <string> namespace pika::cuda::experimental { PIKA_EXPORT const std::string& get_pool_name(); PIKA_EXPORT void set_pool_name(const std::string&); // ----------------------------------------------------------------- // This RAII helper class enables polling for a scoped block struct [[nodiscard]] enable_user_polling { enable_user_polling(std::string const& pool_name = "") : pool_name_(pool_name) { // install polling loop on requested thread pool if (pool_name_.empty()) { detail::register_polling(pika::resource::get_thread_pool(0)); set_pool_name(pika::resource::get_pool_name(0)); } else { detail::register_polling(pika::resource::get_thread_pool(pool_name_)); set_pool_name(pool_name_); } } ~enable_user_polling() { if (pool_name_.empty()) { detail::unregister_polling(pika::resource::get_thread_pool(0)); } else { detail::unregister_polling(pika::resource::get_thread_pool(pool_name_)); } } private: std::string pool_name_; }; } // namespace pika::cuda::experimental
#include "stdafx.h" #include "ist/ist_sys.h" #include "system.h" #ifdef WIN32 #pragma comment(lib,"SDL.lib") #pragma comment(lib,"SDLmain.lib") #pragma comment(lib,"SDL_mixer.lib") #pragma comment(lib,"opengl32.lib") #pragma comment(lib,"glu32.lib") #pragma comment(lib,"glew32.lib") #pragma comment(lib,"ftgl.lib") #pragma comment(lib,"zlib.lib") #pragma comment(lib,"libpng.lib") #pragma comment(lib,"imm32.lib") #endif namespace exception { sgui::App* CreateApp(int argc, char *argv[]); #ifdef EXCEPTION_ENABLE_RUNTIME_CHECK void PrintLeakObject(); #endif void DumpReplay(const string& path); void ExecuteServer(int argc, char *argv[]); } int main(int argc, char *argv[]) { #ifdef EXCEPTION_CHECK_LEAK _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); char *hoge = new char[128]; #endif while(exception::FindProcess("updater.exe")) { sgui::Sleep(100); } while(exception::FindProcess("exception_conflict_config.exe")) { sgui::Sleep(100); } if(ist::IsFile("updater.exe.tmp")) { if(ist::IsFile("updater.exe")) { remove("updater.exe"); } rename("updater.exe.tmp", "updater.exe"); } std::string command = argc>=2 ? argv[1] : ""; #ifdef EXCEPTION_ENABLE_REPLAY_DUMP if(command=="dump_replay") { if(argc>=3) { exception::DumpReplay(argv[2]); } return 0; } #endif // EXCEPTION_ENABLE_REPLAY_DUMP #ifdef EXCEPTION_ENABLE_DEDICATED_SERVER if(command=="server") { exception::ExecuteServer(argc, argv); return 0; } #endif // EXCEPTION_ENABLE_DEDICATED_SERVER try { exception::CreateApp(argc, argv)->exec(); } catch(const std::exception& e) { #ifdef WIN32 MessageBox(NULL, e.what(), "error", MB_OK); #else puts(e.what()); #endif } #ifdef EXCEPTION_ENABLE_RUNTIME_CHECK exception::PrintLeakObject(); #endif return 0; }
#ifndef _DefienLackProc_H_ #define _DefienLackProc_H_ #include "BaseProcess.h" class DefineLackProc :public BaseProcess { public: DefineLackProc(); virtual ~DefineLackProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); private: }; #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int f[110],g[110][110]; int main() { string a,b; while (cin >> a >> b) { int n = a.size(); a = " " + a;b = " " + b; for (int i = 1;i <= n; i++) for (int j = i;j <= n; j++) { g[i][j] = j-i+1; } for (int len = 0;len < n; len++) for (int i = 1;i+len <= n; i++) { int j = i + len,loc; for (loc = j;loc >= i && b[loc-1] == b[j]; loc--) ; g[i][j] = min(g[i][j],g[i][loc-1] + 1); for (int k = loc-1;k >= i;k--) if (b[k] == b[j]) g[i][j] = min(g[i][j],g[i][k] + g[k+1][loc-1]); //printf("%d %d %d\n",i,j,f[i][j]); } for (int i = 1;i <= n; i++) { f[i] = g[1][i]; if (a[i] == b[i]) f[i] = f[i-1]; else { for (int j = 0;j < i; j++) f[i] = min(f[i],f[j]+g[j+1][i]); } } printf("%d\n",f[n]); } return 0; }
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jefftk@google.com (Jeff Kaufman) #include "ngx_rewrite_driver_factory.h" #include <cstdio> #include "log_message_handler.h" #include "ngx_message_handler.h" #include "ngx_rewrite_options.h" #include "ngx_server_context.h" #include "ngx_thread_system.h" #include "ngx_url_async_fetcher.h" #include "pthread_shared_mem.h" #include "net/instaweb/http/public/content_type.h" #include "net/instaweb/http/public/rate_controller.h" #include "net/instaweb/http/public/rate_controlling_url_async_fetcher.h" #include "net/instaweb/http/public/wget_url_fetcher.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_driver_factory.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/static_asset_manager.h" #include "net/instaweb/apache/in_place_resource_recorder.h" #include "net/instaweb/system/public/serf_url_async_fetcher.h" #include "net/instaweb/system/public/system_caches.h" #include "net/instaweb/system/public/system_rewrite_options.h" #include "net/instaweb/util/public/google_message_handler.h" #include "net/instaweb/util/public/null_shared_mem.h" #include "net/instaweb/util/public/posix_timer.h" #include "net/instaweb/util/public/property_cache.h" #include "net/instaweb/util/public/scheduler_thread.h" #include "net/instaweb/util/public/shared_circular_buffer.h" #include "net/instaweb/util/public/shared_mem_statistics.h" #include "net/instaweb/util/public/slow_worker.h" #include "net/instaweb/util/public/stdio_file_system.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/thread_system.h" namespace net_instaweb { class FileSystem; class Hasher; class MessageHandler; class Statistics; class Timer; class UrlAsyncFetcher; class UrlFetcher; class Writer; const char NgxRewriteDriverFactory::kStaticAssetPrefix[] = "/ngx_pagespeed_static/"; namespace { const char kShutdownCount[] = "child_shutdown_count"; } // namespace NgxRewriteDriverFactory::NgxRewriteDriverFactory( NgxThreadSystem* ngx_thread_system) : SystemRewriteDriverFactory(ngx_thread_system), ngx_thread_system_(ngx_thread_system), // TODO(oschaaf): mod_pagespeed ifdefs this: shared_mem_runtime_(new ngx::PthreadSharedMem()), main_conf_(NULL), threads_started_(false), use_per_vhost_statistics_(false), is_root_process_(true), ngx_message_handler_(new NgxMessageHandler(thread_system()->NewMutex())), ngx_html_parse_message_handler_( new NgxMessageHandler(thread_system()->NewMutex())), install_crash_handler_(false), message_buffer_size_(0), shared_circular_buffer_(NULL), statistics_frozen_(false), ngx_url_async_fetcher_(NULL), log_(NULL), resolver_timeout_(NGX_CONF_UNSET_MSEC), use_native_fetcher_(false) { InitializeDefaultOptions(); default_options()->set_beacon_url("/ngx_pagespeed_beacon"); SystemRewriteOptions* system_options = dynamic_cast<SystemRewriteOptions*>( default_options()); system_options->set_file_cache_clean_inode_limit(500000); system_options->set_avoid_renaming_introspective_javascript(true); set_message_handler(ngx_message_handler_); set_html_parse_message_handler(ngx_html_parse_message_handler_); // see https://code.google.com/p/modpagespeed/issues/detail?id=672 int thread_limit = 1; caches_.reset( new SystemCaches(this, shared_mem_runtime_.get(), thread_limit)); } NgxRewriteDriverFactory::~NgxRewriteDriverFactory() { ShutDown(); CHECK(uninitialized_server_contexts_.empty() || is_root_process_); STLDeleteElements(&uninitialized_server_contexts_); shared_mem_statistics_.reset(NULL); } Hasher* NgxRewriteDriverFactory::NewHasher() { return new MD5Hasher; } UrlAsyncFetcher* NgxRewriteDriverFactory::DefaultAsyncUrlFetcher() { const char* fetcher_proxy = ""; if (main_conf_ != NULL) { fetcher_proxy = main_conf_->fetcher_proxy().c_str(); } UrlAsyncFetcher* fetcher = NULL; SerfUrlAsyncFetcher* serf_fetcher = NULL; if (use_native_fetcher_) { ngx_url_async_fetcher_ = new NgxUrlAsyncFetcher( fetcher_proxy, log_, resolver_timeout_, 25000, resolver_, thread_system(), message_handler()); fetcher = ngx_url_async_fetcher_; } else { serf_fetcher = new SerfUrlAsyncFetcher( fetcher_proxy, NULL, thread_system(), statistics(), timer(), 2500, message_handler()); fetcher = serf_fetcher; } SystemRewriteOptions* system_options = dynamic_cast<SystemRewriteOptions*>( default_options()); if (rate_limit_background_fetches_) { // Unfortunately, we need stats for load-shedding. if (system_options->statistics_enabled()) { // TODO(oschaaf): mps bases this multiplier on the configured // num_rewrite_threads_ which we don't have (yet). int multiplier = 4; fetcher = new RateControllingUrlAsyncFetcher( fetcher, 500 * multiplier /* max queue size */, multiplier /* requests/host */, 500 * multiplier /* queued per host */, thread_system(), statistics()); if (serf_fetcher != NULL) { defer_cleanup(new Deleter<SerfUrlAsyncFetcher>(serf_fetcher)); } else if (ngx_url_async_fetcher_ != NULL) { defer_cleanup(new Deleter<NgxUrlAsyncFetcher>(ngx_url_async_fetcher_)); } } else { message_handler()->Message( kError, "Can't enable fetch rate-limiting without statistics"); } } return fetcher; } MessageHandler* NgxRewriteDriverFactory::DefaultHtmlParseMessageHandler() { return ngx_html_parse_message_handler_; } MessageHandler* NgxRewriteDriverFactory::DefaultMessageHandler() { return ngx_message_handler_; } FileSystem* NgxRewriteDriverFactory::DefaultFileSystem() { return new StdioFileSystem(); } Timer* NgxRewriteDriverFactory::DefaultTimer() { return new PosixTimer; } NamedLockManager* NgxRewriteDriverFactory::DefaultLockManager() { CHECK(false); return NULL; } void NgxRewriteDriverFactory::SetupCaches(ServerContext* server_context) { // TODO(anupama): Remove duplication wrt mod_pagespeed code. caches_->SetupCaches(server_context); server_context->set_enable_property_cache(true); PropertyCache* pcache = server_context->page_property_cache(); const PropertyCache::Cohort* cohort = pcache->AddCohort(RewriteDriver::kBeaconCohort); server_context->set_beacon_cohort(cohort); cohort = pcache->AddCohort(RewriteDriver::kDomCohort); server_context->set_dom_cohort(cohort); } RewriteOptions* NgxRewriteDriverFactory::NewRewriteOptions() { NgxRewriteOptions* options = new NgxRewriteOptions(thread_system()); options->SetRewriteLevel(RewriteOptions::kCoreFilters); return options; } void NgxRewriteDriverFactory::InitStaticAssetManager( StaticAssetManager* static_asset_manager) { static_asset_manager->set_library_url_prefix(kStaticAssetPrefix); } void NgxRewriteDriverFactory::PrintMemCacheStats(GoogleString* out) { // TODO(morlovich): Port the client code to proper API, so it gets // shm stats, too. caches_->PrintCacheStats(SystemCaches::kIncludeMemcached, out); } bool NgxRewriteDriverFactory::InitNgxUrlAsyncFetcher() { if (ngx_url_async_fetcher_ == NULL) { return true; } log_ = ngx_cycle->log; return ngx_url_async_fetcher_->Init(); } bool NgxRewriteDriverFactory::CheckResolver() { if (use_native_fetcher_ && resolver_ == NULL) { return false; } return true; } void NgxRewriteDriverFactory::StopCacheActivity() { if (is_root_process_) { return; // No caches used in root process. } RewriteDriverFactory::StopCacheActivity(); caches_->StopCacheActivity(); } NgxServerContext* NgxRewriteDriverFactory::MakeNgxServerContext() { NgxServerContext* server_context = new NgxServerContext(this); uninitialized_server_contexts_.insert(server_context); return server_context; } ServerContext* NgxRewriteDriverFactory::NewServerContext() { LOG(DFATAL) << "MakeNgxServerContext should be used instead"; return NULL; } void NgxRewriteDriverFactory::ShutDown() { StopCacheActivity(); if (!is_root_process_) { Variable* child_shutdown_count = statistics()->GetVariable(kShutdownCount); child_shutdown_count->Add(1); } ngx_message_handler_->set_buffer(NULL); ngx_html_parse_message_handler_->set_buffer(NULL); for (NgxMessageHandlerSet::iterator p = server_context_message_handlers_.begin(); p != server_context_message_handlers_.end(); ++p) { (*p)->set_buffer(NULL); } server_context_message_handlers_.clear(); RewriteDriverFactory::ShutDown(); caches_->ShutDown(message_handler()); if (is_root_process_) { // Cleanup statistics. // TODO(morlovich): This looks dangerous with async. if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->GlobalCleanup(message_handler()); } if (shared_circular_buffer_ != NULL) { shared_circular_buffer_->GlobalCleanup(message_handler()); } } } void NgxRewriteDriverFactory::StartThreads() { if (threads_started_) { return; } ngx_thread_system_->PermitThreadStarting(); // TODO(jefftk): use a native nginx timer instead of running our own thread. // See issue #111. SchedulerThread* thread = new SchedulerThread(thread_system(), scheduler()); bool ok = thread->Start(); CHECK(ok) << "Unable to start scheduler thread"; defer_cleanup(thread->MakeDeleter()); threads_started_ = true; } void NgxRewriteDriverFactory::ParentOrChildInit(ngx_log_t* log) { if (install_crash_handler_) { NgxMessageHandler::InstallCrashHandler(log); } ngx_message_handler_->set_log(log); ngx_html_parse_message_handler_->set_log(log); SharedCircularBufferInit(is_root_process_); } // TODO(jmarantz): make this per-vhost. void NgxRewriteDriverFactory::SharedCircularBufferInit(bool is_root) { // Set buffer size to 0 means turning it off if (shared_mem_runtime() != NULL && (message_buffer_size_ != 0)) { // TODO(jmarantz): it appears that filename_prefix() is not actually // established at the time of this construction, calling into question // whether we are naming our shared-memory segments correctly. shared_circular_buffer_.reset(new SharedCircularBuffer( shared_mem_runtime(), message_buffer_size_, filename_prefix().as_string(), "foo.com" /*hostname_identifier()*/)); if (shared_circular_buffer_->InitSegment(is_root, message_handler())) { ngx_message_handler_->set_buffer(shared_circular_buffer_.get()); ngx_html_parse_message_handler_->set_buffer( shared_circular_buffer_.get()); } } } void NgxRewriteDriverFactory::RootInit(ngx_log_t* log) { net_instaweb::log_message_handler::Install(log); ParentOrChildInit(log); // Let SystemCaches know about the various paths we have in configuration // first, as well as the memcached instances. for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; caches_->RegisterConfig(server_context->config()); } caches_->RootInit(); } void NgxRewriteDriverFactory::ChildInit(ngx_log_t* log) { is_root_process_ = false; ParentOrChildInit(log); if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->Init(false, message_handler()); } caches_->ChildInit(); for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; server_context->ChildInit(); } uninitialized_server_contexts_.clear(); } // Initializes global statistics object if needed, using factory to // help with the settings if needed. // Note: does not call set_statistics() on the factory. Statistics* NgxRewriteDriverFactory::MakeGlobalSharedMemStatistics( const NgxRewriteOptions& options) { if (shared_mem_statistics_.get() == NULL) { shared_mem_statistics_.reset(AllocateAndInitSharedMemStatistics( "global", options)); } DCHECK(!statistics_frozen_); statistics_frozen_ = true; SetStatistics(shared_mem_statistics_.get()); return shared_mem_statistics_.get(); } SharedMemStatistics* NgxRewriteDriverFactory:: AllocateAndInitSharedMemStatistics( const StringPiece& name, const NgxRewriteOptions& options) { GoogleString log_filename; bool logging_enabled = false; if (!options.log_dir().empty()) { // Only enable statistics logging if a log_dir() is actually specified. log_filename = StrCat(options.log_dir(), "/stats_log_", name); logging_enabled = options.statistics_logging_enabled(); } // Note that we create the statistics object in the parent process, and // it stays around in the kids but gets reinitialized for them // inside ChildInit(), called from pagespeed_child_init. SharedMemStatistics* stats = new SharedMemStatistics( options.statistics_logging_interval_ms(), options.statistics_logging_max_file_size_kb(), log_filename, logging_enabled, StrCat(filename_prefix(), name), shared_mem_runtime(), message_handler(), file_system(), timer()); InitStats(stats); stats->Init(true, message_handler()); return stats; } void NgxRewriteDriverFactory::SetServerContextMessageHandler( ServerContext* server_context, ngx_log_t* log) { NgxMessageHandler* handler = new NgxMessageHandler( thread_system()->NewMutex()); handler->set_log(log); handler->set_buffer(shared_circular_buffer_.get()); server_context_message_handlers_.insert(handler); defer_cleanup(new Deleter<NgxMessageHandler>(handler)); server_context->set_message_handler(handler); } void NgxRewriteDriverFactory::InitStats(Statistics* statistics) { // Init standard PSOL stats. SystemRewriteDriverFactory::InitStats(statistics); RewriteDriverFactory::InitStats(statistics); RateController::InitStats(statistics); // Init Ngx-specific stats. NgxServerContext::InitStats(statistics); InPlaceResourceRecorder::InitStats(statistics); statistics->AddVariable(kShutdownCount); } } // namespace net_instaweb
// // Vertices.h // PLYLoader // // Created by JIANG, SHAN on 12-10-19. // Copyright (c) 2012 JIANG, SHAN. All rights reserved. // #ifndef PLYLoader_Vertices_h #define PLYLoader_Vertices_h #include "Points.h" #include "inc\Vec2.h" class Vertices: public Points{ public: Vertices(); ~Vertices(); void alcMem(unsigned int num, bool hasColorMap, bool hasNormal, bool hasTexCoords); void setNormals(Vec3 *nor); void setTexCoords(Vec2 *tex); Vec3 *getNormals(); Vec2 *getTexCoords(); unsigned int *getNeighbors(); bool hasTexture(); unsigned int getNumNgb(); private: bool hasNor, hasTex; Vec3 *normals; // array of point normals Vec2 *texCoords; // array of texture coords unsigned int *neighbors; unsigned int nn; }; #endif
// Файл util.h с реализацией вспомогательных утилит #include "util.h" // Запись строки символов в указанный файл void str2file(std::string &str, std::string fileName) { std::ofstream out; // поток для записи out.open(fileName); // окрываем файл для записи if (out.is_open()) { out << str; } } // Чтение из файла в вектор строк void file2vector(std::string fileName, std::vector<std::string> &text) { std::ifstream in; // поток для чтения in.open(fileName); // окрываем файл для записи std::string line; if (in.is_open()) { while (getline(in, line)) { text.push_back(line); } } } // Формирование строк для файла с глобальными объектами // Пока формируется только для одной единицы компиляции // В дальнейшем нужно будет собирать множество разных файлов с одинаковыми расширениями. void createGlobal(std::vector<std::string> &text, std::string filename) { // Создается заголовок, определяющий глобальный объект text.push_back( R""""(+package c2eo +alias c2eo.ctypes.c_bool +alias c2eo.ctypes.c_char +alias c2eo.ctypes.c_float64 +alias c2eo.ctypes.c_int16 +alias c2eo.ctypes.c_int32 +alias c2eo.ctypes.c_int64 [arg] > global )"""" ); // Читаются сформированные глобальные объекты file2vector(filename+".glob", text); // Формируется начало последовательности инициализаций text.push_back("\n seq > @"); // Читаются инициализации объектов file2vector(filename+".glob.seq", text); } // Запись сформированного файла с глобальными объектами void text2file(std::vector<std::string> &text, std::string fileName) { std::ofstream out; // поток для записи out.open(fileName); // окрываем файл для записи if (out.is_open()) { for(auto line: text) { out << line << "\n"; } } } void createStatic(std::vector<std::string> &text, std::string filename) { // Создается заголовок, определяющий статический объект text.push_back( R""""(+package c2eo +alias c2eo.ctypes.c_bool +alias c2eo.ctypes.c_char +alias c2eo.ctypes.c_float64 +alias c2eo.ctypes.c_int16 +alias c2eo.ctypes.c_int32 +alias c2eo.ctypes.c_int64 [arg] > )""""+filename+ "\n"); // Читаются сформированные статические объекты file2vector(filename+".stat", text); // Формируется начало последовательности инициализаций text.push_back("\n seq > @"); // Читаются инициализации объектов file2vector(filename+".stat.seq", text); }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Path.hpp" #include "Core/ResourceManager.hpp" #include "Math/Rectangle.hpp" #include "Serialization/Serialize.hpp" #include <cstdint> #include <type_traits> namespace Push { class Mask : public Noncopyable { public: Mask() = default; Mask(Mask&& rhs); Mask& operator=(Mask&& rhs); bool IsReady() const; bool CheckCollision(float x, float y) const; bool CheckCollision(const Vector& position) const; template<typename Serializer> void Serialize(Serializer& serializer); void Initialize(const Path& file); private: void Initialize(); private: Path m_file; std::unique_ptr<Resource, ResourceDeleter> m_resource; Path m_resourceFile; uint32_t m_width = 0u; uint32_t m_height = 0u; }; template<typename Serializer> void Mask::Serialize(Serializer& serializer) { Push::Serialize(serializer, "Resource", m_resourceFile); Push::Serialize(serializer, "Width", m_width); Push::Serialize(serializer, "Height", m_height); //INITIALIZE(); } }
#include <iostream> #include <vector> #include <utility> void test0(); int main() { test0(); return 0; } struct tracker { tracker() { std::cout << "calling tracker()\n"; } ~tracker() { std::cout << "calling ~tracker()\n"; } tracker(tracker const&) { std::cout << "calling tracker(tracker const&)\n"; } tracker& operator=(tracker const&) { std::cout << "calling operator=(tracker const&)\n"; return *this; } tracker(tracker&&) { std::cout << "callling tracker(tracker&&)\n"; } tracker& operator=(tracker&&) { std::cout << "calling operator(tracker&&)\n"; return *this; } }; std::tuple<std::vector<tracker>, std::vector<float>, int> func() { std::cout << "--- init ---\n"; std::vector<tracker> ints(10, tracker{}); std::vector<float> floats(20, 1.2f); std::cout << "--- return ---\n"; return {std::move(ints), std::move(floats), 5}; } void test0() { auto v = func(); std::cout << "--- finished ---\n"; }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2007-2015 Hartmut Kaiser // Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon // Copyright (c) 2012-2013 Thomas Heller // // 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/assert.hpp> #include <pika/string_util/from_string.hpp> #include <pika/string_util/trim.hpp> #include <pika/type_support/unused.hpp> #include <fmt/format.h> #include <climits> #include <cstddef> #include <cstdint> #include <string> // clang-format off #if defined(PIKA_HAVE_MORE_THAN_64_THREADS) || \ (defined(PIKA_HAVE_MAX_CPU_COUNT) && PIKA_HAVE_MAX_CPU_COUNT > 64) # if defined(PIKA_HAVE_MAX_CPU_COUNT) # include <bitset> # else # include <boost/dynamic_bitset.hpp> # endif #endif // clang-format on namespace pika::threads::detail { /// \cond NOINTERNAL #if !defined(PIKA_HAVE_MORE_THAN_64_THREADS) || \ (defined(PIKA_HAVE_MAX_CPU_COUNT) && PIKA_HAVE_MAX_CPU_COUNT <= 64) using mask_type = std::uint64_t; using mask_cref_type = std::uint64_t; inline std::uint64_t bits(std::size_t idx) { PIKA_ASSERT(idx < CHAR_BIT * sizeof(mask_type)); return std::uint64_t(1) << idx; } inline bool any(mask_cref_type mask) { return mask != 0; } inline mask_type not_(mask_cref_type mask) { return ~mask; } inline bool test(mask_cref_type mask, std::size_t idx) { PIKA_ASSERT(idx < CHAR_BIT * sizeof(mask_type)); return (bits(idx) & mask) != 0; } inline void set(mask_type& mask, std::size_t idx) { PIKA_ASSERT(idx < CHAR_BIT * sizeof(mask_type)); mask |= bits(idx); } inline void unset(mask_type& mask, std::size_t idx) { PIKA_ASSERT(idx < CHAR_BIT * sizeof(mask_type)); mask &= not_(bits(idx)); } inline std::size_t mask_size(mask_cref_type /*mask*/) { return CHAR_BIT * sizeof(mask_type); } inline void resize(mask_type& /*mask*/, std::size_t s) { PIKA_ASSERT(s <= CHAR_BIT * sizeof(mask_type)); PIKA_UNUSED(s); } inline std::size_t find_first(mask_cref_type mask) { if (mask) { std::size_t c = 0; // Will count mask's trailing zero bits. // Set mask's trailing 0s to 1s and zero rest. mask = (mask ^ (mask - 1)) >> 1; for (/**/; mask; ++c) mask >>= 1; return c; } return ~std::size_t(0); } inline bool equal(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return lhs == rhs; } // return true if at least one of the masks has a bit set inline bool bit_or(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return (lhs | rhs) != 0; } // return true if at least one bit is set in both masks inline bool bit_and(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return (lhs & rhs) != 0; } // returns the number of bits set // taken from https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan inline std::size_t count(mask_cref_type mask) { std::size_t c; // c accumulates the total bits set in v for (c = 0; mask; c++) { mask &= mask - 1; // clear the least significant bit set } return c; } inline void reset(mask_type& mask) { mask = 0ull; } // clang-format off #else # if defined(PIKA_HAVE_MAX_CPU_COUNT) using mask_type = std::bitset<PIKA_HAVE_MAX_CPU_COUNT>; using mask_cref_type = std::bitset<PIKA_HAVE_MAX_CPU_COUNT> const&; # else using mask_type = boost::dynamic_bitset<std::uint64_t>; using mask_cref_type = boost::dynamic_bitset<std::uint64_t> const&; # endif // clang-format on inline bool any(mask_cref_type mask) { return mask.any(); } inline mask_type not_(mask_cref_type mask) { return ~mask; } inline bool test(mask_cref_type mask, std::size_t idx) { return mask.test(idx); } inline void set(mask_type& mask, std::size_t idx) { mask.set(idx); } inline void unset(mask_type& mask, std::size_t idx) { mask.set(idx, 0); } inline std::size_t mask_size(mask_cref_type mask) { return mask.size(); } // clang-format off inline void resize(mask_type& mask, std::size_t s) { # if defined(PIKA_HAVE_MAX_CPU_COUNT) PIKA_ASSERT(s <= mask.size()); PIKA_UNUSED(mask); PIKA_UNUSED(s); # else return mask.resize(s); # endif } inline std::size_t find_first(mask_cref_type mask) { # if defined(PIKA_HAVE_MAX_CPU_COUNT) if (mask.any()) { for (std::size_t i = 0; i != PIKA_HAVE_MAX_CPU_COUNT; ++i) { if (mask[i]) return i; } } return ~std::size_t(0); # else return mask.find_first(); # endif } // clang-format on inline bool equal(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return lhs == rhs; } // return true if at least one of the masks has a bit set inline bool bit_or(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return (lhs | rhs).any(); } // return true if at least one bit is set in both masks inline bool bit_and(mask_cref_type lhs, mask_cref_type rhs, std::size_t = 0) { return (lhs & rhs).any(); } // returns the number of bits set inline std::size_t count(mask_cref_type mask) { return mask.count(); } inline void reset(mask_type& mask) { mask.reset(); } #endif PIKA_EXPORT std::string to_string(mask_cref_type); /// \endcond } // namespace pika::threads::detail namespace pika::detail { template <> struct from_string_impl<pika::threads::detail::mask_type, void> { template <typename Char> static void call(std::basic_string<Char> const& value, pika::threads::detail::mask_type& target) { // Trim whitespace from beginning and end std::basic_string<Char> value_trimmed = value; pika::detail::trim(value_trimmed); if (value_trimmed.size() < 3) { throw std::out_of_range( fmt::format("from_string<mask_type>: hexadecimal string (\"{}\"), expecting a " "prefix of 0x and at least one digit", value_trimmed)); } if (value_trimmed.find("0x") != 0) { throw std::out_of_range(fmt::format("from_string<mask_type>: hexadecimal string " "(\"{}\") does not start with \"0x\"", value_trimmed)); } // Convert a potentially hexadecimal character to an integer (mask) between 0 and 15 constexpr auto const to_mask = [](unsigned char const c) { if (48 <= c && c < 58) { return c - 48; } else if (auto const c_lower = std::tolower(c); 97 <= c_lower && c_lower < 103) { return c_lower - 87; } throw std::out_of_range(fmt::format( "from_string<mask_type>: got invalid hexadecimal character (\"{}\")", c)); }; pika::threads::detail::reset(target); pika::threads::detail::resize(target, 0); for (auto begin = value_trimmed.begin() + 2; begin != value_trimmed.cend(); ++begin) { // Each character read represents 4 bits so we make space for those bytes #if !defined(PIKA_HAVE_MAX_CPU_COUNT) pika::threads::detail::resize(target, pika::threads::detail::mask_size(target) + 4); #endif target <<= 4; // Store the current 4 bits into a mask of the same size as the target #if defined(PIKA_HAVE_MAX_CPU_COUNT) pika::threads::detail::mask_type cur(to_mask(*begin)); #else pika::threads::detail::mask_type cur( pika::threads::detail::mask_size(target), to_mask(*begin)); #endif // Add the newly read bits to the mask target |= cur; } } }; } // namespace pika::detail
/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef sequence_sink_hh #define sequence_sink_hh #include <map> #include "bookmarks.hh" #include "grep_proc.hh" #include "listview_curses.hh" #include "sequence_matcher.hh" class sequence_sink : public grep_proc_sink<vis_line_t> { public: sequence_sink(sequence_matcher& sm, bookmark_vector<vis_line_t>& bv) : ss_matcher(sm), ss_bookmarks(bv){}; void grep_match(grep_proc<vis_line_t>& gp, vis_line_t line, int start, int end) { this->ss_line_values.clear(); }; void grep_capture(grep_proc<vis_line_t>& gp, vis_line_t line, int start, int end, char* capture) { if (start == -1) { this->ss_line_values.push_back(""); } else { this->ss_line_values.push_back(std::string(capture)); } }; void grep_match_end(grep_proc<vis_line_t>& gp, vis_line_t line) { sequence_matcher::id_t line_id; this->ss_matcher.identity(this->ss_line_values, line_id); std::vector<vis_line_t>& line_state = this->ss_state[line_id]; if (this->ss_matcher.match(this->ss_line_values, line_state, line)) { std::vector<vis_line_t>::iterator iter; for (iter = line_state.begin(); iter != line_state.end(); ++iter) { this->ss_bookmarks.insert_once(vis_line_t(*iter)); } line_state.clear(); } }; private: sequence_matcher& ss_matcher; bookmark_vector<vis_line_t>& ss_bookmarks; std::vector<std::string> ss_line_values; std::map<sequence_matcher::id_t, std::vector<vis_line_t> > ss_state; }; #endif
#include <bits/stdc++.h> using namespace std; int n; char a[100], b[100]; int main() { // scanf("%d%s%s", &n, a + 1, b + 1); // int cmp = 0; //// for (int i = 1; i <= n; i++) { //// if (a[i] == '>') cmp++; //// else cmp--; //// if (b[i] == '<') cmp++; //// else cmp--; //// } // for (int i = 1; i <= n; i++) // if (a[i] != b[i]) // if (a[i] == '>') cmp++; // else cmp--; // if (cmp == 0) printf("Drew.\n"); // else if (cmp > 0) printf("uim wins.\n"); // else printf("uim wins."); return 0; }
#pragma once #include "bricks/config.h" #include "bricks/core/sfinae.h" #if BRICKS_CONFIG_LOGGING_ZOMBIES #include "bricks/core/object.h" #endif #define tempnew Bricks::Internal::TemporaryPointer() * namespace Bricks { #if BRICKS_CONFIG_RTTI template<typename T, typename U> static inline typename SFINAE::EnableIf<SFINAE::IsCompatibleType<T, U>::Value, T*>::Type CastToDynamic(U* u) { return static_cast<T*>(u); } template<typename T, typename U> static inline typename SFINAE::EnableIf<!SFINAE::IsCompatibleType<T, U>::Value, T*>::Type CastToDynamic(U* u) { return dynamic_cast<T*>(u); } template<typename T, typename U> static inline bool IsTypeOf(U* u) { return dynamic_cast<T*>(u); } // CastTo<>() uses static_cast where possible, and dynamic_cast otherwise. // In debug mode it also prefers dynamic_cast for base -> derived, while static_cast is used in release mode. #if BRICKS_ENV_RELEASE template<typename T, typename U> static inline typename SFINAE::EnableIf<SFINAE::IsCompatibleType<T, U>::Value || SFINAE::IsCompatibleType<U, T>::Value, T*>::Type CastTo(U* u) { return static_cast<T*>(u); } template<typename T, typename U> static inline typename SFINAE::EnableIf<!SFINAE::IsCompatibleType<T, U>::Value && !SFINAE::IsCompatibleType<U, T>::Value, T*>::Type CastTo(U* u) { return dynamic_cast<T*>(u); } #else template<typename T, typename U> static inline T* CastTo(U* u) { return CastToDynamic<T, U>(u); } #endif #else template<typename T, typename U> static inline T* CastTo(U* u) { return (T*)u; } template<typename T, typename U> static inline T* CastToDynamic(U* u) { return NULL; } template<typename T, typename U> static inline bool IsTypeOf(U* u) { return false; } #endif template<typename T> static inline const T* CastToRaw(const void* u) { return reinterpret_cast<const T*>(u); } template<typename T> static inline T* CastToRaw(void* u) { return reinterpret_cast<T*>(u); } template<typename U> static inline void* CastToRaw(U* u) { return reinterpret_cast<void*>(u); } template<typename T> class Pointer { private: T* value; public: typedef T Type; static Pointer<T> Null; Pointer() : value(NULL) { } Pointer(const Pointer<T>& t) : value(t.value) { } Pointer(T* t) : value(t) { } template<typename U> Pointer(const Pointer<U>& t, bool retain = true) : value(t.GetValue()) { } Pointer<T>& operator=(const Pointer<T>& t) { Swap(t); return *this; } Pointer<T>& operator=(T* t) { value = t; return *this; } template<typename U> Pointer<T>& operator=(const Pointer<U>& t) { Swap(t); return *this; } T* operator->() const { BRICKS_FEATURE_LOG_ZOMBIE(value); return value; } T& operator*() const { BRICKS_FEATURE_LOG_ZOMBIE(value); return *value; } T* GetValue() const { BRICKS_FEATURE_LOG_ZOMBIE(value); return value; } operator T*() const { BRICKS_FEATURE_LOG_ZOMBIE(value); return value; } void Swap(const Pointer<T>& t) { value = t.value; } }; template<typename T> Pointer<T> Pointer<T>::Null = Pointer<T>(NULL); #define BRICKS_INTERNAL_POINTER_COMPARISON(oper) \ template<typename T, typename T2> static bool operator oper(const Pointer<T>& t1, const Pointer<T2>& t2) { return t1.GetValue() oper t2.GetValue(); } \ template<typename T, typename T2> static bool operator oper(T* t1, const Pointer<T2>& t2) { return t1 oper t2.GetValue(); } \ template<typename T, typename T2> static bool operator oper(const Pointer<T>& t1, T2* t2) { return t1.GetValue() oper t2; } BRICKS_INTERNAL_POINTER_COMPARISON(==); BRICKS_INTERNAL_POINTER_COMPARISON(!=); BRICKS_INTERNAL_POINTER_COMPARISON(>); BRICKS_INTERNAL_POINTER_COMPARISON(<); BRICKS_INTERNAL_POINTER_COMPARISON(>=); BRICKS_INTERNAL_POINTER_COMPARISON(<=); #undef BRICKS_INTERNAL_POINTER_COMPARISON template<typename T, typename U> static inline T* CastTo(const Pointer<U>& u) { return CastTo<T, U>(u.GetValue()); } \ template<typename T, typename U> static inline T* CastToDynamic(const Pointer<U>& u) { return CastToDynamic<T, U>(u.GetValue()); } \ template<typename T, typename U> static inline bool IsTypeOf(const Pointer<U>& u) { return IsTypeOf<T, U>(u.GetValue()); } \ template<typename T, typename U> static inline T* CastToRaw(const Pointer<U>& u) { return CastToRaw<T>(u.GetValue()); } \ template<typename U> static inline void* CastToRaw(const Pointer<U>& u) { return CastToRaw<U>(u.GetValue()); } namespace Internal { struct TemporaryPointer { template<typename T> T* operator *(const T& t) { return const_cast<T*>(&t); } }; } }
#include <iostream> #include "capthread.h" #include "capfork.h" using namespace std; void strcpy(const string src, char *dst, size_t size) { if (size + 1 < src.size()) { return; } memcpy(dst, src.c_str(), src.size()); dst[src.size()] = '\0'; } int main() { string input; int type; cout << "type [0=q2.1, 1=q2.2, 2=q2.3]?"; cin >> type; cout << "input \t= "; cin >> input; size_t size = input.size() + 1; char *str = new char[size]; strcpy(input, str, size); if (type == 0) { cout << "convert by capthread" << endl; pthread_t threadId; pthread_create(&threadId, NULL, capthread, str); pthread_join(threadId, NULL); } else if (type == 1) { cout << "convert by capfork" << endl; capfork(str, size); } else if (type == 2) { cout << "convert by capfork (read & write)" << endl; auto ret = capfork2(str, size); memcpy(str, &ret[0], ret.size()); } cout << "output \t= " + string(str) << endl; delete[] str; return 0; }
/** * @file Single_Thread.hpp * * @author Matthew * @version 1.0.0 * @date Apr 17, 2015 */ #ifndef VALKNUT_CORE_THREAD_POLICIES_SINGLE_THREAD_HPP_ #define VALKNUT_CORE_THREAD_POLICIES_SINGLE_THREAD_HPP_ namespace valknut{ namespace thread_policies{ ////////////////////////////////////////////////////////////////////////// /// @class Single_Thread /// /// @todo Description /// ///////////////////////////////////////////////////////////////////////// class Single_Thread{ public: //---------------------------------------------------------------------- // Thread Policy API //---------------------------------------------------------------------- public: inline void enter() const{} inline void leave() const{} }; } // namespace thread_policies } // namespace valknut #endif /* VALKNUT_CORE_THREAD_POLICIES_SINGLE_THREAD_HPP_ */
#pragma once #include "ThreadSafeQueue.h" #include "AudioChunk.h" class SpotifyProvider { public: void StartThread(); SpotifyProvider(const char* username, const char* password, const char* listname, ThreadSafeQueue<AudioChunk>* queue); ~SpotifyProvider(); private: void Login(); static void ProcessThread(); const char * m_username; const char * m_password; };
#pragma once #include "cocos2d.h" #include "extensions/cocos-ext.h" #include "ui/CocosGUI.h" #include "SceneManager.h" USING_NS_CC; class LobbyLayer : public cocos2d::Layer { private: Sprite* m_RoomBG; ui::ListView* m_RoomViewbox; ui::Button *m_RoomCreate; ui::Button *m_Shop; ui::Button *m_Btn_Refresh; public: LobbyLayer(); ~LobbyLayer(); virtual bool init(); // implement the "static create()" method manually CREATE_FUNC(LobbyLayer); bool AddBtn(int RoomNum); void selectedRoomEvent(Ref* pSender, ui::ListView::EventType type); };
#include<iostream> using namespace std; int main() { char ac = 'a'; int ai = ac; cout << ai << " " << endl; cout << static_cast<int>(ac) << '\n'; return 0; }
#include "myview.h" #include <QLabel> #include <QDebug> MyView::MyView(QWidget *parent) : QAbstractItemView(parent) { } QRect MyView::visualRect(const QModelIndex &index) const { Q_UNUSED(index); return QRect(0, 0, 300, 200); } void MyView::scrollTo(const QModelIndex &index, ScrollHint hint) { Q_UNUSED(index); Q_UNUSED(hint); } QModelIndex MyView::indexAt(const QPoint &point) const { Q_UNUSED(point); Qt: return QModelIndex(); } QModelIndex MyView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) { Q_UNUSED(cursorAction); Q_UNUSED(modifiers); return QModelIndex(); } int MyView::horizontalOffset() const { return 0; } int MyView::verticalOffset() const { return 0; } bool MyView::isIndexHidden(const QModelIndex &index) const { Q_UNUSED(index) return false; } void MyView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) { Q_UNUSED(rect); Q_UNUSED(command); } QRegion MyView::visualRegionForSelection(const QItemSelection &selection) const { Q_UNUSED(selection); return QRegion(); } void MyView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) { Q_UNUSED(bottomRight); Q_UNUSED(roles); //モデルからデータを取得し、表示内容を更新する. updateView(topLeft, model()->data(topLeft)); }
#include "pch.h" #include "Room.h" Room::Room() { initParent(); } Room::~Room() { m_player = nullptr; m_dContext = nullptr; m_device = nullptr; m_gameTimerPointer = nullptr; m_models = nullptr; m_wvpCBuffers = nullptr; int i = 0; for (auto p : m_gameObjects) { i++; if (p != nullptr) { delete p; } } m_gameObjects.clear(); for (size_t i = 0; i < m_rooms.size(); i++) //Not created here. Will release in gamestate { m_rooms.at(i) = nullptr; } } void Room::initialize(ID3D11Device* device, ID3D11DeviceContext* dContext, std::unordered_map<std::string, Model>* models, std::vector<ConstBuffer<VS_WVPW_CONSTANT_BUFFER>>* cBuffer, Player* player, XMVECTOR position, std::shared_ptr<DirectX::AudioEngine> audioEngine, Timer* gameTimer, GameOptions option) { m_device = device; m_dContext = dContext; m_player = player; m_worldPosition = position; m_wvpCBuffers = cBuffer; m_models = models; m_audioEngine = audioEngine; m_gameTimerPointer = gameTimer; resourceHandler = &ResourceHandler::get(); option = option; } void Room::initParent() { m_dContext = nullptr; m_device = nullptr; m_player = nullptr; m_models = nullptr; m_wvpCBuffers = nullptr; m_entrencePosition = DirectX::XMVectorZero(); m_worldPosition = DirectX::XMVectorZero(); m_perFrameData.skyLightDirection = {-0.8f, 1.0f, -0.7f, }; m_perFrameData.skyLightColor = DirectX::XMFLOAT3(1.f, 1.0f, 1.0f); m_perFrameData.skyLightIntensity = 1.f; m_perFrameData.cameraPos = XMFLOAT3(0, 0, 0); m_perFrameData.nrOfPointLights = 0; m_perFrameData.fogStart = 0.f; m_perFrameData.fogEnd = 0.f; m_perFrameData.ambientColor = { 0.8f, 0.8f, 0.8f }; } void Room::update(float dt, Camera* camera, Room* &activeRoom, bool &activeRoomChanged) { for (size_t i = 0; i < m_gameObjects.size(); i++) { Portal* portalPtr = dynamic_cast<Portal*>(m_gameObjects[i]); if (portalPtr != nullptr) { portalPtr->update(); if (portalPtr->shouldChangeActiveRoom()) { activeRoom = m_rooms.at(portalPtr->getRoomID()); portalPtr->resetActiveRoomVariable(); activeRoomChanged = true; activeRoom->onEntrance(); } } else { m_gameObjects[i]->update(dt); } VS_WVPW_CONSTANT_BUFFER wvpData; DirectX::XMMATRIX viewPMtrx = camera->getViewMatrix() * camera->getProjectionMatrix(); wvpData.wvp = m_gameObjects[i]->getWorldMatrix() * viewPMtrx; wvpData.worldMatrix = m_gameObjects[i]->getWorldMatrix(); int wvpbufferIndex = m_gameObjects.at(i)->getWvpCBufferIndex(); m_wvpCBuffers->at(wvpbufferIndex).upd(&wvpData); } } void Room::onEntrance() { m_gameTimerPointer->stop(); m_player->setSpawnPosition(getEntrancePosition()); } void Room::addGameObjectToRoom(bool dynamic, bool colide, float weight, Model* mdl, DirectX::XMVECTOR position, DirectX::XMVECTOR scale3D, DirectX::XMFLOAT3 boundingBoxSize, DirectX::XMFLOAT3 acceleration, DirectX::XMFLOAT3 deceleration) { m_gameObjects.emplace_back(new GameObject()); GameObject* gObject = m_gameObjects.back(); m_wvpCBuffers->emplace_back(); m_wvpCBuffers->back().init(m_device, m_dContext); int bufferIndex = (int)m_wvpCBuffers->size() - 1; if (dynamic) { gObject->initializeDynamic(colide, false, bufferIndex, weight, acceleration, deceleration, mdl); } else { gObject->initializeStatic(colide, bufferIndex, mdl); } gObject->setScale(scale3D); gObject->setPosition(m_worldPosition + position); if (colide) { if(m_player != nullptr) m_player->addAABB(gObject->getAABBPtr()); } if (boundingBoxSize.x == 0 && boundingBoxSize.y == 0 && boundingBoxSize.z == 0) { } else gObject->setBoundingBox(boundingBoxSize); } void Room::addPlatformToRoom(Model* mdl, DirectX::XMVECTOR position, DirectX::XMFLOAT3 platformBoundingBox, BoundingOrientedBox* pyramid) { m_wvpCBuffers->emplace_back(); m_wvpCBuffers->back().init(m_device, m_dContext); m_gameObjects.emplace_back(new Platform()); dynamic_cast<Platform*>(m_gameObjects.back())->init(true, (int)m_wvpCBuffers->size() - 1, pyramid, mdl); XMVECTOR pos = m_worldPosition + position; m_gameObjects.back()->setBoundingBox(platformBoundingBox); m_gameObjects.back()->setPosition(pos); if(m_player != nullptr) m_player->addAABB(m_gameObjects.back()->getAABBPtr()); } void Room::addPortalToRoom(XMVECTOR teleportLocation, Model* mdl, DirectX::XMVECTOR position, DirectX::XMVECTOR scale3D, DirectX::XMFLOAT3 boundingBoxSize, int room, bool oneTimeUse) { m_wvpCBuffers->emplace_back(); m_wvpCBuffers->back().init(m_device, m_dContext); int bufferIndex = (int)m_wvpCBuffers->size() - 1; XMVECTOR pos = m_worldPosition + teleportLocation; m_gameObjects.emplace_back(new Portal()); if(room != -1) dynamic_cast<Portal*>(m_gameObjects.back())->initialize((int)m_wvpCBuffers->size() - 1, mdl, m_rooms[room]->getEntrancePosition() + XMVectorSet(0.f, m_player->getAABB().Extents.y + 0.1f, 0, 0), m_player, room, oneTimeUse); else dynamic_cast<Portal*>(m_gameObjects.back())->initialize((int)m_wvpCBuffers->size() - 1, mdl, pos, m_player, room, oneTimeUse); pos = m_worldPosition + position; m_gameObjects.back()->setScale(scale3D); m_gameObjects.back()->setPosition(pos); m_gameObjects.back()->setBoundingBox(boundingBoxSize); //m_player.addAABB(m_gameObjects.back()->getAABBPtr()); } void Room::addLeverToRoom(Model* mdl, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation, DirectX::XMFLOAT3 leverBB) { XMVECTOR pos = m_worldPosition + position; m_wvpCBuffers->emplace_back(); m_wvpCBuffers->back().init(m_device, m_dContext); m_gameObjects.emplace_back(new Lever()); dynamic_cast<Lever*>(m_gameObjects.back())->init(false, (int)m_wvpCBuffers->size() - 1, mdl); m_gameObjects.back()->setPosition(pos); m_gameObjects.back()->setBoundingBox(leverBB); m_gameObjects.back()->getMoveCompPtr()->rotation = rotation; } void Room::addObjectToRoom(GameObject* object) { m_wvpCBuffers->emplace_back(); m_wvpCBuffers->back().init(m_device, m_dContext); m_gameObjects.emplace_back(object); m_gameObjects.back()->setWvpCBufferIndex((int)m_wvpCBuffers->size() - 1); } std::vector<GameObject*>* Room::getGameObjectsPtr() { return &m_gameObjects; } std::vector<BoundingBox>* Room::getBoundingBoxPtr() { return &m_boundingBoxes; } std::vector<BoundingOrientedBox>* Room::getOrientedBoundingBoxPtr() { return &m_orientedBoundingBoxes; } std::vector<BoundingBox>* Room::getTriggerBoxes() { return &m_triggerBoundingBoxes; } void Room::addBoundingBox(XMVECTOR position, XMFLOAT3 extends) { XMFLOAT3 roomPos; XMStoreFloat3(&roomPos, m_worldPosition + position); m_boundingBoxes.emplace_back(roomPos, extends); } void Room::addOrientedBoundingBox(XMVECTOR position, XMFLOAT3 extends, XMVECTOR rotation) { XMFLOAT3 roomPos; XMStoreFloat3(&roomPos, m_worldPosition + position); XMVECTOR rotationVector = XMQuaternionRotationRollPitchYawFromVector(rotation); XMFLOAT4 rot; XMStoreFloat4(&rot, rotationVector); m_orientedBoundingBoxes.emplace_back(roomPos, extends, rot); } void Room::addOrientedBoundingBox(BoundingOrientedBox OBB) { m_orientedBoundingBoxes.emplace_back(OBB); } void Room::addTriggerBB(XMVECTOR position, XMFLOAT3 extends) { XMFLOAT3 roomPos; XMStoreFloat3(&roomPos, m_worldPosition + position); m_triggerBoundingBoxes.emplace_back(roomPos, extends); } DirectX::XMVECTOR Room::getEntrancePosition() const { if (m_player == nullptr) return XMVectorZero(); return (m_worldPosition + m_entrencePosition + XMVectorSet(0.f, m_player->getAABB().Extents.y + 0.1f, 0, 0)); } void Room::addRooms(std::vector<Room*>* rooms) { for (size_t i = 0; i < rooms->size(); i++) { m_rooms.emplace_back(rooms->at(i)); } } void Room::updatePlayerBB() { if (m_player == nullptr) return; for (size_t i = 0; i < m_gameObjects.size(); i++) { if(m_gameObjects.at(i)->collidable()) m_player->addAABB(m_gameObjects.at(i)->getAABBPtr()); } m_player->addAABBFromVector(&m_boundingBoxes); m_player->addOrientedBBFromVector(&m_orientedBoundingBoxes); } int Room::createLight(XMFLOAT3 position, float range, XMFLOAT3 diffuseColor) { if(m_perFrameData.nrOfPointLights <= 5) { XMFLOAT3 wPos; XMStoreFloat3(&wPos, m_worldPosition + XMLoadFloat3(&position)); PointLight pLight; pLight.position = wPos; pLight.range = range; pLight.diffuse = diffuseColor; m_perFrameData.pointLights[m_perFrameData.nrOfPointLights++] = pLight; } else { assert(false && "Error, adding more lights to room than allowed."); } return m_perFrameData.nrOfPointLights - 1; } int Room::createLight(PointLight pLight) { XMFLOAT3 wPos; XMStoreFloat3(&wPos, m_worldPosition + XMLoadFloat3(&pLight.position)); pLight.position = wPos; if (m_perFrameData.nrOfPointLights <= MAX_POINT_LIGHTS) { m_perFrameData.pointLights[m_perFrameData.nrOfPointLights++] = pLight; } else { assert(false && "Error, adding more lights to room than allowed."); } return m_perFrameData.nrOfPointLights - 1; } void Room::changeLight(int index, XMFLOAT3 position, float range, XMFLOAT3 diffuseColor) { m_perFrameData.pointLights[index].position = position; m_perFrameData.pointLights[index].diffuse = diffuseColor; m_perFrameData.pointLights[index].range = range; } void Room::changeLight(const int index, PointLight light) { m_perFrameData.pointLights[index].position = light.position; m_perFrameData.pointLights[index].diffuse = light.diffuse; m_perFrameData.pointLights[index].range = light.range; } PointLight* Room::getLight(int index) { return &m_perFrameData.pointLights[index]; } DirectX::XMVECTOR Room::getRelativePosition(DirectX::XMVECTOR pos) const { XMVECTOR temp = m_worldPosition + pos; return temp; } PS_PER_FRAME_BUFFER Room::getPerFrameData() { return m_perFrameData; }
/* * In a more traditional environments, one would split into .H and .CPP files. However in Arduino, the ".ino" file * comes with certain built-in includes (such as "Arduino.h" and more) which are not automatically added to other CPP * files. So, to make things more seamless, I will be putting implementation directly into the header files, which may * look unnatural to C++ purists */ #pragma once #include <stdarg.h> #define TDM_SERVO_ANGLEMIN 0 //Physical servos rotate between 0 .. 180 degrees #define TDM_SERVO_ANGLEMAX 180 //Physical servos rotate between 0 .. 180 degrees #define TDM_SERVO_PULSEMIN 130 //PWM pulse between 130 and 600 #define TDM_SERVO_PULSEMAX 600 //PWM pulse between 130 and 600 #define TDM_SERVO_MAXCOUNT (TDM_PWM_NUMBER_OF_CONTROLLERS * TDM_PWM_CHANNELS_PER_CONTROLLER) namespace tdm { /* * This should have been a static member of the Servo class, however given the fact how statics * behave from .H files, we'll keep it global */ void* _CACHED_SERVOS[TDM_SERVO_MAXCOUNT]; /* * A class for controling single servo */ class Servo { private: uint8_t _channel; PwmIO _pwm; Servo(uint8_t channel) { _channel = channel; } public: /* * A static builder for creating & caching servos */ static Servo* build(uint8_t channel) { if (channel<TDM_SERVO_MAXCOUNT) { if (_CACHED_SERVOS[channel]==NULL) { _CACHED_SERVOS[channel] = new Servo(channel); } return (Servo*) _CACHED_SERVOS[channel]; } return NULL; } /* * set servo to certain angle */ void setAngle(int degrees){ _pwm.setPulse(_channel, computePulseLength(degrees)); } /* * turn off the servo */ void turnOff(void) { _pwm.setPulse(_channel, TDM_PWM_PIN_OFF); } /* * Get the servo channel */ uint8_t getChannel() { return _channel; } private: /* * convert from degrees to PWM pulses */ int computePulseLength (int degrees){ if(degrees>=TDM_SERVO_ANGLEMAX){degrees=TDM_SERVO_ANGLEMAX;} if(degrees<=TDM_SERVO_ANGLEMIN){degrees=TDM_SERVO_ANGLEMIN;} return map(degrees,TDM_SERVO_ANGLEMIN,TDM_SERVO_ANGLEMAX,TDM_SERVO_PULSEMIN,TDM_SERVO_PULSEMAX); } }; //class Servo /* * A class for controling multiple servos */ class ServoGroup { private: Vector<Servo*> _items; public: ServoGroup() { }; /* * Construct a servo group from parameters. Example: (3,0,9,12) describes a group * of 3 servos, taking channels 0, 9 and 12 */ ServoGroup(int numargs, ...) { va_list args; va_start(args, numargs); for(int i=0; i<numargs; i++) { addChannel(va_arg(args, uint8_t)); } va_end(args); } /* * add servo channel to group */ void addChannel(uint8_t channel) { _items.push_back(Servo::build(channel)); } /* * get servo channel at index */ uint8_t getChannelAtIndex(int index) { return _items[index]->getChannel(); } /* * set angles */ void setAngles(int degrees[]){ for(int i=0; i < _items.size(); i++) { _items[i]->setAngle(degrees[i]); } } /* * turn off all servos */ void turnOffAllServos(void) { for(int i=0; i < _items.size(); i++) { _items[i]->turnOff(); } } /* * turn off one servo at index */ void turnOffAtIndex(int index) { _items[index]->turnOff(); } /* * get the group size */ int size() { return _items.size(); } }; //class ServoGroup }; //namespace
// Copyright 2011 Yandex #ifndef LTR_LEARNERS_COMPOSITION_LEARNER_LINEAR_COMPOSITION_LEARNER_H_ #define LTR_LEARNERS_COMPOSITION_LEARNER_LINEAR_COMPOSITION_LEARNER_H_ #include "ltr/utility/shared_ptr.h" #include "ltr/learners/composition_learner/composition_learner.h" #include "ltr/scorers/composition_scorers/linear_composition_scorer.h" namespace ltr { namespace composition { /** * A composition learner, what produces a linear composition scorer */ template <class TElement> class LinearCompositionLearner : public CompositionLearner<TElement, LinearCompositionScorer> { typedef ltr::utility::shared_ptr<LinearCompositionLearner> Ptr; private: virtual string getDefaultAlias() const { return "LinearCompositionLearner"; } }; }; }; #endif // LTR_LEARNERS_COMPOSITION_LEARNER_LINEAR_COMPOSITION_LEARNER_H_
/* -*- Mode: c++; tab-width: 4; 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. * * @author Arjan van Leeuwen (arjanl) */ group "webfeeds.webfeed_reader_manager"; require WEBFEEDS_EXTERNAL_READERS; include "modules/webfeeds/src/webfeed_reader_manager.h"; include "modules/prefsfile/prefsfile.h"; include "modules/util/opfile/opfile.h"; global { PrefsFile* prefsfile; OpFile file; }; setup { file.Construct(UNI_L("webfeed_providers.ini"), OPFILE_TEMP_FOLDER); prefsfile = OP_NEW(PrefsFile, (PREFS_INI)); if (prefsfile) { TRAPD(err, prefsfile->ConstructL(); prefsfile->SetFileL(&file); prefsfile->WriteIntL("Google Reader", "ID", 1); prefsfile->WriteStringL("Google Reader", "URL", UNI_L("http://reader.google.com/subscribe?url=%s")); prefsfile->WriteIntL("BlablaBlabla", "ID", 3); prefsfile->WriteStringL("BlablaBlabla", "URL", UNI_L("http://blabla.bla.com/subscribe?url=%s")); prefsfile->CommitL(); ); } }; test("get reader IDs") { WebFeedReaderManager manager; verify(OpStatus::IsSuccess(manager.Init(prefsfile, TRUE))); verify(manager.GetCount() == 2); verify(manager.GetIdByIndex(0) == 1); verify(manager.GetIdByIndex(1) == 3); }; test("get reader names") { WebFeedReaderManager manager; verify(OpStatus::IsSuccess(manager.Init(prefsfile, TRUE))); OpString name; verify(OpStatus::IsSuccess(manager.GetName(1, name))); verify(name.Compare(UNI_L("Google Reader")) == 0); }; test("get url for external reader") { WebFeedReaderManager manager; verify(OpStatus::IsSuccess(manager.Init(prefsfile, TRUE))); URL feed_url = g_url_api->GetURL("http://www.overheardinnewyork.com/index.xml"); URL correct_subscribe_url = g_url_api->GetURL("http://reader.google.com/subscribe?url=http%3A%2F%2Fwww.overheardinnewyork.com%2Findex.xml"); URL target_url; verify(OpStatus::IsSuccess(manager.GetTargetURL(1, feed_url, target_url))); verify(correct_subscribe_url == target_url); }; exit { OP_DELETE(prefsfile); file.Delete(); };
// You need the definitions in the dynamiclinklibrary.h file to call the DLLs functions from your app // dynamiclinklibraries.cpp : Defines the entry point for the console application. // Compile by using: cl /EHsc /link dynamiclinklibrary.lib MathClient.cpp #include "stdafx.h" #include <iostream> #include "dynamiclinklibrary.h" using namespace std; int main() { double a = 7.4; int b = 99; cout << "a + b = " << dynamiclinklibrary::Functions::Add(a, b) << endl; cout << "a * b = " << dynamiclinklibrary::Functions::Multiply(a, b) << endl; cout << "a + (a * b) = " << dynamiclinklibrary::Functions::AddMultiply(a, b) << endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include "Table.h" #include "AllocSvrConnect.h" #include "Logger.h" #include "Configure.h" #include "IProcess.h" #include "TaskRedis.h" #include "CoinConf.h" #include "Util.h" #include "OperationRedis.h" Table::Table():status(-1) { } Table::~Table() { } void Table::init() { timer.init(this); stopAllTimer(); this->status = STATUS_TABLE_EMPTY; clevel = Configure::getInstance()->level; ante = 0; tax = 0; memset(player_array, 0, sizeof(player_array)); memset(m_bTableCardArray, 0, sizeof(m_bTableCardArray)); countPlayer = 0; currRound = 0; currMaxCoin = 0; raseUid = 0; betUid = 0; commonCoin = 0; raterent = 0; maxbetcoin = 0; pregame_winner = NULL; memset(leaverarry, 0, sizeof(leaverarry)); leavercount=0; memset(winnerorder, 0, sizeof(winnerorder)); winnercount = 0; maxCount = Configure::getInstance()->numplayer; thisGameLimit = 0; owner = 0; haspasswd = false; tableName[0] = '\0'; password[0] = '\0'; GameID[0] = '\0'; EndType = 0; kicktimeflag = false; isthrowwin = false; m_nRePlayTime = 0; SendCardTime = 0; hassendcard = false; m_nRoundNum1 = 0; m_nRoundNum2 = 0; m_nRoundNum3 = 0; m_nGetCoinHigh1 = 0; m_nGetCoinLow1 = 0; m_nGetCoinHigh2 = 0; m_nGetCoinLow2 = 0; m_nGetCoinHigh3 = 0; m_nGetCoinLow3 = 0; m_bRewardType = 1; m_nGetRollHigh1 = 0; m_nGetRollLow1 = 0; m_nGetRollHigh2 = 0; m_nGetRollLow2 = 0; m_nGetRollHigh3 = 0; m_nGetRollLow3 = 0; m_nMagicCoin = 1; } void Table::reset() { currRound = 0; currMaxCoin = 0; raseUid = 0; betUid = 0; commonCoin = 0; raterent = 0; maxbetcoin = 0; memset(leaverarry, 0, sizeof(leaverarry)); leavercount=0; memset(winnerorder, 0, sizeof(winnerorder)); winnercount = 0; GameID[0] = '\0'; EndType = 0; thisGameLimit = 0; memset(m_bTableCardArray, 0, sizeof(m_bTableCardArray)); kicktimeflag = false; isthrowwin = false; SendCardTime = 0; hassendcard = false; m_nRoundNum1 = 0; m_nRoundNum2 = 0; m_nRoundNum3 = 0; m_nGetCoinHigh1 = 0; m_nGetCoinLow1 = 0; m_nGetCoinHigh2 = 0; m_nGetCoinLow2 = 0; m_nGetCoinHigh3 = 0; m_nGetCoinLow3 = 0; m_bRewardType = 1; m_nGetRollHigh1 = 0; m_nGetRollLow1 = 0; m_nGetRollHigh2 = 0; m_nGetRollLow2 = 0; m_nGetRollHigh3 = 0; m_nGetRollLow3 = 0; this->setRoundTaskConf(); } Player* Table::getPlayer(int uid) { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->id == uid) return player; } return NULL; } bool Table::isUserInTab(int uid) { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->id == uid) return true; } return false; } int Table::playerSeatInTab(Player* complayer) { /*for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] == NULL) { player_array[i] = complayer; complayer->status = STATUS_PLAYER_COMING; complayer->tid = this->id; complayer->tab_index = i; return 0; } }*/ //调整用户进入的顺序,促使进入如果只有两个用户则在对面 if(player_array[0] == NULL) { player_array[0] = complayer; complayer->status = STATUS_PLAYER_COMING; complayer->tid = this->id; complayer->tab_index = 0; return 0; } if(player_array[2] == NULL) { player_array[2] = complayer; complayer->status = STATUS_PLAYER_COMING; complayer->tid = this->id; complayer->tab_index = 2; return 0; } //当前桌子只允许两个人 if(maxCount == 2) return -1; if(player_array[1] == NULL) { player_array[1] = complayer; complayer->status = STATUS_PLAYER_COMING; complayer->tid = this->id; complayer->tab_index = 1; return 0; } //当前桌子只允许三个人 if(maxCount == 3) return -1; if(player_array[3] == NULL) { player_array[3] = complayer; complayer->status = STATUS_PLAYER_COMING; complayer->tid = this->id; complayer->tab_index = 3; return 0; } return -1; } int Table::playerComming(Player* player) { if(player == NULL) return -1; //如果此用户已经在此桌子则把另外那个player清除,替代为新的player if(isUserInTab(player->id)) { for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] && player_array[i]->id == player->id) { player->status = player_array[i]->status; player->tid = player_array[i]->tid; player->tab_index = player_array[i]->tab_index; player->thisroundhasbet = player_array[i]->thisroundhasbet; player->hasallin = player_array[i]->hasallin; player->optype = player_array[i]->optype; player->hascard = player_array[i]->hascard; player->nextlimitcoin = player_array[i]->nextlimitcoin; player->carrycoin = player_array[i]->carrycoin; player->betCoinList[0] = player_array[i]->betCoinList[0]; player->betCoinList[1] = player_array[i]->betCoinList[1]; player->betCoinList[2] = player_array[i]->betCoinList[2]; player->betCoinList[3] = player_array[i]->betCoinList[3]; player->betCoinList[4] = player_array[i]->betCoinList[4]; player->card_array[0] = player_array[i]->card_array[0]; player->card_array[1] = player_array[i]->card_array[1]; player->card_array[2] = player_array[i]->card_array[2]; player->card_array[3] = player_array[i]->card_array[3]; player->card_array[4] = player_array[i]->card_array[4]; player_array[i]->init(); player_array[i] = player; } } return 0; } //说明此房间这个用户进入不成功,返回-2之后重新给此用户分配房间 if(playerSeatInTab(player) < 0) return -2; //如果桌子不是在玩牌则状态变为等待准备状态 if(!this->isActive()) { this->status = STATUS_TABLE_READY; } //这里设置用户进入的标志,并且设置状态 player->enter(); //当前用户数加1 ++this->countPlayer; if(this->countPlayer == 1) this->setRoundTaskConf(); AllocSvrConnect::getInstance()->updateTableUserCount(this); return 0; } void Table::setSeatNULL(Player* player) { for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] == player) player_array[i] = NULL; } } void Table::playerLeave(int uid) { Player* player = this->getPlayer(uid); if(player) { this->playerLeave(player); } } void Table::playerLeave(Player* player) { if(player == NULL) return; if (!isUserInTab(player->id)) { return; } _LOG_WARN_("Tid[%d] Player[%d] Leave\n", this->id, player->id); //清空上一个赢牌的用户 if(pregame_winner) { if(pregame_winner->id == player->id) pregame_winner = NULL; } player->leave(); player->init(); this->setSeatNULL(player); //如果桌子不是在玩牌则状态变为等待准备状态 if(!this->isActive()) { this->status = STATUS_TABLE_READY; } //当前用户减一 --this->countPlayer; //房间里面只剩一个人的时候直接解锁 if(this->countPlayer == 1) { stopKickTimer(); unlockTable(); } if(this->isEmpty()) { this->init(); } AllocSvrConnect::getInstance()->updateTableUserCount(this); } bool Table::isAllReady() { int readyCount=0; for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] && player_array[i]->isReady()) readyCount++; if(readyCount == this->countPlayer) return true; } return false; } bool Table::isAllRobot() { for(int i = 0; i < this->leavercount; ++i) { if(leaverarry[i].source != 30) return false; } for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] && player_array[i]->source != 30) { //排除掉还没有准备的情况 if(player_array[i]->isComming()) continue; if(!player_array[i]->isReady()) return false; } } return true; } bool Table::isCanGameStart() { int readyCount=0; for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] && player_array[i]->isReady()) readyCount++; //大于两个人准备则说明此盘游戏可以开始了 if(readyCount >= 2) return true; } return false; } void Table::gameStart() { stopTableStartTimer(); stopKickTimer(); unlockTable(); int i = 0; int j = 0; m_GameLogic.RandCard(m_bTableCardArray[0],sizeof(m_bTableCardArray)/sizeof(m_bTableCardArray[0][0])); //这里是手动做牌,给牌型任务做测试 /*BYTE cardArray1[5] = {0x29, 0x11, 0x1b, 0x38, 0x09 }; memcpy(m_bTableCardArray[0],cardArray1, sizeof(m_bTableCardArray[0])); //m_bTableCardArray[1] = {0x18,0x1c,0x1d,0x3a,0x3d}; BYTE cardArray2[5] = {0x3b, 0x1a, 0x39, 0x1c, 0x2d}; memcpy(m_bTableCardArray[2],cardArray2, sizeof(m_bTableCardArray[2])); //m_bTableCardArray[3] = {0x08,0x09,0x1a,0x2b,0x3c};*/ int randnum = rand()%100; //randnum = 0; //高级场 if((Configure::getInstance()->level == 3 || Configure::getInstance()->level == 4)&& randnum < Configure::getInstance()->loserate) { for(i = 0; i < GAME_PLAYER; ++i) { char cardbuff[64]={0}; for(j = 0; j < 5; ++j) { sprintf(cardbuff+5*j, "0x%02x ",m_bTableCardArray[i][j]); } _LOG_DEBUG_("[gameStart] tid=[%d] cardarray:[%s]\n", this->id,cardbuff); } short templowindex = -1; for(i = 0; i < GAME_PLAYER; ++i) { if(player_array[i]) { player_array[i]->isbacklist = CoinConf::getInstance()->isUserInBlackList(player_array[i]->id); if(player_array[i]->isbacklist) { templowindex = i; break; } } } printf("templowindex:%d \n", templowindex); if(templowindex >= 0) { BYTE templowcard[5] = {0}; short tempindex = 0; for(i = 0; i < GAME_PLAYER; ++i) { if(player_array[i]) { memcpy(templowcard, m_bTableCardArray[i], 5); tempindex = i; break; } } for(j = 0; j < GAME_PLAYER; ++j) { if(i != j && player_array[j]) { BYTE tempfirst[5]; BYTE tempsecond[5]; memcpy(tempfirst, templowcard, 5); memcpy(tempsecond, m_bTableCardArray[j], 5); bool retflag = m_GameLogic.CompareCard(tempfirst, tempsecond, 5); printf("j:%d retflag:%s\n", j, retflag ? "true":"flase"); if(retflag) { memcpy(templowcard, m_bTableCardArray[j], 5); tempindex = j; } } } printf("templowindex:%d tempindex:%d \n", templowindex, tempindex); if(templowindex != tempindex) { memcpy(m_bTableCardArray[tempindex], m_bTableCardArray[templowindex], 5); memcpy(m_bTableCardArray[templowindex], templowcard, 5); } } } for(i = 0; i < GAME_PLAYER; ++i) { char cardbuff[64]={0}; for(j = 0; j < 5; ++j) { sprintf(cardbuff+5*j, "0x%02x ",m_bTableCardArray[i][j]); } _LOG_DEBUG_("[gameStart] tid=[%d] cardarray:[%s]\n", this->id,cardbuff); } for(i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player) { memcpy(player->card_array,m_bTableCardArray[i], sizeof(m_bTableCardArray[0])); char cardbuff[64]={0}; for(j = 0; j < 5; ++j) { sprintf(cardbuff+5*j, "0x%02x ",player->card_array[j]); } BYTE bCardArray[5]; memcpy(bCardArray, player->card_array, 5); m_GameLogic.SortCard(bCardArray, 5); _LOG_INFO_("[gameStart] tid=[%d] uid=[%d] cardarray:[%s] cardType:%d\n", this->id, player->id, cardbuff, m_GameLogic.GetCardKind(bCardArray, 5)); player->hascard = true; player->status = STATUS_PLAYER_ACTIVE; if(player->istask) { if(Configure::getInstance()->level <= 3) { int randnum = rand()%100; int CurTotal = TaskRedis::getInstance()->getPlayerCompleteCount(player->id); if( CurTotal < Configure::getInstance()->curBeforeCount ) { int randTemp = Configure::getInstance()->esayTaskProbability; if( randTemp != 100 ) { randTemp += rand()%(100 - randTemp); } if( randnum < randTemp ) { player->task1 = TaskManager::getInstance()->getRandEsayTask(); } } /*if( (player->task1 == NULL) && (randnum < Configure::getInstance()->esayRandNum) ) { player->task1 = TaskManager::getInstance()->getRandEsayTask(); }*/ if(player->task1 == NULL) { player->task1 = TaskManager::getInstance()->getRandTask(); } if(player->task1) { player->ningot = player->task1->ningotlow + rand()%(player->task1->ningothigh - player->task1->ningotlow + 1); _LOG_INFO_("player[%d] get taskid[%ld] taskname[%s] level[%d]\n", player->id, player->task1->taskid, player->source == 1 ? player->task1->taskANDname : player->task1->taskIOSname, this->clevel); } } } AllocSvrConnect::getInstance()->userUpdateStatus(player, STATUS_PLAYER_ACTIVE); } } //设置桌子的台费规则 this->setTableRent(); //设置用户携带的金币数量 //this->setPlayerCarryCoin(); this->status = STATUS_TABLE_ACTIVE; this->setStartTime(time(NULL)); time_t t; time(&t); char time_str[32]={0}; struct tm* tp= localtime(&t); strftime(time_str,32,"%Y%m%d%H%M%S",tp); char gameId[64] ={0}; short tlevel = this->clevel; sprintf(gameId, "%s|%02d|%02d|%d|%d|%d|%d", time_str,tlevel,this->countPlayer, player_array[0]?player_array[0]->id:0, player_array[1]?player_array[1]->id:0, player_array[2]?player_array[2]->id:0, player_array[3]?player_array[3]->id:0); this->setGameID(gameId); _LOG_INFO_("[gameStart] tid=[%d] raterent[%d] ante[%d] gameid[%s]\n",this->id, this->raterent, this->ante, this->getGameID()); AllocSvrConnect::getInstance()->updateTableStatus(this); //把当前这局的金币数限制为带入金币第二大的人 this->thisGameLimit = getSecondLargeCoin(); } void Table::setTableRent() { //这主要是解决游戏还没有开始桌费配置修改的情况 //找到当前低注类型,如果这个桌子这几人中有读到配置是固定台费和按比率台费的则默认按固定台费收 //如果都是一种类型,则按照里面最小的那个人确定这个桌子的台费 // int64_t minmoney = 0x7FFFFFFFFFFFFF; // short minrate = 1000; // for(int i = 0; i < GAME_PLAYER; ++i) // { // Player* player = player_array[i]; // if(player && player->isActive()) // { // if(player->coincfg.raterent < minrate) // { // minrate = player->coincfg.raterent; // } // if(player->carrycoin < minmoney) // minmoney = player->carrycoin; // } // } // this->raterent = minrate; // if(minmoney/Configure::getInstance()->fraction < 1) // this->ante = 1; // else // this->ante = (int64_t)minmoney/Configure::getInstance()->fraction; CoinCfg cfg; cfg.level = Configure::getInstance()->level; CoinConf::getInstance()->getCoinCfg(&cfg); this->tax = cfg.tax; this->ante = cfg.ante; LOGGER(E_LOG_INFO) << "Ante=" << this->ante << " tax=" << this->tax; } void Table::setRoundTaskConf() { int i = 0; for(i= 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player) { this->m_nRoundNum1 = player->coincfg.roundnum & 0x00FF; this->m_nRoundNum2 = player->coincfg.roundnum>>8 & 0x00FF; this->m_nRoundNum3 = player->coincfg.roundnum>>16 & 0x00FF; this->m_nGetCoinHigh1 = player->coincfg.coinhigh1; this->m_nGetCoinLow1 = player->coincfg.coinlow1; this->m_nGetCoinHigh2 = player->coincfg.coinhigh2; this->m_nGetCoinLow2 = player->coincfg.coinlow2; this->m_nGetCoinHigh3 = player->coincfg.coinhigh3; this->m_nGetCoinLow3 = player->coincfg.coinlow3; this->m_bRewardType = player->coincfg.rewardtype; this->m_nGetRollHigh1 = player->coincfg.rollhigh1; this->m_nGetRollLow1 = player->coincfg.rolllow1; this->m_nGetRollHigh2 = player->coincfg.rollhigh2; this->m_nGetRollLow2 = player->coincfg.rolllow2; this->m_nGetRollHigh3 = player->coincfg.rollhigh3; this->m_nGetRollLow3 = player->coincfg.rolllow3; this->m_nMagicCoin = player->coincfg.magiccoin; } } if(rand()%100 < Configure::getInstance()->rewardRate) this->m_bRewardType = 1; else this->m_bRewardType = 2; } //是否只有一个人正在玩牌的人,如果只有一个winner就为那个人 bool Table::iscanGameOver(Player **winner) { if(!this->isActive()) return false; short activeCount = 0; for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; //此人必须是active状态,并且有手牌 if(player && player->isActive() && player->hascard) { ++activeCount; *winner = player; if(activeCount > 1) return false; } } return true; } //是否只有一个人正在玩牌的人,如果只有一个winner就为那个人 bool Table::iscanGameOver() { if(!this->isActive()) return false; short activeCount = 0; for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; //此人必须是active状态,并且有手牌 if(player && player->isActive() && player->hascard) { ++activeCount; if(activeCount > 1) return false; } } return true; } void Table::setPlayerlimitcoin(Player* nextplayer) { _LOG_DEBUG_("=-----------------maxbetcoin:%d\n", this->maxbetcoin); nextplayer->nextlimitcoin = this->maxbetcoin - nextplayer->betCoinList[this->currRound]; if(nextplayer->nextlimitcoin > nextplayer->carrycoin - nextplayer->betCoinList[0]) nextplayer->nextlimitcoin = nextplayer->carrycoin - nextplayer->betCoinList[0]; else nextplayer->nextlimitcoin = nextplayer->nextlimitcoin; } void Table::setPlayerOptype(Player* player, short playeroptype) { if(playeroptype == OP_CHECK) { if(this->currRound < 2) player->optype = OP_RASE|OP_CHECK|OP_THROW; else player->optype = OP_ALLIN|OP_RASE|OP_CHECK|OP_THROW; } else if (playeroptype == OP_CALL || playeroptype == OP_RASE) { if(this->currRound < 2) player->optype = OP_RASE|OP_CALL|OP_THROW; else player->optype = OP_ALLIN|OP_RASE|OP_CALL|OP_THROW; } else if (playeroptype == OP_ALLIN) { if(this->currRound < 2) player->optype = OP_RASE|OP_CALL|OP_THROW; else player->optype = OP_ALLIN|OP_RASE|OP_CALL|OP_THROW; } else if (playeroptype == OP_THROW) { if(this->currMaxCoin != 0) { if(this->currRound < 2) player->optype = OP_RASE|OP_CALL|OP_THROW; else player->optype = OP_ALLIN|OP_RASE|OP_CALL|OP_THROW; } else { if(this->currRound < 2) player->optype = OP_CHECK|OP_RASE|OP_THROW; else player->optype = OP_CHECK|OP_ALLIN|OP_RASE|OP_THROW; } } if(this->currMaxCoin == this->maxbetcoin) //当已经到达下注上限则直接把加注的操作类型给去除 player->optype &= 0xFD; if((player->carrycoin - player->betCoinList[0] + player->betCoinList[this->currRound]) < this->currMaxCoin) { //当自己身上携带的钱已经不足以跟注的钱了,则只有allin和弃牌选项 player->optype = OP_ALLIN|OP_THROW; } } Player* Table::getNextBetPlayer(Player* player, short playeroptype) { if(player == NULL) return NULL; //说明此用户已经有操作行为 if(this->currRound != 1) player->timeoutCount = 0; //当前这轮此用户已经下注 player->thisroundhasbet = true; for(int i = 1; i < GAME_PLAYER; ++i) { int player_index = (player->tab_index+i)%GAME_PLAYER; Player* otherplayer = this->player_array[player_index]; if(otherplayer && otherplayer->id != player->id && otherplayer->isActive() && otherplayer->hascard) { //当前已经轮到的用户就是加注用户 if(otherplayer->id == raseUid) return NULL; //是第五轮则说明是在给用户开牌和弃牌两种选项 if(this->currRound == 5) { //当前这个用户这轮已经选择则继续判断下一个用户 if(otherplayer->thisroundhasbet) continue; betUid = otherplayer->id; otherplayer->optype = OP_THROW | OP_CHECK; return otherplayer; } //当前这轮都还没有下过注,并且没有allin if(!otherplayer->thisroundhasbet && !otherplayer->hasallin) { //设置当前用户为将要下注的用户 betUid = otherplayer->id; setPlayerOptype(otherplayer, playeroptype); return otherplayer; } //说明下一个用户已经ALLIN了 if(otherplayer->hasallin) continue; int nextplayerbetcoin = otherplayer->betCoinList[this->currRound]; int thisplayerbetcoin = player->betCoinList[this->currRound]; if((currMaxCoin == 0)&&(nextplayerbetcoin == thisplayerbetcoin)) return NULL; //解决加注的人离开游戏,这轮一直不结束的bug if(otherplayer->thisroundhasbet && player->thisroundhasbet) { if(nextplayerbetcoin == thisplayerbetcoin && currMaxCoin == nextplayerbetcoin) return NULL; } //设置当前用户为将要下注的用户 betUid = otherplayer->id; //if(otherplayer->carrycoin - otherplayer->betCoinList[0] + otherplayer->betCoinList[this->currRound] <= this->currMaxCoin) //{ // otherplayer->optype = OP_ALLIN|OP_THROW; //} //else //{ setPlayerOptype(otherplayer, playeroptype); //} return otherplayer; } } return NULL; } short Table::getCanPlayNum() { short num = 0; for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->isActive() && player->hascard && !player->hasallin) num++; } return num; } int64_t Table::getSecondLargeCoin() { int64_t firstcoin, secondcoin; firstcoin = secondcoin = 0; int i; int maxindex = -1; for(i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->isActive() && player->hascard) { if(player->carrycoin - player->betCoinList[0] > firstcoin) { maxindex = i; firstcoin = player->carrycoin - player->betCoinList[0]; //_LOG_DEBUG_("id:%d firstcoin:%ld i:%d\n", player->id, firstcoin, i); } } } for(i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->isActive() && player->hascard && i != maxindex) { if(player->carrycoin - player->betCoinList[0] > secondcoin) { secondcoin = player->carrycoin - player->betCoinList[0]; //_LOG_DEBUG_("id:%d secondcoin:%ld i:%d\n", player->id, secondcoin, i); } } } return secondcoin; } void Table::setMaxBetCoin() { int64_t secondLargeCoin = getSecondLargeCoin(); //_LOG_DEBUG_("=======secondLargeCoin:%d=======\n", secondLargeCoin); //设置第一轮下注的最大数值 if(this->currRound == 0) { int64_t confcoin= Configure::getInstance()->maxmulone * this->ante; this->maxbetcoin = confcoin < secondLargeCoin ? confcoin : secondLargeCoin; } //当是第一轮下注完毕,则第二轮是按照第一轮下注的数量定第二轮下注上限 /*else if(this->currRound == 1) { int64_t confcoin= (Configure::getInstance()->maxmulone + Configure::getInstance()->maxmultwo)* this->ante - this->currMaxCoin; this->maxbetcoin = confcoin < secondLargeCoin ? confcoin : secondLargeCoin; }*/ //否则没有上限 else { this->maxbetcoin = secondLargeCoin; } } Player* Table::getPreWinner() { Player* prewinner = NULL; //如果是第五轮则设置前一个赢牌用户为牌面上的四个明牌大的人 if(this->currRound == 5) prewinner = this->deduceWiner(1,4); else if(this->currRound == 0) prewinner = this->deduceWiner(1,1); else prewinner = this->deduceWiner(1,this->currRound); return prewinner; } Player* Table::getCurrWinner() { Player* winner = NULL; //第六轮才是亮底牌的时候 if(this->currRound == 6) { winner = this->deduceWiner(0,4); } else { if(this->currRound == 5) winner = this->deduceWiner(1,4); else winner = this->deduceWiner(1,this->currRound); } return winner; } Player* Table::getFirstBetPlayer(Player* winner) { Player* firstBetPlayer = NULL; if(this->currRound < 5) { //如果当前最大牌的那个人已经allin了 if(winner->hasallin) { for(int j = 1; j < GAME_PLAYER; ++j) { short nextindex = (winner->tab_index + j) % GAME_PLAYER; if(player_array[nextindex] && player_array[nextindex]->isActive() && !player_array[nextindex]->hasallin && player_array[nextindex]->hascard) { firstBetPlayer = player_array[nextindex]; break; } } } if(firstBetPlayer == NULL) firstBetPlayer = winner; //前两轮用户可以选择加注但是不能梭哈 if(this->currRound <= 1) firstBetPlayer->optype = OP_RASE|OP_CHECK|OP_THROW; else firstBetPlayer->optype = OP_RASE|OP_ALLIN|OP_CHECK|OP_THROW; } else if(this->currRound == 5) { firstBetPlayer = winner; firstBetPlayer->optype = OP_THROW|OP_CHECK; } else { firstBetPlayer = winner; firstBetPlayer->optype = 0; } return firstBetPlayer; } bool Table::hasSomeOneAllin() { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && player->isActive() && player->hascard && player->hasallin) return true; } return false; } int Table::setNextRound() { this->stopBetCoinTimer(); if(!hassendcard && this->currRound > 1) { hassendcard = true; this->startSendCardTimer(1500); return 0; } hassendcard = false; this->setMaxBetCoin(); Player* prewinner = getPreWinner(); this->currRound++; Player* winner = getCurrWinner(); if(winner == NULL) { _LOG_ERROR_("Can't Get Winner tid[%d]\n",this->id); return -1; } Player* firstBetPlayer = getFirstBetPlayer(winner); //得到较小的那个能下注的数目 setPlayerlimitcoin(firstBetPlayer); short activeCount = this->getCanPlayNum(); //如果可以下注的人只有一个人的时候这个桌子的操作类型为0 if(activeCount < 2 && this->currRound < 5) firstBetPlayer->optype = 0; this->startBetCoinTimer(firstBetPlayer->id, Configure::getInstance()->betcointime); firstBetPlayer->setBetCoinTime(time(NULL)); //如果当前是第五轮了而第四轮大家都是看牌过来的,则直接跳过第五轮,转到第六轮结束游戏 if(this->currRound == 5 && this->currMaxCoin == 0 && !this->hasSomeOneAllin()) { this->currRound++; firstBetPlayer->optype = 0; } //当前加注的用户和下注的用户都设置为第一轮开始下注的人 this->raseUid = this->betUid = firstBetPlayer->id; this->currMaxCoin = 0; int sendNum = 0; for(int i = 0; i < GAME_PLAYER; ++i) { if(sendNum == this->countPlayer) break; Player* getplayer = this->player_array[i]; if(getplayer) { getplayer->thisroundhasbet = false;//发牌的时候把所用用户当前轮是否下注置为否 IProcess::sendRoundCard(getplayer, this, firstBetPlayer, prewinner, this->currRound); sendNum++; } } if(this->currRound == 6) return IProcess::GameOver(this, winner); //当第一个下注用户操作类型为空的时候直接发下一轮的牌 if(firstBetPlayer->optype == 0) return setNextRound(); } short Table::GetPlayerCardKind(BYTE bPlayerCardList[], BYTE bBeginPos, BYTE bEndPos) { BYTE bPlayerCardArray[5]; memcpy(bPlayerCardArray,bPlayerCardList,sizeof(bPlayerCardList)); m_GameLogic.SortCard(bPlayerCardArray + bBeginPos,bEndPos - bBeginPos + 1); return m_GameLogic.GetCardKind(bPlayerCardArray + bBeginPos,bEndPos - bBeginPos + 1); } //推断胜者 Player* Table::deduceWiner(BYTE bBeginPos, BYTE bEndPos) { if(this->countPlayer <= 0) return NULL; //保存扑克 BYTE bTableCardArray[GAME_PLAYER][5]; memcpy(bTableCardArray,m_bTableCardArray,sizeof(m_bTableCardArray)); BYTE bWiner = 0; //寻找玩家 for (bWiner=0;bWiner<GAME_PLAYER;bWiner++) { Player* player = player_array[bWiner]; if (player && player->hascard) break; } //对比玩家 for (BYTE i=(bWiner+1);i<GAME_PLAYER;i++) { Player* player = player_array[i]; if (player == NULL) continue; if (!player->hascard) continue; if (m_GameLogic.CompareCard(bTableCardArray[i]+bBeginPos,bTableCardArray[bWiner]+bBeginPos,bEndPos-bBeginPos+1)==true) bWiner=i; } //说明所有人手上都没有牌了 if(bWiner == GAME_PLAYER) return NULL; return player_array[bWiner]; } //推断胜者的顺序,用于传回给前端 Player* Table::deduceWinerOrder(BYTE bBeginPos, BYTE bEndPos) { if(this->countPlayer <= 0) return NULL; //保存扑克 BYTE bTableCardArray[GAME_PLAYER][5]; memcpy(bTableCardArray,m_bTableCardArray,sizeof(m_bTableCardArray)); BYTE bWiner = 0; //寻找玩家 for (bWiner=0;bWiner<GAME_PLAYER;bWiner++) { Player* player = player_array[bWiner]; //是否已经有序了 if (player && player->hascard && !player->isorder) break; } //对比玩家 for (BYTE i=(bWiner+1);i<GAME_PLAYER;i++) { Player* player = player_array[i]; if (player == NULL) continue; if (!player->hascard) continue; //是否已经有序了 if (player->isorder) continue; if (m_GameLogic.CompareCard(bTableCardArray[i]+bBeginPos,bTableCardArray[bWiner]+bBeginPos,bEndPos-bBeginPos+1)==true) bWiner=i; } return player_array[bWiner]; } int Table::gameOver(Player* winner, bool bisthrowwin) { if(winner == NULL) { _LOG_ERROR_("[gameOver] winner id is NULL\n"); return -1; } //判断是否是对手都弃牌了他赢得这局 if(bisthrowwin) this->isthrowwin = true; this->stopBetCoinTimer(); //设置上一盘赢牌的用户 pregame_winner = winner; int i = 0; this->calcWinnerOrder(); for(i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; //说明这个人还在桌子里面,只是弃牌了而已,把其加入赢钱列表 if(player && player->isActive() && !player->hascard) { winnerorder[winnercount++] = player->id; } } for(i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && player->isActive()) { player->status = STATUS_PLAYER_OVER; AllocSvrConnect::getInstance()->userUpdateStatus(player, STATUS_PLAYER_OVER); player->startnum++; //结束的时候把此用户最终手牌类型算出来 if(player->hascard) { //只有真的是走到第六轮的时候才会计算此用户的最终牌型 if(this->currRound == 6) player->finalcardvalue = this->GetPlayerCardKind(player->card_array, 0, 4); else player->finalcardvalue = -1; } } } this->status = STATUS_TABLE_OVER; this->setEndTime(time(NULL)); AllocSvrConnect::getInstance()->updateTableStatus(this); this->calcCoin(winner); _LOG_INFO_("[gameOver] gameid[%s]\n", this->getGameID()); this->startKickTimer(Configure::getInstance()->kicktime); return 0; } void Table::calcWinnerOrder() { int i = 0; while(1) { bool iscanbreak = true; for(i = 0; i< GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && player->hascard && !player->isorder) { iscanbreak = false; break; } } if(iscanbreak) break; Player *winner = deduceWinerOrder(0,4); winner->isorder = true; winnerorder[winnercount++] = winner->id; } } int Table::calcCoin(Player *gamewinner) { int64_t tempLeveCoin = this->commonCoin; //离开输牌的金币数给赢牌的那一个人 if(gamewinner->carrycoin >= tempLeveCoin) { gamewinner->finalgetCoin += this->commonCoin; tempLeveCoin = 0; } else { gamewinner->finalgetCoin += gamewinner->carrycoin; tempLeveCoin -= gamewinner->carrycoin; } int i = 0; while(1) { Player *winner = this->deduceWiner(0,4); if(winner == NULL) break; //前面已经给这个玩家加钱了,这里不能重复操作 if(gamewinner->id != winner->id) { if(tempLeveCoin > 0) { if(winner->betCoinList[0] >= tempLeveCoin) { winner->finalgetCoin += tempLeveCoin; tempLeveCoin = 0; } else { winner->finalgetCoin += winner->betCoinList[0]; tempLeveCoin -= winner->betCoinList[0]; } } } for(i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && player->id != winner->id && player->betCoinList[0] != 0) { //结算完一个用户就把手牌设置为无状态 if(player->betCoinList[0] <= winner->betCoinList[0]) { winner->finalgetCoin += player->betCoinList[0]; player->finalgetCoin -= player->betCoinList[0]; player->betCoinList[0] = 0; //_LOG_DEBUG_("+++++winner:%d winnerbetcountcoin:%ld player:%d playerbetcountcoin:%ld winnerfinalgetcoin:%ld\n", // winner->id, winner->betCoinList[0], player->id, player->betCoinList[0], winner->finalgetCoin); //当已经计算完此用户的金币则把其手牌也置为false player->hascard = false; } //说明此人金币没有完全被最大牌的用户赢光 else { winner->finalgetCoin += winner->betCoinList[0]; player->finalgetCoin -= winner->betCoinList[0]; player->betCoinList[0] -= winner->betCoinList[0]; //_LOG_DEBUG_("winner:%d winnerbetcountcoin:%ld player:%d playerbetcountcoin:%ld winnerfinalgetcoin:%ld\n", // winner->id, winner->betCoinList[0], player->id, player->betCoinList[0], winner->finalgetCoin); } } } //把最大牌赢的用户也设置为没牌状态,并且把他下注的钱也清空 winner->hascard = false; winner->betCoinList[0] = 0; } for(i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && player->finalgetCoin > 0) { Util::taxDeduction(player->finalgetCoin, this->tax, player->deducte_tax); if (E_MSG_SOURCE_ROBOT == player->source) { int64_t lRobotWin = player->finalgetCoin + player->deducte_tax; if (!OperationRedis::getInstance()->AddRobotWin(player->pid, Configure::getInstance()->server_id, (int)lRobotWin)) LOGGER(E_LOG_DEBUG) << "OperationRedis::AddRobotWin Error, pid=" << player->pid << ", server_id=" << Configure::getInstance()->server_id << ", win=" << lRobotWin; } else { LOGGER(E_LOG_INFO) << "player = " << player->id << " is winner, cal tax now = " << this->tax << " final get coin = " << player->finalgetCoin; if (!OperationRedis::getInstance()->UpdateTaxRank(player->pid, Configure::getInstance()->server_id, GAME_ID, Configure::getInstance()->level, player->tid, player->id, player->deducte_tax)) LOGGER(E_LOG_DEBUG) << "OperationRedis::GenerateTip Error, pid=" << player->pid << ", server_id=" << Configure::getInstance()->server_id << ", gameid=" << GAME_ID << ", level=" << Configure::getInstance()->level << ", id=" << player->id << ", Tax=" << player->deducte_tax; } } } if (tempLeveCoin > 0) { _LOG_INFO_("Confiscated Coin tempLeveCoin[%ld] gameid[%s]\n", tempLeveCoin, this->getGameID()); } return 0; } void Table::reSetInfo() { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player) player->reset(); } this->reset(); } void Table::setKickTimer() { if(this->isActive() || this->countPlayer <= 1) return; this->startKickTimer(Configure::getInstance()->kicktime); this->lockTable(); for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = this->player_array[i]; if(player && (!player->isActive() || !player->isReady())&& player->startnum == 1) { IProcess::serverWarnPlayerKick(this, player, Configure::getInstance()->kicktime - 2); } } } //================时间操作函数========================= void Table::stopAllTimer() { this->timer.stopAllTimer(); } void Table::startBetCoinTimer(int uid,int timeout) { _LOG_DEBUG_("=====uid:%d====[startBetCoinTimer]\n", uid); timer.startBetCoinTimer(uid,timeout); } void Table::stopBetCoinTimer() { _LOG_DEBUG_("=========[stopBetCoinTimer]\n"); timer.stopBetCoinTimer(); } void Table::startTableStartTimer(int timeout) { _LOG_DEBUG_("=========[startTableStartTimer]\n"); timer.startTableStartTimer(timeout); } void Table::stopTableStartTimer() { _LOG_DEBUG_("=========[stopTableStartTimer]\n"); timer.stopTableStartTimer(); } void Table::startKickTimer(int timeout) { _LOG_DEBUG_("=========[startKickTimer]\n"); timer.startKickTimer(timeout); } void Table::stopKickTimer() { _LOG_DEBUG_("=========[stopKickTimer]\n"); timer.stopKickTimer(); } void Table::startSendCardTimer(int timeout) { _LOG_DEBUG_("=========[startSendCardTimer]\n"); timer.startSendCardTimer(timeout); } void Table::stopSendCardTimer() { _LOG_DEBUG_("=========[stopSendCardTimer]\n"); timer.stopSendCardTimer(); }
#ifndef _manager_h_ #define _manager_h_ #include "window.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> class Manager : public Window { public: Manager(); GLFWwindow* window; static bool showQuads; private: static bool drawQuads(); static bool drawCube(); protected: virtual void loop(); void exit(); }; #endif
// Created on: 1997-05-14 // Created by: Christian CAILLET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _XSControl_Reader_HeaderFile #define _XSControl_Reader_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColStd_SequenceOfTransient.hxx> #include <TopTools_SequenceOfShape.hxx> #include <Standard_CString.hxx> #include <IFSelect_ReturnStatus.hxx> #include <TColStd_HSequenceOfTransient.hxx> #include <Standard_Integer.hxx> #include <IFSelect_PrintCount.hxx> #include <Message_ProgressRange.hxx> class XSControl_WorkSession; class Interface_InterfaceModel; class Standard_Transient; class TopoDS_Shape; //! A groundwork to convert a shape to data which complies //! with a particular norm. This data can be that of a whole //! model or that of a specific list of entities in the model. //! You specify the list using a single selection or a //! combination of selections. A selection is an operator which //! computes a list of entities from a list given in input. To //! specify the input, you can use: //! - A predefined selection such as "xst-transferrable-roots" //! - A filter based on a signature. //! A signature is an operator which returns a string from an //! entity according to its type. //! For example: //! - "xst-type" (CDL) //! - "iges-level" //! - "step-type". //! A filter can be based on a signature by giving a value to //! be matched by the string returned. For example, //! "xst-type(Curve)". //! If no list is specified, the selection computes its list of //! entities from the whole model. To use this class, you have to //! initialize the transfer norm first, as shown in the example below. //! Example: //! Control_Reader reader; //! IFSelect_ReturnStatus status = reader.ReadFile (filename.); //! When using IGESControl_Reader or STEPControl_Reader - as the //! above example shows - the reader initializes the norm directly. //! Note that loading the file only stores the data. It does //! not translate this data. Shapes are accumulated by //! successive transfers. The last shape is cleared by: //! - ClearShapes which allows you to handle a new batch //! - TransferRoots which restarts the list of shapes from scratch. class XSControl_Reader { public: DEFINE_STANDARD_ALLOC //! Creates a Reader from scratch (creates an empty WorkSession) //! A WorkSession or a Controller must be provided before running Standard_EXPORT XSControl_Reader(); //! Creates a Reader from scratch, with a norm name which //! identifies a Controller Standard_EXPORT XSControl_Reader(const Standard_CString norm); //! Creates a Reader from an already existing Session, with a //! Controller already set //! Virtual destructor Standard_EXPORT XSControl_Reader(const Handle(XSControl_WorkSession)& WS, const Standard_Boolean scratch = Standard_True); //! Empty virtual destructor virtual ~XSControl_Reader() {} //! Sets a specific norm to <me> //! Returns True if done, False if <norm> is not available Standard_EXPORT Standard_Boolean SetNorm (const Standard_CString norm); //! Sets a specific session to <me> Standard_EXPORT void SetWS (const Handle(XSControl_WorkSession)& WS, const Standard_Boolean scratch = Standard_True); //! Returns the session used in <me> Standard_EXPORT Handle(XSControl_WorkSession) WS() const; //! Loads a file and returns the read status //! Zero for a Model which compies with the Controller Standard_EXPORT IFSelect_ReturnStatus ReadFile (const Standard_CString filename); //! Loads a file from stream and returns the read status Standard_EXPORT IFSelect_ReturnStatus ReadStream(const Standard_CString theName, std::istream& theIStream); //! Returns the model. It can then be consulted (header, product) Standard_EXPORT Handle(Interface_InterfaceModel) Model() const; //! Returns a list of entities from the IGES or STEP file //! according to the following rules: //! - if first and second are empty strings, the whole file is selected. //! - if first is an entity number or label, the entity referred to is selected. //! - if first is a list of entity numbers/labels separated by commas, the entities referred to are selected, //! - if first is the name of a selection in the worksession and second is not defined, //! the list contains the standard output for that selection. //! - if first is the name of a selection and second is defined, the criterion defined //! by second is applied to the result of the first selection. //! A selection is an operator which computes a list of entities from a list given in //! input according to its type. If no list is specified, the selection computes its //! list of entities from the whole model. //! A selection can be: //! - A predefined selection (xst-transferrable-mode) //! - A filter based on a signature //! A Signature is an operator which returns a string from an entity according to its type. For example: //! - "xst-type" (CDL) //! - "iges-level" //! - "step-type". //! For example, if you wanted to select only the advanced_faces in a STEP file you //! would use the following code: //! Example //! Reader.GiveList("xst-transferrable-roots","step-type(ADVANCED_FACE)"); //! Warning //! If the value given to second is incorrect, it will simply be ignored. Standard_EXPORT Handle(TColStd_HSequenceOfTransient) GiveList (const Standard_CString first = "", const Standard_CString second = ""); //! Computes a List of entities from the model as follows //! <first> being a Selection, <ent> being an entity or a list //! of entities (as a HSequenceOfTransient) : //! the standard result of this selection applied to this list //! if <first> is erroneous, a null handle is returned Standard_EXPORT Handle(TColStd_HSequenceOfTransient) GiveList (const Standard_CString first, const Handle(Standard_Transient)& ent); //! Determines the list of root entities which are candidate for //! a transfer to a Shape, and returns the number //! of entities in the list Standard_EXPORT virtual Standard_Integer NbRootsForTransfer(); //! Returns an IGES or STEP root //! entity for translation. The entity is identified by its //! rank in a list. Standard_EXPORT Handle(Standard_Transient) RootForTransfer (const Standard_Integer num = 1); //! Translates a root identified by the rank num in the model. //! false is returned if no shape is produced. Standard_EXPORT Standard_Boolean TransferOneRoot (const Standard_Integer num = 1, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Translates an IGES or STEP //! entity identified by the rank num in the model. //! false is returned if no shape is produced. Standard_EXPORT Standard_Boolean TransferOne (const Standard_Integer num, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Translates an IGES or STEP //! entity in the model. true is returned if a shape is //! produced; otherwise, false is returned. Standard_EXPORT Standard_Boolean TransferEntity (const Handle(Standard_Transient)& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Translates a list of entities. //! Returns the number of IGES or STEP entities that were //! successfully translated. The list can be produced with GiveList. //! Warning - This function does not clear the existing output shapes. Standard_EXPORT Standard_Integer TransferList (const Handle(TColStd_HSequenceOfTransient)& list, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Translates all translatable //! roots and returns the number of successful translations. //! Warning - This function clears existing output shapes first. Standard_EXPORT Standard_Integer TransferRoots(const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Clears the list of shapes that //! may have accumulated in calls to TransferOne or TransferRoot.C Standard_EXPORT void ClearShapes(); //! Returns the number of shapes produced by translation. Standard_EXPORT Standard_Integer NbShapes() const; //! Returns the shape resulting //! from a translation and identified by the rank num. //! num equals 1 by default. In other words, the first shape //! resulting from the translation is returned. Standard_EXPORT TopoDS_Shape Shape (const Standard_Integer num = 1) const; //! Returns all of the results in //! a single shape which is: //! - a null shape if there are no results, //! - a shape if there is one result, //! - a compound containing the resulting shapes if there are more than one. Standard_EXPORT TopoDS_Shape OneShape() const; //! Prints the check list attached to loaded data, on the Standard //! Trace File (starts at std::cout) //! All messages or fails only, according to <failsonly> //! mode = 0 : per entity, prints messages //! mode = 1 : per message, just gives count of entities per check //! mode = 2 : also gives entity numbers Standard_EXPORT void PrintCheckLoad (const Standard_Boolean failsonly, const IFSelect_PrintCount mode) const; //! Prints the check list attached to loaded data. Standard_EXPORT void PrintCheckLoad (Standard_OStream& theStream, const Standard_Boolean failsonly, const IFSelect_PrintCount mode) const; //! Displays check results for the //! last translation of IGES or STEP entities to Open CASCADE //! entities. Only fail messages are displayed if failsonly is //! true. All messages are displayed if failsonly is //! false. mode determines the contents and the order of the //! messages according to the terms of the IFSelect_PrintCount enumeration. Standard_EXPORT void PrintCheckTransfer (const Standard_Boolean failsonly, const IFSelect_PrintCount mode) const; //! Displays check results for the last translation of IGES or STEP entities to Open CASCADE entities. Standard_EXPORT void PrintCheckTransfer (Standard_OStream& theStream, const Standard_Boolean failsonly, const IFSelect_PrintCount mode) const; //! Displays the statistics for //! the last translation. what defines the kind of //! statistics that are displayed as follows: //! - 0 gives general statistics (number of translated roots, //! number of warnings, number of fail messages), //! - 1 gives root results, //! - 2 gives statistics for all checked entities, //! - 3 gives the list of translated entities, //! - 4 gives warning and fail messages, //! - 5 gives fail messages only. //! The use of mode depends on the value of what. If what is 0, //! mode is ignored. If what is 1, 2 or 3, mode defines the following: //! - 0 lists the numbers of IGES or STEP entities in the respective model //! - 1 gives the number, identifier, type and result //! type for each IGES or STEP entity and/or its status //! (fail, warning, etc.) //! - 2 gives maximum information for each IGES or STEP entity (i.e. checks) //! - 3 gives the number of entities per type of IGES or STEP entity //! - 4 gives the number of IGES or STEP entities per result type and/or status //! - 5 gives the number of pairs (IGES or STEP or result type and status) //! - 6 gives the number of pairs (IGES or STEP or result type //! and status) AND the list of entity numbers in the IGES or STEP model. //! If what is 4 or 5, mode defines the warning and fail //! messages as follows: //! - if mode is 0 all warnings and checks per entity are returned //! - if mode is 2 the list of entities per warning is returned. //! If mode is not set, only the list of all entities per warning is given. Standard_EXPORT void PrintStatsTransfer (const Standard_Integer what, const Standard_Integer mode = 0) const; //! Displays the statistics for the last translation. Standard_EXPORT void PrintStatsTransfer (Standard_OStream& theStream, const Standard_Integer what, const Standard_Integer mode = 0) const; //! Gives statistics about Transfer Standard_EXPORT void GetStatsTransfer (const Handle(TColStd_HSequenceOfTransient)& list, Standard_Integer& nbMapped, Standard_Integer& nbWithResult, Standard_Integer& nbWithFail) const; protected: //! Returns a sequence of produced shapes Standard_EXPORT TopTools_SequenceOfShape& Shapes(); Standard_Boolean therootsta; TColStd_SequenceOfTransient theroots; private: Handle(XSControl_WorkSession) thesession; TopTools_SequenceOfShape theshapes; }; #endif // _XSControl_Reader_HeaderFile
// // main.cpp // NeheGL // // Created by Andong Li on 8/28/13. // Copyright (c) 2013 Andong Li. All rights reserved. // entry function of this project // #include "headers.h" //just change here to change renderer #define RENDERER NEHE39 int main(int argc, char * argv[]){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize (640, 480); glutInitWindowPosition (100,100); glutCreateWindow (RENDERER::TITLE); RENDERER::InitGL(); glutDisplayFunc(RENDERER::DrawGLScene); glutReshapeFunc(RENDERER::ReSizeGLScene); glutTimerFunc(0, RENDERER::UpdateScene, 0); //handle keyboard actions glutKeyboardFunc(RENDERER::KeyboardFuction); glutKeyboardUpFunc(RENDERER::KeyboardUpFuction); glutSpecialFunc(RENDERER::KeySpecialFuction); glutSpecialUpFunc(RENDERER::KeySpecialUpFuction); glutMainLoop(); return EXIT_SUCCESS; }
#include "User.h" #include "protocol.h" User::User(LinkID linkID) { mUserType = SceneServer; mLinkID = linkID; mUserID = linkID; } User::~User() { }
// // IntLib.h // Landru // // Created by Nick Porcino on 10/29/14. // // #pragma once #include "LandruActorVM/LandruLibForward.h" namespace Landru { namespace Std { //----------- // Int Libary \__________________________________________ class IntLib { public: static void registerLib(Library& l); static RunState add(FnContext& run); static RunState sub(FnContext& run); static RunState mul(FnContext& run); static RunState div(FnContext& run); static RunState mod(FnContext& run); static RunState min(FnContext& run); static RunState max(FnContext& run); }; } // Std } // Landru
// // Torpedo.cpp // GAME2 // // Created by ruby on 2017. 11. 11.. // Copyright © 2017년 ruby. All rights reserved. // #include "Torpedo.hpp" void Torpedo::move() { moveUp(); }
#include <stdio.h> #include <iostream> #include <string.h> #define TAMANHO 300 using namespace std; FILE *f, *s; int criararquivo (char uf[2]); int fechararquivo (); int main(int argc, char**argv) { cout << "Tamanho dos registros..:" << TAMANHO<<"\n\n"; char registro [TAMANHO]; int qt; int qtest=0; char uf[3]; int r =0; uf[2]='\0'; if(argc != 2) { fprintf(stderr,"Erro na chamada do comando.\n"); fprintf(stderr, "USO: %s .....", argv[0]); return 1; } f = fopen(argv[1],"r"); if(!f) { fprintf(stderr,"Arquivo %s não pode ser aberto para leitura\n", argv[1]); return 1; } qt = fread(registro,TAMANHO,1,f); strncpy(uf,registro+288,2); criararquivo(uf); while(qt > 0) { r++; if(strncmp(uf,registro+288,2)==0) { fwrite(registro,1,TAMANHO,s); qt = fread(registro,TAMANHO,1,f); qtest++; } else { cout << "CEPS Copiados do Estado: "<< uf<<" "<< qtest <<"\n"; strncpy(uf,registro+288,2); r--; qtest=0; criararquivo(uf); } } cout << "Total de Registros Lido: "<< r <<"\n"; fclose(f); fclose(s); } int criararquivo (char uf[2]) { char nome[5]=""; strcat( nome,uf); strcat( nome,".txt"); s = fopen(nome,"w+" ); if(!s) { fprintf(stderr,"Arquivo %s não pode ser aberto para leitura\n", uf); return 0; } return 1 ; } /*int fechararquivo () { if(!fclose(s)) { fprintf(stderr,"Arquivo %s não pode ser fechado\n"); return 0; } return 1 ; } */
// bellman ford algorithm to find single source shortest path in a graph // the graph is assumed to be directed and is stored in the form of a vector of edges // complexity: O(|V|*|E|) ll dist[MAXN]; void check_neg_cycle(vector<pair<ll,pair<int,int>>> edges){ for(auto edge: edges){ if(dist[edge.second.second] > dist[edge.second.first]+edge.first){ cout << "Negative cycle detected!"; return; } } } void bellman_ford(int src,int n, vector<pair<ll,pair<int,int>>> edges){ for(int i = 0; i < n; i++) dist[i] = INF; dist[src] = 0; for(int i = 0; i < n-1; i++){ for(auto edge:edges){ int start = edge.second.first; int end = edge.second.second; ll wt = edge.first; if(dist[end] > dist[start]+wt){ dist[end] = dist[start]+wt; } } } check_neg_cycle(edges); }
#pragma once #include<Windows.h> class Hand { public: Hand(); Hand(int newWinRate, LPCSTR newName); ~Hand(); private: int winRate; LPCSTR name; void checkOrCall(LPCSTR nameOfTheWindow); void fold(LPCSTR nameOfTheWindow); void bet(LPCSTR nameOfTheWindow); };
// Subsequence with the biggest sum%m value O(2^(n/2)*n) int n, m, a[40]; void comb(int l, int r, vi &v){ int sz = r-l+1; for(int i=0;i<(1<<sz);i++){ int sum = 0; for(int j=0;j<sz;j++) if(i & (1<<j)) sum = (sum + a[l+j])%m; v.pb(sum); } sort(v.begin(), v.end()); } int merge(vi &x, vi &y){ int k=y.size()-1, ans=0; for(auto v: x){ while(k>0 and v+y[k]>=m) k--; ans = max(ans, v+y[k]); } return ans; } int main() {sws; vi x, y; cin >> n >> m; for(int i=0;i<n;i++) cin >> a[i]; comb(0, n/2, x); comb(n/2 + 1, n-1, y); cout << merge(x, y) << endl; return 0; }
/* waveread.h文件,用于读取wav文件 包含wavread类,构建对象时需要输入文件路径: wavread wav("/Users/Administrator/Downloads/data1081.wav"); wavread类介绍: 成员函数: 1、echo_info();输出wav文件相关信息 数据成员: 1.info(保存wav文件信息); 2.data(保存音频信息) 对data的特殊说明: 1.data中的数据可能为16bits、8bits,etc.本次实验中的音频使用的均是16bits,所以说嘛以16bits为例,用short存储. 2.最高位为符号位,有没有使用1补码没有确定. 3.使用时,需要进行符号位判断,取得其绝对值,并将其归一化转化为double型 考虑到与MATLAB的数据一致,所以归一化为[-1,+1] symbol=(wav.data[i]&0x8000)?-wav.data[i]^0xffff:wav.data[i]; double_data=symbol/2^15; 代码如上,wav.data[i]&0x8000取符号位,-wav.data[i]^0xffff为按位取反并反转符号。 Ps:至于为什么不用~按位取反,我在Xcode里发现“~”不怎么管用…… */ #ifndef _WAVREAD_H #define _WAVREAD_H #include <fstream> using namespace std; struct wav_info { char file_type[4]; //是否是WAV文件 unsigned int file_size; //文件大小 unsigned int frequency; //采样率 unsigned int bps; //byte率 unsigned short sample_bit; //样本位数 unsigned int data_size; //数据大小 }; class wavread { public: wavread(char *fname) { fstream fs; fs.open(fname,ios::binary|ios::in); if (!fs) { throw 1; } //获取文件大小 fs.seekg(0,ios::end); info.file_size=fs.tellg(); //获取文件类型 fs.seekg(0x08); fs.read(info.file_type,4); if (strncmp(info.file_type,"WAVE",4)) { throw 1; } //Sample rate fs.seekg(0x18); fs.read((char *)&info.frequency,4); //bps fs.seekg(0x1c); fs.read((char *)&info.bps,4); //sample bit fs.seekg(0x22); fs.read((char *)&info.sample_bit,2); //data size fs.seekg(0x28); fs.read((char *)&info.data_size,4); //data data=new unsigned short[info.data_size/2]; //每个数据为2字节,保存在short中 fs.seekg(0x2c); fs.read((char *)data,sizeof(char)*info.data_size); fs.close(); }; ~wavread() { delete [] data; }; void echo_info() { cout << "文件大小为 :" << info.file_size << endl; cout << "采样频率 :" << info.frequency << endl; cout << "Byte率 :" << info.bps << endl; cout << "样本位数 :" << info.sample_bit << endl; cout << "音频数据大小:" << info.data_size << endl; }; wav_info info; unsigned short *data; //数据 }; #endif
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmJsonObjects.h" // IWYU pragma: keep #include <algorithm> #include <cassert> #include <cstddef> #include <functional> #include <limits> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cmext/algorithm> #include "cmGeneratorExpression.h" #include "cmGeneratorTarget.h" #include "cmGlobalGenerator.h" #include "cmInstallGenerator.h" #include "cmInstallSubdirectoryGenerator.h" #include "cmInstallTargetGenerator.h" #include "cmJsonObjectDictionary.h" #include "cmJsonObjects.h" #include "cmLinkLineComputer.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmPropertyMap.h" #include "cmSourceFile.h" #include "cmState.h" #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTest.h" #include "cmake.h" namespace { std::vector<std::string> getConfigurations(const cmake* cm) { std::vector<std::string> configurations; const auto& makefiles = cm->GetGlobalGenerator()->GetMakefiles(); if (makefiles.empty()) { return configurations; } makefiles[0]->GetConfigurations(configurations); if (configurations.empty()) { configurations.emplace_back(); } return configurations; } bool hasString(const Json::Value& v, const std::string& s) { return !v.isNull() && std::any_of(v.begin(), v.end(), [s](const Json::Value& i) { return i.asString() == s; }); } template <class T> Json::Value fromStringList(const T& in) { Json::Value result = Json::arrayValue; for (std::string const& i : in) { result.append(i); } return result; } } // namespace void cmGetCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir, const std::string& buildDir, std::vector<std::string>* internalFiles, std::vector<std::string>* explicitFiles, std::vector<std::string>* tmpFiles) { const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/'; auto const& makefiles = gg->GetMakefiles(); for (const auto& mf : makefiles) { for (std::string const& lf : mf->GetListFiles()) { const std::string startOfFile = lf.substr(0, cmakeRootDir.size()); const bool isInternal = (startOfFile == cmakeRootDir); const bool isTemporary = !isInternal && (lf.find(buildDir + '/') == 0); std::string toAdd = lf; if (!sourceDir.empty()) { const std::string& relative = cmSystemTools::RelativePath(sourceDir, lf); if (toAdd.size() > relative.size()) { toAdd = relative; } } if (isInternal) { if (internalFiles) { internalFiles->push_back(std::move(toAdd)); } } else { if (isTemporary) { if (tmpFiles) { tmpFiles->push_back(std::move(toAdd)); } } else { if (explicitFiles) { explicitFiles->push_back(std::move(toAdd)); } } } } } } Json::Value cmDumpCMakeInputs(const cmake* cm) { const cmGlobalGenerator* gg = cm->GetGlobalGenerator(); const std::string& buildDir = cm->GetHomeOutputDirectory(); const std::string& sourceDir = cm->GetHomeDirectory(); std::vector<std::string> internalFiles; std::vector<std::string> explicitFiles; std::vector<std::string> tmpFiles; cmGetCMakeInputs(gg, sourceDir, buildDir, &internalFiles, &explicitFiles, &tmpFiles); Json::Value array = Json::arrayValue; Json::Value tmp = Json::objectValue; tmp[kIS_CMAKE_KEY] = true; tmp[kIS_TEMPORARY_KEY] = false; tmp[kSOURCES_KEY] = fromStringList(internalFiles); array.append(tmp); tmp = Json::objectValue; tmp[kIS_CMAKE_KEY] = false; tmp[kIS_TEMPORARY_KEY] = false; tmp[kSOURCES_KEY] = fromStringList(explicitFiles); array.append(tmp); tmp = Json::objectValue; tmp[kIS_CMAKE_KEY] = false; tmp[kIS_TEMPORARY_KEY] = true; tmp[kSOURCES_KEY] = fromStringList(tmpFiles); array.append(tmp); return array; } class LanguageData { public: bool operator==(const LanguageData& other) const; void SetDefines(const std::set<std::string>& defines); bool IsGenerated = false; std::string Language; std::string Flags; std::vector<std::string> Defines; std::vector<std::pair<std::string, bool>> IncludePathList; }; bool LanguageData::operator==(const LanguageData& other) const { return Language == other.Language && Defines == other.Defines && Flags == other.Flags && IncludePathList == other.IncludePathList && IsGenerated == other.IsGenerated; } void LanguageData::SetDefines(const std::set<std::string>& defines) { std::vector<std::string> result; result.reserve(defines.size()); for (std::string const& i : defines) { result.push_back(i); } std::sort(result.begin(), result.end()); Defines = std::move(result); } namespace std { template <> struct hash<LanguageData> { std::size_t operator()(const LanguageData& in) const { using std::hash; size_t result = hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags); for (auto const& i : in.IncludePathList) { result = result ^ (hash<std::string>()(i.first) ^ (i.second ? std::numeric_limits<size_t>::max() : 0)); } for (auto const& i : in.Defines) { result = result ^ hash<std::string>()(i); } result = result ^ (in.IsGenerated ? std::numeric_limits<size_t>::max() : 0); return result; } }; } // namespace std static Json::Value DumpSourceFileGroup(const LanguageData& data, const std::vector<std::string>& files, const std::string& baseDir) { Json::Value result = Json::objectValue; if (!data.Language.empty()) { result[kLANGUAGE_KEY] = data.Language; if (!data.Flags.empty()) { result[kCOMPILE_FLAGS_KEY] = data.Flags; } if (!data.IncludePathList.empty()) { Json::Value includes = Json::arrayValue; for (auto const& i : data.IncludePathList) { Json::Value tmp = Json::objectValue; tmp[kPATH_KEY] = i.first; if (i.second) { tmp[kIS_SYSTEM_KEY] = i.second; } includes.append(tmp); } result[kINCLUDE_PATH_KEY] = includes; } if (!data.Defines.empty()) { result[kDEFINES_KEY] = fromStringList(data.Defines); } } result[kIS_GENERATED_KEY] = data.IsGenerated; Json::Value sourcesValue = Json::arrayValue; for (auto const& i : files) { const std::string relPath = cmSystemTools::RelativePath(baseDir, i); sourcesValue.append(relPath.size() < i.size() ? relPath : i); } result[kSOURCES_KEY] = sourcesValue; return result; } static Json::Value DumpSourceFilesList( cmGeneratorTarget* target, const std::string& config, const std::map<std::string, LanguageData>& languageDataMap) { // Collect sourcefile groups: std::vector<cmSourceFile*> files; target->GetSourceFiles(files, config); std::unordered_map<LanguageData, std::vector<std::string>> fileGroups; for (cmSourceFile* file : files) { LanguageData fileData; fileData.Language = file->GetOrDetermineLanguage(); if (!fileData.Language.empty()) { const LanguageData& ld = languageDataMap.at(fileData.Language); cmLocalGenerator* lg = target->GetLocalGenerator(); cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target, fileData.Language); std::string compileFlags = ld.Flags; const std::string COMPILE_FLAGS("COMPILE_FLAGS"); if (const char* cflags = file->GetProperty(COMPILE_FLAGS)) { lg->AppendFlags(compileFlags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS)); } const std::string COMPILE_OPTIONS("COMPILE_OPTIONS"); if (const char* coptions = file->GetProperty(COMPILE_OPTIONS)) { lg->AppendCompileOptions( compileFlags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS)); } fileData.Flags = compileFlags; // Add include directories from source file properties. std::vector<std::string> includes; const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES"); if (const char* cincludes = file->GetProperty(INCLUDE_DIRECTORIES)) { const std::string& evaluatedIncludes = genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES); lg->AppendIncludeDirectories(includes, evaluatedIncludes, *file); for (const auto& include : includes) { fileData.IncludePathList.emplace_back( include, target->IsSystemIncludeDirectory(include, config, fileData.Language)); } } fileData.IncludePathList.insert(fileData.IncludePathList.end(), ld.IncludePathList.begin(), ld.IncludePathList.end()); const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS"); std::set<std::string> defines; if (const char* defs = file->GetProperty(COMPILE_DEFINITIONS)) { lg->AppendDefines( defines, genexInterpreter.Evaluate(defs, COMPILE_DEFINITIONS)); } const std::string defPropName = "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config); if (const char* config_defs = file->GetProperty(defPropName)) { lg->AppendDefines( defines, genexInterpreter.Evaluate(config_defs, COMPILE_DEFINITIONS)); } defines.insert(ld.Defines.begin(), ld.Defines.end()); fileData.SetDefines(defines); } fileData.IsGenerated = file->GetIsGenerated(); std::vector<std::string>& groupFileList = fileGroups[fileData]; groupFileList.push_back(file->ResolveFullPath()); } const std::string& baseDir = target->Makefile->GetCurrentSourceDirectory(); Json::Value result = Json::arrayValue; for (auto const& it : fileGroups) { Json::Value group = DumpSourceFileGroup(it.first, it.second, baseDir); if (!group.isNull()) { result.append(group); } } return result; } static Json::Value DumpCTestInfo(cmLocalGenerator* lg, cmTest* testInfo, const std::string& config) { Json::Value result = Json::objectValue; result[kCTEST_NAME] = testInfo->GetName(); // Concat command entries together. After the first should be the arguments // for the command std::string command; for (auto const& cmd : testInfo->GetCommand()) { command.append(cmd); command.append(" "); } // Remove any config specific variables from the output. result[kCTEST_COMMAND] = cmGeneratorExpression::Evaluate(command, lg, config); // Build up the list of properties that may have been specified Json::Value properties = Json::arrayValue; for (auto& prop : testInfo->GetProperties().GetList()) { Json::Value entry = Json::objectValue; entry[kKEY_KEY] = prop.first; // Remove config variables from the value too. entry[kVALUE_KEY] = cmGeneratorExpression::Evaluate(prop.second, lg, config); properties.append(entry); } result[kPROPERTIES_KEY] = properties; return result; } static void DumpMakefileTests(cmLocalGenerator* lg, const std::string& config, Json::Value* result) { auto mf = lg->GetMakefile(); std::vector<cmTest*> tests; mf->GetTests(config, tests); for (auto test : tests) { Json::Value tmp = DumpCTestInfo(lg, test, config); if (!tmp.isNull()) { result->append(tmp); } } } static Json::Value DumpCTestProjectList(const cmake* cm, std::string const& config) { Json::Value result = Json::arrayValue; auto globalGen = cm->GetGlobalGenerator(); for (const auto& projectIt : globalGen->GetProjectMap()) { Json::Value pObj = Json::objectValue; pObj[kNAME_KEY] = projectIt.first; Json::Value tests = Json::arrayValue; // Gather tests for every generator for (const auto& lg : projectIt.second) { // Make sure they're generated. lg->GenerateTestFiles(); DumpMakefileTests(lg, config, &tests); } pObj[kCTEST_INFO] = tests; result.append(pObj); } return result; } static Json::Value DumpCTestConfiguration(const cmake* cm, const std::string& config) { Json::Value result = Json::objectValue; result[kNAME_KEY] = config; result[kPROJECTS_KEY] = DumpCTestProjectList(cm, config); return result; } static Json::Value DumpCTestConfigurationsList(const cmake* cm) { Json::Value result = Json::arrayValue; for (const std::string& c : getConfigurations(cm)) { result.append(DumpCTestConfiguration(cm, c)); } return result; } Json::Value cmDumpCTestInfo(const cmake* cm) { Json::Value result = Json::objectValue; result[kCONFIGURATIONS_KEY] = DumpCTestConfigurationsList(cm); return result; } static Json::Value DumpTarget(cmGeneratorTarget* target, const std::string& config) { cmLocalGenerator* lg = target->GetLocalGenerator(); const cmStateEnums::TargetType type = target->GetType(); const std::string typeName = cmState::GetTargetTypeName(type); Json::Value ttl = Json::arrayValue; ttl.append("EXECUTABLE"); ttl.append("STATIC_LIBRARY"); ttl.append("SHARED_LIBRARY"); ttl.append("MODULE_LIBRARY"); ttl.append("OBJECT_LIBRARY"); ttl.append("UTILITY"); ttl.append("INTERFACE_LIBRARY"); if (!hasString(ttl, typeName) || target->IsImported()) { return Json::Value(); } Json::Value result = Json::objectValue; result[kNAME_KEY] = target->GetName(); result[kIS_GENERATOR_PROVIDED_KEY] = target->Target->GetIsGeneratorProvided(); result[kTYPE_KEY] = typeName; result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory(); result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory(); if (type == cmStateEnums::INTERFACE_LIBRARY) { return result; } result[kFULL_NAME_KEY] = target->GetFullName(config); if (target->Target->GetHaveInstallRule()) { result[kHAS_INSTALL_RULE] = true; Json::Value installPaths = Json::arrayValue; for (const auto& installGenerator : target->Makefile->GetInstallGenerators()) { auto installTargetGenerator = dynamic_cast<cmInstallTargetGenerator*>(installGenerator.get()); if (installTargetGenerator != nullptr && installTargetGenerator->GetTarget()->Target == target->Target) { auto dest = installTargetGenerator->GetDestination(config); std::string installPath; if (!dest.empty() && cmSystemTools::FileIsFullPath(dest)) { installPath = dest; } else { installPath = cmStrCat( target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX"), '/', dest); } installPaths.append(installPath); } } result[kINSTALL_PATHS] = installPaths; } if (target->HaveWellDefinedOutputFiles()) { Json::Value artifacts = Json::arrayValue; artifacts.append( target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact)); if (target->HasImportLibrary(config)) { artifacts.append( target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact)); } if (target->IsDLLPlatform()) { const cmGeneratorTarget::OutputInfo* output = target->GetOutputInfo(config); if (output && !output->PdbDir.empty()) { artifacts.append(output->PdbDir + '/' + target->GetPDBName(config)); } } result[kARTIFACTS_KEY] = artifacts; result[kLINKER_LANGUAGE_KEY] = target->GetLinkerLanguage(config); std::string linkLibs; std::string linkFlags; std::string linkLanguageFlags; std::string frameworkPath; std::string linkPath; cmLinkLineComputer linkLineComputer(lg, lg->GetStateSnapshot().GetDirectory()); lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags, linkFlags, frameworkPath, linkPath, target); linkLibs = cmTrimWhitespace(linkLibs); linkFlags = cmTrimWhitespace(linkFlags); linkLanguageFlags = cmTrimWhitespace(linkLanguageFlags); frameworkPath = cmTrimWhitespace(frameworkPath); linkPath = cmTrimWhitespace(linkPath); if (!cmTrimWhitespace(linkLibs).empty()) { result[kLINK_LIBRARIES_KEY] = linkLibs; } if (!cmTrimWhitespace(linkFlags).empty()) { result[kLINK_FLAGS_KEY] = linkFlags; } if (!cmTrimWhitespace(linkLanguageFlags).empty()) { result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags; } if (!frameworkPath.empty()) { result[kFRAMEWORK_PATH_KEY] = frameworkPath; } if (!linkPath.empty()) { result[kLINK_PATH_KEY] = linkPath; } const std::string sysroot = lg->GetMakefile()->GetSafeDefinition("CMAKE_SYSROOT"); if (!sysroot.empty()) { result[kSYSROOT_KEY] = sysroot; } } std::set<std::string> languages; target->GetLanguages(languages, config); std::map<std::string, LanguageData> languageDataMap; for (std::string const& lang : languages) { LanguageData& ld = languageDataMap[lang]; ld.Language = lang; lg->GetTargetCompileFlags(target, config, lang, ld.Flags); std::set<std::string> defines; lg->GetTargetDefines(target, config, lang, defines); ld.SetDefines(defines); std::vector<std::string> includePathList; lg->GetIncludeDirectories(includePathList, target, lang, config); for (std::string const& i : includePathList) { ld.IncludePathList.emplace_back( i, target->IsSystemIncludeDirectory(i, config, lang)); } } Json::Value sourceGroupsValue = DumpSourceFilesList(target, config, languageDataMap); if (!sourceGroupsValue.empty()) { result[kFILE_GROUPS_KEY] = sourceGroupsValue; } return result; } static Json::Value DumpTargetsList( const std::vector<cmLocalGenerator*>& generators, const std::string& config) { Json::Value result = Json::arrayValue; std::vector<cmGeneratorTarget*> targetList; for (auto const& lgIt : generators) { cm::append(targetList, lgIt->GetGeneratorTargets()); } std::sort(targetList.begin(), targetList.end()); for (cmGeneratorTarget* target : targetList) { Json::Value tmp = DumpTarget(target, config); if (!tmp.isNull()) { result.append(tmp); } } return result; } static Json::Value DumpProjectList(const cmake* cm, std::string const& config) { Json::Value result = Json::arrayValue; auto globalGen = cm->GetGlobalGenerator(); for (auto const& projectIt : globalGen->GetProjectMap()) { Json::Value pObj = Json::objectValue; pObj[kNAME_KEY] = projectIt.first; // All Projects must have at least one local generator assert(!projectIt.second.empty()); const cmLocalGenerator* lg = projectIt.second.at(0); // Project structure information: const cmMakefile* mf = lg->GetMakefile(); auto minVersion = mf->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION"); pObj[kMINIMUM_CMAKE_VERSION] = minVersion ? minVersion : ""; pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory(); pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory(); pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config); // For a project-level install rule it might be defined in any of its // associated generators. bool hasInstallRule = false; for (const auto generator : projectIt.second) { for (const auto& installGen : generator->GetMakefile()->GetInstallGenerators()) { if (!dynamic_cast<cmInstallSubdirectoryGenerator*>(installGen.get())) { hasInstallRule = true; break; } } if (hasInstallRule) { break; } } pObj[kHAS_INSTALL_RULE] = hasInstallRule; result.append(pObj); } return result; } static Json::Value DumpConfiguration(const cmake* cm, const std::string& config) { Json::Value result = Json::objectValue; result[kNAME_KEY] = config; result[kPROJECTS_KEY] = DumpProjectList(cm, config); return result; } static Json::Value DumpConfigurationsList(const cmake* cm) { Json::Value result = Json::arrayValue; for (std::string const& c : getConfigurations(cm)) { result.append(DumpConfiguration(cm, c)); } return result; } Json::Value cmDumpCodeModel(const cmake* cm) { Json::Value result = Json::objectValue; result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(cm); return result; }
#include <fstream> #include <iostream> #include "../../OCScriptLib/src/OCScript.hpp" class SampleCommand1 : public OCScript::ICommand { public: static SampleCommand1& GetInstance() { static SampleCommand1 instance; return instance; } private: SampleCommand1() { } public: wstring GetCommandName() { return L"SampleCommand1"; } void Access(OCScript::AccessEventArgs *e, vector<wstring> params) { wcout << L"SampleCommand1が呼び出されました" << endl; wcout << L"引数一覧:" << endl; for (auto item : params) wcout << L"- " + item << endl; } void PreUpdate() { wcout << L"SampleCommand1 前更新処理" << endl; } void Update() { wcout << L"SampleCommand1 本更新処理" << endl; } }; class SampleCommand2 : public OCScript::ICommand { public: static SampleCommand2& GetInstance() { static SampleCommand2 instance; return instance; } private: SampleCommand2() { } public: wstring GetCommandName() { return L"SampleCommand2"; } void Access(OCScript::AccessEventArgs *e, vector<wstring> params) { wcout << L"SampleCommand2が呼び出されたよ!" << endl; } void PreUpdate() { wcout << L"SampleCommand2 前更新処理" << endl; } void Update() { wcout << L"SampleCommand2 本更新処理" << endl; } }; int wmain(int argc, wchar_t* argv[]) { _wsetlocale(LC_ALL, L""); if (argc == 2) { OCScript::Core osc; vector<wstring> rawLines; FILE* stream; int openError = _wfopen_s(&stream, argv[1], L"r, ccs=UTF-8"); if (openError == 0 && stream) { while (feof(stream) == 0) { wchar_t str[256]; fgetws(str, sizeof(str), stream); if (ferror(stream) != 0) { fclose(stream); wcerr << L"読み込みに失敗しました" << endl; return -1; } rawLines.push_back(str); } fclose(stream); } else { wcerr << L"ファイルオープンに失敗しました" << endl; return -1; } try { // コマンド登録 osc.AddCommand(&SampleCommand1::GetInstance()); osc.AddCommand(&SampleCommand2::GetInstance()); // スクリプトの読み込み osc.LoadScript(rawLines); while (!osc.IsEndOfScript()) { // 現在の行を実行 osc.ExecuteCurrentLine(); // 更新(描画処理や計算処理などを含む) osc.TriggerPreUpdate(); osc.TriggerUpdate(); } } catch (exception ex) { cerr << ex.what() << endl; return -1; } } return 0; }
// 19.06.01 // 백준 #7562 : 나이트의 이동 // BFS 방식 #include <iostream> #include <queue> #include <utility> using namespace std; int tc; int res[10000]; int dir_x[8]={2,1,-1,-2,-2,-1,1,2}; int dir_y[8]={1,2,2,1,-1,-2,-2,-1}; int length; int cur[2]; int goal[2]; int solve(int x,int y) { int visited[310][310]={0,}; int depth[310][310]={0,}; queue<pair<int,int>> q; pair <int,int> r = make_pair(x,y); q.push(r); while(!q.empty()) { int cur_x=q.front().first; int cur_y=q.front().second; q.pop(); if (cur_x==goal[0] && cur_y==goal[1]) { return depth[goal[0]][goal[1]]; } for(int i=0; i<8; i++) { int nx=cur_x+dir_x[i]; int ny=cur_y+dir_y[i]; if (nx>=0 && nx<length && ny>=0 && ny<length && !visited[nx][ny]) { visited[nx][ny]=1; depth[nx][ny]=depth[cur_x][cur_y]+1; q.push(pair<int,int>(nx,ny)); } } } } int main(void) { cin>>tc; for(int i=0;i<tc;i++) { cin>>length; cin>>cur[0]>>cur[1]; cin>>goal[0]>>goal[1]; res[i]=solve(cur[0],cur[1]); } for(int i=0;i<tc;i++) { cout<<res[i]<<endl; } return 0; }