text
stringlengths
8
6.88M
#ifndef WARLOCKSTATE_H #define WARLOCKSTATE_H #include <iostream> #include <string> #include "SpellCasterState.h" #include "../Specifications.h" class WarlockState : public SpellCasterState { public: WarlockState(const std::string& name, int health = static_cast<int>(HP::WARLOCK), int damage = static_cast<int>(DMG::WARLOCK), int mana = static_cast<int>(MANA::WARLOCK)); virtual ~WarlockState(); }; #endif // WARLOCKSTATE_H
#include "test_lib_1.h" #include <iostream> void test_lib_1() { std::cout << "test_lib_1" << '\n'; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMLANDMARK_HPP_ #define _GDCMIO_DICOMLANDMARK_HPP_ #include <string> #include <vector> #include <fwData/Image.hpp> #include <fwData/macros.hpp> #include "gdcmIO/config.hpp" #include "gdcmIO/DicomSCoord.hpp" namespace gdcmIO { /** * @brief This class define a container of landmarks to translate * in DICOM/FW4SPL form. * * @class DicomLandmark * @author IRCAD (Research and Development Team). * @date 2011. */ class GDCMIO_CLASS_API DicomLandmark { public : GDCMIO_API DicomLandmark(); GDCMIO_API ~DicomLandmark(); /** * \brief Set landmark(s) data in an image. * * \param a_image Image where landmark(s) could be inserted. */ GDCMIO_API void convertToData(::fwData::Image::sptr a_image); /** * \brief Get landmark(s) data from an image and convert it to a closed DICOM form. * * \param a_image Image which can contain landmark(s). */ GDCMIO_API void setFromData(::fwData::Image::csptr a_image) throw (::fwTools::Failed); GDCMIO_API fwGettersSettersDocMacro(Labels, labels, std::vector<std::string>, Labels container (eg : label for each landmark : "Label_1")); GDCMIO_API fwGettersSettersDocMacro(SCoords, SCoords, std::vector<SCoord>, Spatial coordinates container (eg : coordinates on x, y axis)); GDCMIO_API fwGettersSettersDocMacro(RefFrames, refFrames, std::vector<unsigned int>, Slice numbers container (equal to coordinate on z axis)); /** * @brief Add to DicomLandmark the label of one landmark. */ GDCMIO_API void addLabel(const std::string & a_label); /** * @brief Add to DicomLandmark the SCOORD of one landmark. */ GDCMIO_API void addSCoord(const SCoord & a_point); /** * @brief Add to DicomLandmark the referenced frame number of one landmark. */ GDCMIO_API void addRefFrame(const unsigned int a_refFrame); private : std::vector<std::string> m_labels; ///< Labels container (e.g: label for each landmark : "Label_1") std::vector<SCoord> m_SCoords; ///< Coordinates container (equal to coordinates on x, y axis). ///< (e.g: coordinates for each landmark : "175.0,23.5"). std::vector<unsigned int> m_refFrames; ///< Slice numbers container (equal to coordinate on z axis) }; } // namespace gdcmIO #endif /* DICOMLANDMARK_H_ */
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> #include <Uno.UX.Property-1.h> namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct app18_List_Selected_Property;} namespace g{struct List;} namespace g{ // internal sealed class app18_List_Selected_Property :596 // { ::g::Uno::UX::Property1_type* app18_List_Selected_Property_typeof(); void app18_List_Selected_Property__ctor_3_fn(app18_List_Selected_Property* __this, ::g::List* obj, ::g::Uno::UX::Selector* name); void app18_List_Selected_Property__Get1_fn(app18_List_Selected_Property* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval); void app18_List_Selected_Property__New1_fn(::g::List* obj, ::g::Uno::UX::Selector* name, app18_List_Selected_Property** __retval); void app18_List_Selected_Property__get_Object_fn(app18_List_Selected_Property* __this, ::g::Uno::UX::PropertyObject** __retval); void app18_List_Selected_Property__Set1_fn(app18_List_Selected_Property* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin); void app18_List_Selected_Property__get_SupportsOriginSetter_fn(app18_List_Selected_Property* __this, bool* __retval); struct app18_List_Selected_Property : ::g::Uno::UX::Property1 { uWeak< ::g::List*> _obj; void ctor_3(::g::List* obj, ::g::Uno::UX::Selector name); static app18_List_Selected_Property* New1(::g::List* obj, ::g::Uno::UX::Selector name); }; // } } // ::g
#include<cstdio> using namespace std; int main(){ //input int ra,ca; fscanf(stdin,"%d %d",&ra,&ca); int a[ra][ca]; for(int i=0;i<ra;++i){ for(int j=0;j<ca;++j){ fscanf(stdin,"%d",&a[i][j]); } } int rb,cb; fscanf(stdin,"%d %d",&rb,&cb); int b[rb][cb]; for(int i=0;i<rb;++i){ for(int j=0;j<cb;++j){ fscanf(stdin,"%d",&b[i][j]); } } if(ca!=rb){ fprintf(stdout,"Error: %d != %d",ca,rb); return 0; } int result[ra][cb]; fprintf(stdout,"%d %d\n",ra,cb); for(int i=0;i<ra;++i){ for(int j=0;j<cb;++j){ int sum = 0; for(int k=0;k<ca;++k){ sum += a[i][k]*b[k][j]; } result[i][j] = sum; } } //output fprintf(stdout,"%d",result[0][0]); for(int i=1;i<cb;++i){ fprintf(stdout," %d",result[0][i]); } for(int i=1;i<ra;++i){ fprintf(stdout,"\n%d",result[i][0]); for(int j=1;j<cb;++j){ fprintf(stdout," %d",result[i][j]); } } return 0; } //test but i think the format is wrong
#include "Graph.hpp" #include <list> #include <algorithm> #include <functional> #include <chrono> #include <iostream> #include "Dijkstra.hpp" using namespace std::chrono; Graph::Graph(System::Drawing::Image^ img, int max_slope) { System::Drawing::Bitmap^ bitmap = gcnew System::Drawing::Bitmap(img); int scale = 2; int dividend = 1; int cost_of_path = 5; std::vector<std::vector<double>> heights; heights.reserve(bitmap->Height / scale); for (int y = 0; y < bitmap->Height; y += scale) { std::vector<double> line; line.reserve(bitmap->Width / scale); for (int x = 0; x < bitmap->Width; x += scale) { double sum = 0; for (int xx = 0; xx < scale; xx++) { for (int yy = 0; yy < scale; yy++) { sum += bitmap->GetPixel(x + xx, y + yy).GetHue(); } } line.push_back(static_cast<double>(sum) / (scale*scale) / dividend); } heights.emplace_back(std::move(line)); } //dzikie rozniczkowanie for (int y = 0; y < heights.size(); y++) { std::vector<Point> line; for (int x = 0; x < heights[y].size(); x++) { std::vector<Edge> edges; std::vector<Edge> edges_reversed; for (int xx = (x == 0 ? 0 : -1); xx <= (x == heights[y].size() - 1 ? 0 : 1); xx++) { for (int yy = (y == 0 ? 0 : -1); yy <= (y == heights.size() - 1 ? 0 : 1); yy++) { if (!(xx == 0 && yy == 0)) { double slope = heights[y][x] - heights[y + yy][x + xx]; if (std::abs(slope) < max_slope) { double flat_path = (std::abs(xx) + std::abs(yy) == 2.0 ? 1.41 : 1.0)*cost_of_path; edges.emplace_back(Edge(x + xx, y + yy, std::max(static_cast<int>(flat_path + slope),0))); edges_reversed.emplace_back(Edge(x + xx, y + yy, std::max(static_cast<int>(flat_path - slope),0))); } } } } line.emplace_back(edges, edges_reversed); } this->points.emplace_back(std::move(line)); } } void Graph::clear() { for (auto & line : points) { for (auto & point : line) { point.visited = false; point.cost = LONG_MAX / 3; point.cost_reversed = LONG_MAX / 3; } } return; } void Graph::clear_visited() { for (auto & line : points) { for (auto & point : line) { point.visited = false; } } } adj_matrix Graph::get_adjacency_matrix(std::shared_ptr<Solution> actual, long range) { auto dijkstra= Dijkstra<decltype(this), decltype(actual)>::get_dijkstra(this, actual); this->clear(); adj_matrix adjacency_matrix; for(auto& proceeded_base : actual->bases) { std::vector<bool> vect(actual->bases.size()); //wiersz w macierzy przyleglosci dijkstra->set_start(proceeded_base); while(!dijkstra->are_candidates_empty()) { dijkstra->get_proceeded_point(); auto it = actual->bases.begin(); for (int i = 0; i < actual->bases.size(); i++, ++it) { //sprawdzenie czy punkt nie jest bazą if ((it->x == dijkstra->proceeded_point.x) && (it->y == dijkstra->proceeded_point.y)) { vect[i] = true; } } dijkstra->add_candidates(range); } dijkstra->clear_all(); adjacency_matrix.emplace_back(std::move(vect)); } for(int i=0; i<adjacency_matrix.size(); i++) { adjacency_matrix[i][i] = false; } return adjacency_matrix; }
#include <iostream> #include <string> using namespace std; // 1, 11, 21, 1211, 111221, ... string getNextSequence(string current) { int count = 1; string acum = ""; for (int i = 0; i < current.length(); i++) { if (i + 1 == current.length() || current[i] != current[i + 1]) { acum += to_string(count) + current[i]; count = 1; } else { count ++; } } return acum; } int getSequenceNumber(int index) { if (index == 1) { return 1; } else { string res = "1"; for (int i = 1; i < index; i ++) { res = getNextSequence(res); } return stoi(res); } } int main() { cout << getSequenceNumber(2); }
#ifdef _WIN32 # define TEST_EXPORT __declspec(dllexport) #else # define TEST_EXPORT #endif TEST_EXPORT int testCxxModule(void) { return 0; }
#include<iostream> using namespace std; int main() { int n, m, i, j; int arr[1000]; cin >> n; m = n; for (i = 0; i < n; i++) { cin >> arr[i]; } for (i = 0; i < n; i++) { for (j = 0; j < n - i - 1; j++) { int temp = 0; if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (i = 0; i < n; i++) { if ((arr[i] == arr[i + 1]) && arr[i + 1] > 0) { for (j = i; j < n; j++) { arr[j] = arr[j + 1]; } i = i - 1; m = m - 1; } } cout << m << endl; for (i = 0; i < m; i++) cout << arr[i] << ' '; cout << endl; return 0; }
#include "congl.hpp" using namespace ConGL::_2D; wchar_t menu0DT [8][22] = { L" Insanis Sphaera ", L" ", L" ", L" ABOUT ", L" ", L" START ", L" CREDITS ", L" EXIT " }; wchar_t menu1DT [28][46] = { L" Insanis Sphaera ", L" ", L" ", L" ", L" CODE BULBA ", L" ", L" GRAPHICS BULBA ", L" ", L" ", L" ", L" ", L" This game was written using ConGL API: ", L" https://github.com/bulbaME/ConGL ", L" ", L" ", L" ", L" Big thanks to everyone who ", L" helped creating this game! ", L" ", L" ", L" Watermelon - for funny pistacio ", L" Адвокат - for lovely gifs ", L" Flamingo - greatest beta tester ", L" Master - for awesome feedback ", L" Coffevarca - beta tester 2 ", L" Dasha - for amazing alien ", L" Stin - beta tester 3 ", L" Vsi - release tester " }; wchar_t menu2DT [17][82] = { L" ACTION KEY Main goal is to keep shpere stable. ", L"Close [ESCAPE] You can achieve that dragging and ", L"Pause / Resume [ESCAPE] collapsing particles in the sphere. ", L"Select [RETURN] Avoid enemy particles. ", L"Pause credits [SPACE] ", L" No stability makes sphere collapse. ", L"Pick particle [ARROWS] ", L"Select particle [RETURN] Sphere is growing when particles are ", L"Move particle [WASD] collapsing inside of it. ", L"Speed up particle [SPACE] ", L"Collapse particle [E] Also you have to keep all particle ", L" levels balanced. If there is too much", L" ====== PARTICLES ====== or too little of any particle shpere ", L"[@] - particle A collapses. ", L"[8] - particle B ", L"[¢] - particle C ", L"[Z] - enemy particle " }; wchar_t uiDT [3][19] = { L"STB [ ]", L"BLC [ ]", L"EXP [ ]" }; wchar_t pause1DT [7][22] = { L" PAUSED ", L" STAGE ", L" ", L" RESUME ", L" RESTART ", L" MAIN MENU ", L" EXIT " }; wchar_t pause2DT [6][22] = { L" Sphaera Concidit ", L" STAGE ", L" ", L" RESTART ", L" MAIN MENU ", L" EXIT " }; wchar_t pause3DT [6][22] = { L" Sphaera Confirmatae ", L" STAGE ", L" ", L" RESTART ", L" MAIN MENU ", L" EXIT " }; wchar_t easterEgg1DT [7][10] = { L" X X ", L" X X ", L" XXXXX ", L" XX X XX ", L" XXXXXXX ", L"X X X X", L" X X " }; wchar_t easterEgg2DT [7][10] = { L" X X ", L" X X ", L"X XXXXX X", L" XX X XX ", L" XXXXXXX ", L" X X ", L" X X " }; wchar_t uiTxtDT [1][6] = { {L"STAGE"} }; txr::Texture menu0TXR; txr::Texture menu1TXR; txr::Texture menu2TXR; txr::Texture uiTXR; txr::Texture uiTxtTXR; txr::Texture pause1TXR; txr::Texture pause2TXR; txr::Texture pause3TXR; txr::Texture easterEgg1TXR; txr::Texture easterEgg2TXR; void spriteInit() { menu0TXR.setProper<22, 8>(menu0DT); menu1TXR.setProper<46, 28>(menu1DT); menu2TXR.setProper<82, 17>(menu2DT); uiTXR.setProper<19, 3>(uiDT); uiTxtTXR.setProper<6, 1>(uiTxtDT); pause1TXR.setProper<22, 7>(pause1DT); pause2TXR.setProper<22, 6>(pause2DT); pause3TXR.setProper<22, 6>(pause3DT); easterEgg1TXR.setProper<10, 7>(easterEgg1DT); easterEgg2TXR.setProper<10, 7>(easterEgg2DT); }
#include "rvlightbulb.h" RVLightBulb::RVLightBulb(double r) :RVSphere(r) { m_radius = r; m_minS = 0; m_maxS = 2 * M_PI; m_minT = - M_PI_2; m_maxT = + M_PI_2; } RVLightBulb::~RVLightBulb() { } float RVLightBulb::x(double s, double t) { return float(m_radius*qCos(t)*qCos(s)) ; } float RVLightBulb::y(double s, double t) { return float(m_radius*qSin(t)); } float RVLightBulb::z(double s, double t) { return float(m_radius* qCos(t)*qSin(s)); } double RVLightBulb::radius() const { return m_radius; } void RVLightBulb::setRadius(double radius) { m_radius = radius; }
#include <iostream> using namespace std; int main() { int numsSize; cout<<"Enter number of elements:\n"; cin>>numsSize; int nums[numsSize]; cout<<"Enter elements:\n"; for(int i=0;i<numsSize;i++) { cin>>nums[i]; } int target; cout<<"Enter the target element:\n"; cin>>target; for(int i=0;i<numsSize;i++) { for(int j=i+1;j<numsSize;j++) { if(nums[i]+nums[j]==target) { cout<<"The index of the elements are:\n["<<i<<","<<j<<"]"<<endl; } } } return 0; }
#include <iostream> #include <string.h> #include <map> #include <vector> #include <stack> #include <sstream> using namespace std; typedef struct { string name; string type; long memory; bool initialized; long begin; long size; } Variable; typedef struct { string type; string name; string index; } Array; typedef struct { string iterator; string condition; long begin; } ForLoop; extern map<string, Variable> variables; extern vector<string> commands; extern stack<long> jumps; extern stack<long> whileLoop; extern stack<ForLoop> forLoop; extern stack<Array> arrays; extern map<long,long> constToGen; extern long memIndex; extern long cmdIndex; string longToString(long val); long stringToLong(string val); void addCommand(string cmd); void replace(string& str, const string& from, const string& to); void createVar(Variable *var,string name, string type); void createVar(Variable *var,string name, string type, long size, long begin); void insertVar(string name, Variable var); void genConst(string a); long getMemory1Index(Variable var, int line); long getMemory2Index(Variable var, int line); vector<string> generateConstants(); string decToBin(long val); void controllVariable(string name, int line); void error(string msg, int line); class Compiler { public: void declareVar(string name, int line); void declareTab(string name, string begin, string end, int line); void assignVar(char* name, int line); void checkIde(string name, int line); void pushArrayIde(string name, string index, int line); void pushArrayNum(string name, string index, int line); void read(char* name,int line); void write(char* name, int line); void assignJump(); void elseIf(); void endWhile(); void endDoWhile(); void startUpFor(char* i, char* from, char* to, int line); void startDownFor(char* i, char* from, char* to, int line); void endUpFor(); void endDownFor(); }; class Expressions { public: void singleVal(char* a, int yylineno); void add(char* a, char* b, int yylineno); void sub(char* a, char* b, int yylineno); void div(char* a, char* b, int yylineno); void mod(char* a, char* b, int yylineno); void mul(char* a, char* b, int yylineno); }; class Conditions { public: void eq(char* a,char* b, int yylineno); void notEq(char* a,char* b, int yylineno); void less(char* a,char* b, int yylineno); void greater(char* a,char* b, int yylineno); void lessEq(char* a,char* b, int yylineno); void greaterEq(char* a,char* b, int yylineno); };
#include "BlackWhiteEffect.h" #include "Window.h" BlackWhiteEffect::BlackWhiteEffect() { fbo = new Fbo(window::getWindowSize(), false); shader.addShader("shaders/gui.vsh", GL_VERTEX_SHADER); shader.addShader("shaders/blackWhiteEffect.fsh", GL_FRAGMENT_SHADER); shader.start(); shader.bindTextureUnit("textureSampler", 0); shader.activateUniform("useBlackWhite"); shader.activateUniform("useMMatrix"); shader.activateUniform("useTextureSampler"); shader.stop(); } void BlackWhiteEffect::applyBlackWhite(unsigned int vaoId, unsigned int rgbTexture, bool useBlackWhite) { shader.start(); glBindVertexArray(vaoId); glEnableVertexAttribArray(0); fbo->bindFrameBuffer(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.setUniformVariable("useMMatrix", false); shader.setUniformVariable("useTextureSampler", true); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, rgbTexture); shader.setUniformVariable("useBlackWhite", useBlackWhite); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); fbo->unbindFrameBuffer(); glDisableVertexAttribArray(0); glBindVertexArray(0); shader.stop(); } BlackWhiteEffect::~BlackWhiteEffect() { delete fbo; }
#include <SPI.h> #include "nRF24L01.h" #include "RF24.h" #include <LiquidCrystal.h> #define LCD_RW "GND" #define LCD_RS A0 #define LCD_EN A1 #define LCD_D4 A2 #define LCD_D5 A3 #define LCD_D6 A4 #define LCD_D7 A5 LiquidCrystal lcd(LCD_RS, LCD_EN, LCD_D4, LCD_D5, LCD_D6, LCD_D7); RF24 radio(8, 9); const byte address[6] = "c3lab"; uint8_t counter = 0; void setup() { Serial.begin(115200); lcd.begin(16, 2); lcd.clear(); Serial.println(radio.begin() ? "begin() OK!" : "begin() FALHOU!"); Serial.println(radio.setDataRate(RF24_2MBPS) ? "setDataRate() OK!" : "setDataRate() FALHOU!"); radio.setPALevel(RF24_PA_LOW); radio.setAutoAck(true); radio.setPayloadSize(1); radio.openReadingPipe(0, address); radio.startListening(); } void loop() { if (radio.available()) { radio.read(&counter, sizeof(uint8_t)); Serial.println(counter); lcd.clear(); lcd.setCursor(0, 0); lcd.print(counter); } }
void setup_DS() { #ifdef USE_DS18B20 LD_printString_6x8("DS on pin: ", LCDX1, 5); for (int i = 0; i < nSensor; i++) { DS[i].init(DS_CONVTIME); mb.addHreg(hrDSTEMP + i); // Модбас регистр - значение температуры int pins[] = PIN_DS; LD_printNumber((long)pins[i]); if (i < (nSensor - 1)) LD_printChar_6x8(", "); #ifdef SERIAL_CONFIG DS[i].printConfig(); String sInfo = "ID " + String(i, DEC) + "|Connected " + String(DS[i].Connected, DEC); PRINTLN(sInfo); #endif } #endif } void update_DS() { #ifdef USE_DS18B20 for (int i = 0; i < nSensor; i++) { DS[i].check(); #ifdef DS_ERRORS float t = DS[i].Temp; if (t > DS_MIN_T) { dsTemp[i] = t; cntrDSerrors = 0; } else if (cntrDSerrors > DS_ERRORS) { dsTemp[i] = t; cntrDSerrors++; } else { cntrDSerrors++; } #else dsTemp[i] = DS[i].Temp; #endif String dsInfo = ". DS " + String(i, DEC) + ": " + String(dsTemp[i], 2) + " | parasite: " + String(DS[i].Parasite, DEC) + " | " + String(DS[i].TimeConv, DEC); PRINTLN(dsInfo); } #endif }
#pragma once #include <iostream> #include <vector> #include "Item.h" using namespace std; class Customer { private: vector<Item> inventory; int gold; public: Customer(); ~Customer(); void ShowInventory(); int GetGold(); void SetGold(int gold); void InsertItem(Item item); void DeleteItem(int index); Item GetItem(int index); int GetItemCount(); };
#include <stdio.h> #include <conio.h> #include <group7.h> int r,c,r2,c2; void main () { char *ch[]={"RECTANGULAR MATRIX", "SQUARE MATRIX", "DIAGONAL MATRIX", "SCALAR DIAGONAL MATRIX", "UNITARY MATRIX", "ADDITION MATRIX", "SUBTRACTION MATRIX", "SCALAR MULTIPLICATION MATRIX", "MULTIPLICATION MATRIX", "TRANSPOSE MATRIX", "SYMETRIC MATRIX", "SKEW-SYMETRIC MATRIX", "MATRIX VALIDATION" }; int length; int forLoop; int op; clrscr(); gotoxy(25,20); printf("WELCOME TO MATRIX APPLICATION"); printf("\n\n\n\t\t\t PRESS ENTER TO CONTINUE..."); getche(); clrscr(); gotoxy(26,15); printf("PROGRAMMERS' NOTE"); gotoxy(5,20); printf("The Application is intended to solve and clear the basic concepts of Matrix\n\n (plural Matrices)."); printf("\n\n\n\n=> This Matrix Application involves all the basic Matrix properties that are\n\n required by the basic learners of Matrices. Moreover it defines each\n\n property with an example."); printf(" GOOD LUCK !"); gotoxy(25,40); printf("Press Enter to continue!"); getche(); do { // Start of DoWhile start(); gotoxy(8,8); printf("Selection Menu for the Matrix"); gotoxy(10,10); length=sizeof(ch)/sizeof(int); for(forLoop=0; forLoop<length; forLoop++) printf("\n\n\t%d. %s",(forLoop+1), ch[forLoop]); printf("\n\n\t%d. EXIT",forLoop+1); printf("\n\n\tEnter your Selection: "); scanf("%d",&op); switch (op) { case 1: showRectangular(); break; case 2: showSquare(); break; case 3: showDiagonal(r, r2, c, c2); break; case 4: showScalarDiagonal(r, r2, c, c2); break; case 5: showUnitary(r, r2, c, c2); break; case 6: showAddition(r, r2, c, c2); break; case 7: showSubtraction(r, r2, c, c2); break; case 8: showScalarMultiplication(r, r2, c, c2); break; case 9: showMultiplication(r, r2, c, c2); break; case 10: showTranspose(r, r2, c, c2); break; case 11: showSymetric(r, r2, c, c2); break; case 12: showSkewSymetric(r, r2, c, c2); break; case 13: showMatrixValidation(r, r2, c, c2); break; case 14: break; default: break; } // End of Switch }while (op!=14); // End of DoWhile } // End of Main Method
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include "camadaenlace.h" #include "camadafisica.h" using namespace std; void CamadaEnlaceDadosTransmissoraControleDeErroBitParidadePar(int quadro[]){ int size = 32; int bit = 0; // adiciona o novo bit no tamanho do quadro int aux[size + 1]; int j = 0; for (int j = 0; j < size; j++){ bit ^= quadro[j] & 1; //xor quadro[j] >>= 1; // Se o bit for 0 nada é alterado, se o bit for 1 altera entre 0 e 1 } for (j = 0; j < size; j++){ aux[j] = quadro[j]; } aux[size] = bit; //chama a camada física CamadaFisicaTransmissora(quadro); } void CamadaEnlaceDadosTransmissoraControleDeErroCRC(int quadro[]){ // usar polinomio CRC-32 (IEEE 802) int size = 4; int size_t = 8; int gerador[size]; //definindo gerador para 1001 gerador[0] = 1; gerador[1] = 0; gerador[2] = 0; gerador[3] = 1; int i; for (i = 5; i < size - 1; i++ ){ gerador[i] = 0; } cout << "Quadro:" << endl; for (i = 1; i < size_t; i++){ cout << quadro[i]; } cout << "\n"; cout << "Gerador:"; for (i = 0; i < size; i++){ cout << gerador[i]; } cout << "\n"; // Códificação CRC int j; int resto[size]; for (j = 0; j < size; j++){ if (resto[0] == 1){ for (i = 0; i < size; i++){ //xor resto[j] ^= gerador[i]; } } } int quadro_n = quadro[i] && gerador[size]; cout << "Mensagem Transmitida:" << endl; // Dobrar o tamanho do size para que não tenha problema na divisão //Soma 3 considerando que o CRC seja 0000 for (i = 0; i < 2*size + 3; i ++){ cout << quadro_n; } cout << "\n"; //chama a camada física CamadaFisicaTransmissora(quadro); } void CamadaEnlaceDadosTransmissoraControleDeErroHamming(int quadro[]){ // implementação do código para Hamming (11,7) int size = 32; int size_bits = 11; int i; int aux[size_bits]; std::vector<int> bit; cout << "Mensagem recebida:"; cout << "\n"; for (i = 0; i < size_bits; i++){ //aux[size_bits] = quadro[i]; cout << quadro[i]; } int P1 = 0; int P2 = 0; int P4 = 0; int P8 = 0; for (i = 0; i < size_bits; i++){ P1 = (aux[i] + aux [i + 3] + aux[i + 5] + aux[i + 7] + aux[i + 9 ] + aux[i + 11]) % 2 == 0; // verificar a paridade %2==0 bit.push_back(P1); P2 = (aux [i] + aux[i + 3] + aux [i + 6] + aux [i + 7] + aux [i + 10] + aux [i +11]) % 2 == 0; bit.push_back(P2); bit.push_back(aux[i]); P4 = (aux[i] + aux[i + 5] + aux [i + 6] + aux[i + 7]) % 2 == 0; bit.push_back(P4); bit.push_back(aux[i + 1]); bit.push_back(aux[i + 2]); bit.push_back(aux[i + 3]); P8 = (aux[i] + aux [i + 9] + aux [i + 10] + aux [i + 11]) %2 == 0; bit.push_back(P8); bit.push_back(aux[i + 9]); bit.push_back(aux[i + 10]); bit.push_back(aux[i + 11]); } cout << endl; cout << "A mensagem transmitida eh:" << int(bit.size()) << endl;; //chama a camada física CamadaFisicaTransmissora(quadro); } void CamadaDeEnlaceTransmissoraControleDeErro(int quadro[]){ int tipoDeControleDeErro; cout << "\n"; cout << "\nTipo de Controle de Erro: \n 0 - Bit Paridade Par \n 1 - CRC\n 2 - Código de Hamming\n "; cin >> tipoDeControleDeErro; switch(tipoDeControleDeErro){ case 0: CamadaEnlaceDadosTransmissoraControleDeErroBitParidadePar(quadro); break; case 1: CamadaEnlaceDadosTransmissoraControleDeErroCRC(quadro); break; case 2:CamadaEnlaceDadosTransmissoraControleDeErroHamming(quadro); break; } } /*Considerando size = 32*/ void CamadaDeEnlaceTransmissoraEnquadramentoContagemDeCaracteres(int quadro[]){ int i; int quantidade; int size = 32; int new_size; quantidade = size/8; int quadro_invertido[8]; new_size = size + 8; //Novo quadro recebe o tamanho no new_size; int novo_quadro[new_size]; for (i = new_size-1; i > 1; i--){ novo_quadro[i] = quadro[i - 8]; } i = 0; while (quantidade > 0){ quadro_invertido[i] = quantidade%2; quantidade = quantidade/2; i++; } if (i == 7){ quadro_invertido[i] = 0; i++; } if (i == 6){ for (i = 6; i < 8; i++) quadro_invertido[i] = 0; } if (i == 5){ for (i = 5; i < 8; i++) quadro_invertido[i] = 0; } if (i == 4){ for (i = 4; i < 8; i++) quadro_invertido[i] = 0; } if (i == 3){ for (i = 3; i < 8; i++) quadro_invertido[i] = 0; } if (i == 2){ for (i = 2; i < 8; i++) quadro_invertido[i] = 0; } if (i == 1){ for (i = 1; i < 8; i++) quadro_invertido[i] = 0; } cout << endl; int j = 0; i = 7; while (j < 8){ novo_quadro[j] = quadro_invertido[i]; j++; i--; } cout << "\nEnquadramento por contagem de caracter:" << endl; cout << "\n" << endl; for (i = 0; i < new_size; i++){ cout << novo_quadro[i]; } cout << "\n"<< endl; //próxima camada - controle de erro CamadaDeEnlaceTransmissoraControleDeErro(quadro); //chama a próxima camada CamadaEnlaceDadosReceptora(quadro); } void CamadaDeEnlaceTransmissoraEnquadramentoInsercaoDeBytes(int quadro[]){ // implmentação da inserção de bytes int flag_bytes[] = {0,0,1,0,0,0,1,1}; // Considerando a flag == # -dec == 35 -bin== 00100011 int flag_esc[] = {0,0,0,0,0,0,0,0,0}; // referente ao byte de escape //É necessário percorrer pelo quadro para encontrar a flag int i; int size = 32; int qtd_flag = 0; for ( i = 0; i < size - 8; i++ ){ if (flag_bytes){ qtd_flag++; i = i + 8; } } int new_size = size + 8*qtd_flag + 16; int novo_quadro[new_size]; cout << "Inserção de bytes"; cout << "\n"; cout << "Flag:"; cout << "\n"; for (i = 0; i < 8; i++) cout << flag_bytes[i]; cout << "\n"; cout << "Quadro:"; cout << "\n"; for (i = 0; i < new_size; i++) cout << novo_quadro[i]; cout << "\n"; // próxima camada controle de erro CamadaDeEnlaceTransmissoraControleDeErro(quadro); //chama a próxima camada CamadaEnlaceDadosReceptora(quadro); } void CamadaEnlaceDadosTransmissora (int quadro[]){ CamadaEnlaceDadosTransmissoraEnquadramento(quadro); //próxima camada //CamadaDeEnlaceTransmissoraControleDeErro(quadro); //próxima camada //CamadaFisicaTransmissora(); } void CamadaEnlaceDadosTransmissoraEnquadramento(int quadro[]){ int tipoDeEnquadramento; cout << "\n"; cout << "\nTipo de Enquadramento: \n 0 - Contagem De Caracteres \n 1 - Inserção de Bytes\n "; cin >> tipoDeEnquadramento; switch (tipoDeEnquadramento){ case 0: // contagem de caracteres CamadaDeEnlaceTransmissoraEnquadramentoContagemDeCaracteres(quadro); break; case 1: CamadaDeEnlaceTransmissoraEnquadramentoInsercaoDeBytes(quadro); break; } } /*Desenquadramento*/ void CamadaEnlaceDadosReceptoraDesenquadramentoContagemDeCaracteres(int quadro[]){ //implemente o código int i; int size = 32; int aux; int novo_quadro[size - 8]; aux = novo_quadro[size - 8]; cout <<"\n Quadro Desenquadrado:"; cout << "\n"; for (i = 1; i < size - 8; i++){ aux = quadro[i + 7]; cout << aux; } cout << "\n"; //chama a próxima camada } void CamadaEnlaceDadosReceptoraDesenquadramentoInsercaoDebytes(int quadro[]){ //para desenquadrar foi implementado o inverso do enquadramento int flag_bytes[] = {0,0,1,0,0,0,1,1}; // Considerando a flag == # -dec == 35 -bin== 00100011 int flag_esc[] = {0,0,0,0,0,0,0,0,0}; // referente ao byte de escape int i; int size = 32; int qtd_flag = 0; for ( i = 0; i < size - 8 ; i++ ){ if (flag_bytes){ qtd_flag++; i = i + 8; } } int new_size = size + 8*qtd_flag - 16; int novo_quadro[new_size]; cout << "Inserção de bytes"; cout << "\n"; cout << "Flag:"; cout << "\n"; for (i = 0; i < 8; i++) cout << flag_bytes[i]; cout << "\n"; cout << "Quadro Desenquadrado:"; cout << "\n"; for (i = 0; i < new_size; i++) cout << novo_quadro[i]; cout << "\n"; // chama a próxima camada } void CamadaEnlaceDadosReceptoraEnquadramento(int quadro[]){ /*Realiza a chamada para o tipo de desenquadramento*/ int tipoDesenquadramento; cout << "\n"; cout << "\nTipo de Enquadramento - Camada Receptora: \n 0 - Contagem De Caracteres \n 1 - Inserção de Bytes\n "; cin >> tipoDesenquadramento; switch (tipoDesenquadramento){ case 0: // contagem de caracteres CamadaEnlaceDadosReceptoraDesenquadramentoContagemDeCaracteres(quadro); break; case 1: CamadaEnlaceDadosReceptoraDesenquadramentoInsercaoDebytes(quadro); break; } } void CamadaEnlaceDadosReceptoraControleDeErroBitParidadePar (int quadro[]){ cout << "Verificação se houve erro:" << endl; // Em 0 -> nada muda int bit; int size = 32; int aux[size -1]; int i; int n = 0; for (i = 0; i < size ; i++){ n ^= quadro[i]; } if ( n == 0){ cout << "Foi encontrado erro na transmissão do quadro." << endl; } else { cout << "Não houve erro na transmissão do quadro." << endl; } for ( i = 0; i < size -1; i++){ //Novo quadro - > aux é igual ao quadro original aux[i] = quadro[i]; } // Próxima camada CamadaEnlaceDadosReceptoraEnquadramento(quadro); } void CamadaEnlaceDadosReceptoraControleDeErroCRC (int quadro []){ cout << "Verificação se houve erro:" << endl; /* Para esse controle de erro, pode ser utilizado o início da implementação que foi feita para a camada transmissora do CRC */ // usar polinomio CRC-32 (IEEE 802) int size = 4; int size_t = 8; int gerador[size]; //definindo gerador para 1001 gerador[0] = 1; gerador[1] = 0; gerador[2] = 0; gerador[3] = 1; int i; for (i = 5; i < size - 1; i++ ){ gerador[i] = 0; } cout << "Quadro:" << endl; for (i = 1; i < size_t; i++){ cout << quadro[i]; } cout << "\n"; cout << "Gerador:"; for (i = 0; i < size; i++){ cout << gerador[i]; } // Implementação da decodificação do CRC int j; int resto[size]; for ( j = 0; j < size + 3; j ++){ if (resto[0] == 1){ for (i = 0; i < size; i++){ //xor igual da codificação, trocando apenas o parâmetro j por i resto[i] ^= gerador[i]; } } // continuação da divisão if ( j < 2*size){ for (i = 0; i < size -1; i++){ resto[i] = resto[i]; } } } if (resto[size - 1] == 0) cout << "\nA Mensagem foi recebida sem erro." << endl; else cout << "\nA Mensagem foi recebida com erro." << endl; cout << "\nA Mensagem recebida foi:" << endl; for (i = 0; i < size + 4 ; i++){ cout << quadro[i]; } // próxima camada CamadaEnlaceDadosReceptoraEnquadramento(quadro); } void CamadaEnlaceDadosReceptoraControleDeErroDeHamming(int quadro[]){ // implementar de decoficação int size = 32; int size_bits = 11; int i; int total = 0; int aux[size_bits]; std::vector<int> bit; cout << "Mensagem recebida:"; cout << "\n"; for (i = 0; i < size_bits; i++){ //aux[size_bits] = quadro[i]; bit.push_back(quadro[i]); } for (i = 0; i < size; i++){ int M3 = 0; int M5 = 0; int M7 = 0; int M9 = 0; int M11 = 0; // Os valores de M3 a M11 podem receber valores de 0 ou 1 M3 = (bit[i + 0] ^ bit [i + 1]) == bit [i + 0]; M5 = (bit[i + 3] ^ bit [i + 0]) == bit [i + 0]; M7 = (bit[i + 3] ^ bit [i + 1]) == bit [i + 0]; M9 = (bit[i + 7] ^ bit [i + 0]) == bit [i + 0]; M11 = (bit[i + 7] ^ bit [i + 1]) == bit [i + 0]; total = quadro[i] && quadro [i + 1] && quadro [i + 3] && quadro[i + 7]; } if (total == 2){ cout << "Houve erro na codificação de Hamming." << endl; } else { cout << "Não houve erro na codificação de Hamming." << endl; } cout << "Soma dos bits:" << total << endl; // próxima camada CamadaEnlaceDadosReceptoraEnquadramento(quadro); } void CamadaEnlaceReceptoraControleDeErro(int quadro[]){ int tipoDeControleDeErro; cout << "Camada Receptora" << endl; cout << "\n"; cout << "\nTipo de Controle de Erro: \n 0 - Bit Paridade Par \n 1 - CRC\n 2 - Código de Hamming\n "; cin >> tipoDeControleDeErro; switch(tipoDeControleDeErro){ case 0: CamadaEnlaceDadosReceptoraControleDeErroBitParidadePar(quadro); break; case 1: CamadaEnlaceDadosReceptoraControleDeErroCRC(quadro); break; case 2: CamadaEnlaceDadosReceptoraControleDeErroDeHamming(quadro); break; } } void CamadaEnlaceDadosReceptora(int quadro[]){ //implemente o código //chama a próxima camada //CamadaEnlaceDadosReceptoraEnquadramento(quadro); //chama a próxima camada CamadaEnlaceReceptoraControleDeErro(quadro); //chama a próxima camada //CamadaDeAplicacaoReceptora(); }
/** * Copyright (C) Omar Thor, Aurora Hernandez - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * * Written by * Omar Thor <omar@thorigin.com>, 2018 * Aurora Hernandez <aurora@aurorahernandez.com>, 2018 */ #ifndef DMTK_ALGORITHM_CLUSTERING_METRIC_HPP #define DMTK_ALGORITHM_CLUSTERING_METRIC_HPP #include <type_traits> #include <functional> #include "dmtk/element/function/euclidean.hpp" #include "dmtk/util/tuple_hash.hpp" DMTK_NAMESPACE_BEGIN enum euclidean_distance_metric_type { min, max }; /** * @brief Euclidean min distance metric (MIN or MAX) * * Finds the MIN or MAX distance between cluster X and Y such that * D(X, Y) = min_{x in X, y in X} d(x, y) */ template<euclidean_distance_metric_type type = euclidean_distance_metric_type::min> struct euclidean_distance_metric { std::conditional_t<type == min, std::less<void>, std::greater<void>> comparator; template<typename Cluster> auto operator()(const Cluster& a, const Cluster& b) { static_assert(is_container_v<Cluster>, "Arguments are containers"); fp_type best = type == min ? std::numeric_limits<fp_type>::max() : std::numeric_limits<fp_type>::min(); for(auto ait = a.begin(), a_end = a.end(); ait != a_end; ++ait) { for(auto bit = b.begin(), b_end = b.end(); bit != b_end; ++bit) { auto tmp = euclidean_distance(*ait, *bit); if(comparator(tmp, best)) { best = tmp; } } } return best; } }; /** * @brief Euclidean Min Distance Metric (alias) * * @see euclidean_distance_metric */ using euclidean_min_distance_metric = euclidean_distance_metric<min>; /** * @brief Euclidean Max Distance Metric (alias) * * @see euclidean_distance_metric */ using euclidean_max_distance_metric = euclidean_distance_metric<max>; /** * @brief Euclidean Centroid Metric (MIN or MAX) * * Finds the euclidean distance between two clusters */ struct euclidean_centroid_metric { template<typename Cluster> auto operator()(const Cluster& a, const Cluster& b) { return euclidean_distance_squared(centroid(a), centroid(b)); } }; /** * @brief Group Average Metric * * Finds the euclidean average of all points of two clusters */ struct euclidean_group_average_metric { template<typename Cluster> auto operator()(const Cluster& a, const Cluster& b) { static_assert(is_container_v<Cluster>, "Arguments are containers"); fp_type sum = 0; fp_type count = a.size() * b.size(); for(auto ait = a.begin(), a_end = a.end(); ait != a_end; ++ait) { for(auto bit = b.begin(), b_end = b.end(); bit != b_end; ++bit) { sum += euclidean_distance(*ait, *bit); } } fp_type average_group = sum / count; return average_group; } }; /** * @brief Default metric function */ using default_metric_function = euclidean_min_distance_metric; DMTK_NAMESPACE_END #endif /* DMTK_ALGORITHM_CLUSTERING_METRIC_HPP */
// Pentru urmatoarele valori ale datelor: // int i =4; // int j = 6; // int k = 8; // int l = 1; // int m = 10; // Evaluati expressile: // (i+j) div (m-j) // (j+(m-l*(j+i))-k)+5 // i-j+k-l+m // 3*j mod m - i // j*j-i-k #include <iostream> #include <string> #include <windows.h> int main() { int i = 4, j = 6, k = 8, l = 1, m = 10; std::cout << "i+j*l-m: " << std::string((i + j * l - m) ? "true" : "false") << std::endl; std::cout << "(i+j) div (m-j): " << std::string(((i + j) / (m - j)) ? "true" : "false") << std::endl; std::cout << "(j+(m-l*(j+i))-k)+5: " << std::string(((j + (m - l * (j + i)) - k) + 5) ? "true" : "false") << std::endl; std::cout << "i-j+k-l+m: " << std::string((i - j + k - l + m) ? "true" : "false") << std::endl; std::cout << "3*j mod m - i: " << std::string((3 * j % m - i) ? "true" : "false") << std::endl; std::cout << "j*j-i-k: " << std::string((j*j - i - k) ? "true" : "false") << std::endl; //Template: //std::cout << " " << std::string((1) ? "true" : "false") << std::endl; std::cout << std::endl; system("pause"); return 0; }
#pragma once #include "GlobalHeader.h" // fa::OStream #include <utility> // std::move #include "Nutrient.h" // fa::NutrientType #include "NutrientTableImpl.h" // fa::NutrientTableImpl namespace fa { template <class Target> class NutrientTableStaticDelegator final { public: using this_type = NutrientTableStaticDelegator; using value_type = Target; NutrientTableStaticDelegator() noexcept : val_{ } { } //! Do not put more than one of each NutrientType in here! template <class ...Args> explicit NutrientTableStaticDelegator(Args &&...args) noexcept : val_{ std::forward<Args>(args)... } { } friend this_type operator+(this_type const &lhs, this_type const &rhs) { return this_type{ lhs.val_ + rhs.val_ }; } friend this_type operator-(this_type const &lhs, this_type const &rhs) { return this_type{ lhs.val_ - rhs.val_ }; } friend this_type operator*(this_type const &nutrientTable, Amount::value_type amt) { return this_type{ nutrientTable.val_ * amt }; } friend this_type operator/(this_type const &nutrientTable, Amount::value_type amt) { return this_type{ nutrientTable.val_ / amt }; } this_type getMacroNutrients() const { return this_type{ val_.getMacroNutrients() }; } this_type getMicroNutrients() const { return this_type{ val_.getMicroNutrients() }; } auto getNutrient(NutrientType nutrientType) const -> decltype(auto) { return val_.getNutrient(nutrientType); } auto getPercentages() const -> decltype(auto) { return val_.getPercentages(); } friend OStream &operator<<(OStream &os, this_type const &obj) { return os << obj.val_; } friend bool operator==(this_type const &lhs, this_type const &rhs) noexcept { return lhs.val_ == rhs.val_; } friend bool operator!=(this_type const &lhs, this_type const &rhs) noexcept { return !(lhs == rhs); } private: value_type val_; }; // END of class NutrientTableStaticDelegator using NutrientTable = NutrientTableStaticDelegator<NutrientTableImpl>; } // END of namespace fa
#include "Core_PCH.h" #define CHECK(x) m_lastErrorCode = x; if (m_lastErrorCode != 0) { break; } #define CHECK_EX(c, x) c->m_lastErrorCode = x; if (c->m_lastErrorCode != 0) { break; } namespace ServerEngine { NetSocket::NetSocket() : NetSocket(uv_default_loop()) { } NetSocket::NetSocket(uv_loop_t* loopHandle) : m_loopHandle(loopHandle), m_lastErrorCode(0) { m_socketHandle = new uv_tcp_t(); m_socketHandle->data = this; uv_tcp_init(m_loopHandle, m_socketHandle); m_reuseBuf.base = nullptr; m_reuseBuf.len = 0; } NetSocket::~NetSocket() { /*if (uv_is_active((uv_handle_t*)m_socketHandle)) { uv_close((uv_handle_t*)m_socketHandle, nullptr); uv_run(m_loopHandle, UV_RUN_DEFAULT); }*/ SAFE_DELETE(m_socketHandle); SAFE_DELETE_ARRAY(m_reuseBuf.base); } bool NetSocket::Bind(const char* ip, int port) { do { sockaddr_in addr; CHECK(uv_ip4_addr(ip, port, &addr)); CHECK(uv_tcp_bind(m_socketHandle, (const struct sockaddr*)&addr, 0)); return true; } while (false); return false; } bool NetSocket::Listen(int maxConnections) { do { CHECK(uv_listen((uv_stream_t*)m_socketHandle, maxConnections, UV_OnNewConnection)); return true; } while (false); return false; } bool NetSocket::Connect(const char* ip, int port) { uv_connect_t* request = new uv_connect_t(); do { sockaddr_in addr; CHECK(uv_ip4_addr(ip, port, &addr)); CHECK(uv_tcp_connect(request, m_socketHandle, (const struct sockaddr*)&addr, UV_OnConnect)); return true; } while (false); SAFE_DELETE(request); return false; } bool NetSocket::Send(const char* data, int length) { NetPacket* packet = new NetPacket(); packet->Split(data, length); uv_write_t request; request.data = packet; m_lastErrorCode = uv_write(&request, (uv_stream_t*)m_socketHandle, packet->GetBuffers(), packet->GetBufferCount(), UV_OnWrite); if (m_lastErrorCode != 0) { SAFE_DELETE(packet); return false; } return true; } void NetSocket::Close() { uv_shutdown_t request; m_lastErrorCode = uv_shutdown(&request, (uv_stream_t*)m_socketHandle, UV_OnShutdown); if (m_lastErrorCode != 0) { request.handle = (uv_stream_t*)m_socketHandle; UV_OnShutdown(&request, m_lastErrorCode); } } uv_loop_t* NetSocket::GetLoopHandle() const { return m_loopHandle; } uv_tcp_t* NetSocket::GetSocketHandle() const { return m_socketHandle; } void NetSocket::UV_OnNewConnection(uv_stream_t* server, int status) { if (server == nullptr || server->data == nullptr) { return; } NetSocket* serverSocket = (NetSocket*)server->data; if (status < 0) { serverSocket->m_lastErrorCode = status; return; } NetSocket* clientSocket = new NetSocket(serverSocket->m_loopHandle); do { CHECK_EX(serverSocket, uv_accept((uv_stream_t*)serverSocket->m_socketHandle, (uv_stream_t*)clientSocket->m_socketHandle)); CHECK_EX(serverSocket, uv_read_start((uv_stream_t*)clientSocket->m_socketHandle, UV_OnAllocBuf, UV_OnRead)); // TODO: Notify out. return; // Success. } while (false); SAFE_DELETE(clientSocket); } void NetSocket::UV_OnConnect(uv_connect_t* request, int status) { do { if (request == nullptr || request->handle == nullptr || request->handle->data == nullptr) { break; } NetSocket* socket = (NetSocket*)request->handle->data; CHECK_EX(socket, status); CHECK_EX(socket, uv_read_start((uv_stream_t*)socket->m_socketHandle, UV_OnAllocBuf, UV_OnRead)); } while (false); SAFE_DELETE(request); } void NetSocket::UV_OnAllocBuf(uv_handle_t* handle, size_t size, uv_buf_t* buf) { if (handle == nullptr || handle->data == nullptr) { return; } NetSocket* serverSocket = (NetSocket*)handle->data; if (serverSocket->m_reuseBuf.len != size) { SAFE_DELETE_ARRAY(serverSocket->m_reuseBuf.base); serverSocket->m_reuseBuf.base = new char[size]; serverSocket->m_reuseBuf.len = (unsigned long)size; } buf->base = serverSocket->m_reuseBuf.base; buf->len = serverSocket->m_reuseBuf.len; } void NetSocket::UV_OnRead(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { //if (nread < 0) //{ // uv_shutdown_t* shutdownReq = new uv_shutdown_t(); // uv_shutdown(shutdownReq, stream, on_shutdown); //} } void NetSocket::UV_OnWrite(uv_write_t* request, int status) { SAFE_DELETE(request->data); } void NetSocket::UV_OnShutdown(uv_shutdown_t* request, int status) { } }
/* Write a program that will convert US dollars amounts to Japanese yen and to euros, storing the conversion factors in the constants YEN_PER_DOLLAR and EUROS_PER_DOLLAR. To get the most up-to-date rates, search the internet using the term "currency exchange rate". If you cannot find the most recent exchange rates, use the following: 1 dollar = 83.14 Yen 1 dollar = 0.7337 Euros Format your currency amounts in fixed-Point notation, with two decimal places of precision, and be sure the decimal point is always displayed. Author: Aaron Maynard */ #include<iostream> #include<iomanip> using namespace std; int main() { // Declare variables const double YEN_PER_DOLLAR = 98.93; const double EUROS_PER_DOLLAR = 0.74; double dollars, yen, euros; // User input cout << "Enter dollar amount: "; cin >> dollars; // Do the math yen = dollars * YEN_PER_DOLLAR; euros = dollars * EUROS_PER_DOLLAR; // Print to screen cout << setprecision(2) << fixed; cout << "$" << dollars << " = " << yen << " Yen" << endl; cout << "$" << dollars << " = " << euros << " Euros" << endl; return 0; }
// // GnIListCtrlItem.cpp // Core // // Created by Max Yoon on 11. 7. 27.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #include "GnInterfacePCH.h" #include "GnIListCtrlItem.h" GnImplementRTTI(GnIListCtrlItem, GnIButton); GnIListCtrlItem::GnIListCtrlItem(const gchar* pcDefaultImage, const gchar* pcClickImage , const gchar* pcDisableImage, eButtonType eDefaultType) : GnIButton( pcDefaultImage, pcClickImage , pcDisableImage, eDefaultType ), mEmptyItem( false ) { } GnIListCtrlItem::~GnIListCtrlItem() { } bool GnIListCtrlItem::PushUp(float fPointX, float fPointY) { return GnInterface::PushUp( fPointX, fPointY ); } bool GnIListCtrlItem::PushMove(float fPointX, float fPointY) { return GnIButton::PushMove( fPointX, fPointY ); } void GnIListCtrlItem::Push() { GnIButton::Push(); } void GnIListCtrlItem::PushUp() { GnIButton::PushUp(); }
/* -*- 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 ** */ #ifndef _AUTH_SN_H_ #define _AUTH_SN_H_ #ifdef _ENABLE_AUTHENTICATE class AuthElm; class CookiePath; class Sequence_Splitter; typedef Sequence_Splitter ParameterList; struct DebugUrlMemory; class ServerNameAuthenticationManager { private: /** Last username used in authentication dialog */ OpString username; /** Last username used in proxy authentication dialog */ OpString proxyusername; // Last registered name /** List of proxy authentication credentials. Only one password per port */ AutoDeleteHead authenticate_proxy; #ifndef NO_FTP_SUPPORT /** List of FTP authentication credentials */ AutoDeleteHead authenticate_ftp; #endif // NO_FTP_SUPPORT /** List of HTTP authentication credentials. May have more than one password per port. */ AutoDeleteHead authenticate_http; /** List of HTTPS authentication credentials. May have more than one password per port. */ AutoDeleteHead authenticate_https; #ifdef _USE_PREAUTHENTICATION_ /** HTTP Authentication credential aliases by path */ CookiePath *auth_paths_http; /** HTTPS Authentication credential aliases by path */ CookiePath *auth_paths_https; #endif protected: ServerNameAuthenticationManager(); ~ServerNameAuthenticationManager(); private: public: #ifndef AUTH_RESTRICTED_USERNAME_STORAGE /** Set the last used username for authentication */ OP_STATUS SetLastUserName(const OpStringC &nam); /** Set the last used username for proxy authentication */ OP_STATUS SetLastProxyUserName(const OpStringC &nam); #endif /** Get the last used username for authentication */ OpStringC GetLastUserName() const {return username;} /** Get the last used username for proxy authentication */ OpStringC GetLastProxyUserName() const {return proxyusername;} /** Add a new authentication element for the specified path */ void Add_Auth(AuthElm *, const OpStringC8 &path); /** Get the currently used authentication credetials used for the given port, path, protocol and realm, usingthe specified authentication scheme */ AuthElm *Get_Auth(const char *realm, unsigned short port, const char *path, URLType, AuthScheme schm, URL_CONTEXT_ID context_id); #ifdef _USE_PREAUTHENTICATION_ /** * Try to resolve HTTP authentication realm internally. * This function is meant to be called before unauthenticated connect in order to resolve realm for particular URL path. * If internal search is successful - we save time and traffic. * * @return HTTP authentication realm, if it could be resolved internally, NULL otherwise. */ const char *ResolveRealm(unsigned short port, const char *path, URLType typ, AuthScheme schm, URL_CONTEXT_ID a_context_id) const; #endif // _USE_PREAUTHENTICATION_ /** Clear all authentication credentials */ void Clear_Authentication_List(); /** Update the credentials for the authentication element having the given id, with the argument parameter list */ OP_STATUS Update_Authenticate(unsigned long aid, ParameterList *); BOOL SafeToDelete(); void RemoveSensitiveData(); #ifdef _OPERA_DEBUG_DOC_ void GetMemUsed(DebugUrlMemory &debug); #endif }; #endif #endif // _AUTH_SN_H_
#include <algorithm> #include <cmath> #include <iostream> #include <limits> #include <vector> using ll = long long; class SegmentTree { public: SegmentTree() = delete; SegmentTree(const std::vector<ll>& numbers); ll GetSubSum(int idx, int start, int end, int left, int right) const; private: ll InitTree(const std::vector<ll>& numbers, int idx, int start, int end); std::size_t m_size, m_height; std::vector<ll> m_numbers; }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int N, M; std::cin >> N >> M; std::vector<ll> data; data.reserve(N); for (int i = 0; i < N; ++i) { ll t; std::cin >> t; data.push_back(t); } SegmentTree segtree(data); for (int i = 0; i < M; ++i) { int a, b; std::cin >> a >> b; std::cout << segtree.GetSubSum(0, 0, data.size() - 1, a - 1, b - 1) << '\n'; } } SegmentTree::SegmentTree(const std::vector<ll>& numbers) : m_size(numbers.size()), m_height(std::ceil(std::log2(m_size))), m_numbers((1 << m_height + 1), std::numeric_limits<long long>::max()) { InitTree(numbers, 0, 0, m_size - 1); } ll SegmentTree::InitTree(const std::vector<ll>& numbers, int idx, int start, int end) { if (start == end) { m_numbers[idx] = numbers[start]; } else { m_numbers[idx] = std::min( InitTree(numbers, idx * 2 + 1, start, (start + end) / 2), InitTree(numbers, idx * 2 + 2, (start + end) / 2 + 1, end)); } return m_numbers[idx]; } ll SegmentTree::GetSubSum(int idx, int start, int end, int left, int right) const { if (start > right || end < left) { return std::numeric_limits<long long>::max(); } if (start >= left && end <= right) { return m_numbers[idx]; } return std::min( GetSubSum(2 * idx + 1, start, (start + end) / 2, left, right), GetSubSum(2 * idx + 2, (start + end) / 2 + 1, end, left, right)); }
#ifndef UNIVERSALFORCE_H #define UNIVERSALFORCE_H #include "Force.h" class Object; class UniversalForce : public Force { public: explicit UniversalForce(Object*); UniversalForce(const UniversalForce&); virtual ~UniversalForce(void); virtual void exec(void); virtual bool isDone(void); virtual Vector getForcePoint(void); void changeObject(Object*); private: Object* object; }; #endif
// world hello.cpp : 定义控制台应用程序的入口点。 // #include <iostream> #include "string-trans.h" #include "contour_fill.h" int main() { using namespace std; contour_fill::contr_set_type lines=readdata(); vector<contour_fill::contr_set_type> contr_set_type; contour_fill(lines,0,0,450,350).get_fill_contours(contr_set_type); return 0; }
#include<bits/stdc++.h> using namespace std; #define PI 3.1415926535897932 int main(){ int a; int *lpa; lpa=&a; double d, e; printf("input!!!!!\n"); scanf("%d",&a); printf("変数a に %d 代入\n",a); printf("変数a のアドレスは%p \n",&a); printf("変数a をさすポインタは lpa \n"); printf("*lpa の値は%d \n",*lpa); }
#include <iostream> #include <vector> using namespace std; class Solution { public: int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount+1, amount+1); dp[0] = 0; int n = coins.size(); for(int i=0;i<n;i++){ int coin = coins[i]; if(coin <= amount) dp[coin] = 1; for(int j=1;j<=amount;j++) if(coin <= amount && dp[j] != amount+1 && j + coin <= amount) dp[j + coin] = min(dp[j + coin], dp[j] + 1); } int res = (dp[amount] == amount+1) ? -1 : dp[amount]; return res; } }; int main(){ Solution s; vector<int> v; v.push_back(2147483647); cout << s.coinChange(v, 2) << endl; return 0; }
#include <iostream> #include <vector> #include <string.h> #include <algorithm> bool checkString(std::string &s1, std::string &s2) { if( s1.length() < s2.length() || s1.length() == s2.length() && s1 < s2) { return true; } return false; } void bigSorting (std::vector<std::string> &arr) { int counter = 1; std::sort(arr.begin(), arr.end(), checkString); for(auto &n : arr) { std::cout << n << " "; } } int main() { std::vector<std::string> m_Array = {"31415926535897932384626433832795", "2", "1", "21", "22","8"}; bigSorting(m_Array); return 0; }
#include <opencv2/opencv.hpp> #include <opencv2/nonfree/nonfree.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/stitching/detail/blenders.hpp> #include <algorithm> using namespace cv; using namespace std; // Functions prototypes void Homography(const vector<Mat> &Images, vector<Mat> &transforms); void FindOutputLimits(const vector<Mat> &Images, vector<Mat> &transforms, int &xMin, int &xMax, int &yMin, int &yMax); void warpMasks(const vector<Mat> &Images, vector<Mat> &masks_warped, const vector<Mat> &transforms, const Mat &panorama); void warpImages(const vector<Mat> &Images, const vector<Mat> &masks_warped, const vector<Mat> &transforms, Mat &panorama); void BlendImages(const vector<Mat> &Images, Mat &pano_feather, Mat &pano_multiband, const vector<Mat> &masks_warped, const vector<Mat> &transforms); int main() { // Initialize OpenCV nonfree module initModule_nonfree(); // Set the dir/name of each image const int NUM_IMAGES = 6; const string IMG_NAMES[] = { "img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg", "img5.jpg", "img6.jpg" }; //uncomment for reordered test //const string IMG_NAMES[] = { "img1.jpg", "img6.jpg", "img5.jpg", "img2.jpg", "img3.jpg", "img4.jpg" }; // Load the images vector<Mat> Images; for (int i = 0; i < NUM_IMAGES; i++) { Images.push_back(imread(IMG_NAMES[i])); //uncomment to show images //imshow("check", Images[i]); //waitKey(1); } // 1. Initialize all the transforms to the identity matrix vector<Mat> transforms; for (int i = 0; i < NUM_IMAGES; i++) { transforms.push_back(Mat::eye(3, 3, CV_64F)); } // 2. Calculate the transformation matrices Homography(Images, transforms); // 3. Compute the min and max limits of the transformations int xMin, xMax, yMin, yMax; FindOutputLimits(Images, transforms, xMin, xMax, yMin, yMax); // 4/5. Initialize the panorama image Mat panorama = Mat::zeros(yMax - yMin + 1, xMax - xMin + 1, CV_64F); cout << "X total = " << xMax - xMin + 1 << endl; cout << "Y total = " << yMax - yMin + 1 << endl; cout << "panorama height = " << panorama.size().height << endl; cout << "panorama width = " << panorama.size().width << endl; // 6. Initialize warped mask images vector<Mat> masks_warped(NUM_IMAGES); //masks_warped.reserve(NUM_IMAGES); // 7. Warp image masks warpMasks(Images, masks_warped, transforms, panorama); // 8. Warp the images warpImages(Images, masks_warped, transforms, panorama); // 9. Initialize the blended panorama images Mat pano_feather = Mat::zeros(panorama.size(),CV_64F); Mat pano_multiband = Mat::zeros(panorama.size(), CV_64F); // 10. Blend BlendImages(Images, pano_feather, pano_multiband, masks_warped, transforms); return 0; } void Homography(const vector<Mat> &Images, vector<Mat> &transforms) { //get number of images int num_images = Images.size(); //generate key points and match images for (int i = 1; i < num_images; i++) { //sift detector and extractor Ptr<FeatureDetector> feature_detector = FeatureDetector::create("SIFT"); Ptr<DescriptorExtractor> descriptor_extract = DescriptorExtractor::create("SIFT"); //matcher Ptr<DescriptorMatcher> desc_matcher = DescriptorMatcher::create("BruteForce"); //keypoints/dexscriptors for first image vector<KeyPoint> store_kp_first; Mat current_d_first; //keypoints/dexscriptors for second image vector<KeyPoint> store_kp_sec; Mat current_d_sec; //vector for match data vector<DMatch> match_data; Mat image_out; //points for first and second image vector<Point2d> first; vector<Point2d> second; //detect and extract for both images feature_detector->detect(Images[i], store_kp_first); descriptor_extract->compute(Images[i], store_kp_first, current_d_first); feature_detector->detect(Images[i - 1], store_kp_sec); descriptor_extract->compute(Images[i - 1], store_kp_sec, current_d_sec); //matcha and draw matches desc_matcher->match(current_d_first, current_d_sec, match_data); drawMatches(Images[i], store_kp_first, Images[i - 1], store_kp_sec, match_data, image_out, DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); //uncomment to save images /*std:ostringstream os; os << "Dmatched_image_" << i << ".jpg"; imwrite(os.str(), image_out)*/; //process for removing our of range matches double min_dist = DBL_MAX; for (int j = 0; j < match_data.size(); j++) { double distance = match_data[j].distance; if (distance < min_dist) min_dist = distance; } //needs to be modified depending on data set min_dist *= 3.2; //delete bad matches match_data.erase( std::remove_if( match_data.begin(), match_data.end(), [min_dist](DMatch remove) {return (remove.distance > min_dist); } ), match_data.end() ); //extra the coordinates for (int j = 0; j < match_data.size(); j++) { first.push_back(store_kp_first[match_data[j].queryIdx].pt); second.push_back(store_kp_sec[match_data[j].trainIdx].pt); } //compute transform transforms[i] = findHomography(first, second, RANSAC); } //uncomment for direct comparison /*Mat transform_extra = transforms[0] * transforms[5]; std::cout << transform_extra << endl;*/ //finish computing transforms between images for (int i = 1; i < num_images; i++) { transforms[i] = transforms[i - 1] * transforms[i]; } //uncomment ro display 5th tranform //std::cout << transforms[5] << endl; } void FindOutputLimits(const vector<Mat> &Images, vector<Mat> &transforms, int &xMin, int &xMax, int &yMin, int &yMax) { int num_images = Images.size(); //std::cout << "length of vector: " << Images.size() << std::endl; //initalize min amd max values xMin = INT_MAX; yMin = INT_MAX; xMax = INT_MIN; yMax = INT_MIN; //printf("[xMin xMax yMin yMax] = [%d, %d, %d, %d]\n", xMin, xMax, yMin, yMax); //initialize matrices for operations Mat proj = Mat::ones(3, 1, CV_64F); Mat corn = Mat::ones(3, 1, CV_64F); Mat trans = Mat::eye(3, 3, CV_64F); vector<Mat> corners(4); //intialize corners for (int i = 0; i < corners.size(); i++) { corners[i] = Mat::ones(3, 1, CV_64F); } //fill in corner vector for (int i = 0; i < num_images; i++) { corners[0].at<double>(0, 0) = 0; corners[0].at<double>(1, 0) = 0; corners[1].at<double>(0, 0) = 0; corners[1].at<double>(1, 0) = Images[i].size().height - 1; corners[2].at<double>(0, 0) = Images[i].size().width - 1;; corners[2].at<double>(1, 0) = 0; corners[3].at<double>(0, 0) = Images[i].size().width - 1;; corners[3].at<double>(1, 0) = Images[i].size().height - 1; //for the corners compute projection and keep track of max and min for (int j = 0; j < corners.size(); j++) { corn.at<double>(0, 0) = corners[j].at<double>(0, 0); corn.at<double>(1, 0) = corners[j].at<double>(1, 0); //compute proj and noramilze proj = transforms[i] * corn; proj /= proj.at<double>(2,0); //updat max and min values for x and y if (proj.at<double>(0, 0) > xMax) { xMax = proj.at<double>(0, 0); } if(proj.at<double>(0,0) < xMin){ xMin = proj.at<double>(0, 0); } if (proj.at<double>(1, 0) > yMax) { yMax = proj.at<double>(1, 0); } if (proj.at<double>(1, 0) < yMin) { yMin = proj.at<double>(1, 0); } } } //fill translation matrix trans.at<double>(0, 2) = -xMin; trans.at<double>(1, 2) = -yMin; //update transformation matrices for (int i = 0; i < num_images; i++) { transforms[i] = trans * transforms[i]; } //cout << trans << endl; //printf("[xMin xMax yMin yMax] = [%d, %d, %d, %d]\n", xMin, xMax, yMin, yMax); } void warpMasks(const vector<Mat> &Images, vector<Mat> &masks_warped, const vector<Mat> &transforms, const Mat &panorama) { int num_images = Images.size(); //std::cout << "length of vector: " << Images.size() << std::endl; //initilaize masks vector<Mat> masks(num_images); for (int i = 0; i < num_images; i++) { //create masks and make warped masks masks[i] = Mat::ones(Images[i].size().height, Images[i].size().width, CV_8U); masks[i].setTo(cv::Scalar::all(255)); warpPerspective(masks[i], masks_warped[i], transforms[i], panorama.size()); //uncomment to save warped masks /*std::ostringstream os; os << "warped_masks_" << i << ".jpg"; imwrite(os.str(), masks_warped[i]);*/ } } void warpImages(const vector<Mat> &Images, const vector<Mat> &masks_warped, const vector<Mat> &transforms, Mat &panorama) { int num_images = Images.size(); //initialize image out matrices vector<Mat> Images_out(num_images); for (int i = 0; i < num_images; i++) { //create warped images warpPerspective(Images[i],Images_out[i],transforms[i],panorama.size(), INTER_LINEAR, BORDER_CONSTANT,1); //copy to panorama Images_out[i].copyTo(panorama,masks_warped[i]); //uncomment to save warped images /*std::ostringstream os; os << "warped_image_" << i << ".jpg"; imwrite(os.str(), Images_out[i]);*/ } //uncomment to save panorama //imwrite("panorma_warped.jpg", panorama); } void BlendImages(const vector<Mat> &Images, Mat &pano_feather, Mat &pano_multiband, const vector<Mat> &masks_warped, const vector<Mat> &transforms) { //create blenders detail::FeatherBlender f_blend; detail::MultiBandBlender mb_blend; //prepare blenders f_blend.prepare(Rect(0, 0, pano_feather.cols, pano_feather.rows)); mb_blend.prepare(Rect(0, 0, pano_feather.cols, pano_feather.rows)); for (int i = 0; i < Images.size(); i++) { Mat image_warped; //warp images, and convert warpPerspective(Images[i], image_warped, transforms[i], pano_feather.size(), INTER_LINEAR, BORDER_REPLICATE, 1); image_warped.convertTo(image_warped, CV_16S); //feed images to blender f_blend.feed(image_warped, masks_warped[i], Point(0, 0)); mb_blend.feed(image_warped, masks_warped[i], Point(0, 0)); } //create empty masks Mat f_empty = Mat::zeros(pano_feather.size(), CV_8U); Mat mb_empty = Mat::zeros(pano_multiband.size(), CV_8U); //blend and convert f_blend.blend(pano_feather, f_empty); mb_blend.blend(pano_multiband, mb_empty); pano_feather.convertTo(pano_feather, CV_8U); pano_multiband.convertTo(pano_multiband, CV_8U); //uncomment to display blended images //imwrite("pano_feather.jpg", pano_feather); //imwrite("pano_multiband.jpg", pano_multiband); }
// #pragma once #ifndef MNODE_H #define MNODE_H #include <vector> #include <iostream> #include <string> #include <queue> #include "utils.h" #include "mJSON.h" using namespace std; // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; Node* buildNode(std::string in); void printNode(Node* node); #endif
class ReverseSolver { public: string Reverse(string str, int from, int to) { if (from < 0 || to >= str.size()) { throw new exception("参数错误!!!"); } string res{}; for (int i = to; i >= from; --i) { res += str[i]; } return res; } string ReverseSentence(string str) { if (str.size() < 1) return ""; int start = 0; string res = ""; for (int i = 0; i < str.size(); ++i) { if (str[i] == ' ') { int end = i - 1; res += Reverse(str, start, end); res += " "; // cout << start << ", " << end << ": " << res << endl; start = i + 1; } if (i == str.size() - 1) { res += Reverse(str, start, i); } } return Reverse(res, 0, res.size() - 1); } void test() { vector<string> test_cases = { "student. a am I" }; for (auto& i : test_cases) { cout << " In <== " << i << endl; cout << "Out ==> " << ReverseSentence(i) << endl; } } };
#ifndef _SPRITE_H_ #define _SPRITE_H_ #include "vector.h" #include "hgeSprite.h" class Sprite { public: Sprite(); ~Sprite(); void GetPosition( Vector2f& outPosition ); void SetPosition( const Vector2f& aNewPosition ); void SetTexture( HTEXTURE aNewTexture, Vector2f& aSize ); hgeSprite* GetRawSprite() { return mySprite; } private: hgeSprite* mySprite; Vector2f myPosition; }; #endif//_SPRITE_H_
/* -*- 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 DOM_STYLESHEETLIST_H #define DOM_STYLESHEETLIST_H #include "modules/dom/src/domobj.h" class DOM_Document; class DOM_Collection; class DOM_StyleSheetList : public DOM_Object { protected: DOM_StyleSheetList(DOM_Document *document); DOM_Document *document; DOM_Collection *collection; public: static OP_STATUS Make(DOM_StyleSheetList *&stylesheetlist, DOM_Document *document); virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_GetState GetIndex(int property_index, ES_Value* value, ES_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_STYLESHEETLIST || DOM_Object::IsA(type); } virtual void GCTrace(); virtual ES_GetState GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime); DOM_DECLARE_FUNCTION(item); enum { FUNCTIONS_ARRAY_SIZE = 2 }; }; #endif // DOM_STYLESHEETLIST_H
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SKLAND_GUI_MOUSE_EVENT_HPP_ #define SKLAND_GUI_MOUSE_EVENT_HPP_ #include "input-event.hpp" #include "../core/point.hpp" #include <wayland-client.h> #include <linux/input-event-codes.h> namespace skland { class Surface; enum MouseButtonType { kMouseButtonLeft = BTN_LEFT, kMouseButtonRight = BTN_RIGHT, kMouseButtonMiddle = BTN_MIDDLE }; enum MouseButtonState { kMouseButtonReleased = WL_POINTER_BUTTON_STATE_RELEASED, /* 0 */ kMouseButtonPressed = WL_POINTER_BUTTON_STATE_PRESSED /* 1 */ }; class MouseEvent : public InputEvent { friend class Input; MouseEvent() = delete; MouseEvent(const MouseEvent &orig) = delete; MouseEvent &operator=(const MouseEvent &other) = delete; public: MouseEvent(Input *input) : InputEvent(input), surface_(nullptr), serial_(0), time_(0), button_(0), state_(0), axis_(0) { } Surface *surface() const { return surface_; } uint32_t serial() const { return serial_; } /** * @brief The X coordinate on wayland surface * @return */ double surface_x() const { return surface_xy_.x; } /** * @brief The Y coordinate on wayland surface * @return */ double surface_y() const { return surface_xy_.y; } double window_x() const { return window_xy_.x; } double window_y() const { return window_xy_.y; } uint32_t button() const { return button_; } uint32_t state() const { return state_; } uint32_t axis() const { return axis_; } private: ~MouseEvent() {} /** The surface this pointer hovers */ Surface *surface_; uint32_t serial_; Point2D surface_xy_; Point2D window_xy_; uint32_t time_; uint32_t button_; uint32_t state_; uint32_t axis_; }; } #endif // SKLAND_GUI_MOUSE_EVENT_HPP_
#include<iostream> #include<vector> #include<queue> #include<assert.h> #include<time.h> #include<algorithm> using namespace std; /*有一组数据,求其中最大的前十个数据*/ #if 0 int main() { srand((unsigned int)time(NULL)); vector<int> vec; for (int i = 0; i < 200000; ++i) { vec.push_back(i); } priority_queue<int,vector<int>,greater<int>> queue; int k = 0; for (; k < 10; ++k) { queue.push(vec[k]); } for (; k < 200000; ++k) { if (vec[k] > queue.top()) { queue.pop(); queue.push(vec[k]); } } while (!queue.empty()) { cout << queue.top() << " "; queue.pop(); } cout << endl; return 0; } #endif /*有一组数据,求其中最小的前十个数据*/ #if 0 int main() { srand((unsigned int)time(NULL)); vector<int> vec; for (int i = 0; i < 200000; ++i) { vec.push_back(i); } priority_queue<int> queue; //默认为大根堆 int k = 0; for (; k < 10; ++k) { queue.push(vec[k]); } for (; k < 200000; ++k) { if (vec[k] < queue.top()) { queue.pop(); queue.push(vec[k]); } } while (!queue.empty()) { cout << queue.top() << " "; queue.pop(); } cout << endl; return 0; } #endif /*有一组数据,求其中第10小的数据*/ #if 0 int main() { srand((unsigned int)time(NULL)); vector<int> vec; for (int i = 0; i < 200000; ++i) { vec.push_back(i); } priority_queue<int> queue; //默认为大根堆 int k = 0; for (; k < 10; ++k) { queue.push(vec[k]); } for (; k < 200000; ++k) { if (vec[k] < queue.top()) { queue.pop(); queue.push(vec[k]); } } cout << queue.top(); cout << endl; return 0; } #endif /*有一个大文件,内存限制200M,找出文件中最大的前十个数字*/ #if 0 int main() { srand((unsigned int)time(NULL)); FILE* fw = fopen("datat.txt", "wb"); if (NULL == fw) { perror("file open fail !"); exit(EXIT_FAILURE); } for (int i = 0; i < 200000; ++i) { int data = rand() % 10000 + 1; fwrite(&data,sizeof(int),1,fw); } fclose(fw); FILE* fr = fopen("datat.txt","rb"); if (NULL == fr) { perror("file open fail !"); exit(EXIT_FAILURE); } const int fileSize = 11; FILE* pFile[fileSize] = { nullptr }; for (int i = 0; i < fileSize; ++i) { char fileName[20]; sprintf(fileName, "datat%d.txt", i + 1); pFile[i] = fopen("fileName", "wb+"); if (NULL == pFile[i]) { perror("file open fail !"); exit(EXIT_FAILURE); } } int data = 0; int fileIndex = 0; while (fread(&data, sizeof(int), 1, fr) > 0) { fileIndex = data % fileSize; fwrite(&data, sizeof(int), 1, pFile[fileIndex]); } int k = 0; priority_queue<int, vector<int>, greater<int>> minHeap; while (k < 10 && fread(&data, sizeof(int), 1, pFile[0]) > 0) { minHeap.push(data); k++; } for (int i = 0; i < fileSize; ++i) { while (fread(&data, sizeof(int), 1, pFile[i]) > 0) { if (data > minHeap.top()) { minHeap.pop(); minHeap.push(data); } } } while(!minHeap.empty()) { cout << minHeap.top() << " "; minHeap.pop(); } cout << endl; for (int i = 0; i < fileSize; ++i) { fclose(pFile[i]); } fclose(fr); return 0; } #endif
#include "Explosion.h" #include "Platy.Game.Core/Util/Util.h" #include <Util/Util.h> namespace Platy { namespace Game { Explosion::Explosion( const float& aParticleMaxSize, const sf::Vector2f& aPosition, const sf::Color& aColor, const size_t& aParticleCount, const float& anIntensity, const float& aLifeTime, const float& someGravity, const bool& shouldFade) : ParticleEmitter( aParticleMaxSize, EOrientation(), aPosition, aColor, aParticleCount, anIntensity, aLifeTime, 0, 0, someGravity, INTENSITY_MODULATION_DIVIDER_EXPLOSION, shouldFade, true) { for (size_t i = 0; i < myParticles.size(); i++) { ResetParticle(i); } } void Explosion::Update(const float& someDeltaTime) { myLifeTime -= someDeltaTime; if (myLifeTime <= 0) { return; } ParticleEmitter::Update(someDeltaTime); } void Explosion::ResetParticle(const size_t& anIndex) { myParticles[anIndex].velocity = Util::DegToVec2(Core::Util::RandFloat(0, 360)); myParticleVertices[anIndex * 4].position = myPosition; ParticleEmitter::ResetParticle(anIndex); } } }
#include "About.h" #include "ui_About.h" // RsaToolbox using namespace RsaToolbox; // Qt #include <QCoreApplication> #include <QMessageBox> About::About(QWidget *parent) : QDialog(parent), ui(new Ui::About) { ui->setupUi(this); this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); initializeLicenses(); ui->licenseCombo->setCurrentIndex(0); ui->licenses->setCurrentIndex(0); QObject::connect(ui->licenseCombo, SIGNAL(currentIndexChanged(int)), ui->licenses, SLOT(setCurrentIndex(int))); #ifdef DEBUG_MODE QMessageBox::warning(this, "Debug warning", "The about window may not display licenses in debug mode."); #endif } About::~About() { delete ui; } QString About::appName() const { return ui->appName->text(); } void About::setAppName(QString name) { ui->appName->setText(name); } QString About::version() const { return ui->version->text(); } void About::setVersion(QString version) { ui->version->setText(version); } QString About::description() const { return ui->description->text(); } void About::setDescription(QString text) { ui->description->setText(text); } QString About::contactInfo() const { return ui->contact->text(); } void About::setContactInfo(QString text) { ui->contact->setText(text); } void About::initializeLicenses() { // R&S QFile file(rsLicensePath()); if (file.open(QFile::ReadOnly)) { ui->rsLicense->setText(file.readAll()); file.close(); } else { ui->rsLicense->clear(); } // Qt file.setFileName(qtLicensePath()); if (file.open(QFile::ReadOnly)) { ui->qtLicense->setText(file.readAll()); file.close(); } else { ui->qtLicense->clear(); } // Msvc file.setFileName(msvcLicensePath()); if (file.open(QFile::ReadOnly)) { ui->msvcLicense->setText(file.readAll()); file.close(); } else { ui->msvcLicense->clear(); } // QuaZIP file.setFileName(quaZipLicensePath()); if (file.open(QFile::ReadOnly)) { ui->quaZipLicense->setText(file.readAll()); file.close(); } else { ui->quaZipLicense->clear(); } // ZLib file.setFileName(zLibLicensePath()); if (file.open(QFile::ReadOnly)) { ui->zLibLicense->setText(file.readAll()); file.close(); } else { ui->zLibLicense->clear(); } // QCustomPlot file.setFileName(qCustomPlotLicensePath()); if (file.open(QFile::ReadOnly)) { ui->qCustomPlotLicense->setText(file.readAll()); file.close(); } else { ui->qCustomPlotLicense->clear(); } } QDir About::licenseDir() { QDir dir(QCoreApplication::applicationDirPath()); dir.cd("Licenses"); return dir; } QString About::rsLicensePath() { QRegExp regexp("^.*R&S.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; } QString About::qtLicensePath() { QRegExp regexp("^.*Qt.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; } QString About::msvcLicensePath() { QRegExp regexp("^.*Microsoft.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; } QString About::quaZipLicensePath() { QRegExp regexp("^.*QuaZip.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; } QString About::zLibLicensePath() { QRegExp regexp("^.*ZLib.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; } QString About::qCustomPlotLicensePath() { QRegExp regexp("^.*QCustomPlot.*(\\.txt)$", Qt::CaseInsensitive); QDir dir = licenseDir(); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); foreach (QString file, files) { if (file.contains(regexp)) return dir.filePath(file); } return ""; }
#include "stdafx.h" #include <math.h> #include "Condition.h" CCondition::CCondition() { } CCondition::~CCondition() { } void CCondition::SetName(const wstring& strName) { m_strCondtionName = strName; } void CCondition::SetAverage(unsigned long ulAverage) { m_ulAverage = ulAverage; } void CCondition::SetRange(unsigned long ulLow, unsigned long ulHigh) { m_range.high = ulHigh*FACTOR; m_range.low = ulLow*FACTOR; } void CCondition::AddContent(int nIndex, unsigned long ulContent, bool bFixed) { m_contentList.push_back(element(nIndex, ulContent, bFixed)); } void CCondition::CalculateH(unsigned long ulSumD) { m_lfH = (double)m_ulAverage / (double)ulSumD * m_lfGroupTotalScore; } void CCondition::SetGroupTotalScore(double lfScore) { m_lfGroupTotalScore = lfScore; } double CCondition::CalculateE(const int nElemCount, const unsigned long* pUlRatioList, const unsigned long* pUlContentIndexList) { unsigned long ulB = 0; for (int i = 0; i < nElemCount; i++) { ulB += pUlRatioList[i] * m_contentList[pUlContentIndexList[i]].m_ulContent; } if (ulB >= m_range.low && ulB <= m_range.high) { return 0; } double lfC = 0; if (ulB < m_range.low) { lfC = (double)(m_range.low - ulB) / (double)m_range.low; } else { lfC = (double)(ulB - m_range.high) / (double)m_range.high; } double lfE = lfC * m_lfH; return lfE; }
#include <iostream> using namespace std; struct BSTNode{ BSTNode*right; BSTNode*left; BSTNode*up; int key; }; void addNode(BSTNode * &tree, int klucz) { BSTNode *newNode=new BSTNode; newNode->right=NULL; newNode->left=NULL; newNode->up=NULL; newNode->key=klucz; if (tree == NULL) { tree = newNode; } else { BSTNode * cp = tree; while (true) { if (newNode->key <= cp->key) { if (cp->left == NULL) break; else cp = cp->left; } else { if (cp->right == NULL) break; else cp = cp->right; } } newNode->up = cp; if (newNode->key <= cp->key) cp->left = newNode; else cp->right = newNode; } } /* void *addNode(BSTNode *&tree,BSTNode *w) { if(tree=NULL) { tree=w; }else{ BSTNode *x=tree; while(true){ if(w->key<=x->key) { if(x->left==NULL) { x->left=w; w->up=x; break; }else{ x=x->left; } }else{ if(x->right==NULL) { x->right=w; w->up=x; break; }else{ x=x->right; } } } } } */ void inorder(BSTNode *tree) { if(tree!=NULL) { inorder(tree->left); cout<<tree->key<<" "; inorder(tree->right); } } int main() { BSTNode *tree=new BSTNode; tree->right=NULL; tree->left=NULL; tree->up=NULL; tree->key=5; addNode(tree,7); addNode(tree,9); addNode(tree,1); addNode(tree,12); addNode(tree,-3); addNode(tree,0); inorder(tree); return 0; }
// GoogleDriveImageTagConverter.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #include <string> using namespace std; #define ERROR_PROC() \ {\ CloseClipboard();\ ::MessageBoxA(NULL, "컨버팅 실패", "Error", MB_OK);\ return 0;\ } int _tmain(int argc, _TCHAR* argv[]) { // 클립보드 정보 읽기 ::OpenClipboard(NULL); HANDLE hClipboard = GetClipboardData(CF_TEXT); if (!hClipboard) ERROR_PROC(); string str = (char*)GlobalLock(hClipboard); CloseClipboard(); const int idx0 = str.find('='); if (string::npos == idx0) ERROR_PROC(); const int idx1 = str.find('&', idx0); if (string::npos == idx1) ERROR_PROC(); // 이미 컨버팅 되었다면, 컨버팅하지 않는다. if (string::npos != str.find("export=view")) { ::MessageBoxA(NULL, "이미 컨버팅 되어서 클립보드에 저장되어 있습니다.", "Msg", MB_OK); return 0; } string imageLink = str.substr(idx0+1, idx1 - idx0 - 1); string cvtURL = "http://drive.google.com/uc?export=view&id=" + imageLink; // 클립보드에 저장 ::OpenClipboard(NULL); EmptyClipboard(); HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, 256); char *mem = (char*)GlobalLock(hglbCopy); strcpy_s(mem, 256, cvtURL.c_str()); GlobalUnlock(hglbCopy); ::SetClipboardData(CF_TEXT, mem); CloseClipboard(); // 변환된 URL을 메세지창에 보여준다. string msg = "클립보드에 새 링크가 복사 되었습니다.\nsrc link = " + str + "\n\n" + "convert link = " + cvtURL; ::MessageBoxA(NULL, msg.c_str(), "Msg", MB_OK); return 0; }
#include "CorrespondSurfaceAndVolumetricTemplate.h" #include "distPoint3Triangle3.h" using std::min; using std::max; using Wm5::computeClosestPoint; CorrespondTemplates::CorrespondTemplates() { meshAligned = false; originalSurfaceTemplate = NULL; rigidlyAlignedSurfaceTemplate = NULL; } CorrespondTemplates::CorrespondTemplates(char * surfTempOriginal, char * surfTempRigidAligned, char * volumetricNodes, char * volumetricElements, int numNodes, int numElements) { originalSurfaceTemplate = new TriangleMesh(); if (!importMeshWrapper(surfTempOriginal,originalSurfaceTemplate)) { cout<<"Problem opening "<<surfTempOriginal<<endl; delete originalSurfaceTemplate; originalSurfaceTemplate = 0; return; } rigidlyAlignedSurfaceTemplate = new TriangleMesh(); if (!importMeshWrapper(surfTempRigidAligned,rigidlyAlignedSurfaceTemplate)) { cout<<"Problem opening "<<surfTempOriginal<<endl; delete rigidlyAlignedSurfaceTemplate; rigidlyAlignedSurfaceTemplate = 0; return; // will leak } int i, intRead1, intRead2, intRead3, intRead4; float floatRead1, floatRead2, floatRead3; FILE * fp = fopen(volumetricNodes, "r"); if(fp == NULL) { cout<<"File "<<volumetricNodes<<" not found"<<endl; return; } for(i = 0; i < numNodes; i++) { fscanf(fp, "%*d %*d %f %f %f ", &floatRead1, &floatRead2, &floatRead3); g_Node * node = new g_Node(); node->coordinate(g_Vector(floatRead1, floatRead2, floatRead3)); volumetricMeshNodes.insert(node); } fclose(fp); fp = fopen(volumetricElements, "r"); if(fp == NULL) { cout<<"File "<<volumetricElements<<" not found"<<endl; return; } for(i = 0; i < numElements; i++) { fscanf(fp, "%*d %*d %*d %d %d %d %d ", &intRead1, &intRead2, &intRead3, &intRead4); vector<int> tetrahedron; tetrahedron.push_back(intRead1-1); tetrahedron.push_back(intRead2-1); tetrahedron.push_back(intRead3-1); tetrahedron.push_back(intRead4-1); allTetrahedra.push_back(tetrahedron); } fclose(fp); meshAligned = false; } CorrespondTemplates::~CorrespondTemplates() { if(originalSurfaceTemplate != NULL) { delete originalSurfaceTemplate; originalSurfaceTemplate = NULL; } if(rigidlyAlignedSurfaceTemplate != NULL) { delete rigidlyAlignedSurfaceTemplate; rigidlyAlignedSurfaceTemplate = NULL; } } void CorrespondTemplates::setAlignedSurface(TriangleMesh * surf) { originalSurfaceTemplate = new TriangleMesh(*surf); rigidlyAlignedSurfaceTemplate = new TriangleMesh(*surf); meshAligned = true; } void CorrespondTemplates::setTetModel(g_NodeContainer meshNodes, vector< vector<int> > allTetrahedra) { volumetricMeshNodes.clear(); for(int i = 0; i < meshNodes.numberOfItems(); i++) volumetricMeshNodes.insert(meshNodes[i]); this->allTetrahedra = allTetrahedra; } void CorrespondTemplates::deformVolumetricMeshRigidly(char * outfile) { if(!meshAligned) { //Align the volumetric mesh using the known alignment of the template mesh computeRigidAlignment(originalSurfaceTemplate, rigidlyAlignedSurfaceTemplate, volumetricMeshNodes); meshAligned = true; } //Export if(outfile != NULL) { FILE * fp = fopen(outfile, "w"); if(fp == NULL) { cout<<"File "<<outfile<<" could not be created"<<endl; return; } for(int i = 0; i < volumetricMeshNodes.numberOfItems(); i++) fprintf(fp, "%d -1 %f %f %f\n", i, volumetricMeshNodes[i]->coordinate().x(), volumetricMeshNodes[i]->coordinate().y(), volumetricMeshNodes[i]->coordinate().z()); fclose(fp); } } bool CorrespondTemplates::computeRigidAlignment(TriangleMesh * originalMesh, TriangleMesh * alignedMesh, g_NodeContainer contToBeAligned) { long int i, numberOfNodes, dimension, dimensionH, lwork, info, determinant; double alpha, beta; char job, trans; bool returnval; numberOfNodes = originalMesh->getNumberOfNodes(); dimension = 3; dimensionH = 4; job = 'A'; trans = 'N'; alpha = 1.0; beta = 0.0; lwork = 2*numberOfNodes; double * work = new double[lwork]; double * A = new double[numberOfNodes * dimensionH]; double * b = new double[numberOfNodes * dimension]; double * S = new double[dimension]; double * U = new double[dimension*dimension]; double * VT = new double[dimension*dimension]; double * R = new double[dimensionH*dimension]; returnval = true; //populate the arrays A and b: for(i = 0; i < numberOfNodes; i++) { A[i] = originalMesh->nodes()[i]->coordinate().x(); A[numberOfNodes + i] = originalMesh->nodes()[i]->coordinate().y(); A[2*numberOfNodes + i] = originalMesh->nodes()[i]->coordinate().z(); A[3*numberOfNodes + i] = 1.0; b[i] = alignedMesh->nodes()[i]->coordinate().x(); b[numberOfNodes + i] = alignedMesh->nodes()[i]->coordinate().y(); b[2*numberOfNodes + i] = alignedMesh->nodes()[i]->coordinate().z(); } //compute an estimate of R: clapack::dgels_(&trans, &numberOfNodes, &dimensionH, &dimension, A, &numberOfNodes, b, &numberOfNodes, work, &lwork, &info); if(info != 0) { cout<<"Problem with estimating R "<<info<<endl; goto align_EXIT; } //make sure that R is a valid matrix (orthonormal): b contains R delete [] work; lwork = max(3 * min(dimension, dimensionH) + max(dimension, dimensionH), 5*min(dimension, dimensionH)); work = new double[lwork]; //only copy 3 by 3 submatrix to R: for(i = 0; i < dimension; i++) { R[i] = b[i]; R[dimension + i] = b[numberOfNodes + i]; R[2*dimension + i] = b[2*numberOfNodes + i]; } //copy the modified version back to b (as help storage) and then to R in the correct order R[10] = R[8]; R[9] = R[7]; R[8] = R[6]; R[6] = R[5]; R[5] = R[4]; R[4] = R[3]; R[3] = b[3]; R[7] = b[numberOfNodes+3]; R[11] = b[2*numberOfNodes+3]; //transform the coordinates: numberOfNodes = contToBeAligned.numberOfItems(); delete [] A; A = new double[numberOfNodes * dimensionH]; //populate the array A: for(i = 0; i < numberOfNodes; i++) { A[i] = contToBeAligned[i]->coordinate().x(); A[numberOfNodes + i] = contToBeAligned[i]->coordinate().y(); A[2*numberOfNodes + i] = contToBeAligned[i]->coordinate().z(); A[3*numberOfNodes + i] = 1.0; } //do the rigid transformation and set it to part: clapack::dgemm_(&trans, &trans, &numberOfNodes, &dimension, &dimensionH, &alpha, A, &numberOfNodes, R, &dimensionH, &beta, b, &numberOfNodes); for(i = 0; i < numberOfNodes; i++) { contToBeAligned[i]->coordinate(g_Vector(b[i], b[numberOfNodes + i], b[2*numberOfNodes + i])); } align_EXIT: delete [] work; delete [] A; delete [] b; delete [] S; delete [] U; delete [] VT; delete [] R; return returnval; } TriangleMesh * CorrespondTemplates::correspondSurface(TriangleMesh * meshToDeform, TriangleMesh * frame, char * exportFilename) { int i, j; double dist, minDist, threshold; g_Vector globallyClosest, closestPoint; threshold = 20.0 * frame->getMeshResolution(); for(i = 0; i < meshToDeform->getNumberOfNodes(); i++) { for(j = 0; j < frame->getNumberOfTriangles(); j++) { // closestPoint = computeClosestPoint(meshToDeform->nodes()[i], frame->elements()[j]); // dist = closestPoint.DistanceTo(meshToDeform->nodes()[i]->coordinate()); g_Vector closestPoint; dist = computeClosestPoint(*meshToDeform->nodes()[i], *frame->elements()[j], closestPoint ); dist = sqrt(dist); if((j == 0) || (dist < minDist)) { minDist = dist; globallyClosest = closestPoint; } } if(minDist < threshold) meshToDeform->nodes()[i]->coordinate(globallyClosest); } exportMeshWrapper(exportFilename, meshToDeform); return meshToDeform; } void CorrespondTemplates::computeMappings(char * outfileMappingTet, char * outfileMappingSurf, g_Node * contactPoint) { //Compute the mappings using barycentric coordinates findSurfaceNodes(); maptet2surfID = surfaceNodes; // output tetmesh surface computeSurface( "tet_mesh_surf.wrl" ); deformVolumetricMeshRigidly(); int i, j, k, numNodesTet, numElemsTet, numNodesSurf, numElemsSurf; double dist, minDist, d, mind, distContactPoint, minDistContactPoint; numNodesTet = volumetricMeshNodes.numberOfItems(); numElemsTet = trianglesOnSurface.size(); numNodesSurf = rigidlyAlignedSurfaceTemplate->getNumberOfNodes(); numElemsSurf = rigidlyAlignedSurfaceTemplate->getNumberOfTriangles(); //First compute the mapping from the tetrahedral mesh to the surface mesh mappingIndicesTet.resize(3*numNodesTet); mappingWeightsTet.resize(3*numNodesTet); offsetsTet.resize(numNodesTet); for(i = 0; i < numNodesTet; i++) { if(surfaceNodes[i] == -1) { mappingIndicesTet[3*i] = mappingIndicesTet[3*i+1] = mappingIndicesTet[3*i+2] = -1; mappingWeightsTet[3*i] = mappingWeightsTet[3*i+1] = mappingWeightsTet[3*i+2] = -1; } else { for(j = 0; j < numElemsSurf; j++) { // g_Vector closestPoint = computeClosestPoint(volumetricMeshNodes[i], rigidlyAlignedSurfaceTemplate->elements()[j]); // dist = closestPoint.DistanceTo(volumetricMeshNodes[i]->coordinate()); g_Vector closestPoint; dist = computeClosestPoint(*volumetricMeshNodes[i], *rigidlyAlignedSurfaceTemplate->elements()[j], closestPoint ); dist = sqrt(dist); if((j == 0) || (dist < minDist)) { minDist = dist; mappingIndicesTet[3*i] = rigidlyAlignedSurfaceTemplate->elements()[j]->nodes()[0]->id()-1; mappingIndicesTet[3*i+1] = rigidlyAlignedSurfaceTemplate->elements()[j]->nodes()[1]->id()-1; mappingIndicesTet[3*i+2] = rigidlyAlignedSurfaceTemplate->elements()[j]->nodes()[2]->id()-1; //---------------------- for(int n = 0; n < 3; n++){ d = volumetricMeshNodes[i]->coordinate().DistanceTo(rigidlyAlignedSurfaceTemplate->elements()[j]->nodes()[n]->coordinate()); if((n == 0) || (d < mind)){ mind = d; maptet2surfID[i] = rigidlyAlignedSurfaceTemplate->elements()[j]->nodes()[n]->id()-1; } } //------------------------ vector<double> barycentrics = computeBarycentrics(volumetricMeshNodes[i]->coordinate(), closestPoint, rigidlyAlignedSurfaceTemplate->elements()[j]); mappingWeightsTet[3*i] = barycentrics[0]; mappingWeightsTet[3*i+1] = barycentrics[1]; mappingWeightsTet[3*i+2] = barycentrics[2]; offsetsTet[i] = barycentrics[3]; } } } } //Export if(outfileMappingTet != NULL) { #if 0 FILE * fp = fopen(outfileMappingTet, "w"); if(fp == NULL) { cout<<"Problem writing "<<outfileMappingTet<<endl; return; } for(i = 0; i < numNodesTet; i++) fprintf(fp, "%d %d %d %f %f %f %f\n", mappingIndicesTet[3*i], mappingIndicesTet[3*i+1], mappingIndicesTet[3*i+2], mappingWeightsTet[3*i], mappingWeightsTet[3*i+1], mappingWeightsTet[3*i+2], offsetsTet[i]); fclose(fp); #else // Make a surface mesh using the tetmesh surface plus the coordinates from the surface mesh computeSurface( outfileMappingTet, true ); #endif } //Second compute the mapping from the surface mesh to the tetrahedral mesh mappingIndicesSurf.resize(3*numNodesSurf); mappingWeightsSurf.resize(3*numNodesSurf); offsetsSurf.resize(numNodesSurf); contactTriangleId.resize(3); contactWeights.resize(3); contactoffset.resize(1); for(i = 0; i < numNodesSurf; i++) { for(j = 0; j < numElemsTet; j++) { g_Element elem; set<int>::iterator triangleIt; for(triangleIt = trianglesOnSurface[j].begin(); triangleIt != trianglesOnSurface[j].end(); triangleIt++) elem.node(volumetricMeshNodes[*triangleIt]); // g_Vector closestPoint = computeClosestPoint(rigidlyAlignedSurfaceTemplate->nodes()[i], &elem); // dist = closestPoint.DistanceTo(rigidlyAlignedSurfaceTemplate->nodes()[i]->coordinate()); g_Vector closestPoint; dist = computeClosestPoint(*rigidlyAlignedSurfaceTemplate->nodes()[i], elem, closestPoint ); dist = sqrt(dist); if((j == 0) || (dist < minDist)) { minDist = dist; k = 0; for(triangleIt = trianglesOnSurface[j].begin(); triangleIt != trianglesOnSurface[j].end(); triangleIt++, k++) mappingIndicesSurf[3*i+k] = *triangleIt; vector<double> barycentrics = computeBarycentrics(rigidlyAlignedSurfaceTemplate->nodes()[i]->coordinate(), closestPoint, &elem); mappingWeightsSurf[3*i] = barycentrics[0]; mappingWeightsSurf[3*i+1] = barycentrics[1]; mappingWeightsSurf[3*i+2] = barycentrics[2]; offsetsSurf[i] = barycentrics[3]; } //--------------------------- if(i == 0 && contactPoint != NULL){ g_Vector closestContactPoint; distContactPoint = computeClosestPoint(*contactPoint, elem, closestContactPoint ); distContactPoint = sqrt(distContactPoint); // g_Vector closestContactPoint = computeClosestPoint(contactPoint, &elem); // distContactPoint = closestContactPoint.DistanceTo(contactPoint->coordinate()); if((j == 0) || (distContactPoint < minDistContactPoint)) { minDistContactPoint = distContactPoint; k = 0; for(triangleIt = trianglesOnSurface[j].begin(); triangleIt != trianglesOnSurface[j].end(); triangleIt++, k++) contactTriangleId[3*i+k] = *triangleIt; vector<double> barycentricsContactPoint = computeBarycentrics(contactPoint->coordinate(), closestContactPoint, &elem); contactWeights[3*i] = barycentricsContactPoint[0]; contactWeights[3*i+1] = barycentricsContactPoint[1]; contactWeights[3*i+2] = barycentricsContactPoint[2]; contactoffset[i] = barycentricsContactPoint[3]; } } //---------------------------- } } //Export if(outfileMappingSurf != NULL) { #if 0 FILE * fp = fopen(outfileMappingSurf, "w"); if(fp == NULL) { cout<<"Problem writing "<<outfileMappingSurf<<endl; return; } for(i = 0; i < numNodesSurf; i++) fprintf(fp, "%d %d %d %f %f %f %f\n", mappingIndicesSurf[3*i], mappingIndicesSurf[3*i+1], mappingIndicesSurf[3*i+2], mappingWeightsSurf[3*i], mappingWeightsSurf[3*i+1], mappingWeightsSurf[3*i+2], offsetsSurf[i]); fclose(fp); #else // Make a surface mesh using the tetmesh surface plus the coordinates from the surface mesh TriangleMesh surfTet; for (int i=0; i<numNodesSurf; ++i ) { // std::cerr << i << " " << std::endl; g_Vector coord = mappingWeightsSurf[3*i] * volumetricMeshNodes[mappingIndicesSurf[3*i]]->coordinate(); coord += mappingWeightsSurf[3*i+1] * volumetricMeshNodes[mappingIndicesSurf[3*i+1]]->coordinate(); coord += mappingWeightsSurf[3*i+2] * volumetricMeshNodes[mappingIndicesSurf[3*i+2]]->coordinate(); surfTet.node(new g_Node( coord )); } // std::cerr << std::endl; g_ElementContainer eleSurf = rigidlyAlignedSurfaceTemplate->elements(); g_NodeContainer newNodes = surfTet.nodes(); for ( g_ElementContainer::const_iterator fIt=eleSurf.begin(); fIt != eleSurf.end(); ++fIt ) { g_Element *ele = new g_Element(); g_NodeContainer faceNodes = (*fIt)->nodes(); for ( g_NodeContainer::const_iterator nIt = faceNodes.begin(); nIt != faceNodes.end(); ++nIt ) { ele->node(newNodes[(*nIt)->id()-1]); } surfTet.element(ele); } exportMeshWrapper( outfileMappingSurf, &surfTet ); #endif } } void CorrespondTemplates::importMappings(char * infileMappingTet, char * infileMappingSurf, int numNodesTet, int numNodesSurf) { int i, intRead1, intRead2, intRead3; float floatRead1, floatRead2, floatRead3, floatRead4; mappingIndicesTet.clear(); mappingWeightsTet.clear(); offsetsTet.clear(); FILE * fp = fopen(infileMappingTet, "r"); if(fp == NULL) { cout<<"Problem reading "<<infileMappingTet<<endl; return; } for(i = 0; i < numNodesTet; i++) { fscanf(fp, "%d %d %d %f %f %f %f ", &intRead1, &intRead2, &intRead3, &floatRead1, &floatRead2, &floatRead3, &floatRead4); mappingIndicesTet.push_back(intRead1); mappingIndicesTet.push_back(intRead2); mappingIndicesTet.push_back(intRead3); mappingWeightsTet.push_back(floatRead1); mappingWeightsTet.push_back(floatRead2); mappingWeightsTet.push_back(floatRead3); offsetsTet.push_back(floatRead4); } fclose(fp); mappingIndicesSurf.clear(); mappingWeightsSurf.clear(); offsetsSurf.clear(); fp = fopen(infileMappingSurf, "r"); if(fp == NULL) { cout<<"Problem reading "<<infileMappingSurf<<endl; return; } for(i = 0; i < numNodesSurf; i++) { fscanf(fp, "%d %d %d %f %f %f %f ", &intRead1, &intRead2, &intRead3, &floatRead1, &floatRead2, &floatRead3, &floatRead4); mappingIndicesSurf.push_back(intRead1); mappingIndicesSurf.push_back(intRead2); mappingIndicesSurf.push_back(intRead3); mappingWeightsSurf.push_back(floatRead1); mappingWeightsSurf.push_back(floatRead2); mappingWeightsSurf.push_back(floatRead3); offsetsSurf.push_back(floatRead4); } fclose(fp); } void CorrespondTemplates::findSurfaceNodes() { int i, numTetNodes; numTetNodes = volumetricMeshNodes.numberOfItems(); surfaceNodes.resize(numTetNodes); for(i = 0; i < numTetNodes; i++) surfaceNodes[i] = -1; trianglesOnSurface.clear(); multiset< set<int> > trianglesInTetrahedralMesh; for(i = 0; i < allTetrahedra.size(); i++) { set<int> triangle1; triangle1.insert(allTetrahedra[i][0]); triangle1.insert(allTetrahedra[i][1]); triangle1.insert(allTetrahedra[i][2]); set<int> triangle2; triangle2.insert(allTetrahedra[i][0]); triangle2.insert(allTetrahedra[i][1]); triangle2.insert(allTetrahedra[i][3]); set<int> triangle3; triangle3.insert(allTetrahedra[i][0]); triangle3.insert(allTetrahedra[i][2]); triangle3.insert(allTetrahedra[i][3]); set<int> triangle4; triangle4.insert(allTetrahedra[i][1]); triangle4.insert(allTetrahedra[i][2]); triangle4.insert(allTetrahedra[i][3]); trianglesInTetrahedralMesh.insert(triangle1); trianglesInTetrahedralMesh.insert(triangle2); trianglesInTetrahedralMesh.insert(triangle3); trianglesInTetrahedralMesh.insert(triangle4); } multiset< set<int> >::iterator it; for(it = trianglesInTetrahedralMesh.begin(); it != trianglesInTetrahedralMesh.end(); it++) { //If a triangle occurs only once, set all of its nodes to be surface nodes if(trianglesInTetrahedralMesh.count(*it) == 1) { set<int>::iterator triangleIt; for(triangleIt = (*it).begin(); triangleIt != (*it).end(); triangleIt++) surfaceNodes[*triangleIt] = 1; trianglesOnSurface.push_back(*it); } } } TriangleMesh * CorrespondTemplates::computeSurface(char * exportFilename, bool useMapping) { int i, j, counter, numTetNodes; TriangleMesh * resultMesh = new TriangleMesh(); vector<int> surfaceIds; //Find the surface: findSurfaceNodes(); numTetNodes = volumetricMeshNodes.numberOfItems(); surfaceIds.resize(numTetNodes); g_NodeContainer nodesSurf; if ( useMapping ) nodesSurf = rigidlyAlignedSurfaceTemplate->nodes(); //Add the nodes: counter = 0; for(i = 0; i < numTetNodes; i++) { if(surfaceNodes[i] == -1) surfaceIds[i] = -1; else { surfaceIds[i] = counter; counter++; g_Vector coord; if ( useMapping ) { coord = mappingWeightsTet[3*i] * nodesSurf[mappingIndicesTet[3*i]]->coordinate(); coord += mappingWeightsTet[3*i+1] * nodesSurf[mappingIndicesTet[3*i+1]]->coordinate(); coord += mappingWeightsTet[3*i+2] * nodesSurf[mappingIndicesTet[3*i+2]]->coordinate(); } else { coord = volumetricMeshNodes[i]->coordinate(); } g_Node * newNode = new g_Node(coord); resultMesh->node(newNode); } } //Add the triangles (find the correct orientation): for(i = 0; i < trianglesOnSurface.size(); i++) { g_Element * elem = new g_Element(); for(j = 0; j < allTetrahedra.size(); j++) { set<int> triangle; triangle.insert(allTetrahedra[j][0]); triangle.insert(allTetrahedra[j][1]); triangle.insert(allTetrahedra[j][2]); if(trianglesOnSurface[i] == triangle) { elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][0]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][2]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][1]]]); break; } triangle.clear(); triangle.insert(allTetrahedra[j][0]); triangle.insert(allTetrahedra[j][1]); triangle.insert(allTetrahedra[j][3]); if(trianglesOnSurface[i] == triangle) { elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][0]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][1]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][3]]]); break; } triangle.clear(); triangle.insert(allTetrahedra[j][0]); triangle.insert(allTetrahedra[j][2]); triangle.insert(allTetrahedra[j][3]); if(trianglesOnSurface[i] == triangle) { elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][0]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][3]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][2]]]); break; } triangle.clear(); triangle.insert(allTetrahedra[j][1]); triangle.insert(allTetrahedra[j][2]); triangle.insert(allTetrahedra[j][3]); if(trianglesOnSurface[i] == triangle) { elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][1]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][2]]]); elem->node(resultMesh->nodes()[surfaceIds[allTetrahedra[j][3]]]); break; } } resultMesh->element(elem); } //Export: if(exportFilename != NULL) { exportMeshWrapper(exportFilename, resultMesh); } return resultMesh; } /* g_Vector CorrespondTemplates::computeClosestPoint(g_Node * vertex, g_Element * triangle) { //Check the projection if it is in the triangle: g_Plane plane(triangle->nodes()[0]->coordinate(), triangle->nodes()[1]->coordinate(), triangle->nodes()[2]->coordinate()); g_Vector projection = plane.project(vertex->coordinate()); g_Vector pos = vertex->coordinate(); vector<double> bCoord = computeBarycentrics(pos,projection,triangle); g_Vector closestPoint; bCoord[0] = (sgn(bCoord[0]) == 0)?1e-39:bCoord[0]; bCoord[1] = (sgn(bCoord[1]) == 0)?1e-39:bCoord[1]; bCoord[2] = (sgn(bCoord[2]) == 0)?1e-39:bCoord[2]; if ( bCoord[0] > 0 && bCoord[1] > 0 && bCoord[2] > 0 ) { // Point projects inside closestPoint = projection; } else { if ( bCoord[0] * bCoord[1] * bCoord[2] < 0 ) { // Closest to an edge -- or vertex; closestPoint calculation likely not correct if ( bCoord[0] < 0 ) { float scale = 1.0 / (bCoord[1] + bCoord[2]); closestPoint = scale * bCoord[1] * triangle->nodes()[1]->coordinate() + scale * bCoord[2] * triangle->nodes()[2]->coordinate(); } else { if ( bCoord[1] < 0 ) { float scale = 1.0 / (bCoord[0] + bCoord[2]); closestPoint = scale * bCoord[0] * triangle->nodes()[0]->coordinate() + scale * bCoord[2] * triangle->nodes()[2]->coordinate(); } else { if ( bCoord[2] < 0 ) { float scale = 1.0 / (bCoord[1] + bCoord[0]); closestPoint = scale * bCoord[1] * triangle->nodes()[1]->coordinate() + scale * bCoord[0] * triangle->nodes()[0]->coordinate(); } } } } else { // We are closest to a vertex if ( bCoord[0] > 0 ) { closestPoint = triangle->nodes()[0]->coordinate(); } else { if ( bCoord[1] > 0 ) { closestPoint = triangle->nodes()[1]->coordinate(); } else { if ( bCoord[2] > 0 ) closestPoint = triangle->nodes()[0]->coordinate(); } } } } return closestPoint; } */ /* g_Vector CorrespondTemplates::computeClosestPoint(g_Node * vertex, g_Element * triangle) { int i, turn1, turn2, turn3; double dot, dist, minDist; g_Vector closestPoint, projection; //Check the three vertices for(i = 0; i < 3; i++) { dist = vertex->coordinate().DistanceTo(triangle->nodes()[i]->coordinate()); if((i == 0) || (dist < minDist)) { minDist = dist; closestPoint = triangle->nodes()[i]->coordinate(); } } //Check the projection if it is in the triangle: g_Plane plane(triangle->nodes()[0]->coordinate(), triangle->nodes()[1]->coordinate(), triangle->nodes()[2]->coordinate()); projection = plane.project(vertex->coordinate()); dot = (triangle->nodes()[1]->coordinate()-triangle->nodes()[0]->coordinate()).Cross(projection-triangle->nodes()[1]->coordinate()).Dot(plane.normal()); if(dot < 0) turn1 = -1; else turn1 = 1; dot = (triangle->nodes()[2]->coordinate()-triangle->nodes()[1]->coordinate()).Cross(projection-triangle->nodes()[2]->coordinate()).Dot(plane.normal()); if(dot < 0) turn2 = -1; else turn2 = 1; dot = (triangle->nodes()[0]->coordinate()-triangle->nodes()[2]->coordinate()).Cross(projection-triangle->nodes()[0]->coordinate()).Dot(plane.normal()); if(dot < 0) turn3 = -1; else turn3 = 1; if(turn1 == turn2 && turn2 == turn3) { dist = vertex->coordinate().DistanceTo(projection); if(dist < minDist) { minDist = dist; closestPoint = projection; } } return closestPoint; } */ vector<double> CorrespondTemplates::computeBarycentrics( g_Vector& coordinate, g_Vector& coordinateOnSurface, g_Element * triangle) { double areaABC, areaPBC, areaPCA; vector<double> barycentrics; g_Vector normal = (triangle->nodes()[1]->coordinate()-triangle->nodes()[0]->coordinate()).Cross(triangle->nodes()[2]->coordinate()-triangle->nodes()[0]->coordinate()); normal.Normalize(); // Compute twice area of triangle ABC areaABC = normal.Dot((triangle->nodes()[1]->coordinate()-triangle->nodes()[0]->coordinate()).Cross(triangle->nodes()[2]->coordinate()-triangle->nodes()[0]->coordinate())); // Compute barycentrics areaPBC = normal.Dot((triangle->nodes()[1]->coordinate()-coordinateOnSurface).Cross(triangle->nodes()[2]->coordinate()-coordinateOnSurface)); barycentrics.push_back(areaPBC / areaABC); areaPCA = normal.Dot((triangle->nodes()[2]->coordinate()-coordinateOnSurface).Cross(triangle->nodes()[0]->coordinate()-coordinateOnSurface)); barycentrics.push_back(areaPCA / areaABC); barycentrics.push_back(1.0 - barycentrics[0] - barycentrics[1]); // Compute the normal offset g_Vector projectedPoint = barycentrics[0]*triangle->nodes()[0]->coordinate() + barycentrics[1]*triangle->nodes()[1]->coordinate() + barycentrics[2]*triangle->nodes()[2]->coordinate(); projectedPoint = projectedPoint - coordinate; barycentrics.push_back(normal.Dot(projectedPoint)); return barycentrics; }
#include "cellogram/point_source_detection.h" #include <string> #include <iostream> #include <fstream> #include <vector> #include <Eigen/Dense> #include <igl/list_to_matrix.h> #include <igl/Timer.h> bool load_img(const std::string & path, Eigen::MatrixXd &res) { std::fstream file; file.open(path.c_str()); if (!file.good()) { std::cerr << "Failed to open file : " << path << std::endl; file.close(); return false; } std::string s; std::vector<std::vector<double>> matrix; while (getline(file, s)) { std::stringstream input(s); double temp; matrix.emplace_back(); std::vector<double> &currentLine = matrix.back(); while (input >> temp) currentLine.push_back(temp); } if (!igl::list_to_matrix(matrix, res)) { std::cerr << "list to matrix error" << std::endl; file.close(); return false; } return true; } int main(int argc, char** argv) { Eigen::MatrixXd img; const double sigma = 2; Eigen::MatrixXd V; Eigen::MatrixXd V_std; Eigen::VectorXd pval_Ar; const std::string root = DATA_DIR; load_img(root + "1-1.txt", img); double min = img.minCoeff(); double max = img.maxCoeff(); Eigen::MatrixXd imgNorm; imgNorm = (img.array() - min) / (max - min); cellogram::DetectionParams params; cellogram::point_source_detection(imgNorm, sigma, 0.5, V, params); std::cout << V << std::endl; std::cout << params.std_x << std::endl; return 0; }
#include <stdio.h> int main() { int i, space, rows, k=0; printf("Enter number of rows: "); scanf("%d",&rows); printf("\nPrinting....\n"); for(i=0; i<rows; i++,k=0) { for(space=0; space<rows-i; space++) { printf(" "); } while(k<=2*i) { printf("* "); ++k; } printf("\n"); } return 0; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "calendar.h" #include "editwindow.h" #include "deletedialogue.h" #include "settingswindow.h" #include "notelistwindow.h" #include "note.h" #include "notebook.h" #include "memory" #include "settings.h" enum class DeleteOption{One, Outdated, All}; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); signals: void noteDeleted(); void noteEdited(); public slots: void openEditWindow(Note * const note = nullptr); void openSettingsWindow(); void openAllNotesWindow(); void openAboutWindow(); void openDeleteDialogue(); int showDeleteMessageBox(const DeleteOption op); void showNotes(); void showClosestNote(); void addNote(Note * const note); void saveNotes(); void deleteNoteFromListWindow(Note * const note); void deleteAll(); void deleteOutdated(); void setChanged(); int showExitWOSavingMessageBox(); protected: void closeEvent(QCloseEvent *event); private slots: void switchButtons(); void resizeMe(); void closeProgram(); void showFromTray(); void showTrayMessage(); void deleteNote(Note * const note); void deleteNotes(std::shared_ptr<QList<Note*>> noteList); void iconActivated(QSystemTrayIcon::ActivationReason reason); private: void setUI(); void moveToCenter(QWidget * const window); void createMenu(); void createTrayIcon(); void createStatusBar(); void createButtonLayout(); void createCalendar(); void createScrollArea(); void addNoteLabel(); void resizeTimer(); bool isChanged; bool isClosing; std::shared_ptr<Notebook> notes; std::shared_ptr<Settings> settings; //Interface QList<QLabel*> noteLabels; QHBoxLayout *mainLayout; QVBoxLayout *leftLayout; QVBoxLayout *buttonsLayout; Calendar *cal; QPushButton *addButton; QPushButton *editButton; QPushButton *removeButton; QPushButton *todayButton; QPushButton *quitButton; QLabel *noteTextTitle; QScrollArea *scrollArea; QVBoxLayout *scrollLayout; QLabel *statusLabel; QSystemTrayIcon *trayIcon; QMenu *trayIconMenu; QAction *quitAction; QAction *notificationsAction; QAction *openAction; QTimer *trayTimer; }; #endif // MAINWINDOW_H
#pragma once #include <SFML/Graphics.hpp> using namespace sf; //! Klasa Scaleable. /*! Klasa reprezentująca obiekt gry tj. pionek i plansza */ class Scaleable { protected: /* textura danego obiektu*/ Texture texture; /* rozmiar danego obiektu*/ Vector2f size; /* skala danego obiektu*/ Vector2f scale; /* pozycja danego obiektu*/ Vector2f position; /* rozmiar tekstury danego obiektu*/ Vector2u textureSize; /* sprite danego obiektu*/ Sprite sprite; public: //! Metoda sluzuca do pobrania textury /*! \brief Metoda sluzuca do pobrania textury obiektu */ Texture getTexture(); //! Metoda sluzuca do pobrania rozmiaru /*! \brief Metoda sluzuca do pobrania rozmaiaru obiektu */ Vector2f getSize(); //! Metoda sluzuca do pobrania skali /*! \brief Metoda sluzuca do pobrania skali obiektu */ Vector2f getScale(); //! Metoda sluzuca do pobrania pozycji /*! \brief Metoda sluzuca do pobrania pozycji obiektu */ Vector2f getPosition(); //! Metoda sluzuca do ustawnienia textury /*! \brief Metoda sluzuca do ustawienia textury t dla obiektu \param t textura obiektu */ void setTexture(Texture t); //! Metoda sluzuca do rozmiaru obiektu /*! \brief Metoda sluzuca do ustawienia rozmiaru s dla obiektu \param s rozmiar obiektu */ void setSize(Vector2f s); //! Metoda sluzuca do ustawnienia sklai /*! \brief Metoda sluzuca do ustawienia skali s dla obiektu \param s skala obiektu */ void setScale(Vector2f); //! Metoda sluzuca do ustawnienia pozycji /*! \brief Metoda sluzuca do ustawienia pozycji p dla obiektu \param p textura obiektu */ void setPosition(Vector2f p); //! Metoda sluzuca do stworzenia sprite'a obiektu /*! \brief Metoda sluzuca do stworzenia sprite'a obiektu */ Sprite createSprite(); //! Czysta metoda wirtualna sluzuca do oblicznia skali obiektu /*! \brief Czysta metoda wirtualna sluzuca do oblicznia skali obiektu na podsatwie szerokosci s i wysokosci h \param s szerokosc \param h wysokosc */ virtual Vector2f calculateScale(float s, float h) = 0; };
#ifndef COVARIANCE_H #define COVARIANCE_H #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include "common.h" #include "hyperspherical.h" #include "cdmSpectrum.h" #include "cosmology.h" #include "cosmometry.h" #include "growth.h" #include "survey.h" /** * Calculation of auto- and cross-spectra for cosmic shear and the integrated Sachs-Wolfe effect. k-integrations are performed as matrix multiplications (corresponding to a trapezoidal rule). * For radial integrals involving spherical Bessel functions, a Levin algorithm is used. Bessel functions are evaluated with CLASS; due to the CLASS structure, l-modes are referred to mostly by their * index in an array, not the actual wavenumber. The iSW calculation is optional. */ class covariance { private: static const double z_min, z_max; // lower and upper limit for z integration static const int nz; // number of subintervals for z integration double ki_min, ki_max; // borders for k-integration static const int ni; // number of points for k-integration double* ki; // k-steps for integration survey* obs; // pointer to survey parameters, including fiducial cosmology growth* structure; // structure formation quantities, including matter power spectrum and growth function cosmometry* cosmo; // true cosmology (<-> fiducial) HyperInterpStruct* pHIS; // pointer to struct for CLASS Bessel functions int l_index; // index of the wavenumber in the struct int nk; // number of k-steps double k_min, k_max; // k-range double* k; // k-steps double chi_min_fiducial, chi_max_fiducial; // comoving distance to the minimum and maximum redshift in the fiducial cosmology double chi_min, chi_max; // distances in the true cosmology int nc; // size of the covariance matrix (=nk for lensing only, =nk+1 for added iSW) double **signal; // arrays storing the signal and noise parts of the covariance double **noise; public: /** * Constructor initializing pointers (only!). The booleans determine if iSW information is included and if Class is used to calculate the power spectrum. By default, k-modes are spaced linearly. * (This may be adjusted later when calling calculate_signal and calculate_noise.) */ covariance (int size, double min, double max, survey* sv, cosmoParams cp, bool isw=false, bool cls=true); /** * Destructor. */ ~covariance (); /** * Calculates the covariance matrix for the given mode. Note that l is the index of the mode in the array, not the wavenumber itself. The k-steps are linearly spaced, as set in the constructor, * unless modified by a call to set_k. */ void calculate_signal (HyperInterpStruct* pBIS, int L); /** * Calculates the covariance matrix for the given mode in the specified k-range. Note that l is the index of the mode in the array, not the wavenumber itself. k-modes are * linearly equidistant unless last argument is set to true for logarithmic spacing. They are returned to the constructor settings at the end of the function. */ void calculate_signal (HyperInterpStruct* pBIS, int L, double kmin, double kmax, bool logarithmic=false); /** * Calculates the noise matrix for the given mode in the specified k-range. Note that l is the index of the mode in the array, not the wavenumber itself. The k-steps are spaced * linearly, as set in the constructor, unless modified by a call to set_k. */ void calculate_noise (HyperInterpStruct* pBIS, int L); /** * Calculates the noise matrix for the given mode in the specified k-range. Note that l is the index of the mode in the array, not the wavenumber itself. k-modes are * linearly equidistant unless last argument is set to true for logarithmic spacing - the setting should obviously be the same as for the signal. They are reset * to the default spacing at the end of the function. */ void calculate_noise (HyperInterpStruct* pBIS, int L, double kmin, double kmax, bool logarithmic=false); /** * \f[G_l(k_1,k_2)=\int\mathrm{d}z\,\bar{n}_z(z)F_l(z,k_1)U_l(z,k_2)\f], * solved using a composite Simpson's rule. */ void calculate_G (gsl_matrix* Gl); /** * Width of a subinterval in the z-integration. */ double z_step (); /** * Returns the i-th step in the z-integration. */ double get_z (int i); /** * Sets an angular mode l (but does not perform signal or noise calculations). */ void set_l (HyperInterpStruct* pBIS, int L); /** * Calculates n linearly or logarithmically equidistant k-values between (and including) the given limits. */ void set_k (double K[], int n, double min, double max, bool logarithmic=false); /** * Returns the array holding the radial wavenumbers. */ void get_k (double K[]); /** * Returns the ij-entry of the covariance matrix (signal only). */ double C (int i, int j) const; /** * Returns the ij-entry of the noise matrix. */ double R (int i, int j) const; /** * Returns the noise term of the lensing covariance between the two specified modes, * \f[N_l(k_1,k_2)=\frac{\sigma_{\epsilon}^2}{2\pi^2}\int\frac{\mathrm{d}\chi^0}{\chi_{\mathrm{H}}}n(z_p)E^0(z_p)j_l(k_1\chi^0)j_l(k_2\chi^0).\f] * Flag is 1 if the Levin integration fails to converge, 0 otherwise. * Points is the number of the subintervals used in the integration. */ double N (double k1, double k2, int& flag, int& points); double N (double k1, double k2); /** * Integration kernel for the noise term. */ double N_kernel (double chi0); /** * Static (GSL-compatible) implementation of the noise kernel. */ static double N_kernel_stat (double chi0, void* pp); /** * \f[F_l(z,k)=\int\frac{\mathrm{d}\chi^0}{\chi_{\mathrm{H}}}p(z_p,z)j_l(k\chi^0)\f]. * Flags is set to 0 initially and 1 if the integration fails. Points is the number of subintervals used. */ double F (double z, double k, int& flags, int& points); double F (double z, double k); /** * Kernel for the above integral. */ double F_kernel (double chi0, double z); /** * Static implementation of the kernel. */ static double F_kernel_stat (double chi, void* pp); /** * \f[U_l(z,k)=\int_0^{\chi(z)}\mathrm{d}\chi^{\prime}\,\frac{\chi-\chi^{\prime}}{\chi\chi^{\prime}}\frac{D_+(a)}{a}j_l(k\chi)\f]. * Flags is set to 0 initially and 1 if the integration fails. Points is the number of subintervals used. */ double U (double z, double k, int& flags, int& points); double U (double z, double k); /** * Kernel for the above integral. */ double U_kernel (double chi, double chi_z); /** * Static implementation of the kernel. */ static double U_kernel_stat (double chi, void* pp); /** * Weight function for the iSW effect: * \f[w(\chi)=E(a)\frac{\partial}{\partial a}\frac{D_+(a)}{a}.\f] */ double w (double chi); /** * Static implementation of \f$w(\chi)\f$. */ static double w_stat (double chi, void* pp); /** * Coefficient for the expansion of the iSW weight function in spherical Bessel functions, * \f[W_l(k)=\frac{2}{\chi_{\mathrm{H}}}\int_0^{\chi_{\mathrm{H}}}\mathrm{d}\chi\,w(\chi)j_l(k\chi).\f] */ double W (double k, int& flag, int& points); double W (double k); /** * iSW auto-spectrum calculated with the Limber approximation. */ double Limber (int L); /** * Integration kernel for the iSW auto-spectrum calculated with the Limber approximation. */ static double limber_kernel (double chi, void* pp); /** * Returns the linear matter power spectrum (at z=0) at wavenumber k. */ double P_delta (double k); }; // for integration kernels: pointer to covariance object and additional (floating-point) parameter, e. g. k or z struct integral_params { covariance* cv; double a; }; #endif
#include <iostream> #include <vector> #include <queue> using namespace std; class Node{ public: int inDegree = 0; bool next[501] = {false, }; }; vector<string> strRet; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); int testCase; cin >> testCase; for(int tc = 1; tc <= testCase; tc++){ int n; cin >> n; int nums[n+1]; Node node[n+1]; for(int i = 1; i <= n; i++){ cin >> nums[i]; } //작년 순위대로 DAG 그래프작성. for(int i = 1; i <= n-1; i++){ for(int j = i+1; j <= n; j++){ node[nums[i]].next[nums[j]] = true; node[nums[j]].inDegree++; } } // cout << "Node status-----------" << endl; // for(int i = 1; i <= n; i++){ // cout << "node : " << i << " / inDegree : " << node[i].inDegree << endl; // cout << "next : "; // for(int j = 1; j <= n; j++){ // if(node[i].next[j]){ // cout << j << " "; // } // } // cout << endl; // } int cCase; cin >> cCase; //올해 바뀐순위정보 그래프 갱신. for(int i = 1; i <= cCase; i++){ int a, b; cin >> a >> b; if(node[a].next[b] == true){ //원래 a가 b보다 컸던경우 node[a].next[b] = false; node[b].inDegree--; node[b].next[a] = true; node[a].inDegree++; }else{ //원래 b가 a보다 컸던경우 node[b].next[a] = false; node[a].inDegree--; node[a].next[b] = true; node[b].inDegree++; } } // cout << "Node Changed status-----------" << endl; // for(int i = 1; i <= n; i++){ // cout << "node : " << i << " / inDegree : " << node[i].inDegree << endl; // cout << "next : "; // for(int j = 1; j <= n; j++){ // if(node[i].next[j]){ // cout << j << " "; // } // } // cout << endl; // } //갱신된 Node정보를 가지고 topologySort 실행 //만약 한번 진행할때 inDegree가 0인 값이 두번나오면 //확실한 순위를 찾을 수 없으므로 ? 출력 //topolotySort를 마치고 사이즈가 안나올때(사이클이 돔) //()사이클이 돈다는 것은 크기관계가 먹고 먹힌다는 것이다 - IMPOSSIBLE) //위의 두 상황에 걸치지 않으면 정상 출력. queue<int> q; //첫 인풋정함 bool flag = true; bool isOverlap = false; for(int i = 1; i <= n; i++){ if(node[i].inDegree == 0){ if(flag){ //cout << "start : " << i << endl; q.push(i); flag = false; }else{ //한번 초기 q를 설정했는데 또 inDegree가 0인 것이 있다. //확실한 순위를 찾을 수 없음 strRet.push_back("?"); //cout << "?" << endl; isOverlap = true; break; } } } if(isOverlap){ //중복된순간 그냥 다음으로 넘어감. continue; } vector<int> ret; while(!q.empty()){ int curIndex = q.front(); //cout << curIndex << " "; ret.push_back(curIndex); q.pop(); flag = true; isOverlap = false; for(int i = 1; i <= n; i++){ if(node[curIndex].next[i]){ if(--node[i].inDegree == 0){ if(flag){ q.push(i); flag = false; }else{ strRet.push_back("?"); //cout << "?" << endl; isOverlap = true; break; } } } } if(isOverlap){ break; } } if(isOverlap){ continue; } if(ret.size() == n){ //정상 출력 string tp = ""; for(auto it = ret.begin(); it != ret.end(); it++){ tp += to_string(*it)+" "; //cout << *it << " "; } strRet.push_back(tp); //cout << endl; }else{ //Cycle이 돌아서 ret을 다 채우지 못함. //불가능함 모순발생 strRet.push_back("IMPOSSIBLE"); //cout << "IMPOSSIBLE" << endl; } } for(auto it = strRet.begin(); it != strRet.end(); it++){ cout << *it << '\n'; } return 0; }
#pragma once // ADD_DLG 对话框 class ADD_DLG : public CDialogEx { DECLARE_DYNAMIC(ADD_DLG) public: ADD_DLG(CWnd* pParent = NULL); // 标准构造函数 virtual ~ADD_DLG(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG2 }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString name1; CString number1; CString major1; CString sex1; CString birth; double phone1; CString home1; CString pic1; };
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; using Graph = vector<vector<int>>; const double PI = 3.14159265358979323846; const ll MOD = 1000000007; const int INF = 1e9; const int dx[4] = {1,0,-1,0}; const int dy[4] = {0,1,0,-1}; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } int main(){ int N; cin >> N; vector<int>A(N); rep(i,N)cin >> A[i]; vector<int>dp(N,INF); dp[0] = 0; for(int i = 1; i < N; i++){ chmin(dp[i],dp[i-1] + abs(A[i-1] - A[i])); if(i > 1)chmin(dp[i],dp[i-2] + abs(A[i-2] - A[i])); } cout << dp[N-1] << endl; return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "TestController.h" #include <Platform.h> #include <geometry/Ring.h> #include <model/static/Ring.h> #include "geometry/Point.h" #include "TestView.h" #include <stdint.h> #include "delaunay/DelaunayTriangulation.h" /*##########################################################################*/ /** * */ template<typename T> struct my_voronoi_diagram_traits { typedef T coordinate_type; typedef boost::polygon::voronoi_cell<coordinate_type> cell_type; typedef boost::polygon::voronoi_vertex<coordinate_type> vertex_type; typedef boost::polygon::voronoi_edge<coordinate_type> edge_type; // This copes with degenerations. typedef struct { bool operator() (const vertex_type& v1, const vertex_type& v2) const { return false; } } vertex_equality_predicate_type; }; /** * */ typedef boost::polygon::voronoi_diagram<double, my_voronoi_diagram_traits <double> > my_voronoi_diagram; /*##########################################################################*/ namespace boost { namespace polygon { template <> struct geometry_concept<Geometry::Point> { typedef point_concept type; }; template<> struct point_traits<Geometry::Point> { typedef int coordinate_type; /* * TODO sprawdzić jak często to się wykonuje i skąd. Jak tylko w kroku inicjacji, to OK. * Dał bym tutaj też mnożnik, żeby uniknąć sytuacji, kiedy dwa zmiennoprzecinkowe punkty * wejściowe, które są bardzo blisko siebie zostaną przez poniższy get zwróceone jako * ten sam punkt. Można albo mnożyć przez stała (np 1000), albo znaleźć najmniejszą różnicę * mięczy dwoma współrzednymi w danych wejściowych i przeskalować je odpowiednio. */ static inline coordinate_type get (const Geometry::Point& point, orientation_2d orient) { return (orient == HORIZONTAL) ? boost::math::iround (point.x) : boost::math::iround (point.y); } }; } } //std::ostream &operator<< (std::ostream &o, TriangleVector const &e) //{ // size_t cnt = 0; // for (TriangleVector::const_iterator i = e.begin (); i != e.end (); ++i, ++cnt) { // o << cnt << ". " << *i << " A="; // // if (i->A) { // o << *(i->A); // } // else { // o << "NULL"; // } // // o << " B="; // // if (i->B) { // o << *(i->B); // } // else { // o << "NULL"; // } // // o << " C="; // // if (i->C) { // o << *(i->C); // } // else { // o << "NULL"; // } // // o << "\n"; // } // // return o; //} // //std::ostream &operator<< (std::ostream &o, TrianglePtrVector const &e) //{ // size_t cnt = 0; // for (TrianglePtrVector::const_iterator i = e.begin (); i != e.end (); ++i, ++cnt) { // o << **i; // // if (i + 1 != e.end ()) { // o << " | "; // } // } // // return o; //} // //std::ostream &operator<< (std::ostream &o, TriangleIndex const &e) //{ // size_t cnt = 0; // for (TriangleIndex::const_iterator i = e.begin (); i != e.end (); ++i, ++cnt) { // TrianglePtrVector const &trianglesForPoint = *i; // // for (TrianglePtrVector::const_iterator k = trianglesForPoint.begin (); k != trianglesForPoint.end (); ++k) { // o << cnt << " : " << **k; // // if (k + 1 != trianglesForPoint.end ()) { // o << " | "; // } // } // // o << "\n"; // } // // return o; //} /*##########################################################################*/ /** * Input must be in COUNTER CLOCKWISE order. */ class VoronoiRenderer { public: VoronoiRenderer (const Geometry::Ring& i, Geometry::LineString* v) : input(i), voronoi(v) { } void construct (); // TODO do usunięcia lub przeniesienia. typedef double coordinate_type; typedef my_voronoi_diagram::vertex_type vertex_type; typedef my_voronoi_diagram::edge_type edge_type; typedef my_voronoi_diagram::cell_type cell_type; typedef Geometry::Point point_type; private: void clipInfiniteEdge (const edge_type& edge, std::vector<point_type>* clipped_edge) const; private: const Geometry::Ring &input; Geometry::LineString *voronoi; }; /****************************************************************************/ void VoronoiRenderer::construct () { my_voronoi_diagram vd; #ifndef NDEBUG boost::timer::cpu_timer t0; #endif construct_voronoi (input.begin (), input.end (), &vd); #ifndef NDEBUG printlog ("Voronoi diagram construction time : %f ms", t0.elapsed ().wall / 1000000.0); #endif boost::timer::cpu_timer t1; int result = 0; for (my_voronoi_diagram::const_edge_iterator it = vd.edges ().begin (); it != vd.edges ().end (); ++it) { if (it->is_primary ()) { ++result; my_voronoi_diagram::vertex_type const *v0 = it->vertex0 (); my_voronoi_diagram::vertex_type const *v1 = it->vertex1 (); if (it->is_infinite ()) { std::vector<point_type> samples; clipInfiniteEdge (*it, &samples); voronoi->push_back (samples[0]); voronoi->push_back (samples[1]); } else { voronoi->push_back (Geometry::makePoint (v0->x (), v0->y ())); voronoi->push_back (Geometry::makePoint (v1->x (), v1->y ())); } } } #ifndef NDEBUG printlog ("Triangulation time (derived from voronoi as its dual) : %f ms", t1.elapsed ().wall / 1000000.0); printlog ("Voronoi prim. edges : %d", result); // std::cout << edgeFans << std::endl; #endif } /** * Implementation based on BOOST. */ void VoronoiRenderer::clipInfiniteEdge (const edge_type& edge, std::vector<point_type>* clipped_edge) const { const cell_type& cell1 = *edge.cell (); const cell_type& cell2 = *edge.twin ()->cell (); point_type origin, direction; // Infinite edges could not be created by two segment sites. if (cell1.contains_point () && cell2.contains_point ()) { point_type const &p1 = input[cell1.source_index ()]; point_type const &p2 = input[cell2.source_index ()]; origin.x = (p1.x + p2.x) * 0.5; origin.y = (p1.y + p2.y) * 0.5; direction.x = p1.y - p2.y; direction.y = p2.x - p1.x; } // coordinate_type side = xh (brect_) - xl (brect_); coordinate_type side = 200; coordinate_type koef = side / (std::max) (fabs (direction.x), fabs (direction.y)); if (edge.vertex0 () == NULL) { clipped_edge->push_back (Geometry::makePoint (origin.x - direction.x * koef, origin.y - direction.y * koef)); } else { clipped_edge->push_back (Geometry::makePoint (edge.vertex0 ()->x (), edge.vertex0 ()->y ())); } if (edge.vertex1 () == NULL) { clipped_edge->push_back (Geometry::makePoint (origin.x + direction.x * koef, origin.y + direction.y * koef)); } else { clipped_edge->push_back (Geometry::makePoint (edge.vertex1 ()->x (), edge.vertex1 ()->y ())); } } /*##########################################################################*/ void TestController::onPreUpdate (Event::UpdateEvent *e, Model::IModel *m, View::IView *v) { if (firstTime) { firstTime = false; } else { return; } /*-------------------------------------------------------------------------*/ #if 0 // TODO unit tests! // Unit testy. Geometry::Edge a, b; a.a.x = -1; a.a.y = 0; a.b.x = 1; a.b.y = 0; b.a.x = 0; b.a.y = 1; b.b.x = 0; b.b.y = -1; assert (Geometry::intersects (a, b)); // Stykają się, ale nie przecinają. a.a.x = -1; a.a.y = 1; a.b.x = 1; a.b.y = 1; b.a.x = 0; b.a.y = 1; b.b.x = 0; b.b.y = -1; assert (!Geometry::intersects (a, b)); Triangle t; t.a = 3; t.b = 2; t.c = 1; DelaunayTriangulation::Edge ed; ed.first = 3; ed.second = 2; assert (getEdgeSide (t, ed) == 3); ed.first = 1; ed.second = 3; assert (getEdgeSide (t, ed) == 2); ed.first = 1; ed.second = 2; assert (getEdgeSide (t, ed) == 1); #endif /*--------------------------------------------------------------------------*/ Model::Ring *ring = dynamic_cast<Model::Ring *> (m); Geometry::Ring *svg = ring->getData (); // boost::geometry::correct (*svg); // Bo z SVG jakoś tak załadował, że 2 ostatnie są jak pierwszy. svg->resize (svg->size () - 2); std::cerr << "SVG vertices : " << svg->size () << std::endl; // std::cerr << boost::geometry::dsv (*svg) << std::endl; typedef std::vector <Delaunay::Point> Input; Input input; for (Geometry::Ring::const_iterator i = svg->begin (); i != svg->end (); ++i) { input.push_back (Delaunay::Point (i->x, i->y)); } typedef Delaunay::DelaunayTriangulation <Input> MyTriagulation; MyTriagulation cdt (input/*, &voronoi, &delaunay, &crossing*/); cdt.constructDelaunay (&crossing); MyTriagulation::TriangleVector const &triangulation = cdt.getTriangulation (); // 5. Create debug output // Trójkąty // for (TriangleVector::const_iterator i = triangulation.begin (); i != triangulation.end (); ++i) { // delaunay->push_back (input[i->a]); // delaunay->push_back (input[i->b]); // delaunay->push_back (input[i->c]); // } // Krawedzie trójkątów for (MyTriagulation::TriangleVector::const_iterator i = triangulation.begin (); i != triangulation.end (); ++i) { Delaunay::Point const &a = input[Delaunay::a (*i)]; Delaunay::Point const &b = input[Delaunay::b (*i)]; Delaunay::Point const &c = input[Delaunay::c (*i)]; // Wireframe delaunay.push_back (Geometry::makePoint (a.x, a.y)); delaunay.push_back (Geometry::makePoint (b.x, b.y)); delaunay.push_back (Geometry::makePoint (b.x, b.y)); delaunay.push_back (Geometry::makePoint (c.x, c.y)); delaunay.push_back (Geometry::makePoint (c.x, c.y)); delaunay.push_back (Geometry::makePoint (a.x, a.y)); // Trójkąty pełne delaunay2.push_back (Geometry::makePoint (a.x, a.y)); delaunay2.push_back (Geometry::makePoint (b.x, b.y)); delaunay2.push_back (Geometry::makePoint (c.x, c.y)); // delaunay2->push_back (input[i->a]); // delaunay2->push_back (input[i->b]); // delaunay2->push_back (input[i->c]); } /*--------------------------------------------------------------------------*/ VoronoiRenderer vr (*svg, &voronoi); vr.construct (); /*--------------------------------------------------------------------------*/ TestView *tv = dynamic_cast<TestView *> (v); tv->voronoi = &voronoi; tv->delaunay = &delaunay; tv->delaunay2 = &delaunay2; tv->crossing = &crossing; }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "xyz.h" #include <stdio.h> Xyz::Xyz() : QObject() { } void Xyz::doXyz() { printf("This is xyz !\n"); }
/* * VideoCompressor.h * * Created on: 28 Feb 2011 * Author: two * * This is used to Encode the frames, currently Setup to use H.262 (MPEG2-video) but no reason as to * why it can be adapted to others. * */ #ifndef VIDEOCOMPRESSOR_H_ #define VIDEOCOMPRESSOR_H_ //Bug? with INT64_C not being decalred in scope. Silly C++ #ifndef INT64_C #define INT64_C(c) (c ## LL) #define UINT64_C(c) (c ## ULL) #endif //ifndef INT64_C extern "C" { #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libavcodec/avcodec.h> #include <pthread.h> } class VideoCompressor { private: AVCodec * m_ptrCodec; AVCodecContext * m_ptrCodecCtx; int m_nEncodingWidth; int m_nEncodingHeight; int m_nEncodingBitRate; enum PixelFormat m_eColourSpace; int m_nGOPSize; enum CodecID m_eCodecID; bool m_bUseGlobalHeaders; // True for MP4, Default False. Stops error for mp4 Packetising public: VideoCompressor(); int setupEncoder(); void setWidthHeight(int width, int height); void setBitRate(int rate); void setColourSpace(enum PixelFormat pixformat); void setGOPSize(int size); void setGlobalHeaders(bool value); void setCodecID(enum CodecID codecid); int encodeFrame(AVFrame * frame, char * buffer, int bufferLength, int * writtenSize); AVCodecContext* getCodecContext(); virtual ~VideoCompressor(); }; #endif /* VIDEOCOMPRESSOR_H_ */
#include "Stitched.h" Stitched::Stitched(vector<vector<vec2>> const & allVertices, vec2 position, vec2 velocity, float rotation, float fAngVel, float mass, float elasticity, float fFricCoStatic, float fFricCoDynamic, float fDrag, float fAngDrag, glm::vec4 colour) : RigidBody(ShapeID::Stitched, position, velocity, rotation, fAngVel, mass, elasticity, fFricCoStatic, fFricCoDynamic, fDrag, fAngDrag) { m_Colour = colour; Transform pos = Transform(); pos.SetPosition(m_position); Transform rot = Transform(); rot.SetRotate2D(m_rotation); m_GlobalTransform.LocalTransform(pos.GetTransform(), rot.GetTransform(), Transform::Identity()); for (int i = 0; i < allVertices.size(); ++i) { vec2 pos = vec2(0.0f, 0.0f); for (int j = 0; j < allVertices[i].size(); ++j) { pos += allVertices[i][j]; } pos /= (float)allVertices[i].size(); m_PolyRelPos.push_back(pos); vector<vec2> verts; for (int j = 0; j < allVertices[i].size(); ++j) { verts.push_back(allVertices[i][j] - pos); } Poly* poly = new Poly(verts, position + pos, { 0,0 }, rotation, 1, 1, 1, 1, 1, 1, 1, colour); m_Polys.push_back(poly); } } Stitched::~Stitched() { for (int i = 0; i < m_Polys.size(); ++i) { delete m_Polys[i]; } } void Stitched::fixedUpdate(vec2 const& gravity, float timeStep) { RigidBody::fixedUpdate(gravity, timeStep); Transform pos = Transform(); pos.SetPosition(m_position); Transform rot = Transform(); rot.SetRotate2D(m_rotation); m_GlobalTransform.LocalTransform(pos.GetTransform(), rot.GetTransform(), Transform::Identity()); for (int i = 0; i < m_Polys.size(); ++i) { Transform pos; pos.SetPosition(m_PolyRelPos[i]); m_Polys[i]->Move(m_GlobalTransform, pos); } } void Stitched::makeGizmo() { for (int i = 0; i < m_Polys.size(); ++i) { m_Polys[i]->SetIsFilled(m_bIsFilled); m_Polys[i]->makeGizmo(); } }
// Copyright Low Entry. All Rights Reserved. #pragma once #include "ILowEntryFileManagerModule.h" class FLowEntryFileManagerModule : public ILowEntryFileManagerModule { virtual void StartupModule() override; virtual void ShutdownModule() override; };
// Simple sound queue for synchronous sound handling in SDL // Copyright (C) 2005 Shay Green. MIT license. #ifndef SOUND_QUEUE_H #define SOUND_QUEUE_H #include <SDL2/SDL.h> // Simple SDL sound wrapper that has a synchronous interface class Sound_Queue { public: Sound_Queue(); ~Sound_Queue(); // Initialize with specified sample rate and channel count. // Returns NULL on success, otherwise error string. const char* init( long sample_rate, int chan_count = 1 ); // Number of samples in buffer waiting to be played int sample_count() const; // Write samples to buffer and block until enough space is available typedef short sample_t; void write( const sample_t*, int count ); private: enum { buf_size = 2048 }; enum { buf_count = 3 }; sample_t* volatile bufs; SDL_sem* volatile free_sem; int volatile read_buf; int write_buf; int write_pos; bool sound_open; sample_t* buf( int index ); void fill_buffer( Uint8*, int ); static void fill_buffer_( void*, Uint8*, int ); }; #endif
#include <bits/stdc++.h> using namespace std; void display(stack<int> st) { while (!st.empty()) { cout << st.top() << " "; st.pop(); } cout<<endl; } void insert(stack<int>&st, int temp) { if (st.empty()) { st.push(temp); return; } int val = st.top(); st.pop(); insert(st, temp); st.push(val); } void reversestack(stack<int> &st) { // base if (st.size() == 1) { return; } //HYPOTHEIS int temp = st.top(); st.pop(); reversestack(st); //INDUCTION insert(st, temp); } int main() { stack<int> st; st.push(1); st.push(2); st.push(3); st.push(4); st.push(5); display(st); reversestack(st); display(st); return 0; }
// Created on: 2005-03-17 // Created by: OPEN CASCADE Support // Copyright (c) 2005-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 _Extrema_HUBTreeOfSphere_HeaderFile #define _Extrema_HUBTreeOfSphere_HeaderFile #include <NCollection_UBTreeFiller.hxx> #include <NCollection_Handle.hxx> #include <Bnd_Sphere.hxx> typedef NCollection_UBTree<Standard_Integer,Bnd_Sphere> Extrema_UBTreeOfSphere; typedef NCollection_UBTreeFiller<Standard_Integer,Bnd_Sphere> Extrema_UBTreeFillerOfSphere; typedef NCollection_Handle<Extrema_UBTreeOfSphere> Extrema_HUBTreeOfSphere; #endif //_Extrema_HUBTreeOfSphere_HeaderFile
#include "core/types.h" #include "core/maths.h" #include "mat22.h" #include <vector> typedef std::vector<Matrix22> NodeRow; std::vector<Vec2> CgMul(const std::vector<NodeRow>& A, const std::vector<Vec2>& x) { assert(A[0].size() == x.size()); std::vector<Vec2> b(A.size()); for (size_t i=0; i < A.size(); ++i) { for (size_t j=0; j < x.size(); ++j) { b[i] += A[i][j]*x[j]; } } return b; } std::vector<Vec2> CgMul(float c, const std::vector<Vec2>& x) { std::vector<Vec2> r(x.size()); for (size_t i=0; i < r.size(); ++i) r[i] = c*x[i]; return r; } std::vector<Vec2> CgAdd(const std::vector<Vec2>& a, const std::vector<Vec2>& b) { assert(a.size() == b.size()); std::vector<Vec2> c(a.size()); for (size_t i=0; i < a.size(); ++i) c[i] = a[i] + b[i]; return c; } std::vector<Vec2> CgSub(const std::vector<Vec2>& a, const std::vector<Vec2>& b) { assert(a.size() == b.size()); std::vector<Vec2> c(a.size()); for (size_t i=0; i < a.size(); ++i) c[i] = a[i] - b[i]; return c; } float CgDot(const std::vector<Vec2>& a, const std::vector<Vec2>& b) { assert(a.size() == b.size()); float d = 0.0f; for (size_t i=0; i < a.size(); ++i) { d += Dot(a[i], b[i]); } return d; } void CgDebug(const Matrix22& m) { printf("{ %f, %f }\n", m(0, 0), m(0, 1)); printf("{ %f, %f }\n", m(1, 0), m(1, 1)); } void CgDebug(const char* s, const std::vector<Vec2>& x) { for (size_t i=0; i < x.size(); ++i) printf("%s[%u] = {%f, %f}\n", s, uint32_t(i), x[i].x, x[i].y); } void CgDebug(const char* s, const std::vector<NodeRow>& A) { for (size_t i=0; i < A.size(); ++i) { for (int r=0; r < 2; ++r) { for (size_t j=0; j < A[i].size(); ++j) { printf("%f, %f, ", A[i][j](r,0), A[i][j](r, 1)); } printf("\n"); } } } // returns x std::vector<Vec2> CgSolve(const std::vector<NodeRow>& A, const std::vector<Vec2>& b, uint32_t imax, float e) { assert(A.size() == A[0].size()); uint32_t i=0; std::vector<Vec2> x(A[0].size()); std::vector<Vec2> r = CgSub(b, CgMul(A, x)); std::vector<Vec2> d = r; float sigmaNew = CgDot(r, r); //const float sigma0 = sigmaNew; assert(A.size() == A[0].size()); assert(x.size() == A.size()); assert(r.size() == A.size()); assert(d.size() == A.size()); //CgDebug("b", b); std::vector<Vec2> q; while (i < imax)// && sigmaNew > e*e*sigma0) { q = CgMul(A, d); // CgDebug("q", q); float a = sigmaNew / CgDot(d, q); x = CgAdd(x, CgMul(a,d)); // could reseed residual here to account for numerical inaccuracy r = CgSub(r, CgMul(a, q)); float sigmaOld = sigmaNew; if (sigmaOld <= 0.0001f) return x; sigmaNew = CgDot(r, r); //printf("%d %f\n", i, sigmaNew); float beta = sigmaNew / sigmaOld; d = CgAdd(r, CgMul(beta, d)); ++i; } return x; }
#include <Arduino.h> #include "display.h" #include "config.h" #include "weather.h" #include "rtc.h" #include "ldr.h" #include "LedControl_HW_SPI.h" //#include "LedControl_SW_SPI.h" LedControl_HW_SPI lc = LedControl_HW_SPI(); //Hardware SPI //LedControl_SW_SPI lc = LedControl_SW_SPI(); //Software SPI CRtc RtcDisplay; CLdr Ldr; CConfig ConfigDisplay; unsigned int brightness = 0; //0..15 unsigned long displayDelayTime = 0; //Sprites const char digits[10][3] = {{0b01111100, 0b01000100, 0b01111100}, //0 {0b00000000, 0b00000000, 0b01111100}, //1 {0b01110100, 0b01010100, 0b01011100}, //2 {0b01000100, 0b01010100, 0b01111100}, //3 {0b00011100, 0b00010000, 0b01111100}, //4 {0b01011100, 0b01010100, 0b01110100}, //5 {0b01111100, 0b01010100, 0b01110100}, //6 {0b00000100, 0b00000100, 0b01111100}, //7 {0b01111100, 0b01010100, 0b01111100}, //8 {0b00011100, 0b00010100, 0b01111100}}; //9 const char digitsBin[10] = {0b00000000, //b0 0b10000000, //b1 0b01000000, //b2 0b11000000, //b3 0b00100000, //b4 0b10100000, //b5 0b01100000, //b6 0b11100000, //b7 0b00010000, //b8 0b10010000}; //b9 char charOne[1] = {0b01111100}; //1 char charMinus[2] = {0b00010000, 0b00010000}; //- (2px) char charUnknown[3] = {0b00010000, 0b00010000, 0b00010000}; //- (3px) char charDegree[1] = {0b00000100}; //° char charCelcius[2] = {0b00011100, 0b00010100}; //C char charFahrenheit[2] = {0b00111100, 0b00010100}; //F char charPercentage[4] = {0b01001000, 0b00100000, 0b00010000, 0b01001000}; //% char charLoadingInit[4] = {0b00011000, 0b00100100, 0b00100100, 0b00011000}; //[ ] //also used as reset char charLoadingDone[4] = {0b00011000, 0b00111100, 0b00111100, 0b00011000}; //[X] char charLoadingError[4] = {0b00000000, 0b00011000, 0b00011000, 0b00000000}; // X char charA[3] = {0b01110000, 0b00101000, 0b01110000}; //A char charU[3] = {0b01110000, 0b01000000, 0b01110000}; //U char charT[2] = {0b01111100, 0b01010000}; //T char charO[3] = {0b01110000, 0b01010000, 0b01110000}; //O char charBrightness[6] = {0b01000010, 0b00011000, 0b00100100, 0b00100100, 0b00011000, 0b01000010}; //Sun char charCycle[8] = {0b00111000, 0b01000100, 0b10000010, 0b10000010, 0b10000010, 0b01010000, 0b00110000, 0b01110000}; //↻ char charSloth[8] = {0b00111100, 0b01011010, 0b10001011, 0b10100011, 0b10100011, 0b10001011, 0b01011010, 0b00111100}; //Slothface char pongBall[8] = {0b10000000, 0b01000000, 0b00100000, 0b00010000, 0b00001000, 0b00000100, 0b00000010, 0b00000001}; char pongBat[6] = {0b11100000, 0b01110000, 0b00111000, 0b00011100, 0b00001110, 0b00000111}; char pongWall = 0b11111111; //Print a single digit 0 - 9 void printDigit(unsigned int startAddr, unsigned int startRow, unsigned int digit) { int address = startAddr; int row = startRow; for (int i = 0; i < 3; i++) { lc.setRow(address, row, digits[digit][i]); row++; if (row == 8) { row = 0; address++; } } } //Print a char array void printChar(unsigned int startAddr, unsigned int startRow, char data[], unsigned int length) { int address = startAddr; int row = startRow; for (int i = 0; i < length; i++) { lc.setRow(address, row, data[i]); row++; if (row == 8) { address++; row = 0; } } } //Update the display brightness void updateBrightness() { if (_autoBrightness) //Check if autobrightness is on { brightness = Ldr.read(); //Get brightness from LDR sensor } lc.setIntensity(0, brightness); //Update the brightness lc.setIntensity(1, brightness); } //Initialize the displays void CDisplay::init() { lc.begin(_pinDisplaySS, 2); //Define CS pin //lc.begin(_pinDisplayMOSI, _pinDisplaySCK, _pinDisplaySS, 2); lc.shutdown(0, false); //Get display out of sleep mode lc.shutdown(1, false); lc.setIntensity(0, 6); //Set to medium brightness while starting up lc.setIntensity(1, 6); lc.clearDisplay(0); //Clear the display if anything was still on there lc.clearDisplay(1); } //Turn up the brightness by 1 void CDisplay::brightnessUp() { if (_autoBrightness) //If autobrightness was enabled, disable it { Serial.println("[Display] Turning off auto brightness..."); _autoBrightness = false; ConfigDisplay.saveSettings(); } if (brightness < 15) //Check if brightness is not max { brightness++; updateBrightness(); } showBrightness(); printf("[Display] Bightness: %u/15\n", brightness); } //Turn down the brightness by 1 void CDisplay::brightnessDown() //If autobrightness was enabled, disable it { if (_autoBrightness) { Serial.println("[Display] Turning off auto brightness..."); _autoBrightness = false; ConfigDisplay.saveSettings(); } if (brightness > 0) //Check if brightness is not min { brightness--; updateBrightness(); } showBrightness(); printf("[Display] Bightness: %u/15\n", brightness); } //Display the time void CDisplay::showTime() { updateBrightness(); if ((millis() - 3000) > displayDelayTime) //Check if no setting is showing { if (!_onlineSync) //Check if RTC is not used by the other core RtcDisplay.update(); //Let RTC update global time uint8_t timeHour = _timeHour; //Handle 12H clock if (!_use24h && (timeHour > 12)) { timeHour = timeHour - 12; } lc.clearDisplay(0); lc.clearDisplay(1); //Print time if ((timeHour / 10 % 10) != 0) //Uncomment to hide leading 0 { printDigit(0, 0, timeHour / 10 % 10); } printDigit(0, 4, timeHour % 10); /* if (_timeMinute != 48) { printDigit(1, 1, _timeMinute / 10 % 10); printDigit(1, 5, _timeMinute % 10); } else { printChar(1, 0, charSloth, 8); } */ printDigit(1, 1, _timeMinute / 10 % 10); printDigit(1, 5, _timeMinute % 10); } } //Display the date void CDisplay::showDate() { updateBrightness(); if ((millis() - 3000) > displayDelayTime) //Check if no setting is showing { if (!_onlineSync) //Check if RTC is not used by the other core RtcDisplay.update(); //Let RTC update global time lc.clearDisplay(0); lc.clearDisplay(1); //Handle date format if (_useDdmm) //Day - Month { if ((_timeDay / 10 % 10) != 0) printDigit(0, 0, _timeDay / 10 % 10); else printDigit(0, 0, 0); printDigit(0, 4, _timeDay % 10); printChar(1, 0, charMinus, sizeof(charMinus)); if ((_timeMonth / 10 % 10) != 0) { printChar(1, 3, charOne, sizeof(charOne)); printDigit(1, 5, _timeMonth % 10); } else printDigit(1, 3, _timeMonth % 10); } else //Month - Day { if ((_timeMonth / 10 % 10) != 0) printChar(0, 0, charOne, sizeof(charOne)); printDigit(0, 2, _timeMonth % 10); printChar(0, 6, charMinus, sizeof(charMinus)); if ((_timeDay / 10 % 10) != 0) printDigit(1, 1, _timeDay / 10 % 10); else printDigit(1, 1, 0); printDigit(1, 5, _timeDay % 10); } } } //Display the temperature void CDisplay::showTemperature() { updateBrightness(); if ((millis() - 3000) > displayDelayTime) //Check if no setting is showing { lc.clearDisplay(0); lc.clearDisplay(1); if (_temperature < 0) //Check if temperature is up to date. If it couldn't sync or if not connected the temperature is -1 Kelvin. { //Error printChar(0, 3, charUnknown, sizeof(charUnknown)); printChar(0, 7, charUnknown, sizeof(charUnknown)); } else { int temperature; //Calculate temperature from Kelvin if (_useCelcius) temperature = int((_temperature - 273.15) + 0.5); else temperature = int(((_temperature - 273.15) * 1.8) + 32.5); //Check if temperature is below -9 if (temperature <= -10) { printChar(0, 0, charMinus, sizeof(charMinus)); printDigit(0, 3, (temperature * -1) / 10 % 10); printDigit(0, 7, (temperature * -1) % 10); } //Check if temperature is below 0 else if (temperature < 0) { printChar(0, 4, charMinus, sizeof(charMinus)); printDigit(0, 7, (temperature * -1) % 10); } //Check if temperature is above 100 else if (temperature >= 100) printChar(0, 1, charOne, sizeof(charOne)); //check if temperature is over 9 if (temperature >= 10) printDigit(0, 3, temperature / 10 % 10); printDigit(0, 7, temperature % 10); } //Display unit printChar(1, 3, charDegree, sizeof(charDegree)); if (_useCelcius) printChar(1, 5, charCelcius, sizeof(charCelcius)); else printChar(1, 5, charFahrenheit, sizeof(charFahrenheit)); } } //Display the humidity void CDisplay::showHumidity() { updateBrightness(); if ((millis() - 3000) > displayDelayTime) //Check if no setting is showing { lc.clearDisplay(0); lc.clearDisplay(1); if ((_humidity < 0) || (_humidity > 100)) //Check if humidity is up to date or out of range. If it couldn't sync or if not connected the humidity is -1%. { printChar(0, 2, charUnknown, sizeof(charUnknown)); printChar(0, 6, charUnknown, sizeof(charUnknown)); } else { if (_humidity > 99) printChar(0, 0, charOne, sizeof(charOne)); if (_humidity > 10) printDigit(0, 2, _humidity / 10 % 10); printDigit(0, 6, _humidity % 10); } printChar(1, 3, charPercentage, sizeof(charPercentage)); } } //Display time and date in binary void CDisplay::showTimeBin() { updateBrightness(); if ((millis() - 3000) > displayDelayTime) { if (!_onlineSync) RtcDisplay.update(); lc.clearDisplay(0); lc.clearDisplay(1); lc.setRow(0, 0, (digitsBin[_timeHour / 10 % 10] | 0b00000001)); lc.setRow(0, 1, (digitsBin[_timeHour % 10] | 0b00000001)); lc.setRow(0, 3, (digitsBin[_timeMinute / 10 % 10] | 0b00000001)); lc.setRow(0, 4, (digitsBin[_timeMinute % 10] | 0b00000001)); lc.setRow(0, 6, (digitsBin[_timeSecond / 10 % 10] | 0b00000001)); lc.setRow(0, 7, (digitsBin[_timeSecond % 10] | 0b00000001)); if (!_useDdmm) { lc.setRow(1, 3, (digitsBin[_timeMonth / 10 % 10] | 0b00000001)); lc.setRow(1, 4, (digitsBin[_timeMonth % 10] | 0b00000001)); lc.setRow(1, 6, (digitsBin[_timeDay / 10 % 10] | 0b00000001)); lc.setRow(1, 7, (digitsBin[_timeDay % 10] | 0b00000001)); } else { lc.setRow(1, 3, (digitsBin[_timeDay / 10 % 10] | 0b00000001)); lc.setRow(1, 4, (digitsBin[_timeDay % 10] | 0b00000001)); lc.setRow(1, 6, (digitsBin[_timeMonth / 10 % 10] | 0b00000001)); lc.setRow(1, 7, (digitsBin[_timeMonth % 10] | 0b00000001)); } } //write manual that bin time is always 24h } //Display the brightness value void CDisplay::showBrightness() { lc.clearDisplay(0); lc.clearDisplay(1); printChar(0, 5, charBrightness, sizeof(charBrightness)); if (brightness == 0) { lc.setRow(0, 0, 0b00000000); lc.setRow(1, 7, 0b00000000); } else if (brightness == 1 || brightness == 2) { lc.setRow(0, 0, 0b10000000); lc.setRow(1, 7, 0b10000000); } else if (brightness == 3 || brightness == 4) { lc.setRow(0, 0, 0b11000000); lc.setRow(1, 7, 0b11000000); } else if (brightness == 5 || brightness == 6) { lc.setRow(0, 0, 0b11100000); lc.setRow(1, 7, 0b11100000); } else if (brightness == 7 || brightness == 8) { lc.setRow(0, 0, 0b11110000); lc.setRow(1, 7, 0b11110000); } else if (brightness == 9 || brightness == 10) { lc.setRow(0, 0, 0b11111000); lc.setRow(1, 7, 0b11111000); } else if (brightness == 11 || brightness == 12) { lc.setRow(0, 0, 0b11111100); lc.setRow(1, 7, 0b11111100); } else if (brightness == 13 || brightness == 14) { lc.setRow(0, 0, 0b11111110); lc.setRow(1, 7, 0b11111110); } else if (brightness == 15) { lc.setRow(0, 0, 0b11111111); lc.setRow(1, 7, 0b11111111); } displayDelayTime = millis(); updateBrightness(); } //Show text 'Auto' to indicate autobrightness is active void CDisplay::showAutoBrightness() { Serial.println("[Display] Showing auto brightness setting..."); lc.clearDisplay(0); lc.clearDisplay(1); printChar(0, 1, charA, sizeof(charA)); printChar(0, 5, charU, sizeof(charU)); printChar(1, 1, charT, sizeof(charT)); printChar(1, 4, charO, sizeof(charO)); displayDelayTime = millis(); updateBrightness(); } //Show the char '↻' to indicate auto cycling is active void CDisplay::showAutoCycle() { Serial.println("[Display] Showing auto cycle setting..."); lc.clearDisplay(0); lc.clearDisplay(1); printChar(0, 4, charCycle, sizeof(charCycle)); displayDelayTime = millis(); updateBrightness(); } //Show status while initializing void CDisplay::showStatus(EStatus state_1, EStatus state_2, EStatus state_3) { //Print state 1 lc.clearDisplay(0); lc.clearDisplay(1); switch (state_1) { case EStatus::Init: printChar(0, 0, charLoadingInit, sizeof(charLoadingInit)); break; case EStatus::Done: printChar(0, 0, charLoadingDone, sizeof(charLoadingDone)); break; default: //Error printChar(0, 0, charLoadingError, sizeof(charLoadingError)); break; } //Print state 2 switch (state_2) { case EStatus::Init: printChar(0, 6, charLoadingInit, sizeof(charLoadingInit)); break; case EStatus::Done: printChar(0, 6, charLoadingDone, sizeof(charLoadingDone)); break; default: //Error printChar(0, 6, charLoadingError, sizeof(charLoadingError)); break; } //Print state 3 switch (state_3) { case EStatus::Init: printChar(1, 4, charLoadingInit, sizeof(charLoadingInit)); break; case EStatus::Done: printChar(1, 4, charLoadingDone, sizeof(charLoadingDone)); break; default: //Error printChar(1, 4, charLoadingError, sizeof(charLoadingError)); break; } } //Show reset icon to indicate ESP is resetting void CDisplay::showReset() { lc.clearDisplay(0); lc.clearDisplay(1); printChar(0, 6, charLoadingInit, sizeof(charLoadingInit)); } void CDisplay::renderPong(int posBat, int posBall_X, int posBall_Y, int possWall, bool wall) { int ball_addr = 0; int ball_row = 0; if (posBall_X > 7) { ball_addr = 1; ball_row = posBall_X - 8; } else { ball_addr = 0; ball_row = posBall_X; } updateBrightness(); lc.clearDisplay(0); lc.clearDisplay(1); //ball lc.setRow(ball_addr, ball_row, pongBall[posBall_Y]); //bat lc.setRow(1, 7, pongBat[posBat - 1]); //wall if (wall) { lc.setRow(0, possWall, pongWall); } } void CDisplay::renderPongReset() { for (int i = 0; i < 8; i++) { lc.setRow(1, 7 - i, 0b11111111); delay(30); } for (int i = 0; i < 8; i++) { lc.setRow(0, 7 - i, 0b11111111); delay(30); } for (int i = 0; i < 8; i++) { lc.setRow(1, 7 - i, 0b00000000); lc.setRow(1, 7, 0b00011100); delay(30); } for (int i = 0; i < 8; i++) { lc.setRow(0, 7 - i, 0b00000000); delay(30); } }
#include <iostream> using namespace std; #include <stdio.h> #include <cmath> #include <vector> vector<double> lambda = {1, 2, 3, 4, 3, 2}; vector<double> add(vector<double> x, double c1,vector<double> y, double c2) { vector<double> xnew; for (int i=0; i<x.size(); i++) { xnew.push_back(c1*x[i] + c2*y[i]); } return xnew; } vector<double> f(double t, vector<double> x) { vector<double> xnew; xnew.push_back(-lambda[0]*x[0]); for (int i=1; i<x.size(); ++i) { xnew.push_back(-lambda[i]*x[i]+lambda[i-1]*x[i-1]); } xnew.push_back(lambda[x.size()-1]*x[x.size()-1]); return xnew; } vector<double> Euler(double t, vector<double> x, double dt) { return add(x, 1, f(t,x), dt); } vector<double> ModifiedEuler(double t, vector<double> x, double dt) { return add(x, 1, f(t+dt/2., add(x, 1, f(t, x), dt/2.)), dt); } vector<double> RK4(double t, vector<double> x, double dt) { vector<double> K1 = f(t, x); vector<double> K2 = f(t+dt/2., add(x, 1, K1, dt/2.)); vector<double> K3 = f(t+dt/2., add(x, 1, K2, dt/2.)); vector<double> K4 = f(t+dt, add(x, 1, K3, dt)); return add(x, 1, add(K1, 1, add(K2, 2, add(K3, 2, K4, 1), 1), 1), dt/6.); } int main() { int NPoints = 1000; double a = 0; double b = 10; double dt = (b-a)/double(NPoints); double t = 0; vector<double> x = {1000, 0, 0, 50, 5000, 125, 0}; cout << t << " "; for (auto val: x) { cout << val << " "; } cout << endl; for (int i=1;i<NPoints; ++i) { x = RK4(t, x, dt); t+= dt; cout << t << " "; for (auto val: x) { cout << val << " "; } cout << endl; } }
#ifdef HAVE_OPENCV_FEATURES2D typedef SimpleBlobDetector::Params SimpleBlobDetector_Params; #endif
#ifndef SIGNAL_HPP #define SIGNAL_HPP #include <vector> class Signal : public std::vector<double> { public: Signal(double Te, std::size_t N = 0); Signal(double Te, std::size_t N, double value); //utility functions double mean() const; double variance() const; //arithmetic operators Signal& operator +=(double d); Signal& operator -=(double d); Signal& operator *=(double d); Signal& operator /=(double d); Signal operator+(const Signal& s) const; Signal& operator+=(const Signal& s); static Signal noise(double Te, std::size_t N, double mean, double variance); Signal derive() const; Signal integrate(double start = 0) const; private: double m_te; double variance(double mean) const; }; #endif // SIGNAL_HPP
/************************************************************************************** * File Name : Component.h * Project Name : Keyboard Warriors * Primary Author : Doyeong Yi * Secondary Author : * Copyright Information : * "All content 2019 DigiPen (USA) Corporation, all rights reserved." **************************************************************************************/ #pragma once #include "ComponentType.h" class Object; class Component { public: friend class Object; Component(ComponentType type) : componentType(type) {}; virtual ~Component() { }; virtual void Initialize() {}; Object * GetOwner() const { return pOwner; } void SetOwner(Object * owner) { pOwner = owner; } ComponentType GetType() { return componentType; } Object* pOwner = nullptr; ComponentType componentType; };
#include<vector> #include<iostream> #include<algorithm> #include<unordered_map> using namespace std; class Solution { public: int countRangeSum(vector<int>& nums, int lower, int upper) { //基本思想:线段树,超时,时间复杂度O(n^2) //建立线段树tree,然后双重循环分别遍历区间的起始和终止 //利用线段树求出[i,j]区间的和sum,如果满足[lower,upper]区间res++ int res=0; vector<long long> tree(nums.size()*2,0); for(int i=0;i<nums.size();i++) tree[nums.size()+i]=nums[i]; for(int i=nums.size()-1;i>=1;i--) tree[i]=tree[2*i]+tree[2*i+1]; for(int i=nums.size();i<tree.size();i++) { for(int j=i;j<tree.size();j++) { int left=i,right=j; long long sum=0; while(left<=right) { if(left%2==1) { sum+=tree[left]; left++; } if(right%2==0) { sum+=tree[right]; right--; } left/=2; right/=2; } if(sum>=lower && sum<=upper) res++; } } return res; } }; class Solution1 { public: int res=0; vector<long> temp; //归并排序辅助数组 int countRangeSum(vector<int>& nums, int lower, int upper) { //基本思想:前缀和+归并排序,先计算得到nums的前缀和presum,presum[i+1]-presum[i]=nums[i],再对presum进行归并排序 //归并排序合并的两个数组时,比如nums1={2,5,8} nums2={1,7,9} //遍历nums2中的每个元素减去nums1中的每个元素,就得到nums中所有范围区间的元素和 //只要nums2每个元素-nums1每个元素的值在[lower,upper],res++ //但是因为nums1和nums2都是有序的,所以对于当前nums1中的元素presum[i],只要presum[l]-presum[i]<lower得到nums2满足条件的左起点 //presum[r]-presum[i]<=upper得到nums2满足条件的右终点,最后res+=r-l,大大优化,减少了很多遍历次数 long sum=0; vector<long> presum(nums.size()+1,0); temp.resize(nums.size()+1,0); for(int i=0;i<nums.size();i++) { sum+=nums[i]; presum[i+1]=sum; } mergeSort(presum,0,int(presum.size())-1,lower,upper); return res; } void mergeSort(vector<long>& presum, int left, int right, int lower, int upper) { if(left>=right) return; int mid=(left+right)/2; mergeSort(presum,left,mid,lower,upper); mergeSort(presum,mid+1,right,lower,upper); Merge(presum,left,mid,right,lower,upper); } void Merge(vector<long>& presum, int left, int mid, int right, int lower, int upper) { int i=left,j=mid+1,k=left; int l=mid+1,r=mid+1; while(i<=mid) { while(l<=right&&presum[l]-presum[i]<lower) l++; while(r<=right&&presum[r]-presum[i]<=upper) r++; res+=r-l; i++; } i=left; j=mid+1; while(i<=mid&&j<=right) { if(presum[i]<presum[j]) temp[k++]=presum[i++]; else temp[k++]=presum[j++]; } while(i<=mid) temp[k++]=presum[i++]; while(j<=right) temp[k++]=presum[j++]; for(int t=left;t<=right;t++) presum[t]=temp[t]; } }; int main() { Solution1 solute; vector<int> nums={-2,5,-1}; int lower=-2,upper=2; cout<<solute.countRangeSum(nums,lower,upper)<<endl; }
#ifndef QRDIALOG_H #define QRDIALOG_H #include <QDialog> namespace Ui { class QRDialog; } class QRDialog : public QDialog { Q_OBJECT public: explicit QRDialog(QWidget *parent = nullptr); ~QRDialog(); private: Ui::QRDialog *ui; }; #endif // QRDIALOG_H
#include "../include/AnimationAsset.h" #include <iomanip> #include <thread> void CAE::AnimationAsset::loadFromFile() { auto task = [this]() { sf::Context _; if(std::ifstream istream(assetPath.data(), ifstream::in); istream.is_open()) { json j; istream >> j; try { auto info = j.at("defaultInfo"); name = info.at("name").get<std::string>(); if(info.at("texturePath").is_array()) { is_array = true; json _t = j["defaultInfo"]["texturePath"]; if(_t.is_array()) { std::multimap<int, sf::Texture> textures; sf::Vector2u size; unsigned int sz = _t.size(); unsigned int widht = 0; unsigned int height = 0; int i = 0; int padding = 20; draw_data.padding = padding; for(auto& elem : _t) { Textures tt; auto dir = elem.at("PathsToTexture").get<std::string>(); sf::Vector2u s; tt.path = dir; for(auto& p : elem["Textures"]) { sf::Texture t; texturePath += p.get<std::string>(); if(!t.loadFromFile(dir + "/" + p.get<std::string>())) { Console::AppLog::addLog("Can't open " + dir + "/" + p.get<std::string>(), Console::error); data_ready.store(2); return; //return false; } tt.files.emplace_back(p.get<std::string>()); tt.textures.push_back(t); textures.emplace(i, t); s.x = std::max(s.x, t.getSize().x); s.y = std::max(s.y, t.getSize().y); } size.x = std::max(s.x, size.x); size.y = std::max(s.y, size.y); widht = std::max((unsigned int) (s.x * elem["Textures"].size()), widht); height = std::max(s.y * sz, height); ++i; t_data.emplace(i, tt); } sf::RenderTexture tx; tx.create(widht, height + padding * sz); int x = 0, y = 0; tx.clear(sf::Color::Transparent); draw_data.FrameSize = size; draw_data.TextureSize = tx.getSize(); //draw_data.FrameCount for(i = 0; i < sz; ++i) { auto range = textures.equal_range(i); for(auto it = range.first; it != range.second; ++it) { sf::Sprite s(it->second); s.setPosition(x, y); tx.draw(s); x += size.x; } x = 0; y += size.y + 20; } tx.display(); texture = tx.getTexture(); setTexture(texture); } } else { is_array = false; texturePath = info.at("texturePath").get<std::string>(); if(!texture.loadFromFile(texturePath)) { Console::AppLog::addLog("Can't load texture", Console::error); //return false; data_ready.store(2); return; } setTexture(texture); } for(auto& group : j.at("Groups")) { groups.emplace_back(std::make_shared<Group>(Group())); groups.back()->load(group); } //return true; } catch (json::exception& e) { Console::AppLog::addLog("Json throw exception, message: " + std::string(e.what()), Console::error); //data_ready.store(false); data_ready.store(2); return; } } data_ready.store(1); }; data_ready.store(0); std::thread(task).detach(); } bool CAE::AnimationAsset::saveAsset(std::string_view path) { if(path.empty()) path = assetPath; ofstream o(path.data()); json j; auto& info = j["defaultInfo"]; info["name"] = name; if(is_array) { info["texturePath"] = json::array(); for(auto& p : t_data) { json j2; j2["PathsToTexture"] = p.second.path; j2["Textures"] = json::array(); for(auto& pp : p.second.files) { j2["Textures"].emplace_back(pp); } info["texturePath"].emplace_back(j2); } } else info["texturePath"] = texturePath; int i = 0; auto& g = j["Groups"]; for(auto& group : groups) { group->save(g[i]); ++i; } o << std::setw(4) << j; o.close(); return true; } CAE::AnimationAsset::AnimationAsset(std::string_view _path) : assetPath(_path), data_ready(0) { draw_data.padding = 20; draw_data.FrameCount = 0; } sf::Image CAE::AnimationAsset::makeTexture(const json& j, sf::Vector2i _padding) { if(j.is_array()) { std::multimap<int, sf::Texture> textures; sf::Vector2u size; int sz = j.size(); unsigned int widht = 0; unsigned int height = 0; int max = 0; int i = 0; int _i = 0; sf::Vector2i padding = _padding; for(auto& elem : j) { Textures tt; auto dir = elem.at("PathsToTexture").get<std::string>(); sf::Vector2u s; tt.path = dir; for(auto& p : elem["Textures"]) { sf::Texture t; if(!t.loadFromFile(dir + "/" + p.get<std::string>())) { Console::AppLog::addLog("Can't open " + dir + "/" + p.get<std::string>(), Console::error); return sf::Image(); } tt.files.emplace_back(p.get<std::string>()); textures.emplace(i, t); s.x = std::max(s.x, t.getSize().x); s.y = std::max(s.y, t.getSize().y); _i++; } max = std::max(max, _i); size.x = std::max(s.x, size.x); size.y = std::max(s.y, size.y); widht = std::max((unsigned int) (s.x * elem["Textures"].size()), widht); height = std::max(s.y * sz, height); ++i; // textures.emplace_back(tt); } sf::RenderTexture tx; tx.create(widht + padding.x * max, height + padding.y * sz); int x = 0, y = 0; tx.clear(sf::Color::Transparent); for(i = 0; i < sz; ++i) { auto range = textures.equal_range(i); for(auto it = range.first; it != range.second; ++it) { sf::Sprite s(it->second); s.setPosition(x, y); tx.draw(s); x += size.x + padding.x; } x = 0; y += size.y + padding.y; } tx.display(); return tx.getTexture().copyToImage(); } else Console::AppLog::addLog("AnimAsset::maketexture expected array", Console::logType::error); } void CAE::AnimationAsset::ParseMultiAsset(const json& j, std::multimap<int, sf::Texture>& textures) { if(j.is_array()) { //std::multimap<int, sf::Texture> textures; sf::Vector2u size; int sz = j.size(); unsigned int widht = 0; unsigned int height = 0; int i = 0; for(auto& elem : textures) i = std::max(elem.first + 1, i); for(auto& elem : j) { Textures tt; auto dir = elem.at("PathsToTexture").get<std::string>(); sf::Vector2u s; tt.path = dir; for(auto& p : elem["Textures"]) { sf::Texture t; if(!t.loadFromFile(dir + "/" + p.get<std::string>())) { Console::AppLog::addLog("Can't open " + dir + "/" + p.get<std::string>(), Console::error); return; } tt.files.emplace_back(p.get<std::string>()); textures.emplace(i, t); s.x = std::max(s.x, t.getSize().x); s.y = std::max(s.y, t.getSize().y); } size.x = std::max(s.x, size.x); size.y = std::max(s.y, size.y); widht = std::max((unsigned int) (s.x * elem["Textures"].size()), widht); height = std::max(s.y * sz, height); ++i; // textures.emplace_back(tt); } } } // //std::vector<CAE::Group> //CAE::AnimationAsset::createGroups(std::multimap<int, sf::Texture> textures, sf::Vector2u FrameSize, sf::Vector2i padding) //{ // int i = 0; // std::map<int, int> keysCount; // std::vector<Group> groups; // for(auto& elem : textures) // keysCount[elem.first]++; // sf::Vector2i countXY = {std::max_element(keysCount.begin(), keysCount.end())->second, static_cast<int>(keysCount.size()) + 1}; // unsigned int widht = (FrameSize.x + padding.x) * countXY.x; // unsigned int height = (FrameSize.y + padding.y) * countXY.y; // int sz = textures.size(); // int x = 0, y = 0; // groups.resize(keysCount.size()); // for(auto& elem : textures) // { // if(i != elem.first) // { // i = elem.first; // groups[i].setName(std::to_string(i)); // ImGui::Text("%s", groups[i].getName().c_str()); // x = 0; // y += FrameSize.y + padding.y; // } // x += FrameSize.x + padding.x; // auto size = elem.second.getSize(); // groups[i].getParts().emplace_back(std::make_shared<Part>(sf::FloatRect(x, y, size.x, size.y))); // } //} sf::Image CAE::AnimationAsset::CreateMultiTexture(std::multimap<int, sf::Texture> textures, sf::Vector2u FrameSize, sf::Vector2i padding) { std::map<int, int> keysCount; for(auto& elem : textures) keysCount[elem.first]++; sf::Vector2i countXY = {std::max_element(keysCount.begin(), keysCount.end())->second, static_cast<int>(keysCount.size()) + 1}; unsigned int widht = (FrameSize.x + padding.x) * countXY.x; unsigned int height = (FrameSize.y + padding.y) * countXY.y; unsigned int sz = textures.size(); sf::RenderTexture tx; tx.create(widht, height); int x = 0, y = 0; tx.clear(sf::Color::Transparent); for(int i = 0; i < sz; ++i) { auto range = textures.equal_range(i); for(auto it = range.first; it != range.second; ++it) { sf::Sprite s(it->second); s.setPosition(x, y); tx.draw(s); x += FrameSize.x + padding.x; } x = 0; y += FrameSize.y + padding.y; } tx.display(); return tx.getTexture().copyToImage(); } void CAE::AnimationAsset::editAsset() { ImGui::BeginChild("Asset edit"); ImGui::EndChild(); }
#include <core/maths.h> #include <core/shader.h> #include <core/platform.h> #include <core/mat22.h> #include "cg.h" #include <iostream> #include <cmath> #include <functional> #include <algorithm> #include <vector> #include <stdint.h> #include <xmmintrin.h> using namespace std; const int kWidth = 800; const int kHeight = 600; float gViewLeft = -1.0f; float gViewBottom = -2.0f; float gViewWidth = 5.0f; float gViewAspect = kHeight/float(kWidth); Vec2 gGravity(0.0f, -9.8f); float gStiffness = 100000.0f; float gDamping = 0.0f; const int gSubsteps = 1; Vec2 gMousePos; int gMouseIndex=-1; float gMouseStrength = 100.0f; const Matrix22 kIdentity(Vec2(1.0f, 0.0f), Vec2(0.0f, 1.0f)); struct Particle { Particle(Vec2 x, float im) : p(x), invMass(im) {} Vec2 p; Vec2 v; Vec2 f; float invMass; }; struct Spring { uint32_t i, j; float r; float ks; float kd; }; std::vector<Particle> gParticles; std::vector<Spring> gSprings; int FindClosestParticle(Vec2 p) { float minDistSq = FLT_MAX; int minIndex = -1; for (size_t i=0; i < gParticles.size(); ++i) { float d = LengthSq(p-gParticles[i].p); if (d < minDistSq) { minDistSq = d; minIndex = i; } } return minIndex; } void Init() { gParticles.clear(); gSprings.clear(); /* Create chain */ for (int i=0; i < 10; ++i) { const float kLength = 0.1f; gParticles.push_back(Particle(Vec2(i*kLength, 0.0f), i?1.0f:0.0f)); if (i) { Spring s = { i-1, i, kLength, gStiffness, gDamping }; gSprings.push_back(s); } } } void SolveExplicit(float dt) { // integrate particles forward in time for (size_t i=0; i < gParticles.size(); ++i) { gParticles[i].v += gParticles[i].invMass*(gParticles[i].f - gDamping*gParticles[i].v)*dt; gParticles[i].p += gParticles[i].v*dt;// + 0.5f*gParticles[i].f*dt*dt*gParticles[i].invMass; } } Matrix22 SpringJdx(uint32_t i, uint32_t j, float r, float ks) { Vec2 p = gParticles[i].p; Vec2 q = gParticles[j].p; Vec2 u = p-q; float m = Length(u); // normalize u /= m; Matrix22 l = Outer(u, u); Matrix22 c = -ks*(l + (1.0f - r/m)*(kIdentity-l)); return c; } Matrix22 SpringJdv(uint32_t i, uint32_t j, float kd) { Vec2 p = gParticles[i].p; Vec2 q = gParticles[j].p; Vec2 u = Normalize(p-q); return -kd*Outer(u, u); } // returns the force on i from spring Vec2 SpringF(uint32_t i, uint32_t j, float r, float ks, float kd, Vec2 dp, Vec2 dq, Vec2 dvi=Vec2(), Vec2 dvj=Vec2()) { Vec2 p = gParticles[i].p+dp; Vec2 q = gParticles[j].p+dq; Vec2 u = p-q; Vec2 v = gParticles[i].v+dvi-gParticles[j].v+dvj; float l = Length(u); u /= l; float e = l-r; return -(ks *e + kd*Dot(v, u))*u; } // finite difference approximation to J Matrix22 SpringJn(uint32_t i, uint32_t j, float r, float ks, float kd, float dp, float dq) { Vec2 fdx = SpringF(i, j, r, ks, kd, Vec2(dp, 0.0f), Vec2(dq, 0.0f)) - SpringF(i, j, r, ks, kd, Vec2(), Vec2()); Vec2 fdy = SpringF(i, j, r, ks, kd, Vec2(0.0f, dp), Vec2(0.0f, dq)) - SpringF(i, j, r, ks, kd, Vec2(), Vec2()); if (dp > 0.0f) return Matrix22(fdx/dp, fdy/dp); else return Matrix22(fdx/dq, fdy/dq); } void SolveImplicit(float dt) { size_t n = gParticles.size(); // construct n by n block matrix of force Jacobians std::vector<NodeRow> A(n, NodeRow(n)); std::vector<NodeRow> dJdx(n, NodeRow(n)); for (size_t i=0; i < gSprings.size(); ++i) { const Spring& s = gSprings[i]; // calculate Jacobian of force on i Matrix22 Jp = -dt*dt*SpringJdx(s.i, s.j, s.r, s.ks); Matrix22 Jpdp = Jp; Matrix22 Jpdq = -1.0f*Jp; Matrix22 Jqdq = Jp; Matrix22 Jqdp = -1.0f*Jp; Matrix22 Jv = -dt*SpringJdv(s.i, s.j, s.kd); // force derivative wrt first particle A[s.i][s.i] += Jpdp+Jv; // force on i due to other particle is in the opposite direction A[s.i][s.j] += Jpdq-Jv; // force on j due to j is the same as i A[s.j][s.j] += Jqdq+Jv; // force on j due to i is same as force on i due to j A[s.j][s.i] += Jqdp-Jv; // ----------------------------------- // // force derivative wrt first particle dJdx[s.i][s.i] += Jpdp; // force on i due to other particle is in the opposite direction dJdx[s.i][s.j] += Jpdq; // force on j due to j is the same as i dJdx[s.j][s.j] += Jqdq; // force on j due to i is same as force on i due to j dJdx[s.j][s.i] += Jqdp; } std::vector<Vec2> v(n); std::vector<Vec2> f(n); for (size_t i=0; i < n; ++i) { f[i] = dt*gParticles[i].f; v[i] = gParticles[i].v; } // calculate b std::vector<Vec2> b = CgSub(f, CgMul(dJdx, v)); // multiply through by mass for (size_t i=0; i < n; ++i) A[i][i] = 1.0f/max(gParticles[i].invMass, 0.01f)*kIdentity + A[i][i]; // solve for dv std::vector<Vec2> dv = CgSolve(A, b, 20, 0.001f); // update v for (size_t i=0; i < n; ++i) { gParticles[i].v += dv[i]*gParticles[i].invMass; gParticles[i].p += gParticles[i].v*dt; } } void Advance(float dt) { static float et = 0.0f; et += dt; for (size_t i=0; i < gParticles.size(); ++i) { Particle& p = gParticles[i]; //if (p.invMass > 0.0f) p.f = gGravity;//*(1.0f/p.invMass); } for (size_t i=0; i < gSprings.size(); ++i) { Spring& s = gSprings[i]; Vec2 f = SpringF(s.i, s.j, s.r, s.ks, s.kd, Vec2(), Vec2()); float msum = gParticles[s.i].invMass + gParticles[s.j].invMass; float ma = gParticles[s.i].invMass / msum; float mb = gParticles[s.j].invMass / msum; gParticles[s.i].f += f; gParticles[s.j].f -= f; } if (gMouseIndex != -1) gParticles[gMouseIndex].f += gMouseStrength*(gMousePos-gParticles[gMouseIndex].p); //SolveExplicit(dt); SolveImplicit(dt); } void Update() { const float dt = 1.0f/60.0f; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(gViewLeft, gViewLeft+gViewWidth, gViewBottom, gViewBottom+gViewWidth*gViewAspect); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); double startTime = GetSeconds(); for (int i=0; i < gSubsteps; ++i) { Advance(dt/gSubsteps); } double elapsedTime = GetSeconds()-startTime; glBegin(GL_LINES); for (size_t i=0; i < gSprings.size(); ++i) { Vec2 a = gParticles[gSprings[i].i].p; Vec2 b = gParticles[gSprings[i].j].p; glVertex2fv(a); glVertex2fv(b); } glEnd(); glPointSize(4.0f); glBegin(GL_POINTS); glColor3f(0.0f, 1.0f, 0.0f); for (size_t i=0; i < gParticles.size(); ++i) { glVertex2fv(gParticles[i].p); } glEnd(); if (gMouseIndex != -1) { glBegin(GL_LINES); glColor3f(0.0f, 1.0f, 0.0f); glVertex2fv(gMousePos); glVertex2fv(gParticles[gMouseIndex].p); glEnd(); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, kWidth, kHeight, 0); int x = 10; int y = 15; char line[1024]; glColor3f(1.0f, 1.0f, 1.0f); sprintf(line, "Time: %.2fms", float(elapsedTime)*1000.0f); DrawString(x, y, line); y += 13; glutSwapBuffers(); } Vec2 RasterToScene(int x, int y) { float vx = gViewLeft + gViewWidth*x/float(kWidth); float vy = gViewBottom + gViewWidth*gViewAspect*(1.0f-y/float(kHeight)); return Vec2(vx, vy); } int lastx = 0; int lasty = 0; void GLUTMouseFunc(int b, int state, int x, int y) { switch (state) { case GLUT_UP: { lastx = x; lasty = y; gMouseIndex = -1; break; } case GLUT_DOWN: { lastx = x; lasty = y; gMousePos = RasterToScene(x, y); gMouseIndex = FindClosestParticle(gMousePos); } }; } void GLUTKeyboardDown(unsigned char key, int x, int y) { switch (key) { case 'w': { break; } case 's': { break; } case 'a': { break; } case 'd': { break; } case 'u': { break; } case 'j': { break; } case 'r': { Init(); break; } case 27: case 'q': { exit(0); break; } }; } void GLUTKeyboardUp(unsigned char key, int x, int y) { switch (key) { case 'w': { break; } case 's': { break; } case 'a': { break; } case 'd': { break; } }; } void GLUTMotionFunc(int x, int y) { // int dx = x-lastx; // int dy = y-lasty; lastx = x; lasty = y; gMousePos = RasterToScene(x, y); } int main(int argc, char* argv[]) { //_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); // init gl glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(kWidth, kHeight); glutCreateWindow("FEM"); glutPositionWindow(200, 100); #if _WIN32 glewInit(); #endif Init(); glutIdleFunc(Update); glutDisplayFunc(Update); glutMouseFunc(GLUTMouseFunc); glutMotionFunc(GLUTMotionFunc); glutKeyboardFunc(GLUTKeyboardDown); glutKeyboardUpFunc(GLUTKeyboardUp); /* glutReshapeFunc(GLUTReshape); glutDisplayFunc(GLUTUpdate); glutSpecialFunc(GLUTArrowKeys); glutSpecialUpFunc(GLUTArrowKeysUp); */ #if __APPLE__ int swap_interval = 1; CGLContextObj cgl_context = CGLGetCurrentContext(); CGLSetParameter(cgl_context, kCGLCPSwapInterval, &swap_interval); #endif glutMainLoop(); return 0; }
const int potPin = A0; // potentiometer const int pwmOutPin = 3; // PWM output int potentiometerValue; //range from 0 to 1023 int pwmValue; //range from 0 to 255 int speedPercentage; //range from 0 to 100 void setup() { // put your setup code here, to run once: Serial.begin(9600); // Serial Monitor Ctrl + Shift + m pinMode(potPin, INPUT); pinMode(pwmOutPin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: potentiometerValue = analogRead(potPin); pwmValue = (potentiometerValue/4); // pwmValue = map(potentiometerValue, 0,1023, 0, 255); speedPercentage = (int) (potentiometerValue/1023.0*100); analogWrite(pwmOutPin, pwmValue); //Serial.println(); Serial.print(potentiometerValue); Serial.print("\t"); Serial.print(pwmValue); Serial.print("\t"); Serial.print(speedPercentage); Serial.println(); }
#include "precompiled.h" #include "vfs.h" #include "file.h" namespace vfs { }; vfs::IFile::IFile(const char* filename, bool write) { this->m_filename = strDup(filename); this->m_buffer = NULL; } vfs::IFile::~IFile() { delete [] m_filename; delete [] m_buffer; } bool vfs::IFile::readLine(char* linebuf, U32 bufsize) { if (!m_buffer) cache(); if(m_bufferpos == m_buffer + m_size) return false; char* out = linebuf; while((*m_bufferpos != 10) && (*m_bufferpos != 13) && (m_bufferpos < m_buffer + m_size)) { *out = *m_bufferpos; out++; m_bufferpos++; } if(out < linebuf + bufsize) *out = 0; while(((*m_bufferpos == 10)||(*m_bufferpos == 13)) && m_bufferpos < m_buffer + m_size) m_bufferpos++; return true; } void vfs::IFile::writeLine(const char* linebuf, bool flush) { write(linebuf, (U32)strlen(linebuf), flush); write("\n", (U32)strlen("\n"), flush); }
// // Created by mikcy on 15. 6. 7. // #include <iostream> #include "Compile.h" #include "logger.h" //std::map<std::string, std::string> Compile::_compile_opt; compile_result Compile::compile() { std::string cmd(getCommand()); InformMessage("cmd %s", cmd.c_str()); FILE *pp = popen(cmd.c_str(), "r"); struct compile_result result; result.error = false; if(pp==NULL) { result.error = true; result.message = "pipe open failed"; return result; } // 임시저장용 char buf[1024]; // 컴파일 성공시 아무런 메시지를 출력하지 않는다. while(fgets(buf, 1024, pp) != NULL) { result.error = true; result.message.append(buf); } pclose(pp); return result; } std::string Compile::getCommand() { std::string cmd(_compiler); cmd.push_back(' '); for (auto it = _compile_opt.begin(); it!=_compile_opt.end(); it++) { cmd.append(it->first); cmd.push_back(' '); cmd.append(it->second); } cmd.push_back(' '); cmd.append(_codePath); return cmd; } std::string Compile::getBinaryPath() { return _codePath.substr(0, _codePath.find('.')); }
#include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { bool loop = true; char c; // for each digit int ip = 0; // input pointer int sum = 0; int state = 0; string s; // for input string string buf; // operand cout << "7+23+5+100+25와 같이 덧셈 문자열을 입력하세요." << endl; getline(cin, s, '\n'); // 문자열 입력 while (loop) { // loop=false가 될 때까지 반복 switch (state) { case 0: c = s.at(ip++); // 문자열 s의 ip++(1)번째 값을 c에 저장 if(isdigit(c)) // c에 저장된 문자가 숫자인지 판별 { buf.append(1, c); // c를 buf에 저장(buf와 연결) cout << "buf (in state 0) = " << buf <<endl; state = 1; } else cout << "잘못 입력하였습니다." << endl; break; case 1: c = s.at(ip++); // 문자열 s의 ip++(1)번째 값을 c에 저장 cout << "s(i) = " << c << endl; if(isdigit(c)) // c에 저장된 문자가 숫자인지 판별 { buf.append(1, c); // c를 buf에 저장(buf와 연결) cout << "buf (in state 1) = " << buf << endl; state = 1; // case1 반복 } else if(c=='+' || c== '=') // c에 저장된 문자가 ’+’나 ‘=’일 경우 state = 2; // case2 실행 else cout << "잘못 입력하였습니다." << endl; break; case 2: cout << "buf (in state 2) = " << buf << endl; sum += stoi(buf); // 덧셈 실행(buf에 저장된 문자를 숫자로 바꿔서 실행) buf.clear(); // 문자열 buf를 clear state = 1; // case1 반복을 위해 state에 1 저장 if(c=='=') { // c에 저장된 문자가 ‘=’일 경우(문자열 종료) loop = false; // loop=false로 만들어서 while문 종료 } else state=1; // state=1 저장해서 case1 반복 break; } } cout << "숫자들의 합은 " << sum; return 0; }
[ MAIN ] // Part A if(NEWIND <=1) double mtime = 1E10; // Part B if(EVID==1) { mtime = TIME + 1.23; self.mevent(mtime, 33); } // Part C capture past = TIME >= mtime;
#ifndef GTTOOLSETTINGS_H #define GTTOOLSETTINGS_H class GtToolSettings { private: static gchar mWorkPath[GN_MAX_PATH]; static gchar mBackgroundFile[GN_MAX_PATH]; static gint32 mScalePercent; public: static void EBMStartup(); static void EBMShutdown(); static void SetWorkPath(const char* path); static gchar* GetWorkPath(); static void SetBackgroundFilePath(const char* pcPath); static gchar* GetBackgroundFilePath(); static gint32 GetScalePercent(); static void SetScalsePercent(gint32 iScale); static float GetScale(); static void MakeSaveFilePath(const gchar* pcFileName, const gchar* pcFolder, char* outPath , gsize outSize); static void CreateWorkDirectory(); static void CreateDirectoryInWorkDirectory(const gchar* objectType, const gchar* pcFolderName); static void SaveFile(); static void LoadFile(); }; #endif // GTTOOLSETTINGS_H
#include "GameManager.h" GameManager * GameManager::s_singleton = nullptr; GameManager::GameManager() { p_screen = nullptr; p_resourcesManager = nullptr; p_stateManager = nullptr; init(); } GameManager::~GameManager() { clear(); } GameManager * GameManager::getSingleton() { if( !s_singleton ) { s_singleton = new GameManager(); } return s_singleton; } void GameManager::killSingleton() { if( s_singleton ) { delete s_singleton; } s_singleton = nullptr; } void GameManager::clear() { if( p_screen ) { delete p_screen; } p_screen = nullptr; if( p_resourcesManager ) { delete p_resourcesManager; } p_resourcesManager = nullptr; if( p_stateManager ) { delete p_stateManager; } p_stateManager = nullptr; } void GameManager::init() { clear(); setScreenSize( 800, 600 ); setScreenRatio( sf::Vector2u( 0, 0 ) ); setScreenTitle( "No Title" ); m_isUpdated = true; m_isScissored = false; p_resourcesManager = new ResourcesManager(); p_stateManager = new StateManager(); update(); } void GameManager::run() { while( p_stateManager->isRunning() && p_screen->isOpen() ) { sf::Event event; while( p_screen->pollEvent( event ) ) { handleEvent( event ); p_stateManager->handleEvent( event ); } update(); p_stateManager->update(); p_screen->clear( sf::Color::Black ); p_screen->draw( *p_stateManager ); p_screen->display(); } } void GameManager::update( void ) { if( m_isUpdated ) { if( !p_screen ) { p_screen = new sf::RenderWindow( sf::VideoMode( m_screenSize.x, m_screenSize.y ), m_screenTitle ); m_screenInitSize = m_screenSize; } p_screen->setTitle( m_screenTitle ); p_screen->setSize( m_screenSize ); m_isUpdated = false; } } void GameManager::handleEvent( sf::Event &e ) { if( e.type == sf::Event::Closed ) { p_screen->close(); } else if( e.type == sf::Event::Resized ) { if( m_screenRatio.x > 0 && m_screenRatio.y > 0 ) { int isWidthBigger = std::abs( static_cast<int>( m_screenSize.x - p_screen->getSize().x ) ) > std::abs( static_cast<int>( m_screenSize.y - p_screen->getSize().y ) ); if( isWidthBigger ) { setScreenSize( p_screen->getSize().x, p_screen->getSize().x * m_screenRatio.y / m_screenRatio.x ); } else { setScreenSize( p_screen->getSize().y * m_screenRatio.x / m_screenRatio.y, p_screen->getSize().y ); } } else { setScreenSize( p_screen->getSize() ); } } } void GameManager::setViewport( sf::FloatRect zone, sf::RenderStates states ) { sf::View v; zone = states.transform.transformRect( zone ); v.reset( zone ); sf::FloatRect r( zone.left / m_screenInitSize.x, zone.top / m_screenInitSize.y, zone.width / m_screenInitSize.x, zone.height / m_screenInitSize.y ); v.setViewport( r ); p_screen->setView( v ); m_isScissored = true; } void GameManager::setDefaultViewport() { p_screen->setView( p_screen->getDefaultView() ); m_isScissored = false; } sf::FloatRect GameManager::getCurrentViewport() { sf::View v = p_screen->getView(); sf::FloatRect r = v.getViewport(); return sf::FloatRect( r.left * m_screenInitSize.x, r.top * m_screenInitSize.y, r.width * m_screenInitSize.x, r.height * m_screenInitSize.y ); } sf::Vector2f GameManager::getMouseCoord() { return getScreen()->mapPixelToCoords( sf::Mouse::getPosition( *getScreen() ) ); } sf::Vector2f GameManager::getCoord( float x, float y ) { return getCoord( sf::Vector2i( (int)x, (int)y ) ); } sf::Vector2f GameManager::getCoord( int x, int y ) { return getCoord( sf::Vector2i( x, y ) ); } sf::Vector2f GameManager::getCoord( sf::Vector2f p ) { return getCoord( sf::Vector2i( p ) ); } sf::Vector2f GameManager::getCoord( sf::Vector2i p ) { return getScreen()->mapPixelToCoords( p ); }
#include <Servo.h> #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #define ACELERADORSAIDA 3 #define AILERONSAIDA 5 #define LEMESAIDA 6 #define PROFUNDORSAIDA 9 Servo acelerador, aileron, leme, profundor; RF24 radio(7, 8); // CSN, CE const byte address[6] = "0A0A1"; int vlrAcelerador = 0; int vlrAileron = 90; int vlrLeme = 90; int vlrProfundor = 90; long tempoSemReceberComando = 0; void setup() { //radio radio.begin(); radio.setDataRate(RF24_250KBPS); radio.openReadingPipe(0, address); radio.setPALevel(RF24_PA_MIN); radio.startListening(); //servos acelerador.attach(ACELERADORSAIDA); aileron.attach(AILERONSAIDA); leme.attach(LEMESAIDA); profundor.attach(PROFUNDORSAIDA); acelerador.write(vlrAcelerador); aileron.write(vlrAileron); leme.write(vlrLeme); profundor.write(vlrProfundor); } void reiniciaMedidas(){ executaAcelerador(70); executaAileron(90); executaLeme(90); executaProfundor(90); } void executaAcelerador(int vlrTmp){ if(vlrTmp != vlrAcelerador){ vlrAcelerador = vlrTmp; acelerador.write( vlrAcelerador ); } } void executaAileron(int vlrTmp){ if(vlrTmp != vlrAileron){ vlrAileron = vlrTmp; aileron.write( vlrAileron ); } } void executaLeme(int vlrTmp){ if(vlrTmp != vlrLeme){ vlrLeme = vlrTmp; leme.write( vlrLeme ); } } void executaProfundor(int vlrTmp){ if(vlrTmp != vlrProfundor){ vlrProfundor = vlrTmp; profundor.write( vlrProfundor ); } } void processarDadosRecebidos(char dados[25]){ String str(dados); executaAcelerador( str.substring(0, 3).toInt() ); executaAileron( str.substring(3, 6).toInt() ); executaLeme( str.substring(6, 9).toInt() ); executaProfundor( str.substring(9, 12).toInt() ); } void loop() { if (radio.available()) { char text[25] = ""; radio.read(&text, sizeof(text)); processarDadosRecebidos(text); tempoSemReceberComando = 0; } tempoSemReceberComando = tempoSemReceberComando + 100; if(tempoSemReceberComando > 12000){ reiniciaMedidas(); tempoSemReceberComando = 0; } delay(100); }
#include "views/helpview.hpp" #include "views/viewstack.hpp" #include "graphics.hpp" #include "views/defaultlayout.hpp" extern bool paused; vector<string> help_prgh = { "== All Modes ==", " Escape - Return to the previous screen", " Space - Pause", "== Main Screen ==", " d - Digging mode", " u - Units Screen", " h - Help Screen", " a - Announcements Screen", " r - Recruit a new RED clearance citizen", " e - Recruit a new INFRARED clearance citizen", " q - Quit", "== Digging Screen ==", " Arrows - Move the cursor (the 'X')", " Enter - Toggle digging wall underneath cursor", "== Units Screen ==", " Arrows - Move the cursor (the '> <'s)", " Enter - Modify data cell", " Tab - Switch between Skills and Department assignment", "", "", "Good Luck!" }; struct HelpInfo : StaticWidget<HelpInfo> { void render(Graphics& g, render_box const& pos) { for (uint x=0; x<help_prgh.size(); ++x) { g.drawString(pos.x, pos.y + x, help_prgh[x], true, Graphics::Context::BROWN); } } static HelpInfo instance; }; HelpInfo HelpInfo::instance; HelpView::HelpView(ViewStack* vs) : vstk(vs) { nav.register_key(KEY_Escape, "[Esc] Back", [this]() { vstk->pop(); }); nav.register_key(KEY_space, "[Spc] Pause", [this]() { paused = !paused; }); } void HelpView::render(Graphics& g, render_box const& pos) { render_box pos2 = DefaultLayout::render_layout(this, g, pos); HelpInfo::instance.render(g, pos2); } void HelpView::handle_keypress(KeyboardKey ks) { nav.handle_keypress(ks); }
#ifndef SHOC_OTP_HOTP_H #define SHOC_OTP_HOTP_H #include "shoc/mac/hmac.h" namespace shoc { template<class H> uint32_t hotp(const void *key, size_t key_len, uint64_t count, int mod) { static_assert(H::SIZE >= 20, "HOTP hash algorithm must provide at least 20 byte long value"); byte digest[H::SIZE]; if constexpr (little_endian()) { count = (count & 0x00000000ffffffff) << 32 | (count & 0xffffffff00000000) >> 32; count = (count & 0x0000ffff0000ffff) << 16 | (count & 0xffff0000ffff0000) >> 16; count = (count & 0x00ff00ff00ff00ff) << 8 | (count & 0xff00ff00ff00ff00) >> 8; } hmac<H>(&count, sizeof(count), key, key_len, digest); uint32_t offset = digest[H::SIZE - 1] & 0x0f; uint32_t bin_code = (digest[offset] & 0x7f) << 24 | (digest[offset + 1] & 0xff) << 16 | (digest[offset + 2] & 0xff) << 8 | (digest[offset + 3] & 0xff); return bin_code % utl::ipow(10, mod); } } #endif
#pragma once #include "game.h" class FE : public Game { public: FE(void); ~FE(void); void initialize(void); };
/** * @file Noncopyable.hpp * * @brief This header contains a mixin that disallows copying of an object * * @author Matthew Rodusek (matthew.rodusek@gmail.com) * @date January 26, 2015 */ #ifndef VALKNUT_CORE_UNCOPYABLE_HPP_ #define VALKNUT_CORE_UNCOPYABLE_HPP_ #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // valknut::core local libraries #include "../../../include/valknut/core/config.hpp" namespace valknut{ namespace noncopyable_{ // protection again unintended Argument-Dependent Lookup (ADL) ////////////////////////////////////////////////////////////////////////// /// @class valknut::noncopyable_::Noncopyable /// /// This class forces all that implement it to not be copyable via /// copy constructor, nor assignable. /// /// @ingroup core ////////////////////////////////////////////////////////////////////////// class Noncopyable{ protected: /// @brief Protected empty constructor to prevent creation #ifdef VALKNUT_COMPILER_HAS_CPP11_DEFAULT_FUNCTIONS VALKNUT_CONSTEXPR Noncopyable() = default; ~Noncopyable() = default; #else Noncopyable(){} ~Noncopyable(){} #endif #ifdef VALKNUT_COMPILER_HAS_CPP11_DELETED_FUNCTIONS Noncopyable( const Noncopyable& ) = delete; Noncopyable &operator = ( const Noncopyable& ) = delete; #else private: Noncopyable( const Noncopyable& ); Noncopyable &operator = ( const Noncopyable& ); #endif }; } // namespace noncopyable_ typedef noncopyable_::Noncopyable Noncopyable; } // namespace valknut #endif /* VALKNUT_CORE_UNCOPYABLE_HPP_ */
#include "include/RT_Object.hpp" RT_Object::RT_Object() : m_Shininess(0.0f), m_Reflectivity(0.0f) {} RT_Object::RT_Object(const RT_Vec3& ka, const RT_Vec3& kd, \ const RT_Vec3& ks, double shi, double ref, double tra) : m_Ka(ka), m_Kd(kd), m_Ks(ks), m_Shininess(shi), \ m_Reflectivity(ref), m_Transparency(tra) {} void RT_Object::setKa(const RT_Vec3& ka) { m_Ka = ka; } void RT_Object::setKd(const RT_Vec3& kd) { m_Kd = kd; } void RT_Object::setKs(const RT_Vec3& ks) { m_Ks = ks; } void RT_Object::setShininess(double shi) { m_Shininess = shi; } void RT_Object::setReflectivity(double ref) { m_Reflectivity = ref; } void RT_Object::setTransparency(double tra) { m_Transparency = tra; } RT_Vec3 RT_Object::getKa() const { return m_Ka; } RT_Vec3 RT_Object::getKd() const { return m_Kd; } RT_Vec3 RT_Object::getKs() const { return m_Ks; } double RT_Object::getShininess() const { return m_Shininess; } double RT_Object::getReflectivity() const { return m_Reflectivity; } double RT_Object::getTransparency() const { return m_Transparency; }
#include <iostream> #include <map> #include <vector> using namespace std; int main() { int N, c; cin >> N >> c; int cnt[N + 1]; cnt[0] = 0; map<int, vector<int>> appear; for (int i = 1; i <= N; ++i) { int a; cin >> a; cnt[i] = cnt[i - 1] + (a == c); appear[a].push_back(i); } int ans = cnt[N]; for (int v = 1; v <= 500000; ++v) { if (v == c || appear.find(v) == appear.end()) continue; int sum = 0, ma = 0, now = 0; for (int i : appear[v]) { sum = max(0, sum - (cnt[i] - cnt[now])); now = i; ++sum; ma = max(ma, sum); } ans = max(ans, cnt[N] + ma); } cout << ans << endl; return 0; }
//单链表(有头结点) #include <iostream> using namespace std; typedef int ElemType; typedef struct LNode{ ElemType data; struct LNode* next; }LNode; void InitList(LNode *&); //初始化list void ListHeadInsert(LNode *&); //头插法 void ListTailInsert(LNode *&); //尾插法 void DisplayList(LNode *); //打印链表 bool GetElem(LNode *, int &, int &); //按序号查找 bool LocateElem(LNode *, int &, ElemType &); //按值查找 LNode *GetPtr(LNode *, int); //寻找前驱结点(有待优化) bool TailInsert(LNode *, int, ElemType); //尾插法插入数据 bool HeadInsert(LNode *, int, ElemType); //头插法插入数据 bool DeleteElem(LNode*, int); //删除结点 int GetListLength(LNode*); //求表长 //主函数 int main() { LNode* list = nullptr; int choice; int index; ElemType data; cout << "SingleList test menu(1-ListHeadInsert,2-ListTailInsert,3-GetElem,4-LocateElem,\n" "5-TailInsert,6-HeadInsert,7-DeleteData,8-GetLength,9-Display,0-exit):"; cin >> choice; while(choice != 0) { switch(choice){ case 1: ListHeadInsert(list); break; case 2: ListTailInsert(list); break; case 3: cout << "Which index you want to know(max is " << list->data << "):"; cin >> index; if(GetElem(list, index, data)) { cout << "It is " << data << endl; } else { cout << "Error!" << endl; } break; case 4: cout << "Input you want to know elem:"; cin >> index; if(LocateElem(list, index, data)) { cout << data << " is in " << index << endl; } else { cout << "Error!" << endl; } break; case 5: cout << "Input you where you want to insert and data:"; cin >> index >> data; if(TailInsert(list, index, data)) { cout << "Done!" << endl; } else { cout << "Error!" << endl; } break; case 6: cout << "Input you where you want to insert and data:"; cin >> index >> data; if(HeadInsert(list, index, data)) { cout << "Done!" << endl; } else { cout << "Error!" << endl; } break; case 7: cout << "Input which you want to delete:"; cin >> index; if(DeleteElem(list, index)) { cout << "Done!" << endl; } else { cout << "Error!" << endl; } break; case 8: cout << "This list's length is " << GetListLength(list) << endl; break; case 9: DisplayList(list); break; default: cout << "Error! Try again." << endl; break; } cout << "Continue or exit:"; cin >> choice; } return 0; } void InitList(LNode *&l) { if(l == nullptr) { l = new LNode; l->data = 0; l->next = nullptr; } } void ListHeadInsert(LNode *&l) { ElemType data; LNode *s; InitList(l); cout << "HeadInsert input data(-1 to stop):"; cin >> data; while(data != -1) { s = new LNode; s->data = data; s->next = l->next; l->next = s; ++(l->data); cout << "Input next data:"; cin >> data; } } void ListTailInsert(LNode *&l) { ElemType data; LNode *s, *p; InitList(l); p = l; while(p->next) { p = p->next; } cout << "TailInsert input data(-1 to stop):"; cin >> data; while(data != -1) { s = new LNode; s->data = data; p->next = s; p = s; //保持p指针始终指向尾结点 ++(l->data); cout << "Input next data:"; cin >> data; } p->next = nullptr; //尾结点的next指向空 } bool GetElem(LNode *l, int& count, int &elem) { int index = 0; if(count < 0 || count > l->data) { return false; } else { l = l->next; while(l->next && index++ < count) { l = l->next; } elem = l->data; return true; } } bool LocateElem(LNode *l, int& count, ElemType &elem) { int index = 0; l = l->next; while(l->next) { ++index; if(l->data == elem) { count = index; return true; } l = l->next; } return false; } LNode *GetPtr(LNode *l, int i) { int index = 1; l = l->next; while(index++ < i) { l = l->next; } return l; } bool TailInsert(LNode* l, int i, int data) { LNode* s; LNode* p = l; if(i < 1 || i > l->data) { return false; } else { l = GetPtr(l, i); s = new LNode; s->data = data; s->next = l->next; l->next = s; ++(p->data); //头结点长度数据长度+1 return true; } } bool HeadInsert(LNode* l, int i, int data) { LNode* s; LNode* p = l; ElemType temp; if(i < 1 || i > l->data) { return false; } else { l = GetPtr(l, i); s = new LNode; s->data = data; s->next = l->next; l->next = s; temp = l->data; l->data = s->data; s->data = temp; ++(p->data); return true; } } bool DeleteElem(LNode* l, int i) { LNode* s; LNode* p = l; if(i < 1 || i > l->data) { return false; } else if(i == 1) { s = l->next; l->next = s->next; } else { l = GetPtr(l, i-1); s = l->next; l->next = s->next; } cout << s->data << " has been deleted." << endl; --(p->data); delete s; return true; } int GetListLength(LNode* l) { int length = 0; l = l->next; while(l) { l = l->next; ++length; } return length; } void DisplayList(LNode *l) { int i = 0; cout << "Data Length is " << l->data << endl; l = l->next; while(l != nullptr) { cout << "Data[" << i++ << "] = " << l->data << endl; l = l->next; } }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; char s[1111111], good[1111111]; int n, last; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); gets(s); n = strlen(s); last = -1; for (int i = 0; i < n; ++i) if (s[i] == '(') last = i;else { if (s[i] == ')' && last != -1) { good[last] = 1; last = -1; } if (s[i] != ' ' && (s[i] <'a' || s[i] >'z') && (s[i] <'A' || s[i]>'Z')) last = -1; } last = -1; for (int i = n - 1; i >= 0; --i) if (s[i] == ')') last = i;else { if (s[i] == '(' && last != -1) { good[last] = 1; last = -1; } if (s[i] != ' ' && (s[i] <'a' || s[i] >'z') && (s[i] <'A' || s[i]>'Z')) last = -1; } int ans = 0; for (int i = 0; i < n; i++) if ((s[i] == ')' || s[i] == '(') && !good[i]) ++ans; cout << ans << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2000-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Luca Venturi */ #include "core/pch.h" #include "modules/cache/multimedia_cache.h" #ifdef MULTIMEDIA_CACHE_SUPPORT OP_STATUS MultimediaCacheFile::ConstructPrivate(UINT8 suggested_flags, OpFileLength suggested_max_file_size, UINT16 suggested_max_segments) { OP_ASSERT(segments.GetCount()==0); BOOL exists=FALSE; RETURN_IF_ERROR(sfrw.Exists(exists)); // If the file header is invalid, truncate it if(exists) { OpFileLength len; RETURN_IF_ERROR(sfrw.GetFileLength(len)); if( len<MMCACHE_HEADER_SIZE || // Too short for the header sfrw.Read8()!='O' || // No Opera Multimedia Cache File sfrw.Read8()!='M' || sfrw.Read8()!='C' || sfrw.Read8()!='F' || sfrw.Read8()!=1) // No Version 1 { RETURN_IF_ERROR(sfrw.Truncate()); exists=FALSE; } } if(exists) // Read the header { // Read the remaining part of the header #ifdef DEBUG_ENABLE_OPASSERT OpFileLength pos; OP_ASSERT(OpStatus::IsSuccess(sfrw.GetReadFilePos(pos)) && pos==5); #endif header_flags=sfrw.Read8(); max_size=sfrw.Read64(); max_segments=sfrw.Read16(); segments.DeleteAll(); #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(OpStatus::IsSuccess(sfrw.GetReadFilePos(pos)) && pos==MMCACHE_HEADER_SIZE); #endif // Read the segments informations from the disk RETURN_IF_ERROR(LoadAllSegments(FALSE)); #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(OpStatus::IsSuccess(sfrw.GetReadFilePos(pos)) && pos==GetFullHeaderLength()); #endif } else // Write the header { #ifdef DEBUG_ENABLE_OPASSERT OpFileLength pos; OP_ASSERT(OpStatus::IsSuccess(sfrw.GetWriteFilePos(pos)) && pos==0); #endif header_flags=suggested_flags; RETURN_IF_ERROR(WriteInitialHeader()); RETURN_IF_ERROR(sfrw.Write64(suggested_max_file_size)); // Max File Size RETURN_IF_ERROR(sfrw.Write16(suggested_max_segments)); // Max number of segments #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(OpStatus::IsSuccess(sfrw.GetWriteFilePos(pos)) && pos==MMCACHE_HEADER_SIZE); #endif max_size=suggested_max_file_size; max_segments=suggested_max_segments; segments.DeleteAll(); if(!max_size && ! header_flags & MMCACHE_HEADER_64_BITS) max_size=2*1024*1024;//UINT_MAX-65536 OP_ASSERT(max_size<=UINT_MAX-65536 || (header_flags & MMCACHE_HEADER_64_BITS)); // Write the segment informations to the disk RETURN_IF_ERROR(WriteAllSegments(FALSE, FALSE)); } CheckInvariants(); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::ConstructFile(const uni_char* path, OpFileFolder folder, OpFileLength suggested_max_file_size, UINT16 suggested_max_segments) { OP_ASSERT(!ram); RETURN_IF_ERROR(sfrw.ConstructFile(path, folder, FALSE)); ram=FALSE; OP_NEW_DBG("MultimediaCacheFile::ConstructFile", "multimedia_cache.write"); OP_DBG((UNI_L("*** File %s constructed in path %d"), path, (int)folder)); return ConstructPrivate(MMCACHE_HEADER_64_BITS, suggested_max_file_size, suggested_max_segments); } OP_STATUS MultimediaCacheFile::ConstructMemory(OpFileLength suggested_max_file_size, UINT16 suggested_max_segments) { OP_ASSERT(!ram); OP_ASSERT(suggested_max_file_size>0); if(!suggested_max_file_size) return OpStatus::ERR_OUT_OF_RANGE; // Check that there are not strange side effects in converting to UINT32 OP_ASSERT(suggested_max_file_size+MMCACHE_HEADER_SIZE+suggested_max_segments*GetSegmentHeaderLength() + STREAM_BUF_SIZE == (OpFileLength)((UINT32)(suggested_max_file_size+MMCACHE_HEADER_SIZE+suggested_max_segments*GetSegmentHeaderLength() + STREAM_BUF_SIZE))); // Allocate enough memory for the requested size plus the header + STREAM_BUF_SIZE, because of a bug in streaming that can make the file a bit too big RETURN_IF_ERROR(sfrw.ConstructMemory((UINT32)(suggested_max_file_size+MMCACHE_HEADER_SIZE+suggested_max_segments*GetSegmentHeaderLength() + STREAM_BUF_SIZE))); ram=TRUE; return ConstructPrivate(MMCACHE_HEADER_64_BITS, suggested_max_file_size, suggested_max_segments); } OP_STATUS MultimediaCacheFile::WriteInitialHeader() { RETURN_IF_ERROR(sfrw.SetWriteFilePos(0)); RETURN_IF_ERROR(sfrw.Write8('O')); // Sign RETURN_IF_ERROR(sfrw.Write8('M')); RETURN_IF_ERROR(sfrw.Write8('C')); RETURN_IF_ERROR(sfrw.Write8('F')); RETURN_IF_ERROR(sfrw.Write8(1)); // Version RETURN_IF_ERROR(sfrw.Write8(header_flags)); // Flags return OpStatus::OK; } OP_STATUS MultimediaCacheFile::LoadAllSegments(BOOL reposition) { OP_ASSERT(segments.GetCount()==0); OP_ASSERT(max_segments>0); if(reposition) RETURN_IF_ERROR(sfrw.SetReadFilePos(MMCACHE_HEADER_SIZE)); else { OpFileLength pos; RETURN_IF_ERROR(sfrw.GetReadFilePos(pos)); OP_ASSERT(pos==MMCACHE_HEADER_SIZE); if(pos!=MMCACHE_HEADER_SIZE) return OpStatus::ERR_NOT_SUPPORTED; } if(segments.GetCount()!=0) return OpStatus::ERR_NOT_SUPPORTED; UINT8 guard_bytes=(header_flags & MMCACHE_HEADER_GUARDS)?1:0; OpFileLength header_full_size=GetSegmentPos(max_segments); OpFileLength content_virtual_position=header_full_size; // Length of the content contained in the segments so far (used to calculate the physical position in the disk) cached_size=0; // Load the segment informations from the file for(UINT16 cur_segment=0; cur_segment<max_segments; cur_segment++) { // Read the segment values OpFileLength content_start; OpFileLength content_len; OpFileLength file_start=content_virtual_position+(guard_bytes); UINT8 flags; if(header_flags & MMCACHE_HEADER_64_BITS) { content_start=sfrw.Read64(); content_len=sfrw.Read64(); } else { content_start=sfrw.Read32(); content_len=sfrw.Read32(); } flags=sfrw.Read8(); if(content_len==0) // This situation can happen for a crash or because the segments are finished { if(flags & MMCACHE_SEGMENT_NEW) // Crash: content lasts till the end of the file { OpFileLength file_len; RETURN_IF_ERROR(sfrw.GetFileLength(file_len)); content_len=file_len-file_start; // Content lasts till the end of the file // Don't remove this flag... it is usefull if(!content_len) { // Jump to the end of the header RETURN_IF_ERROR(sfrw.SetReadFilePos(header_full_size)); break; // Crash after updating the segment but before writing } } else // This segment is after the last one { // Jump to the end of the header RETURN_IF_ERROR(sfrw.SetReadFilePos(header_full_size)); break; } } cached_size+=content_len; // Create the segment and add it to the list MultimediaSegment *seg=OP_NEW(MultimediaSegment, ()); if(!seg) return OpStatus::ERR_NO_MEMORY; OP_STATUS ops; if( OpStatus::IsError(ops=seg->SetSegment(file_start, content_start, content_len, flags)) || OpStatus::IsError(ops=segments.Add(seg))) { OP_DELETE(seg); return ops; } if(flags & MMCACHE_SEGMENT_DIRTY) seg->to_be_discarded=TRUE; // Basically this segment cannot be used content_virtual_position+=guard_bytes+content_len; } OP_ASSERT(max_segments>=segments.GetCount()); #ifdef DEBUG_ENABLE_OPASSERT OpFileLength pos; OpFileLength file_len; OP_ASSERT(OpStatus::IsSuccess(sfrw.GetReadFilePos(pos)) && OpStatus::IsSuccess(sfrw.GetFileLength(file_len)) && // file_len == content_virtual_position && pos==header_full_size); #endif return OpStatus::OK; } OP_STATUS MultimediaCacheFile::CloseAll() { RETURN_IF_ERROR(WriteInitialHeader()); RETURN_IF_ERROR(WriteAllSegments(TRUE, TRUE)); RETURN_IF_ERROR(sfrw.Close()); segments.DeleteAll(); cached_size=0; return OpStatus::OK; } OP_STATUS MultimediaCacheFile::DeleteContent() { RETURN_IF_ERROR(sfrw.Truncate()); segments.DeleteAll(); cached_size=0; RETURN_IF_ERROR(WriteInitialHeader()); RETURN_IF_ERROR(WriteAllSegments(TRUE, TRUE)); return OpStatus::OK; } void MultimediaCacheFile::GetOptimisticFullRange(OpFileLength &start, OpFileLength &end) const { start=end=0; if(!GetSegmentsInUse()) return; for(UINT32 i=0, num=GetSegmentsInUse(); i<num; i++) { MultimediaSegment *seg=segments.Get(i); OP_ASSERT(seg); if(seg) { if(i==0 || seg->GetContentStart()<start) start=seg->GetContentStart(); if(i==0 || seg->GetContentEnd()>end) end=seg->GetContentEnd(); } } } OP_STATUS MultimediaCacheFile::WriteAllSegments(BOOL reposition, BOOL update_header) { OP_ASSERT(segments.GetCount()<=max_segments); OP_ASSERT(max_segments>0); OP_ASSERT(!update_header || reposition); // update_header requires reposition CheckInvariants(); if(reposition) { if(update_header) { RETURN_IF_ERROR(sfrw.SetWriteFilePos(MMCACHE_HEADER_SIZE-10)); RETURN_IF_ERROR(sfrw.Write64(max_size)); RETURN_IF_ERROR(sfrw.Write16(max_segments)); OpFileLength pos; RETURN_IF_ERROR(sfrw.GetWriteFilePos(pos)); OP_ASSERT(pos==MMCACHE_HEADER_SIZE); if(pos!=MMCACHE_HEADER_SIZE) return OpStatus::ERR_NOT_SUPPORTED; } else RETURN_IF_ERROR(sfrw.SetWriteFilePos(MMCACHE_HEADER_SIZE)); } else { OpFileLength pos; RETURN_IF_ERROR(sfrw.GetWriteFilePos(pos)); OP_ASSERT(pos==MMCACHE_HEADER_SIZE); if(pos!=MMCACHE_HEADER_SIZE) return OpStatus::ERR_NOT_SUPPORTED; } //if(segments.GetCount()!=max_segments) // return OpStatus::ERR_NOT_SUPPORTED; //UINT8 guard_bytes=(header_flags & MMCACHE_HEADER_GUARDS)?1:0; #ifdef DEBUG_ENABLE_OPASSERT OpFileLength header_full_size=(header_flags & MMCACHE_HEADER_64_BITS)? MMCACHE_HEADER_SIZE+17*max_segments:MMCACHE_HEADER_SIZE+9*max_segments; #endif // Write the segment informations to the file UINT16 cur_segment=0; for(; cur_segment<segments.GetCount(); cur_segment++) { MultimediaSegment *seg=segments.Get(cur_segment); OpFileLength content_start=0; OpFileLength content_len=0; UINT8 flags=0; if(seg) { OP_ASSERT(!seg->empty_space || seg->IsDirty()); content_start=seg->GetContentStart(); content_len=seg->GetContentLength()+seg->empty_space; flags=seg->GetFlags(); } // Write a segment header RETURN_IF_ERROR(MultimediaSegment::DirectWriteHeader(sfrw, header_flags, content_start, content_len, flags)); } // Write the segment informations to the file for(; cur_segment<max_segments; cur_segment++) { // Write a dummy segment header RETURN_IF_ERROR(MultimediaSegment::DirectWriteHeader(sfrw, header_flags, 0, 0, 0)); } //OP_ASSERT(max_segments==segments.GetCount()); #ifdef DEBUG_ENABLE_OPASSERT OpFileLength pos; OP_ASSERT(OpStatus::IsSuccess(sfrw.GetWriteFilePos(pos)) && pos == header_full_size); #endif CheckInvariants(); return OpStatus::OK; } OpFileLength MultimediaCacheFile::GetAvailableSpace() { OpFileLength avail_space=0; if(max_size>0) avail_space=max_size-cached_size; else avail_space=2047*1024*1024L-cached_size; // A limit of around 2 GB is simulated if(streaming) { for(UINT32 i=segments.GetCount(); i>0; i--) { MultimediaSegment *seg=segments.Get(i-1); if(seg) avail_space+=seg->empty_space; } } return avail_space; } #ifdef DEBUG_ENABLE_OPASSERT void MultimediaCacheFile::CheckInvariants() { OP_ASSERT(GetSegmentsInUse()<=max_segments); OpFileLength size=0; int num_new_segments=0; int num_dirty_segments=0; OpFileLength empty_space=0; if(!streaming) OP_ASSERT(consume_policy==CONSUME_NONE); for(UINT32 i=0, num=GetSegmentsInUse(); i<num; i++) { MultimediaSegment *seg=segments.Get(i); OP_ASSERT(seg); if(seg) { seg->CheckInvariants(); size+=seg->GetContentLength(); empty_space+=seg->empty_space; if(seg->IsNew()) num_new_segments++; if(seg->IsDirty()) num_dirty_segments++; if(seg->reserve_segment) { OP_ASSERT(seg->reserve_segment->file_offset+seg->reserve_segment->content_len+seg->reserve_segment->empty_space==seg->file_offset); } } } OP_ASSERT(size==cached_size || streaming); OP_ASSERT(size+empty_space==cached_size); OP_ASSERT(num_new_segments==0 || num_new_segments==1); OP_ASSERT(max_size==0 || max_size>=cached_size); if(streaming && deep_streaming_check) OP_ASSERT(segments.GetCount()<=2); if(streaming) OP_ASSERT(max_size>0); // That's the concept of streaming! :-) } #endif // DEBUG_ENABLE_OPASSERT OP_STATUS MultimediaCacheFile::WriteContent(OpFileLength content_position, const void *buf, UINT32 original_len, UINT32 &written_bytes) { UINT32 len=original_len; OpFileLength total_empty_space=0; if(streaming && consume_policy==CONSUME_ON_WRITE) { UINT32 consumed_bytes=0; total_empty_space=GetAvailableSpace(); if(total_empty_space<original_len) { RETURN_IF_ERROR(AutoConsume(original_len-(UINT32)total_empty_space, consumed_bytes)); len=(UINT32)(total_empty_space+consumed_bytes); OP_ASSERT(GetAvailableSpace()==len); } } RETURN_IF_ERROR(WriteContentKernel(content_position, buf, len, written_bytes)); // While streaming, in some situations, the content needs to be written partly in the Master segment and partly in the Reserve, but // WriteContentKernel() can only write to a single segment. // So if not everything has been written, a second write is attempted, to spread the content in both the segments if(streaming && written_bytes<original_len) { UINT32 bytes_temp; if(OpStatus::IsSuccess(WriteContentKernel(content_position+written_bytes, ((UINT8 *)buf)+written_bytes, len-written_bytes, bytes_temp))) written_bytes+=bytes_temp; } return OpStatus::OK; } OP_STATUS MultimediaCacheFile::WriteContentKernel(OpFileLength content_position, const void *buf, UINT32 len, UINT32 &written_bytes) { if(!sfrw.IsFileValid()) return OpStatus::ERR_NOT_SUPPORTED; OP_ASSERT(content_position != FILE_LENGTH_NONE); OP_ASSERT(buf); OP_ASSERT(len>0); if(!buf) return OpStatus::ERR_NULL_POINTER; MultimediaSegment *segment=NULL; OpFileLength file_pos; written_bytes=0; if(len==0) return OpStatus::OK; RETURN_IF_ERROR(GetWriteSegmentByContentPosition(segment, content_position, file_pos, TRUE)); OP_ASSERT(segment); OP_ASSERT(file_pos>=MMCACHE_HEADER_SIZE); if(!segment) return OpStatus::ERR_NULL_POINTER; OpFileLength empty_space=(streaming)?segment->empty_space:0; OpFileLength extension_bytes=empty_space; BOOL last_segment=GetSegmentsInUse() && segment==segments.Get(GetSegmentsInUse()-1); RETURN_IF_ERROR(WriteContentDirect(file_pos, buf, len, empty_space, written_bytes, last_segment)); segment->AddContent(written_bytes, extension_bytes); // Also update the empty space and cache_dize of the segment if(segment->reserve_segment) { // The reserve segment should have no content in this case (just created to allow streaming later) // If it's not the case, the content of the reserve is dropped to avoid corruption OP_ASSERT(segment->reserve_segment->GetContentLength()==0); //OP_ASSERT(!segment->empty_space); /* It can happen in legitimate cases */ segment->reserve_segment->empty_space+=segment->reserve_segment->content_len; segment->reserve_segment->content_len=0; segment->reserve_segment->content_start=segment->content_start+segment->content_len+segment->empty_space; // The reserve points to the complete end of the segment, empty space included } OP_ASSERT(!empty_space || (empty_space>=written_bytes || (last_segment && extension_bytes>0 && extension_bytes<=max_size-cached_size))); // Compute Empty space and cached size cached_size+=extension_bytes; // If the empty space is used, the cache_size does not change CheckInvariants(); return OpStatus::OK; } #ifdef SELFTEST OP_STATUS MultimediaCacheFile::DebugAddSegment(MultimediaSegment *seg) { OP_ASSERT(seg); if(!seg) return OpStatus::ERR_NO_MEMORY; // Check that the segment is not yet in the array and that there is no overlapping if(max_segments) { OpAutoVector<MultimediaSegment> covered; RETURN_IF_ERROR(GetUnsortedCoverage(covered, seg->GetContentStart(), seg->GetContentLength())); OP_ASSERT(covered.GetCount()==0); } // Add to the array RETURN_IF_ERROR(segments.Add(seg)); OP_ASSERT(segments.Get(segments.GetCount()-1)==seg); if(max_segments<segments.GetCount()) max_segments=segments.GetCount(); cached_size+=seg->GetContentLength(); if(seg->IsDirty()) seg->to_be_discarded=TRUE; // Simulate a load CheckInvariants(); return OpStatus::OK; } OpFileLength MultimediaCacheFile::DebugGetSegmentLength(int index) { return segments.Get(index)->GetContentLength(); } OpFileLength MultimediaCacheFile::DebugGetSegmentEmptySpace(int index) { return segments.Get(index)->empty_space; } OpFileLength MultimediaCacheFile::DebugGetSegmentContentStart(int index) { return segments.Get(index)->GetContentStart(); } #endif // SELFTEST OP_STATUS MultimediaCacheFile::WriteContentDirect(OpFileLength file_position, const void *buf, UINT32 size, OpFileLength usable_empty_space, UINT32 &written_bytes, BOOL last_segment) { written_bytes=0; if(max_size) { OP_ASSERT(!usable_empty_space || streaming); if(cached_size>=max_size && !usable_empty_space) // It's ok... if cached_size>max_size, size is supposed to have been reduced too late... return OpStatus::ERR_OUT_OF_RANGE; //OpStatus::OK; if(usable_empty_space) { UINT32 size_available; if(last_segment) size_available=(UINT32)((max_size-cached_size) + usable_empty_space); else size_available=(UINT32)usable_empty_space; if(size>size_available) size=size_available; } else if(cached_size+size>max_size) size=(UINT32)(max_size-cached_size); OP_ASSERT(size>0); } RETURN_IF_ERROR(sfrw.SetWriteFilePos(file_position)); RETURN_IF_ERROR(sfrw.WriteBuf(buf, size)); written_bytes=size; return OpStatus::OK; } void MultimediaSegment::AddContent(OpFileLength size, OpFileLength &extension_bytes) { content_len+=size; if(size>empty_space) { extension_bytes=size-empty_space; empty_space=0; } else { extension_bytes=0; empty_space-=size; } } BOOL MultimediaSegment::ContainsContentBeginning(OpFileLength start, OpFileLength &bytes_available, OpFileLength &file_pos) { if(start>=GetContentStart() && start<GetContentEnd()) { bytes_available=GetContentEnd()-start; file_pos=GetFileOffset()+start-GetContentStart(); OP_ASSERT(file_pos+bytes_available==GetFileOffset()+GetContentLength()); return TRUE; } return FALSE; } BOOL MultimediaSegment::ContainsPartialContent(OpFileLength requested_start, OpFileLength requested_len, OpFileLength &available_start, OpFileLength &available_len, OpFileLength &file_pos) { OpFileLength requested_end; if(requested_len==FILE_LENGTH_NONE) { if(requested_start>=GetContentEnd()) return FALSE; requested_end=GetContentEnd(); } else requested_end=requested_start+requested_len; if( (requested_start >= GetContentStart() && requested_start < GetContentEnd()) || // Requested start included in the segment (requested_end-1 >= GetContentStart() && requested_end-1 < GetContentEnd()) || // Requested end included in the segment (GetContentStart() >= requested_start && GetContentStart() < requested_end ) || // Segment start included in the request (GetContentEnd()-1 >= requested_start && GetContentEnd()-1 < requested_end )) // Segment end included in the request { OpFileLength start=(requested_start<GetContentStart())?GetContentStart():requested_start; OpFileLength end=(requested_end<GetContentEnd())?requested_end:GetContentEnd(); OP_ASSERT(end>=start); OP_ASSERT(start>=GetContentStart()); OP_ASSERT(end<=GetContentEnd()); OP_ASSERT(end>=start); available_start=start; available_len=end-start; file_pos=file_offset+start-GetContentStart(); return TRUE; } return FALSE; } BOOL MultimediaSegment::CanAppendContent(OpFileLength start, OpFileLength &file_pos) { if(start==GetContentEnd()) { file_pos=GetFileOffset()+GetContentLength(); return TRUE; } return FALSE; } OP_STATUS MultimediaCacheFile::GetWriteSegmentByContentPosition(MultimediaSegment *&segment, OpFileLength content_position, OpFileLength &file_pos, BOOL update_disk) { OP_ASSERT(content_position != FILE_LENGTH_NONE); /* The write can happen: * - on the last segment (preferred, also to let the file grow) * - on a segment with empty space (if streaming is allowed) * - on a new segment */ // Check the last segment if(GetSegmentsInUse()>0 && (max_size==0 || cached_size<max_size)) // This segment cannot have priority if the disk is full { UINT16 index=GetSegmentsInUse()-1; MultimediaSegment *seg=segments.Get(index); OP_ASSERT(seg); if(seg) { // Try to append if(seg->CanAppendContent(content_position, file_pos)) { OP_ASSERT(segments.Get(index)==seg); if(!seg->IsNew()) // Mark the segment as new { seg->SetNew(TRUE); if(update_disk) RETURN_IF_ERROR(seg->UpdateDisk(header_flags, sfrw, GetSegmentPos(index))); } segment=seg; return OpStatus::OK; } else if(seg->IsNew()) // If the segment is new, close it! { seg->SetNew(FALSE); if(update_disk) RETURN_IF_ERROR(seg->UpdateDisk(header_flags, sfrw, GetSegmentPos(index))); } } } BOOL could_append_but_full=FALSE; // Check if it can be "streamed" on a segment with empty space // Priority is given to the master segment (with upper index), not to the reserve, even if this should no longer be a requirement if(streaming) { for(int i=GetSegmentsInUse(); i>0; i--) { MultimediaSegment *seg=segments.Get(i-1); OP_ASSERT(seg); if(seg && seg->CanAppendContent(content_position, file_pos)) { if(seg->empty_space) // Check if the segment can contain at least one more byte { segment=seg; return OpStatus::OK; } else could_append_but_full=TRUE; // Segment Full. Keep searching... } } } // If it can be contained in a segment already written (also the last one!), return an error! Overwrite is not supported. for(int i=GetSegmentsInUse(); i>0; i--) { MultimediaSegment *seg=segments.Get(i-1); OpFileLength bytes_available; OpFileLength pos; OP_ASSERT(seg); if(seg && seg->ContainsContentBeginning(content_position, bytes_available, pos)) return OpStatus::ERR_NOT_SUPPORTED; } /* New segment required */ // !!! WARNING: this condition is met when there is a seek on write, while streaming ==> Drop everything!!! // This has to be performed because while streaming all the size is pre allocated, and it is not possible to create new segments to // contain a write in a different position than expected if(streaming && auto_delete_on_streaming && !could_append_but_full && GetSegmentsInUse()) RETURN_IF_ERROR(DeleteContent()); // Check if we are over the maximum number of segments if(GetSegmentsInUse()>=max_segments) return OpStatus::ERR_NOT_SUPPORTED; // Prevent the useless creation of a new segment, also because the write will fail triggering a bug if(max_size>0 && cached_size>=max_size) return OpStatus::ERR_OUT_OF_RANGE; MultimediaSegment *seg=OP_NEW(MultimediaSegment, ()); OpFileLength len; if(!seg) return OpStatus::ERR_NO_MEMORY; OP_STATUS ops; if( OpStatus::IsError(ops=sfrw.GetFileLength(len)) || OpStatus::IsError(ops=seg->SetSegment(len, content_position, 0, MMCACHE_SEGMENT_NEW)) || OpStatus::IsError(ops=segments.Add(seg))) { OP_DELETE(seg); return ops; } UINT16 index=GetSegmentsInUse()-1; OP_ASSERT(segments.Get(index)==seg); // In case of streaming, the segment is created as using all the space available, which simplify several problems if(!index && streaming && max_size>0) { OP_ASSERT(cached_size==0); seg->content_len=0; seg->empty_space=max_size; seg->SetDirty(TRUE); cached_size=max_size; } if(update_disk) RETURN_IF_ERROR(seg->UpdateDisk(header_flags, sfrw, GetSegmentPos(index))); segment=seg; file_pos=segment->GetFileOffset(); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::RetrieveFromEmptySpace(OpFileLength start, OpFileLength &bytes_available, OpFileLength &file_pos) { OP_ASSERT(enable_empty_space_recover); if(!enable_empty_space_recover) return OpStatus::ERR_NOT_SUPPORTED; // Look for the segment that, in its reserve, can contain this range // Please note that we assume that the segment itself cannot contains it // We can visualize the two segments (master and reserve) in this way: // // || Reserve Segment || Master Segment || // || More Data | Empty Space || Data || // // Example: 256 bytes stream cache, downloaded from 0 to 272, 64 byte read, 16 "lost", 48 still in Empty Space // || 256... 272 | 16... 63 || 64..255 || // // So we are looking to see if start is incuded in the empty space // It has to be understood that the Empty Space contains the Data that have been consumed by the, master segments, but that are // still available on the disk. So they logically start before the beginning of the master segment for(UINT32 i=GetSegmentsInUse(); i>0; i--) { MultimediaSegment *seg=segments.Get(i-1); OP_ASSERT(seg && !seg->ContainsContentBeginning(start, bytes_available, file_pos)); if( seg && seg->EmptySpaceContains(start)) { bytes_available=seg->content_start-start; // The beginning of the master is the end of the "virtual empty segment" file_pos=seg->file_offset-bytes_available; // Check that it is inside the reserve segment (in the empty spcae) and before the master segment OP_ASSERT(file_pos>=seg->reserve_segment->file_offset+seg->reserve_segment->content_len && file_pos<seg->file_offset && file_pos<seg->reserve_segment->file_offset+seg->reserve_segment->content_len+seg->reserve_segment->empty_space); return OpStatus::OK; } } return OpStatus::ERR_NO_SUCH_RESOURCE; } BOOL MultimediaSegment::EmptySpaceContains(OpFileLength content_position) { return reserve_segment && content_start>content_position && content_start - reserve_segment->empty_space <= content_position && reserve_segment->empty_space>0; } OP_STATUS MultimediaCacheFile::ReadContent(OpFileLength content_position, void *buf, UINT32 size, UINT32 &read_bytes) { CheckInvariants(); if(!sfrw.IsFileValid()) return OpStatus::ERR_NOT_SUPPORTED; MultimediaSegment *found_seg=NULL; OpFileLength bytes_available=0; OpFileLength file_pos=0; UINT32 seg_index=0; read_bytes=0; // Look for the segment that contains the position for(UINT32 i=GetSegmentsInUse(); i>0 && !found_seg; i--) { MultimediaSegment *seg=segments.Get(i-1); OP_ASSERT(seg); if(seg && seg->ContainsContentBeginning(content_position, bytes_available, file_pos)) { found_seg=seg; seg_index=i-1; } } if(!found_seg) { if(streaming && enable_empty_space_recover) // Check if the content is stilla vailable in the reserve segment RETURN_IF_ERROR(RetrieveFromEmptySpace(content_position, bytes_available, file_pos)); else return OpStatus::ERR_NO_SUCH_RESOURCE; } OpFileLength bytes_to_read=(bytes_available<size)?bytes_available:size; RETURN_IF_ERROR(sfrw.SetReadFilePos(file_pos)); RETURN_IF_ERROR(sfrw.ReadBuf(buf, (UINT32) bytes_to_read)); OP_ASSERT(bytes_to_read<UINT_MAX); read_bytes=(UINT32)bytes_to_read; // If the bytes are retrieved from the empty space, there is no need to consume them, as at the moment this would require a // second call to retrieve the bytes in the master segment // found_seg then it's NULL, and it's fine if(streaming && found_seg && consume_policy==CONSUME_ON_READ) { OpFileLength skip=content_position-found_seg->content_start; // Bytes to skip OP_ASSERT(found_seg->content_start<=content_position); OP_ASSERT(skip==0 || (skip>0 && skip<=found_seg->content_len)); OP_ASSERT(found_seg->content_len>=read_bytes+skip); // If a seek read is detected (skip>0), the bytes before the new position are dropped. // This is unavoidable, else we would need to create a new segment to contain the bytes that have been // skipped but not consumed. This potentially waste bandwidth, but it also solves many problems. // Otherwise, ConsumeBytes() should be somewhat exposed to URL, and called explicitly by the media module // The problem is that if the skip affect the reserve segment, we also need to skip all the bytes in the master, // which will trigger a reorganization... // For semplicity, we apply a shortcut only valid for 2 indexes OP_ASSERT(!deep_streaming_check || GetSegmentsInUse()<=2); if(!found_seg->reserve_segment && GetSegmentsInUse()==2) // Check if this segment is the reserve { OP_ASSERT(seg_index==0 || seg_index==1); int master_seg_index=1-seg_index; MultimediaSegment *master_seg=segments.Get(master_seg_index); OP_ASSERT(master_seg && master_seg!=found_seg); OP_ASSERT(master_seg->reserve_segment == found_seg); OP_ASSERT(master_seg->content_start < found_seg->content_start && master_seg->content_start+master_seg->content_len < content_position); RETURN_IF_ERROR(ConsumeBytes(master_seg_index, master_seg->content_start, (UINT32)(master_seg->content_len))); OP_ASSERT(!deep_streaming_check || GetSegmentsInUse()<=2); // Shortcut: consuming bytes will promote the reserve to master OP_ASSERT(master_seg->reserve_segment == found_seg); OP_ASSERT(!found_seg->content_len && !found_seg->empty_space); OP_ASSERT(master_seg->content_start < content_position && master_seg->content_start+master_seg->content_len>=content_position); OP_ASSERT(segments.Get(master_seg_index)==master_seg); RETURN_IF_ERROR(ConsumeBytes(master_seg_index, master_seg->content_start, (UINT32)(content_position-master_seg->content_start))); OP_ASSERT(!deep_streaming_check || GetSegmentsInUse()<=2); } else // This segment is the master RETURN_IF_ERROR(ConsumeBytes(seg_index, found_seg->content_start, (UINT32)(read_bytes+skip))); } CheckInvariants(); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::ConsumeBytes(int seg_index, OpFileLength content_position, UINT32 bytes_to_consume) { MultimediaSegment *seg=segments.Get(seg_index); OP_ASSERT(seg); if(!seg) return OpStatus::ERR_NULL_POINTER; OP_ASSERT(content_position>=seg->content_start && content_position+bytes_to_consume<=seg->content_start+seg->content_len); // Mark the segment as dirty, updating also the status on the disk if(!seg->IsDirty()) { seg->SetDirty(TRUE); RETURN_IF_ERROR(seg->UpdateDisk(header_flags, sfrw, GetSegmentPos(seg_index))); seg->SetNew(FALSE); } OP_ASSERT(seg->IsDirty()); // Check if there is already a reserve segment if(!seg->reserve_segment) { seg->reserve_segment=OP_NEW(MultimediaSegment, ()); if(!seg->reserve_segment) return OpStatus::ERR_NO_MEMORY; OP_STATUS ops; // The reserve segment point at the beginning of the segment itself, and it's empty if( OpStatus::IsError(ops=seg->reserve_segment->SetSegment(seg->file_offset, seg->content_start+seg->content_len+seg->empty_space, 0, MMCACHE_SEGMENT_DIRTY)) || OpStatus::IsError(ops=segments.Add(seg->reserve_segment))) { OP_DELETE(seg->reserve_segment); return ops; } // Shortcut only valid because we force the use of two segments int reserve_seg_index=segments.GetCount()-1; // Checks that the shortcut is valid OP_ASSERT(segments.Get(reserve_seg_index)==seg->reserve_segment); // Swap the segments, to have the master after the reserve (even if this should no longer be a concern) segments.Replace(seg_index, seg->reserve_segment); segments.Replace(reserve_seg_index, seg); // Swap the indexes int t_index=seg_index; seg_index=reserve_seg_index; reserve_seg_index=t_index; OP_ASSERT(seg_index>reserve_seg_index); // Update the situation on the disk RETURN_IF_ERROR(seg->reserve_segment->UpdateDisk(header_flags, sfrw, GetSegmentPos(reserve_seg_index))); RETURN_IF_ERROR(seg->UpdateDisk(header_flags, sfrw, GetSegmentPos(seg_index))); CheckInvariants(); } OpFileLength dumped_bytes=0; RETURN_IF_ERROR(seg->ConsumeBytes(content_position, bytes_to_consume, dumped_bytes)); CheckInvariants(); OP_ASSERT(dumped_bytes<=cached_size); // If the master segment is empty, the reserve is promoted to master if(!seg->content_len) { #ifdef DEBUG_ENABLE_OPASSERT OpFileLength aggregated_space=seg->content_len+seg->empty_space+seg->reserve_segment->content_len+seg->reserve_segment->empty_space; #endif // Fill the master segment with the content of the reserve // WARNING: it is supposed to work even if the Reserve segment has a reserve segment by itself //seg->content_start=seg->reserve_segment->content_start; seg->content_len=seg->reserve_segment->content_len; seg->file_offset=seg->reserve_segment->file_offset; seg->empty_space+=seg->reserve_segment->empty_space; // Preserve the empty space // Reset the reserve segment, so it is like when it has been created seg->reserve_segment->content_start=seg->content_start+seg->content_len+seg->empty_space; // The reserve points to the complete end of the segment, empty space included seg->reserve_segment->content_len=0; seg->reserve_segment->empty_space=0; #ifdef DEBUG_ENABLE_OPASSERT OpFileLength aggregated_space2=seg->content_len+seg->empty_space+seg->reserve_segment->content_len+seg->reserve_segment->empty_space; OP_ASSERT(aggregated_space2 == aggregated_space); OP_ASSERT(aggregated_space2 == seg->content_len+seg->empty_space); #endif seg->CheckInvariants(); seg->reserve_segment->CheckInvariants(); } CheckInvariants(); return OpStatus::OK; } int MultimediaCacheFile::FindSegmentForAutoConsume() { MultimediaSegment *found_seg=NULL; int found_seg_index=-1; for(UINT32 i=0, num=GetSegmentsInUse(); i<num; i++) { MultimediaSegment *seg=segments.Get(i); if(seg && seg->content_len>0 && (!found_seg || seg->content_start < found_seg->content_start)) { found_seg=seg; found_seg_index=i; } } return found_seg_index; } OP_STATUS MultimediaCacheFile::AutoConsume(UINT32 bytes_to_consume, UINT32 &bytes_consumed) { bytes_consumed=0; OP_ASSERT(streaming); if(!streaming) return OpStatus::ERR_NOT_SUPPORTED; do { int seg_index=FindSegmentForAutoConsume(); if(seg_index<0) break; MultimediaSegment *seg=segments.Get(seg_index); UINT32 bytes_to_consume_now=(UINT32)((seg->content_len>bytes_to_consume-bytes_consumed)?bytes_to_consume-bytes_consumed:seg->content_len); RETURN_IF_ERROR(ConsumeBytes(seg_index, seg->content_start, bytes_to_consume_now)); bytes_consumed+=bytes_to_consume_now; } while(bytes_consumed<bytes_to_consume); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::GetUnsortedCoverage(OpAutoVector<MultimediaSegment> &out_segments, OpFileLength start, OpFileLength len) { OP_ASSERT(start != FILE_LENGTH_NONE); OP_ASSERT(len>0 || len==FILE_LENGTH_NONE); OP_ASSERT(out_segments.GetCount()==0); if(start==FILE_LENGTH_NONE) return OpStatus::ERR_OUT_OF_RANGE; // Look for the segments in the range requested for(UINT32 i=0, num=GetSegmentsInUse(); i<num; i++) { MultimediaSegment *seg=segments.Get(i); OpFileLength available_start=0; OpFileLength available_len=0; OpFileLength file_pos=0; OP_ASSERT(seg); if(seg && !seg->HasToBeDiscarded() && seg->ContainsPartialContent(start, len, available_start, available_len, file_pos)) { MultimediaSegment *new_seg=OP_NEW(MultimediaSegment, (file_pos, available_start, available_len)); if(!new_seg) return OpStatus::ERR_NO_MEMORY; OP_STATUS ops=out_segments.Add(new_seg); if(OpStatus::IsError(ops)) { OP_DELETE(new_seg); return ops; } } } CheckInvariants(); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::GetSortedCoverage(OpAutoVector<MultimediaSegment> &segments, OpFileLength start, OpFileLength len, BOOL merge) { RETURN_IF_ERROR(GetUnsortedCoverage(segments, start, len)); // This call also check the parameters // Shell sort on GetContentStart() UINT32 num=segments.GetCount(); UINT32 inc=(num+1)/2; while(inc > 0) { for(UINT32 i = inc; i<num; i++) { MultimediaSegment *temp=segments.Get(i); MultimediaSegment *cmp_seg=NULL; OpFileLength cur_start=(temp)?temp->GetContentStart():0; UINT32 j=i; OP_ASSERT(temp); while(j >= inc && (cmp_seg=segments.Get(j - inc))!= NULL && cmp_seg->GetContentStart() > cur_start) { segments.Replace(j, cmp_seg); j = j - inc; } OP_ASSERT(cmp_seg); segments.Replace(j, temp); } inc = (UINT32 ) ((inc+1) / 2.2); } // Merge if(merge) { for(UINT32 i=num; i>1; i--) { MultimediaSegment *cur=segments.Get(i-1); MultimediaSegment *prev=segments.Get(i-2); OP_ASSERT(cur && prev && cur->GetContentStart()>prev->GetContentStart()); if(cur && prev && cur->GetContentStart()==prev->GetContentEnd()) { prev->SetLength(prev->GetContentLength() + cur->GetContentLength()); segments.Remove(i-1); OP_DELETE(cur); } } } CheckInvariants(); return OpStatus::OK; } OP_STATUS MultimediaCacheFile::GetMissingCoverage(OpAutoVector<StorageSegment> &missing, OpFileLength start, OpFileLength len) { OpAutoVector<MultimediaSegment> covered; // Segment available // This call also check the parameters // Merge or no merge is the same (from a functional POV), as the segments are sorted. // But I expect no merge to be slightly faster RETURN_IF_ERROR(GetSortedCoverage(covered, start, len, FALSE)); OpFileLength cur=start; OpFileLength end=(len==FILE_LENGTH_NONE)?FILE_LENGTH_NONE:start+len; // Go through the ordered segments, marking what is missing for(int i=0, segs=covered.GetCount(); i<segs && (cur<end ||len==FILE_LENGTH_NONE); i++) { OP_ASSERT(covered.Get(i)); if(covered.Get(i)) { if(covered.Get(i)->GetContentStart()<=cur) { OP_ASSERT(covered.Get(i)->GetContentStart()==cur || i==0); // Only the first segment could start before the range OP_ASSERT(covered.Get(i)->GetContentEnd()>cur); // The real end (the last byte is excluded) cannot be before the segment // Even if the assert fails, this is not causing problems to the method, but it means problems in other parts if(covered.Get(i)->GetContentEnd()>cur) // Just to be on the safe side... cur=covered.Get(i)->GetContentEnd(); } else { OP_ASSERT(covered.Get(i)->GetContentEnd()<end || len==FILE_LENGTH_NONE); // Granted by GetSortedCoverage() StorageSegment *seg=OP_NEW(StorageSegment, ()); if(!seg) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(missing.Add(seg)); OP_ASSERT(covered.Get(i)->GetContentStart()>cur); // No other cases are possible seg->content_start=cur; seg->content_length=covered.Get(i)->GetContentStart()-cur; cur=covered.Get(i)->GetContentEnd(); OP_ASSERT(cur<end || i==segs-1 || len==FILE_LENGTH_NONE); } } } // end for // Add the last segment, if it has not been covered if(cur<end && len!=FILE_LENGTH_NONE) { StorageSegment *seg=OP_NEW(StorageSegment, ()); if(!seg) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(missing.Add(seg)); seg->content_start=cur; seg->content_length=end-cur; } CheckInvariants(); return OpStatus::OK; } void MultimediaCacheFile::GetPartialCoverage(OpFileLength position, BOOL &available, OpFileLength &length, BOOL multiple_segments) { OP_ASSERT(position != FILE_LENGTH_NONE); length=0; available = FALSE; if(position==FILE_LENGTH_NONE) return; MultimediaSegment *closest_seg=NULL; int num_seg=0; do { available=FALSE; // Look for the segment that contain the position for(UINT32 i=0, num=GetSegmentsInUse(); i<num; i++) { MultimediaSegment *seg=segments.Get(i); if(seg && !seg->HasToBeDiscarded()) { // Check if it is the right segment if(seg->GetContentStart()<=position && seg->GetContentEnd()>position) { available=TRUE; length+=seg->GetContentEnd()-position; if(!multiple_segments) return; position=seg->GetContentEnd(); // Look for the next segment num_seg++; break; } else if(enable_empty_space_recover && seg->EmptySpaceContains(position)) // Check empty space in reserve segment { OP_ASSERT(seg->GetContentStart()>position); available=TRUE; length+=seg->GetContentStart()-position; if(!multiple_segments) return; position=seg->GetContentStart(); // Look for the next segment num_seg++; break; } // Check if it is the closest segment (after the position) if(seg->GetContentStart()>position && seg->GetContentLength()>0 && (!closest_seg || seg->GetContentStart()<closest_seg->GetContentStart())) closest_seg=seg; } } } while(available); available=num_seg>0; if(!available && closest_seg) { length=closest_seg->GetContentStart()-position; // Recover bytes from empty spacec if(enable_empty_space_recover && closest_seg->reserve_segment) { OP_ASSERT(closest_seg->reserve_segment->empty_space<length); // Else it should have been marked as available if(closest_seg->reserve_segment->empty_space<length) length-=closest_seg->reserve_segment->empty_space; } } } #ifdef SELFTEST int MultimediaCacheFile::DebugGetNewSegments() { int num_new_segments=0; for(UINT32 i=0; i<GetSegmentsInUse(); i++) { MultimediaSegment *seg=segments.Get(i); if(seg && seg->IsNew()) num_new_segments++; } return num_new_segments; } int MultimediaCacheFile::DebugGetDirtySegments() { int num_dirty_segments=0; for(UINT32 i=0; i<GetSegmentsInUse(); i++) { MultimediaSegment *seg=segments.Get(i); if(seg && seg->IsDirty()) num_dirty_segments++; } return num_dirty_segments; } #endif // SELFTEST OP_STATUS MultimediaSegment::UpdateDisk(UINT8 header_flags, SimpleFileReadWrite &sfrw, UINT32 header_pos) { RETURN_IF_ERROR(sfrw.SetWriteFilePos(header_pos)); return MultimediaSegment::DirectWriteHeader(sfrw, header_flags, content_start, content_len, flags); } OP_STATUS MultimediaSegment::DirectWriteHeader(SimpleFileReadWrite &sfrw, UINT8 header_flags, OpFileLength start, OpFileLength len, UINT8 segment_flags) { if(header_flags & MMCACHE_HEADER_64_BITS) { RETURN_IF_ERROR(sfrw.Write64(start)); RETURN_IF_ERROR(sfrw.Write64(len)); } else { RETURN_IF_ERROR(sfrw.Write32((UINT32)start)); RETURN_IF_ERROR(sfrw.Write32((UINT32)len)); } RETURN_IF_ERROR(sfrw.Write8(segment_flags)); return OpStatus::OK; } OP_STATUS MultimediaSegment::SetSegment(OpFileLength file_start, OpFileLength segment_start, OpFileLength segment_len, UINT8 segment_flags) { content_start=segment_start; content_len=segment_len; file_offset=file_start; flags=segment_flags; CheckInvariants(); // Some controls if(content_start == FILE_LENGTH_NONE) { content_start=0; flags=MMCACHE_SEGMENT_DIRTY; // Disable segment } if(file_offset == FILE_LENGTH_NONE) { file_offset=0; flags=MMCACHE_SEGMENT_DIRTY; // Disable segment, but in this case it is not enough return OpStatus::ERR_OUT_OF_RANGE; } if(content_len == FILE_LENGTH_NONE) { content_len=0; flags=MMCACHE_SEGMENT_DIRTY; // Disable segment, but in this case it is not enough return OpStatus::ERR_OUT_OF_RANGE; } OP_ASSERT(content_len>0 || (segment_flags & MMCACHE_SEGMENT_NEW) || (segment_flags & MMCACHE_SEGMENT_DIRTY) ); return OpStatus::OK; } OP_STATUS MultimediaSegment::ConsumeBytes(OpFileLength content_position, UINT32 bytes_to_consume, OpFileLength &dumped_bytes) { OP_ASSERT(reserve_segment); OP_ASSERT(content_position>=content_start); OP_ASSERT(content_position<content_start+content_len); if(!reserve_segment) return OpStatus::ERR_NULL_POINTER; if(content_position<content_start || content_position>=content_start+content_len) return OpStatus::ERR_OUT_OF_RANGE; CheckInvariants(); // Check that the reserve segment is coherent // WARNING: if a read occurs in the middle of the segment, all the previous content is discarded // Dump the bytes from the current segment dumped_bytes=content_position-content_start+bytes_to_consume; content_start=content_position+dumped_bytes; content_len-=dumped_bytes; file_offset+=dumped_bytes; // Add empty space to the reserve segment reserve_segment->empty_space+=dumped_bytes; CheckInvariants(); // Check that the reserve segment is coherent return OpStatus::OK; } #ifdef DEBUG_ENABLE_OPASSERT void MultimediaSegment::CheckInvariants() { OP_ASSERT(content_start!=FILE_LENGTH_NONE && content_len!=FILE_LENGTH_NONE && file_offset>=MMCACHE_HEADER_SIZE && ( (flags&3) == flags)); if(reserve_segment) { OP_ASSERT(reserve_segment->file_offset+reserve_segment->content_len+reserve_segment->empty_space==file_offset); OP_ASSERT(reserve_segment->content_start==content_start+content_len+empty_space); } if(HasToBeDiscarded()) OP_ASSERT(IsDirty()); } #endif // DEBUG_ENABLE_OPASSERT BOOL MultimediaCacheFileDescriptor::Eof() const { OP_ASSERT(mcf); if(!mcf) return TRUE; OpFileLength start; OpFileLength end; mcf->GetOptimisticFullRange(start, end); return read_pos>=end; } OP_STATUS MultimediaCacheFileDescriptor::Write(const void* data, OpFileLength len) { OP_ASSERT(mcf); if(!mcf) return OpStatus::ERR_NULL_POINTER; OP_ASSERT(!read_only); if(read_only) return OpStatus::ERR_NOT_SUPPORTED; OP_ASSERT(len<=UINT_MAX); OP_ASSERT(write_pos!=FILE_LENGTH_NONE); UINT32 written_bytes; RETURN_IF_ERROR(mcf->WriteContent(write_pos, data, (UINT32)len, written_bytes)); OP_NEW_DBG("MultimediaCacheFileDescriptor::Write", "multimedia_cache.write"); if(written_bytes!=len) { OP_DBG((UNI_L("*** Error Written %d bytes (instead of %d) on position %d"), (UINT32)written_bytes, (UINT32)len, (UINT32)write_pos)); return OpStatus::ERR; } OP_DBG((UNI_L("*** Written %d bytes on position %d"), (UINT32)written_bytes, (UINT32)write_pos)); write_pos+=len; return OpStatus::OK; } void MultimediaCacheFileDescriptor::SetReadPosition(OpFileLength pos) { OP_NEW_DBG("MultimediaCacheFileDescriptor::SetReadPosition", "multimedia_cache.read"); OP_DBG((UNI_L("*** Read position set to %d"), (UINT32)pos)); read_pos=pos; } void MultimediaCacheFileDescriptor::SetWritePosition(OpFileLength pos) { OP_NEW_DBG("MultimediaCacheFileDescriptor::SetWritePosition", "multimedia_cache.write"); OP_DBG((UNI_L("*** Write position set to %d"), (UINT32)pos)); write_pos=pos; } OP_STATUS MultimediaCacheFileDescriptor::Read(void* data, OpFileLength len, OpFileLength* bytes_read) { if(!mcf) return OpStatus::ERR_NULL_POINTER; OP_ASSERT(len<=UINT_MAX); UINT32 bytes_read32=0; UINT32 bytes_temp=1; OP_NEW_DBG("MultimediaCacheFileDescriptor::Read", "multimedia_cache.read"); if(bytes_read) *bytes_read=0; // Read multiple times, because the segment can be finished but the content can continue in another one... while(bytes_read32<len && bytes_temp) { OP_STATUS ops=mcf->ReadContent(read_pos+bytes_read32, ((unsigned char *)data)+bytes_read32, (UINT32)len-bytes_read32, bytes_temp); if(OpStatus::IsError(ops) && !bytes_read32) // No bytes with an error, it's usually a real error { if(ops==OpStatus::ERR_NO_SUCH_RESOURCE) { OP_DBG((UNI_L("*** Read (ok, but stopped for ERR_NO_SUCH_RESOURCE) %d bytes (instead of %d) from position %d"), (UINT32)bytes_read32, (UINT32)len, (UINT32)read_pos)); return OpStatus::OK; // Allow request for content not cached } OP_DBG((UNI_L("*** Error read %d bytes (instead of %d) from position %d"), (UINT32)bytes_read32, (UINT32)len, (UINT32)read_pos)); return ops; } bytes_read32+=bytes_temp; } OP_DBG((UNI_L("*** Read %d bytes from position %d"), (UINT32)bytes_read32, (UINT32)read_pos)); if(bytes_read) *bytes_read=bytes_read32; read_pos+=len; return OpStatus::OK; } MultimediaCacheFileDescriptor *MultimediaCacheFile::CreateFileDescriptor(int mode) { MultimediaCacheFileDescriptor *desc=OP_NEW(MultimediaCacheFileDescriptor, (this)); if(!desc) return NULL; if(mode & OPFILE_APPEND) { MultimediaSegment *seg=GetLastSegment(); if(seg) desc->SetWritePosition(seg->GetContentEnd()); } else if(mode==OPFILE_READ) desc->SetReadOnly(TRUE); return desc; } OP_STATUS MultimediaCacheFileDescriptor::GetFileLength(OpFileLength& len) const { len=0; if(!mcf) return OpStatus::ERR_NULL_POINTER; OP_STATUS ops=mcf->sfrw.GetFileLength(len); if(OpStatus::IsSuccess(ops)) { len-=mcf->GetFullHeaderLength(); OP_ASSERT(len != FILE_LENGTH_NONE); if(len == FILE_LENGTH_NONE) { len=0; return OpStatus::ERR; } } return ops; } #endif // MULTIMEDIA_CACHE_SUPPORT
#include <iostream> #include <algorithm> using namespace std; typedef long long ll; #define N 10000 ll cost[N][N]; void floyd_warshall() { for (ll k = 0; k < N; ++k) { for (ll i = 0; i < N; ++i) { for (ll j = 0; j < N; ++j) { cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]); } } } }
#include "../include/mvm0/cpu.hh" #include <cassert> #include <cstring> namespace { std::uint32_t imm(int x) { assert(x >= 0); return static_cast<std::uint32_t>(x); } } // namespace namespace mvm0 { CPU::CPU(const ROM &rom) : _ram(MEM_RAM_SIZE, 0), _rom(rom), _status(Status::OK) {} void CPU::init() { std::fill(_regs.begin(), _regs.end(), 0); _regs[REG_SP] = 1024; _pc = 1024; _prev_pc = 0; _zf = 0; } // Run the next instruction // Returns 0 if CPU ready for next instruction, 1 if stopped // Call status() for more infos if stopped int CPU::step() { if (_pc < MEM_CODE_START || _pc >= MEM_SIZE) { _status = Status::SEGV; return 1; } const auto &ins = _rom.ins[_pc - MEM_CODE_START]; auto a0 = ins.args.size() > 0 ? ins.args[0] : 0; auto a1 = ins.args.size() > 1 ? ins.args[1] : 0; auto a2 = ins.args.size() > 2 ? ins.args[2] : 0; auto pc_cpy = _pc; if (ins.name == "mov") { _reg(a1) = _reg(a0); ++_pc; } else if (ins.name == "movi") { _reg(a1) = imm(a0); ++_pc; } else if (ins.name == "ldr") { _reg(a1) = _mem(_reg(a0)); ++_pc; } else if (ins.name == "str") { _mem(_reg(a1)) = _reg(a0); ++_pc; } else if (ins.name == "b") { _pc = imm(a0); } else if (ins.name == "bz") { if (_zf) _pc = imm(a0); else ++_pc; } else if (ins.name == "bn") { if (!_zf) _pc = imm(a0); else ++_pc; } else if (ins.name == "call") { _regs[REG_SP] -= 4; _mem(_regs[REG_SP]) = _pc + 1; _pc = imm(a0); } else if (ins.name == "ret") { _pc = _mem(_regs[REG_SP]); _regs[REG_SP] += 4; } else if (ins.name == "sys") { std::size_t code = imm(a0); if (code == 0) _status = Status::NORMAL_EXIT; else _status = Status::BAD_INS; ++_pc; } else if (ins.name == "add") { _reg(a2) = _reg(a0) + _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "sub") { _reg(a2) = _reg(a0) - _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "mul") { _reg(a2) = _reg(a0) * _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "div") { _reg(a2) = _reg(a0) / _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "mod") { _reg(a2) = _reg(a0) % _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "and") { _reg(a2) = _reg(a0) & _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "or") { _reg(a2) = _reg(a0) | _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "xor") { _reg(a2) = _reg(a0) ^ _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "shl") { _reg(a2) = _reg(a0) >> _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else if (ins.name == "shr") { _reg(a2) = _reg(a0) << _reg(a1); _zf = _reg(a2) == 0; ++_pc; } else { _status = Status::BAD_INS; } if (_status == Status::OK) _prev_pc = pc_cpy; return _status != Status::OK; } void CPU::read_ram(std::size_t addr, std::size_t size, void *out_buf) const { assert(addr < MEM_CODE_START); assert(addr + size <= MEM_CODE_START); const std::uint8_t *ptr = &_ram[0] + addr; std::memcpy(out_buf, ptr, size); } std::uint32_t &CPU::_reg(int idx) { auto sidx = static_cast<std::size_t>(idx); assert(sidx < BASE_REGS); return _regs[sidx]; } std::uint32_t &CPU::_mem(int addr) { auto sptr = static_cast<std::size_t>(addr); if (sptr >= MEM_CODE_START) { _status = Status::SEGV; return _guard; } std::uint8_t *ptr = &_ram[0] + addr; return *(reinterpret_cast<std::uint32_t *>(ptr)); } } // namespace mvm0
#include <iostream> #include <cstdio> #include <string> #include <assert.h> #include <queue> #include <algorithm> typedef long long LL; typedef long long ll; typedef long double LD; typedef long double ld; using namespace std; const int N = 1000111; int n, k; int a[N]; priority_queue< pair<int, int> > q; int main() { //freopen(".in", "r", stdin); //freopen(".out", "w", stdout); scanf("%d%d",&n,&k); for (int i = 0; i < n; ++i) { scanf("%d", a + i); } bool done = false; for (int i = 0; i < n; ++i) { q.push(make_pair(-a[i], i)); if (i + 1 >= k) { while (q.top().second <= i - k) q.pop(); if (-q.top().first < a[i - k + 1]) { sort(a + i - k + 1, a + i + 1); done = true; break; } } } if (!done) { sort(a + n - k, a + n); } for (int i = 0; i < n; ++i) { printf("%d ", a[i]); } puts(""); return 0; }
class TwoSum { public: // NOTE: 进一步的优化可以是: 只使用一半大小的set, 只需遍历半个数组即可得到答案 // 这是由于输入数据是非降序的,若当前数是 sum/2,往后再遍历必 > sum, 从而无需遍历后半段 vector<int> FindNumbersWithSum(vector<int> array, int sum) { set<int> memo; for (auto& i : array) { if (memo.count(i) == 0) { memo.emplace(i); } } int a = sum; int b = sum; for (auto& i : array) { int remainder = sum - i; if (remainder < 0 || remainder == i) continue; if (memo.count(remainder)) { if (i * remainder < a * b) { a = i; b = remainder; } } } if (a == sum && b == sum) return { }; if (a > b) return { b, a }; return { a, b }; } void test() { vector<tuple<vector<int>, int>> test_cases = { {{1, 1, 1, 1, 1, 1, 1, 1}, 3 }, {{2, 4, 6, 7, 7, 8}, 6}, {{1, 2}, 2} }; for (auto& i : test_cases) { cout << get<0>(i) << " ==> " << FindNumbersWithSum(get<0>(i), get<1>(i)) << endl; } } };
// Licensed under the GNU General Public License, Version 3. #include "ValidationEngine.h" #include "TransactionBase.h" #include <libdvmcore/CommonJS.h> using namespace std; namespace dev { namespace dvm { ValidationEngineRegistrar* ValidationEngineRegistrar::s_this = nullptr; void NoProof::init() { DVM_REGISTER_VALIDATION_ENGINE(NoProof); } void NoReward::init() { DVM_REGISTER_VALIDATION_ENGINE(NoReward); } void NoProof::populateFromParent(BlockHeader& _bi, BlockHeader const& _parent) const { ValidationEngineFace::populateFromParent(_bi, _parent); _bi.setDifficulty(calculateDVMashDifficulty(chainParams(), _bi, _parent)); _bi.setGasLimit(calculateGasLimit(chainParams(), _bi)); } void NoProof::generateValidation(BlockHeader const& _bi) { BlockHeader header(_bi); header.setValidation(NonceField, h64{0}); header.setValidation(MixHashField, h256{0}); RLPStream ret; header.streamRLP(ret); if (m_onValidationGenerated) m_onValidationGenerated(ret.out()); } void NoProof::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const { ValidationEngineFace::verify(_s, _bi, _parent, _block); if (_parent) { // Check difficulty is correct given the two timestamps. auto expected = calculateDVMashDifficulty(chainParams(), _bi, _parent); auto difficulty = _bi.difficulty(); if (difficulty != expected) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)expected, (bigint)difficulty)); } } StringHashMap NoProof::jsInfo(BlockHeader const& _bi) const { return {{"difficulty", toJS(_bi.difficulty())}}; } void ValidationEngineFace::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const { _bi.verify(_s, _parent, _block); if (_s != CheckNothingNew) { if (_bi.difficulty() < chainParams().minimumDifficulty) BOOST_THROW_EXCEPTION( InvalidDifficulty() << RequirementError( bigint(chainParams().minimumDifficulty), bigint(_bi.difficulty()))); if (_bi.gasLimit() < chainParams().minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError( bigint(chainParams().minGasLimit), bigint(_bi.gasLimit()))); if (_bi.gasLimit() > chainParams().maxGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError( bigint(chainParams().maxGasLimit), bigint(_bi.gasLimit()))); if (_bi.number() && _bi.extraData().size() > chainParams().maximumExtraDataSize) { BOOST_THROW_EXCEPTION( ExtraDataTooBig() << RequirementError(bigint(chainParams().maximumExtraDataSize), bigint(_bi.extraData().size())) << errinfo_extraData(_bi.extraData())); } u256 const& daoHardfork = chainParams().daoHardforkBlock; if (daoHardfork != 0 && daoHardfork + 9 >= daoHardfork && _bi.number() >= daoHardfork && _bi.number() <= daoHardfork + 9) if (_bi.extraData() != fromHex("0x64616f2d686172642d666f726b")) BOOST_THROW_EXCEPTION( ExtraDataIncorrect() << errinfo_comment("Received block from the wrong fork (invalid extradata).")); } if (_parent) { auto gasLimit = _bi.gasLimit(); auto parentGasLimit = _parent.gasLimit(); if (gasLimit < chainParams().minGasLimit || gasLimit > chainParams().maxGasLimit || gasLimit <= parentGasLimit - parentGasLimit / chainParams().gasLimitBoundDivisor || gasLimit >= parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor) BOOST_THROW_EXCEPTION( InvalidGasLimit() << errinfo_min( (bigint)((bigint)parentGasLimit - (bigint)(parentGasLimit / chainParams().gasLimitBoundDivisor))) << errinfo_got((bigint)gasLimit) << errinfo_max((bigint)((bigint)parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor))); } } void ValidationEngineFace::populateFromParent(BlockHeader& _bi, BlockHeader const& _parent) const { _bi.populateFromParent(_parent); } void ValidationEngineFace::verifyTransaction(ImportRequirements::value _ir, TransactionBase const& _t, BlockHeader const& _header, u256 const& _gasUsed) const { if ((_ir & ImportRequirements::TransactionSignatures) && _header.number() < chainParams().EIP158ForkBlock && _t.isReplayProtected()) BOOST_THROW_EXCEPTION(InvalidSignature()); if ((_ir & ImportRequirements::TransactionSignatures) && _header.number() < chainParams().experimentalForkBlock && _t.hasZeroSignature()) BOOST_THROW_EXCEPTION(InvalidSignature()); if ((_ir & ImportRequirements::TransactionBasic) && _header.number() >= chainParams().experimentalForkBlock && _t.hasZeroSignature() && (_t.value() != 0 || _t.gasPrice() != 0 || _t.nonce() != 0)) BOOST_THROW_EXCEPTION(InvalidZeroSignatureTransaction() << errinfo_got((bigint)_t.gasPrice()) << errinfo_got((bigint)_t.value()) << errinfo_got((bigint)_t.nonce())); if (_header.number() >= chainParams().homesteadForkBlock && (_ir & ImportRequirements::TransactionSignatures) && _t.hasSignature()) _t.checkLowS(); dvm::DVMSchedule const& schedule = dvmSchedule(_header.number()); // Pre calculate the gas needed for execution if ((_ir & ImportRequirements::TransactionBasic) && _t.baseGasRequired(schedule) > _t.gas()) BOOST_THROW_EXCEPTION(OutOfGasIntrinsic() << RequirementError( (bigint)(_t.baseGasRequired(schedule)), (bigint)_t.gas())); // Avoid transactions that would take us beyond the block gas limit. if (_gasUsed + (bigint)_t.gas() > _header.gasLimit()) BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementErrorComment( (bigint)(_header.gasLimit() - _gasUsed), (bigint)_t.gas(), string("_gasUsed + (bigint)_t.gas() > _header.gasLimit()"))); } ValidationEngineFace* ValidationEngineRegistrar::create(ChainOperationParams const& _params) { ValidationEngineFace* ret = create(_params.validationEngineName); assert(ret && "Validation engine not found."); if (ret) ret->setChainParams(_params); return ret; } DVMSchedule const& ValidationEngineBase::dvmSchedule(u256 const& _blockNumber) const { return chainParams().scheduleForBlockNumber(_blockNumber); } u256 ValidationEngineBase::blockReward(u256 const& _blockNumber) const { DVMSchedule const& schedule{dvmSchedule(_blockNumber)}; return chainParams().blockReward(schedule); } u256 calculateDVMashDifficulty( ChainOperationParams const& _chainParams, BlockHeader const& _bi, BlockHeader const& _parent) { const unsigned c_expDiffPeriod = 100000; if (!_bi.number()) throw GenesisBlockCannotBeCalculated(); auto const& minimumDifficulty = _chainParams.minimumDifficulty; auto const& difficultyBoundDivisor = _chainParams.difficultyBoundDivisor; auto const& durationLimit = _chainParams.durationLimit; bigint target; // stick to a bigint for the target. Don't want to risk going negative. if (_bi.number() < _chainParams.homesteadForkBlock) // Frontier-era difficulty adjustment target = _bi.timestamp() >= _parent.timestamp() + durationLimit ? _parent.difficulty() - (_parent.difficulty() / difficultyBoundDivisor) : (_parent.difficulty() + (_parent.difficulty() / difficultyBoundDivisor)); else { bigint const timestampDiff = bigint(_bi.timestamp()) - _parent.timestamp(); bigint const adjFactor = _bi.number() < _chainParams.byzantiumForkBlock ? max<bigint>(1 - timestampDiff / 10, -99) : // Homestead-era difficulty adjustment max<bigint>((_parent.hasUncles() ? 2 : 1) - timestampDiff / 9, -99); // Byzantium-era difficulty adjustment target = _parent.difficulty() + _parent.difficulty() / 2048 * adjFactor; } bigint o = target; unsigned exponentialIceAgeBlockNumber = unsigned(_parent.number() + 1); // EIP-2384 Istanbul/Berlin Difficulty Bomb Delay if (_bi.number() >= _chainParams.muirGlacierForkBlock) { if (exponentialIceAgeBlockNumber >= 9000000) exponentialIceAgeBlockNumber -= 9000000; else exponentialIceAgeBlockNumber = 0; } // EIP-1234 Constantinople Ice Age delay else if (_bi.number() >= _chainParams.constantinopleForkBlock) { if (exponentialIceAgeBlockNumber >= 5000000) exponentialIceAgeBlockNumber -= 5000000; else exponentialIceAgeBlockNumber = 0; } // EIP-649 Byzantium Ice Age delay else if (_bi.number() >= _chainParams.byzantiumForkBlock) { if (exponentialIceAgeBlockNumber >= 3000000) exponentialIceAgeBlockNumber -= 3000000; else exponentialIceAgeBlockNumber = 0; } unsigned periodCount = exponentialIceAgeBlockNumber / c_expDiffPeriod; if (periodCount > 1) o += (bigint(1) << (periodCount - 2)); // latter will eventually become huge, so ensure // it's a bigint. o = max<bigint>(minimumDifficulty, o); return u256(min<bigint>(o, std::numeric_limits<u256>::max())); } u256 calculateGasLimit( ChainOperationParams const& _chainParams, BlockHeader const& _bi, u256 const& _gasFloorTarget) { u256 gasFloorTarget = _gasFloorTarget == Invalid256 ? 3141562 : _gasFloorTarget; u256 gasLimit = _bi.gasLimit(); u256 boundDivisor = _chainParams.gasLimitBoundDivisor; if (gasLimit < gasFloorTarget) return min<u256>(gasFloorTarget, gasLimit + gasLimit / boundDivisor - 1); else return max<u256>(gasFloorTarget, gasLimit - gasLimit / boundDivisor + 1 + (_bi.gasUsed() * 6 / 5) / boundDivisor); } } } // namespace dev dvm
/* moveniu 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. moveniu 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 moveniu. If not, see <http://www.gnu.org/licenses/>. */ #ifndef RANDOM_H #define RANDOM_H #include <chrono> #include <string> namespace utils { int64_t GetPerformanceCounter(); void MemoryClean(void *ptr, size_t len); void RandAddSeed(); bool GetRandBytes(unsigned char* buf, int num); bool GetOSRand(unsigned char *buf, int num); bool GetStrongRandBytes(std::string & out); } #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 2e6 + 100; int q[maxn],a[maxn],sum[maxn]; bool cmp(int a,int b,int c,int _a,int _b,int _c) { if (a != _a) return a > _a; if (b != _b) return b < _b; return c < _c; } int main() { int n,k; scanf("%d%d",&n,&k); int ans = -1001,x,y; for (int i = 1;i <= n; i++) { scanf("%d",&a[i]); a[n+i] = a[i]; if (a[i] > ans) {ans = a[i];x = y = i;} } int l = 1,r = 1;q[1] = 0; for (int i = 1;i <= n+n; i++) { sum[i] = sum[i-1] + a[i]; while (l <= r && i-q[l] > k) { if (q[r] > q[l] && cmp(sum[q[r]] - sum[q[l]],q[l]+1,q[r]-q[l],ans,x,y-x+1)) { ans = sum[q[r]] - sum[q[l]]; x = q[l] + 1;y = q[r]; } l++; } while (l <= r && sum[i] < sum[q[r]]) r--; q[++r] = i; if (q[r] > q[l] && cmp(sum[q[r]] - sum[q[l]],q[l]+1,q[r]-q[l],ans,x,y-x+1)) { ans = sum[q[r]] - sum[q[l]]; x = q[l] + 1;y = q[r]; } } if (q[r] > q[l] && sum[q[r]]-sum[q[l]] > ans) { ans = sum[q[r]] - sum[q[l]]; x = q[l]+1,y = q[r]; } printf("%d %d %d\n",ans,x,(y-1)%n+1); return 0; }
#pragma once #include "Template.hh" #include <unordered_set> namespace HotaSim { struct BiomTemplate : public Template { std::unordered_set<TmplId> ability_ids; }; }
// Created on: 1993-04-13 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gp_TrsfForm_HeaderFile #define _gp_TrsfForm_HeaderFile //! Identifies the type of a geometric transformation. enum gp_TrsfForm { gp_Identity, //!< No transformation (matrix is identity) gp_Rotation, //!< Rotation gp_Translation, //!< Translation gp_PntMirror, //!< Central symmetry gp_Ax1Mirror, //!< Rotational symmetry gp_Ax2Mirror, //!< Bilateral symmetry gp_Scale, //!< Scale gp_CompoundTrsf, //!< Combination of the above transformations gp_Other //!< Transformation with not-orthogonal matrix }; #endif // _gp_TrsfForm_HeaderFile
#ifndef RADICAL_H #define RADICAL_H #include "Real.h" #include <typeinfo> #include <string> #include <iostream> #include <sstream> using namespace std; class Radical : public Real{ private: int coeficiente; int indice; int radicando; public: Radical(); Radical(int,int,int); int getCoeficiente(); void setCoeficiente(int); int getIndice(); void setIndice(int); int getRadicando(); void setRadicando(int); virtual string operator+(Real* racional){ stringstream ss; Radical* tem = dynamic_cast<Radical*>(racional); string resultado=""; int suma; if(tem->getRadicando()==radicando){ suma = tem->getCoeficiente()+ coeficiente; ss <<"("<<suma<<")"<<" ("<<radicando<<") "<<"^"<<"(1/"<<indice<<")"; resultado = ss.str(); return resultado; } } virtual string operator+(int numero){ //suma de un radical con un int stringstream ss; string resultado; ss<<numero<<"+"<<"("<<coeficiente <<") ("<<indice<<") "<<"^"<<"(1/"<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator+(double numero){ string resultado; stringstream ss; ss<<numero<<"+"<<"("+coeficiente <<") ("<<indice<<") "<<"^"<<"(1/"<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator-(Real* real){ //resta de un radical stringstream ss; string resultado; int suma; Radical* tem = dynamic_cast<Radical*>(real); if(tem->getRadicando()==radicando){ suma = tem->getCoeficiente()- coeficiente; ss<<"("<<suma<<")"<<" ("<<indice<<") "<<"^"<<"(1/"<<radicando<<")"; resultado = ss.str(); return resultado; } } virtual string operator-(int numero){ stringstream ss; string resultado; ss<<numero<<"-"<<"("<<coeficiente <<") ("<<indice<<") "<<"^"<<"(1/"<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator-(double numero){ string resultado; stringstream ss; ss<<numero<<"+"<<"("+coeficiente <<") ("<<indice<<") "<<"^"<<"(1/"<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator*(Real* radical){ //multiplicacion con radical! stringstream ss; Radical* tem = dynamic_cast<Radical*>(radical); int operacion1; int operacion2; int operacion3; string resultado; if(tem->getRadicando()==radicando&&tem->getIndice()==indice){ operacion1= tem->getCoeficiente()* coeficiente; operacion2 = (tem->getIndice()+indice); operacion3= (tem->getIndice()*indice); ss<< "("<<operacion1<<")"<<" ("<<radicando<<") "<<"^"<<operacion2<<"/"<<operacion3<<")"; resultado = ss.str(); return resultado; } else{ operacion1= tem->getCoeficiente()* coeficiente; ss<< "("<<operacion1<<")"<<" ("<<radicando<<") "<<"^"<<"1/"<<indice<<")"<<" ("<<tem->getRadicando()<<") 1/"<<tem->getIndice(); resultado = ss.str(); return resultado; } } virtual string operator*(int numero){ stringstream ss; int operacion1; int operacion2; string resultado; operacion1=coeficiente*numero; ss<< "("<<operacion1<<")"<<" ("<<indice<<") "<<"^"<<"("<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator*(double numero){ stringstream ss; int operacion1; int operacion2; operacion1= coeficiente*numero; string resultado; ss<< "("<<operacion1<<")"<<" ("<<indice<<") "<<"^"<<"("<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator/(Real* real){ stringstream ss; Radical* tem = dynamic_cast<Radical*>(real); int operacion1; int operacion2; int operacion3; string resultado; if(tem->getRadicando()==radicando){ operacion1= coeficiente/tem->getCoeficiente(); operacion2 = indice/tem->getIndice(); operacion3 = radicando*tem->getRadicando(); ss<< "("<<operacion1<<")"<<" ("<<operacion2<<") "<<"^"<<"("<<operacion3<<")"; resultado = ss.str(); } return resultado; } virtual string operator/(int numero){ int operacion1; int operacion2; stringstream ss; string resultado; operacion1= coeficiente/numero; ss<<"("<<operacion1<<")"<<" ("<<indice<<") "<<"^"<<"("<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string operator/(double numero){ int operacion1; int operacion2; stringstream ss; string resultado; operacion1= coeficiente/numero; ss<<"("<<operacion1<<")"<<" ("<<indice<<") "<<"^"<<"("<<radicando<<")"; resultado = ss.str(); return resultado; } virtual string toString(){ stringstream ss; string ret; ss<<"("<<coeficiente<<")"<<" ("<<indice<<") "<<"^"<<"("<<radicando<<")"; return ss.str(); } friend ostream& operator <<(ostream &escribirDouble, Radical* r){ stringstream ss; ss<<r->getCoeficiente()<<"("<<r->getRadicando()<<") ^(1/"<<r->getIndice()<<")"; return escribirDouble<<ss.str(); } }; #endif
#include <iostream> #include <string> #include <cstring> #include <vector> using namespace std; class KMP { private: string pattern; // next 数组的值是除当前字符外(注意不包括当前字符)的 // 公共前后缀最长长度 vector<int> next; void buildNext() { if (pattern.size() == 0) return; next.assign(pattern.size() + 1, 0); int j = 0, k = -1; // 起始值为 -1 next[j] = -1; while (j < pattern.size()) { if (k == -1 || pattern[j] == pattern[k]) { j++; k++; // 找到最前方也没有值相等则为0, 当p[j]==p[k]时, next[j] = next[j-1]+1 next[j] = k; } else { // 不相等时, 收缩位置往前找到相同的, 如果一直找不到则会到达-1 k = next[k]; } } } // 递归计算 K 值 int getNext(int i) { if (i == 0) { return -1; } if (i > 0) { int k = getNext(i-1); while (k >= 0) { if (pattern[k] == pattern[j-1]) return k+1; else k = getNext(k); } return 0; } return 0; } public: KMP() = delete; explicit KMP(const string& p) : pattern(p) { buildNext(); } explicit KMP(const char* p) : KMP(string(p)) { } void printNext() const { for (auto i : next) { cout << i << " "; } cout << endl; } int match(const string& str) { return match(str.c_str()); } int match(const char* str) { auto ss = strlen(str); int size = pattern.size(); int i=0, j=0; if (size == 0) return 0; if (size > ss) return -1; while (str[i] != '\0' && j < size) { if (j == -1 || str[i] == pattern[j]) { i++; j++; } else { // 相对于主串进行偏移 j = next[j]; } } if (j == size) return i - j; else return -1; } }; class Solution { public: int strStr(string haystack, string needle) { KMP k(needle); return k.match(haystack); } }; int main() { Solution s; int i = s.strStr("hello", "ll"); cout << i << endl; KMP k("abcdabce"); k.printNext(); return 0; }
#include <QFileInfo> #include <QDebug> #include <QImage> #include <QDir> #include "pictureshrinker.h" PictureShrinker::PictureShrinker(QObject *parent) : QThread(parent) { } void PictureShrinker::setPath(QString path) { if (this->_path != path) { this->_path = path; } } void PictureShrinker::setSavePath(QString path) { if (this->_savePath != path) { this->_savePath = path; } } void PictureShrinker::setScale(int widthPercent, int heightPercent) { if (this->_widthPercent != widthPercent) { this->_widthPercent = widthPercent; } if (this->_heightPercent != heightPercent) { this->_heightPercent = heightPercent; } } void PictureShrinker::run() { if (this->_path.isEmpty()) { emit this->error(PictureShrinker::tr("Missing path to file")); return; } if (this->_savePath.isEmpty()) { emit this->error(PictureShrinker::tr("Missing save path")); return; } if (this->_widthPercent < 0) { emit this->error(PictureShrinker::tr("Bad width")); return; } if (this->_heightPercent < 0) { emit this->error(PictureShrinker::tr("Bad height")); return; } QImage *image = new QImage(this->_path); QImage newImage = image->scaled(float(this->_widthPercent)/100.0 * image->width(), float(this->_heightPercent)/100.0 * image->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); QString pathToSave = QDir::toNativeSeparators(this->_savePath + QDir::separator() + QFileInfo(this->_path).fileName()); qDebug() << __FILE__ << __LINE__ << "save to :" << pathToSave; newImage.save(pathToSave); delete image; }