text
stringlengths
8
6.88M
#include<bits/stdc++.h> using namespace std; int main() { int testCases; cout << "Enter Test Cases: "; cin >> testCases; while(testCases--) { stack<int> s; int last; unsigned long long int num; cout << "Enter number: "; cin >> num; while(num) { last = num%10; num /= 10; if(s.empty()) s.push(last); else if(s.top()!=last) s.push(last); } while(!s.empty()) { cout<<s.top(); s.pop(); } cout<<endl; } return 0; }
#include "../include/colour.h" #include <math.h> RGBColor hsv2rgb(float H, float S, float V) { float r, g, b; float h = H / 360; float s = S / 100; float v = V / 100; int i = floor(h * 6); float f = h * 6 - i; float p = v * (1 - s); float q = v * (1 - f * s); float t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } RGBColor color; color.r = r * 255; color.g = g * 255; color.b = b * 255; return color; }
#include "error.hh" #include <execinfo.h> #include <cxxabi.h> #include <sstream> #include <memory> #include <stdlib.h> namespace ten { saved_backtrace::saved_backtrace() { size = backtrace(array, 50); } std::string saved_backtrace::str() { std::stringstream ss; std::unique_ptr<char *, void (*)(void*)> messages(backtrace_symbols(array, size), free); // skip the first frame which is the constructor for (int i = 1; i < size && messages; ++i) { char *mangled_name = 0, *offset_begin = 0, *offset_end = 0; // find parantheses and +address offset surrounding mangled name for (char *p = messages.get()[i]; *p; ++p) { if (*p == '(') { mangled_name = p; } else if (*p == '+') { offset_begin = p; } else if (*p == ')') { offset_end = p; break; } } // if the line could be processed, attempt to demangle the symbol if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) { *mangled_name++ = '\0'; *offset_begin++ = '\0'; *offset_end++ = '\0'; int status; std::unique_ptr<char, void (*)(void*)> real_name(abi::__cxa_demangle(mangled_name, 0, 0, &status), free); if (status == 0) { // if demangling is successful, output the demangled function name ss << "[bt]: (" << i << ") " << messages.get()[i] << " : " << real_name.get() << "+" << offset_begin << offset_end << std::endl; } else { // otherwise, output the mangled function name ss << "[bt]: (" << i << ") " << messages.get()[i] << " : " << mangled_name << "+" << offset_begin << offset_end << std::endl; } } else { // otherwise, print the whole line ss << "[bt]: (" << i << ") " << messages.get()[i] << std::endl; } } return ss.str(); } } // end namespace ten
/** * @file TcpClient.cpp * @author dtuchscherer <daniel.tuchscherer@hs-heilbronn.de> * @brief TCP client implementation * @details For connecting to and disconnecting from TCP servers. * @version 1.0 * @copyright Copyright (c) 2015, dtuchscherer. * All rights reserved. * * Redistributions and use in source and binary forms, with * or without modifications, are permitted provided that the * following conditions are met: Redistributions of source code must * retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the Heilbronn University nor the name of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS “AS IS” * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /******************************************************************************* * MODULES USED *******************************************************************************/ #include "TcpClient.h" /******************************************************************************* * DEFINITIONS AND MACROS *******************************************************************************/ /******************************************************************************* * TYPEDEFS, ENUMERATIONS, CLASSES *******************************************************************************/ /******************************************************************************* * PROTOTYPES OF LOCAL FUNCTIONS *******************************************************************************/ /******************************************************************************* * EXPORTED VARIABLES *******************************************************************************/ /******************************************************************************* * GLOBAL MODULE VARIABLES *******************************************************************************/ /******************************************************************************* * EXPORTED FUNCTIONS *******************************************************************************/ /******************************************************************************* * FUNCTION DEFINITIONS *******************************************************************************/ TcpClient::TcpClient() noexcept : TcpSocket() { } TcpClient::~TcpClient() noexcept { } AR::boolean TcpClient::connect(IpAddress& ip_address, const AR::uint16 port) noexcept { // return value AR::boolean connected_r = FALSE; AR::boolean socket_created = is_socket_initialized(); // look if the socket is there if ( socket_created == TRUE ) { // first build the address AR::uint32 ip = ip_address.get_ip_address(); struct sockaddr_in server; ip_address.create_address_struct(ip, port, server); // then establish the connection to the server const SocketHandleType& socket_handle = get_socket_handle(); const auto connected = ::connect(socket_handle, (struct sockaddr*)&server, sizeof(struct sockaddr)); if ( connected >= 0 ) { connected_r = TRUE; } else { connected_r = FALSE; m_last_error = errno; } } else { connected_r = FALSE; } return connected_r; } AR::boolean TcpClient::disconnect() noexcept { return close_socket(); }
/* -*- coding: utf-8 -*- !@time: 2019-12-27 14:13 !@author: superMC @email: 18758266469@163.com !@fileName: 0028_number_that_appears_more_than_half_of_the_array.cpp */ #include <environment.h> class Solution { typedef unordered_map<int, int> uMap; public: int MoreThanHalfNum_Solution(const vector<int> &numbers) { if (numbers.empty()) { return 0; } uMap mp; int threshold = numbers.size() / 2 + 1; for (auto &num : numbers) { if (mp.find(num) == mp.end()) { mp.insert(std::make_pair(num, 1)); } else { mp[num]++; } for (auto &iter :mp) { if (iter.second >= threshold) { return iter.first; } } } return 0; } }; int fun() { vector<int> input = {1, 2, 3, 4, 4, 4}; int output = Solution().MoreThanHalfNum_Solution(input); printf("%d", output); return 0; }
/** * @file sensor_distress.cc * * @copyright 2017 3081 Staff, All rights reserved. * * @author Zijing Mo <zijingmo888@gmail.com> */ /******************************************************************************* * Includes ******************************************************************************/ #include <limits> #include "src/sensor_distress.h" #include "src/arena_entity.h" /******************************************************************************* * Namespaces ******************************************************************************/ NAMESPACE_BEGIN(csci3081); /******************************************************************************* * Constructors/Destructor ******************************************************************************/ SensorDistress::SensorDistress() : activated_(false), point_of_sensor_distress_(0, 0), angle_of_sensor_distress_(0) { } /******************************************************************************* * Member Functions ******************************************************************************/ void SensorDistress::Accept(EventCollision * e){ } void SensorDistress::Reset(void) { } /* reset() */ NAMESPACE_END(csci3081);
#ifndef HASHTABLE_HPP #define HASHTABLE_HPP #include "list.hpp" class HashTable { public: HashTable(); ~HashTable(); void add(const std::string key, const std::string value); bool get(std::string key, std::string& value); bool remove(std::string key, std::string& value); private: int size; List** arr; int hashMapIndex(const std::string key); }; #endif
#include<iostream> #include<stdio.h> #include<bits/stdc++.h> #include<algorithm> #include<cmath> #include<string> #include<cstring> #include<vector> #include<map> #include<queue> #include<set> #include<list> #include<unordered_map> #include<unordered_set> #define ll long long #define MAX 100000003 #define MAX_RLEN 50 #define ll long long #define pb push_back #define pii pair<ll,ll> #define N 200005 #define PI 3.1415926535 using namespace std; int main() { bool flag=true; int n; cin>>n; int arr[n]; int max=INT_MIN; for(int i=0;i<n;i++) { cin>>arr[i]; if(arr[i]>max) max=arr[i]; else flag=false; } if(flag==1) cout<<"true"; else cout<<"false"; }
// Copyright (c) 2018, tlblanc <tlblanc1490 at gmail dot com> #ifndef IO_MEMIO_H_ #define IO_MEMIO_H_ #include <arpa/inet.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdio.h> extern inline const uint8_t *readmem(const uint8_t *mem, uint8_t *dest, size_t len) { memcpy(dest, mem, len); return mem + len; } extern inline const uint8_t *readmempad(const uint8_t *mem, uint8_t *dest, size_t len) { size_t padding; memcpy(dest, mem, len); padding = (4 - (len % 4)) % 4; return mem + len + padding; } extern inline const uint8_t* readu32(const uint8_t *mem, uint32_t *value) { memcpy(reinterpret_cast<uint8_t*>(value), mem, sizeof(*value)); *value = ntohl(*value); return mem + 4; } extern inline const uint8_t* readu64(const uint8_t *mem, uint64_t *value) { mem = readu32(mem, reinterpret_cast<uint32_t*>(value) + 1); mem = readu32(mem, reinterpret_cast<uint32_t*>(value)); return mem; } extern inline const uint8_t* readu16(const uint8_t *mem, uint16_t *value) { memcpy(reinterpret_cast<uint8_t*>(value), mem, sizeof(*value)); *value = ntohs(*value); return mem + 2; } extern inline uint8_t* writeu16(uint8_t *mem, uint16_t value) { value = htons(value); memcpy(mem, reinterpret_cast<uint8_t*>(&value), sizeof(value)); return mem + 2; } extern inline uint8_t* writeu32(uint8_t *mem, uint32_t value) { value = htonl(value); memcpy(mem, reinterpret_cast<uint8_t*>(&value), sizeof(value)); return mem + 4; } extern inline uint8_t* writeu64(uint8_t *mem, uint64_t value) { mem = writeu32(mem, *(reinterpret_cast<uint32_t*>(&value) + 1)); return writeu32(mem, static_cast<uint32_t>(value)); } extern inline uint8_t* writeu48(uint8_t *mem, uint64_t value) { uint16_t s = htons(value >> 32); uint32_t u = htonl(value & 0xffffffff); memcpy(mem, reinterpret_cast<uint8_t*> (&s), sizeof(s)); memcpy(mem + 2, reinterpret_cast<uint8_t*>(&u), sizeof(u)); return mem + 6; } extern inline uint8_t* writemem(uint8_t *mem, const uint8_t *src, size_t len) { memcpy(mem, src, len); return mem + len; } extern inline uint8_t* writemempad(uint8_t *mem, const uint8_t *src, size_t len) { size_t padding = (4 - (len % 4)) % 4; memcpy(mem, src, len); if (padding > 0) { memset(mem + len, 0, padding); } return mem + len + padding; } #endif // IO_MEMIO_H_
#pragma once #include "GcMediateObject.h" class GcToolBarDockable : public CDockablePane, public GcMediateObject { DECLARE_DYNAMIC(GcToolBarDockable) public: class ToolBar : public CMFCToolBar { public: virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler) { CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler); } virtual BOOL AllowShowOnList() const { return FALSE; } }; protected: ToolBar mToolBar; int mChildBeginTop; CWnd* mpMainWnd; // Construction public: // must derive your own class GcToolBarDockable(); virtual ~GcToolBarDockable(); void SetVisibleCaptionBar(bool bShow); protected: DECLARE_MESSAGE_MAP() virtual void ReciveNotiyfiMessage(WPARAM wParam, LPARAM lParam){}; virtual void ReceiveMediateMessage(gtuint messageIndex, GcMediateObjectMessage* pSander){}; public: virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); afx_msg void OnSize(UINT nType, int cx, int cy); };
#pragma once #include "../gl_command.h" #include "../gl_strings.h" namespace glmock { // // http://www.opengl.org/sdk/docs/man3/xhtml/glBindTexture.xml class GLBindTexture : public GLCommand { public: GLBindTexture(GLenum target, GLuint texture); virtual ~GLBindTexture(); static const char* EnumToString(GLenum value) { const char* str = 0; switch(value) { case GL_TEXTURE_1D: str = AS_STRING(GL_TEXTURE_1D); break; case GL_TEXTURE_2D: str = AS_STRING(GL_TEXTURE_2D); break; case GL_TEXTURE_3D: str = AS_STRING(GL_TEXTURE_3D); break; case GL_TEXTURE_1D_ARRAY: str = AS_STRING(GL_TEXTURE_1D_ARRAY); break; case GL_TEXTURE_2D_ARRAY: str = AS_STRING(GL_TEXTURE_2D_ARRAY); break; case GL_TEXTURE_RECTANGLE: str = AS_STRING(GL_TEXTURE_RECTANGLE); break; case GL_TEXTURE_CUBE_MAP: str = AS_STRING(GL_TEXTURE_CUBE_MAP); break; case GL_TEXTURE_BUFFER: str = AS_STRING(GL_TEXTURE_BUFFER); break; case GL_TEXTURE_2D_MULTISAMPLE: str = AS_STRING(GL_TEXTURE_2D_MULTISAMPLE); break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: str = AS_STRING(GL_TEXTURE_2D_MULTISAMPLE_ARRAY); break; default: str = AS_STRING(UNKNOWN); break; }; return str; } public: void Eval(GLenum target, GLuint texture); private: GLenum mTarget; GLuint mTexture; }; }
#include "SoftwareI2C.h" SoftwareI2C softwarei2c; void setup() { Serial.begin(115200); softwarei2c.begin(3, 2); // sda, scl } void loop() { softwarei2c.beginTransmission(5); softwarei2c.write('H'); softwarei2c.endTransmission(); }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XSLT_COMPILER_H #define XSLT_COMPILER_H #ifdef XSLT_SUPPORT #include "modules/xslt/src/xslt_instruction.h" class XSLT_StylesheetImpl; class XSLT_String; class XSLT_Program; class XMLCompleteName; class XMLCompleteNameN; class XSLT_XPathPattern; class XMLNamespaceDeclaration; class XSLT_XPathExpression; class XSLT_Element; class XPathPattern; class XPathExtensions; #ifdef XSLT_ERRORS # define XSLT_ADD_INSTRUCTION(code) (compiler->AddInstructionL (code, 0, this)) # define XSLT_ADD_INSTRUCTION_WITH_ARGUMENT(code, argument) (compiler->AddInstructionL (code, argument, this)) # define XSLT_ADD_INSTRUCTION_EXTERNAL(code, origin) (compiler->AddInstructionL (code, 0, origin)) # define XSLT_ADD_INSTRUCTION_WITH_ARGUMENT_EXTERNAL(code, argument, origin) (compiler->AddInstructionL (code, argument, origin)) # define XSLT_ADD_JUMP_INSTRUCTION(code) (compiler->AddJumpInstructionL (code, this)) # define XSLT_ADD_JUMP_INSTRUCTION_EXTERNAL(code, origin) (compiler->AddJumpInstructionL (code, origin)) #else // XSLT_ERRORS # define XSLT_ADD_INSTRUCTION(code) (compiler->AddInstructionL (code, 0)) # define XSLT_ADD_INSTRUCTION_WITH_ARGUMENT(code, argument) (compiler->AddInstructionL (code, argument)) # define XSLT_ADD_INSTRUCTION_EXTERNAL(code, origin) (compiler->AddInstructionL (code, 0)) # define XSLT_ADD_INSTRUCTION_WITH_ARGUMENT_EXTERNAL(code, argument, origin) (compiler->AddInstructionL (code, argument)) # define XSLT_ADD_JUMP_INSTRUCTION(code) (compiler->AddJumpInstructionL (code)) # define XSLT_ADD_JUMP_INSTRUCTION_EXTERNAL(code, origin) (compiler->AddJumpInstructionL (code)) #endif // XSLT_ERRORS class XSLT_MessageHandler; class XSLT_Compiler { protected: XSLT_StylesheetImpl *stylesheet; XSLT_MessageHandler *messagehandler; XSLT_Instruction *instructions; unsigned instructions_used, instructions_total; uni_char **strings; unsigned strings_used, strings_total; XMLCompleteName **names; unsigned names_used, names_total; XSLT_XPathExpression **expressions; unsigned expressions_used, expressions_total; XPathPattern **patterns; unsigned patterns_used, patterns_total; XMLNamespaceDeclaration **nsdeclarations; unsigned nsdeclarations_used, nsdeclarations_total; XSLT_Program **programs; unsigned programs_used, programs_total; #ifdef XSLT_ERRORS void AddInstructionL (XSLT_Instruction::Code code, UINTPTR *&argument_ptr, XSLT_Element *origin); #else // XSLT_ERRORS void AddInstructionL (XSLT_Instruction::Code code, UINTPTR *&argument_ptr); #endif // XSLT_ERRORS public: XSLT_Compiler (XSLT_StylesheetImpl *stylesheet, XSLT_MessageHandler *messagehandler); ~XSLT_Compiler (); XSLT_StylesheetImpl *GetStylesheet () { return stylesheet; } XSLT_MessageHandler *GetMessageHandler () { return messagehandler; } XSLT_Compiler *GetNewCompilerL () { return OP_NEW_L (XSLT_Compiler, (stylesheet, messagehandler)); } #ifdef XSLT_ERRORS void AddInstructionL (XSLT_Instruction::Code code, UINTPTR argument, XSLT_Element *origin); unsigned AddJumpInstructionL (XSLT_Instruction::Code code, XSLT_Element *origin); /**< Returns the handle to use in SetJumpDestination. */ #else // XSLT_ERRORS void AddInstructionL (XSLT_Instruction::Code code, UINTPTR argument); unsigned AddJumpInstructionL (XSLT_Instruction::Code code); /**< Returns the handle to use in SetJumpDestination. */ #endif // XSLT_ERRORS unsigned AddStringL (const uni_char *string); unsigned AddNameL (const XMLCompleteNameN &name, BOOL process_namespace_aliases); unsigned AddExpressionL (const XSLT_String &source, XPathExtensions* extension, XMLNamespaceDeclaration *nsdeclaration); unsigned AddPatternsL (XPathPattern **patterns, unsigned patterns_count); unsigned AddNamespaceDeclarationL (XMLNamespaceDeclaration *nsdeclaration); unsigned AddProgramL (XSLT_Program *program); /**< Adds a pointer to a XSLT_Program to this program for use in a CALL instruction. The program is still owned by the caller and must be alive until this program has finished. */ void SetJumpDestination (unsigned jump_instruction_offset); void FinishL (XSLT_Program *program); }; #endif // XSLT_SUPPORT #endif // XSLT_COMPILER_H
#include<bits/stdc++.h> using namespace std; main() { int n; while(cin>>n) { int as[n][n], i, j; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { if(i==1)as[i][j]=1; else if(i>1 && j==1)as[i][j]=1; else as[i][j]=as[i-1][j]+as[i][j-1]; } } cout<<as[n][n]<<endl; } return 0; }
#include"ClassDate.h" //调整日期(加法调整) Date& Date::AdjustDateAdd(Date& d) { //无需调整的情况 if (d._day <= 28 || (d._month != 2 && d._day <= 30) || (((d._month != 2) && ((d._month != 4) || (d._month != 6) || (d._month != 9) || (d._month != 11))&&d._day<=31))) return d; //需要调整的情况 while (!(d._day <= 28 || (d._month != 2 && d._day <= 30) || (((d._month != 2) && ((d._month != 4) || (d._month != 6) || (d._month != 9) || (d._month != 11)) && d._day <= 31)))) { if (d._month == 2) { //判断闰年 if (((d._year % 100 == 0) && (d._year % 400 == 0)) || ((d._year % 100 != 0) && (d._year % 4 == 0))) { d._day -= 29; d._month += 1; } else { d._day -= 28; d._month += 1; } } //有30天的月份 else if ((d._month == 4) || (d._month == 6) || (d._month == 9) || (d._month == 11)) { d._day -= 30; d._month += 1; } //有31天的月份 else { d._day -= 31; d._month += 1; } //判断月份是否超过12 if (d._month > 12) { d._year += 1; d._month = 1; } } return d; } //当前日期x天之后是什么日期 Date Date::operator+(int days) { Date temp(*this);//因为不能改变原本的数据,所以要创建临时变量 temp._day += days; //调整日期 AdjustDate(temp); //返回 return temp; } //当前日期x天前是什么日期 Date Date::operator-(int days) { Date temp(*this); temp._day -= days; //调整日期 AdjustDate(temp); return temp; } //调整日期(减法) Date& Date::AdjustDateSub(Date& d) { if (d._day > 0) return d; while (d._day<=0) { //当d.day恰好等于0 if (0 == d._day) { d._month -= 1; if (0 == d._month) { d._year -= 1; d._month = 12; d._day = 31; } //判断当前d,month是什么月 //d.month是2月 else if (2 == d._month) { //判断闰年 if (((d._year % 100 == 0) && (d._year % 400 == 0)) || ((d._year % 100 != 0) && (d._year % 4 == 0))) { d._day = 29; } else d._day = 28; } else if ((d._month = 4) || (d._month = 6) || (d._month = 9) || (d._month = 11)) { d._day = 30; } else { d._month = 31; } } //先给月份减1 d._month -= 1; //判断月份是否为0 if (0 == d._month) { d._year -= 1; d._month = 12; } //如果当前月是2月 if (2 == d._month) { if (((d._year % 100 == 0) && (d._year % 400 == 0)) || ((d._year % 100 != 0) && (d._year % 4 == 0))) d._day += 29; else d._day += 28; } else if (4 == d._month || 6 == d._month || 9 == d._month || 11 == d._month) d._day += 30; else d._day += 31; } AdjustDateAdd(d); return d; } Date& Date::AdjustDate(Date& d) { if (d._day > 0) { AdjustDateAdd(d); } else { AdjustDateSub(d); } return d; } //两个日期之间相差多少天 Date Date::operator-(const Date& d) { Date temp(*this); //this大于d if ((*this)>d) { if (this->_day >= d._day) temp._day = this->_day - d._day; else { temp._month =this->_month - 1; if (2 == temp._month) { if (((d._year % 100 == 0) && (d._year % 400 == 0)) || ((d._year % 100 != 0) && (d._year % 4 == 0))) { temp._day =this->_day + 29; } else temp._day =this->_day + 28; } else if ((4 == temp._month) || (6 == temp._month) || (9 == temp._month) || (11 == temp._month)) { temp._day =this->_day + 30; } else { temp._day =this->_day + 31; } temp._day = temp._day - d._day; } if (temp._month >= d._month) temp._month = temp._month - d._month; else { temp._year -= 1; temp._month += 12; temp._month -= d._month; } temp._year -= d._year; } else { temp._day = d._day; temp._month = d._month; temp._year = d._year; if (this->_day <= d._day) temp._day = d._day-this->_day; else { temp._month -= 1; if (2 == temp._month) { if (((d._year % 100 == 0) && (d._year % 400 == 0)) || ((d._year % 100 != 0) && (d._year % 4 == 0))) { temp._day += 29; } else temp._day += 28; } else if ((4 == temp._month) || (6 == temp._month) || (9 == temp._month) || (11 == temp._month)) { temp._day += 30; } else { temp._day += 31; } temp._day = temp._day - this->_day; } if (temp._month >= this->_month) temp._month -= this->_month; else { temp._year -= 1; temp._month += 12; temp._month = temp._month - this->_month; } temp._year = temp._year - this->_year; } return temp; } //比较两个日期的大小 bool Date::operator>(const Date& d) { if ((this->_year > d._year) || ((this->_year == d._year) && (this->_month > d._month)) || ((this->_year == d._year) && (this->_month == d._month) && (this->_day > d._day))) return true; return false; } bool Date::operator<(const Date& d) { if ((this->_year > d._year) || ((this->_year == d._year) && (this->_month > d._month)) || ((this->_year == d._year) && (this->_month == d._month) && (this->_day > d._day))) return false; return true; } bool Date::operator==(const Date& d) { if ((this->_year == d._year) && (this->_month == d._month) && (this->_day == d._day)) return true; return false; } bool Date::operator!=(const Date& d) { if ((this->_year == d._year) && (this->_month == d._month) && (this->_day == d._day)) return false; return true; } //重载赋值操作符 Date& Date::operator=(const Date& d) { this->_year = d._year; this->_month = d._month; this->_day = d._day; return (*this); } //重载取地址符号 Date* Date::operator&() { return this; } //前置++/-- Date& Date::operator++() { this->_year += 1; this->_month += 1; this->_day += 1; return (*this); } Date& Date::operator--() { this->_year -= 1; this->_month -= 1; this->_day -= 1; return (*this); } //后置++/-- Date Date::operator++(int) { Date temp(*this); this->_year += 1; this->_month += 1; this->_day += 1; return temp; } Date Date::operator--(int) { Date temp(*this); this->_year -= 1; this->_month -= 1; this->_day -= 1; return temp; } //打印日期 void Date::PrintDate() { cout << this->_year << '/' << this->_month << '/' << this->_day << endl; } /////////////////////////////////////////测试函数 void TestDate() { Date d1(2018,6,13); /*Date d2(2019,5,10); Date d3; d3 = d2 - d1; d3.PrintDate(); d1.PrintDate();*/ d1 = d1 + 10; d1.PrintDate(); //cout << &d1 << ' ' << &d2 << endl; system("pause"); }
// // Activity_video_games.hpp // projekt_programowanie_obiektowe // // Created by Phillip on 11/06/2018. // Copyright © 2018 Phillip. All rights reserved. // #ifndef Activity_video_games_h #define Activity_video_games_h #include "Activity.hpp" class Activity_video_games : public Activity { public: void start_new_activity(); }; #endif /* Activity_video_games_h */
#ifndef __WPP__QT__QUICK_VIEW_H__ #define __WPP__QT__QUICK_VIEW_H__ #include <QQuickView> #include <QGuiApplication> namespace wpp { namespace qt { class QQuickView : public ::QQuickView { protected: QGuiApplication *app; public: explicit QQuickView(QGuiApplication *app, QWindow *parent = 0) : ::QQuickView(parent), app(app) { init(); } QQuickView(QGuiApplication *app, QQmlEngine* engine, QWindow *parent) : ::QQuickView(engine, parent), app(app) { init(); } QQuickView(QGuiApplication *app, const QUrl &source, QWindow *parent = 0) : ::QQuickView(source, parent), app(app) { init(); } virtual ~QQuickView() { } void show(); private: void init(); //helper }; } } #endif
#pragma once #include "CoreMinimal.h" #include "Components/InputComponent.h" #include "GameFramework/Pawn.h" #include "Tank.generated.h" UCLASS() class TANKBATTLE_API ATank : public APawn { GENERATED_BODY() public: ATank(); protected: virtual void BeginPlay() override; public: virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; UFUNCTION(BlueprintCallable, Category = Tank) void SetTurretChildActor(UChildActorComponent* TurretFromBp); private: // Rotate turret at speed , -ve values for CCW void RotateTurret(float Speed); // A reference from blueprint UChildActorComponent* Turret = nullptr; };
#include <iostream> #include <math.h> bool isPrime(int num) { for(int i = 2; i <= sqrt(num); ++i){ if(num % i == 0) { return false; } } return true; } int inputNumber() { int num = 0; std :: cout << "Input number to find prime divisors : "; std :: cin >> num; while(!std :: cin || num < 0){ std :: cin.clear(); std :: cin.ignore(); std :: cout << "Please input only positive numbers: "; std :: cin >> num; } return num; } bool printPrimeDivisors(int number) { int isTrue = 0; for (int i = 2; i < number; ++i) { if (0 == number % i && isPrime(i)) { isTrue = 1; std :: cout << i << " "; } } std :: cout << std :: endl; return isTrue; } int main() { int number = inputNumber(); if (!printPrimeDivisors(number)) { std :: cout << "The number hasn't got prime divisors.\n"; } return 0; }
// // FitnessFunction.cpp // GA // // Created by Tom den Ottelander on 19/11/2019. // Copyright © 2019 Tom den Ottelander. All rights reserved. // #include "FitnessFunction.hpp" using namespace std; using namespace nlohmann; extern bool storeAbsoluteConvergence; extern bool storeUniqueConvergence; extern bool printElitistArchiveOnUpdate; extern bool storeDistanceToParetoFrontOnElitistArchiveUpdate; extern nlohmann::json convergence; extern bool saveLogFilesOnEveryUpdate; extern string path_JSON_MO_info; extern string path_JSON_SO_info; extern string path_JSON_Run; extern string dataDir; extern nlohmann::json JSON_MO_info; extern nlohmann::json JSON_SO_info; extern nlohmann::json JSON_Run; extern bool storeElitistArchive; extern bool updateElitistArchiveOnEveryEvaluation; extern int loggingIntervalMode; extern int loggingLinearInterval; extern bool printEveryEvaluation; bool errorParetoFrontSent = false; bool errorParetoPointsSent = false; /* ------------------------ Base Fitness Function ------------------------ */ FitnessFunction::FitnessFunction(vector<float> optimum, ProblemType *problemType) : bestIndividual(), optimum(optimum), optimumFound(false), maxEvaluations(-1), maxUniqueEvaluations(-1), maxNetworkUniqueEvaluations(-1), problemType(problemType), totalEvaluations(0), totalUniqueEvaluations(0), totalNetworkUniqueEvaluations(0), uniqueSolutions() { } FitnessFunction::FitnessFunction(ProblemType *problemType) : bestIndividual(), optimumFound(false), maxEvaluations(-1), maxUniqueEvaluations(-1), maxNetworkUniqueEvaluations(-1), problemType(problemType), totalEvaluations(0), totalUniqueEvaluations(0), totalNetworkUniqueEvaluations(0), uniqueSolutions() { } void FitnessFunction::clear(){ bestIndividual = Individual(); elitistArchive.clear(); optimumFound = false; totalEvaluations = 0; totalUniqueEvaluations = 0; totalNetworkUniqueEvaluations = 0; uniqueSolutions.clear(); JSON_MO_info.clear(); JSON_SO_info.clear(); done = false; networkLibrary.clear(); } // Performs additional operations like incrementing the amount of (unique) evaluations, checking whether an individual is the best so far yet and storing convergence data. void FitnessFunction::evaluationProcedure(Individual &ind){ // cout << "Evaluating " << ind.toString() << "at eval=" << totalEvaluations << " and uniqEval=" << totalUniqueEvaluations << endl; checkIfBestFound(ind); totalEvaluations++; // Do this stuff only if it is a MO-problem. if(numObjectives > 1){ // Update the elitist archive if(updateElitistArchiveOnEveryEvaluation){ updateElitistArchive(&ind); } // Store the distance of the front to the approximation on every log10 interval. if(log(totalEvaluations)){ pair<float, float> avg_max_distance = calculateDistanceParetoToApproximation(); JSON_MO_info["changes_on_interval"]["total_evals"]["elitist_archive"].push_back(elitistArchiveToJSON()); JSON_MO_info["changes_on_interval"]["total_evals"]["avg_dist"].push_back(avg_max_distance.first); JSON_MO_info["changes_on_interval"]["total_evals"]["max_dist"].push_back(avg_max_distance.second); JSON_MO_info["changes_on_interval"]["total_evals"]["evals"].push_back(totalEvaluations); JSON_MO_info["changes_on_interval"]["total_evals"]["pareto_points_found"].push_back(paretoPointsFound()); } } // Do this stuff only if it is a SO-problem if (numObjectives == 1){ if(log(totalEvaluations)){ JSON_SO_info["changes_on_interval"]["total_evals"]["evaluated_solution_genotype"].push_back(Utility::genotypeToString(ind.genotype)); JSON_SO_info["changes_on_interval"]["total_evals"]["evaluated_solution_fitness"].push_back(ind.fitness[0]); JSON_SO_info["changes_on_interval"]["total_evals"]["best_solution_genotype"].push_back(Utility::genotypeToString(bestIndividual.genotype)); JSON_SO_info["changes_on_interval"]["total_evals"]["best_solution_fitness"].push_back(bestIndividual.fitness[0]); JSON_SO_info["changes_on_interval"]["total_evals"]["evals"].push_back(totalEvaluations); } // Store the best fitness found so far if(storeAbsoluteConvergence){ convergence["absolute"].push_back(bestIndividual.fitness[0]); } } // Do stuff based on whether this is a new unique evaluation if(!uniqueSolutions.contains(ind.genotype)){ uniqueSolutions.put(ind.genotype, ind.fitness); totalUniqueEvaluations++; // Store unique convergence only for SO-problems if(numObjectives == 1){ if(storeUniqueConvergence){ convergence["unique"].push_back(bestIndividual.fitness[0]); } if(log(totalUniqueEvaluations)){ JSON_SO_info["changes_on_interval"]["unique_evals"]["evaluated_solution_genotype"].push_back(Utility::genotypeToString(ind.genotype)); JSON_SO_info["changes_on_interval"]["unique_evals"]["evaluated_solution_fitness"].push_back(ind.fitness[0]); JSON_SO_info["changes_on_interval"]["unique_evals"]["best_solution_genotype"].push_back(Utility::genotypeToString(bestIndividual.genotype)); JSON_SO_info["changes_on_interval"]["unique_evals"]["best_solution_fitness"].push_back(bestIndividual.fitness[0]); JSON_SO_info["changes_on_interval"]["unique_evals"]["evals"].push_back(totalUniqueEvaluations); } } // Store distance front to approximation only if MO-problem and if unique evaluations is on a log10 interval. if(numObjectives > 1 && log(totalUniqueEvaluations)){ pair<float, float> avg_max_distance = calculateDistanceParetoToApproximation(); JSON_MO_info["changes_on_interval"]["unique_evals"]["elitist_archive"].push_back(elitistArchiveToJSON()); JSON_MO_info["changes_on_interval"]["unique_evals"]["avg_dist"].push_back(avg_max_distance.first); JSON_MO_info["changes_on_interval"]["unique_evals"]["max_dist"].push_back(avg_max_distance.second); JSON_MO_info["changes_on_interval"]["unique_evals"]["evals"].push_back(totalUniqueEvaluations); JSON_MO_info["changes_on_interval"]["unique_evals"]["pareto_points_found"].push_back(paretoPointsFound()); } } if(printEveryEvaluation){ cout << " Eval: " << Utility::padWithSpacesAfter(to_string(totalEvaluations), 8); cout << "UniqEval: " << Utility::padWithSpacesAfter(to_string(totalUniqueEvaluations), 8); cout << "NetworkUniqEval: " << Utility::padWithSpacesAfter(to_string(totalNetworkUniqueEvaluations), 8); cout << "Ind: " << ind.toString(); if (storeNetworkUniqueEvaluations){ try{ cout << " Network: " << networkLibrary.hash(ind.genotype); } catch (exception) { // Do nothing. } } cout << endl; } if(saveLogFilesOnEveryUpdate){ try{ Utility::writeRawData(JSON_Run.dump(), path_JSON_Run); if(numObjectives > 1) Utility::writeRawData(JSON_MO_info.dump(), path_JSON_MO_info); else Utility::writeRawData(JSON_SO_info.dump(), path_JSON_SO_info); } catch (exception) { cout << "Could not save results." << endl; } } } bool FitnessFunction::log(int evals){ switch (loggingIntervalMode) { case 0: return Utility::isLogPoint(evals, 2); case 1: return Utility::isLinearPoint(evals, loggingLinearInterval); default: cout << "Logging interval mode not set correctly." << endl; return false; } } bool FitnessFunction::isDone(){ if(done) { return true; } if(optimumFound || maxEvaluationsExceeded() || maxUniqueEvaluationsExceeded() || maxNetworkUniqueEvaluationsExceeded()){ done = true; } return done; } bool FitnessFunction::isMO(){ if(numObjectives > 1){ return true; } return false; } // Displays the description of the fitness function void FitnessFunction::display(){ cout << "Base fitness function" << endl; } // Checks whether this individual is fitter than the best found individual so far. // Checks whether the individual is optimal. void FitnessFunction::checkIfBestFound(Individual &ind){ if(optimumFound){ return; } if(convergenceCriteria == ConvergenceCriteria::OPTIMAL_FITNESS){ optimumFound = true; for (int obj = 0; obj < optimum.size(); obj++){ if (ind.fitness[obj] < optimum[obj] || optimum[obj] == -1){ optimumFound = false; break; } } } else if (convergenceCriteria == ConvergenceCriteria::GENOTYPE){ if(ind.genotypeEquals(optimalGenotype)){ optimumFound = true; }; } // Set bestIndividual only for SO-problems. if(numObjectives == 1 && ind.fitness[0] > bestIndividual.fitness[0]){ bestIndividual = ind.copy(); } } // Update the eltist archive by supplying the best front found. It adds non-dominated solution to and removes dominated solutions from the archive. Returns true if the supplied front adds any individuals to the elitist archive bool FitnessFunction::updateElitistArchive(Individual* ind){ bool addToArchive = true; // Loop over every solution that is in the archive at the beginning of this method. for (int i = elitistArchive.size() - 1; i >= 0; i--){ // Delete every solution from the archive that is dominated by this solution. if(ind->dominates(elitistArchive[i])){ elitistArchive.erase(elitistArchive.begin() + i); } // If the solution from the archive dominates this one or it is equal, then don't add this solution to the archive. Thus, remove it from the front. else if (elitistArchive[i].dominates(*ind) || ind->fitnessEquals(elitistArchive[i])){ addToArchive = false; return addToArchive; } } if (addToArchive){ // cout << "Add to archive: " << ind->toString() << endl; elitistArchive.push_back(ind->copy()); // Only check for convergence criteria if there are new solutions added to the elitist archive. pair<float, float> avg_max_distance = {-1, -1}; if (convergenceCriteria == ConvergenceCriteria::ENTIRE_PARETO){ // If the true pareto front is not known, rely on enitreParetoFrontFound() functions that are implemented in child classes if (trueParetoFront.size() == 0){ if(entireParetoFrontFound()){ optimumFound = true; } // Else, compute the avg distance of front to approximation and check if it is 0. (in fact if it is < 0.000001). } else { if (avg_max_distance.first == -1) avg_max_distance = calculateDistanceParetoToApproximation(); if (avg_max_distance.first < 0.000001){ optimumFound = true; } } } else if (convergenceCriteria == ConvergenceCriteria::EPSILON_PARETO_DISTANCE){ if (avg_max_distance.first == -1) avg_max_distance = calculateDistanceParetoToApproximation(); if (avg_max_distance.first <= epsilon){ optimumFound = true; } } else if (convergenceCriteria == ConvergenceCriteria::NONE){ // Do nothing } if (printElitistArchiveOnUpdate){ drawElitistArchive(); } } return addToArchive; } bool FitnessFunction::updateElitistArchive(vector<Individual> &front){ bool solutionsAdded = false; for (int i = 0; i < front.size(); i++){ bool added = updateElitistArchive(&front[i]); solutionsAdded = solutionsAdded || added; } return solutionsAdded; } bool FitnessFunction::updateElitistArchive(vector<Individual*> &front){ bool solutionsAdded = false; for (int i = 0; i < front.size(); i++){ bool added = updateElitistArchive(front[i]); solutionsAdded = solutionsAdded || added; } return solutionsAdded; } // The elitist archive is used as approximation // Returns two values in the pair: // value 1: the average of the distances from the points on the true pareto to the closest point in the elitist archive // value 2: the maximum of the distances from the points on the true pareto to the closest point in the elitist archive pair<float, float> FitnessFunction::calculateDistanceParetoToApproximation(){ if (trueParetoFront.size() == 0){ if (!errorParetoFrontSent) { cout << "ERROR: Wanted to calculate distance of pareto to approximation, but true Pareto front is unknown" << endl; errorParetoFrontSent = true; } storeDistanceToParetoFrontOnElitistArchiveUpdate = false; return {-1.0f, -1.0f}; } if (elitistArchive.size() == 0){ return {INFINITY, INFINITY}; } float summedDistance = 0.0f; float maxDistance = 0.0f; for (int i = 0; i < trueParetoFront.size(); i++){ float minimalDistance = INFINITY; for (int j = 0; j < elitistArchive.size(); j++){ float distance = Utility::EuclideanDistance(trueParetoFront[i], elitistArchive[j].fitness); if (distance < minimalDistance){ minimalDistance = distance; if (distance == 0.0f){ break; } } } summedDistance += minimalDistance; maxDistance = max(maxDistance, minimalDistance); } float avgDistance = summedDistance / trueParetoFront.size(); // distanceToParetoFrontData.push_back(tuple<int, int, float>{totalEvaluations, totalUniqueEvaluations, avgDistance}); return {avgDistance, maxDistance}; } int FitnessFunction::paretoPointsFound(){ if(trueParetoFront.size() == 0){ if (!errorParetoPointsSent){ cout << "No Pareto points known" << endl; errorParetoPointsSent = true; } return 0; } int pointsFound = 0; for (int i = 0; i < trueParetoFront.size(); i++){ vector<float> paretoPoint = trueParetoFront[i]; for (int j = 0; j < elitistArchive.size(); j++){ if (elitistArchive[j].fitness[0] == paretoPoint[0] && elitistArchive[j].fitness[1] == paretoPoint[1]){ pointsFound++; break; } } } return pointsFound; } json FitnessFunction::elitistArchiveToJSON(){ json result; for (int i = 0; i < elitistArchive.size(); i++){ json solution; solution["g"] = Utility::genotypeToString(elitistArchive[i].genotype); json array; array[0] = elitistArchive[i].fitness[0]; array[1] = elitistArchive[i].fitness[1]; solution["f"] = array; result[i] = solution; } return result; } // Override this method in specific problems. For example, do an extra check on objective values. bool FitnessFunction::entireParetoFrontFound(){ return elitistArchive.size() == optimalParetoFrontSize; } void FitnessFunction::setGenotypeChecking(vector<int> genotype){ checkForGenotype = true; optimalGenotype = genotype; } // Returns the total amount of evaluations over all fitness functions. int FitnessFunction::getTotalAmountOfEvaluations(){ return totalEvaluations; } // Checks whether the maximum amount of evaluations is exceeded bool FitnessFunction::maxEvaluationsExceeded(){ return totalEvaluations >= maxEvaluations && maxEvaluations != -1; } bool FitnessFunction::maxUniqueEvaluationsExceeded(){ return totalUniqueEvaluations >= maxUniqueEvaluations && maxUniqueEvaluations != -1; } bool FitnessFunction::maxNetworkUniqueEvaluationsExceeded(){ return totalNetworkUniqueEvaluations >= maxNetworkUniqueEvaluations && maxNetworkUniqueEvaluations != -1; } // Returns the id of the fitness function string FitnessFunction::id() { return "base"; } // Sets the length and the optimum void FitnessFunction::setLength(int length){ totalProblemLength = length; } void FitnessFunction::setNumObjectives(int numObj){ numObjectives = numObj; } // Sets the MO-problem optimum. void FitnessFunction::setOptimum(vector<float> opt){ optimum = opt; } // Sets the SO-problem optimum. void FitnessFunction::setOptimum(float opt){ optimum[0] = opt; } // Transforms the genotype (e.g. remove identity layers in encoding) // Should be overridden in derived classes vector<int> FitnessFunction::transform(vector<int> &genotype){ return genotype; } void FitnessFunction::draw2DVisualization(vector<Individual> &population, int maxX, int maxY){ vector<Individual*> drawList; drawList.reserve(population.size()); for (int i = 0; i < population.size(); i++){ drawList.push_back(&population[i]); } sort(drawList.begin(), drawList.end(), [](const Individual* lhs, const Individual* rhs){ if (lhs->fitness[1] < rhs->fitness[1]){ return true; } else if (lhs->fitness[1] > rhs->fitness[1]){ return false; } else { return lhs->fitness[0] < rhs->fitness[0]; } }); int i = 0; string result = ""; for (int y = 0; y < maxY; y++){ for (int x = 0; x < maxX; x++){ if (drawList[i]->fitness[0] == x && drawList[i]->fitness[1] == y){ result += " o "; } else { result += " . "; } result += " "; while (drawList[i]->fitness[0] == x && drawList[i]->fitness[1] == y && i < drawList.size()-1){ i++; } } result += "\n"; } cout << result << endl; } void FitnessFunction::drawElitistArchive(){ draw2DVisualization(elitistArchive, optimum[0]+1, optimum[1]+1); } void FitnessFunction::saveElitistArchiveToJSON(){ json result; for (int i = 0; i < elitistArchive.size(); i++){ json solution; solution["genotype"] = Utility::genotypeToString(elitistArchive[i].genotype); json fitness; for (int j = 0; j < numObjectives; j++){ fitness[j] = elitistArchive[i].fitness[j]; } solution["fitness"] = fitness; result[i] = solution; } Utility::writeRawData(result.dump(), dataDir, ""); } void FitnessFunction::printElitistArchive(bool fullArchive){ bool printDots = true; cout << "Elitist archive: (size=" << elitistArchive.size() << ")" << endl; for (int i = 0; i < elitistArchive.size(); i++){ if(fullArchive || i == 0 || i == 1 || i == elitistArchive.size() - 1){ cout << i << ": " << elitistArchive[i].toString() << endl; } else if (printDots){ cout << "..." << endl; printDots = false; } } } void FitnessFunction::logNetworkUniqueEvaluations(){ if (numObjectives == 1){ JSON_SO_info["changes_on_interval"]["network_unique_evals"]["best_solution_genotype"].push_back(Utility::genotypeToString(bestIndividual.genotype)); JSON_SO_info["changes_on_interval"]["network_unique_evals"]["best_solution_fitness"].push_back(bestIndividual.fitness[0]); JSON_SO_info["changes_on_interval"]["network_unique_evals"]["evals"].push_back(totalNetworkUniqueEvaluations); if(saveLogFilesOnEveryUpdate) Utility::writeRawData(JSON_SO_info.dump(), path_JSON_SO_info); } else { pair<float, float> avg_max_distance = calculateDistanceParetoToApproximation(); JSON_MO_info["changes_on_interval"]["network_unique_evals"]["elitist_archive_fitness"].push_back(elitistArchiveToJSON()); JSON_MO_info["changes_on_interval"]["network_unique_evals"]["avg_dist"].push_back(avg_max_distance.first); JSON_MO_info["changes_on_interval"]["network_unique_evals"]["max_dist"].push_back(avg_max_distance.second); JSON_MO_info["changes_on_interval"]["network_unique_evals"]["evals"].push_back(totalNetworkUniqueEvaluations); JSON_MO_info["changes_on_interval"]["network_unique_evals"]["pareto_points_found"].push_back(paretoPointsFound()); if(saveLogFilesOnEveryUpdate) Utility::writeRawData(JSON_MO_info.dump(), path_JSON_MO_info); } } /* ------------------------ OneMax Fitness Function ------------------------ */ OneMax::OneMax(int length) : FitnessFunction(vector<float>(1, length), getProblemType()) {} OneMax::OneMax() : FitnessFunction(getProblemType()) {} vector<float> OneMax::evaluate(Individual &ind) { int summedGenotype = accumulate(ind.genotype.begin(), ind.genotype.end(), 0); vector<float> result(1, summedGenotype); ind.fitness[0] = result[0]; evaluationProcedure(ind); return result; } void OneMax::display() { cout << "OneMax fitness function" << endl; } string OneMax::id() { return "OM"; } ProblemType* OneMax::getProblemType(){ return new BinaryProblemType(); } FitnessFunction* OneMax::clone() const { FitnessFunction* result = new OneMax(static_cast<const OneMax&>(*this)); result->problemType = this->problemType; return result; } /* ------------------------ Leading Ones Fitness Function ------------------------ */ LeadingOnes::LeadingOnes(int length) : FitnessFunction(vector<float>(1, length), getProblemType()) {} LeadingOnes::LeadingOnes() : FitnessFunction(getProblemType()) {} ProblemType* LeadingOnes::getProblemType(){ return new BinaryProblemType(); } vector<float> LeadingOnes::evaluate(Individual &ind) { vector<float> result (1, 0); for (unsigned long i = 0; i < ind.genotype.size(); i++){ if (ind.genotype[i] == 0){ break; } else { result[0]++; } } ind.fitness[0] = result[0]; evaluationProcedure(ind); return result; } FitnessFunction* LeadingOnes::clone() const { FitnessFunction* result = new LeadingOnes(static_cast<const LeadingOnes&>(*this)); result->problemType = this->problemType; return result; } void LeadingOnes::display() { cout << "LeadingOnes fitness function" << endl; } string LeadingOnes::id() { return "LO"; }
class woodfence_foundation_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_1_foundation; descriptionShort = $STR_BLD_name_WoodenFence_1_foundation; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_1_foundation_DZ"; }; }; }; class woodfence_frame_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_1_frame; descriptionShort = $STR_BLD_name_WoodenFence_1_frame; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_1_frame_DZ"; }; }; }; class woodfence_quaterpanel_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_quaterpanel; descriptionShort = $STR_BLD_name_WoodenFence_quaterpanel; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_quaterpanel_DZ"; }; }; }; class woodfence_halfpanel_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_halfpanel; descriptionShort = $STR_BLD_name_WoodenFence_halfpanel; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_halfpanel_DZ"; }; }; }; class woodfence_thirdpanel_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_thirdpanel; descriptionShort = $STR_BLD_name_WoodenFence_thirdpanel; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_thirdpanel_DZ"; }; }; }; class woodfence_1_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_1; descriptionShort = $STR_BLD_name_WoodenFence_1; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_1_DZ"; }; }; }; class woodfence_2_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_2; descriptionShort = $STR_BLD_name_WoodenFence_2; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_2_DZ"; }; }; }; class woodfence_3_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_3; descriptionShort = $STR_BLD_name_WoodenFence_3; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_3_DZ"; }; }; }; class woodfence_4_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_4; descriptionShort = $STR_BLD_name_WoodenFence_4; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_4_DZ"; }; }; }; class woodfence_5_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_5; descriptionShort = $STR_BLD_name_WoodenFence_5; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_5_DZ"; }; }; }; class woodfence_6_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_6; descriptionShort = $STR_BLD_name_WoodenFence_6; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_6_DZ"; }; }; }; class woodfence_7_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenFence_7; descriptionShort = $STR_BLD_name_WoodenFence_7; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenFence_7_DZ"; }; }; }; class metalfence_foundation_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_1_foundation; descriptionShort = $STR_BLD_name_MetalFence_1_foundation; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_1_foundation_DZ"; }; }; }; class metalfence_frame_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_1_frame; descriptionShort = $STR_BLD_name_MetalFence_1_frame; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_1_frame_DZ"; }; }; }; class metalfence_halfpanel_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_halfpanel; descriptionShort = $STR_BLD_name_MetalFence_halfpanel; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_halfpanel_DZ"; }; }; }; class metalfence_thirdpanel_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_thirdpanel; descriptionShort = $STR_BLD_name_MetalFence_thirdpanel; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_thirdpanel_DZ"; }; }; }; class metalfence_1_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_1; descriptionShort = $STR_BLD_name_MetalFence_1; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_1_DZ"; }; }; }; class metalfence_2_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_2; descriptionShort = $STR_BLD_name_MetalFence_2; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_2_DZ"; }; }; }; class metalfence_3_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_3; descriptionShort = $STR_BLD_name_MetalFence_3; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_3_DZ"; }; }; }; class metalfence_4_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_4; descriptionShort = $STR_BLD_name_MetalFence_4; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_4_DZ"; }; }; }; class metalfence_5_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_5; descriptionShort = $STR_BLD_name_MetalFence_5; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_5_DZ"; }; }; }; class metalfence_6_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_6; descriptionShort = $STR_BLD_name_MetalFence_6; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_6_DZ"; }; }; }; class metalfence_7_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_MetalFence_7; descriptionShort = $STR_BLD_name_MetalFence_7; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "MetalFence_7_DZ"; }; }; }; class woodfence_gate_foundation_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenGate_Foundation; descriptionShort = $STR_BLD_name_WoodenGate_Foundation; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenGate_foundation_DZ"; }; }; }; class woodfence_gate_1_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenGate_1; descriptionShort = $STR_BLD_name_WoodenGate_1; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenGate_1_DZ"; }; }; }; class woodfence_gate_2_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenGate_2; descriptionShort = $STR_BLD_name_WoodenGate_2; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenGate_2_DZ"; }; }; }; class woodfence_gate_3_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenGate_3; descriptionShort = $STR_BLD_name_WoodenGate_3; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenGate_3_DZ"; }; }; }; class woodfence_gate_4_kit: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_WoodenGate_4; descriptionShort = $STR_BLD_name_WoodenGate_4; model = "\z\addons\dayz_epoch\models\supply_crate.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; class ItemActions { class Build { text = $STR_ACTIONS_BUILD; script = "spawn player_build;"; require[] = {"ItemToolbox","ItemEtool"}; create = "WoodenGate_4_DZ"; }; }; };
#include "State.h" Transition* State::getTriggeredTransition(Agent* gameObject) { for (auto transition : m_transitions) { if (transition->hasTriggered(gameObject)) { return transition; } } return nullptr; }
#include "G4RunManager.hh" #include "G4UImanager.hh" #include "G4UIterminal.hh" #include "QGSP_BERT.hh" #include "G4VisExecutive.hh" #include "G4UIExecutive.hh" #ifdef G4UI_USE_TCSH #include "G4UItcsh.hh" #endif #ifdef G4VIS_USE #include "G4VisExecutive.hh" #endif #include "H_DetectorConstruction.h" #include "H_PrimaryGeneratorAction.h" #include "H_RunAction.h" #include "H_EventAction.h" #include "H_SteppingAction.h" #include "Randomize.hh" int main(int argc, char** argv) { G4UIExecutive* ui = 0; if ( argc == 1 ) { ui = new G4UIExecutive(argc, argv); } G4long myseed = 345354; G4Random::setTheEngine(new CLHEP::RanecuEngine); G4Random::setTheSeed(myseed); // Run manager initialization G4RunManager* runManager = new G4RunManager; G4VUserDetectorConstruction* detector = new H_DetectorConstruction; runManager->SetUserInitialization(detector); // QGSP_BERT Physics list (HEP, used by ATLAS) G4VModularPhysicsList* physicsList = new QGSP_BERT; physicsList->SetVerboseLevel(0); runManager->SetUserInitialization(physicsList); H_RunAction* runAction = new H_RunAction; runManager->SetUserAction(runAction); H_PrimaryGeneratorAction* genAction = new H_PrimaryGeneratorAction(); runManager->SetUserAction(genAction); H_SteppingAction* stepAction = new H_SteppingAction(genAction); runManager->SetUserAction(stepAction); H_EventAction* eventAction = new H_EventAction(runAction, stepAction); runManager->SetUserAction(eventAction); G4VisManager* visManager = new G4VisExecutive; // G4VisExecutive can take a verbosity argument - see /vis/verbose guidance. // G4VisManager* visManager = new G4VisExecutive("Quiet"); visManager->Initialize(); G4UImanager* UImanager = G4UImanager::GetUIpointer(); if ( ! ui ) { // batch mode G4String command = "/control/execute "; G4String fileName = argv[1]; UImanager->ApplyCommand(command+fileName); } else { // interactive mode UImanager->ApplyCommand("/control/execute init_vis.mac"); if (ui->IsGUI()) { UImanager->ApplyCommand("/control/execute gui.mac"); } ui->SessionStart(); delete ui; } return 0; }
#include "scene_lights.h" SceneLights::SceneLights(State& state): mState(&state), mUniformBufferInfo(state.device), mSphere(state), ubo(nullptr) { descriptors = {}; } SceneLights::~SceneLights() { if (ubo) { vkUnmapMemory(mState->device, mUniformBufferInfo.memory); ubo = nullptr; } } void SceneLights::init() { mSphere.init(8, 16); //PointLight& l1 = createPointLight(); //l1.init(*mState, glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), 1.33f); //PointLight& l2 = createPointLight(); //l2.init(*mState, glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(2.0f, -1.0f, 0.0f), 1.0f); //l2.ubo->model = glm::translate(glm::vec3(2.0f, -1.0, 0.0f)); //PointLight l2 = createPointLight(); createUniformBuffer(); createDescriptorPool(); createDescriptorSets(); } VkDeviceSize SceneLights::calcAlignment(uint32_t structSize) { // (num of alignments in struct [0, n]) * (size of alignment) + (aligment if struct is not multiple of alignment) // for alignment of 256 // if struct size = 264 -> (264 / 256) * 256 + ((264 % 256) > 0 ? 256 : 0 -> 1 * 256 + 256 // if struct size = 64 -> (64 / 256) * 256 + ((64 % 256) > 0 ? 256 : 0 -> 0 + 256 // if struct size = 512 -> (512 / 256) * 256 + ((512 % 256) > 0 ? 256 : 0 -> 512 + 0 VkDeviceSize uboAlignment = mState->deviceInfo.minUniformBufferOffsetAlignment; return (structSize / uboAlignment) * uboAlignment + ((structSize % uboAlignment) > 0 ? uboAlignment : 0); } void SceneLights::draw(VkCommandBuffer& cmdBuffer) { vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mState->pipelines.pointLight.pipeline); vkCmdBindVertexBuffers(cmdBuffer, 0, 1, &(mSphere.mCommonBufferInfo.buffer), &(mSphere.vertexBufferOffset)); vkCmdBindIndexBuffer(cmdBuffer, mSphere.mCommonBufferInfo.buffer, mSphere.indexBufferOffset, VK_INDEX_TYPE_UINT32); for (size_t i = 0; i < pointLights.size(); ++i) { uint32_t uboOffset = sceneAlignment + i * mDynamicAlignmentSize; uint32_t lightOffset = uboOffset + pointLightUboAlignment; uint32_t dynamicOffsets[] = { uboOffset, lightOffset }; vkCmdBindDescriptorSets( cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mState->pipelines.pointLight.layout, 0, descriptors.size(), descriptors.data(), NUM_DYNAMIC_OFFSETS, dynamicOffsets); vkCmdDrawIndexed(cmdBuffer, mSphere.numIndices, 1, 0, 0, 0); } } void SceneLights::update(VkCommandBuffer& cmdBuffer, const Timer& timer, Camera& camera) { mState->ubo.view = camera.view(); mState->ubo.proj = camera.proj(); *((State::UBO*) ubo) = mState->ubo; //memcpy(ubo, &(mState->ubo), sizeof(State::UBO)); for (size_t i = 0; i < pointLights.size(); ++i) { uint32_t uboOffset = sceneAlignment + i * mDynamicAlignmentSize; uint32_t lightOffset = uboOffset + pointLightUboAlignment; PointLight::UBO& model = pointLightUbos[i]; PointLight::LightUBO& lightUbo = pointLightLightUbos[i]; //PointLight::UBO* modelPtr = reinterpret_cast<PointLight::UBO*>(ubo + uboOffset); //*modelPtr = model; *((PointLight::UBO*) (ubo + uboOffset)) = model; *((PointLight::LightUBO*) (ubo + lightOffset)) = lightUbo; } VkMappedMemoryRange range = {}; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.memory = mUniformBufferInfo.memory; range.size = mUniformBufferInfo.size; vkFlushMappedMemoryRanges(mState->device, 1, &range); /*vkCmdUpdateBuffer( cmdBuffer, mUniformBufferInfo.buffer, 0, mUniformBufferInfo.size, ubo);*/ } void SceneLights::createUniformBuffer() { sceneAlignment = calcAlignment(sizeof(State::UBO)); pointLightUboAlignment = calcAlignment(sizeof(PointLight::UBO)); pointLightLightAlignment = calcAlignment(sizeof(PointLight::LightUBO)); offsetUbos = sceneAlignment; offsetLightUbos = offsetUbos; mDynamicAlignmentSize = pointLightUboAlignment + pointLightLightAlignment; VkDeviceSize bufSize = sceneAlignment + pointLights.size() * mDynamicAlignmentSize; mUniformBufferInfo.size = bufSize; BufferHelper::createDynamicUniformBuffer(*mState, mUniformBufferInfo); vkMapMemory(mState->device, mUniformBufferInfo.memory, 0, mUniformBufferInfo.size, 0, (void**) &ubo); LOG("SCENE LIGHTS UNIFORM BUFFER"); } void SceneLights::createDescriptorSets() { VkDescriptorSetLayout layouts[] = { mState->descriptorSetLayouts.uniformVertex, mState->descriptorSetLayouts.dynamicUniformVertex, mState->descriptorSetLayouts.dynamicUniformFragment }; /*VkDescriptorSet descriptors[] = { sceneSet, modelSet, lightSet };*/ VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = mDescriptorPool; allocInfo.descriptorSetCount = NUM_POINT_LIGHT_DESCRIPTORS; allocInfo.pSetLayouts = layouts; VK_CHECK_RESULT(vkAllocateDescriptorSets(mState->device, &allocInfo, descriptors.data())); VkDescriptorBufferInfo sceneInfo = {}; sceneInfo.buffer = mUniformBufferInfo.buffer; sceneInfo.offset = 0; sceneInfo.range = sizeof(State::UBO); VkDescriptorBufferInfo buffInfo = {}; buffInfo.buffer = mUniformBufferInfo.buffer; buffInfo.offset = 0; buffInfo.range = sizeof(PointLight::UBO); VkDescriptorBufferInfo lightBuffInfo = {}; lightBuffInfo.buffer = mUniformBufferInfo.buffer; lightBuffInfo.offset = 0; lightBuffInfo.range = sizeof(PointLight::LightUBO); std::array<VkWriteDescriptorSet, 3> writeSets = {}; writeSets[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeSets[0].dstSet = descriptors[0]; writeSets[0].dstBinding = 0; writeSets[0].dstArrayElement = 0; writeSets[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeSets[0].descriptorCount = 1; writeSets[0].pBufferInfo = &sceneInfo; writeSets[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeSets[1].dstSet = descriptors[1]; writeSets[1].dstBinding = 0; writeSets[1].dstArrayElement = 0; writeSets[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; writeSets[1].descriptorCount = 1; writeSets[1].pBufferInfo = &buffInfo; writeSets[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeSets[2].dstSet = descriptors[2]; writeSets[2].dstBinding = 0; writeSets[2].dstArrayElement = 0; writeSets[2].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; writeSets[2].descriptorCount = 1; writeSets[2].pBufferInfo = &lightBuffInfo; vkUpdateDescriptorSets(mState->device, writeSets.size(), writeSets.data(), 0, nullptr); LOG("SCENE LIGHTS DESCRIPTORS"); /* List of descriptors example uint32_t numDescriptors = numPointLightDescriptors * pointLights.size(); std::vector<VkWriteDescriptorSet> writeSets(numDescriptors); std::vector<VkDescriptorSetLayout> layouts(pointLights.size(), mState->descriptorSetLayouts.pointLight); pointLightDescriptors.resize(pointLights.size()); pointLightInfos.resize(pointLights.size()); VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = mDescriptorPool; allocInfo.descriptorSetCount = pointLightDescriptors.size(); allocInfo.pSetLayouts = layouts.data(); VK_CHECK_RESULT(vkAllocateDescriptorSets(mState->device, &allocInfo, pointLightDescriptors.data())); VkDescriptorBufferInfo sceneInfo = {}; sceneInfo.buffer = mUniformBufferInfo.buffer; sceneInfo.offset = 0; sceneInfo.range = sizeof(State::UBO); VkDeviceSize offset = sceneAlignment; for (size_t i = 0; i < pointLights.size(); ++i) { PointLightInfo& info = pointLightInfos[i]; //PointLight& light = *(pointLights[i]); VkDescriptorSet& descSet = pointLightDescriptors[i]; //VkDescriptorSet& lightSet = pointLightDescriptors[setsPerLight * i + 1]; VkWriteDescriptorSet& sceneWriteSet = writeSets[numPointLightDescriptors * i]; VkWriteDescriptorSet& uboWriteSet = writeSets[numPointLightDescriptors * i + 1]; VkWriteDescriptorSet& lightWriteSet = writeSets[numPointLightDescriptors * i + 2]; info.uboOffset = offset; VkDescriptorBufferInfo buffInfo = {}; buffInfo.buffer = mUniformBufferInfo.buffer; buffInfo.offset = offset; buffInfo.range = sizeof(PointLight::UBO); offset += pointLightUboAlignment; info.lightOffset = offset; VkDescriptorBufferInfo lightBuffInfo = {}; lightBuffInfo.buffer = mUniformBufferInfo.buffer; lightBuffInfo.offset = offset; lightBuffInfo.range = sizeof(PointLight::LightUBO); offset += pointLightLightAlignment; sceneWriteSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; sceneWriteSet.dstSet = descSet; sceneWriteSet.dstBinding = 0; sceneWriteSet.dstArrayElement = 0; sceneWriteSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; sceneWriteSet.descriptorCount = 1; sceneWriteSet.pBufferInfo = &sceneInfo; uboWriteSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; uboWriteSet.dstSet = descSet; uboWriteSet.dstBinding = 1; uboWriteSet.dstArrayElement = 0; uboWriteSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; uboWriteSet.descriptorCount = 1; uboWriteSet.pBufferInfo = &buffInfo; lightWriteSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; lightWriteSet.dstSet = descSet; lightWriteSet.dstBinding = 2; lightWriteSet.dstArrayElement = 0; lightWriteSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; lightWriteSet.descriptorCount = 1; lightWriteSet.pBufferInfo = &lightBuffInfo; } vkUpdateDescriptorSets(mState->device, writeSets.size(), writeSets.data(), 0, nullptr); */ } void SceneLights::createDescriptorPool() { /* VkDescriptorPoolSize uboSize = {}; uboSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; uboSize.descriptorCount = pointLights.size() + 1; */ VkDescriptorPoolSize uboSize = {}; uboSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; uboSize.descriptorCount = NUM_POINT_LIGHT_DESCRIPTORS; VkDescriptorPoolSize uniformSize = {}; uniformSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uniformSize.descriptorCount = NUM_POINT_LIGHT_DESCRIPTORS; VkDescriptorPoolSize poolSizes[] = { uboSize, uniformSize }; VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = ARRAY_SIZE(poolSizes); poolInfo.pPoolSizes = poolSizes; poolInfo.maxSets = uboSize.descriptorCount; VK_CHECK_RESULT(vkCreateDescriptorPool(mState->device, &poolInfo, nullptr, &mDescriptorPool)); LOG("SCENE LIGHTS DESCRIPTOR POOL"); } void SceneLights::addLight(PointLight& light) { // pointLights.push_back(&light); } PointLight& SceneLights::createPointLight(PointLight::UBO& ubo, PointLight::LightUBO& lightUbo) { pointLightUbos.push_back(ubo); pointLightLightUbos.push_back(lightUbo); pointLights.push_back(PointLight(pointLightUbos.back(), pointLightLightUbos.back())); return pointLights.back(); } PointLight& SceneLights::createPointLight() { PointLight::UBO ubo = {}; PointLight::LightUBO lightUbo = {}; return createPointLight(ubo, lightUbo); }
/* multiplicacion de matriz de 3x3 con vector por Jorge Luis Mancera A1 PI LAD*/ #include <iostream> using namespace std; int main () { float a[1][3], b[3][3], c[1][3]; int i=0, k=0, l=0 ; for (int j=0;j<3;j++){ cout<<"Ingrese el elemento "<< i <<","<< j <<" del vector: "; cin>>a[i][j]; } cout<<endl; for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ cout<<"Ingrese el elemento "<< i <<","<< j <<" de la matriz: "; cin>>b[i][j]; } } cout<<endl; c[0][0]=(a[0][0])*(b[0][0])+(a[0][1])*(b[1][0])+(a[0][2])*(b[2][0]); c[0][1]=(a[0][0])*(b[0][1])+(a[0][1])*(b[1][1])+(a[0][2])*(b[2][1]); c[0][2]=(a[0][0])*(b[0][2])+(a[0][1])*(b[1][2])+(a[0][2])*(b[2][2]); cout<<"La multiplicacion de: "<<endl<<endl<<endl; cout<< a[0][0]<<" "; cout<< a[0][1]<<" "; cout<< a[0][2]<<" "<<endl<<endl<<endl; cout<<"y "<<endl<<endl<<endl; cout<< b[0][0]<<" "; cout<< b[0][1]<<" "; cout<< b[0][2]<<" "<<endl<<endl; cout<< b[1][0]<<" "; cout<< b[1][1]<<" "; cout<< b[1][2]<<" "<<endl<<endl; cout<< b[2][0]<<" "; cout<< b[2][1]<<" "; cout<< b[2][2]<<" "; cout<<endl<<endl<<endl; cout<<"es: "<<endl<<endl<<endl; cout<< c[0][0]<<" "; cout<< c[0][1]<<" "; cout<< c[0][2]<<" "<<endl<<endl; return 0; }
// // www.blinkenlight.net // // Copyright 2016 Udo Klein // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ #include <dcf77.h> // Affichage TFT #include <TFT_ST7735.h> // Graphics and font library for ST7735 driver chip #include <SPI.h> #define TFT_GREY 0x7BEF #define TFT_W 160 #define TFT_H 128 // Buffers pour affichage char fdate[16]; char ftime[9]; TFT_ST7735 myGLCD = TFT_ST7735(); // Invoke library, pins defined in User_Setup.h #define DELAY 500 unsigned long runTime = 0; #if defined(__AVR__) const uint8_t dcf77_analog_sample_pin = 5; //const uint8_t dcf77_sample_pin = A5; // A5 == d19 const uint8_t dcf77_sample_pin = 2; // Any valid digital pin const uint8_t dcf77_inverted_samples = 0; const uint8_t dcf77_analog_samples = 0; const uint8_t dcf77_pin_mode = INPUT; // disable internal pull up // const uint8_t dcf77_pin_mode = INPUT_PULLUP; // enable internal pull up const uint8_t dcf77_monitor_led = 18; // A4 == d18 uint8_t ledpin(const uint8_t led) { return led; } #else const uint8_t dcf77_sample_pin = 53; const uint8_t dcf77_inverted_samples = 0; // const uint8_t dcf77_pin_mode = INPUT; // disable internal pull up const uint8_t dcf77_pin_mode = INPUT_PULLUP; // enable internal pull up const uint8_t dcf77_monitor_led = 19; uint8_t ledpin(const uint8_t led) { return led < 14 ? led : led + (54 - 14); } #endif // DCF transmitter is in CET/CEST time zone const int8_t timezone_offset = 0; // Paris, Amsterdam, Berlin, Roma... namespace Timezone { uint8_t days_per_month(const Clock::time_t &now) { switch (now.month.val) { case 0x02: // valid till 31.12.2399 // notice year mod 4 == year & 0x03 return 28 + ((now.year.val != 0) && ((bcd_to_int(now.year) & 0x03) == 0) ? 1 : 0); case 0x01: case 0x03: case 0x05: case 0x07: case 0x08: case 0x10: case 0x12: return 31; case 0x04: case 0x06: case 0x09: case 0x11: return 30; default: return 0; } } void adjust(Clock::time_t &time, const int8_t offset) { // attention: maximum supported offset is +/- 23h int8_t hour = BCD::bcd_to_int(time.hour) + offset; if (hour > 23) { hour -= 24; uint8_t day = BCD::bcd_to_int(time.day) + 1; if (day > days_per_month(time)) { day = 1; uint8_t month = BCD::bcd_to_int(time.month); ++month; if (month > 12) { month = 1; uint8_t year = BCD::bcd_to_int(time.year); ++year; if (year > 99) { year = 0; } time.year = BCD::int_to_bcd(year); } time.month = BCD::int_to_bcd(month); } time.day = BCD::int_to_bcd(day); time.weekday.val = time.weekday.val < 7 ? time.weekday.val + 1 : time.weekday.val - 6; } if (hour < 0) { hour += 24; uint8_t day = BCD::bcd_to_int(time.day) - 1; if (day < 1) { uint8_t month = BCD::bcd_to_int(time.month); --month; if (month < 1) { month = 12; int8_t year = BCD::bcd_to_int(time.year); --year; if (year < 0) { year = 99; } time.year = BCD::int_to_bcd(year); } time.month = BCD::int_to_bcd(month); day = days_per_month(time); } time.day = BCD::int_to_bcd(day); time.weekday.val = time.weekday.val > 1 ? time.weekday.val - 1 : time.weekday.val + 6; } time.hour = BCD::int_to_bcd(hour); } } uint8_t sample_input_pin() { const uint8_t sampled_data = #if defined(__AVR__) dcf77_inverted_samples ^ (dcf77_analog_samples ? (analogRead(dcf77_analog_sample_pin) > 200) : digitalRead(dcf77_sample_pin)); #else dcf77_inverted_samples ^ digitalRead(dcf77_sample_pin); #endif digitalWrite(ledpin(dcf77_monitor_led), sampled_data); return sampled_data; } void dateTimeDisplay(Clock::time_t now) { char *fmtDate = formatDate(now); char *fmtTime = formatTime(now); char *fmtTimeZone = formatTimeZone(now); myGLCD.setTextColor(TFT_MAGENTA, TFT_BLACK); myGLCD.drawString(fmtDate, 30, 32, 2); myGLCD.setTextColor(TFT_CYAN, TFT_BLACK); myGLCD.drawString(fmtTime, 32, 56, 4); myGLCD.drawString(fmtTimeZone, 65, 82, 2); } Clock::time_t dummy; void makeDummyDateTime() { dummy.day = BCD::int_to_bcd(1); dummy.month = BCD::int_to_bcd(12); dummy.year = BCD::int_to_bcd(41); dummy.weekday = BCD::int_to_bcd(4); dummy.hour = BCD::int_to_bcd(1); dummy.minute = BCD::int_to_bcd(23); dummy.second = BCD::int_to_bcd(45); dummy.uses_summertime = true; } const char *fDayOfWeek(Clock::time_t now) { switch (now.weekday.val) { case 0x01: return "LUN"; case 0x02: return "MAR"; case 0x03: return "MER"; case 0x04: return "JEU"; case 0x05: return "VEN"; case 0x06: return "SAM"; case 0x07: return "DIM"; } } const char *fMonth(Clock::time_t now) { switch (now.month.val) { case 0x01: return "JAN"; case 0x02: return "FEV"; case 0x03: return "MAR"; case 0x04: return "AVR"; case 0x05: return "MAI"; case 0x06: return "JUN"; case 0x07: return "JUL"; case 0x08: return "AOU"; case 0x09: return "SEP"; case 0x10: return "OCT"; case 0x11: return "NOV"; case 0x12: return "DEC"; } } char *formatDate(Clock::time_t now) { int offset = 0; strncpy(fdate, fDayOfWeek(now), 3); fdate[3] = ' '; if (now.day.digit.hi) { fdate[4] = '0' + now.day.digit.hi; fdate[5] = '0' + now.day.digit.lo; offset = 6; } else { fdate[4] = '0' + now.day.digit.lo; offset = 5; } fdate[offset] = ' '; strncpy(fdate + offset + 1, fMonth(now), 3); fdate[offset + 4] = ' '; fdate[offset + 5] = '2'; fdate[offset + 6] = '0'; fdate[offset + 7] = '0' + now.year.digit.hi; fdate[offset + 8] = '0' + now.year.digit.lo; fdate[offset + 9] = 0; return fdate; } char *formatTime(Clock::time_t now) { ftime[0] = '0' + now.hour.digit.hi; ftime[1] = '0' + now.hour.digit.lo; ftime[2] = ':'; ftime[3] = '0' + now.minute.digit.hi; ftime[4] = '0' + now.minute.digit.lo; ftime[5] = ':'; ftime[6] = '0' + now.second.digit.hi; ftime[7] = '0' + now.second.digit.lo; ftime[8] = 0; return ftime; } char *formatTimeZone(Clock::time_t now) { return now.uses_summertime ? " CEST" : " CET "; } void setup() { pinMode(7, OUTPUT); digitalWrite(7, LOW); delay(10); digitalWrite(7, HIGH); // Setup the LCD myGLCD.init(); myGLCD.setRotation(3); myGLCD.fillScreen(TFT_BLACK); myGLCD.setTextColor(TFT_WHITE, TFT_BLACK); myGLCD.drawString("* DCF77 (C) 2016 U.Klein", 4, 8, 1); pinMode(ledpin(dcf77_monitor_led), OUTPUT); pinMode(dcf77_sample_pin, dcf77_pin_mode); DCF77_Clock::setup(); DCF77_Clock::set_input_provider(sample_input_pin); // Placeholder date & time makeDummyDateTime(); dateTimeDisplay(dummy); // Wait till clock is synced, depending on the signal quality this may take // rather long. About 5 minutes with a good signal, 30 minutes or longer // with a bad signal for (uint8_t state = Clock::useless; state == Clock::useless || state == Clock::dirty; state = DCF77_Clock::get_clock_state()) { // wait for next sec Clock::time_t now; DCF77_Clock::get_current_time(now); // render one dot per second while initializing static uint8_t count = 0; myGLCD.drawString((count++ % 2) ? "|" : "-", 4, 8, 1); } myGLCD.drawString(" ", 4, 8, 1); } void loop() { Clock::time_t now; DCF77_Clock::get_current_time(now); Timezone::adjust(now, timezone_offset); dateTimeDisplay(now); }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #define INF 1000000000 #define REP(i,n) for(int i=0; i<n; i++) #define REP_R(i,n,m) for(int i=m; i<n; i++) #define MAX 50 using namespace std; int h,w; char grid[MAX + 5][MAX + 5]; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, -1, 0, 1}; bool flag = false; int cnt = 0; int main() { memset(grid, '.', sizeof(grid)); cin >> h >> w; for (int i=1; i<=h; i++) { for (int j=1; j<=w; j++) { cin >> grid[i][j]; } } for (int i=1; i<=h; i++) { for (int j=1; j<=w; j++) { if (grid[i][j] == '#') { if (grid[i-1][j] == '.' && grid[i][j-1] == '.' && grid[i+1][j] == '.' && grid[i][j+1] == '.') { printf("No\n"); return 0; } } } } printf("Yes\n"); return 0; }
#include <cassert> #include "PaletteRecords.h" #include <fstream> #include "StreamUtilities.h" using namespace std; using namespace OpenFlight; namespace { const int kNumberOfColorEntries = 1024; } //------------------------------------------------------------------------- //--- ColorPalette //------------------------------------------------------------------------- ColorPaletteRecord::ColorPaletteRecord(PrimaryRecord* ipParent) : AncillaryRecord(ipParent) { //there are 1024 entries in the palette mColors.resize(kNumberOfColorEntries); } //------------------------------------------------------------------------- bool ColorPaletteRecord::parseRecord(std::ifstream& iRawRecord, int iVersion) { std::streamoff startPos = iRawRecord.tellg(); Record::parseRecord(iRawRecord, iVersion); bool ok = true; // 132 is where the data starts, // iRawRecord.seekg(startPos + 132); //color format is a, b, g, r. for(int i = 0; i < kNumberOfColorEntries && ok; ++i) { uint32_t color; ok &= readUint32(iRawRecord, color); swapBytes4((void*)&color); //swap to have r g b a; mColors[i] = Color4ub(color); } // bool hasColorName = getRecordLength() > 4228; // read color name table // not implemented yet... // return ok; } //------------------------------------------------------------------------- // returns the Color4ub at index iIndex. This index is the index stored in the // other records. It appears the index must be divided by 128 to give the // proper index into the stored color vector... // Color4ub ColorPaletteRecord::getColor(int iIndex) const { Color4ub r; const int paletteIndex = iIndex / 128; if (paletteIndex >= 0 && paletteIndex < kNumberOfColorEntries) { r = mColors[paletteIndex]; } return r; } //------------------------------------------------------------------------- //--- LightSourcePaletteRecord //------------------------------------------------------------------------- LightSourcePaletteRecord::LightSourcePaletteRecord(PrimaryRecord* ipParent) : AncillaryRecord(ipParent) {} //------------------------------------------------------------------------------ const Color4f& LightSourcePaletteRecord::getAmbient() const { return mAmbient;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getConstantAttenuationCoefficient() const { return mConstantAttenuationCoefficient;} //------------------------------------------------------------------------------ const Color4f& LightSourcePaletteRecord::getDiffuse() const { return mDiffuse;} //------------------------------------------------------------------------------ int32_t LightSourcePaletteRecord::getIndex() const { return mIndex;} //------------------------------------------------------------------------------ LightSourcePaletteRecord::lightType LightSourcePaletteRecord::getLightType() const { return mLightType;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getLinearAttenuationCoefficient() const { return mLinearAttenuationCoefficient;} //------------------------------------------------------------------------------ std::string LightSourcePaletteRecord::getName() const { return mName;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getPitch() const { return mPitch;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getQuadraticAttenuationCoefficient() const { return mQuadraticAttenuationCoefficient;} //------------------------------------------------------------------------------ const Color4f& LightSourcePaletteRecord::getSpecular() const { return mSpecular;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getSpotCutoffAngle() const { return mSpotCutoffAngle;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getSpotExponentialDropoff() const { return mSpotExponentialDropoff;} //------------------------------------------------------------------------------ float LightSourcePaletteRecord::getYaw() const { return mYaw;} //------------------------------------------------------------------------------ bool LightSourcePaletteRecord::isModelingLight() const { return mIsModelingLight;} //------------------------------------------------------------------------- bool LightSourcePaletteRecord::parseRecord(std::ifstream& iRawRecord, int iVersion) { std::streamoff startPos = iRawRecord.tellg(); Record::parseRecord(iRawRecord, iVersion); bool ok = true; int32_t dummyInt32; ok &= readInt32(iRawRecord, mIndex); iRawRecord.seekg(startPos + 16); ok &= readChar(iRawRecord, 20, mName); iRawRecord.seekg(startPos + 40); ok &= readColor4f(iRawRecord, mAmbient); ok &= readColor4f(iRawRecord, mDiffuse); ok &= readColor4f(iRawRecord, mSpecular); ok &= readInt32(iRawRecord, dummyInt32); mLightType = (lightType)dummyInt32; iRawRecord.seekg(startPos + 132); ok &= readFloat32(iRawRecord, mSpotExponentialDropoff); ok &= readFloat32(iRawRecord, mSpotCutoffAngle); ok &= readFloat32(iRawRecord, mYaw); ok &= readFloat32(iRawRecord, mPitch); ok &= readFloat32(iRawRecord, mConstantAttenuationCoefficient); ok &= readFloat32(iRawRecord, mLinearAttenuationCoefficient); ok &= readFloat32(iRawRecord, mQuadraticAttenuationCoefficient); ok &= readInt32(iRawRecord, dummyInt32); mIsModelingLight = dummyInt32 == 0 ? false : true; return ok; } //------------------------------------------------------------------------- //--- MaterialPaletteRecord //------------------------------------------------------------------------- MaterialPaletteRecord::MaterialPaletteRecord(PrimaryRecord* ipParent) : AncillaryRecord(ipParent) {} //------------------------------------------------------------------------------ float MaterialPaletteRecord::getAlpha() const { return mAlpha;} //------------------------------------------------------------------------------ const Color3f& MaterialPaletteRecord::getAmbient() const { return mAmbient;} //------------------------------------------------------------------------------ const Color3f& MaterialPaletteRecord::getDiffuse() const { return mDiffuse;} //------------------------------------------------------------------------------ const Color3f& MaterialPaletteRecord::getEmissive() const { return mEmissive;} //------------------------------------------------------------------------------ int MaterialPaletteRecord::getFlags() const { return mFlags;} //------------------------------------------------------------------------------ int MaterialPaletteRecord::getIndex() const { return mIndex;} //------------------------------------------------------------------------------ std::string MaterialPaletteRecord::getName() const { return mName;} //------------------------------------------------------------------------------ float MaterialPaletteRecord::getShininess() const { return mShininess;} //------------------------------------------------------------------------------ const Color3f& MaterialPaletteRecord::getSpecular() const { return mSpecular;} //------------------------------------------------------------------------- bool MaterialPaletteRecord::parseRecord(std::ifstream& iRawRecord, int iVersion) { Record::parseRecord(iRawRecord, iVersion); bool ok = true; ok &= readInt32(iRawRecord, mIndex); ok &= readChar(iRawRecord, 12, mName); ok &= readInt32(iRawRecord, mFlags); ok &= readColor3f(iRawRecord, mAmbient); ok &= readColor3f(iRawRecord, mDiffuse); ok &= readColor3f(iRawRecord, mSpecular); ok &= readColor3f(iRawRecord, mEmissive); ok &= readFloat32(iRawRecord, mShininess); ok &= readFloat32(iRawRecord, mAlpha); return ok; } //------------------------------------------------------------------------- //--- VertexPaletteRecord //------------------------------------------------------------------------- VertexPaletteRecord::VertexPaletteRecord(PrimaryRecord* ipParent) : AncillaryRecord(ipParent), mOffset(8) { //As stated by the specification, the first vertex will be found //at offset 8. } //------------------------------------------------------------------------- bool VertexPaletteRecord::addVertexRawRecord(std::ifstream& iRawRecord) { bool ok = true; uint16_t dummyInt16; uint16_t recordLength = 0; ok &= readUint16(iRawRecord, dummyInt16); opCode oc = (opCode)dummyInt16; ok &= readUint16(iRawRecord, recordLength); if(ok) { Vertex v; ok &= readUint16(iRawRecord, v.mColorNameIndex); ok &= readUint16(iRawRecord, v.mFlags); ok &= readVector3d(iRawRecord, v.mCoordinate); uint32_t dummyUint32; switch (oc) { case ocVertexWithColor: { }break; case ocVertexWithColorAndNormal: { ok &= readVector3f(iRawRecord, v.mNormal); }break; case ocVertexWithColorNormalAndUv: { ok &= readVector3f(iRawRecord, v.mNormal); ok &= readVector2f(iRawRecord, v.mTextureCoordinate); }break; case ocVertexWithColorAndUv: { ok &= readVector2f(iRawRecord, v.mTextureCoordinate); }break; default: break; } // do not read color if the flags is set, since they are // undefined... if( !v.hasFlag(Vertex::fNoColor) ) { //packed color is in a,b,g,r and we want r,g,b,a ok &= readUint32(iRawRecord, dummyUint32); swapBytes4((void*) &dummyUint32); v.mPackedColor = Color4ub(dummyUint32); ok &= readUint32(iRawRecord, v.mColorIndex); } mOffsetToVertexIndex.insert( make_pair(mOffset, (int)mVertices.size() ) ); mOffset += recordLength; mVertices.push_back( v ); } return ok; } //------------------------------------------------------------------------- int VertexPaletteRecord::getIndexFromByteOffset(int iOffset) const { auto it = mOffsetToVertexIndex.find(iOffset); return it != mOffsetToVertexIndex.end() ? it->second : -1; } //------------------------------------------------------------------------- int VertexPaletteRecord::getNumberOfVertices() const { return (int)mVertices.size(); } //------------------------------------------------------------------------- const Vertex& VertexPaletteRecord::getVertex(int iIndex) const { assert(iIndex >= 0 && iIndex < mVertices.size()); return mVertices.at(iIndex); } //------------------------------------------------------------------------- const std::vector<Vertex>& VertexPaletteRecord::getVertices() const { return mVertices; } //------------------------------------------------------------------------- bool VertexPaletteRecord::parseRecord(std::ifstream& iRawRecord, int iVersion) { Record::parseRecord(iRawRecord, iVersion); bool ok = true; //since all vertex data are contained in the records following //the vertex palette, there is nothing to read here! //The vertex palette will be populated by the reader when //it encouters the actual vertex record. // it is possible to skip the whole vertex data by skipping // all the following records // // ocVertexWithColor: // ocVertexWithColorAndNormal: // ocVertexWithColorNormalAndUv: // ocVertexWithColorAndUv: // // return ok; }
// // Created by Алексей Ячменьков on 04.11.2020. // #include "Variable.h" double Symbol_table::get_value (string s) { for (int i = 0; i < var_table.size(); ++i) if (var_table[i].name == s) return var_table[i].value; error("ERROR: get: undefined name ", s); } void Symbol_table::print_values() { for (int i = 0; i < var_table.size(); ++i){ if (var_table[i].constant == 1) cout << "Constant "; cout << var_table[i].name << " = " << var_table[i].value << "\t"; if ((i !=0 )&&(i % 3 == 0)) cout << endl; } cout << endl; } void Symbol_table::set_value (string s, double d) { for (int i = 0; i <= var_table.size(); ++i) { if (var_table[i].name == s) { if (var_table[i].constant == false) { var_table[i].value = d; return; } error(s, "ERROR: - const"); } } error("ERROR: set: undefined name ", s); } bool Symbol_table::is_declared (string s) { for (int i = 0; i < var_table.size(); ++i) if (var_table[i].name == s) return true; return false; } double Symbol_table::define_name (string var, double val, bool con) { if (is_declared(var)) error(var, "ERROR: declared twice"); var_table.push_back (Variable{ var, val, con }); return val; }
#ifndef KOSARAJU_H #define KOSARAJU_H #include <queue> #include <stack> #include <string> #include <unordered_map> #include <vector> class KosarajuSCC { protected: int nb_nodes; // No. of vertices std::vector<std::vector<int> > outgoing; // node-> outgoing edges std::vector<std::vector<int> > ingoing; // node-> outgoing edgse std::vector<std::vector<int> > ends; // edge -> endnodes std::vector<int> scc; std::vector<std::vector<int> > sccs; std::vector<bool> is_mand; std::unordered_map<int, int> level2mandscc; std::unordered_map<int, int> mandscc2somenode; // Fills Stack with vertices (in increasing order of finishing // times). The top element of stack has the maximum finishing // time void fillOrder(int v, bool visited[], std::stack<int>& s); // A recursive function to print DFS starting from v void DFS(int v, bool visited[], int curr); std::vector<int> levels; public: KosarajuSCC(int v, std::vector<std::vector<int> > outgoing, std::vector<std::vector<int> > ingoing, std::vector<std::vector<int> > ends); virtual ~KosarajuSCC() {} virtual bool ignore_edge(int e) { return false; } virtual bool ignore_node(int n) { return false; } virtual bool mandatory_node(int n) { return false; } // The main function that finds and prints strongly connected // components void run(); inline int scc_of(int u) { return scc[u]; } inline std::vector<int> get_scc(int i) { return sccs[i]; } inline int nb_sccs() { return sccs.size(); } // Levels void _set_levels(int start, int sink); void topological_sort(int u, std::vector<std::vector<int> >& out, std::vector<std::vector<int> >& ends, std::queue<int>& sort, std::vector<bool>& seen); void _set_levels(int u, bool vis[], std::unordered_map<int, bool>& mscc, int parent = -1, std::string des = ""); void set_levels(int start, int sink); inline int level_of_scc(int scc) { return levels[scc]; } inline bool scc_mand(int scc) { return is_mand[scc]; } inline int mand_scc_level(int level) { return level2mandscc[level]; } inline int node_from_mandscc(int mandscc) { return mandscc2somenode[mandscc]; } }; #endif
// Выведите значение наименьшего из всех положительных элементов в массиве. Известно, что в массиве есть хотя бы один положительный элемент. // Формат входных данных // В первой строке вводится количество элементов в массиве. Во второй строке вводятся элементы массива. // Формат выходных данных // Выведите ответ на задачу. #include <iostream> #include <vector> using namespace std; int main() { //ввод int n; cin >> n; vector<int> a; //считывание for (int i = 0; i < n; i++) { int temp; cin >> temp; if (temp > 0) { a.push_back(temp); } } //обработка int min = a[0]; //мин элемент for (int i = 0; i < a.size(); i++) { if (a[i] < min) { min = a[i]; } } //вывод cout << min << endl; return 0; }
// Copyright Lionel Miele-Herndon 2020 #pragma once #include "CoreMinimal.h" #include "AIController.h" #include "ShooterAIController.generated.h" /** * */ UCLASS() class SHOOTERSTARTER_API AShooterAIController : public AAIController { GENERATED_BODY() protected: virtual void BeginPlay(); public: virtual void Tick(float DeltaSeconds) override; private: APawn* PlayerPawn; // UPROPERTY(EditAnywhere) // float AcceptanceRadius = 200; UPROPERTY(EditAnywhere) };
#include "video.h" #include <Windows.h> namespace img { Video::~Video() { vin.release(); vout.release(); } void Video::read(std::string vid) { vin.open(vid); if (!vin.isOpened()) { std::cout << "could not open the video" << std::endl; std::cin.get(); exit(1); } vout.open("videoout/outcpp.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 24, cv::Size(vin.get(cv::CAP_PROP_FRAME_WIDTH), vin.get(cv::CAP_PROP_FRAME_HEIGHT))); if (!vout.isOpened()) { std::cout << "could not open the writer" << std::endl; std::cin.get(); exit(1); } } void Video::detect_vehicle() { Image frame, root; //size_t qtd_frames = static_cast<size_t>(vin.get(cv::CAP_PROP_FRAME_COUNT)); //cv::Mat* frames = new cv::Mat[qtd_frames]; //int count = 0; std::vector<cv::Mat> frames; root.read("videoin/vframe0.png"); std::cout << "creating treshold" << std::endl; while(1) { vin >> frame.str; if (frame.str.empty()) break; vout.write(make_treshold(frame, root).str); //cv::imshow("aloo", make_treshold(frame, root).str); //cv::waitKey(0); //cv::destroyWindow("aloo"); //frames.push_back(make_treshold(frame, root).str); } std::cout << "DONE!" << std::endl; //for (int i = 0; i < frames.size(); i++) //{ // vout.write(frames[i]); //} } }
// Created on: 2016-07-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // 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 _BRepMesh_Classifier_HeaderFile #define _BRepMesh_Classifier_HeaderFile #include <IMeshData_Types.hxx> #include <NCollection_Handle.hxx> #include <memory> class gp_Pnt2d; class CSLib_Class2d; //! Auxiliary class intended for classification of points //! regarding internals of discrete face. class BRepMesh_Classifier : public Standard_Transient { public: //! Constructor. Standard_EXPORT BRepMesh_Classifier(); //! Destructor. Standard_EXPORT virtual ~BRepMesh_Classifier(); //! Performs classification of the given point regarding to face internals. //! @param thePoint Point in parametric space to be classified. //! @return TopAbs_IN if point lies within face boundaries and TopAbs_OUT elsewhere. Standard_EXPORT TopAbs_State Perform(const gp_Pnt2d& thePoint) const; //! Registers wire specified by sequence of points for //! further classification of points. //! @param theWire Wire to be registered. Specified by sequence of points. //! @param theTolUV Tolerance to be used for calculations in parametric space. //! @param theUmin Lower U boundary of the face in parametric space. //! @param theUmax Upper U boundary of the face in parametric space. //! @param theVmin Lower V boundary of the face in parametric space. //! @param theVmax Upper V boundary of the face in parametric space. Standard_EXPORT void RegisterWire( const NCollection_Sequence<const gp_Pnt2d*>& theWire, const std::pair<Standard_Real, Standard_Real>& theTolUV, const std::pair<Standard_Real, Standard_Real>& theRangeU, const std::pair<Standard_Real, Standard_Real>& theRangeV); DEFINE_STANDARD_RTTIEXT(BRepMesh_Classifier, Standard_Transient) private: NCollection_Vector<NCollection_Handle<CSLib_Class2d> > myTabClass; IMeshData::VectorOfBoolean myTabOrient; }; #endif
#include <Wire.h> #include <WiFiNINA.h> #include <WiFiUdp.h> #include <OSCMessage.h> #include <OSCBundle.h> /////////////// // OSC STUFF // /////////////// int status = WL_IDLE_STATUS; #include "arduino_secrets.h" ///////please enter your sensitive data in the Secret tab/arduino_secrets.h char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) WiFiUDP Udp; const IPAddress outIp(192, 168, 1, 131); // remote IP of your computer //const IPAddress outIp(10, 244, 254, 25); // remote IP of your computer unsigned int localPort = 2390; // local port to listen on const unsigned int outPort = 8001; // remote port to receive OSC void setup() { Serial.begin(115200); // check for the WiFi module: if (WiFi.status() == WL_NO_MODULE) { Serial.println("Communication with WiFi module failed!"); // don't continue while (true); } String fv = WiFi.firmwareVersion(); if (fv < "1.0.0") { Serial.println("Please upgrade the firmware"); } // attempt to connect to Wifi network: while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } Serial.println("Connected to wifi"); printWifiStatus(); Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: Udp.begin(localPort); } void loop() { OSCMessage msg("/bass"); // // msg.add(axOsc); // msg.add(ayOsc); msg.add("hi"); Udp.beginPacket(outIp, outPort); msg.send(Udp); // accelBndl.send(Udp); // send the bytes to the SLIP stream Udp.endPacket(); // mark the end of the OSC Packet // //accelBndl.empty(); // empty the bundle to free room for a new one msg.empty(); // Serial.print("Gyro X: "); Serial.print(g.gyro.x); Serial.print(" dps"); // Serial.print("\tY: "); Serial.print(g.gyro.y); Serial.print(" dps"); // Serial.print("\tZ: "); Serial.print(g.gyro.z); Serial.println(" dps"); Serial.println("Looping"); delay(1000); } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }
#include <bits/stdc++.h> using namespace std; const int maxn = 1010; int n, a[maxn][maxn], f[maxn][maxn]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) scanf("%d", &a[i][j]); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) f[i][j] = a[i][j] + max(f[i - 1][j], f[i - 1][j - 1]); } int ans = -1; for (int i = 1; i <= n; i++) ans = max(ans, f[n][i]); printf("%d\n", ans); return 0; }
#ifndef _GetServerInfoProc_H #define _GetServerInfoProc_H #include "CDLSocketHandler.h" #include "IProcess.h" class GetServerInfoProc :public IProcess { public: GetServerInfoProc(); virtual ~GetServerInfoProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt) ; }; #endif
#include <arm.h> #include <Arduino.h> #include <constants.h> #include <Servo.h> /* Arm.cpp contains all functions related to moving the arm including collection, dispensing, and other movement. */ //This is so you dont have to write constants:: every time you want to use it. //Its not really good practice but its ok :P using namespace constants; //Motor Objects Servo clawOpenServo; Servo clawRotateServo; /* * Constructer for the arm object. SPI1 and SPI2 are the pointers to our limit switch data */ arm::arm(uint8_t *SPI1, uint8_t *SPI2) { SPIdata1 = SPI1; SPIdata2 = SPI2; liftPosition = 0; sliderPosition = 0; armPosition = 0; clawOpenServo.attach(CLAW_OPEN_PIN); clawRotateServo.attach(CLAW_ROTATE_PIN); clawOpenServo.write(CLAW_OPEN_DEG); clawRotateServo.write(45); } /* * Homes the larger components of the arm: the slider,lower the lifts and rotates it CW to home. * Home is defined as the claw as being at the bottom of the lift, the slider retracted fully, and the arm rotated forwards */ void arm::homeArm(void) { homeSlider(); homeClaw(); homeRotateArm(); } /* * Extends the slider and lifts the claw/lift */ void arm::extendArm(void) { raiseClaw(); extendSlider(); } /* * Sleeps all the stepper motors of the arm */ void arm::sleepArm(void) { digitalWrite(ARM_SLEEP,LOW); digitalWrite(SLIDER_SLEEP,LOW); digitalWrite(LIFT_SLEEP,LOW); } /* * Wakes up all the stepper motors of the arm */ void arm::wakeupArm(void) { digitalWrite(ARM_SLEEP,HIGH); digitalWrite(SLIDER_SLEEP,HIGH); digitalWrite(LIFT_SLEEP,HIGH); } /* * Moves the lift to a desired position * Parameters: position (0- idk) */ void arm::moveLift(int position) { if(position > liftPosition) { digitalWrite(LIFT_DIR,UP); } else { digitalWrite(LIFT_DIR,DOWN); } for(int i = 0; i < abs(position - liftPosition); i++) { digitalWrite(LIFT_STEP,HIGH); delayMicroseconds(800); digitalWrite(LIFT_STEP,LOW); delayMicroseconds(800); } liftPosition = position; } /* * Moves the slider to a desired position * Parameters: position (0-idk) */ void arm::moveSlider(int position) { if(position > sliderPosition) { digitalWrite(SLIDER_DIR,FORWARDS); } else { digitalWrite(SLIDER_DIR,BACKWARDS); } for(int i = 0; i < abs(position - sliderPosition); i++) { digitalWrite(SLIDER_STEP,HIGH); delay(1); digitalWrite(SLIDER_STEP,LOW); delay(1); } liftPosition = position; sliderPosition = position; } /* * Moves the arm to a desired position * Parameters: position (-idk,idk) */ void arm::moveArm(int position) { if(position > armPosition) { digitalWrite(ARM_DIR,CW); } else { digitalWrite(ARM_DIR,CCW); } for(int i = 0; i < abs(position - armPosition); i++) { digitalWrite(ARM_STEP,HIGH); delay(2); digitalWrite(ARM_STEP,LOW); delay(2); } armPosition = position; } /* * Dispenses all the stones into the gauntlet once already lined up */ void arm::dispenseStones(void) { digitalWrite(DISPENSER,HIGH); } /* * Collects a stone and places it into the dispenser once the robot has parked beside it * Parameters: stoneNumber is the number of stones already stored (0-3) */ void arm::collectStone(int stoneNumber) { homeArm(); clawRotateServo.write(CLAW_COLLECT_DEG); extendSlider(); poleRotateArm(); Serial.println(armPosition); retractSlider(); Serial.println(sliderPosition); openClaw(); delay(400); lowerClaw(); delay(400); Serial.println(liftPosition); closeClaw(); delay(400); moveLift(LIFT_TOP_POSITION); extendSlider(); moveArm(ARM_FRONT_POSITION); homeSlider(); clawRotateServo.write(0); } /* * Stores stone from claw to a spot on the flipper. * Parameters: stoneNumber is the number of stones already stored (0-3) */ void arm::storeStone(int stoneNumber) { switch(stoneNumber){ case 0: moveArm(ARM_STONE0); moveSlider(SLIDER_STONE0); clawRotateServo.write(CLAW_STONE0); break; case 1: moveArm(ARM_STONE1); moveSlider(SLIDER_STONE1); clawRotateServo.write(CLAW_STONE1); break; case 2: moveArm(ARM_STONE2); moveSlider(SLIDER_STONE2); clawRotateServo.write(CLAW_STONE2); break; case 3: moveArm(ARM_STONE3); moveSlider(SLIDER_STONE3); clawRotateServo.write(CLAW_STONE3); break; } moveLift(150); delay(300); openClaw(); } /* * Raises the claw to the highest position */ void arm::raiseClaw(void) { moveLift(LIFT_TOP_POSITION); liftPosition = LIFT_TOP_POSITION; } /* * Lowers the claw until it hits a pole or hits the bottom */ void arm::lowerClaw(void) { digitalWrite(LIFT_DIR,DOWN); while((!(((*SPIdata1) & ((int)pow(2,CLAW_COLLIDE_BIT))))) && ((!(((*SPIdata1) & ((int)pow(2,LIFT_BOT_BIT))))))) { digitalWrite(LIFT_STEP,HIGH); delayMicroseconds(800); digitalWrite(LIFT_STEP,LOW); delayMicroseconds(800); liftPosition -= 1; } } /* * Lowers the claw to the lowest point */ void arm::homeClaw(void) { openClaw(); clawRotateServo.write(CLAW_ROTATE_HOME); digitalWrite(LIFT_DIR,DOWN); while(!(((*SPIdata1) & ((int)pow(2,LIFT_BOT_BIT))))) { digitalWrite(LIFT_STEP,HIGH); delayMicroseconds(800); digitalWrite(LIFT_STEP,LOW); delayMicroseconds(800); } liftPosition = 0; delay(600); digitalWrite(LIFT_DIR,UP); for(int i = 0; i < LIFT_TOP_POSITION;i++) { digitalWrite(LIFT_STEP,HIGH); delayMicroseconds(800); digitalWrite(LIFT_STEP,LOW); delayMicroseconds(800); } liftPosition = LIFT_TOP_POSITION; } /* * Opens the claw */ void arm::openClaw(){ clawOpenServo.write(CLAW_OPEN_DEG); } /* * Closes the claw */ void arm::closeClaw(){ clawOpenServo.write(CLAW_CLOSE_DEG); } /* * Extends the slider of the arm fully */ void arm::extendSlider(void) { moveSlider(SLIDER_FRONT_POSITION); sliderPosition = SLIDER_FRONT_POSITION; } /* * Retracts the slider of the arm fully */ void arm::homeSlider(void){ digitalWrite(SLIDER_DIR,BACKWARDS); while(!(((*SPIdata1) & ((int)pow(2,SLIDER_BACK_BIT))))){ digitalWrite(SLIDER_STEP,HIGH); delay(1); digitalWrite(SLIDER_STEP,LOW); delay(1); } digitalWrite(SLIDER_STEP,LOW); sliderPosition = 0; } /* * Retracts the slider until it collides with a pole or comes home */ void arm::retractSlider(void){ digitalWrite(SLIDER_DIR,BACKWARDS); while((!(((*SPIdata1) & ((int)pow(2,SLIDER_BACK_BIT))))) && (!(((*SPIdata1) & ((int)pow(2,HOOK_COLLIDE_BIT)))))) { digitalWrite(SLIDER_STEP,HIGH); delay(1); digitalWrite(SLIDER_STEP,LOW); delay(1); sliderPosition--; } } /* * Rotates the arm to it's home position. * Parameters: direction: true for CW / false for CCW */ void arm::homeRotateArm(void){ digitalWrite(ARM_DIR,CCW); while(!(((*SPIdata1) & (ARM_HOME_BIT)))) { digitalWrite(ARM_STEP,HIGH); delay(2); digitalWrite(ARM_STEP,LOW); delay(2); } digitalWrite(ARM_STEP,LOW); delay(500); armPosition = 0; moveArm(ARM_FRONT_POSITION); } /* * Rotates the arm until it either collides with a pole or reaches home */ void arm::poleRotateArm(void) { digitalWrite(ARM_DIR,CCW); while(!((*SPIdata1) & (ARM_HOME_BIT))) { digitalWrite(ARM_STEP,HIGH); delay(2); digitalWrite(ARM_STEP,LOW); delay(2); armPosition -= 1; } } int arm::getLiftPosition(void) { return liftPosition; } int arm::getSliderPosition(void) { return sliderPosition; } int arm::getArmPosition(void) { return armPosition; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * */ #include "core/pch.h" #include "modules/forms/src/formsubmitter.h" #include "modules/forms/src/formiterator.h" #include "modules/forms/form.h" #include "modules/forms/formsenum.h" #include "modules/forms/webforms2support.h" #ifdef FORMS_KEYGEN_SUPPORT # include "modules/forms/formvaluekeygen.h" # include "modules/libssl/sslv3.h" # include "modules/libssl/ssl_api.h" # include "modules/libssl/keygen_tracker.h" # include "modules/libssl/sslopt.h" # include "modules/windowcommander/src/SSLSecurtityPasswordCallbackImpl.h" #endif // FORMS_KEYGEN_SUPPORT #include "modules/logdoc/htm_elm.h" #include "modules/logdoc/logdoc_util.h" // GetCurrentBaseTarget #include "modules/doc/frm_doc.h" #include "modules/dochand/win.h" #include "modules/dom/domutils.h" #include "modules/ecmascript_utils/essched.h" #include "modules/ecmascript_utils/esterm.h" FormSubmitter::FormSubmitter(FramesDocument* frames_doc, HTML_Element* form_element, HTML_Element* submit_element, int offset_x, int offset_y, ES_Thread* thread, BOOL triggered_by_script, ShiftKeyState modifiers) : m_frames_doc(frames_doc), m_form_element(form_element), m_submit_element(submit_element), m_offset_x(offset_x), m_offset_y(offset_y), m_thread(thread), m_triggered_by_script(triggered_by_script), m_modifiers(modifiers), m_has_protected(FALSE) #ifdef FORMS_KEYGEN_SUPPORT , m_has_started_key_generation(FALSE) , m_next(NULL) , m_blocking_keygenerator_count(0) , m_keygenerator_aborted(FALSE) , m_keygen_generators(NULL) , m_mh(NULL) #endif // FORMS_KEYGEN_SUPPORT { OP_ASSERT(frames_doc); OP_ASSERT(form_element); OP_ASSERT(form_element->IsMatchingType(HE_FORM, NS_HTML) || form_element->IsMatchingType(HE_ISINDEX, NS_HTML)); } OP_STATUS FormSubmitter::ProtectHTMLElements(BOOL protect) { OP_ASSERT(!protect || !m_has_protected); OP_ASSERT(protect || m_has_protected); DOM_Object* form_node; DOM_Object* submit_node = NULL; DOM_Environment* env = m_frames_doc->GetDOMEnvironment(); #ifdef FORMS_KEYGEN_SUPPORT if (!env) { // Create an environment to protect our elements. This is very expensive // but compared to creating a key, extremely cheap. if (OpStatus::IsError(m_frames_doc->ConstructDOMEnvironment())) { // Couldn't create a dom environment so nothing protects the elements // from being deleted, except that if we have no dom environment // and thus no scripts, it isn't that easy for someone to delete // them. // FIXME: Create a permanent protection of the elements, not based // on DOM return OpStatus::OK; // Will keep going with the keygen without protection } env = m_frames_doc->GetDOMEnvironment(); } #else // Can only come here to handle ONINVALID events in DOM and therefore we know that // we have an environment. #endif // FORMS_KEYGEN_SUPPORT OP_ASSERT(env); // This isn't called unless DOM is involved if (OpStatus::IsError(env->ConstructNode(form_node, m_form_element)) || m_submit_element && OpStatus::IsError(env->ConstructNode(submit_node, m_submit_element))) { return OpStatus::ERR_NO_MEMORY; } ES_Object* form_obj = DOM_Utils::GetES_Object(form_node); ES_Object* submit_obj = submit_node ? DOM_Utils::GetES_Object(submit_node) : NULL; if (protect) { if (!env->GetRuntime()->Protect(form_obj)) { return OpStatus::ERR_NO_MEMORY; } if (submit_obj && !env->GetRuntime()->Protect(submit_obj)) { env->GetRuntime()->Unprotect(form_obj); return OpStatus::ERR_NO_MEMORY; } m_has_protected = TRUE; } else { env->GetRuntime()->Unprotect(form_obj); if (submit_obj) { env->GetRuntime()->Unprotect(submit_obj); } } return OpStatus::OK; } OP_STATUS FormSubmitter::Submit() { ES_ThreadScheduler* scheduler = m_frames_doc->GetESScheduler(); /* Pretty ugly hack to not submit a form if the current document has been replaced using document.write. (jl@opera.com) */ if (scheduler && !scheduler->TestTerminatingAction(ES_OpenURLAction::FINAL, ES_OpenURLAction::CONDITIONAL)) { return OpStatus::ERR; } if (m_frames_doc->IsRestoringFormState(m_thread)) { /* We really do not want this to submit the form as a side-effect. */ return OpStatus::ERR; } m_frames_doc->SignalFormChangeSideEffect(m_thread); #ifdef _WML_SUPPORT_ if (m_frames_doc->GetHLDocProfile() && m_frames_doc->GetHLDocProfile()->HasWmlContent() && !FormManager::ValidateWMLForm(m_frames_doc)) { return OpStatus::OK; // Abort submit } #endif // _WML_SUPPORT_ return SubmitFormStage2(); } #ifdef FORMS_KEYGEN_SUPPORT BOOL FormSubmitter::StartKeyGeneration() { FormIterator iterator(m_frames_doc, m_form_element); BOOL need_to_block = FALSE; while (HTML_Element* control = iterator.GetNext()) { if (control->IsMatchingType(HE_KEYGEN, NS_HTML)) { FormValueKeyGen* keygen_value; keygen_value = FormValueKeyGen::GetAs(control->GetFormValue()); unsigned int keygen_size; keygen_size = keygen_value->GetSelectedKeySize(control); if (keygen_size > 0) { const uni_char* request_type = control->GetStringAttr(ATTR_TYPE); SSL_Certificate_Request_Format format = SSL_Netscape_SPKAC; // default if(request_type && uni_stri_eq(request_type, "PKCS10")) { format = SSL_PKCS10; } OpString8 challenge8; // truncate challenge to ascii if (OpStatus::IsSuccess(challenge8.Set(control->GetStringAttr(ATTR_CHALLENGE)))) { if (!m_mh) { m_mh = OP_NEW(FormSubmitterMessageHandler, (this, m_frames_doc->GetWindow())); if (!m_mh || OpStatus::IsError(m_mh->SetCallBack(this, MSG_FORMS_KEYGEN_FINISHED, 0))) { OP_DELETE(m_mh); m_mh = NULL; // return OpStatus::ERR_NO_MEMORY return FALSE; } } if (!m_keygen_generators) { m_keygen_generators = OP_NEW(OpVector<SSL_Private_Key_Generator>, ()); if (!m_keygen_generators) { // return OpStatus::ERR_NO_MEMORY return FALSE; } } OpWindow* op_win = const_cast<OpWindow*>(m_frames_doc->GetWindow()->GetOpWindow()); OP_ASSERT(m_mh); OP_ASSERT(m_keygen_generators); URL empty_url; SSL_dialog_config dialog_config(op_win, m_mh, MSG_FORMS_KEYGEN_FINISHED, 0, empty_url); URL* action_url_p = m_form_element->GetUrlAttr(ATTR_ACTION, NS_IDX_HTML, m_frames_doc->GetLogicalDocument()); URL action_url; if (action_url_p) { action_url = *action_url_p; } SSL_Options* ssl_options = NULL; SSL_BulkCipherType bulk_cipher_type = SSL_RSA; // Not certain SSL_Private_Key_Generator* keygen_generator = g_ssl_api->CreatePrivateKeyGenerator(dialog_config, action_url, format, bulk_cipher_type, challenge8, keygen_size, ssl_options); if (!keygen_generator || OpStatus::IsError(m_keygen_generators->Add(keygen_generator))) { OP_DELETE(keygen_generator); // return OpStatus::ERR_NO_MEMORY; return FALSE; } OP_STATUS status = keygen_generator->StartKeyGeneration(); if (status == InstallerStatus::KEYGEN_FINISHED) { // Take the value and replace the generator with NULL to indicate that we // have already taken the value keygen_value->SetGeneratedKey(keygen_generator->GetSPKIString().CStr()); m_keygen_generators->Replace(m_keygen_generators->GetCount()-1, NULL); OP_DELETE(keygen_generator); } else { m_blocking_keygenerator_count++; need_to_block = TRUE; } } } } } if (need_to_block) { /** * Fix for bug CORE-15735. * * We're not really blocking for keygen in any case, but it would crash * when keygen finally finished a long time later and the thread had * terminated. * So set thread to NULL. It makes Opera think the submit was not * script-initiated, so some side effects may be experienced. */ m_thread = NULL; FormSubmitter* stored_submitter = OP_NEW(FormSubmitter, (*this)); if (!stored_submitter) { // return OpStatus::ERR_NO_MEMORY; return FALSE; } #ifdef _DEBUG int debug_submit_count_before = 0; FormSubmitter* debug_it = g_opera->forms_module.m_submits_in_progress; while (debug_it) { debug_submit_count_before++; debug_it = debug_it->m_next; } #endif // _DEBUG FormSubmitter** last = &g_opera->forms_module.m_submits_in_progress; while (*last) { last = &(*last)->m_next; } OP_ASSERT(!*last); *last = stored_submitter; #ifdef _DEBUG OP_ASSERT(g_opera->forms_module.m_submits_in_progress); int debug_submit_count_after = 0; debug_it = g_opera->forms_module.m_submits_in_progress; while (debug_it) { debug_submit_count_after++; debug_it = debug_it->m_next; } OP_ASSERT(debug_submit_count_after = debug_submit_count_before+1); #endif // _DEBUG if (!m_has_protected) { OP_STATUS status = stored_submitter->ProtectHTMLElements(TRUE); if (OpStatus::IsError(status)) { // Couldn't protect elements, so we have to give up OP_DELETE(stored_submitter); return FALSE; } } } return need_to_block; } #endif // FORMS_KEYGEN_SUPPORT OP_STATUS FormSubmitter::SubmitFormStage2() { #ifdef WAND_SUPPORT // Hack to avoid wand appear 2 times when several things submits // the form. (Which is a bug itself but almost impossible to // avoid) m_frames_doc->SetWandSubmitting(TRUE); #endif // WAND_SUPPORT #ifdef FORMS_KEYGEN_SUPPORT // Now check if we have to generate any keys if (!m_has_started_key_generation) { m_has_started_key_generation = TRUE; if (StartKeyGeneration()) { // There were keygen tags and now we have to wait for them to be // processed. A FormSubmitter object is registered and protected // and we just need to wait for the callback. return OpStatus::OK; } } #endif // FORMS_KEYGEN_SUPPORT const URL& url = m_frames_doc->GetURL(); Form form(url, m_form_element, m_submit_element, m_offset_x, m_offset_y); OP_STATUS status = OpStatus::OK; URL form_url = form.GetURL(m_frames_doc, status); RETURN_IF_MEMORY_ERROR(status); BOOL shift_pressed = (m_modifiers & SHIFTKEY_SHIFT) != 0; BOOL control_pressed = (m_modifiers & SHIFTKEY_CTRL) != 0; if (!m_triggered_by_script) { m_thread = NULL; } const uni_char* win_name; // First look at the submit button target, fallback on the form // |target| is the event target, not the submit target win_name = m_submit_element ? m_submit_element->GetStringAttr(ATTR_FORMTARGET) : NULL; if (!win_name || !*win_name) { win_name = m_form_element->GetTarget(); // form target if (!win_name || !*win_name) { // Global method in doc_util.cpp win_name = GetCurrentBaseTarget(m_form_element); } } return status = m_frames_doc->MouseOverURL(form_url, win_name, ONSUBMIT, shift_pressed, control_pressed, m_thread, NULL); } // Used by FormManager::Submit when we decide that we need a heap allocated FormSubmitter FormSubmitter::FormSubmitter(FormSubmitter& other) : #ifdef FORMS_KEYGEN_SUPPORT MessageObject(), #endif // FORMS_KEYGEN_SUPPORT m_frames_doc(other.m_frames_doc), m_form_element(other.m_form_element), m_submit_element(other.m_submit_element), m_offset_x(other.m_offset_x), m_offset_y(other.m_offset_y), m_thread(other.m_thread), m_triggered_by_script(other.m_triggered_by_script), m_modifiers(other.m_modifiers), m_has_protected(FALSE) #ifdef FORMS_KEYGEN_SUPPORT , m_has_started_key_generation(other.m_has_started_key_generation) , m_next(NULL) , m_blocking_keygenerator_count(other.m_blocking_keygenerator_count) , m_keygenerator_aborted(other.m_keygenerator_aborted) , m_keygen_generators(other.m_keygen_generators) , m_mh(other.m_mh) #endif // FORMS_KEYGEN_SUPPORT { #ifdef FORMS_KEYGEN_SUPPORT OP_ASSERT(!other.m_next); // Can only steal free FormSubmitters and this is a simple check // Steal the other messagehandler other.m_keygen_generators = NULL; if (m_mh) { // move callback m_mh->RemoveCallBacks(&other, 0); // This shouldn't be able to fail since we just replace one pointer with another // but we should still write this more robust in case the MessageHandler implementation // changes and for instance deallocates stuff in the RemoveCallbacks call. OP_STATUS status = m_mh->SetCallBack(this, MSG_FORMS_KEYGEN_FINISHED, 0); OP_ASSERT(OpStatus::IsSuccess(status)); OpStatus::Ignore(status); other.m_mh = NULL; } other.m_blocking_keygenerator_count = 0; #endif // FORMS_KEYGEN_SUPPORT } void FormSubmitter::Abort() { if (m_has_protected) { OpStatus::Ignore(ProtectHTMLElements(FALSE)); m_has_protected = FALSE; } m_frames_doc = NULL; } #ifdef FORMS_KEYGEN_SUPPORT /* virtual */ void FormSubmitter::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { OP_ASSERT(msg == MSG_FORMS_KEYGEN_FINISHED); OP_ASSERT(par1 == 0); OP_ASSERT(par2 == 0 || par2 == 1); OP_ASSERT(m_blocking_keygenerator_count > 0); BOOL completed_successfully = !!par2; if (!completed_successfully || !m_frames_doc /* FormSubmitter::Abort() called */) { m_keygenerator_aborted = TRUE; } m_blocking_keygenerator_count--; if (m_blocking_keygenerator_count == 0) { // Let it go on. // Unhook from the global list #ifdef _DEBUG FormSubmitter* check_list = g_opera->forms_module.m_submits_in_progress; int debug_submit_count_before = 0; BOOL found_it = FALSE; while (check_list) { if (check_list == this) { OP_ASSERT(!found_it); found_it = TRUE; } debug_submit_count_before++; check_list = check_list->m_next; } OP_ASSERT(found_it); #endif // _DEBUG FormSubmitter** submitter_ptr = &g_opera->forms_module.m_submits_in_progress; while (*submitter_ptr != this) { submitter_ptr = &(*submitter_ptr)->m_next; } // Unhook *submitter_ptr = (*submitter_ptr)->m_next; #ifdef _DEBUG check_list = g_opera->forms_module.m_submits_in_progress; int debug_submit_count_after = 0; while (check_list) { OP_ASSERT(check_list != this); debug_submit_count_after++; check_list = check_list->m_next; } OP_ASSERT(debug_submit_count_after+1 == debug_submit_count_before); #endif // _DEBUG // Unhooked, so lets insert all the generated values into the FormValueKeygen objects if (!m_keygenerator_aborted) { FormIterator iterator(m_frames_doc, m_form_element); unsigned keygen_index = 0; while (HTML_Element* control = iterator.GetNext()) { if (control->IsMatchingType(HE_KEYGEN, NS_HTML)) { FormValueKeyGen* keygen_value; keygen_value = FormValueKeyGen::GetAs(control->GetFormValue()); unsigned int keygen_size; keygen_size = keygen_value->GetSelectedKeySize(control); if (keygen_size > 0) { keygen_index++; if (!m_keygen_generators || m_keygen_generators->GetCount() < keygen_index) { // ouch, we're missing parts. OOM? Someone tampered with the key size choices? } else { SSL_Private_Key_Generator* key_generator = m_keygen_generators->Get(keygen_index-1); if (key_generator) // NULL key generator means that we got the key directly for this HE_KEYGEN { keygen_value->SetGeneratedKey(key_generator->GetSPKIString().CStr()); } } } } } // Let the submit proceed SubmitFormStage2(); } OP_DELETE(this); } // Don't add code here. This object is likely deleted. } #endif // FORMS_KEYGEN_SUPPORT FormSubmitter::~FormSubmitter() { if (m_has_protected) { OpStatus::Ignore(ProtectHTMLElements(FALSE)); } #ifdef FORMS_KEYGEN_SUPPORT if (m_keygen_generators) { m_keygen_generators->DeleteAll(); OP_DELETE(m_keygen_generators); } OP_DELETE(m_mh); #endif // defined FORMS_KEYGEN_SUPPORT } #ifdef ALLOW_TOO_LONG_FORM_VALUES /* static */ BOOL FormSubmitter::HandleTooLongValue(FramesDocument* frames_doc, ValidationResult val_res) { val_res.ClearError(VALIDATE_ERROR_TOO_LONG); if (val_res.IsOk()) { #ifdef OPERA_CONSOLE // Since we break against the specification to keep // bad pages working, we'll log an error so that // the authors can be made aware that their // pages aren't completely ok. This shouldn't // catch user errors since maxlength is enforced // by the widget by not letting the user insert more // text than maxlength. frames_doc->EmitError(UNI_L("Form had field with violated maxlength property. Submitted anyway for compatibility reasons."), NULL); #endif // OPERA_CONSOLE return TRUE; } return FALSE; } #endif // ALLOW_TOO_LONG_FORM_VALUES
/* vi: set et sw=4 ts=4 cino=t0,(0: */ /* * Copyright (C) 2012 Alberto Mardegan <info@mardy.it> * * This file is part of minusphoto. * * minusphoto 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. * * minusphoto 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 minusphoto. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MINUSPHOTO_SIZE_CONTROLLER_H #define MINUSPHOTO_SIZE_CONTROLLER_H #include <QObject> #include <QSize> #include <QUrl> namespace Minusphoto { class SizeControllerPrivate; class SizeController: public QObject { Q_OBJECT Q_PROPERTY(qreal zoom READ zoom WRITE setZoom NOTIFY zoomChanged); Q_PROPERTY(QObject *image READ image WRITE setImage); Q_PROPERTY(QUrl source READ source WRITE setSource); Q_PROPERTY(QSize viewSize READ viewSize WRITE setViewSize); Q_PROPERTY(QString mode READ mode WRITE setMode); public: explicit SizeController(QObject *parent = 0); virtual ~SizeController(); void setZoom(qreal zoom); qreal zoom() const; void setImage(QObject *image); QObject *image() const; void setSource(const QUrl &source); QUrl source() const; void setViewSize(const QSize &size); QSize viewSize() const; void setMode(const QString &mode); QString mode() const; Q_SIGNALS: void zoomChanged(); private: SizeControllerPrivate *d_ptr; Q_DECLARE_PRIVATE(SizeController) }; }; // namespace #endif // MINUSPHOTO_SIZE_CONTROLLER_H
#include <SeetyDog.h> #include "ImGui/imgui.h" //#include "Platform/OpenGL/OpenGLTriangleLayer.h" #include "Breakout/BreakoutLayer.h" class ExampleLayer : public SeetyDog::Layer { public: ExampleLayer() : Layer("Example") { } void OnUpdate() override { //./if (SeetyDog::Input::IsKeyPressed(SD_KEY_TAB)) { //./ SD_INFO("Tab key was press by you (Polled Event - OnUpdate())"); //./} } virtual void OnAttach() override { IMGUI_CHECKVERSION(); ImGui::CreateContext(); //ImGuiIO& io = ImGui::GetIO(); (void)io; ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; } virtual void OnImGuiRender() override { //ImGui::Begin("Test"); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration."); ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or "); ImGui::SameLine(0.0f, 0.0f); if (ImGui::SmallButton("click here")) ImGui::Text("Lol you clicked the button!"); ImGui::Text("Hello World"); //ImGui::End(); } void OnEvent(SeetyDog::Event& event) override { //./if (event.GetEventType() == SeetyDog::EventType::KeyPressed) { //./ SeetyDog::KeyPressedEvent& e = (SeetyDog::KeyPressedEvent&)event; //./ SD_TRACE("{0}", (char)e.GetKeyCode()); //./ if (SeetyDog::Input::IsKeyPressed(SD_KEY_TAB)) { //./ SD_INFO("Tab key was press by you (Natural Event - OnEvent())"); //./ } //./} } }; class DogPark : public SeetyDog::Application { public: DogPark() { //./ PushLayer(new ExampleLayer()); //./PushLayer(new SeetyDog::OpenGLTriangleLayer()); PushLayer(new BreakoutLayer()); } ~DogPark() {} }; SeetyDog::Application* SeetyDog::CreateApplication() { return new DogPark(); }
#include "Deck56.hpp" Deck56::Deck56() :Deck52(){ //{ As 2 3 4 5 6 7 8 9 10 Valet Cavalier Dame Roi } * { Coeur Carreaux Trèfle Pique } const Card CavalierCoeur = Card (0,12); const Card CavalierCarreaux = Card (1,12); const Card CavalierTrefile = Card (2,12); const Card CavalierPique = Card (3,12); (*this)+=CavalierCoeur+CavalierCarreaux+CavalierTrefile+CavalierPique; }
#include "Utils.h" int GetProcessByName(PCSTR name) { DWORD pid = 0; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 process; ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(process); if (Process32First(snapshot, &process)) { do { if (std::string(process.szExeFile) == std::string(name)) { pid = process.th32ProcessID; break; } } while (Process32Next(snapshot, &process)); } CloseHandle(snapshot); if (pid != 0) return pid; return 0; } LPSTR GetPathOfExe() { char filename[MAX_PATH]; DWORD result = ::GetModuleFileName( nullptr, (LPSTR)filename, _countof(filename) ); return filename; } bool IsRunAsAdministrator() { BOOL fIsRunAsAdmin = FALSE; DWORD dwError = ERROR_SUCCESS; PSID pAdministratorsGroup = NULL; SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; if (!AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdministratorsGroup)) { dwError = GetLastError(); goto Cleanup; } if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin)) { dwError = GetLastError(); goto Cleanup; } Cleanup: if (pAdministratorsGroup) { FreeSid(pAdministratorsGroup); pAdministratorsGroup = NULL; } if (ERROR_SUCCESS != dwError) { throw dwError; } return fIsRunAsAdmin; } void ElevateNow(const char* params) { BOOL bAlreadyRunningAsAdministrator = FALSE; try { bAlreadyRunningAsAdministrator = IsRunAsAdministrator(); } catch (...) {} if (!bAlreadyRunningAsAdministrator) { wchar_t szPath[MAX_PATH]; if (GetModuleFileName(NULL, (LPSTR)szPath, ARRAYSIZE(szPath))) { SHELLEXECUTEINFOA sei = { sizeof(sei) }; sei.lpVerb = "runas"; sei.lpFile = (LPCSTR)szPath; sei.hwnd = NULL; sei.nShow = SW_NORMAL; sei.lpParameters = (LPCSTR)params; if (!ShellExecuteEx(&sei)) { DWORD dwError = GetLastError(); if (dwError == ERROR_CANCELLED) _exit(1); } else _exit(1); } } } int EnsureAdmin(int argc, char* argv[]) { if (!IsRunAsAdministrator()) { std::string strArgs(""); for (int i = 1; i < argc; i++) { strArgs.append(argv[i]); if (i < argc - 1) strArgs.append(" "); } ElevateNow(strArgs.c_str()); } return 0; } void RemoveKey() { RegDeleteKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osu!.exe")); } void CreateKey() { HKEY createdKey = nullptr; RegCreateKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osu!.exe"), &createdKey); char* path = GetPathOfExe(); RegSetValueEx(createdKey, "Debugger", 0, REG_SZ, (BYTE*)path, strlen(path)); RegCloseKey(createdKey); } bool KeyExists() { HKEY subKey = nullptr; auto result = RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osu!.exe"), &subKey); RegCloseKey(subKey); return result == ERROR_SUCCESS; }
#include <iostream> #include <math.h> #include <stdlib.h> using namespace std; typedef struct { // x and y coordinates of points (x or gra) double x; double y; } point; point gradient(point arrx) { // gradient vector arrx point gra; gra.x = 2 * arrx.y - 2 * arrx.x; gra.y = 2 * arrx.x + 2 - 4 * arrx.y; return gra; } double calculate_t(point arrx, point gra) { // find specific value of t at each iteration. t is found by taking first derivative of objective function and equating it to zero. Then, t is setted to one side of the equation and other variables are setted to other side. double t; double a = arrx.x; double b = arrx.y; double c = gra.x; double d = gra.y; t = (4*b*d+2*a*c-2*a*d-2*c*b-2*d) / (2*(2*c*d-c*c-2*d*d)); return t; } point update_arrx(point arrx, point gra, double t) { // update point arrx arrx.x = arrx.x + t*gra.x; arrx.y = arrx.y + t*gra.y; return arrx; } double norm_gradient(point gra) { // l = length of gradient double l = sqrt(gra.x * gra.x + gra.y * gra.y); return l; } void main() { point x; x.x = 0; // initial point x.y = 0; point gra = gradient(x); double length = 1000000000; // norm of gradient. Setted to big number to get it while loop. cout << "Initiliziation" << endl; // initial situation is reported cout << "x : (" << x.x << "," << x.y << ")" << endl; cout << "gradient : (" << gra.x << "," << gra.y << ")" << endl<<endl; int k = 1; // k is iteration number while (length>0.001) { //epsilon = 0.001. double t = calculate_t(x, gra); x = update_arrx(x, gra, t); double f = 2 * x.x*x.y + 2 * x.y - x.x*x.x - 2 * x.y*x.y; // function f(x) gra = gradient(x); length = norm_gradient(gra); cout << "k : " << k << endl; //We report information at each iteration cout << "x : (" << x.x << "," << x.y << ")" << endl; cout << "f(x) : " << f << endl; cout << "gradient : (" << gra.x << "," << gra.y << ")" << endl; cout << "norm gradient : " << length << endl; cout << "t : " << t << endl << endl; k++; } getchar(); }
/** * @file Configuration.cpp * @brief 包含类Configuration的实现 */ #include "configuration.h" #include <QSettings> Configuration *Configuration::instance_ = NULL; QMutex Configuration::mutex_; /** * @brief 获取实例函数 * @param void * @return Configuration指针 */ Configuration *Configuration::GetInstance() { if (instance_ == NULL) { mutex_.lock(); ///<上锁 if (instance_ == NULL) { ///<若没有实例,则新建一个 instance_ = new Configuration(); } mutex_.unlock(); ///<开锁 } return instance_; } /** * @brief 构造函数 * @param void * @note */ Configuration::Configuration() { QSettings settings("./config/config.ini", QSettings::IniFormat); ///<定义读取配置文件的类QSettings的实例 settings.beginGroup("DB"); ///<用beginGroup()和endGroup()作为重点来指定相同的前缀 dbhost_ = settings.value("host").toString(); ///<设置主机名 dbname_ = settings.value("dbname").toString(); ///<设置数据库名 dbusername_ = settings.value("username").toString(); ///<设置用户名 dbpassword_ = settings.value("password").toString(); ///<设置密码 settings.endGroup(); }
//https://www.hackerrank.com/challenges/flipping-bits //List of 32 bit signed ints. //Flip all the bits, output the result. //Convenient that C++ has an operator for that #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int count; cin >> count; //vector<unsigned int> forFlipping; //overkill for(int i=0; i<count; i++) { unsigned int bob; cin >> bob; // forFlipping.push_back(bob); cout << ~bob << endl; } return 0; }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #include "Core/Log.hpp" #include "Core/TypeID.hpp" #include "Core/Settings.hpp" #include "Render/OpenGL.hpp" #include "Render/RenderState.hpp" #include "Render/CompressedImage.hpp" #include "Render/Private/TextureResource.hpp" #include <memory> #include <string> #include <cassert> namespace Push { namespace Private { static_assert(sizeof(uint32_t) == sizeof(GLuint), "Invalid texture handle size"); TextureResource::TextureResource(const Path& path, TextureWrap wrap, TextureFilter filter) : Resource(path, TypeID<TextureResource>::value()) , m_wrap(wrap) , m_filter(filter) { } void TextureResource::Setup(uint32_t sampler) const { BindTexture(static_cast<GLuint>(sampler), m_handle); } TextureResource::~TextureResource() { assert(m_data == nullptr && "m_data should be null here"); delete[] m_data; } void TextureResource::SyncLoad() { assert(Value(m_wrap) < Value(TextureWrap::Count)); assert(Value(m_filter) < Value(TextureFilter::Count)); assert(Value(m_format) < Value(PixelFormat::Count)); #if TARGET_OS_IPHONE || TARGET_OS_IPHONE_SIMULATOR static const GLint s_textureWrap[Value(TextureWrap::Count)] = { GL_CLAMP_TO_EDGE, GL_REPEAT }; #else static const GLint s_textureWrap[Value(TextureWrap::Count)] = { GL_CLAMP, GL_REPEAT }; #endif static const GLint s_textureFilter[Value(TextureFilter::Count)] = { GL_NEAREST, GL_LINEAR }; static const GLint s_internalFormat[Value(PixelFormat::Count)] = { 0, GL_RGB, GL_RGBA, GL_ALPHA }; static const GLenum s_pixelFormat[Value(PixelFormat::Count)] = { 0, GL_RGB, GL_RGBA, GL_ALPHA }; glCall(glGenTextures, 1, &m_handle); BindTexture(0, m_handle); glCall(glTexParameteri, static_cast<GLenum>(GL_TEXTURE_2D), static_cast<GLenum>(GL_TEXTURE_WRAP_S), s_textureWrap[Value(m_wrap)]); glCall(glTexParameteri, static_cast<GLenum>(GL_TEXTURE_2D), static_cast<GLenum>(GL_TEXTURE_WRAP_T), s_textureWrap[Value(m_wrap)]); glCall(glTexParameteri, static_cast<GLenum>(GL_TEXTURE_2D), static_cast<GLenum>(GL_TEXTURE_MIN_FILTER), s_textureFilter[Value(m_filter)]); glCall(glTexParameteri, static_cast<GLenum>(GL_TEXTURE_2D), static_cast<GLenum>(GL_TEXTURE_MAG_FILTER), s_textureFilter[Value(m_filter)]); glCall(glTexImage2D, static_cast<GLenum>(GL_TEXTURE_2D), 0, s_internalFormat[Value(m_format)], static_cast<GLint>(m_width), static_cast<GLint>(m_height), 0, s_pixelFormat[Value(m_format)], static_cast<GLenum>(GL_UNSIGNED_BYTE), m_data); delete[] m_data; m_data = nullptr; } void TextureResource::AsyncLoad() { if (LoadImage(Settings::GetInstance()->GetPath(BundleType::Resource, GetPath()), m_width, m_height, m_channels, m_data)) { switch (m_channels) { case 1: m_format = PixelFormat::GRAY; break; case 3: m_format = PixelFormat::RGB; break; case 4: m_format = PixelFormat::RGBA; break; } } else { Log(LogType::Error, "Render", "Texture %s not found!", GetPath().GetPath()); } } void TextureResource::SyncRelease() { glCall(glDeleteTextures, 1, &m_handle); } void TextureResource::AsyncRelease() { } Hash TextureResource::MakeHash(const Path& path, TextureWrap wrap, TextureFilter filter) { return Push::MakeHash(path.GetPath()) + (Value(wrap) << 1 | Value(filter)); } } }
// MIT License // Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <cmath> #include "Solver.h" #include "Body.h" #include "SolverConstraint.h" #include "SolverBody.h" #include "BodyVec.h" #include "Contact.h" //Solver imspired by the btSequentialImpulseSolver from Bullet Physics. //The same solver can be used for dynamic multi-body simulations or for //penetration correction, as is done in this code. It solves the contact //impulses needed to change the body velocities such that they recover from //penetration in a unit time step. //Body masses, impulses and velocities should be seen as "virtual" //values used to recover from penetration. After updating the body positions, //all velocities are set to zero for the next iteration step. //Terminology is kept as it is because the intention is to extend this code to //a simple physics physics engine. //Solvers in Bullet Physics and Box2d create local compact "solverBody" vectors. //Since the body vector is already quite compact this is not done in this solver. Solver::Solver(int nBodies) { m_solverBodies.resize(nBodies, SolverBody()); } Solver::Solver() {} Solver::~Solver() = default; void Solver::solveOverlaps(BodyVec * bodies, const std::vector<Contact>&contacts, const SolverSettings & solverSettings) { m_solverBodies.resize(bodies->size()); for (auto& body : m_solverBodies) body.setZero(); m_solverSettings = solverSettings; initConstraints(*bodies, contacts); solve(); transformBodies(bodies); m_solverConstraints.resize(0); } void Solver::initConstraints(const BodyVec & bodies, const std::vector<Contact>&contacts) { m_solverSettings.maxImpulseError = HUGE_VAL; m_solverConstraints.reserve(contacts.size()); for (int i = 0; i < contacts.size(); i++) { const Contact& contact = contacts[i]; int bodyIdx0 = contact.bodyIdx0(); const Body& body0 = bodies[bodyIdx0]; int bodyIdx1 = contact.bodyIdx1(); const Body& body1 = bodies[bodyIdx1]; Vector2 contactPoint = contact.contactPoint(); Vector2 contactNormal = contact.normal(); Vector2 relPos0 = contactPoint - body0.transform().position(); Vector2 relPos1 = contactPoint - body1.transform().position(); double torqueAxis0 = relPos0.cross(contactNormal); double torqueAxis1 = -relPos1.cross(contactNormal); double invInertia0 = body0.invInertia(); double invInertia1 = body1.invInertia(); double invMass0 = body0.invMass(); double invMass1 = body1.invMass(); SolverConstraint solverConstraint; solverConstraint.bodyIdx0 = bodyIdx0; solverConstraint.bodyIdx1 = bodyIdx1; solverConstraint.normal0 = contactNormal; solverConstraint.normal1 = -contactNormal; solverConstraint.relPos0CrossNormal = torqueAxis0; solverConstraint.relPos1CrossNormal = torqueAxis1; solverConstraint.angularComponent0 = invInertia0 * torqueAxis0; solverConstraint.angularComponent1 = invInertia1 * torqueAxis1; solverConstraint.linearComponent0 = invMass0 * contactNormal; solverConstraint.linearComponent1 = invMass1 * -contactNormal; double inverseEffectiveMass0 = solverConstraint.linearComponent0.length() + solverConstraint.angularComponent0 * solverConstraint.relPos0CrossNormal; double inverseEffectiveMass1 = solverConstraint.linearComponent1.length() + solverConstraint.angularComponent1 * solverConstraint.relPos1CrossNormal; double inverseEffectiveMass = inverseEffectiveMass0 + inverseEffectiveMass1; if (inverseEffectiveMass < DBL_EPSILON) continue; //static-static collision. solverConstraint.effectiveMass = 1.0 / inverseEffectiveMass; solverConstraint.rhs = contact.penetration() * solverConstraint.effectiveMass; solverConstraint.impulse = 0.0; double impulseError = m_solverSettings.maxPenetrationError * solverConstraint.effectiveMass; if (impulseError < m_solverSettings.maxImpulseError) m_solverSettings.maxImpulseError = impulseError; m_solverConstraints.push_back(solverConstraint); } } void Solver::solve() { double error(HUGE_VAL); double maxError = m_solverSettings.maxImpulseError; int nIterations(0); int maxIterations = m_solverSettings.maxIterations; int numConstraints = int(m_solverConstraints.size()); while (error > maxError && nIterations < maxIterations) { ++nIterations; error = 0.0; for (int i = 0; i < numConstraints; i++) { SolverConstraint& constraint = m_solverConstraints[i]; SolverBody& body0 = m_solverBodies[constraint.bodyIdx0]; SolverBody& body1 = m_solverBodies[constraint.bodyIdx1]; double deltaImpulse = constraint.rhs; const double deltaVel0Dotn = constraint.normal0.dot(body0.linearVelocityChangeImpulse()) + constraint.relPos0CrossNormal * body0.angularVelocityChangeImpulse(); const double deltaVel1Dotn = constraint.normal1.dot(body1.linearVelocityChangeImpulse()) + constraint.relPos1CrossNormal * body1.angularVelocityChangeImpulse(); deltaImpulse -= deltaVel0Dotn * constraint.effectiveMass; deltaImpulse -= deltaVel1Dotn * constraint.effectiveMass; //Normal constraint impulses may not be negative. double newImpulse = constraint.impulse + deltaImpulse; if (newImpulse < 0.0) { deltaImpulse = 0.0 - constraint.impulse; constraint.impulse = 0.0; } else { constraint.impulse = newImpulse; } if (deltaImpulse > error) error = deltaImpulse; body0.applyImpulse(constraint.linearComponent0, constraint.angularComponent0, deltaImpulse); body1.applyImpulse(constraint.linearComponent1, constraint.angularComponent1, deltaImpulse); } } } void Solver::transformBodies(BodyVec * bodies) { BodyVec& bodiesRef = *bodies; for (int i = 0; i < bodiesRef.size(); i++) { Vector2 disp = m_solverBodies[i].linearVelocityChangeImpulse(); double rot = m_solverBodies[i].angularVelocityChangeImpulse(); double maxDisplacement = m_solverSettings.maxDisplacement; double maxRotation = m_solverSettings.maxRotation; if (std::abs(disp.x()) > maxDisplacement) disp.setX(std::copysign(1.0, disp.x()) * maxDisplacement); if (std::abs(disp.y()) > maxDisplacement) disp.setY(std::copysign(1.0, disp.y()) * maxDisplacement); if (std::abs(rot) > maxRotation) rot = std::copysign(1.0, rot) * maxRotation; Body& body = bodiesRef[i]; body.updatePosition(disp, rot); } }
#ifndef TRANSACTIONCOMMANDS_HH #define TRANSACTIONCOMMANDS_HH #include "nctypes.hh" #include "ConnectionAwareTransaction.hh" namespace NC { enum struct TransactionCommands { commit, rollback, begin }; template<TransactionCommands c> struct TransactionCommand { }; template<> struct TransactionCommand<TransactionCommands::begin> { static nc_null_t Execute(ConnectionAwareTransaction* owner, const std::tuple<>&) { owner->Begin(); return nc_null_t {}; } }; template<> struct TransactionCommand<TransactionCommands::commit> { static nc_null_t Execute(ConnectionAwareTransaction* owner, const std::tuple<>&) { owner->Commit(); return nc_null_t {}; } }; template<> struct TransactionCommand<TransactionCommands::rollback> { static nc_null_t Execute(ConnectionAwareTransaction* owner, const std::tuple<>&) { owner->Rollback(); return nc_null_t {}; } }; } // namespace NC #endif /* TRANSACTIONCOMMANDS_HH */
// // Created on 09/01/19. // // // Code translated to C++ from the original: https://www.cs.cmu.edu/afs/cs/project/spirit-1/www/#Download. // The original code was adpated for recovery in https://www.ifi.uzh.ch/en/dbtg/Staff/wellenzohn/dasa.html // #include <iostream> #include <cmath> #include <numeric> #include <algorithm> #include "SPIRIT.h" namespace Algorithms { void SPIRIT::doSpirit(arma::mat &A, uint64_t k0, uint64_t w, double lambda) { // // Step 0: prep // impute last exising value instead of all NaNs // uint64_t blockStart = static_cast<unsigned>(-1); uint64_t blockEnd = static_cast<unsigned>(-1); double lastVal = 0; for (uint64_t i = 0; i < A.n_rows; ++i) { if (std::isnan(A.at(i,0))) { lastVal = A.at(i - 1, 0); blockStart = i; break; } } for (uint64_t i = blockStart; i < A.n_rows; ++i) { if (std::isnan(A.at(i,0))) { A.at(i, 0) = lastVal; } else { blockEnd = i; break; } } if (blockEnd == static_cast<unsigned>(-1)) { blockEnd = A.n_rows - 1; } uint64_t n = A.n_cols; uint64_t totalTime = A.n_rows; arma::mat Proj(totalTime, n); arma::mat recon(totalTime, n); //initialize w_i to unit vectors arma::mat W = arma::eye<arma::mat>(n, n); arma::vec d(n); d.fill(0.01); //k0 = number of eigencomponents, passed as a param arma::vec relErrors(totalTime); arma::mat prevW(W); arma::mat Yvalues(totalTime, k0); arma::mat ARc = arma::zeros<arma::mat>(w, k0); //AR coefficients, one for each hidden variable std::vector<arma::mat> G; //"Gain-Matrix", one for each hidden variable //initialize the "Gain-Matrix" with the identity matrix for (uint64_t j = 0; j < k0; ++j) { G.emplace_back(arma::zeros<arma::mat>(w, w)); arma::mat &Gj = G[j]; arma::diagview<double> diag = Gj.diag(); diag.fill(1 / 0.004); } for (uint64_t t = 0; t < totalTime; ++t) { //Simulate a missing block if (blockStart <= t && t <= blockEnd) { //one-step forecast for each y-value arma::vec Y(k0); for (uint64_t j = 0; j < k0; ++j) { arma::vec xj = Yvalues.col(j).subvec(t - w, t - 1); arma::vec aj = ARc.col(j); Y[j] = arma::dot(xj, aj); //Eq 1 in Muscles paper } //estimate the missing value arma::vec xProj = prevW.submat(0, 0, prevW.n_rows - 1, k0 - 1) * Y; //reconstruction of the current time A.at(t, 0) = xProj[0]; //feed back imputed value } //update W for each y_t arma::vec x = A.row(t).t(); arma::mat subW = W.submat(0, 0, W.n_rows - 1, k0 - 1); for (uint64_t j = 0; j < k0; ++j) { arma::vec Wj = subW.col(j); updateW(x, Wj, d[j], lambda); for (uint64_t i = 0; i < subW.n_rows; ++i) { subW(i, j) = Wj[i]; } } grams(subW); for (uint64_t i = 0; i < subW.n_rows; ++i) { for (uint64_t j = 0; j < subW.n_cols; ++j) { W.at(i, j) = subW(i, j); } } //compute low-D projection, reconstruction and relative error arma::vec Y = subW.t() * A.row(t).t(); //project to m-dimensional space prevW = arma::mat(W); for (uint64_t i = 0; i < Y.n_rows; ++i) { Yvalues.at(t, i) = Y[i]; } arma::vec xActual = A.row(t).t(); //actual vector of the current time arma::vec xProj = subW * Y; //reconstruction of the current time for (uint64_t i = 0; i < k0; ++i) { Proj.at(t, i) = Y[i]; } for (uint64_t i = 0; i < xProj.n_rows; ++i) { recon.at(t, i) = xProj[i]; } arma::vec xOrth = xActual - xProj; // relErrors(t) = sum(xOrth.^2)/sum(xActual.^2); relErrors[t] = std::accumulate(xOrth.begin(), xOrth.end(), 0.0, [](const double &accu, const double &elem) { return accu + pow(elem, 2); }) / std::accumulate(xActual.begin(), xActual.end(), 0.0, [](const double &accu, const double &elem) { return accu + pow(elem, 2); }); //update the AR coefficients for each hidden variable if (t >= w) { //we can start only when we have seen w measurements for (uint64_t j = 0; j < k0; ++j) { arma::vec xj = Yvalues.col(j).subvec(t - w + 1, t);// xj = Yvalues(t - w + 1:t, j)^T; double yj = Yvalues.at(t, j); arma::vec aj = ARc.col(j); arma::mat &Gj = G[j]; arma::vec Gjxj = Gj * xj; arma::vec GjxjT = Gj.t() * xj; arma::mat X = Gjxj * GjxjT.t(); // Gj = (1/lambda)*Gj - (1/lambda) *inv(lambda + xj' * Gj * xj) * (Gj * xj) * (xj' * Gj); Gj = (1 / lambda) * Gj - (1 / lambda) * (1 / (lambda + arma::dot(xj, Gjxj))) * X; Gjxj = Gj * xj; //recompute aj -= Gjxj * (arma::dot(xj, aj) - yj); for (uint64_t i = 0; i < aj.n_rows; ++i) { ARc.at(i, j) = aj[i]; } } } } // pull data in col 0, rows [range] from recon into A for (uint64_t i = blockStart; i <= blockEnd; ++i) { A.at(i, 0) = recon.at(i, 0); } } void SPIRIT::grams(arma::mat &A) { uint64_t n = A.n_cols; for (uint64_t j = 1; j < n; ++j) { arma::vec Aj = A.col(j); for (uint64_t k = 0; k <= j - 1; ++k) { arma::vec Ak = A.col(k); double mult = arma::dot(Aj, Ak) / arma::dot(Ak, Ak); Aj -= (mult * Ak); } for (uint64_t i = 0; i < Aj.n_rows; ++i) { A.at(i, j) = Aj[i]; } } for (uint64_t j = 0; j < n; ++j) { double norm2 = 0.0; for (uint64_t i = 0; i < A.n_rows; ++i) { norm2 += A.at(i, j) * A.at(i, j); } norm2 = sqrt(norm2); if (norm2 < sqrtEps) { throw std::runtime_error("[->grams] Columns of A are linearly dependent."); } else { for (uint64_t i = 0; i < A.n_rows; ++i) { A.at(i, j) /= norm2; } } } } void SPIRIT::updateW(arma::vec &old_x, arma::vec &old_w, double &d, double lambda) { double y = arma::dot(old_w, old_x); d = lambda * d + pow(y, 2); arma::vec w(old_w); arma::vec e = old_x - (w * y); w = old_w + ((e * y) / d); old_w = arma::vec(w); arma::vec x = old_x - w * y; old_w = old_w / arma::norm(old_w); old_x = std::move(x); } //*/ } // namespace Algorithms
/* -*- 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. */ #ifndef __URL_B23TREE_REL_REP_H__ #define __URL_B23TREE_REL_REP_H__ #include "modules/util/b23tree.h" class URL_RelRep; #ifdef CACHE_FAST_INDEX class DiskCacheEntry; #endif class RelRep_Store : public B23Tree_Store { public: RelRep_Store(); #ifndef RAMCACHE_ONLY void WriteCacheDataL(DataFile_Record *rec); #ifdef CACHE_FAST_INDEX void WriteCacheDataL(DiskCacheEntry *rec); #endif #endif void DeleteRep(const char *rel); URL_RelRep *FindOrAddRep(const char *rel); void FindOrAddRep(URL_RelRep *rel); }; #endif
//Lab 2£ºHierarchical Object Motion Control System #include "stdafx.h" #include <assert.h> #include <math.h> #include <GL/glut.h> //screen size int g_screenWidth = 0; int g_screenHeight = 0; //points on Spline static int points = 0; //index of points static int number = 7; //number of points static GLfloat t = 0; //time //vectors for computing tangent orientation static GLfloat tangent[3] = { 0 }; static GLfloat binormal[3] = { 0 }; static GLfloat normal[3] = { 0 }; static GLfloat loopIndex = 0; //The M matrix for torso, Left and Right Leg static GLfloat M[16] = { 0 }; //torso static GLfloat tempM[3] = {0}; //temporary matrix to keep the interpolated track of torso's movement static GLfloat M1[16] = { 0 }; //left leg static GLfloat M2[16] = { 0 }; //right leg //M Marix for Catmull-Rom Spline static GLfloat CRSplineM[16] = { -0.5f, 1.0f, -0.5f, 0.0f, 1.5f, -2.5f, 0.0f, 1.0f, -1.5f, 2.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f }; //M Marix for B Spline static GLfloat BSplineM[16] = { -1.0f / 6.0f, 3.0f / 6.0f, -3.0f / 6.0f, 1.0f / 6.0f, 3.0f / 6.0f, -6.0f / 6.0f, 0.0f / 6.0f, 4.0f / 6.0f, -3.0f / 6.0f, 3.0f / 6.0f, 3.0f / 6.0f, 1.0f / 6.0f, 1.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f }; //7 points presented in world coordinate system static GLfloat point[7][3] = { { 12, 0, -20 }, { 6, 0, -20 }, { -1, 0, -10 }, { -5, 0, -10 }, { -1, 0, -5 }, { 2, 0, -5 }, { 3, 0, -3 } }; //Blending Function: Q(t) = T*M*G GLfloat blend(GLfloat T[4], GLfloat MS[16], GLfloat G[4]) { GLfloat B[4] = { 0 }; //B[4] = T*M B[0] = T[0] * MS[0] + T[1] * MS[1] + T[2] * MS[2] + T[3] * MS[3]; B[1] = T[0] * MS[4] + T[1] * MS[5] + T[2] * MS[6] + T[3] * MS[7]; B[2] = T[0] * MS[8] + T[1] * MS[9] + T[2] * MS[10] + T[3] * MS[11]; B[3] = T[0] * MS[12] + T[1] * MS[13] + T[2] * MS[14] + T[3] * MS[15]; GLfloat Qt = B[0] * G[0] + B[1] * G[1] + B[2] * G[2] + B[3] * G[3]; return Qt; } //4 x 4 Matrix Multiplication void matMult4x4(GLfloat M1[16], GLfloat M2[16], GLfloat MResult[16]) { MResult[0] = M1[0] * M2[0] + M1[4] * M2[1] + M1[8] * M2[2] + M1[12] * M2[3]; MResult[1] = M1[1] * M2[0] + M1[5] * M2[1] + M1[9] * M2[2] + M1[13] * M2[3]; MResult[2] = M1[2] * M2[0] + M1[6] * M2[1] + M1[10] * M2[2] + M1[14] * M2[3]; MResult[3] = M1[3] * M2[0] + M1[7] * M2[1] + M1[11] * M2[2] + M1[15] * M2[3]; MResult[4] = M1[0] * M2[4] + M1[4] * M2[5] + M1[8] * M2[6] + M1[12] * M2[7]; MResult[5] = M1[1] * M2[4] + M1[5] * M2[5] + M1[9] * M2[6] + M1[13] * M2[7]; MResult[6] = M1[2] * M2[4] + M1[6] * M2[5] + M1[10] * M2[6] + M1[14] * M2[7]; MResult[7] = M1[3] * M2[4] + M1[7] * M2[5] + M1[11] * M2[6] + M1[15] * M2[7]; MResult[8] = M1[0] * M2[8] + M1[4] * M2[9] + M1[8] * M2[10] + M1[12] * M2[11]; MResult[9] = M1[1] * M2[8] + M1[5] * M2[9] + M1[9] * M2[10] + M1[13] * M2[11]; MResult[10] = M1[2] * M2[8] + M1[6] * M2[9] + M1[10] * M2[10] + M1[14] * M2[11]; MResult[11] = M1[3] * M2[8] + M1[7] * M2[9] + M1[11] * M2[10] + M1[15] * M2[11]; MResult[12] = M1[0] * M2[12] + M1[4] * M2[13] + M1[8] * M2[14] + M1[12] * M2[15]; MResult[13] = M1[1] * M2[12] + M1[5] * M2[13] + M1[9] * M2[14] + M1[13] * M2[15]; MResult[14] = M1[2] * M2[12] + M1[6] * M2[13] + M1[10] * M2[14] + M1[14] * M2[15]; MResult[15] = M1[3] * M2[12] + M1[7] * M2[13] + M1[11] * M2[14] + M1[15] * M2[15]; } //Vector normalization void normalization(GLfloat normalVec[3]) { GLfloat squareQuat = normalVec[0] * normalVec[0] + normalVec[1] * normalVec[1] + normalVec[2] * normalVec[2]; if (squareQuat != 0) { GLfloat baseQuat = sqrt(squareQuat); normalVec[0] = normalVec[0] / baseQuat; normalVec[1] = normalVec[1] / baseQuat; normalVec[2] = normalVec[2] / baseQuat; } } //Vector multiplication - cross product void VectorMult(GLfloat V1[3], GLfloat V2[3], GLfloat VResult[3]) { VResult[0] = V1[1] * V2[2] - V1[2] * V2[1]; VResult[1] = V1[2] * V2[0] - V1[0] * V2[2]; VResult[2] = V1[0] * V2[1] - V1[1] * V2[0]; } //Timer: 16ms interval, about 60 FPS void timer(int value) { glutPostRedisplay(); //As time increases by 0.005, the value of points changes from 0 to 2 t = t + 0.005; if (t >= 1) { t = 0; if (points < number - 1) { points++; } else { points = 0; } } //Reset timer glutTimerFunc(16, timer, 0); } //Interpolate the track of torso with given coordinates and spline type void interpolate(GLfloat pCoord[7][3], GLfloat SplineM[16]) { GLfloat TMatrix[4] = { t*t*t, t*t, t, 1 }; GLfloat TangentTMatrix[4] = { 3*t*t, 2*t, 1, 0 }; //Interpolation of track for (int i = 0; i < 3; i++) { GLfloat GMatrix[4] = { pCoord[points][i], pCoord[(points + 1) % number][i], pCoord[(points + 2) % number][i], pCoord[(points + 3) % number][i] }; tempM[i] = blend(TMatrix, SplineM, GMatrix); tangent[i] = blend(TangentTMatrix, SplineM, GMatrix); } //Tangent vector normalization(tangent); if (points == 0 && loopIndex == 0) { //from the start GLfloat TempVector[3] = { 1, 0, 0 }; //A random vector normalization(TempVector); VectorMult(tangent, TempVector, normal); normalization(normal); VectorMult(normal, tangent, binormal); normalization(binormal); loopIndex++; } else { //not from the start VectorMult(tangent, binormal, normal); normalization(normal); VectorMult(normal, tangent, binormal); normalization(binormal); } //Interpolation Matrix M M[0] = tangent[0]; //1, 1 M[1] = normal[0]; //2, 1 M[2] = binormal[0]; //3, 1 M[3] = 0; //4, 1 M[4] = tangent[1]; //1, 2 M[5] = normal[1]; //2, 2 M[6] = binormal[1]; //3, 2 M[7] = 0; //4, 2 M[8] = tangent[2]; //1, 3 M[9] = normal[2]; //2, 3 M[10] = binormal[2]; //3, 3 M[11] = 0; //4, 3 M[12] = tempM[0]; //1, 4 M[13] = tempM[1]; //2, 4 M[14] = tempM[2]; //3, 4 M[15] = 1; //4, 4 } //Animation of torso - moving along given track and facing direction void animateTorso() { interpolate(point, CRSplineM); glLoadMatrixf(M); glutSolidCube(1.0); } //Animation of legs: hierarchical object motion following the order of Translation, Rotation, Translation void animateLeft() { //left leg //Translation 1 GLfloat LT1[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -1, 0, 1 }; //Rotation GLfloat LAngle = (sin(4 * 3.14*t - 3.14 / 2)*3.14) / 4; GLfloat LT2[16] = { cos(LAngle), sin(LAngle), 0, 0, -sin(LAngle), cos(LAngle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; //Translation 2 GLfloat LT3[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0.3, 1 }; //Concatenated transformation of one object in another object's coordinate system matMult4x4(M, LT2, M1); matMult4x4(M1, LT1, M1); matMult4x4(M1, LT3, M1); //Display glLoadMatrixf(M1); glScalef(0.3f, 2.0f, 0.3f); glutSolidCube(1.0); } void animateRight() { //right leg //Translation 1 GLfloat RT1[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -1, 0, 1 }; //Rotation by Z axis GLfloat LAngle = (sin(4*3.14*t-3.14/2)*3.14)/4; GLfloat RT2[16] = { cos(-LAngle), sin(-LAngle), 0, 0, -sin(-LAngle), cos(-LAngle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; //Translation 2 GLfloat RT3[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -0.3, 1 }; //Concatenated transformation matMult4x4(M, RT2, M2); matMult4x4(M2, RT1, M2); matMult4x4(M2, RT3, M2); //Display glLoadMatrixf(M2); glScalef(0.3f, 2.0f, 0.3f); glutSolidCube(1.0); } void render(void) { //Clear buffer glClearColor(0.0, 0.0, 0.0, 0.0); glClearDepth(1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Render state glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); //Lighting GLfloat LightAmbient[] = { 0.7f, 0.7f, 0.7f, 1.0f }; GLfloat LightDiffuse[] = { 0.4f, 0.4f, 0.4f, 1.0f }; GLfloat LightSpecular[] = { 0.5f, 0.5f, 0.5f, 1.0f }; GLfloat LightPosition[] = { 2.0f, 2.0f, 2.0f, 1.0f }; glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient); glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, LightSpecular); glLightfv(GL_LIGHT0, GL_POSITION, LightPosition); //Surface material GLfloat material_Ka[] = { 0.1f, 0.1f, 0.0f, 1.0f }; GLfloat material_Kd[] = { 0.5f, 0.5f, 0.75f, 1.0f }; GLfloat material_Ks[] = { 0.67f, 0.5f, 0.67f, 1.0f }; GLfloat material_Ke[] = { 0.1f, 0.2f, 0.5f, 1.0f }; GLfloat material_Se = 3; glMaterialfv(GL_FRONT, GL_AMBIENT, material_Ka); glMaterialfv(GL_FRONT, GL_DIFFUSE, material_Kd); glMaterialfv(GL_FRONT, GL_SPECULAR, material_Ks); glMaterialfv(GL_FRONT, GL_EMISSION, material_Ke); glMaterialf(GL_FRONT, GL_SHININESS, material_Se); //Modelview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Animation animateTorso(); animateLeft(); animateRight(); //Disable lighting glDisable(GL_LIGHT0); glDisable(GL_LIGHTING); //Swap back and front buffers glutSwapBuffers(); } //Update the viewport and projection matrix when the size of window is changed void reshape(int w, int h) { g_screenWidth = w; g_screenHeight = h; glViewport(0, 0, (GLsizei)w, (GLsizei)h); //Projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70.0, (GLfloat)w / (GLfloat)h, 1.0, 30.0); } int main(int argc, char** argv) { //Create GL window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutInitWindowPosition(100, 100); glutCreateWindow("Animation Lab 2 - Hierarchical Object Motion Control System - Xie Wu"); //Callback functions glutDisplayFunc(render); glutReshapeFunc(reshape); glutTimerFunc(16, timer, 0); //Main loop glutMainLoop(); return 0; }
//find the min rank of the number // index of the number in the sorted array where //all the permutation of the number in the array #include<stdio.h> #include<conio.h> int Index(int*, int); int Fact(int); void main(){ int size; int a[100]; scanf_s("%d", &size); for (int i = 0; i < size; i++) scanf_s("%d", &a[i]); //Index(a, size); printf("\t%d", Index(a, size)); /*for (int i = 0; i < size; i++) printf("%d\t", a[i]);*/ _getch(); } int Fact(int n){ int fact=1; if (n == 0) return 1; for (int i = 1; i <= n; i++) fact = fact*i; return fact; } int Index(int *ap, int size){ int index = 0; for (int i = 0; i < size; i++){ /*if (ap[i] > ap[j]) { index = Fact(size + 1 - i); j++; } else j++;*/ for (int j = i + 1; j < size; j++){ if (ap[i] > ap[j]) { index = index + Fact(size -1 - i); } } } /*int i = 0; for (int j = i + 1; j < size; j++){ /*if (ap[i] > ap[j]) { index = Fact(size + 1 - i); j++; } else j++; if (ap[i] > ap[j]) { index = Fact(size + 1 - i); } if (j == size-1)i++; }*/ //if (size % 2 != 0) index = index+1 ; return index; }
#include <arba/evnt/evnt.hpp> #include <gtest/gtest.h> #include <cstdlib> class int_event { public: int value; }; TEST(event_box_tests, test_connection) { evnt::event_manager event_manager(1); evnt::event_box event_box; evnt::event_manager other_event_manager(1); int value = 0; other_event_manager.connect<int_event>([&value](int_event& event) { value = event.value; }); event_manager.emit(int_event{ 5 }); ASSERT_EQ(value, 0); event_manager.connect(event_box); event_manager.emit(int_event{ 5 }); ASSERT_EQ(value, 0); other_event_manager.emit(event_box); ASSERT_EQ(value, 5); } TEST(event_box_tests, test_connection_2) { evnt::event_manager event_manager(1); evnt::event_box event_box; evnt::event_manager other_event_manager(1); event_manager.connect(event_box); event_manager.emit(int_event{ 5 }); int value = 0; other_event_manager.connect<int_event>([&value](int_event& event) { value = event.value; }); ASSERT_EQ(value, 0); other_event_manager.emit(event_box); ASSERT_EQ(value, 5); } TEST(event_box_tests, test_auto_deconnection) { evnt::event_manager event_manager(1); int value = 0; { evnt::event_box event_box; evnt::event_manager other_event_manager(1); other_event_manager.connect<int_event>([&value](int_event& event) { value = event.value; }); event_manager.connect(event_box); event_manager.emit(int_event{ 5 }); other_event_manager.emit(event_box); ASSERT_EQ(value, 5); } event_manager.emit(int_event{ 8 }); ASSERT_EQ(value, 5); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#pragma once #include "Vector2.h" #include "object\Player.h" #include "object\Enemy.h" class Func { static Player player; public: void SetPlayer(Player playerIn); static void DrawRotaGraphFWithRate(float x, float y, double exRate, double angle, int handle, int trans); static Vector2 GetVectorWithLength(float vecX, float vecY, float length); static Vector2 GetVectorAimedPlayer(Vector2 posIn, float length); static Vector2 GetRandomPos(Vector2 pos, float distance); static double GetAngleAimedPlayer(Vector2 pos); static void MoveBossPos(Enemy *boss, Vector2 dest, int count); void RandomBossPos(Enemy *boss, int count); };
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <vector> #include <cmath> #include <map> #include <queue> using namespace std; #define LL long long typedef pair<int,int> pii; const int inf = 0x3f3f3f3f; const int MOD = 998244353; const int N = 1e5+10; const int maxx = 200010; #define clc(a,b) memset(a,b,sizeof(a)) const double eps = 1e-8; void fre() {freopen("in.txt","r",stdin);} void freout() {freopen("out.txt","w",stdout);} inline int read() {int x=0,f=1;char ch=getchar();while(ch>'9'||ch<'0') {if(ch=='-') f=-1; ch=getchar();}while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}return x*f;} int a[N]; int n,m; bool check(int k){ queue<LL>q1; queue<LL>q2; if((n-1)%(k-1)!=0){ for(int i=1;i<=k-1-(n-1)%(k-1);i++) q1.push(0); } for(int i=1;i<=n;i++){ q1.push(a[i]); } LL sum=0; while(1){ LL tem=0; for(int i=1;i<=k;i++){ if(q1.size()==0&&q2.size()==0) break; int a1,a2; if(q1.size()==0){ tem+=q2.front(); q2.pop(); continue; } if(q2.size()==0) { tem+=q1.front(); q1.pop(); continue; } a1=q1.front(); a2=q2.front(); if(a1<a2) {tem+=a1;q1.pop();} else {tem+=a2;q2.pop();} } sum+=tem; if(q1.size()==0&&q2.size()==0) break; q2.push(tem); } if(sum>m) return false; else return true; } int main(){ // fre(); int T; scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+1+n); int l=2,r=n; while(l<r){ int mid=(l+r)>>1; if(check(mid)) r=mid; else l=mid+1; } printf("%d\n",r); } return 0; }
/* ** EPITECH PROJECT, 2019 ** OOP_indie_studio_2018 ** File description: ** Game */ #ifndef GAME_HPP_ #define GAME_HPP_ #include "Menu.hpp" #include "Core.hpp" #include "Character.hpp" #include "Assets.hpp" #include "Map.hpp" #include "Event.hpp" #include "Sounds.hpp" #include <memory> #include <iostream> #include <unistd.h> class Menu; class Game { enum class BUTTON { PLAY = 200, EXIT = 99 }; public: Game(); ~Game(); void InitAndChara(); void begin(); void Movement_Player_One(u32 starting_time, const u32 now, const f32 frameDeltaTime); void Movement_Player_Two(u32 starting_time, const u32 now, const f32 frameDeltaTime); void InitAll(); std::shared_ptr<Core> GetCore(); protected: private: Core *_corePtr; std::shared_ptr<Menu> _menu; std::shared_ptr<Core> _core; std::shared_ptr<Character> _perso; std::shared_ptr<Assets> _assets; std::shared_ptr<Map> _map; std::shared_ptr<Sound> _sound; bool _tmp; f32 _tmp2; }; #endif /* !GAME_HPP_ */
// Created on: 1996-08-09 // Created by: Herve LOUESSARD // Copyright (c) 1996-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 _LocalAnalysis_CurveContinuity_HeaderFile #define _LocalAnalysis_CurveContinuity_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GeomAbs_Shape.hxx> #include <LocalAnalysis_StatusErrorType.hxx> class Geom_Curve; class GeomLProp_CLProps; //! This class gives tools to check local continuity C0 //! C1 C2 G1 G2 between two points situated on two curves class LocalAnalysis_CurveContinuity { public: DEFINE_STANDARD_ALLOC //! -u1 is the parameter of the point on Curv1 //! -u2 is the parameter of the point on Curv2 //! -Order is the required continuity: //! GeomAbs_C0 GeomAbs_C1 GeomAbs_C2 //! GeomAbs_G1 GeomAbs_G2 //! //! -EpsNul is used to detect a a vector with nul //! magnitude (in mm) //! //! -EpsC0 is used for C0 continuity to confuse two //! points (in mm) //! //! -EpsC1 is an angular tolerance in radians used //! for C1 continuity to compare the angle between //! the first derivatives //! //! -EpsC2 is an angular tolerance in radians used //! for C2 continuity to compare the angle between //! the second derivatives //! //! -EpsG1 is an angular tolerance in radians used //! for G1 continuity to compare the angle between //! the tangents //! //! -EpsG2 is an angular tolerance in radians used //! for G2 continuity to compare the angle between //! the normals //! //! - percent : percentage of curvature variation (unitless) //! used for G2 continuity //! //! - Maxlen is the maximum length of Curv1 or Curv2 in //! meters used to detect nul curvature (in mm) //! //! the constructor computes the quantities which are //! necessary to check the continuity in the following cases: //! //! case C0 //! -------- //! - the distance between P1 and P2 with P1=Curv1 (u1) and //! P2=Curv2(u2) //! //! case C1 //! ------- //! //! - the angle between the first derivatives //! dCurv1(u1) dCurv2(u2) //! -------- and --------- //! du du //! //! - the ratio between the magnitudes of the first //! derivatives //! //! the angle value is between 0 and PI/2 //! //! case C2 //! ------- //! - the angle between the second derivatives //! 2 2 //! d Curv1(u1) d Curv2(u2) //! ---------- ---------- //! 2 2 //! du du //! //! the angle value is between 0 and PI/2 //! //! - the ratio between the magnitudes of the second //! derivatives //! //! case G1 //! ------- //! the angle between the tangents at each point //! //! the angle value is between 0 and PI/2 //! //! case G2 //! ------- //! -the angle between the normals at each point //! //! the angle value is between 0 and PI/2 //! //! - the relative variation of curvature: //! |curvat1-curvat2| //! ------------------ //! 1/2 //! (curvat1*curvat2) //! //! where curvat1 is the curvature at the first point //! and curvat2 the curvature at the second point Standard_EXPORT LocalAnalysis_CurveContinuity(const Handle(Geom_Curve)& Curv1, const Standard_Real u1, const Handle(Geom_Curve)& Curv2, const Standard_Real u2, const GeomAbs_Shape Order, const Standard_Real EpsNul = 0.001, const Standard_Real EpsC0 = 0.001, const Standard_Real EpsC1 = 0.001, const Standard_Real EpsC2 = 0.001, const Standard_Real EpsG1 = 0.001, const Standard_Real EpsG2 = 0.001, const Standard_Real Percent = 0.01, const Standard_Real Maxlen = 10000); Standard_EXPORT Standard_Boolean IsDone() const; Standard_EXPORT LocalAnalysis_StatusErrorType StatusError() const; Standard_EXPORT GeomAbs_Shape ContinuityStatus() const; Standard_EXPORT Standard_Real C0Value() const; Standard_EXPORT Standard_Real C1Angle() const; Standard_EXPORT Standard_Real C1Ratio() const; Standard_EXPORT Standard_Real C2Angle() const; Standard_EXPORT Standard_Real C2Ratio() const; Standard_EXPORT Standard_Real G1Angle() const; Standard_EXPORT Standard_Real G2Angle() const; Standard_EXPORT Standard_Real G2CurvatureVariation() const; Standard_EXPORT Standard_Boolean IsC0() const; Standard_EXPORT Standard_Boolean IsC1() const; Standard_EXPORT Standard_Boolean IsC2() const; Standard_EXPORT Standard_Boolean IsG1() const; Standard_EXPORT Standard_Boolean IsG2() const; protected: private: Standard_EXPORT void CurvC0 (GeomLProp_CLProps& Curv1, GeomLProp_CLProps& Curv2); Standard_EXPORT void CurvC1 (GeomLProp_CLProps& Curv1, GeomLProp_CLProps& Curv2); Standard_EXPORT void CurvC2 (GeomLProp_CLProps& Curv1, GeomLProp_CLProps& Curv2); Standard_EXPORT void CurvG1 (GeomLProp_CLProps& Curv1, GeomLProp_CLProps& Curv2); Standard_EXPORT void CurvG2 (GeomLProp_CLProps& Curv1, GeomLProp_CLProps& Curv2); Standard_Real myContC0; Standard_Real myContC1; Standard_Real myContC2; Standard_Real myContG1; Standard_Real myContG2; Standard_Real myCourbC1; Standard_Real myCourbC2; Standard_Real myG2Variation; Standard_Real myLambda1; Standard_Real myLambda2; GeomAbs_Shape myTypeCont; Standard_Real myepsnul; Standard_Real myepsC0; Standard_Real myepsC1; Standard_Real myepsC2; Standard_Real myepsG1; Standard_Real myepsG2; Standard_Real myMaxLon; Standard_Real myperce; Standard_Boolean myIsDone; LocalAnalysis_StatusErrorType myErrorStatus; }; #endif // _LocalAnalysis_CurveContinuity_HeaderFile
#ifndef LED13_H; #define LED13_H; #include <Arduino.h> class LED13 { private: byte pin; public: LED13(byte pin); void on(); void off(); void blink(int time); }; #endif
#ifndef DTPUERTO_H #define DTPUERTO_H #include "DtFecha.h" #include <iostream> using namespace std; class DtPuerto { private: string id; string nombre; DtFecha fechaCreacion; int cantArribos; public: DtPuerto(); DtPuerto(string id, string nombre, DtFecha fechaCreacion, int cantArribos); string getid(); string getnombre(); DtFecha getfecha(); int getcant(); }; ostream& operator << (ostream &os, DtPuerto & dtp); #endif
#include <bits/stdc++.h> using namespace std; int main() { int t; cout<<"Enter number of cases\n"; cin >> t; while (t--) { int n, k; cout<<"Enter length of array and number of peaks\n"; cin >> n >> k; vector<int> arr(n + 1); int num = n; for (int i = 2; i < n; i += 2) { if (k == 0) break; arr[i] = num--; k = k - 1; } if (k==1) { cout <<"-1" << endl; continue; } int ctr = 1; for(int i = 1; i <= n; i++){ if (!arr[i]) arr[i] = ctr++; } for (int i = 1; i <= n; i++) cout << arr[i] << " \n"; } return 0; }
#include <iostream> using namespace std; int matrix[1001]; bool visited[1001]; int ans; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while(tc--){ int n; cin >> n; for (int i = 1; i <= n; i++){ cin >> matrix[i]; visited[i] = false; } ans = 0; for(int i = 1; i <= n; i++){ if(!visited[i]){ ans++; int next = matrix[i]; visited[i] = true; while(!visited[next]){ visited[next] = true; next = matrix[next]; } } } cout << ans << '\n'; } return 0; }
// (C) 1992-2016 Intel Corporation. // Intel, the Intel logo, Intel, MegaCore, NIOS II, Quartus and TalkBack words // and logos are trademarks of Intel Corporation or its subsidiaries in the U.S. // and/or other countries. Other marks and brands may be claimed as the property // of others. See Trademarks on intel.com for full list of Intel trademarks or // the Trademarks & Brands Names Database (if Intel) or See www.Intel.com/legal (if Altera) // Your use of Intel Corporation's design tools, logic functions and other // software and tools, and its AMPP partner logic functions, and any output // files any of the foregoing (including device programming or simulation // files), and any associated documentation or information are expressly subject // to the terms and conditions of the Altera Program License Subscription // Agreement, Intel MegaCore Function License Agreement, or other applicable // license agreement, including, without limitation, that your use is for the // sole purpose of programming logic devices manufactured by Intel and sold by // Intel or its authorized distributors. Please refer to the applicable // agreement for further details. /******** * Testing host <-> dev read/writes * * - Testing all sizes from 0 to 1024. * - Doing non-aligned host SRC and non-aligned dev ptrs so * - don't use DMA * - exercise all the non-32bit-aligned logic in hal * (both with non-aligned to aligned and non-aligned to non-aligned) * - Check for over/under-writes * - Check PCIe Window changes by doing writes and read to all available * global memory. * - do that for all aligned/non-aligned host and dev ptrs (all combos) * ********/ #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <time.h> #include <string.h> #include <assert.h> #include "aclutil.h" #include "CL/opencl.h" // Set to 1 to debug read/write correctness failures #define DEBUG 0 // ACL runtime configuration static cl_platform_id platform; static cl_device_id device; static cl_context context; static cl_command_queue queue; static cl_int status; static void dump_error(const char *str, cl_int status) { printf("%s\n", str); printf("Error code: %d\n", status); exit(-1); } static void my_check_buf (char *src, char *dst, size_t size) { if (memcmp (src, dst, size) == 0) { return; } else { printf ("%d bytes read/write FAILED!\n", size); for (int i=0; i < size; i++) { if ( src[i] != dst[i]) printf ("char #%d, src = %d, dst = %d\n", i, src[i], dst[i]); } assert (0); } } void test_rw (size_t dev_offset) { size_t maxbytes = 1024; size_t odd_maxbytes = maxbytes + 3; printf ("--- test_rw with device ptr offset %lu\n", dev_offset); // create the input buffer. +3 makes sure that DMA is not aligned cl_mem dev_buf = clCreateBuffer(context, CL_MEM_READ_WRITE, odd_maxbytes, NULL, &status); if(status != CL_SUCCESS) dump_error("Failed clCreateBuffer.", status); // allocate extra space around for overflow checks char invalid_host = -6; char invalid_read_back = -3; char *host_buf = (char*)acl_aligned_malloc (maxbytes + 10); char *host_buf_alloced = host_buf; for (int j = 0; j < maxbytes + 10; j++) { host_buf[j] = invalid_host; } // Make host ptr non-aligned. Will test un-aligned host ptr to un-aligned dev ptr host_buf += 5; char *read_back_buf = (char*)acl_aligned_malloc (maxbytes + 16); char *read_back_buf_alloced = read_back_buf; for (int j = 0; j < maxbytes + 16; j++) { read_back_buf[j] = (char) invalid_read_back; } // Read-back pointer is aligned. Testing reading from un-aligned dev to aligned host. read_back_buf += 8; if (DEBUG) printf ("host src buf = %p, host dst buf = %p\n", host_buf, read_back_buf); srand(0); // Non-DMA read/writes of all sizes upto 1024. // (yes, testing 0 read/write as well!). for (int i = 1; i <= maxbytes; i++) { if (DEBUG) printf ("Read/write of %d bytes\n", i); // host will have unique values for every write. for (int j = 0; j < i; j++) { host_buf[j] = (char)rand(); } // Using +3 offset on aligned device pointer ensures that DMA is never used // (because the host ptr is aligned). status = clEnqueueWriteBuffer(queue, dev_buf, CL_TRUE, dev_offset, i, (void*)host_buf, 0, NULL, NULL); if(status != CL_SUCCESS) dump_error ("Failed to enqueue buffer write.", status); status = clEnqueueReadBuffer(queue, dev_buf, CL_TRUE, dev_offset, i, (void*)read_back_buf, 0, NULL, NULL); if(status != CL_SUCCESS) dump_error ("Failed to enqueue buffer.", status); // make sure read back what we wrote. if (DEBUG) printf ("%d, %d\n", read_back_buf[0], host_buf[0]); my_check_buf (host_buf, read_back_buf, i); // make sure bounds are ok assert (read_back_buf[-1] == invalid_read_back); assert (read_back_buf[-2] == invalid_read_back); assert (read_back_buf[-3] == invalid_read_back); assert (read_back_buf[-4] == invalid_read_back); assert (read_back_buf[-5] == invalid_read_back); assert (read_back_buf[i] == invalid_read_back); assert (read_back_buf[i+1] == invalid_read_back); assert (read_back_buf[i+2] == invalid_read_back); assert (read_back_buf[i+3] == invalid_read_back); assert (read_back_buf[i+4] == invalid_read_back); } clReleaseMemObject (dev_buf); acl_aligned_free(host_buf_alloced ); acl_aligned_free(read_back_buf_alloced ); // leak everything! } int rwtest (cl_platform_id i_platform, cl_device_id i_device, cl_context i_context, cl_command_queue i_queue) { platform = i_platform; device = i_device; context = i_context; queue = i_queue; test_rw (3); // unaliged dev addr test_rw (0); // aligned dev addr // if did not die, everything is OK printf ("\nHOST READ-WRITE TEST PASSED!\n"); return 0; }
#pragma once #include "logger.h" #include <ostream> #include <string> #include <sstream> namespace lm { //!A log to an output stream. class ostream_logger :public logger { public: //!Class constructor, creates an active log, with a file assigned and opened. ostream_logger(std::ostream&); protected: //!This begins the implementation of the base class. virtual logger& operator<<(const char * _input) {return insert(_input);} virtual logger& operator<<(char _input) {return insert(_input);} virtual logger& operator<<(int _input) {return insert(_input);} virtual logger& operator<<(unsigned int _input) {return insert(_input);} virtual logger& operator<<(long int _input) {return insert(_input);} virtual logger& operator<<(unsigned long int _input) {return insert(_input);} virtual logger& operator<<(long long int _input) {return insert(_input);} virtual logger& operator<<(unsigned long long int _input) {return insert(_input);} virtual logger& operator<<(double _input) {return insert(_input);} virtual logger& operator<<(const std::string& _input) {return insert(_input);} virtual logger& operator<<(std::ostream& ( *pf )(std::ostream&)) {return insert(pf);} virtual logger& operator<<(std::ios& ( *pf )(std::ios&)) {return insert(pf);} virtual logger& operator<<(std::ios_base& ( *pf )(std::ios_base&)) {return insert(pf);} private: template<typename T> logger& insert(const T& _value) { if(!level_mask_ok) { return *this; } s<<_value; s.flush(); return *this; } std::ostream& s; //!<Internal output stream. }; }
#pragma once class DBUser : public CPacketSession { public: DBUser(); ~DBUser(); private: BOOL mIsConnected; WCHAR ID[ID_SIZE]; public: BOOL Begin(VOID); BOOL End(VOID); BOOL Reload(SOCKET listenSocket); inline BOOL SetIsConnected(BOOL isConnected) { CThreadSync Sync; mIsConnected = isConnected; return TRUE; } inline BOOL GetIsConnected(VOID) { CThreadSync Sync; return mIsConnected; } inline VOID SetID(WCHAR _ID[ID_SIZE]) { CThreadSync Sync; _tcsncpy(ID, _ID, ID_SIZE); } };
#ifndef RADIAL_HPP #define RADIAL_HPP #include <vector> #include <cmath> #include <vector> #include "armadillo" #include "string.h" #include <iostream> #include "../atom/vect3.h" #include "../atom/atom.h" #include "../sim/unitcell.h" #include "../sim/simulation.hpp" void binsetup (int noBins, double cutoff, colvec& r, colvec& bins){ double width = cutoff/noBins; r = zeros<colvec>(noBins); bins = zeros<colvec>(noBins); for(int i=0;i<noBins;i++){ r(i)=(width*i)+width; } } void addtobins(atom_list& atoms, const unitcell& cell, colvec& bins, double cutoff, int& counter){ counter++; unitcell newcell = cell; atom_list newatoms = atoms; newatoms.scale_supercell(3,3,3,newcell); for(int i=0;i<newatoms.count();i++){ for(int j=i+1;j<newatoms.count();j++){ double dist = newatoms[j].pos.dist_bc(newatoms[i].pos,newcell); if(dist<cutoff){ int bin = int(ceil((dist/cutoff)*bins.size()))-1; bins(bin)+=2; } } } } void printradial(colvec& r, colvec& bins, int& counter, const unitcell& cell, int n, string filename){ ofstream outfile; outfile.open(filename.c_str()); n*=27; double volume=27*cell.volume(); double rho=n/volume; double width = r(1)-r(0); double R; for(unsigned int i=0;i<bins.size();i++){ R=r(i)-(width/2); bins(i)/=(R*R*width*4*M_PI*n*rho); bins(i)/=counter; outfile<<R<<"\t"<<bins(i)<<endl; } outfile.close(); } #endif
#include <iostream> #include <ctime> #include <cstdlib> #include <windows.h> #include<conio.h> using namespace std; bool game; const int breadth = 20; const int height = 20; int x, y, fruitX, fruitY, score; enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; eDirection initialDir; int tailY[50], tailX[50]; int taila; unsigned seed = time(0); int goodie = 0; void settings(); void visuals(); void logic(); void input(); int main() { settings(); while (!game) { visuals(); logic(); input(); Sleep(100); } return 0; } void settings() { int a = UP; game = false; initialDir = STOP; srand(seed); x = breadth / 2; y = height / 2; fruitX = rand() % breadth; fruitY = rand() % height; score = 0; } void visuals() { system("cls"); char a; for (int a = 0; a < breadth; a++) { cout << "#"; } cout << "\n"; for (int a = 0; a < height; a++) { for (int aa = 0; aa < breadth; aa++) { if (aa == 0 || aa == breadth - 1) { cout << "#"; } else if (a == y && aa == x) { cout << "0"; } else if (aa == fruitX && a == fruitY) { cout <</*aaa*/"*"; } else { bool printTaila = false; for (int count = 0; count < taila; count++) { if (tailX[count] == aa && tailY[count] == a) { cout << "o"; printTaila = true; } } if(!printTaila) cout << " "; } } cout << "\n"; } for (int a = 0; a < breadth; a++) { cout << "#"; } cout << endl << "Score: " << score << endl; } void logic() { int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; tailX[00] = x; tailY[goodie] = y; for (int index = 1; index < taila; index++) { prev2X = tailX[index]; prev2Y = tailY[index]; tailX[index] = prevX; tailY[index] = prevY; prevX = prev2X; prevY = prev2Y; } switch (initialDir) { case LEFT:x--; break; case RIGHT:x++; break; case UP: y--; break; case DOWN: y++; break; } if (x == fruitX && y == fruitY) { score++; fruitX = rand() % breadth; fruitY = rand() % height; taila++; } if (x >= breadth) { x = 0; } if (x < 0) { x = breadth - 1; } if (y >= height) { y = 0; } if (y < 0) { y = height - 1; } for (int index = 0; index < taila; index++) { if (tailY[index] == y && tailX[index] == x) { game = true; } } } void input() { if (_kbhit()) { switch (_getch()) { case 'a': initialDir = LEFT; break; case 'd': initialDir = RIGHT; break; case 'w': initialDir = UP; break; case 's': initialDir = DOWN; break; case 'X': game = true; break; } } }
// // rvMemSys.h - Memory management system // Date: 12/17/04 // Created by: Dwight Luetscher // // Date: 04/01/05 // Modified by: Marcus Whitlock // Added permanent heap and new heap push function to push the heap that contains // a specified piece of memory. // // Date: 04/04/05 // Modified by: Marcus Whitlock // Added rvAutoHeapCtxt class for push and auto-pop of heap context. // #ifndef __RV_MEM_SYS_H__ #define __RV_MEM_SYS_H__ typedef enum { RV_HEAP_ID_DEFAULT, // heap that exists on application startup RV_HEAP_ID_PERMANENT, // heap for allocations that have permanent (application scope) lifetime RV_HEAP_ID_LEVEL, // heap for allocations that have a level lifetime RV_HEAP_ID_MULTIPLE_FRAME, // heap for run-time allocations that have a lifetime of multiple draw frames RV_HEAP_ID_SINGLE_FRAME, // heap for run-time allocations that have a lifetime of a single draw frame RV_HEAP_ID_TEMPORARY, // heap for objects that have a short lifetime (temporaries generally used for level loading) RV_HEAP_ID_IO_TEMP, // heap for allocations that are temporaries used in I/O operations like level loading or writing out data rv_heap_ID_max_count // just a count, not a valid type } Rv_Sys_Heap_ID_t; static const uint MAX_SYSTEM_HEAPS = (uint) rv_heap_ID_max_count; #ifdef _RV_MEM_SYS_SUPPORT // // _RV_MEM_SYS_SUPPORT is defined // extern rvHeapArena *currentHeapArena; // Functions for getting and setting the system heaps. void rvSetSysHeap( Rv_Sys_Heap_ID_t sysHeapID, rvHeap *heapPtr ); // associates a heap with the given system heap ID value rvHeap* rvGetSysHeap( Rv_Sys_Heap_ID_t sysHeapID ); // retrieves the specified system heap void rvGetAllSysHeaps( rvHeap *destSystemHeapArray[MAX_SYSTEM_HEAPS] ); // retrieves all the MAX_SYSTEM_HEAPS heap pointers into the given array void rvSetAllSysHeaps( rvHeap *srcSystemHeapArray[MAX_SYSTEM_HEAPS] ); // associates all the MAX_SYSTEM_HEAPS heap pointers from the given array with their corresponding id value bool rvPushHeapContainingMemory( const void* mem ); // pushes the heap containg the memory specified to the top of the arena stack, making it current - mwhitlock void rvEnterArenaCriticalSection( ); // enters the heap arena critical section void rvExitArenaCriticalSection( ); // exits the heap arena critical section void rvPushSysHeap(Rv_Sys_Heap_ID_t sysHeapID); // pushes the system heap associated with the given identifier to the top of the arena stack, making it current // Useful in situations where a heap is pushed, but a return on error or an // exception could cause the stack to be unwound, bypassing the heap pop // operation - mwhitlock. class rvAutoHeapCtxt { bool mPushed; public: rvAutoHeapCtxt(void) : mPushed(false) { // Should never call this. assert(0); } rvAutoHeapCtxt(Rv_Sys_Heap_ID_t sysHeapID) : mPushed(false) { rvPushSysHeap(sysHeapID); mPushed = true; } rvAutoHeapCtxt(const void* mem) : mPushed(false) { mPushed = rvPushHeapContainingMemory( mem ); } ~rvAutoHeapCtxt(void) { if(mPushed) { currentHeapArena->Pop(); } } }; // // RV_PUSH_SYS_HEAP_ID() // Push system heaps by their ID (always available to idLib, Game and executable). // #define RV_PUSH_SYS_HEAP_ID(sysHeapID) rvPushSysHeap(sysHeapID) #define RV_PUSH_SYS_HEAP_ID_AUTO(varName,sysHeapID) rvAutoHeapCtxt varName(sysHeapID) // // RV_PUSH_HEAP_MEM() // Push the heap containing the piece of memory pointed to. Note that if the // piece of memory is not from a heap, no heap will be pushed. // #define RV_PUSH_HEAP_MEM(memPtr) rvPushHeapContainingMemory(memPtr) #define RV_PUSH_HEAP_MEM_AUTO(varName,memPtr) rvAutoHeapCtxt varName(memPtr) // // RV_PUSH_HEAP_PTR() // Local heaps used mainly by executable (idLib and Game would use these only // if heap was passed in) // #define RV_PUSH_HEAP_PTR(heapPtr) ( (heapPtr)->PushCurrent() ) // // RV_PUSH_SYS_HEAP() // Pop top of heap stack, regardless of how it was pushed. // #define RV_POP_HEAP() ( currentHeapArena->Pop() ) // The following versions enter/exit the heap arena's critical section so that // critical section protection remains active between a push/pop pair (NOTE that // the heap and heap arena are always protected by critical sections within a single method call) #define RV_PUSH_SYS_HEAP_ENTER_CRIT_SECT(sysHeapID) { rvEnterArenaCriticalSection( ); rvPushSysHeap( sysHeapID ); } #define RV_PUSH_HEAP_ENTER_CRIT_SECT(heapPtr) { rvEnterArenaCriticalSection( ); (heapPtr)->PushCurrent( ); } #define RV_POP_HEAP_EXIT_CRIT_SECT() { currentHeapArena->Pop( ); rvExitArenaCriticalSection( ); } #else // #ifdef _RV_MEM_SYS_SUPPORT // // _RV_MEM_SYS_SUPPORT is not defined // #define RV_PUSH_SYS_HEAP_ID(sysHeapID) #define RV_PUSH_SYS_HEAP_ID_AUTO(varName,sysHeapID) #define RV_PUSH_HEAP_MEM(memPtr) #define RV_PUSH_HEAP_MEM_AUTO(varName,memPtr) #define RV_PUSH_HEAP_PTR(heapPtr) #define RV_POP_HEAP() #define RV_PUSH_SYS_HEAP_ENTER_CRIT_SECT(sysHeapID) #define RV_PUSH_HEAP_ENTER_CRIT_SECT(heapPtr) #define RV_POP_HEAP_EXIT_CRIT_SECT() #endif // #else not #ifdef _RV_MEM_SYS_SUPPORT #endif // #ifndef __RV_MEM_SYS_H__
#include <iostream> #include <iomanip> /* Passing by value means that a copy of a variable is fed as an argument. As a result, the original input is not changed. */ int passByValue(int y){ y += 5; return y; } /* Passing by reference means that the function has direct access to the argument. As a result, the original input is directly changed. Reference variables are become another way to express one variable. */ int passByReference(int &y){ //y is a reference to x (the input) y+=15; return y; } int main(){ int x = 5; //passing by value passByValue(x); std::cout << "Value of x after passByValue call: " << x << std::endl; //stays the same std::cout << "Value of passByValue(x): " << passByValue(x) << std::endl; //y destroyed after function call //passing by reference int k = passByReference(x); std::cout << "Value of x after passByReference call: " << x << std::endl; //x itself changes std::cout << "Value of passByReference(x): " << k << std::endl; //passing by reference in main int z = 10; int &y = z; // y is now an alias of z and functions as a reference return 0; }
#include "../DetectMemoryLeak.h" #include "Controller.h" #include <iostream> #include "../AI FSM/Ai_1.h" #include "../Minimap/Minimap.h" #include "../Enemy.h" #include "../UIManager.h" using namespace std; const bool _CONTROLLER_DEBUG = false; Controller::Controller() : thePlayerInfo(NULL) { } Controller::~Controller() { // We just set thePlayerInfo to NULL without deleting. SceneText will delete this. if (thePlayerInfo) thePlayerInfo = NULL; } // Create this controller bool Controller::Create(Player* thePlayerInfo) { if (_CONTROLLER_DEBUG) cout << "Controller::Create()" << endl; this->thePlayerInfo = thePlayerInfo; this->controllerfunc[CONTROLLER_MOVEUP] = &Controller::MoveUp; this->controllerfunc[CONTROLLER_MOVEDOWN] = &Controller::MoveDown; this->controllerfunc[CONTROLLER_MOVELEFT] = &Controller::MoveLeft; this->controllerfunc[CONTROLLER_MOVERIGHT] = &Controller::MoveRight; this->controllerfunc[CONTROLLER_SHOOT] = &Controller::Shoot; this->controllerfunc[CONTROLLER_RELOAD] = &Controller::Reload; this->controllerfunc[CONTROLLER_CHANGE_WEAPON] = &Controller::ChangeWeapon; this->controllerfunc[CONTROLLER_SPAWN_ENEMY] = &Controller::SpawnEnemy; this->controllerfunc[CONTROLLER_ENLARGE_MAP] = &Controller::EnlargeMap; this->controllerfunc[CONTROLLER_PAUSE] = &Controller::Pause; this->controllerfunc[CONTROLLER_BLANK] = &Controller::Blank; return false; } // Read from the controller int Controller::Read(const const float deltaTime) { if (_CONTROLLER_DEBUG) cout << "Controller::Read()" << endl; return 0; } bool Controller::MoveUp(double dt) { if (!Player::GetInstance()->isDodging()) Player::GetInstance()->MoveUp(); //std::cout << "Front" << std::endl; return false; } bool Controller::MoveDown(double dt) { if (!Player::GetInstance()->isDodging()) Player::GetInstance()->MoveDown(); //std::cout << "Back" << std::endl; return false; } bool Controller::MoveLeft(double dt) { if (!Player::GetInstance()->isDodging()) Player::GetInstance()->MoveLeft(); //std::cout << "Left" << std::endl; return false; } bool Controller::MoveRight(double dt) { if (!Player::GetInstance()->isDodging()) Player::GetInstance()->MoveRight(); //std::cout << "Right" << std::endl; return false; } bool Controller::Shoot(double dt) { //if (!Player::GetInstance()->isDodging()) //Player::GetInstance()->Shoot(dt); //std::cout << "Shoot" << std::endl; return false; } bool Controller::Reload(double dt) { Player::GetInstance()->Reload(dt); //std::cout << "Reload" << std::endl; return false; } bool Controller::ChangeWeapon(double dt) { Player::GetInstance()->ChangeWeapon(dt); //std::cout << "ChangeWeapon" << std::endl; return false; } bool Controller::SpawnEnemy(double dt) { CEnemy* NewEnemy = Create::Enemy(Vector3(Math::RandFloatMinMax(-20,20), Math::RandFloatMinMax(-20,20), 0), "player"); NewEnemy->Init(); //NewEnemy->ChangeStrategy(new CStrategy_AI_1(), false); //std::cout << "Enemy Spawned" << std::endl; return false; } bool Controller::EnlargeMap(double dt) { if (!CMinimap::GetInstance()->getIsEnlarged()) { CMinimap::GetInstance()->setIsEnlarged(true); CMinimap::GetInstance()->EnlargeMap(true); return false; } else { CMinimap::GetInstance()->setIsEnlarged(false); CMinimap::GetInstance()->EnlargeMap(false); return false; } return false; } bool Controller::Pause(double dt) { UIManager::GetInstance()->Pause(); return false; } bool Controller::Blank(double dt) { if (Player::GetInstance()->GetBlanks() > 0) Player::GetInstance()->UseBlank(); return false; }
// // Created by user on 2017/2/7. // #ifndef DD_GAMES_REDISOPRS_H #define DD_GAMES_REDISOPRS_H class RedisOprs { public: static int ModUserWinCoin(int uid,int64_t coin); //赢取金币 static int ModUserWealth(int uid,int64_t coin); //财富 static int BackUpWinCoinRank(); static int BackUpWealth(); //获取当天完成的局数 static int getPlayerCompleteCount(int uid); }; #endif //DD_GAMES_REDISOPRS_H
/* Manage collection of tokens. 2013, Tivins <https://github.com/tivins> */ #include <cstdlib> #include "tokens.h" namespace v { Tokens::Tokens() { rootToken = NULL ; lastToken = NULL ; export_legend = true ; } Tokens::~Tokens() { dropAll() ; } void Tokens::add(Token * token) { if (rootToken == NULL) { rootToken = token ; lastToken = token ; } else { token->prev = lastToken ; lastToken->next = token ; lastToken = token ; } } void Tokens::dropAll() { Token * itk, * itk2 ; itk = rootToken ; while(itk != NULL) { itk2 = itk->next ; delete itk ; itk = itk2 ; } ; rootToken = 0 ; lastToken = 0 ; } static int vtkgettokendepth(Token * tk){ int d = -1; while (tk) { d++; tk = tk->parent; } return d; } void Tokens::dump(const char * filename) { FILE * debug = fopen(filename,"w+") ; if (!debug) return ; dump(debug) ; fclose(debug) ; } void Tokens::asJSON(const char *filename) { #define NL "" int i,l=0; Token * tk = rootToken; FILE * out = fopen(filename,"w+") ; if (out==NULL) out = stdout; fprintf(out,"{"); // -- legend if (export_legend) { fprintf(out,"\"legend\":["); for (i=0;i<TOKEN_FINISH;i++){ fprintf(out,"\"%s\",",Token::getTypeName(i,0)); } fprintf(out,"\"eot\""); fprintf(out,"],"); } // -- tokens fprintf(out,"\"tokens\":["NL); i=0; while (tk) { fprintf(out, "{\"id\":\"%d\",\"depth\":\"%d\",\"type\":\"%d\"," "\"subtype\":\"%d\",\"data\":\"%s\",\"pos\":\"%d,%d\"", tk->id, l, tk->type, tk->subtype, tk->data.literalUnicode().ascii(), tk->line, tk->col) ; // Browse i++; if (tk->firstChild) { fprintf(out,",\"children\":["NL); l++; tk = tk->firstChild; continue; } if (tk->next) { fprintf(out,"},"NL); tk = tk->next; continue; } if (tk->parent) { fprintf(out,"}"NL"]"NL"},"NL); l--; tk = tk->parent->next; continue; } tk = NULL; } fprintf(out,"}");//end of last object fprintf(out,"]");//end of tokens' array fprintf(out,"}");//end of global object fclose(out) ; #undef NL } void Tokens::dump(FILE * out) { char depth[32]; int i=0,l=0,k; Token * tk = rootToken; if (out==NULL) out = stdout; fprintf(out,"Tokenizer::dump\n"); while (tk) { l = vtkgettokendepth(tk); memset(depth,0,32*sizeof(char)); for (k=0;k<l;k++){ depth[k*2]='.'; depth[k*2+1]='.'; } #ifdef DEBUG_TREEFY fprintf(out,"%03d (prev %03d, next %03d, parent %03d, child %03d) %02x (%d) %s%s %s\n", tk->id, tkprevid(tk), tknextid(tk), tkparentid(tk), tkfchildid(tk), tk->type, l, depth, tk->getTypeName(), tk->data.ascii()); #else if (tk->data.isEmpty()){ fprintf(out,"%03d %s %s\n", tk->id, depth, tk->getTypeName()); }else{ fprintf(out,"%03d %s %s : %s\n", tk->id, depth, tk->getTypeName(), tk->data.ascii()); } #endif // Browse i++; if (tk->firstChild) { l++; tk = tk->firstChild; continue; } if (tk->next) { tk = tk->next; continue; } if (tk->parent) { l--; tk = tk->parent->next; continue; } tk = NULL; } } } // namespace
#include <iostream> #include <string> #include <vector> #include <array> #include <fstream> #include <sstream> #include <functional> #include <memory> #include <map> #include <cctype> #include <cassert> #define GLEW_STATIC #include <GL/glew.h> #include <SDL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/constants.hpp> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> constexpr char *IMAGE_DIR = "res/images/"; constexpr char *MESH_DIR = "res/models/"; template <typename T> struct Result { T obj; bool success = true; std::string error = ""; }; template<typename T> Result<T> errorResult(std::string error) { Result<T> result; result.success = false; result.error = error; return result; } template<typename T> Result<T> successfulResult(T obj) { Result<T> result; result.obj = std::move(obj); return result; } enum MeshLayout { NONE = 0, POS = 1 << 0, TEX = 1 << 1, NORM = 1 << 2, }; enum class MeshPrimitiveType { TRIANGLES, LINE_SEGMENTS }; struct MeshData { std::vector<GLfloat> vertices; std::vector<GLuint> indices; char layout; MeshPrimitiveType primitive_type; }; struct Vertex { glm::vec3 position; glm::vec2 texcoord; glm::vec3 normal; }; struct Mesh { GLuint vao = 0, vbo = 0, ibo = 0; int num_vertices = 0; char layout = MeshLayout::NONE; Mesh(const MeshData& mesh_data); Mesh(const Mesh &other) = delete; Mesh& operator=(const Mesh &other) = delete; Mesh(Mesh &&other) { vao = other.vao; other.vao = 0; } Mesh &operator=(Mesh &&other) { vao = other.vao; other.vao = 0; return *this; } ~Mesh(); }; struct Shader { GLuint id; GLuint vertex; GLuint fragment; GLint _model; GLint _view; GLint _projection; Shader() : id(0), vertex(0), fragment(0) {} Shader(const Shader &other) = delete; Shader& operator=(const Shader &other) = delete; Shader(Shader &&other) { moveHere(other); } Shader &operator=(Shader &&other) { moveHere(other); return *this; } ~Shader(); private: void moveHere(Shader &other) { id = other.id; vertex = other.vertex; fragment = other.fragment; _model = other._model; _view = other._view; _projection = other._projection; other.id = 0; other.vertex = 0; other.fragment = 0; } }; struct Image { unsigned char *data; int width; int height; int channels; Image(const char *filename); }; struct Texture { GLuint id; Texture(const Image &image); Texture(const Texture &other) = delete; Texture& operator=(const Texture &other) = delete; Texture(Texture &&other) { id = other.id; other.id = 0; } Texture &operator=(Texture &&other) { id = other.id; other.id = 0; return *this; } ~Texture(); }; struct PathMesh { MeshData data; std::vector<std::pair<int, int>> face_pairs; PathMesh(MeshData &mesh_data); };
#include <math.h> double breit(double m,double mr,double gamma) { double dr; { dr = mr*mr-m*m; return(gamma*gamma*m*m/(dr*dr+m*m*gamma*gamma)); } }
#include <cstdio> int main(){ int albe, rosii, verzi; scanf("%d", &albe); rosii = 2 * albe; verzi = rosii - 3; printf("%d\n", albe + rosii + verzi); return 0; }
// // Created by 송지원 on 2020-02-15. // #include <iostream> int countR(int input, int r) { int r_temp = r; int ret = 0; while (input/r_temp >= 1) { ret += (input/r_temp); r_temp *= r; } return ret; } int main() { int N; int count2, count5; scanf("%d", &N); count2 = countR(N, 2); count5 = countR(N, 5); if (count2 < count5) { printf("%d\n", count2); } else { printf("%d\n", count5); } return 0; }
#ifndef KNIGHT_H #define KNIGHT_H #include<string> #include<sstream> #include <Character.h> #include<string> #include<sstream> #include<random> #include "Character.h" #include<iostream> #include<thread> #include<vector> #include "Lance.h" using std::string; using std::stringstream; using std::cout; using std::endl; class Knight : public Character { private: static const WeaponType types; public: Knight(string name); virtual ~Knight(); Knight(const Knight& other); Knight& operator=(const Knight& other); void setWeapon(Weapon *weapon); Knight* clone()const override; string str()const override; void addHealth(); void addStrength(); void addDefense(); void addSpeed(); void addResistance(); void addMagic(); void addLuck(); void addSkill(); protected: }; #endif // KNIGHT_H
#include <iostream> #include <vector> using namespace std; const int INF = 9999, SWITCHES = 10, CLOCKS = 16; // linked[i][j] = 'x': i번 스위치와 j번 시계가 연결되어 있다. // linked[i][j] = '.': i번 스위치와 j번 시계가 연결되어 있지 않다. const char linked[SWITCHES][CLOCKS+1] = { "xxx.............", "...x...x.x.x....", "....x.....x...xx", "x...xxxx........", "......xxx.x.x...", "x.x...........xx", "...x..........xx", "....xx.x......xx", ".xxxxx..........", "...xxx...x...x.."}; // 모든 시계가 12시를 가리키고 있는지 확인한다. bool areAligned(const vector<int>& clocks){ for(int i = 0; i < CLOCKS; ++i){ if(clocks[i] != 12){ return false; } } return true; } // switch번 스위치를 누른다. void push(vector<int>& clocks, int swtch){ for(int clock = 0; clock < CLOCKS; ++clock){ if(linked[swtch][clock] == 'x'){ clocks[clock] += 3; if(clocks[clock] == 15) clocks[clock] = 3; } } } // clocks: 현재 시계들의 상태 // swtch: 이번에 누를 스위치의 번호 // 남은 스위치들을 눌러서 clocks를 12시로 맞출 수 있는 최소 횟수를 반환한다. // 만약 불가능하다면 INF 이상의 큰 수를 반환한다. int solve(vector<int>& clocks, int swtch){ if(swtch == SWITCHES) return areAligned(clocks) ? 0 : INF; // 이 스위치를 0번 누르는 경우부터 세 번 누르는 경우까지를 모두 시도한다. int ret = INF; for(int cnt = 0; cnt < 4; ++cnt){ ret = min(ret, cnt + solve(clocks, swtch + 1)); push(clocks, swtch); } // push(clocks, swtch)가 네 번 호출되었으니 clocks는 원래와 같은 상태가 된다. return ret; } int main() { int numCase = 0, result = 0; vector<int> inputClocks(CLOCKS); //cout << "테스트 케이스 수를 입력하세요 : "; cin >> numCase; //cout << inputClocks.size() << endl; while(numCase--){ //cout << "12/3/6/9 중 하나의 정수 16개를 입력하세요" << endl; for (int i = 0; i < CLOCKS; ++i) { cin >> inputClocks[i]; //cout << inputClocks[i] << endl; } result = solve(inputClocks, 0); if(result == INF){ cout << -1 << endl; } else { cout << result << endl; } inputClocks.clear(); } // cout << endl; // cout << "프로그램을 종료합니다." << endl; return 0; }
// stdafx.h: dołącz plik do standardowych systemowych plików dołączanych, // lub specyficzne dla projektu pliki dołączane, które są często wykorzystywane, ale // są rzadko zmieniane // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Wyklucz rzadko używane rzeczy z nagłówków systemu Windows // TODO: W tym miejscu odwołaj się do dodatkowych nagłówków wymaganych przez program #include <string> #include <memory> #include <unordered_map>
#include <algorithm> #include <fmt/ranges.h> #include <functional> #include <iostream> #include <range/v3/all.hpp> #include <string> #include <utility> #include <vector> int main(int argc, char *argv[]) { return 0; }
/* * License does not expire. * Can be distributed in infinitely projects * Can be distributed and / or packaged as a code or binary product (sublicensed) * * Commercial use allowed under the following conditions : * - Crediting the Author * * Can modify source-code */ /* * File: Transformation.h * Author: Suirad <darius-suirad@gmx.de> * * Created on 23. Juni 2018, 16:39 */ #ifndef TRANSFORMATION_H #define TRANSFORMATION_H #include <GL/glew.h> #include <GLM/glm.hpp> class Transformation { public: //Init Transformation With Specific Values Transformation(float posx = 0.0f, float posy = 0.0f, float posz = 0.0f, float rotx = 0.0f, float roty = 0.0f, float rotz = 0.0f, float scale = 1.0f); //Returning Actual Model Matrix glm::mat4 getModelMatrix(); //Actual Transformation Values float posx = 0.0f, posy = 0.0f, posz = 0.0f, rotx = 0.0f, roty = 0.0f, rotz = 0.0f, scale = 1.0f; private: //Actual Model Matrix glm::mat4 modelMatrix; //Actual Model Matrix Values float matrix_posx = 0.0f, matrix_posy = 0.0f, matrix_posz = 0.0f, matrix_rotx = 0.0f, matrix_roty = 0.0f, matrix_rotz = 0.0f, matrix_scale = 1.0f; }; #endif /* TRANSFORMATION_H */
#include "LogComingProc.h" #include "Logger.h" #include "HallManager.h" #include "Room.h" #include "ErrorMsg.h" #include "GameApp.h" #include "MoneyAgent.h" #include "RoundAgent.h" #include "GameCmd.h" #include "Protocol.h" #include "ProcessManager.h" #include "BaseClientHandler.h" #include "ProtocolServerId.h" #include "CoinConf.h" struct Param { int uid; int tid; short source; char name[64]; char json[1024]; }; LogComingProc::LogComingProc() { this->name = "LogComingProc"; } LogComingProc::~LogComingProc() { } int LogComingProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt ) { //_NOTUSED(pt); int cmd = pPacket->GetCmdType(); short seq = pPacket->GetSeqNum(); short source = pPacket->GetSource(); int uid = pPacket->ReadInt(); string name = pPacket->ReadString(); int tid = pPacket->ReadInt(); int64_t m_lMoney = pPacket->ReadInt64(); short level = pPacket->ReadShort(); string json = pPacket->ReadString(); _LOG_INFO_("==>[LogComingProc] cmd[0x%04x] uid[%d]\n", cmd, uid); _LOG_DEBUG_("[DATA Parse] tid=[%d]\n", tid); _LOG_DEBUG_("[DATA Parse] name=[%s] \n", name.c_str()); _LOG_DEBUG_("[DATA Parse] m_lMoney=[%lu] \n", m_lMoney); _LOG_DEBUG_("[DATA Parse] json=[%s] \n", json.c_str()); BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler); if(level != Configure::getInstance()->m_nLevel && GAME_ID != E_BULL_2017) { _LOG_ERROR_("Level[%d] is not equal Servertype[%d]\n", level, Configure::getInstance()->m_nLevel); return sendErrorMsg(hallhandler, cmd, uid, -3,ErrorMsg::getInstance()->getErrMsg(-3),seq); } MoneyAgent* connect = MoneyServer(); OutputPacket response; response.Begin(cmd, uid); response.SetSeqNum(pt->seq); response.WriteInt(uid); response.WriteShort(Configure::getInstance()->m_nServerId); response.End(); pt->seq = seq; if (source == 30) goto __ROBOT_LOGIN__; if (connect->Send(&response) >= 0) { _LOG_DEBUG_("Transfer request to Back_MYSQLServer OK\n"); struct Param* param = (struct Param *) malloc (sizeof(struct Param));; param->uid = uid; param->tid = tid; param->source = source; strncpy(param->name, name.c_str(),63); param->name[63] = '\0'; //strncpy(param->password, password.c_str(), 31); //param->password[31] = '\0'; strncpy(param->json, json.c_str(), 1023); param->json[1023] = '\0'; pt->data = param; return 1; } else { _LOG_ERROR_("==>[LoginComingProc] [0x%04x] uid=[%d] ERROR:[%s]\n", cmd, uid, "Send request to BackServer Error"); return -1; } __ROBOT_LOGIN__: Room* room = Room::getInstance(); Table *table = room->getTable(); if(table == NULL) { _LOG_WARN_("[This Table is NULL] \n"); return sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),pt->seq); } Player* player = table->isUserInTab(uid); if(player==NULL) { player = room->getAvailablePlayer(); if(player == NULL) { _LOG_ERROR_("[Room is full,no seat for player] \n" ); return sendErrorMsg(hallhandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),pt->seq); } if (!player->checkMoney(m_lMoney)) { ULOGGER(E_LOG_ERROR, uid) << "Not enough money to enter, lower_money = " << CoinConf::getInstance()->getCoinCfg()->minmoney << ", owned_money = " << player->m_lMoney; return sendErrorMsg(clientHandler, cmd, uid, -13, ERRMSG(-13), seq); } player->id = uid; player->m_lMoney = m_lMoney; player->m_nHallid = hallhandler->hallid; strncpy(player->name, name.c_str(), sizeof(player->name) - 1); player->name[sizeof(player->name) - 1] = '\0'; strcpy(player->json, json.c_str()); player->source = source; _LOG_INFO_("[LogComingProc] UID=[%d] NorLogin OK ,m_nSeatID[%d]\n", player->id,player->m_nSeatID ); player->login(); if(table->playerComming(player) != 0) { _LOG_WARN_("Player[%d] Coming This table[%d] Error\n", player->id, table->id); return sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),pt->seq); } } player->source = E_MSG_SOURCE_ROBOT; player->setActiveTime(time(NULL)); sendTabePlayersInfo(table, player, seq); return 0; } int LogComingProc::sendTabePlayersInfo(Table* table, Player* player, short seq) { short timeout = 0; if (table->isIdle()) { timeout = Configure::getInstance()->idletime - (time(NULL) - table->getStatusTime()); } else if (table->isBet()) { timeout = Configure::getInstance()->bettime - (time(NULL) - table->getStatusTime()); } else if (table->isOpen()) { timeout = Configure::getInstance()->opentime - (time(NULL) - table->getStatusTime()); } OutputPacket response; response.Begin(CLIENT_MSG_LOGINCOMING, player->id); response.SetSeqNum(seq); response.WriteShort(Configure::getInstance()->m_nLevel); response.WriteString("ok"); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(table->id); response.WriteShort(table->m_nStatus); response.WriteInt(player->id); response.WriteShort(table->m_nCountPlayer); response.WriteShort(player->m_nSeatID); response.WriteInt64(player->m_lMoney); response.WriteByte(timeout); response.WriteString(player->json); Player* banker = NULL; if(table->bankersid >=0) banker = table->player_array[table->bankersid]; response.WriteInt(banker ? banker->id : 0); response.WriteShort(banker ? banker->m_nSeatID : -1); response.WriteInt64(banker ? banker->m_lMoney : 0); response.WriteString(banker ? banker->name : ""); response.WriteString(banker ? banker->json : ""); response.WriteByte(CoinConf::getInstance()->getCoinCfg()->bankernumplayer - table->bankernum); for(int i = 1; i < 5; ++i) { response.WriteInt64(table->m_lTabBetArray[i]); } response.WriteByte(10); response.WriteInt(table->m_nLimitCoin); response.End(); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[LoginComingProc] Send To Uid[%d] Error!\n", player->id); _LOG_DEBUG_("<==[LogComingProc] Push [0x%04x]\n", CLIENT_MSG_LOGINCOMING); _LOG_DEBUG_("[Data Response] push to uid=[%d]\n", player->id); _LOG_DEBUG_("[Data Response] push to m_nStatus=[%d]\n", player->m_nStatus); _LOG_DEBUG_("[Data Response] tid=[%d]\n", table->id); _LOG_DEBUG_("[Data Response] tstatus=[%d]\n", table->m_nStatus); _LOG_DEBUG_("[Data Response] m_nSeatID=[%d]\n", player->m_nSeatID); _LOG_DEBUG_("[Data Response] comuid=[%d]\n", player->id); _LOG_DEBUG_("[Data Response] timeout=[%d]\n", timeout); _LOG_DEBUG_("[Data Response] banker=[%d]\n", banker ? banker->id : 0); _LOG_DEBUG_("[Data Response] m_nLimitCoin=[%d]\n", table->m_nLimitCoin); return 0; } int LogComingProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); if(pt==NULL) { _LOG_ERROR_("[LoginComingProc:doResponse]Context is NULL\n"); return -1; } if(pt->client == NULL) { _LOG_ERROR_("[LoginComingProc:doResponse]Context is client NULL\n"); return -1; } BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (pt->client); struct Param* param = (struct Param*)pt->data; int uid = param->uid; int tid = param->tid; short source = param->source; string name = string(param->name); string json = string(param->json); short cmd = inputPacket->GetCmdType(); short retno = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); if (retno != 0) { _LOG_ERROR_("[%s:%s:%d]Select User Score Info Error[%d]:[%s]\n", __FILE__, __FUNCTION__, __LINE__, retno, retmsg.c_str()); sendErrorMsg(hallhandler, cmd, uid, -1, (char*)retmsg.c_str(),pt->seq); return -1; } uid = inputPacket->ReadInt(); int64_t money = inputPacket->ReadInt64(); int64_t safemoney = inputPacket->ReadInt64(); int roll = inputPacket->ReadInt(); int roll1 = inputPacket->ReadInt(); int coin = inputPacket->ReadInt(); int exp = inputPacket->ReadInt(); _LOG_DEBUG_("[DATA Parse] money=[%ld]\n", money); _LOG_DEBUG_("[DATA Parse] safemoney=[%ld]\n", safemoney); _LOG_DEBUG_("[DATA Parse] roll=[%d]\n", roll); _LOG_DEBUG_("[DATA Parse] roll1=[%d]\n", roll1); _LOG_DEBUG_("[DATA Parse] coin=[%d]\n", coin); _LOG_DEBUG_("[DATA Parse] exp=[%d]\n", exp); Room* room = Room::getInstance(); Table *table = room->getTable(); if(table == NULL) { _LOG_WARN_("[This Table is NULL] \n"); return sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),pt->seq); } Player* player = table->isUserInTab(uid); if(player==NULL) { player = room->getAvailablePlayer(); if(player == NULL) { _LOG_ERROR_("[Room is full,no seat for player] \n" ); return sendErrorMsg(hallhandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),pt->seq); } if (!player->checkMoney(money)) { ULOGGER(E_LOG_ERROR, uid) << "Not enough money to enter, lower_money = " << CoinConf::getInstance()->getCoinCfg()->minmoney << ", owned_money = " << player->m_lMoney; return sendErrorMsg(hallhandler, cmd, uid, -13, ERRMSG(-13), pt->seq); } player->id = uid; player->m_lMoney = money; player->m_nHallid = hallhandler->hallid; strncpy(player->name, name.c_str(), sizeof(player->name) - 1); player->name[sizeof(player->name) - 1] = '\0'; strcpy(player->json, json.c_str()); player->source = source; player->m_nRoll = roll + roll1; player->m_nExp = exp; player->login(); _LOG_INFO_("[LogComingProc] UID=[%d] NorLogin OK ,m_nSeatID[%d]\n", player->id,player->m_nSeatID ); if(table->playerComming(player) != 0) { _LOG_WARN_("Player[%d] Coming This table[%d] Error\n", player->id, table->id); return sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),pt->seq); } } player->setActiveTime(time(NULL)); if(player->source != 30) { if(RoundServer()->GetRoundInfo(player->id, table->id) < 0) _LOG_ERROR_("[RoundServerConnect send Error uid[%d]]\n", player->id); } sendTabePlayersInfo(table, player, pt->seq); table->SendSeatInfo(player); return 0; } REGISTER_PROCESS(CLIENT_MSG_LOGINCOMING, LogComingProc)
//本题为混合背包模板 //把多重背包和完全背包合体即可 //可以将完全背包的次数设为极大值 //并将多重背包二进制拆分,来优化时间 #include<cstdio> #include<algorithm> using namespace std; int n,t; int hs,ms,he,me; int w[10010],v[10010],s[10010]; int f[1000010]; int w1[1000010],v1[1000010]; int num; void time(); void brick(int); int main() { scanf("%d:%d %d:%d",&hs,&ms,&he,&me); time(); scanf("%d",&n); for(int i=1;i<=n;i++)//输入并拆分 { scanf("%d%d%d",&w[i],&v[i],&s[i]); if(!s[i])s[i]=9999999;//将完全背包的次数设为极大值 brick(i); } for(int i=1;i<=num;i++)//dp,多重背包模板 for(int j=t;j>=w1[i];j--) f[j]=max(f[j],f[j-w1[i]]+v1[i]); printf("%d",f[t]); } //-------------------------------------------------------- void time()//计算时间 { if(me<ms) { t+=(me+60-ms); he-=1; t+=(60*(he-hs)); } else t+=((60*(he-hs))+(me-ms)); } void brick(int i)//二进制拆分 { for(int j=1;j<=s[i];j*=2) { v1[++num]=j*v[i]; w1[num]=j*w[i]; s[i]-=j; } if(s[i]) { v1[++num]=s[i]*v[i]; w1[num]=s[i]*w[i]; } }
// // Copyright 2014 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Paulo Coutinho <paulo@prsolucoes.com> // This provides a method to load and unload JNI in Djinni context // Include it if your app already have a JNI_OnLoad and/or JNI_OnUnload // methods // You can call it from Java after load your library (.so) and call // unload when your library is unloaded or application terminated. #include "djinni/jni/djinni_support.hpp" CJNIEXPORT void JNICALL Java_com_dropbox_djinni_JNILoader_load(JNIEnv *env, jobject /*this*/, jlong nativeRef) { JavaVM *jvm; env->GetJavaVM(&jvm); djinni::jniInit(jvm); } CJNIEXPORT void JNICALL Java_com_dropbox_djinni_JNILoader_unload(JNIEnv *env, jobject /*this*/, jlong nativeRef) { djinni::jniShutdown(); }
#include "gtest/gtest.h" #define QP_SOLVER_PRINTING #define QP_SOLVER_USE_SPARSE #include "solvers/qp_solver.hpp" using namespace qp_solver; class SimpleQP : public QP<2, 3, double> { public: Eigen::Matrix<double, 2, 1> SOLUTION; SimpleQP() { Eigen::MatrixXd P(2,2); Eigen::MatrixXd A(3,2); P << 4, 1, 1, 2; A << 1, 1, 1, 0, 0, 1; this->P = P.sparseView(); this->P_col_nnz << 2, 2; this->q << 1, 1; this->A = A.sparseView(); this->A_col_nnz << 2, 2; this->l << 1, 0, 0; this->u << 1, 0.7, 0.7; this->SOLUTION << 0.3, 0.7; } }; TEST(QPSolverSparseTest, testSimpleQP) { SimpleQP qp; QPSolver<SimpleQP> prob; prob.settings().max_iter = 1000; prob.settings().adaptive_rho = true; prob.settings().verbose = true; prob.setup(qp); prob.solve(qp); Eigen::Vector2d sol = prob.primal_solution(); EXPECT_TRUE(sol.isApprox(qp.SOLUTION, 1e-2)); EXPECT_LT(prob.iter, prob.settings().max_iter); EXPECT_EQ(prob.info().status, SOLVED); } TEST(QPSolverSparseTest, testConjugateGradient) { SimpleQP qp; QPSolver<SimpleQP, Eigen::ConjugateGradient, Eigen::Lower | Eigen::Upper> prob; prob.settings().max_iter = 1000; prob.settings().adaptive_rho = true; prob.settings().verbose = true; prob.setup(qp); prob.solve(qp); Eigen::Vector2d sol = prob.primal_solution(); EXPECT_TRUE(sol.isApprox(qp.SOLUTION, 1e-2)); EXPECT_LT(prob.iter, prob.settings().max_iter); EXPECT_EQ(prob.info().status, SOLVED); } TEST(QPSolverSparseTest, testCanMultipleSolve) { SimpleQP qp; QPSolver<SimpleQP> prob; prob.setup(qp); prob.solve(qp); EXPECT_EQ(prob.info().status, SOLVED); prob.solve(qp); EXPECT_EQ(prob.info().status, SOLVED); } TEST(QPSolverSparseTest, testCanUpdateQP) { SimpleQP qp; QPSolver<SimpleQP> prob; prob.setup(qp); prob.solve(qp); EXPECT_TRUE(prob.primal_solution().isApprox(qp.SOLUTION, 1e-2)); EXPECT_EQ(prob.info().status, SOLVED); qp.P.setIdentity(); // dont't change P_col_nnz! qp.q << 0, 0; qp.SOLUTION << 0.5, 0.5; prob.update_qp(qp); prob.solve(qp); EXPECT_TRUE(prob.primal_solution().isApprox(qp.SOLUTION, 1e-2)); EXPECT_EQ(prob.info().status, SOLVED); }
#include "admin.h" #include "ui_admin.h" #include "database.h" #include <QSqlDatabase> #include <QDebug> #include <QMessageBox> #include <QSqlError> #include <QSqlQuery> //sql语句 #include <QVariantList> #include <QPushButton> Admin::Admin(QWidget *parent) : QWidget(parent), ui(new Ui::Admin) { ui->setupUi(this); setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint); // 禁止最大化按钮 setFixedSize(754,458); // 禁止拖动窗口大小 setWindowTitle("系统管理"); standItemModel = new QStandardItemModel(); standItemModel->setColumnCount(5); standItemModel->setHeaderData(0,Qt::Horizontal,QStringLiteral("账号")); //设置表头内容 standItemModel->setHeaderData(1,Qt::Horizontal,QStringLiteral("姓名")); standItemModel->setHeaderData(2,Qt::Horizontal,QStringLiteral("密码")); standItemModel->setHeaderData(3,Qt::Horizontal,QStringLiteral("权限")); standItemModel->setHeaderData(4,Qt::Horizontal,QStringLiteral("管理")); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); //设置表格属性只读,不能编辑 ui->tableView->setModel(standItemModel); //挂载表格模型 loadInfo(); } int Admin::loadInfo() { //从数据库中加载订单 QSqlQuery query; query.exec("select * from user"); int i=0; while(query.next()) //一行一行遍历 { QString re; if(query.value("gro").toInt()==0) { re = "管理员"; } else { re = "普通用户"; } ID_ *temp = new ID_; temp->num = i; temp->id=query.value("id").toString(); idList.append(temp); QStandardItem *standItem1 = new QStandardItem(tr("%1").arg(query.value("id").toString())); QStandardItem *standItem2 = new QStandardItem(tr("%1").arg(query.value("name").toString())); QStandardItem *standItem3 = new QStandardItem(tr("%1").arg(query.value("password").toString())); QStandardItem *standItem4 = new QStandardItem(tr("%1").arg(re)); standItemModel->setItem(i,0,standItem1); //表格第i行,第0列添加一项内容 //standItemModel->item(i,0)->setForeground(QBrush(QColor(255,0,0))); //设置字符颜色 standItemModel->item(i,0)->setTextAlignment(Qt::AlignCenter); //设置表格内容居中 standItemModel->setItem(i,1,standItem2); //表格第i行,第1列添加一项内容 standItemModel->setItem(i,2,standItem3); standItemModel->setItem(i,3,standItem4); QPushButton *m_PushButton=new QPushButton; m_PushButton->setText(QStringLiteral("删除")); ui->tableView->setIndexWidget(standItemModel->index(i,4),m_PushButton); //向表格单元添加一个控件 connect(m_PushButton,&QPushButton::clicked, [=]() { qDebug()<<i; QSqlQuery query; QString sql = QString("delete from user where id = %1;").arg(numToId(i)); if(query.exec(sql)) { //从数据库中删除成功 qDebug()<<"删除 "<<sql; QMessageBox::warning(this,QStringLiteral("提示"),QStringLiteral("删除成功")); standItemModel->removeRow(i); //删除从第0行开始的连续10行 }else { //删除失败 QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("删除失败")); } } ); i++; } return i; } QString Admin::numToId(int num) { for(int i=0;i<idList.size();i++) { qDebug()<<idList.at(i)->num<<"id:"<<idList.at(i)->id; } QString id = "-1"; for(int i=0;i<idList.size();i++) { if(idList.at(i)->num == num) { id = idList.at(i)->id; } } return id; } Admin::~Admin() { delete ui; } void Admin::on_add_clicked() { //添加用户 if(ui->id->text()!=""&&ui->password->text()!=""&&ui->name->text()!="") { //信息完整 int adm; if(ui->ad->currentText()=="管理员") { adm = 0; } else { adm=1; } QSqlQuery query; QString sql = QString("insert into user(id, name, password,gro) values(%1,'%2','%3',%4);") .arg(ui->id->text()).arg(ui->name->text()).arg(ui->password->text()) .arg(adm); if(query.exec(sql)) { QMessageBox::warning(this,QStringLiteral("提示"),QStringLiteral("添加成功")); ui->id->clear(); ui->name->clear(); ui->password->clear(); loadInfo(); }else{ QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("添加失败")); } }else { QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("请填写完整信息")); } } void Admin::on_add_2_clicked() { this->close(); }
#include <Windows.h> #include <cstdint> #include <iostream> #include <iomanip> #include <cstdio> #include <random> #include <functional> #include <stdexcept> #include <algorithm> #include "CWTCore.h" using namespace CWT; // Suppress MSVC-specific strdup deprecation warning for pybind11. #define strdup _strdup #include <pybind11/embed.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> namespace py = pybind11; // Open new console for c(in/out/err) void OpenConsole() { AllocConsole(); FILE* cinStream; FILE* coutStream; FILE* cerrStream; freopen_s(&cinStream, "CONIN$", "r", stdin); freopen_s(&coutStream, "CONOUT$", "w", stdout); freopen_s(&cerrStream, "CONOUT$", "w", stderr); std::cout.clear(); std::cin.clear(); std::cerr.clear(); /* // https://stackoverflow.com/a/57241985: // std::wcout, std::wclog, std::wcerr, std::wcin HANDLE hConOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE hConIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); SetStdHandle(STD_OUTPUT_HANDLE, hConOut); SetStdHandle(STD_ERROR_HANDLE, hConOut); SetStdHandle(STD_INPUT_HANDLE, hConIn); std::wcout.clear(); std::wclog.clear(); std::wcerr.clear(); std::wcin.clear(); */ } PYBIND11_EMBEDDED_MODULE(cube, m) { py::class_<Vector2<int32_t>>(m, "Vector2_int32") .def_readwrite("X", &Vector2<int32_t>::X) .def_readwrite("Y", &Vector2<int32_t>::Y); py::class_<Vector3<int32_t>>(m, "Vector3_int32") .def_readwrite("X", &Vector3<int32_t>::X) .def_readwrite("Y", &Vector3<int32_t>::Y) .def_readwrite("Z", &Vector3<int32_t>::Z); py::class_<Vector3<float>>(m, "Vector3_float32") .def_readwrite("X", &Vector3<float>::X) .def_readwrite("Y", &Vector3<float>::Y) .def_readwrite("Z", &Vector3<float>::Z); py::class_<Vector3<int64_t>>(m, "Vector3_int64") .def_readwrite("X", &Vector3<int64_t>::X) .def_readwrite("Y", &Vector3<int64_t>::Y) .def_readwrite("Z", &Vector3<int64_t>::Z); py::class_<cube::Item>(m, "Item") .def_readwrite("category", &cube::Item::category) .def_readwrite("id", &cube::Item::id) .def_readwrite("model", &cube::Item::model) .def_readwrite("region_x", &cube::Item::region_x) .def_readwrite("region_y", &cube::Item::region_y) .def_readwrite("stars", &cube::Item::stars) .def_readwrite("field_18", &cube::Item::field_18) .def_readwrite("material", &cube::Item::material) //.def_readwrite("customizations", &cube::Item::customizations) .def_readwrite("customization_count", &cube::Item::customization_count) .def_readwrite("field_9E", &cube::Item::field_9E) .def_readwrite("field_9F", &cube::Item::field_9F); py::class_<cube::WornEquipment>(m, "WornEquipment") .def_readwrite("mystery_near_neck", &cube::WornEquipment::mystery_near_neck) .def_readwrite("neck", &cube::WornEquipment::neck) .def_readwrite("chest", &cube::WornEquipment::chest) .def_readwrite("feet", &cube::WornEquipment::feet) .def_readwrite("hands", &cube::WornEquipment::hands) .def_readwrite("shoulder", &cube::WornEquipment::shoulder) .def_readwrite("weapon_left", &cube::WornEquipment::weapon_left) .def_readwrite("weapon_right", &cube::WornEquipment::weapon_right) .def_readwrite("ring_left", &cube::WornEquipment::ring_left) .def_readwrite("ring_right", &cube::WornEquipment::ring_right) .def_readwrite("pet", &cube::WornEquipment::pet); py::class_<cube::EntityData::Appearance>(m, "Appearance") .def_readwrite("hair_color_r", &cube::EntityData::Appearance::hair_color_r) .def_readwrite("hair_color_g", &cube::EntityData::Appearance::hair_color_g) .def_readwrite("hair_color_b", &cube::EntityData::Appearance::hair_color_b) .def_readwrite("movement_flags", &cube::EntityData::Appearance::movement_flags) .def_readwrite("graphical_size", &cube::EntityData::Appearance::graphical_size) .def_readwrite("hitbox_size", &cube::EntityData::Appearance::hitbox_size) .def_readwrite("physical_size", &cube::EntityData::Appearance::physical_size) .def_readwrite("face_id", &cube::EntityData::Appearance::face_id) .def_readwrite("hair_id", &cube::EntityData::Appearance::hair_id) .def_readwrite("hands_id", &cube::EntityData::Appearance::hands_id) .def_readwrite("feet_id", &cube::EntityData::Appearance::feet_id) .def_readwrite("chest_id", &cube::EntityData::Appearance::chest_id) .def_readwrite("tail_id", &cube::EntityData::Appearance::tail_id) .def_readwrite("shoulder_id", &cube::EntityData::Appearance::shoulder_id) .def_readwrite("wings_id", &cube::EntityData::Appearance::wings_id) .def_readwrite("head_scale", &cube::EntityData::Appearance::head_scale) .def_readwrite("chest_scale", &cube::EntityData::Appearance::chest_scale) .def_readwrite("hand_scale", &cube::EntityData::Appearance::hand_scale) .def_readwrite("feet_scale", &cube::EntityData::Appearance::feet_scale) .def_readwrite("unk_scale", &cube::EntityData::Appearance::unk_scale) .def_readwrite("weapon_scale", &cube::EntityData::Appearance::weapon_scale) .def_readwrite("tail_scale", &cube::EntityData::Appearance::tail_scale) .def_readwrite("shoulder_scale", &cube::EntityData::Appearance::shoulder_scale) .def_readwrite("wings_scale", &cube::EntityData::Appearance::wings_scale) .def_readwrite("maybe_chest_rotation", &cube::EntityData::Appearance::maybe_chest_rotation) .def_readwrite("hands_rotation", &cube::EntityData::Appearance::hands_rotation) .def_readwrite("wings_rotation", &cube::EntityData::Appearance::wings_rotation) .def_readwrite("chest_position", &cube::EntityData::Appearance::chest_position) .def_readwrite("head_position", &cube::EntityData::Appearance::head_position) .def_readwrite("hands_position", &cube::EntityData::Appearance::hands_position) .def_readwrite("feet_position", &cube::EntityData::Appearance::feet_position) .def_readwrite("unk_position", &cube::EntityData::Appearance::unk_position) .def_readwrite("wings_position", &cube::EntityData::Appearance::wings_position); py::class_<cube::EntityData>(m, "EntityData") .def_readwrite("position", &cube::EntityData::position) .def_readwrite("rotation", &cube::EntityData::rotation) .def_readwrite("velocity", &cube::EntityData::velocity) .def_readwrite("accel", &cube::EntityData::accel) .def_readwrite("retreat", &cube::EntityData::retreat) .def_readwrite("head_rotation", &cube::EntityData::head_rotation) .def_readwrite("physics_flags", &cube::EntityData::physics_flags) .def_readwrite("hostility_or_ai_type", &cube::EntityData::hostility_or_ai_type) .def_readwrite("race", &cube::EntityData::race) .def_readwrite("action_id", &cube::EntityData::action_id) .def_readwrite("action_timer", &cube::EntityData::action_timer) .def_readwrite("combo_hits", &cube::EntityData::combo_hits) .def_readwrite("time_since_last_combo_hit", &cube::EntityData::time_since_last_combo_hit) .def_readwrite("appearance", &cube::EntityData::appearance) .def_readwrite("binary_toggles", &cube::EntityData::binary_toggles) .def_readwrite("roll_time", &cube::EntityData::roll_time) .def_readwrite("stun_time", &cube::EntityData::stun_time) .def_readwrite("some_animation_time", &cube::EntityData::some_animation_time) .def_readwrite("speed_slowed_time", &cube::EntityData::speed_slowed_time) .def_readwrite("speed_boosted_time", &cube::EntityData::speed_boosted_time) .def_readwrite("level", &cube::EntityData::level) .def_readwrite("exp", &cube::EntityData::exp) .def_readwrite("job_class", &cube::EntityData::job_class) .def_readwrite("specialization", &cube::EntityData::specialization) .def_readwrite("camera_looking_at_block_offset", &cube::EntityData::camera_looking_at_block_offset) .def_readwrite("hp", &cube::EntityData::hp) .def_readwrite("mp", &cube::EntityData::mp) .def_readwrite("stealth", &cube::EntityData::stealth) .def_readwrite("current_movement_type_speed", &cube::EntityData::current_movement_type_speed) .def_readwrite("light_diameter", &cube::EntityData::light_diameter) .def_readwrite("eagle_flying_to_zone_pos", &cube::EntityData::eagle_flying_to_zone_pos) .def_readwrite("eagle_flying_from_coords", &cube::EntityData::eagle_flying_from_coords) .def_readwrite("some_unk_item", &cube::EntityData::some_unk_item) .def_readwrite("worn_equipment", &cube::EntityData::worn_equipment) .def_property("name", [](const cube::EntityData& e) -> std::string { // getter return std::string(e.name); }, [](cube::EntityData& e, const std::string& name) { // setter std::memcpy(e.name, name.c_str(), 16); e.name[15] = '\x00'; } ) .def_readwrite("client_steam_ID", &cube::EntityData::client_steam_ID); py::class_<cube::Creature>(m, "Creature") .def_static("new", [](uint64_t guid) { uint64_t tmp_guid = guid; return cube::Creature::New(&tmp_guid); }, py::return_value_policy::reference ) .def_readwrite("guid", &cube::Creature::guid) .def_readwrite("entity_data", &cube::Creature::entity_data) .def_readwrite("buffs", &cube::Creature::buffs, py::return_value_policy::reference) .def_readwrite("character_height_bob", &cube::Creature::character_height_bob) .def_readwrite("on_damage_flash_effect", &cube::Creature::on_damage_flash_effect) .def_readwrite("stamina", &cube::Creature::stamina) .def_readwrite("pet_guid", &cube::Creature::pet_guid) //.def_readwrite("inventories", &cube::Creature::inventories) .def_readwrite("entity_data", &cube::Creature::entity_data) .def_readwrite("unk_item", &cube::Creature::unk_item) .def_readwrite("gold", &cube::Creature::gold) .def_readwrite("climbing_speed", &cube::Creature::climbing_speed) .def_readwrite("swimming_speed", &cube::Creature::swimming_speed) .def_readwrite("diving_skill", &cube::Creature::diving_skill) .def_readwrite("riding_speed", &cube::Creature::riding_speed) .def_readwrite("hang_gliding_speed", &cube::Creature::hang_gliding_speed) .def_readwrite("sailing_speed", &cube::Creature::sailing_speed) .def_readwrite("light_diameter", &cube::Creature::light_diameter); //.def_readwrite("animation_state", &cube::Creature::animation_state) py::class_<cube::World>(m, "World") .def_readwrite("local_player", &cube::World::local_player, py::return_value_policy::reference) .def_readwrite("creatures_list", &cube::World::creatures_list, py::return_value_policy::reference); py::class_<cube::Game>(m, "Game") .def_readwrite("seed", &cube::Game::seed) .def_readonly("world", &cube::Game::world, py::return_value_policy::reference); m.def("get_game", &CWT::GetGamePtr, py::return_value_policy::reference); } DWORD WINAPI MyFunc(LPVOID lpvParam) { OpenConsole(); std::cout << "Opened console" << std::endl; CWT::InitCWT(); // Wait until cube::Game is initialized. cube::Game* game = nullptr; while (game == nullptr) { game = CWT::GetGamePtr(); Sleep(250); } std::cout << "Got game" << std::endl; // Create our python interpreter. py::initialize_interpreter(); while (true) { // Run script.py if the user is pressing the Y key. if (GetAsyncKeyState((int)'Y') & 0x8000) { std::cout << "Running Python script!" << std::endl; try { py::eval_file("script.py"); } catch (std::exception const& e) { std::cout << e.what() << std::endl; } Sleep(2000); } Sleep(250); } // Close our python interpreter. py::finalize_interpreter(); return 0; }; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: CreateThread(NULL, 0, MyFunc, 0, 0, NULL); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2006-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Patryk Obara */ #include "core/pch.h" #ifdef GADGET_SUPPORT #include "x11_gadget.h" #include "x11_atomizer.h" #include "x11_globals.h" #include "x11_ipcmanager.h" #include "platforms/utilix/x11_all.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/windows/DesktopGadget.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" #include "adjunct/widgetruntime/GadgetStartup.h" using X11Types::Atom; static int num_x11_gadget = 0; X11Gadget::X11Gadget(X11OpWindow* op_window, OpWindow::Style style) : X11WindowWidget(op_window) , m_window_flags(0) { if (style == OpWindow::STYLE_GADGET) m_window_flags = X11Widget::TRANSPARENT|X11Widget::NODECORATION; num_x11_gadget++; } X11Gadget::~X11Gadget() { num_x11_gadget--; } OP_STATUS X11Gadget::Init(X11Widget *parent, const char *name, int flags) { RETURN_IF_ERROR( X11WindowWidget::Init(parent, name, m_window_flags|flags) ); SetWindowRole("widget"); #ifdef WIDGET_RUNTIME_SUPPORT X11IPCManager::Init(GetWindowHandle()); #endif // WIDGET_RUNTIME_SUPPORT return OpStatus::OK; } bool X11Gadget::HandleEvent(XEvent* event) { if (GadgetStartup::IsGadgetStartupRequested()) { switch (event->type) { case LeaveNotify: { // hack; we have to shoot straight to DesktopGadget atm DesktopWindow *dw = g_application->GetActiveDesktopWindow(TRUE); DesktopGadget *dg = static_cast<DesktopGadget*>(dw); if (dg) { dg->OnMouseGadgetLeave(NULL); return true; } } break; case PropertyNotify: { // Workaround for metacity not being able to un-minimize gadget properly (DSK-285640) // This must not be done for decorated gadgets (DSK-304431) if (event->xproperty.atom == ATOMIZE(_NET_WM_STATE) && !g_x11->IsCompositingManagerActive(m_screen) && GetOpWindow() && GetOpWindow()->GetStyle() != OpWindow::STYLE_DECORATED_GADGET) { X11Types::Atom rettype; int format; unsigned long nitems; unsigned long bytes_remaining; unsigned char *data = 0; int rc = XGetWindowProperty(GetDisplay(), GetWindowHandle(), event->xproperty.atom, 0, 10, False, AnyPropertyType, &rettype, &format, &nitems, &bytes_remaining, &data); if (rc == Success && data && rettype == XA_ATOM && format == 32 && nitems > 0) { X11Types::Atom *state = (X11Types::Atom *)data; bool hidden = false; bool skip_taskbar = false; bool below = false; bool above = false; for (unsigned long i=0; i<nitems; i++) { X11Types::Atom cur = state[i]; if (cur == ATOMIZE(_NET_WM_STATE_HIDDEN)) hidden = true; else if (cur == ATOMIZE(_NET_WM_STATE_SKIP_TASKBAR)) skip_taskbar = true; else if (cur == ATOMIZE(_NET_WM_STATE_BELOW)) below = true; else if (cur == ATOMIZE(_NET_WM_STATE_ABOVE)) above = true; } bool normal = !below && !above; if (skip_taskbar && (hidden || normal)) SetWMSkipTaskbar(false); else if (!skip_taskbar && !hidden && !normal) SetWMSkipTaskbar(true); } if (data) XFree(data); } } break; } } return X11WindowWidget::HandleEvent(event); } // static DesktopWindow* X11Gadget::GetDesktopWindow() { // what we should do in here is search through desktop window collection, // find one created with this opwindow and return it here // however GadgetApplication does not maintain proper collection // and we have to keep DesktopWindow structure b0rken because // of Unite dependency. So for now, this is enough. [pobara 2010-02-26] return g_application->GetActiveDesktopWindow(TRUE); } #endif // GADGET_SUPPORT
#include <string> #include <iostream> #include <vector> #include <algorithm> #include "dat.hpp" /******* * DAT * *******/ // CONSTRUCTORS Dat::Dat(std::string filename, bool loadWork) : numberParticles(), persistenceLength(), packingFraction(), systemSize(), torqueParameter(), randomSeed(), timeStep(), framesWork(), dumpParticles(), dumpPeriod(), input(filename) { // HEADER INFORMATION input.read<const int>(&numberParticles); input.read<const double>(&persistenceLength); input.read<const double>(&packingFraction); input.read<const double>(&systemSize); input.read<const double>(&torqueParameter); input.read<const int>(&randomSeed); input.read<const double>(&timeStep); input.read<const int>(&framesWork); input.read<const bool>(&dumpParticles); input.read<const int>(&dumpPeriod); // FILE PARTS LENGTHS headerLength = input.tellg(); particleLength = 5*sizeof(double)*dumpParticles; frameLength = numberParticles*particleLength; workLength = 8*sizeof(double); // ESTIMATION OF NUMBER OF COMPUTED WORK AND ORDER PARAMETER SUMS AND FRAMES numberWork = (input.getFileSize() - headerLength - frameLength)/( framesWork*frameLength + workLength); frames = !dumpParticles ? 0 : (input.getFileSize() - headerLength - numberWork*workLength)/frameLength; // FILE CORRUPTION CHECK if ( input.getFileSize() != headerLength + frames*frameLength + numberWork*workLength ) { std::cerr << "Invalid file size." << std::endl; exit(1); } // ACTIVE WORK AND ORDER PARAMETER if ( loadWork ) { double work; for (int i=0; i < numberWork; i++) { input.read<double>(&work, headerLength // header + frameLength // frame with index 0 + (1 + i)*framesWork*frameLength // all following packs of framesWork frames + i*workLength); // previous values of the active work activeWork.push_back(work); input.read<double>(&work); activeWorkForce.push_back(work); input.read<double>(&work); activeWorkOri.push_back(work); input.read<double>(&work); orderParameter.push_back(work); input.read<double>(&work); orderParameter0.push_back(work); input.read<double>(&work); orderParameter1.push_back(work); input.read<double>(&work); torqueIntegral1.push_back(work); input.read<double>(&work); torqueIntegral2.push_back(work); } } } // DESTRUCTORS Dat::~Dat() {} // METHODS int Dat::getNumberParticles() const { return numberParticles; } double Dat::getPersistenceLength() const { return persistenceLength; } double Dat::getPackingFraction() const { return packingFraction; } double Dat::getSystemSize() const { return systemSize; } double Dat::getTorqueParameter() const { return torqueParameter; } int Dat::getRandomSeed() const { return randomSeed; } double Dat::getTimeStep() const { return timeStep; } int Dat::getFramesWork() const { return framesWork; } long int Dat::getNumberWork() const { return numberWork; } long int Dat::getFrames() const { return frames; } std::vector<double> Dat::getActiveWork() { return activeWork; } std::vector<double> Dat::getActiveWorkForce() { return activeWorkForce; } std::vector<double> Dat::getActiveWorkOri() { return activeWorkOri; } std::vector<double> Dat::getOrderParameter() { return orderParameter; } std::vector<double> Dat::getOrderParameter0() { return orderParameter0; } std::vector<double> Dat::getOrderParameter1() { return orderParameter1; } std::vector<double> Dat::getTorqueIntegral1() { return torqueIntegral1; } std::vector<double> Dat::getTorqueIntegral2() { return torqueIntegral2; } double Dat::getPosition( int const& frame, int const& particle, int const& dimension) { // Returns position of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + dimension*sizeof(double)); // dimension } double Dat::getOrientation(int const& frame, int const& particle){ // Returns position of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + 2*sizeof(double)); // positions } double Dat::getVelocity( int const& frame, int const& particle, int const& dimension) { // Returns velocity of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + 3*sizeof(double) // positions and orientation + dimension*sizeof(double)); // dimension } /******** * DAT0 * ********/ // CONSTRUCTORS Dat0::Dat0(std::string filename, bool loadWork) : numberParticles(), potentialParameter(), propulsionVelocity(), transDiffusivity(), rotDiffusivity(), persistenceLength(), packingFraction(), systemSize(), randomSeed(), timeStep(), framesWork(), dumpParticles(), dumpPeriod(), input(filename) { // HEADER INFORMATION input.read<const int>(&numberParticles); input.read<const double>(&potentialParameter); input.read<const double>(&propulsionVelocity); input.read<const double>(&transDiffusivity); input.read<const double>(&rotDiffusivity); input.read<const double>(&persistenceLength); input.read<const double>(&packingFraction); input.read<const double>(&systemSize); input.read<const int>(&randomSeed); input.read<const double>(&timeStep); input.read<const int>(&framesWork); input.read<const bool>(&dumpParticles); input.read<const int>(&dumpPeriod); // DIAMETERS double diameter; for (int i=0; i < numberParticles; i++) { input.read<double>(&diameter); diameters.push_back(diameter); } // FILE PARTS LENGTHS headerLength = input.tellg(); particleLength = 5*sizeof(double)*dumpParticles; frameLength = numberParticles*particleLength; workLength = 4*sizeof(double); // ESTIMATION OF NUMBER OF COMPUTED WORK AND ORDER PARAMETER SUMS AND FRAMES numberWork = (input.getFileSize() - headerLength - frameLength)/( framesWork*frameLength + workLength); frames = !dumpParticles ? 0 : (input.getFileSize() - headerLength - numberWork*workLength)/frameLength; // FILE CORRUPTION CHECK if ( input.getFileSize() != headerLength + frames*frameLength + numberWork*workLength ) { std::cerr << "Invalid file size." << std::endl; exit(1); } // ACTIVE WORK AND ORDER PARAMETER if ( loadWork ) { double work; for (int i=0; i < numberWork; i++) { input.read<double>(&work, headerLength // header + frameLength // frame with index 0 + (1 + i)*framesWork*frameLength // all following packs of framesWork frames + i*workLength); // previous values of the active work activeWork.push_back(work); input.read<double>(&work); activeWorkForce.push_back(work); input.read<double>(&work); activeWorkOri.push_back(work); input.read<double>(&work); orderParameter.push_back(work); } } } // DESTRUCTORS Dat0::~Dat0() {} // METHODS int Dat0::getNumberParticles() const { return numberParticles; } double Dat0::getPotentialParameter() const { return potentialParameter; } double Dat0::getPropulsionVelocity() const { return propulsionVelocity; } double Dat0::getTransDiffusivity() const { return transDiffusivity; } double Dat0::getRotDiffusivity() const { return rotDiffusivity; } double Dat0::getPersistenceLength() const { return persistenceLength; } double Dat0::getPackingFraction() const { return packingFraction; } double Dat0::getSystemSize() const { return systemSize; } int Dat0::getRandomSeed() const { return randomSeed; } double Dat0::getTimeStep() const { return timeStep; } int Dat0::getFramesWork() const { return framesWork; } long int Dat0::getNumberWork() const { return numberWork; } long int Dat0::getFrames() const { return frames; } std::vector<double> Dat0::getDiameters() { return diameters; } std::vector<double> Dat0::getActiveWork() { return activeWork; } std::vector<double> Dat0::getActiveWorkForce() { return activeWorkForce; } std::vector<double> Dat0::getActiveWorkOri() { return activeWorkOri; } std::vector<double> Dat0::getOrderParameter() { return orderParameter; } double Dat0::getPosition( int const& frame, int const& particle, int const& dimension) { // Returns position of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + dimension*sizeof(double)); // dimension } double Dat0::getOrientation(int const& frame, int const& particle){ // Returns position of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + 2*sizeof(double)); // positions } double Dat0::getVelocity( int const& frame, int const& particle, int const& dimension) { // Returns velocity of a given particle at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + particle*particleLength // other particles + (std::max(frame - 1, 0)/framesWork)*workLength // active work sums (taking into account the frame with index 0) + 3*sizeof(double) // positions and orientation + dimension*sizeof(double)); // dimension } /******** * DATR * ********/ // CONSTRUCTORS DatR::DatR(std::string filename, bool loadOrder) : numberParticles(), rotDiffusivity(), torqueParameter(), timeStep(), framesOrder(), dumpRotors(), dumpPeriod(), randomSeed(), input(filename) { // HEADER INFORMATION input.read<const int>(&numberParticles); input.read<const double>(&rotDiffusivity); input.read<const double>(&torqueParameter); input.read<const double>(&timeStep); input.read<const int>(&framesOrder); input.read<const bool>(&dumpRotors); input.read<const int>(&dumpPeriod); input.read<const int>(&randomSeed); // FILE PARTS LENGTHS headerLength = input.tellg(); rotorLength = 1*sizeof(double); frameLength = numberParticles*rotorLength; orderLength = 2*sizeof(double); // ESTIMATION OF NUMBER OF COMPUTED ORDER PARAMETER SUMS AND FRAMES numberOrder = (input.getFileSize() - headerLength - frameLength)/( framesOrder*frameLength + orderLength); frames = !dumpRotors ? 0 : (input.getFileSize() - headerLength - numberOrder*orderLength)/frameLength; // FILE CORRUTION CHECK if ( input.getFileSize() != headerLength + frames*frameLength + numberOrder*orderLength ) { std::cerr << "Invalid file size." << std::endl; exit(1); } // ORDER PARAMETER if ( loadOrder ) { double order; for (int i=0; i < numberOrder; i++) { input.read<double>(&order, headerLength // header + frameLength // frame with index 0 + (1 + i)*framesOrder*frameLength // all following packs of framesOrder frames + i*orderLength); // previous values of the order parameter orderParameter.push_back(order); input.read<double>(&order); orderParameterSq.push_back(order); } } } // DESTRUCTORS DatR::~DatR() {} // METHODS int DatR::getNumberParticles() const { return numberParticles; } double DatR::getRotDiffusivity() const { return rotDiffusivity; } double DatR::getTorqueParameter() const { return torqueParameter; } double DatR::getTimeStep() const { return timeStep; } int DatR::getDumpPeriod() const { return dumpPeriod; } int DatR::getRandomSeed() const { return randomSeed; } long int DatR::getFrames() const { return frames; } std::vector<double> DatR::getOrderParameter() { return orderParameter; } std::vector<double> DatR::getOrderParameterSq() { return orderParameterSq; } double DatR::getOrientation(int const& frame, int const& rotor) { // Returns position of a given rotor at a given frame. return input.read<double>( headerLength // header + frame*frameLength // other frames + rotor*rotorLength // other rotors + (std::max(frame - 1, 0)/framesOrder)*orderLength); // order parameter sums (taking into account the frame with index 0) }
#include "utils.hpp" #include "common_ptts.hpp" #include "player_ptts.hpp" #include "utils/dirty_word_filter.hpp" #include "child_ptts.hpp" #include <map> namespace nora { namespace config { bool check_conditions(const pd::condition_array& ca) { static const map<pd::condition::condition_type, set<int>> condition_arg_size { { pd::condition::PASS_ADVENTURE, {1}}, { pd::condition::ADVENTURE_NO_CHANCES, {0}}, { pd::condition::NOT_PASS_ADVENTURE, {1}}, { pd::condition::COST_RESOURCE, {2}}, { pd::condition::COST_ITEM, {1, 2}}, { pd::condition::RESOURCE_GE, {2}}, { pd::condition::LEVEL_GREATER_THAN_ACTOR_LEVEL, {0}}, { pd::condition::BUY_GOOD_TIMES_LESS, {3}}, { pd::condition::HAS_ACTOR, {1}}, { pd::condition::NO_ACTOR, {1}}, { pd::condition::LEVEL_GE, {1}}, { pd::condition::LEVEL_LE, {1}}, { pd::condition::LEVEL_GREATER_THAN_EQUIPMENT_LEVEL, {0}}, { pd::condition::LEVEL_GREATER_THAN_HUANZHUANG_LEVEL, {0}}, { pd::condition::ACTOR_INTIMACY_GE, {1, 2}}, { pd::condition::ACTOR_LEVEL_GE, {1, 2}}, { pd::condition::PASS_LIEMING, {1}}, { pd::condition::VIP_LEVEL_GE, {1}}, { pd::condition::GENDER, {1}}, { pd::condition::EQUIPMENT_EXP_GE, {1}}, { pd::condition::EQUIPMENT_QUALITY_GE, {1}}, { pd::condition::EQUIPMENT_LEVEL_GE, {1}}, { pd::condition::ACTOR_STAR_GE, {1, 2}}, { pd::condition::ACTOR_STEP_GE, {1}}, { pd::condition::ACTOR_QUALITY_GE, {1}}, { pd::condition::ACTOR_PIN_LE, {1, 2}}, { pd::condition::ACTOR_CRAFT_GE, {2}}, { pd::condition::ACTOR_CRAFT_E, {2}}, { pd::condition::PASS_PLOT, {1}}, { pd::condition::INTIMACY_GE, {1}}, { pd::condition::FAIL, {1}}, { pd::condition::NO_HUANZHUANG_COLLECTION, {2}}, { pd::condition::HUANZHUANG_EXP_GE, {1}}, { pd::condition::NO_SPINE_COLLECTION, {2}}, { pd::condition::ITEM_COUNT_LE, {1, 2}}, { pd::condition::RANDOM, {1}}, { pd::condition::FRIEND_COUNT_LE, {1}}, { pd::condition::LEAGUE_JOINED, {0}}, { pd::condition::MANSION_CREATED, {0}}, { pd::condition::MANSION_FANCY_GE, {1}}, { pd::condition::ROLE_PIN_LE, {1}}, { pd::condition::MANSION_BANQUET_PRESTIGE_LEVEL_GE, {1}}, { pd::condition::ROLE_PIN_E, {1}}, { pd::condition::RESOURCE_NOT_REACH_MAX, {1}}, { pd::condition::PLOT_OPTION_NOT_LOCKED, {2}}, { pd::condition::TOWER_CUR_LEVEL_E, {1}}, { pd::condition::TOWER_HIGHEST_LEVEL_GE, {1}}, { pd::condition::PLOT_OPTION_SELECTED, {2}}, { pd::condition::MAX_GPIN_GE, {1}}, { pd::condition::GPIN_LIMIT, {1, 2}}, { pd::condition::PASS_XINSHOU_GROUP, {1}}, { pd::condition::HAS_TITLE, {1}}, { pd::condition::ROLE_NOT_EQUIPED_EQUIPMENT_PART, {1}}, { pd::condition::ROLE_HAS_NOT_EQUIPED_EQUIPMENT, {1}}, { pd::condition::NOT_IN_LEAGUE, {0}}, { pd::condition::QUEST_COMMITTED, {1}}, { pd::condition::FORMATION_NO_ACTOR, {2}}, { pd::condition::FORMATION_GRID_NO_ACTOR, {3}}, { pd::condition::LOTTERY_FREE, {1}}, { pd::condition::MARRIED, {0}}, { pd::condition::NOT_MARRIED, {0}}, { pd::condition::EVER_MARRIED, {0}}, { pd::condition::SERVER_OPEN_DAY_IN, {2}}, { pd::condition::FIRST_LOGIN_DAY_E, {1}}, { pd::condition::FEIGE_ONGOING, {1}}, { pd::condition::FEIGE_FINISHED, {1}}, { pd::condition::MANSION_COOK_HAS_RECIPE, {1}}, { pd::condition::MANSION_FARM_PLOT_STATE, {1}}, { pd::condition::ARENA_BEST_RANK_GE, {1}}, { pd::condition::QUEST_ACCEPTED, {1}}, { pd::condition::LEAGUE_SHOP_LEVEL_IS, {1}}, { pd::condition::LEAGUE_SHOP_LEVEL_GE, {1}}, { pd::condition::HAS_BONUS_CITY, {1}}, { pd::condition::MANSION_HALL_QUEST_COUNT_GE, {1}}, { pd::condition::MANSION_FURNITURE_COUNT_GE, {2}}, { pd::condition::CHILD_PHASE_IN, {2}}, { pd::condition::LEVEL_GREATER_THAN_CHILD_LEVEL, {}}, { pd::condition::VIP_LEVEL_LE, {1}}, { pd::condition::SPOUSE_VIP_LEVEL_GE, {1}}, { pd::condition::SPOUSE_VIP_LEVEL_LE, {1}}, { pd::condition::ROLE_HAS_EQUIPMENT_PART_COUNT_GE, {2}} }; auto ret = true; static const set<string> opers{"<", ">", "<=", ">=", "!=", "=", "=="}; for (const auto& i : ca.conditions()) { ASSERT(condition_arg_size.count(i.type()) > 0); if (condition_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " wrong arg size " << i.arg_size(); ret = false; } switch (i.type()) { case pd::condition::NO_HUANZHUANG_COLLECTION: { pd::huanzhuang_part part; if (!pd::huanzhuang_part_Parse(i.arg(0), &part)) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " wrong huanzhuang part " << i.arg(0); ret = false; } break; } case pd::condition::NO_SPINE_COLLECTION: { pd::spine_part part; if (!pd::spine_part_Parse(i.arg(0), &part)) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " wrong spine part " << i.arg(0); ret = false; } break; } case pd::condition::GPIN_LIMIT: { if (i.arg_size() >= 1) { if (opers.count(i.arg(0)) <= 0) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " invalid arg " << i.arg(0); ret = false; } } break; } case pd::condition::FORMATION_NO_ACTOR: { if (!PTTS_HAS(actor, stoul(i.arg(1)))) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " actor not exist " << i.arg(1); ret = false; } break; } case pd::condition::QUEST_COMMITTED: case pd::condition::QUEST_ACCEPTED: { if (!PTTS_HAS(quest, stoul(i.arg(0)))) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " quest not exist " << i.arg(0); ret = false; } break; } default: break; } } return ret; } bool verify_conditions(const pd::condition_array& ca) { auto ret = true; for (const auto& i : ca.conditions()) { switch (i.type()) { case pd::condition::NO_HUANZHUANG_COLLECTION: { pd::huanzhuang_part part; if (!pd::huanzhuang_part_Parse(i.arg(0), &part)) { if (!HUANZHUANG_PTTS_HAS(part, stoul(i.arg(1)))) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " huanzhuang not exist " << i.arg(0) << " " << i.arg(1); ret = false; } } break; } case pd::condition::NO_SPINE_COLLECTION: { pd::spine_part part; if (!pd::spine_part_Parse(i.arg(0), &part)) { if (!SPINE_PTTS_HAS(part, stoul(i.arg(1)))) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " spine not exist " << i.arg(0) << " " << i.arg(1); ret = false; } } break; } case pd::condition::MANSION_FURNITURE_COUNT_GE: { uint32_t pttid = stoul(i.arg(0)); if (!PTTS_HAS(mansion_furniture, pttid)) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " mansion furniture not exist " << i.arg(0); ret = false; } break; } case pd::condition::CHILD_PHASE_IN: { pd::child_phase phase; if (!pd::child_phase_Parse(i.arg(0), &phase)) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " invalid child phase " << i.arg(0); ret = false; } if (!pd::child_phase_Parse(i.arg(1), &phase)) { CONFIG_ELOG << pd::condition::condition_type_Name(i.type()) << " invalid child phase " << i.arg(1); ret = false; } break; } default: break; } } return ret; } bool check_events(const pd::event_array& ea) { static const map<pd::event::event_type, set<int>> event_arg_size { { pd::event::ADD_RESOURCE, {2}}, { pd::event::ADD_RESOURCE_IGNORE_MAX, {2}}, { pd::event::DEC_RESOURCE, {2}}, { pd::event::RESET_RESOURCE, {2}}, { pd::event::ADD_ACTOR, {1}}, { pd::event::ADD_ITEM, {2}}, { pd::event::REMOVE_ITEM, {2}}, { pd::event::ADD_BUY_GOOD_TIMES, {2}}, { pd::event::PASS_ADVENTURE, {1}}, { pd::event::LEVELUP_ACTOR_SKILL, {1, 2}}, { pd::event::ADD_SPINE_COLLECTION, {2, 4}}, { pd::event::ADD_HUANZHUANG_COLLECTION, {2, 4}}, { pd::event::ACCEPT_QUEST, {1}}, { pd::event::REMOVE_QUEST, {1}}, { pd::event::ACTOR_LEVELUP, {0, 1}}, { pd::event::ADD_EQUIPMENT, {2}}, { pd::event::EQUIPMENT_LEVELUP, {0}}, { pd::event::EQUIPMENT_ADD_QUALITY, {0}}, { pd::event::EQUIPMENT_CHANGE_RAND_ATTR, {0}}, { pd::event::EQUIPMENT_XILIAN, {0}}, { pd::event::EQUIPMENT_XILIAN_CONFIRM, {0}}, { pd::event::LEVELUP, {0}}, { pd::event::CHANGE_ACTOR_INTIMACY, {1, 2, 3}}, { pd::event::ACTOR_ADD_STEP, {0, 1}}, { pd::event::ACTOR_ADD_STAR, {0}}, { pd::event::ACTOR_ADD_PIN, {0, 1}}, { pd::event::ROLE_ADD_FATE, {0}}, { pd::event::PASS_LIEMING, {1}}, { pd::event::REMOVE_EQUIPMENT, {0}}, { pd::event::ADD_EQUIPMENT_EXP, {1}}, { pd::event::DROP, {2}}, { pd::event::ACTOR_UNLOCK_SKILL, {1, 2}}, { pd::event::CHANGE_INTIMACY, {1}}, { pd::event::NONE, {0}}, { pd::event::ADD_TITLE, {1}}, { pd::event::ADD_PRESENT, {2}}, { pd::event::DEC_PRESENT, {2}}, { pd::event::MANSION_ADD_HALL_QUEST, {1}}, { pd::event::PASS_ADVENTURE_ALL, {0}}, { pd::event::PASS_ADVENTURE_CHAPTER, {1}}, { pd::event::PLOT_LOCK_OPTION, {2}}, { pd::event::PLOT_UNLOCK_OPTION, {2}}, { pd::event::TRIGGER_FEIGE, {1, 2}}, { pd::event::ADD_FEIGE_CHUANWEN, {1}}, { pd::event::ADD_FEIGE_CG, {1}}, { pd::event::ADD_FEIGE_MINGYUN, {1}}, { pd::event::MANSION_COOK_ADD_RECIPE, {1}}, { pd::event::DEC_GONGDOU_EFFECT, {1, 2}}, { pd::event::ACTOR_ADD_SKIN, {1}}, { pd::event::TRIGGER_MAJOR_CITY_BUBBLE, {1}}, { pd::event::ADD_HUANZHUANG_EXP, {1}}, { pd::event::RESET_HUANZHUANG, {1}}, { pd::event::HUANZHUANG_LEVELUP, {0}}, { pd::event::BROADCAST_SYSTEM_CHAT, {1}}, { pd::event::ADD_JADE, {2}}, { pd::event::REMOVE_JADE, {1}}, { pd::event::DROP_RECORD, {2}}, { pd::event::ADD_DAIYANREN_POINTS, {1}}, }; auto ret = true; for (const auto& i : ea.events()) { ASSERT(event_arg_size.count(i.type()) > 0); if (event_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong arg size " << i.arg_size(); return false; } } for (const auto& i : ea.events()) { switch (i.type()) { case pd::event::ADD_RESOURCE: case pd::event::ADD_RESOURCE_IGNORE_MAX: { pd::resource_type type; if (!pd::resource_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong resource type " << i.arg(0); ret = false; continue; } if (stoi(i.arg(1)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(0); ret = false; continue; } break; } case pd::event::DEC_RESOURCE: { pd::resource_type type; if (!pd::resource_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong resource type " << i.arg(0); ret = false; continue; } if (stoi(i.arg(1)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(0); ret = false; continue; } break; } case pd::event::RESET_RESOURCE: { pd::resource_type type; if (!pd::resource_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong resource type " << i.arg(0); ret = false; continue; } if (stoi(i.arg(1)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(0); ret = false; continue; } break; } case pd::event::CHANGE_ACTOR_INTIMACY: { for (auto j = 0; j < i.arg_size() - 1; ++j) { auto pttid = stoul(i.arg(j)); if (!PTTS_HAS(actor, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " actor not exist " << pttid; ret = false; continue; } const auto& actor_ptt = PTTS_GET(actor, pttid); if (actor_ptt.type() == pd::actor::ZHU) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " actor is zhu " << pttid; ret = false; } } if (stoi(i.arg(i.arg_size() - 1)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(i.arg_size() - 1); ret = false; } break; } case pd::event::DEC_GONGDOU_EFFECT: { if (i.arg_size() == 1) { if (stoi(i.arg(0)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(0); ret = false; continue; } } else if (i.arg_size() == 2) { pd::gongdou_type type; if (!pd::gongdou_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong resource type " << i.arg(0); ret = false; continue; } if (stoi(i.arg(1)) <= 0) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid count " << i.arg(1); ret = false; continue; } } break; } case pd::event::ACTOR_ADD_SKIN: { if (!PTTS_HAS(actor_skin, stoul(i.arg(0)))) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " skin not exist " << i.arg(0); ret = false; continue; } break; } case pd::event::ACCEPT_QUEST: case pd::event::REMOVE_QUEST: { if (!PTTS_HAS(quest, stoul(i.arg(0)))) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " quest not exist " << i.arg(0); ret = false; continue; } break; } default: break; } } return ret; } bool verify_events(const pd::event_array& ea) { auto ret = true; for (const auto& i : ea.events()) { switch (i.type()) { case pd::event::ADD_ITEM: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(item, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " item not exist " << pttid; ret = false; continue; } break; } case pd::event::ADD_EQUIPMENT: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(equipment, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " equipment not exist " << pttid; ret = false; continue; } break; } case pd::event::ADD_JADE: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(jade, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " jade not exist " << pttid; ret = false; continue; } break; } case pd::event::ADD_SPINE_COLLECTION: { pd::spine_part part; if (!pd::spine_part_Parse(i.arg(0), &part)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong spine part " << i.arg(0); ret = false; continue; } auto pttid = stoul(i.arg(1)); if (!SPINE_PTTS_HAS(part, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " spine not exist " << pd::spine_part_Name(part) << " " << pttid; ret = false; continue; } if (i.arg_size() == 4) { if (!pd::spine_part_Parse(i.arg(2), &part)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong spine part " << i.arg(2); ret = false; continue; } pttid = stoul(i.arg(3)); if (!SPINE_PTTS_HAS(part, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " spine not exist " << pd::spine_part_Name(part) << " " << pttid; ret = false; continue; } } break; } case pd::event::ADD_HUANZHUANG_COLLECTION:{ pd::huanzhuang_part part; if (!pd::huanzhuang_part_Parse(i.arg(0), &part)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong huanzhuang part " << i.arg(0); ret = false; continue; } auto pttid = stoul(i.arg(1)); if (!HUANZHUANG_PTTS_HAS(part, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " huanzhuang not exist " << pd::huanzhuang_part_Name(part) << " " << pttid; ret = false; continue; } if (i.arg_size() == 4) { if (!pd::huanzhuang_part_Parse(i.arg(2), &part)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " wrong huanzhuang part " << i.arg(2); ret = false; continue; } pttid = stoul(i.arg(3)); if (!HUANZHUANG_PTTS_HAS(part, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " huanzhuang not exist " << pd::huanzhuang_part_Name(part) << " " << pttid; ret = false; continue; } } break; } case pd::event::ACTOR_UNLOCK_SKILL: { if (i.arg_size() == 1) { if (!PTTS_HAS(skill, stoul(i.arg(0)))) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " skill not exist " << i.arg(0); ret = false; continue; } } else if (i.arg_size() == 2) { if (!PTTS_HAS(actor, stoul(i.arg(0)))) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " actor not exist " << i.arg(0); ret = false; continue; } const auto& actor_ptt = PTTS_GET(actor, stoul(i.arg(0))); auto found = false; for (auto j : actor_ptt.lock_skill()) { if (j == stoul(i.arg(1))) { found = true; break; } } if (!found) { CONFIG_ELOG << i.arg(0) << " " << pd::event::event_type_Name(i.type()) << " skill not in role lock skill " << i.arg(1); ret = false; continue; } if (!PTTS_HAS(skill, stoul(i.arg(1)))) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " skill not exist " << i.arg(1); ret = false; continue; } } break; } case pd::event::ADD_TITLE: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(title, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " title not exist " << i.arg(0); ret = false; } break; } case pd::event::PLOT_LOCK_OPTION: case pd::event::PLOT_UNLOCK_OPTION: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(plot_options, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " plot options not exist " << i.arg(0); ret = false; } const auto& ptt = PTTS_GET(plot_options, pttid); auto idx = stoi(i.arg(1)); if (idx < 0 || idx >= ptt.options_size()) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " invalid option: " << idx << " options size: " << ptt.options_size(); ret = false; } break; } case pd::event::TRIGGER_FEIGE: { for (auto j = 0; j < i.arg_size(); ++j) { auto pttid = stoul(i.arg(j)); if (!PTTS_HAS(feige, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " feige not exist " << i.arg(0); ret = false; break; } } break; } case pd::event::ADD_FEIGE_CHUANWEN: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(feige_chuanwen, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " feige chuanwen not exist " << i.arg(0); ret = false; } break; } case pd::event::ADD_FEIGE_MINGYUN: case pd::event::ADD_FEIGE_CG: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(feige_cg, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " feige cg not exist " << i.arg(0); ret = false; } break; } case pd::event::MANSION_COOK_ADD_RECIPE: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(mansion_cook_recipe, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " mansion cook recipe not exist " << i.arg(0); ret = false; } break; } case pd::event::TRIGGER_MAJOR_CITY_BUBBLE: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(major_city_bubble, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " major city bubble not exist " << i.arg(0); ret = false; } break; } case pd::event::BROADCAST_SYSTEM_CHAT: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(system_chat, pttid)) { CONFIG_ELOG << pd::event::event_type_Name(i.type()) << " system chat not exist " << i.arg(0); ret = false; } break; } default: break; } } return ret; } bool check_condevents(const pd::condevent_array& cea) { bool ret = true; for (const auto& i : cea.condevents()) { if (!check_conditions(i.conditions())) { CONFIG_ELOG << "check condevents conditions failed"; ret = false; } if (!check_events(i.events())) { CONFIG_ELOG << "check condevents events failed"; ret = false; } } return ret; } bool verify_condevents(const pd::condevent_array& cea) { bool ret = true; for (const auto& i : cea.condevents()) { if (!verify_conditions(i.conditions())) { CONFIG_ELOG << "verify condevents conditions failed"; ret = false; } if (!verify_events(i.events())) { CONFIG_ELOG << "verify condevents events failed"; ret = false; } } return ret; } void modify_events_by_conditions(const pd::condition_array& ca, pd::event_array& ea) { for (const auto& i : ca.conditions()) { switch (i.type()) { case pd::condition::COST_RESOURCE: { auto *e = ea.add_events(); e->set_type(pd::event::DEC_RESOURCE); e->add_arg(i.arg(0)); e->add_arg(i.arg(1)); break; } case pd::condition::COST_ITEM: { auto *e = ea.add_events(); e->set_type(pd::event::REMOVE_ITEM); for (auto j = 0; j < i.arg_size(); ++j) { e->add_arg(i.arg(j)); } break; } case pd::condition::COST_PRESENT: { auto *e = ea.add_events(); e->set_type(pd::event::DEC_PRESENT); e->add_arg(i.arg(0)); e->add_arg(i.arg(1)); break; } default: break; } } } void modify_conditions_by_events(const pd::event_array& ea, pd::condition_array& ca) { for (const auto& i : ea.events()) { switch (i.type()) { case pd::event::ADD_RESOURCE: { auto *c = ca.add_conditions(); c->set_type(pd::condition::RESOURCE_NOT_REACH_MAX); c->add_arg(i.arg(0)); break; } default: break; } } } bool check_fief_events(pd::fief_event_array& fea, bool silent) { static map<pd::fief_event::fief_event_type, set<int>> event_arg_size { { pd::fief_event::ADD_RESOURCE, {2}}, { pd::fief_event::DEC_RESOURCE, {2}}, { pd::fief_event::INCIDENT_EXTRA_WEIGHT, {2}}, }; auto ret = true; for (const auto& i : fea.events()) { ASSERT(event_arg_size.count(i.type()) > 0); if (event_arg_size.at(i.type()).count(i.arg_size()) <= 0) { ret = false; if (!silent) { CONFIG_ELOG << pd::fief_event::fief_event_type_Name(i.type()) << " wrong arg size " << i.arg_size(); } continue; } switch (i.type()) { case pd::fief_event::ADD_RESOURCE: { pd::fief_resource_type type; if (!pd::fief_resource_type_Parse(i.arg(0), &type)) { if (!silent) { CONFIG_ELOG <<"ADD_RESOURCE has invalid resource type \n" << i.DebugString(); } ret = false; } if (stoul(i.arg(1)) <= 0) { if (!silent) { CONFIG_ELOG << "add_resource count <= 0 \n" << i.DebugString(); } ret = false; } break; } case pd::fief_event::DEC_RESOURCE: { pd::fief_resource_type type; if (!pd::fief_resource_type_Parse(i.arg(0), &type)) { if (!silent) { CONFIG_ELOG <<"DEC_RESOURCE has invalid resource type \n" << i.DebugString(); } ret = false; } if (stoul(i.arg(1)) <= 0) { if (!silent) { CONFIG_ELOG << "dec_resource count <= 0 \n" << i.DebugString(); } ret = false; } break; } case pd::fief_event::INCIDENT_EXTRA_WEIGHT: { pd::fief_resource_type type; if (!pd::fief_resource_type_Parse(i.arg(0), &type)) { if (!silent) { CONFIG_ELOG <<"INCIDENT_EXTRA_WEIGHT has invalid resource type \n" << i.DebugString(); } ret = false; } if (stoul(i.arg(1)) <= 0) { if (!silent) { CONFIG_ELOG << "include_extra_weight count <= 0 \n" << i.DebugString(); } ret = false; } break; } } } return ret; } void modify_fief_events_by_fief_conditions(const pd::fief_condition_array& fca, pd::fief_event_array& fea) { for (const auto& i : fca.conditions()) { switch (i.type()) { case pd::fief_condition::COST_RESOURCE: { auto *e = fea.add_events(); e->set_type(pd::fief_event::DEC_RESOURCE); e->add_arg(i.arg(0)); e->add_arg(i.arg(1)); break; } default: break; } } } bool check_league_conditions(const pd::league_condition_array& lca) { static map<pd::league_condition_type, set<int>> condition_arg_size { { pd::LCT_COST_RESOURCE, {2}}, { pd::LCT_LEVEL_GE, {1}}, { pd::LCT_PASS_CAMPAIGN, {1}}, { pd::LCT_FAIL, {1}}, { pd::LCT_MEMBER_COUNT_GE, {1}}, }; auto ret = true; for (const auto& i : lca.conditions()) { ASSERT(condition_arg_size.count(i.type()) > 0); if (condition_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::league_condition_type_Name(i.type()) << " wrong arg size " << i.arg_size(); ret = false; } } return ret; } bool check_league_events(const pd::league_event_array& lea, bool silent) { static map<pd::league_event_type, set<int>> event_arg_size { { pd::LET_ADD_RESOURCE, {2}}, { pd::LET_DEC_RESOURCE, {2}}, { pd::LET_LEVEL_UP, {0}}, { pd::LET_ADD_ALLOCATABLE_ITEM, {2}}, { pd::LET_DEC_ALLOCATABLE_ITEM, {2}}, { pd::LET_DROP, {1}}, { pd::LET_PASS_CAMPAIGN, {1}}, { pd::LET_PASS_ALL_CAMPAIGN, {0}}, }; auto ret = true; for (const auto& i : lea.events()) { ASSERT(event_arg_size.count(i.type()) > 0); if (event_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::league_event_type_Name(i.type()) << " wrong arg size " << i.arg_size(); ret = false; } } for (const auto& i : lea.events()) { switch (i.type()) { case pd::LET_ADD_RESOURCE: { pd::league_resource_type type; if (!pd::league_resource_type_Parse(i.arg(0), &type)) { if (!silent) { CONFIG_ELOG <<"LET_ADD_RESOURCE has invalid resource type \n" << i.DebugString(); } ret = false; } if (stoul(i.arg(1)) <= 0) { if (!silent) { CONFIG_ELOG << "add_resource count <= 0 \n" << i.DebugString(); } ret = false; } break; } case pd::LET_DEC_RESOURCE: { pd::league_resource_type type; if (!pd::league_resource_type_Parse(i.arg(0), &type)) { if (!silent) { CONFIG_ELOG <<"LET_DEC_RESOURCE has invalid resource type \n" << i.DebugString(); } ret = false; } if (stoul(i.arg(1)) <= 0) { if (!silent) { CONFIG_ELOG << "dec_resource count <= 0 \n" << i.DebugString(); } ret = false; } break; } default: break; } } return ret; } bool verify_league_events(const pd::league_event_array& lea) { auto ret = true; for (const auto& i : lea.events()) { switch (i.type()) { case pd::LET_ADD_ALLOCATABLE_ITEM: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(item, pttid)) { CONFIG_ELOG << pd::league_event_type_Name(i.type()) << " item not exist " << pttid; ret = false; continue; } break; } case pd::LET_DEC_ALLOCATABLE_ITEM: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(item, pttid)) { CONFIG_ELOG << pd::league_event_type_Name(i.type()) << " item not exist " << pttid; ret = false; continue; } break; } case pd::LET_DROP: { auto pttid = stoul(i.arg(0)); if (!PTTS_HAS(league_drop, pttid)) { CONFIG_ELOG << pd::league_event_type_Name(i.type()) << " league drop not exist " << pttid; ret = false; continue; } break; } default: break; } } return ret; } void modify_league_events_by_league_conditions(const pd::league_condition_array& lca, pd::league_event_array& lea) { for (const auto& i : lca.conditions()) { switch (i.type()) { case pd::LCT_COST_RESOURCE: { auto *e = lea.add_events(); e->set_type(pd::LET_DEC_RESOURCE); e->add_arg(i.arg(0)); e->add_arg(i.arg(1)); break; } default: break; } } } bool check_child_conditions(const pd::child_condition_array& cca) { static map<pd::child_condition_type, set<int>> condition_arg_size { { pd::CCT_LEVEL_GE, {1}}, { pd::CCT_VALUE_NOT_FULL, {1}}, { pd::CCT_PHASE_IN, {2}}, { pd::CCT_VALUE_GE, {2}}, { pd::CCT_VALUE_LE, {2}}, { pd::CCT_SKILL_SLOT_EMPTY, {1}}, { pd::CCT_STUDY_LEVEL_IN, {3}}, { pd::CCT_ACTOR_STAR_GE, {2}}, { pd::CCT_FAIL, {1}}, }; auto ret = true; for (const auto& i : cca.conditions()) { ASSERT(condition_arg_size.count(i.type()) > 0); if (condition_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " wrong arg size " << i.arg_size(); ret = false; continue; } switch (i.type()) { case pd::CCT_VALUE_NOT_FULL: case pd::CCT_VALUE_LE: case pd::CCT_VALUE_GE: { pd::child_value_type type; if (!pd::child_value_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " invalid child value type " << i.arg(0); ret = false; } break; } case pd::CCT_PHASE_IN: { pd::child_phase phase; if (!pd::child_phase_Parse(i.arg(0), &phase)) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " invalid phase " << i.arg(0); ret = false; } if (!pd::child_phase_Parse(i.arg(1), &phase)) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " invalid phase " << i.arg(1); ret = false; } break; } case pd::CCT_STUDY_LEVEL_IN: { pd::actor::attr_type type; if (!pd::actor::attr_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " invalid attr type " << i.arg(0); ret = false; } break; } case pd::CCT_ACTOR_STAR_GE: { auto actor = stoul(i.arg(0)); if (!PTTS_HAS(actor, actor)) { CONFIG_ELOG << pd::child_condition_type_Name(i.type()) << " actor not exist " << i.arg(0); ret = false; } break; } default: break; } } return ret; } bool check_child_events(const pd::child_event_array& cea) { static map<pd::child_event_type, set<int>> event_arg_size { { pd::CET_CHANGE_PHASE, {0}}, { pd::CET_CHANGE_VALUE, {2}}, { pd::CET_LEVELUP, {0}}, { pd::CET_LEARN_SKILL, {1}}, { pd::CET_LEVELUP_SKILL, {1}}, { pd::CET_STUDY_LEVELUP, {1}}, { pd::CET_DROP, {1}}, { pd::CET_CHANGE_CONTRIBUTION, {1}}, { pd::CET_NONE, {0}}, }; auto ret = true; for (const auto& i : cea.events()) { ASSERT(event_arg_size.count(i.type()) > 0); if (event_arg_size.at(i.type()).count(i.arg_size()) <= 0) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " wrong arg size " << i.arg_size(); ret = false; continue; } switch (i.type()) { case pd::CET_CHANGE_VALUE: { pd::child_value_type type; if (!pd::child_value_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " invalid child value type " << i.arg(0); ret = false; } break; } case pd::CET_STUDY_LEVELUP: { pd::actor::attr_type type; if (!pd::actor::attr_type_Parse(i.arg(0), &type)) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " invalid actor attr type " << i.arg(0); ret = false; break; } if (type != pd::actor::HP && type != pd::actor::ATTACK && type != pd::actor::PHYSICAL_DEFENCE && type != pd::actor::MAGICAL_DEFENCE) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " wrong actor attr type " << i.arg(0); ret = false; } break; } case pd::CET_LEARN_SKILL: case pd::CET_LEVELUP_SKILL: { auto skill = stoul(i.arg(0)); if (!PTTS_HAS(child_skill, skill)) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " child skill not exist " << i.arg(0); ret = false; } break; } default: break; } } return ret; } bool verify_child_conditions(const pd::child_condition_array& cca) { return true; } bool verify_child_events(const pd::child_event_array& cea) { auto ret = true; for (const auto& i : cea.events()) { switch (i.type()) { case pd::CET_DROP: if (i.arg_size() > 0 && !PTTS_HAS(child_drop, stoul(i.arg(0)))) { CONFIG_ELOG << pd::child_event_type_Name(i.type()) << " child drop not exist " << i.arg(0); ret = false; } break; default: break; } } return ret; } void modify_child_events_by_child_conditions(const pd::child_condition_array& cca, pd::child_event_array& cea) { } pc::spine_item& spine_ptts_get(pd::spine_part part, uint32_t pttid) { switch (part) { case pd::SP_HONGMO: return PTTS_GET(hongmo, pttid); case pd::SP_YANJING: return PTTS_GET(yanjing, pttid); case pd::SP_YANSHENGUANG: return PTTS_GET(yanshenguang, pttid); case pd::SP_SAIHONG: return PTTS_GET(saihong, pttid); case pd::SP_MEIMAO: return PTTS_GET(meimao, pttid); case pd::SP_YANZHUANG: return PTTS_GET(yanzhuang, pttid); case pd::SP_CHUNCAI: return PTTS_GET(chuncai, pttid); case pd::SP_TIEHUA: return PTTS_GET(tiehua, pttid); case pd::SP_LIANXING: return PTTS_GET(lianxing, pttid); case pd::SP_DEFORM_FACE: return PTTS_GET(spine_deform_face, pttid); case pd::SP_DEFORM_HEAD: return PTTS_GET(spine_deform_head, pttid); case pd::SP_ZUI: return PTTS_GET(zui, pttid); case pd::SP_HUZI: return PTTS_GET(huzi, pttid); case pd::SP_LIAN: return PTTS_GET(lian, pttid); default: break; } THROW(not_found); } bool spine_ptts_has(pd::spine_part part, uint32_t pttid) { switch (part) { case pd::SP_HONGMO: return PTTS_HAS(hongmo, pttid); case pd::SP_YANJING: return PTTS_HAS(yanjing, pttid); case pd::SP_YANSHENGUANG: return PTTS_HAS(yanshenguang, pttid); case pd::SP_SAIHONG: return PTTS_HAS(saihong, pttid); case pd::SP_MEIMAO: return PTTS_HAS(meimao, pttid); case pd::SP_YANZHUANG: return PTTS_HAS(yanzhuang, pttid); case pd::SP_CHUNCAI: return PTTS_HAS(chuncai, pttid); case pd::SP_TIEHUA: return PTTS_HAS(tiehua, pttid); case pd::SP_LIANXING: return PTTS_HAS(lianxing, pttid); case pd::SP_DEFORM_FACE: return PTTS_HAS(spine_deform_face, pttid); case pd::SP_DEFORM_HEAD: return PTTS_HAS(spine_deform_head, pttid); case pd::SP_ZUI: return PTTS_HAS(zui, pttid); case pd::SP_HUZI: return PTTS_HAS(huzi, pttid); case pd::SP_LIAN: return PTTS_HAS(lian, pttid); default: break; } THROW(not_found); } pc::huanzhuang_item& huanzhuang_ptts_get(pd::huanzhuang_part part, uint32_t pttid) { switch (part) { case pd::HP_YIFU: return PTTS_GET(yifu, pttid); case pd::HP_TOUFA: return PTTS_GET(toufa, pttid); case pd::HP_JIEZHI: return PTTS_GET(jiezhi, pttid); case pd::HP_EDAI: return PTTS_GET(edai, pttid); case pd::HP_FAZAN: return PTTS_GET(fazan, pttid); case pd::HP_GUANSHI: return PTTS_GET(guanshi, pttid); case pd::HP_TOUJIN: return PTTS_GET(toujin, pttid); case pd::HP_ERHUAN: return PTTS_GET(erhuan, pttid); case pd::HP_XIANGLIAN: return PTTS_GET(xianglian, pttid); case pd::HP_BEISHI: return PTTS_GET(beishi, pttid); case pd::HP_GUANGHUAN: return PTTS_GET(guanghuan, pttid); case pd::HP_SHOUCHI: return PTTS_GET(shouchi, pttid); case pd::HP_DEFORM_FACE: return PTTS_GET(huanzhuang_deform_face, pttid); case pd::HP_DEFORM_HEAD: return PTTS_GET(huanzhuang_deform_head, pttid); default: break; } THROW(not_found); } bool huanzhuang_ptts_has(pd::huanzhuang_part part, uint32_t pttid) { switch (part) { case pd::HP_YIFU: return PTTS_HAS(yifu, pttid); case pd::HP_TOUFA: return PTTS_HAS(toufa, pttid); case pd::HP_JIEZHI: return PTTS_HAS(jiezhi, pttid); case pd::HP_EDAI: return PTTS_HAS(edai, pttid); case pd::HP_FAZAN: return PTTS_HAS(fazan, pttid); case pd::HP_GUANSHI: return PTTS_HAS(guanshi, pttid); case pd::HP_TOUJIN: return PTTS_HAS(toujin, pttid); case pd::HP_ERHUAN: return PTTS_HAS(erhuan, pttid); case pd::HP_XIANGLIAN: return PTTS_HAS(xianglian, pttid); case pd::HP_BEISHI: return PTTS_HAS(beishi, pttid); case pd::HP_GUANGHUAN: return PTTS_HAS(guanghuan, pttid); case pd::HP_SHOUCHI: return PTTS_HAS(shouchi, pttid); case pd::HP_DEFORM_FACE: return PTTS_HAS(huanzhuang_deform_face, pttid); case pd::HP_DEFORM_HEAD: return PTTS_HAS(huanzhuang_deform_head, pttid); default: break; } THROW(not_found); } void load_dirty_word() { const auto& ptts = PTTS_GET_ALL(zangzi); for (const auto& i : ptts) { for (const auto& j : i.second.words()) { dirty_word_filter::instance().insert(j); } } } set<uint32_t> quest_to_all_quests(uint32_t quest_pttid) { set<uint32_t> ret; ASSERT(PTTS_HAS(quest, quest_pttid)); ret.insert(quest_pttid); const auto& ptt = PTTS_GET(quest, quest_pttid); for (const auto& i : ptt.targets()) { for (const auto& j : i.params()) { for (const auto& k : j.pass_events().events()) { if (k.type() == pd::event::ACCEPT_QUEST) { ASSERT(k.arg_size() == 1); auto quests = quest_to_all_quests(stoul(k.arg(0))); ret.insert(quests.begin(), quests.end()); } } } } return ret; } void load_config() { PTTS_SET_FUNCS(options); PTTS_LOAD(options); } void check_config() { PTTS_MVP(options); } void write_all() { PTTS_WRITE_ALL(options); } } }
// Created on: 1992-04-07 // Created by: Christian CAILLET // Copyright (c) 1992-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 _IGESData_IGESEntity_HeaderFile #define _IGESData_IGESEntity_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <IGESData_DefSwitch.hxx> #include <Interface_EntityList.hxx> #include <Standard_Transient.hxx> #include <IGESData_DefType.hxx> #include <IGESData_DefList.hxx> #include <Standard_CString.hxx> class TCollection_HAsciiString; class IGESData_IGESType; class IGESData_LineFontEntity; class IGESData_LevelListEntity; class IGESData_ViewKindEntity; class IGESData_TransfEntity; class IGESData_LabelDisplayEntity; class IGESData_ColorEntity; class gp_GTrsf; class Interface_EntityIterator; class IGESData_IGESEntity; DEFINE_STANDARD_HANDLE(IGESData_IGESEntity, Standard_Transient) //! defines root of IGES Entity definition, including Directory //! Part, lists of (optional) Properties and Associativities class IGESData_IGESEntity : public Standard_Transient { public: //! gives IGES typing info (includes "Type" and "Form" data) Standard_EXPORT IGESData_IGESType IGESType() const; //! gives IGES Type Number (often coupled with Form Number) Standard_EXPORT Standard_Integer TypeNumber() const; //! Returns the form number for that //! type of an IGES entity. The default form number is 0. Standard_EXPORT Standard_Integer FormNumber() const; //! Returns the Entity which has been recorded for a given //! Field Number, i.e. without any cast. Maps with : //! 3 : Structure 4 : LineFont 5 : LevelList 6 : View //! 7 : Transf(ormation Matrix) 8 : LabelDisplay //! 13 : Color. Other values give a null handle //! It can then be of any kind, while specific items have a Type Standard_EXPORT Handle(IGESData_IGESEntity) DirFieldEntity (const Standard_Integer fieldnum) const; //! returns True if an IGESEntity is defined with a Structure //! (it is normally reserved for certain classes, such as Macros) Standard_EXPORT Standard_Boolean HasStructure() const; //! Returns Structure (used by some types of IGES Entities only) //! Returns a Null Handle if Structure is not defined Standard_EXPORT Handle(IGESData_IGESEntity) Structure() const; //! Returns the definition status of LineFont Standard_EXPORT virtual IGESData_DefType DefLineFont() const; //! Returns LineFont definition as an Integer (if defined as Rank) //! If LineFont is defined as an Entity, returns a negative value Standard_EXPORT Standard_Integer RankLineFont() const; //! Returns LineFont as an Entity (if defined as Reference) //! Returns a Null Handle if DefLineFont is not "DefReference" Standard_EXPORT Handle(IGESData_LineFontEntity) LineFont() const; //! Returns the definition status of Level Standard_EXPORT virtual IGESData_DefList DefLevel() const; //! Returns the level the entity //! belongs to. Returns -1 if the entity belongs to more than one level. Standard_EXPORT Standard_Integer Level() const; //! Returns LevelList if Level is //! defined as a list. Returns a null handle if DefLevel is not DefSeveral. Standard_EXPORT Handle(IGESData_LevelListEntity) LevelList() const; //! Returns the definition status of //! the view. This can be: none, one or several. Standard_EXPORT virtual IGESData_DefList DefView() const; //! Returns the view of this IGES entity. //! This view can be a single view or a list of views. //! Warning A null handle is returned if the view is not defined. Standard_EXPORT Handle(IGESData_ViewKindEntity) View() const; //! Returns the view as a single view //! if it was defined as such and not as a list of views. //! Warning A null handle is returned if DefView does not have the value DefOne. Standard_EXPORT Handle(IGESData_ViewKindEntity) SingleView() const; //! Returns the view of this IGES entity as a list. //! Warning A null handle is returned if the //! definition status does not have the value DefSeveral. Standard_EXPORT Handle(IGESData_ViewKindEntity) ViewList() const; //! Returns True if a Transformation Matrix is defined Standard_EXPORT Standard_Boolean HasTransf() const; //! Returns the Transformation Matrix (under IGES definition) //! Returns a Null Handle if there is none //! for a more complete use, see Location & CompoundLocation Standard_EXPORT Handle(IGESData_TransfEntity) Transf() const; //! Returns True if a LabelDisplay mode is defined for this entity Standard_EXPORT Standard_Boolean HasLabelDisplay() const; //! Returns the Label Display //! Associativity Entity if there is one. Returns a null handle if there is none. Standard_EXPORT Handle(IGESData_LabelDisplayEntity) LabelDisplay() const; //! gives Blank Status (0 visible, 1 blanked) Standard_EXPORT Standard_Integer BlankStatus() const; //! gives Subordinate Switch (0-1-2-3) Standard_EXPORT Standard_Integer SubordinateStatus() const; //! gives Entity's Use Flag (0 to 5) Standard_EXPORT Standard_Integer UseFlag() const; //! gives Hierarchy status (0-1-2) Standard_EXPORT Standard_Integer HierarchyStatus() const; //! Returns the LineWeight Number (0 not defined), see also LineWeight Standard_EXPORT Standard_Integer LineWeightNumber() const; //! Returns the true Line Weight, computed from LineWeightNumber and //! Global Parameter in the Model by call to SetLineWeight Standard_EXPORT Standard_Real LineWeight() const; //! Returns the definition status of Color. Standard_EXPORT virtual IGESData_DefType DefColor() const; //! Returns the color definition as //! an integer value if the color was defined as a rank. //! Warning A negative value is returned if the color was defined as an entity. Standard_EXPORT Standard_Integer RankColor() const; //! Returns the IGES entity which //! describes the color of the entity. //! Returns a null handle if this entity was defined as an integer. Standard_EXPORT Handle(IGESData_ColorEntity) Color() const; //! returns "reserved" alphanumeric values res1 and res2 //! res1 and res2 have to be reserved as Character[9 at least] //! (remark : their content is changed) //! returned values are ended by null character in 9th //! returned Boolean is False if res1 and res2 are blank, true else Standard_EXPORT Standard_Boolean CResValues (const Standard_CString res1, const Standard_CString res2) const; //! Returns true if a short label is defined. //! A short label is a non-blank 8-character string. Standard_EXPORT Standard_Boolean HasShortLabel() const; //! Returns the label value for this IGES entity as a string. //! Warning If the label is blank, this string is null. Standard_EXPORT Handle(TCollection_HAsciiString) ShortLabel() const; //! Returns true if a subscript number is defined. //! A subscript number is an integer used to identify a label. Standard_EXPORT virtual Standard_Boolean HasSubScriptNumber() const; //! Returns the integer subscript number used to identify this IGES entity. //! Warning 0 is returned if no subscript number is defined for this IGES entity. Standard_EXPORT Standard_Integer SubScriptNumber() const; //! Initializes a directory field as an Entiy of any kind //! See DirFieldEntity for more details Standard_EXPORT void InitDirFieldEntity (const Standard_Integer fieldnum, const Handle(IGESData_IGESEntity)& ent); //! Initializes Transf, or erases it if <ent> is given Null Standard_EXPORT void InitTransf (const Handle(IGESData_TransfEntity)& ent); //! Initializes View, or erases it if <ent> is given Null Standard_EXPORT void InitView (const Handle(IGESData_ViewKindEntity)& ent); //! Initializes LineFont : if <ent> is not Null, it gives LineFont, //! else <rank> gives or erases (if zero) RankLineFont Standard_EXPORT void InitLineFont (const Handle(IGESData_LineFontEntity)& ent, const Standard_Integer rank = 0); //! Initializes Level : if <ent> is not Null, it gives LevelList, //! else <val> gives or erases (if zero) unique Level Standard_EXPORT void InitLevel (const Handle(IGESData_LevelListEntity)& ent, const Standard_Integer val = 0); //! Initializes Color data : if <ent> is not Null, it gives Color, //! else <rank> gives or erases (if zero) RankColor Standard_EXPORT void InitColor (const Handle(IGESData_ColorEntity)& ent, const Standard_Integer rank = 0); //! Initializes the Status of Directory Part Standard_EXPORT void InitStatus (const Standard_Integer blank, const Standard_Integer subordinate, const Standard_Integer useflag, const Standard_Integer hierarchy); //! Sets a new Label to an IGES Entity //! If <sub> is given, it sets value of SubScriptNumber //! else, SubScriptNumber is erased Standard_EXPORT void SetLabel (const Handle(TCollection_HAsciiString)& label, const Standard_Integer sub = -1); //! Initializes various data (those not yet seen above), or erases //! them if they are given as Null (Zero for <weightnum>) : //! <str> for Structure, <lab> for LabelDisplay, and //! <weightnum> for WeightNumber Standard_EXPORT void InitMisc (const Handle(IGESData_IGESEntity)& str, const Handle(IGESData_LabelDisplayEntity)& lab, const Standard_Integer weightnum); //! Returns True if an entity has one and only one parent, defined //! by a SingleParentEntity Type Associativity (explicit sharing). //! Thus, implicit sharing remains defined at model level //! (see class ToolLocation) Standard_EXPORT Standard_Boolean HasOneParent() const; //! Returns the Unique Parent (in the sense given by HasOneParent) //! Error if there is none or several Standard_EXPORT Handle(IGESData_IGESEntity) UniqueParent() const; //! Returns Location given by Transf in Directory Part (see above) //! It must be considered for local definition : if the Entity is //! set in a "Parent", that one can add its one Location, but this //! is not taken in account here : see CompoundLocation for that. //! If no Transf is defined, returns Identity //! If Transf is itself compound, gives the final result Standard_EXPORT gp_GTrsf Location() const; //! Returns Location considered for Vectors, i.e. without its //! Translation Part. As Location, it gives local definition. Standard_EXPORT gp_GTrsf VectorLocation() const; //! Returns Location by taking in account a Parent which has its //! own Location : that one will be combined to that of <me> //! The Parent is considered only if HasOneParent is True, //! else it is ignored and CompoundLocation = Location Standard_EXPORT gp_GTrsf CompoundLocation() const; //! says if a Name is defined, as Short Label or as Name Property //! (Property is looked first, else ShortLabel is considered) Standard_EXPORT Standard_Boolean HasName() const; //! returns Name value as a String (Property Name or ShortLabel) //! if SubNumber is defined, it is concatenated after ShortLabel //! as follows label(number). Ignored with a Property Name Standard_EXPORT Handle(TCollection_HAsciiString) NameValue() const; //! Returns True if the Entity is defined with an Associativity //! list, even empty (that is, file contains its length 0) //! Else, the file contained NO idencation at all about this list. Standard_EXPORT Standard_Boolean ArePresentAssociativities() const; //! gives number of recorded associativities (0 no list defined) Standard_EXPORT Standard_Integer NbAssociativities() const; //! Returns the Associativity List under the form of an EntityIterator. Standard_EXPORT Interface_EntityIterator Associativities() const; //! gives how many Associativities have a given type Standard_EXPORT Standard_Integer NbTypedAssociativities (const Handle(Standard_Type)& atype) const; //! returns the Associativity of a given Type (if only one exists) //! Error if none or more than one Standard_EXPORT Handle(IGESData_IGESEntity) TypedAssociativity (const Handle(Standard_Type)& atype) const; //! Sets "me" in the Associativity list of another Entity Standard_EXPORT void Associate (const Handle(IGESData_IGESEntity)& ent) const; //! Resets "me" from the Associativity list of another Entity Standard_EXPORT void Dissociate (const Handle(IGESData_IGESEntity)& ent) const; //! Returns True if the Entity is defined with a Property list, //! even empty (that is, file contains its length 0) //! Else, the file contained NO idencation at all about this list Standard_EXPORT Standard_Boolean ArePresentProperties() const; //! Gives number of recorded properties (0 no list defined) Standard_EXPORT Standard_Integer NbProperties() const; //! Returns Property List under the form of an EntityIterator Standard_EXPORT Interface_EntityIterator Properties() const; //! gives how many Properties have a given type Standard_EXPORT Standard_Integer NbTypedProperties (const Handle(Standard_Type)& atype) const; //! returns the Property of a given Type //! Error if none or more than one Standard_EXPORT Handle(IGESData_IGESEntity) TypedProperty (const Handle(Standard_Type)& atype, const Standard_Integer anum = 0) const; //! Adds a Property in the list Standard_EXPORT void AddProperty (const Handle(IGESData_IGESEntity)& ent); //! Removes a Property from the list Standard_EXPORT void RemoveProperty (const Handle(IGESData_IGESEntity)& ent); //! computes and sets "true" line weight according IGES rules from //! global data MaxLineWeight (maxv) and LineWeightGrad (gradw), //! or sets it to defw (Default) if LineWeightNumber is null Standard_EXPORT void SetLineWeight (const Standard_Real defw, const Standard_Real maxw, const Standard_Integer gradw); friend class IGESData_ReadWriteModule; friend class IGESData_GeneralModule; friend class IGESData_IGESReaderTool; friend class IGESData_DirChecker; DEFINE_STANDARD_RTTIEXT(IGESData_IGESEntity,Standard_Transient) protected: //! prepares lists of optional data, set values to defaults Standard_EXPORT IGESData_IGESEntity(); //! Initializes Type and Form Numbers to new values. Reserved for //! special uses Standard_EXPORT void InitTypeAndForm (const Standard_Integer typenum, const Standard_Integer formnum); //! Loads a complete, already loaded, List of Asociativities //! (used during Read or Copy Operations) Standard_EXPORT void LoadAssociativities (const Interface_EntityList& list); //! Loads a complete, already loaded, List of Properties //! (used during Read or Copy Operations) Standard_EXPORT void LoadProperties (const Interface_EntityList& list); //! Removes all properties in once Standard_EXPORT void ClearProperties(); private: //! Clears specific IGES data Standard_EXPORT void Clear(); //! Adds an Associativity in the list (called by Associate only) Standard_EXPORT void AddAssociativity (const Handle(IGESData_IGESEntity)& ent); //! Removes an Associativity from the list (called by Dissociate) Standard_EXPORT void RemoveAssociativity (const Handle(IGESData_IGESEntity)& ent); //! Removes all associativities in once Standard_EXPORT void ClearAssociativities(); Standard_Integer theType; Standard_Integer theForm; Handle(IGESData_IGESEntity) theStructure; IGESData_DefSwitch theDefLineFont; Handle(IGESData_IGESEntity) theLineFont; Standard_Integer theDefLevel; Handle(IGESData_IGESEntity) theLevelList; Handle(IGESData_IGESEntity) theView; Handle(IGESData_IGESEntity) theTransf; Handle(IGESData_IGESEntity) theLabDisplay; Standard_Integer theStatusNum; Standard_Integer theLWeightNum; Standard_Real theLWeightVal; IGESData_DefSwitch theDefColor; Handle(IGESData_IGESEntity) theColor; Standard_Character theRes1[9]; Standard_Character theRes2[9]; Handle(TCollection_HAsciiString) theShortLabel; Standard_Integer theSubScriptN; Interface_EntityList theAssocs; Interface_EntityList theProps; }; #endif // _IGESData_IGESEntity_HeaderFile
#include "stdafx.h" #include <assert.h> #include "PackedFile.h" #include "UnpackedFile.h" PackedFile::PackedFile(UnpackedFile* pFile, offset_type size): m_pFile(pFile),m_Size(size),m_Buffer(4*1024) { m_Stream.zalloc = Z_NULL; m_Stream.zfree = Z_NULL; m_Stream.opaque = Z_NULL; m_Stream.avail_in = 0; m_Stream.next_in = Z_NULL; m_Stream.avail_out = 0; m_Stream.next_out = 0; int ret = inflateInit(&m_Stream); assert(ret == Z_OK); } PackedFile::~PackedFile(void) { inflateEnd(&m_Stream); delete m_pFile; } offset_type PackedFile::Read(void* buffer, offset_type size) { if(size.offset<=0) { offset_type z; z.offset = 0; return z; } m_Stream.avail_out = (unsigned int)size.offset; m_Stream.next_out = (unsigned char*)buffer; while(m_Stream.avail_out>0) { if(m_Stream.avail_in<=0) { offset_type sizetoread; sizetoread.offset = m_Buffer.size(); m_Stream.avail_in = (unsigned int)m_pFile->Read(&m_Buffer[0], sizetoread).offset; m_Stream.next_in = &m_Buffer[0]; } if(m_Stream.avail_in<=0) break; int result = inflate(&m_Stream, Z_NO_FLUSH); if(result != Z_OK) break; } offset_type sizeread; sizeread.offset = m_Stream.next_out - (unsigned char*)buffer; return sizeread; } offset_type PackedFile::Write(const void* buffer, offset_type size) { assert(0&&"not implemented"); offset_type z; z.offset = 0; return z; } offset_type PackedFile::Seek(offset_type pos, enum SeekMode mode) { assert(0&&"not implemented"); offset_type z; z.offset = 0; return z; } offset_type PackedFile::GetSize() { return m_Size; } void PackedFile::ReserveSpace(offset_type size) { assert(0&&"not implemented"); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2002-2007 */ /** \file regexp_advanced_api.h \brief "Advanced" API to the ECMAScript regular expression matcher. A regular expression is created and compiled by calling RegExp::RegExp() and then RegExp::Init(). After compilation the regexp can be used any number of times by calling RegExp::Exec(). See comments below for details. */ #ifndef REGEX_ADVANCED_API_H #define REGEX_ADVANCED_API_H #undef Yield class RegExpMatch { public: unsigned start; // index of first character unsigned length; // number of included characters }; /** A structure that holds flags passed to RegExp::Init */ struct RegExpFlags { RegExpFlags(); BOOL3 ignore_case; /**< This is the "i" flag in ECMAScript. If YES or NO, then the matcher is specialized at compile time, leading to a (slightly) faster matcher at run-time. If MAYBE, then the matcher may have to do extra work at run-time. */ BOOL3 multi_line; /**< This is the "m" flag in ECMAScript. As for ignore_case. */ BOOL ignore_whitespace; /**< This is the "x" flag in ECMAScript 4. If TRUE, then the regexp may contain newlines and line comments, and all comments and whitespace (including Unicode format control characters) are stripped from the regexp during compilation. */ BOOL searching; /**< This is the "y" flag in ECMAScript 4. */ }; class RE_Matcher; #undef Yield class RegExpSuspension { public: virtual void Yield() = 0; virtual void *AllocateL(unsigned nbytes) = 0; protected: virtual ~RegExpSuspension() {} }; class RE_Object; /** A class that represents a compiled regular expression. */ typedef BOOL (RegExpNativeMatcher)(RegExpMatch *result, const uni_char *source, unsigned index, unsigned length); class RegExp { #ifdef __GNUC__ friend class PreventGCCWarningAboutPrivateDestructorAndNoFriends; #endif // __GNUC__ public: /** Syntax errors generated by Init() */ enum ErrorCode { NO_REGEXP_ERROR=0, // Windows header files #defines NO_ERROR. Foo! // Syntax errors in alphabetical order. BACKREFERENCE_OUT_OF_RANGE, BRACKET_IN_CHARSET_IN_ILLEGAL_CONTEXT, CHARSET_NOT_TERMINATED_BY_BRACKET, CONTROL_CHAR_IS_NOT_LETTER, DASH_IN_CHARSET_IN_ILLEGAL_CONTEXT, END_OF_INPUT_AFTER_BACKSLASH, EXPECTED_RIGHTPAREN, INTERNAL_COMPILER_ERROR, JUNK_AT_END_OF_EXPRESSION, ONE_OR_MORE_DIGITS_EXPECTED, QUANTIFIER_MAX_IS_LESS_THAN_MIN, QUANTIFIER_NOT_TERMINATED_BY_BRACE, QUANTIFIER_OVERFLOW, QUESTION_SUBPATTERN_BAD_SYNTAX, RANGE_ENDPOINTS_NOT_ATOMIC_OR_RANGE_EMPTY, SLASH_NOT_FOUND, SYMBOLIC_BACKREFERENCE_BAD_SYNTAX, SYMBOLIC_BACKREFERENCE_MULTIPLY_DEFINED, SYMBOLIC_BACKREFERENCE_UNDEFINED }; RegExp(); /**< Initialize a regular expression matcher object. Increment the reference count. */ void IncRef(); /**< Increment the reference count */ void DecRef(); /**< Decrement the reference count and delete the object if the count reaches zero. */ OP_STATUS Init( const uni_char *pattern, unsigned length, const uni_char **slashpoint, RegExpFlags *flags ); /**< Construct a regular expression matcher. \param pattern The regular expression, NUL-terminated. \param slashpoint If NULL, this parameter has no effect. If not NULL, the parsing of the regex will terminate at the first toplevel "/" encountered in "pattern", and a pointer to the location of this "/" will be stored in *slashpoint. If a "/" is not found and no syntax error occurs before the end of the input is reached, then an error is returned and *slashpoint is set to point to the terminating NUL in "pattern". If a syntax error occurs before the end of the pattern is reached, an error is returned but *slashpoint will be NULL. \param flags A pointer to a flags structure, controlling both compilation and execution \return OpStatus::ERR if syntax error in pattern or if slash is not found, setting a value to be retrieved by SyntaxError() (or if Init is called on an inited object). OpStatus::ERR_NO_MEMORY on OOM. \remarks If compiled with REGEXP_SUBSET, ignore_case and multi_line must be either YES or NO on input, MAYBE is treated as NO. */ void SetIgnoreCaseFlag(BOOL3 v); /**< If the ignore_case flag set by Init is still MAYBE, then set it to v. */ void SetMultiLineFlag(BOOL3 v); /**< If the multi_line flag set by Init is still MAYBE, then set it to v. */ int GetNumberOfCaptures() const; /**< \return the number of capture groups defined by the expression */ #if !defined REGEXP_SUBSET && !defined REGEXP_STRICT int GetNumberOfSymbols() const; /**< \return the number of symbolic capture names defined by the expression */ const uni_char* GetSymbol(int i, int* index) const; /**< Retrieve information about a symbolic capture name defined by the expression. \param i The ordinal of the symbol we're retrieving. \param index (out) The capture index of that symbol \return The symbol. This string will be alive while the regexp is a live. */ #endif BOOL ExecL( const uni_char *input, unsigned int length, unsigned int last_index, RegExpMatch** results, RegExpSuspension* suspend=NULL, BOOL searching=TRUE ) const; BOOL ExecL( const uni_char *input, unsigned int length, unsigned int last_index, RegExpMatch* results, RegExpSuspension* suspend=NULL, BOOL searching=TRUE ) const; /**< Run the matcher on a string and generate match results. Matching will start at last_index but will try subsequent starting points if it fails at last_index. If a flag is still MAYBE, it is taken to be NO. Exec() is reentrant and thread-safe. Exec() allows the matching to be timesliced. This is normally only important if you do not control the pattern, because patterns can be constructed that take an arbitrary amount of time to finish. The timeslicing is not supported if REGEXP_SUBSET is defined. \param input The input string to match against; may contain NULs \param length The length of the input string \param last_index The index in input to start matching at \param results A location that will be given a pointer to an array of match results, when they have been generated. The match results are allocated on the standard heap with new[] \param suspend If not NULL this is either a suspension structure in its initial state or the structure created by a previous call on this method on *exactly* the same value for input. If the engine suspends before matching (returning -1) then this structure will be updated with values that allows the matching to be restarted where it left off. If the engine returns in any other manner, including by throwing an exception, then this structure is invalid and must not be reused. \param searching If TRUE then try for a match at last_index, and if that did not work then try again at last_index+1, and so on. Otherwise return the result of trying the match at last_index only. \return TRUE if the expression matched, FALSE otherwise. \exception OpStatus::ERR_NO_MEMORY on OOM. \remarks If compiled with REGEXP_SUBSET, the input string may not contain NULs and must in fact be NUL-terminated; length is ignored. */ #ifdef ECMASCRIPT_NATIVE_SUPPORT OP_STATUS CreateNativeMatcher(OpExecMemoryManager *executable_memory); /**< Create a machine code matcher for the expression, if the expression is one the JIT compiler supports, otherwise do nothing. @return OpStatus::OK on success, OpStatus::ERR if not supported and OpStatus::ERR_NO_MEMORY on OOM. */ RegExpNativeMatcher *GetNativeMatcher(); #endif // ECMASCRIPT_NATIVE_SUPPORT RegExpMatch *GetMatchArray(); #ifdef REGEXP_UNPARSER void Unparse( FILE *out ); /**< Print the representation of the regexp on stdout. The printout uses Cambridge Polish (fully parenthesized prefix) syntax and prints the compiled regexp as it is represented in the engine. This is useful for debugging the regexp engine. */ #endif RegExp::ErrorCode SyntaxError() const; /**< Return any syntax error code, following a return of OpStatus::ERR from Init() */ private: ~RegExp(); /**< Delete the matcher object and all its storage. */ private: int refcount; ///< Reference count RegExp::ErrorCode syntax_error; ///< Set by Init() on syntax errors RE_Object *re_cs, *re_ci; BOOL3 ignore_case; ///< Current value of the ignore-case flag BOOL3 multi_line; ///< Current value of the multi-line flag RegExpMatch *matches; }; inline RegExp::ErrorCode RegExp::SyntaxError() const { return syntax_error; } #endif // REGEX_ADVANCED_API_H /* eof */
#include <iostream> #include <math.h> using namespace std; int powersum(int a, int nterms) { int psum=0,rem; for(int i=nterms;i>0;i--) {rem=a%10; psum=psum + pow(rem,i); a=a/10;} return psum; } int main() { int n; cin>>n; int terms=0, a=n; while(a>0) {terms++; a=a/10;} int ps=powersum(n,terms); if(ps==n) cout<<"Disarim number"; else cout<<"Not a Disarim number"; return 0; }
// We use 4-character tabstops, so IN VIM: <esc>:set ts=4 and <esc>:set sw=4 // ...that's: ESCAPE key, colon key, then "s-e-t SPACE key t-s-=-4" // //-------- define these in your sketch, if applicable ---------------------------------------------------------- //-------- These must go in your sketch ahead of the #include <PinChangeInt.h> statement ----------------------- // You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts // on any one or two of the three ports. If only a single port remains, the handler will be declared inline // reducing the size and latency of the handler. // #define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts // #define NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts // #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts // --- Mega support --- // #define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts // #define NO_PORTJ_PINCHANGES // to indicate that port c will not be used for pin change interrupts // #define NO_PORTK_PINCHANGES // to indicate that port d will not be used for pin change interrupts // In the Mega, there is no Port C, no Port D. Instead, you get Port J and Port K. Port B remains. // Port J, however, is practically useless because there is only 1 pin available for interrupts. Most // of the Port J pins are not even connected to a header connection. // </end> "Mega Support" notes // -------------------- // // Other preprocessor directives... // You can reduce the code size by 20-50 bytes, and you can speed up the interrupt routine // slightly by declaring that you don't care if the static variables PCintPort::pinState and/or // PCintPort::arduinoPin are set and made available to your interrupt routine. // #define NO_PIN_STATE // to indicate that you don't need the pinState // #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin // #define DISABLE_PCINT_MULTI_SERVICE // to limit the handler to servicing a single interrupt per invocation. // #define GET_PCINT_VERSION // to enable the uint16_t getPCIintVersion () function. // The following is intended for testing purposes. If defined, then a variable PCintPort::pinmode can be read // in your interrupt subroutine. It is not defined by default: // #define PINMODE //-------- define the above in your sketch, if applicable ------------------------------------------------------ /* PinChangeInt.h ---- VERSIONS --- (NOTE TO SELF: Update the PCINT_VERSION define, below) ----------------- Version 2.01 (beta) Thu Jun 28 12:35:48 CDT 2012 ...Wow, Version 2! What? Why? Modified the way that the pin is tested inside the interrupt subroutine (ISR) PCintPort::PCint(), to make the interrupt quicker and slightly reduce the memory footprint. The interrupt's time is reduced by 2 microseconds or about 7%. Instead of using the mode variable, two bitmasks are maintained for each port. One bitmask contains all the pins that are configured to work on RISING signals, the other on FALLING signals. A pin configured to work on CHANGE signals will appear in both bitmasks of the port. Then, the test for a change goes like this: if (thisChangedPin) { if ((thisChangedPin & portRisingPins & PCintPort::curr ) || (thisChangedPin & portFallingPins & ~PCintPort::curr )) { where portRisingPins is the bitmask for the pins configured to interrupt on RISING signals, and portFallingPins is the bitmask for the pins configured to interrupt on FALLING signals. Each port includes these two bitmask variables. This is a significant change to some core functionality to the library, and it saves an appreciable amount of time (2 out of 36 or so micros). Hence, the 2.00 designation. Tue Jun 26 12:42:20 CDT 2012 I was officially given permission to use the PCint library: Re: PCint library « Sent to: GreyGnome on: Today at 08:10:33 AM » « You have forwarded or responded to this message. » Quote Reply Remove HI, Yeah, I wrote the original PCint library. It was a bit of a hack and the new one has better features. I intended the code to be freely usable. Didn't really think about a license. Feel free to use it in your code: I hereby grant you permission. I'll investigate the MIT license, and see if it is appropriate. Chris J. Kiick Robot builder and all around geek. Version 1.81 (beta) Tue Jun 19 07:29:08 CDT 2012 Created the getPCIntVersion function, and its associated GET_PCINT_VERSION preprocessor macro. The version is a 16-bit int, therefore versions are represented as a 4-digit integer. 1810, then, is the first beta release of 1.81x series. 1811 would be a bugfix of 1.810. 1820 would be the production release. Reversed the order of this list, so the most recent notes come first. Made some variables "volatile", because they are changed in the interrupt code. Thanks, Tony Cappellini! Added support for the Arduino Mega! Thanks to cserveny...@gmail.com! NOTE: I don't have a Mega, so I rely on you to give me error (or working) reports! To sum it up for the Mega: No Port C, no Port D. Instead, you get Port J and Port K. Port B remains. Port J, however, is practically useless because there is only 1 pin available for interrupts. Most of the Port J pins are not even connected to a header connector. Caveat Programmer. Created a function to report the version of this code. Put this #define ahead of the #include of this file, in your sketch: #define GET_PCINT_VERSION Then you can call uint16_t getPCIntVersion (); and it will return a 16-bit integer representation of the version of this library. That is, version 1.73beta will be reported as "1730". 1.74, then, will return "1740". And so on, for whatever version of the library this happens to be. The odd number in the 10's position will indicate a beta version, as per usual, and the number in the 1s place will indicate the beta revision (bugs may necessitate a 1.731, 1.732, etc.). Here are some of his notes based on his changes: Mega and friends are using port B, J and K for interrupts. B is working without any modifications. J is mostly useless, because of the hardware UART. I was not able to get pin change notifications from the TX pin (14), so only 15 left. All other (PORT J) pins are not connected on the Arduino boards. K controls Arduino pin A8-A15, working fine. 328/168 boards use C and D. So in case the lib is compiled with Mega target, the C and D will be disabled. Also you cannot see port J/K with other targets. For J and K new flags introduced: NO_PORTJ_PINCHANGES and NO_PORTK_PINCHANGES. Maybe we should have PORTJ_PINCHANGES to enable PJ, because they will be most likely unused. Enjoy! Note: To remain consistent, I have not included PORTJ_PINCHANGES. All ports behave the same, no matter how trivial those ports may seem... no surprises... Version 1.72 Wed Mar 14 18:57:55 CDT 2012 Release. Version 1.71beta Sat Mar 10 12:57:05 CST 2012 Code reordering: Starting in version 1.3 of this library, I put the code that enables interrupts for the given pin, and the code that enables Pin Change Interrupts, ahead of actually setting the user's function for the pin. Thus in the small interval between turning on the interrupts and actually creating a valid link to an interrupt handler, it is possible to get an interrupt. At that point the value of the pointer is 0, so this means that the Arduino will start over again from memory location 0- just as if you'd pressed the reset button. Oops! I corrected it so the code now operates in the proper order. (EDITORIAL NOTE: If you want to really learn something, teach it!) Minor code clean-up: All references to PCintPort::curr are now explicit. This changes the compiled hex code not one whit. I just sleep better at night. Numbering: Changed the numbering scheme. Beta versions will end with an odd number in the hundredths place- because they may be odd- and continue to be marked "beta". I'll just sleep better at night. :-) Version 1.70beta Mon Feb 27 07:20:42 CST 2012 Happy Birthday to me! Happy Birthday tooooo meee! Happy Birthday, Dear Meeeeee-eeeee! Happy Birthday to me! Yes, it is on this auspicious occasion of mine (and Elizabeth Taylor's [R.I.P.]) birthday that I humbly submit to you, gracious Arduino PinChangeInt user, version 1.70beta of the PinChangeInt library. I hope you enjoy it. New in this release: The PinChangeIntTest sketch was created, which can be found in the Examples directory. It exercises: * Two interrupting pins, one on each of the Arduino's PORTs. * detachInterrupt() (and subsequent attachInterrupt()s). Hopefully this will help avoid the embarrassing bugs that I have heretofore missed. As well, it has come to this author's (GreyGnome) attention that the Serial class in Arduino 1.0 uses an interrupt that, if you attempt to print from an interrupt (which is what I was doing in my tests) can easily lock up the Arduino. So I have taken SigurðurOrn's excellent ByteBuffer library and modified it for my own nefarious purposes. (see http://siggiorn.com/?p=460). The zipfile comes complete with the ByteBuffer library; see the ByteBuffer/ByteBuffer.h file for a list of changes, and see the PinChangeIntTest sketch for a usage scenario. Now the (interrupt-less and) relatively fast operation of filling a circular buffer is used in the interrupt routines. The buffer is then printed from loop(). The library has been modified so it can be used in other libraries, such as my AdaEncoder library (http://code.google.com/p/adaencoder/). When #include'd by another library you should #define the LIBCALL_PINCHANGEINT macro. For example: #ifndef PinChangeInt_h #define LIBCALL_PINCHANGEINT #include "../PinChangeInt/PinChangeInt.h" #endif This is necessary because the IDE compiles both your sketch and the .cpp file of your library, and the .h file is included in both places. But since the .h file actually contains the code, any variable or function definitions would occur twice and cause compilation errors- unless #ifdef'ed out. Version 1.6beta Fri Feb 10 08:48:35 CST 2012 Set the value of the current register settings, first thing in each ISR; e.g., ISR(PCINT0_vect) { PCintPort::curr = portB.portInputReg; // version 1.6 ... ...instead of at the beginning of the PCintPort::PCint() static method. This means that the port is read closer to the beginning of the interrupt, and may be slightly more accurate- only by a couple of microseconds, really, but it's a cheap win. Fixed a bug- a BUG!- in the attachInterrupt() and detachInterrupt() methods. I didn't have breaks in my switch statements! Augh! What am I, a (UNIX) shell programmer? ...Uh, generally, yes... Added the PINMODE define and the PCintPort::pinmode variable. Version 1.51 Sun Feb 5 23:28:02 CST 2012 Crap, a bug! Changed line 392 from this: PCintPort::pinState=curr & changedPins ? HIGH : LOW; to this: PCintPort::pinState=curr & p->mask ? HIGH : LOW; Also added a few lines of (commented-out) debug code. Version 1.5 Thu Feb 2 18:09:49 CST 2012 Added the PCintPort::pinState static variable to allow the programmer to query the state of the pin at the time of interrupt. Added two new #defines, NO_PIN_STATE and NO_PIN_NUMBER so as to reduce the code size by 20-50 bytes, and to speed up the interrupt routine slightly by declaring that you don't care if the static variables PCintPort::pinState and/or PCintPort::arduinoPin are set and made available to your interrupt routine. // #define NO_PIN_STATE // to indicate that you don't need the pinState // #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin Version 1.4 Tue Jan 10 09:41:14 CST 2012 All the code has been moved into this .h file, so as to allow #define's to work from the user's sketch. Thanks to Paul Stoffregen from pjrc.com for the inspiration! (Check out his website for some nice [lots more memory] Arduino-like boards at really good prices. ...This has been an unsolicited plug. Now back to our regular programming. ...Hehe, "programming", get it?) As a result, we no longer use the PinChangeIntConfig.h file. The user must #define things in his/her sketch. Which is better anyway. Removed the pcIntPorts[] array, which created all the ports by default no matter what. Now, only those ports (PCintPort objects) that you need will get created if you use the NO_PORTx_PINCHANGES #defines. This saves flash memory, and actually we get a bit of a memory savings anyway even if all the ports are left enabled. The attachInterrupt and detachInterrupt routines were modified to handle the new PCintPort objects. Version 1.3 Sat Dec 3 22:56:20 CST 2011 Significant internal changes: Tested and modified to work with Arduino 1.0. Modified to use the new() operator and symbolic links instead of creating a pre-populated PCintPins[]. Renamed some variables to simplify or make their meaning more obvious (IMHO anyway). Modified the PCintPort::PCint() code (ie, the interrupt code) to loop over a linked-list. For those who love arrays, I have left some code in there that should work to loop over an array instead. But it is commented out in the release version. For Arduino versions prior to 1.0: The new() operator requires the cppfix.h library, which is included with this package. For Arduino 1.0 and above: new.h comes with the distribution, and that is #included. Version 1.2 Sat Dec 3 Sat Dec 3 09:15:52 CST 2011 Modified Thu Sep 8 07:33:17 CDT 2011 by GreyGnome. Fixes a bug with the initial port value. Now it sets the initial value to be the state of the port at the time of attachInterrupt(). The line is port.PCintLast=port.portInputReg; in attachInterrupt(). See GreyGnome comment, below. Added the "arduinoPin" variable, so the user's function will know exactly which pin on the Arduino was triggered. Version 1.1 Sat Dec 3 00:06:03 CST 2011 ...updated to fix the "delPin" function as per "pekka"'s bug report. Thanks! ---- ^^^ VERSIONS ^^^ (NOTE TO SELF: Update the PCINT_VERSION define, below) ------------- See google code project for latest, bugs and info http://code.google.com/p/arduino-pinchangeint/ For more information Refer to avr-gcc header files, arduino source and atmega datasheet. This library was inspired by and derived from "johnboiles" (it seems) PCInt Arduino Playground example here: http://www.arduino.cc/playground/Main/PcInt If you are the original author, please let us know at the google code page It provides an extension to the interrupt support for arduino by adding pin change interrupts, giving a way for users to have interrupts drive off of any pin. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PinChangeInt_h #define PinChangeInt_h #define PCINT_VERSION 2010 // This number MUST agree with the version number, above. #include "stddef.h" // Thanks to Maurice Beelen, nms277, Akesson Karlpetter, and Orly Andico for these fixes. #if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #include <new.h> #else #include <WProgram.h> #include <pins_arduino.h> #ifndef LIBCALL_PINCHANGEINT #include "../cppfix/cppfix.h" #endif #endif #undef DEBUG /* * Theory: all IO pins on Atmega168 are covered by Pin Change Interrupts. * The PCINT corresponding to the pin must be enabled and masked, and * an ISR routine provided. Since PCINTs are per port, not per pin, the ISR * must use some logic to actually implement a per-pin interrupt service. */ /* Pin to interrupt map: * D0-D7 = PCINT 16-23 = PCIR2 = PD = PCIE2 = pcmsk2 * D8-D13 = PCINT 0-5 = PCIR0 = PB = PCIE0 = pcmsk0 * A0-A5 (D14-D19) = PCINT 8-13 = PCIR1 = PC = PCIE1 = pcmsk1 */ #undef INLINE_PCINT #define INLINE_PCINT // Thanks to cserveny...@gmail.com for MEGA support! #if defined __AVR_ATmega2560__ || defined __AVR_ATmega1280__ || defined __AVR_ATmega1281__ || defined __AVR_ATmega2561__ || defined __AVR_ATmega640__ #define __USE_PORT_JK // Mega does not have PORTC or D #define NO_PORTC_PINCHANGES #define NO_PORTD_PINCHANGES #if ((defined(NO_PORTB_PINCHANGES) && defined(NO_PORTJ_PINCHANGES)) || \ (defined(NO_PORTJ_PINCHANGES) && defined(NO_PORTK_PINCHANGES)) || \ (defined(NO_PORTK_PINCHANGES) && defined(NO_PORTB_PINCHANGES))) #define INLINE_PCINT inline #endif #else #if ((defined(NO_PORTB_PINCHANGES) && defined(NO_PORTC_PINCHANGES)) || \ (defined(NO_PORTC_PINCHANGES) && defined(NO_PORTD_PINCHANGES)) || \ (defined(NO_PORTD_PINCHANGES) && defined(NO_PORTB_PINCHANGES))) #define INLINE_PCINT inline #endif #endif // Provide drop in compatibility with johnboiles PCInt project at // http://www.arduino.cc/playground/Main/PcInt #define PCdetachInterrupt(pin) PCintPort::detachInterrupt(pin) #define PCattachInterrupt(pin,userFunc,mode) PCintPort::attachInterrupt(pin, userFunc,mode) #define PCgetArduinoPin() PCintPort::getArduinoPin() typedef void (*PCIntvoidFuncPtr)(void); class PCintPort { public: PCintPort(int index,int pcindex, volatile uint8_t& maskReg) : portInputReg(*portInputRegister(index)), portPCMask(maskReg), PCICRbit(1 << pcindex), portRisingPins(0), portFallingPins(0), firstPin(NULL) { #ifdef FLASH ledsetup(); #endif } volatile uint8_t& portInputReg; static void attachInterrupt(uint8_t pin, PCIntvoidFuncPtr userFunc, int mode); static void detachInterrupt(uint8_t pin); INLINE_PCINT void PCint(); static volatile uint8_t curr; #ifndef NO_PIN_NUMBER static volatile uint8_t arduinoPin; #endif #ifndef NO_PIN_STATE static volatile uint8_t pinState; #endif #ifdef PINMODE static volatile uint8_t pinmode; #endif #ifdef FLASH static void ledsetup(void); #endif protected: class PCintPin { public: PCintPin() : PCintFunc((PCIntvoidFuncPtr)NULL), mode(0) {} PCIntvoidFuncPtr PCintFunc; uint8_t mode; uint8_t mask; uint8_t arduinoPin; PCintPin* next; }; void addPin(uint8_t arduinoPin,uint8_t mode,PCIntvoidFuncPtr userFunc); void delPin(uint8_t mask); volatile uint8_t& portPCMask; const uint8_t PCICRbit; volatile uint8_t portRisingPins; volatile uint8_t portFallingPins; volatile uint8_t lastPinView; PCintPin* firstPin; }; #ifndef LIBCALL_PINCHANGEINT // LIBCALL_PINCHANGEINT *********************************************** volatile uint8_t PCintPort::curr=0; #ifndef NO_PIN_NUMBER volatile uint8_t PCintPort::arduinoPin=0; #endif #ifndef NO_PIN_STATE volatile uint8_t PCintPort::pinState=0; #endif #ifdef PINMODE volatile uint8_t PCintPort::pinmode=0; #endif #ifdef FLASH #define PINLED 13 volatile uint8_t *led_port; uint8_t led_mask; uint8_t not_led_mask; boolean ledsetup_run=false; void PCintPort::ledsetup(void) { if (! ledsetup_run) { led_port=portOutputRegister(digitalPinToPort(PINLED)); led_mask=digitalPinToBitMask(PINLED); not_led_mask=led_mask^0xFF; pinMode(PINLED, OUTPUT); digitalWrite(PINLED, LOW); ledsetup_run=true; } }; #endif #ifndef NO_PORTB_PINCHANGES PCintPort portB=PCintPort(2, 0,PCMSK0); // port PB==2 (from Arduino.h, Arduino version 1.0) #endif #ifndef NO_PORTC_PINCHANGES // note: no PORTC on MEGA PCintPort portC=PCintPort(3, 1,PCMSK1); // port PC==3 (also in pins_arduino.c, Arduino version 022) #endif #ifndef NO_PORTD_PINCHANGES // note: no PORTD on MEGA PCintPort portD=PCintPort(4, 2,PCMSK2); // port PD==4 #endif #ifdef __USE_PORT_JK #ifndef NO_PORTJ_PINCHANGES PCintPort portJ=PCintPort(10,1,PCMSK1); // port PJ==10 #endif #ifndef NO_PORTK_PINCHANGES PCintPort portK=PCintPort(11,2,PCMSK2); // port PK==11 #endif #endif void PCintPort::addPin(uint8_t arduinoPin, uint8_t mode,PCIntvoidFuncPtr userFunc) { // Create pin p: fill in the data. This is no longer in another method (saves some bytes). PCintPin* p=new PCintPin; p->arduinoPin=arduinoPin; p->mode = mode; p->next=NULL; p->mask = digitalPinToBitMask(arduinoPin); // the mask #ifdef DEBUG Serial.print("createPin. pin given: "); Serial.print(arduinoPin, DEC); int addr = (int) p; Serial.print(" instance addr: "); Serial.println(addr, HEX); Serial.print("userFunc addr: "); Serial.println((int)p->PCintFunc, HEX); #endif // pin created if (p == NULL) return; // Add to linked list, starting with firstPin if (firstPin == NULL) firstPin=p; else { PCintPin* tmp=firstPin; while (tmp->next != NULL) { tmp=tmp->next; }; tmp->next=p; } p->PCintFunc=userFunc; // Version 1.71 beta: move this step here from createPin: // Enable the pin for interrupts by adding to the PCMSKx register. // ...The final steps; at this point the interrupt is enabled on this pin. PCICR |= PCICRbit; portPCMask |= p->mask; if ((mode == RISING) || (mode == CHANGE)) portRisingPins |= p->mask; if ((mode == FALLING) || (mode == CHANGE)) portFallingPins |= p->mask; #ifdef DEBUG Serial.print("addPin. pin given: "); Serial.print(arduinoPin, DEC), Serial.print (" pin stored: "); int addr = (int) p; Serial.print(" instance addr: "); Serial.println(addr, HEX); #endif } void PCintPort::delPin(uint8_t mask) { PCintPin* current=firstPin; PCintPin* prev=NULL; while (current) { if (current->mask == mask) { // found the target uint8_t oldSREG = SREG; cli(); // disable interrupts portPCMask &= ~mask; // disable the mask entry. portRisingPins &= ~mask; portFallingPins &= ~mask; if (portPCMask == 0) PCICR &= ~(PCICRbit); // Link the previous' next to the found next. Then remove the found. if (prev != NULL) prev->next=current->next; // linked list skips over current. else firstPin=current->next; // at the first pin; save the new first pin delete current; SREG = oldSREG; // Restore register; reenables interrupts return; } prev=current; current=current->next; } } static PCintPort *lookupPortNumToPort( int portNum ) { PCintPort *port = NULL; switch (portNum) { #ifndef NO_PORTB_PINCHANGES case 2: port=&portB; break; #endif #ifndef NO_PORTC_PINCHANGES case 3: port=&portC; break; #endif #ifndef NO_PORTD_PINCHANGES case 4: port=&portD; break; #endif #ifdef __USE_PORT_JK #ifndef NO_PORTJ_PINCHANGES case 10: port=&portJ; break; #endif #ifndef NO_PORTK_PINCHANGES case 11: port=&portK; break; #endif #endif } return port; } /* * attach an interrupt to a specific pin using pin change interrupts. */ void PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode) { PCintPort *port; uint8_t portNum = digitalPinToPort(arduinoPin); if ((portNum == NOT_A_PORT) || (userFunc == NULL)) return; port=lookupPortNumToPort(portNum); // Added by GreyGnome... must set the initial value of lastPinView for it to be correct on the 1st interrupt. // ...but even then, how do you define "correct"? Ultimately, the user must specify (not provisioned for yet). port->lastPinView=port->portInputReg; // map pin to PCIR register port->addPin(arduinoPin,mode,userFunc); #ifdef DEBUG Serial.print("attachInterrupt FUNC: "); Serial.println(arduinoPin, DEC); #endif } void PCintPort::detachInterrupt(uint8_t arduinoPin) { PCintPort *port; #ifdef DEBUG Serial.print("detachInterrupt: "); Serial.println(arduinoPin, DEC); #endif uint8_t portNum = digitalPinToPort(arduinoPin); if (portNum == NOT_A_PORT) return; port=lookupPortNumToPort(portNum); port->delPin(digitalPinToBitMask(arduinoPin)); } // common code for isr handler. "port" is the PCINT number. // there isn't really a good way to back-map ports and masks to pins. void PCintPort::PCint() { #ifdef FLASH if (*led_port & led_mask) *led_port&=not_led_mask; else *led_port|=led_mask; #endif uint8_t thisChangedPin; #ifndef DISABLE_PCINT_MULTI_SERVICE uint8_t pcifr; do { #endif // get the pin states for the indicated port. uint8_t changedPins = PCintPort::curr ^ lastPinView; //changedPins &= portPCMask; lastPinView = PCintPort::curr; PCintPin* p = firstPin; // 3427 while (p) { thisChangedPin=p->mask & changedPins; if (thisChangedPin) { if ((thisChangedPin & portRisingPins & PCintPort::curr ) || (thisChangedPin & portFallingPins & ~PCintPort::curr )) { // Trigger interrupt if the bit is high and it's set to trigger on mode RISING or CHANGE // Trigger interrupt if the bit is low and it's set to trigger on mode FALLING or CHANGE #ifndef NO_PIN_STATE PCintPort::pinState=PCintPort::curr & p->mask ? HIGH : LOW; #endif #ifndef NO_PIN_NUMBER PCintPort::arduinoPin=p->arduinoPin; #endif #ifdef PINMODE PCintPort::pinmode=p->mode; #endif p->PCintFunc(); } } p=p->next; } #ifndef DISABLE_PCINT_MULTI_SERVICE pcifr = PCIFR & PCICRbit; PCIFR = pcifr; // clear the interrupt if we will process it (no effect if bit is zero) } while(pcifr); #endif } #ifndef NO_PORTB_PINCHANGES ISR(PCINT0_vect) { PCintPort::curr = portB.portInputReg; // version 1.6 portB.PCint(); } #endif #ifndef NO_PORTC_PINCHANGES ISR(PCINT1_vect) { PCintPort::curr = portC.portInputReg; // version 1.6 portC.PCint(); } #endif #ifndef NO_PORTD_PINCHANGES ISR(PCINT2_vect){ PCintPort::curr = portD.portInputReg; // version 1.6 portD.PCint(); } #endif #ifdef __USE_PORT_JK #ifndef NO_PORTJ_PINCHANGES ISR(PCINT1_vect) { PCintPort::curr = portJ.portInputReg; // version 1.73beta portJ.PCint(); } #endif #ifndef NO_PORTK_PINCHANGES ISR(PCINT2_vect){ PCintPort::curr = portK.portInputReg; // version 1.73beta portK.PCint(); } #endif #endif // __USE_PORT_JK #ifdef GET_PCINT_VERSION uint16_t getPCIntVersion () { return ((uint16_t) PCINT_VERSION); } #endif // GET_PCINT_VERSION #endif // #ifndef LIBCALL_PINCHANGEINT ************************************************************* #endif // #ifndef PinChangeInt_h *******************************************************************
/** * @file np_add_subtract_multiply_divide_f4_quad_hw.cc * @author Gerbrand De Laender * @date 21/04/2021 * @version 1.0 * * @brief E091103, Master thesis * * @section DESCRIPTION * * Element-wise addition, subtraction, multiplication and division. * Single precision (f4) implementation. * */ #include <hls_math.h> #include "np_add_subtract_multiply_divide_f4_quad.h" typedef union { unsigned int u4; np_t f4; } converter; void np_add_subtract_multiply_divide_f4_quad_hw(stream_t &X1, stream_t &X2, stream_t &OUT, len_t stream_len, sel_t sel) { #pragma HLS INTERFACE axis port=X1 #pragma HLS INTERFACE axis port=X2 #pragma HLS INTERFACE axis port=OUT #pragma HLS INTERFACE s_axilite port=stream_len #pragma HLS INTERFACE s_axilite port=sel #pragma HLS INTERFACE s_axilite port=return for(int i = 0; i < stream_len; i++) { #pragma HLS PIPELINE II=1 channel_t x1 = X1.read(); channel_t x2 = X2.read(); channel_t out; converter c1, c2,c3; switch(sel) { case 0x00: if(x1.keep(3, 0) & 0xf) { c1.u4 = x1.data.range(31, 0); c2.u4 = x2.data.range(31, 0); c3.f4 = c1.f4 + c2.f4; out.data.range(31, 0) = c3.u4; } if(x1.keep(7, 4) & 0xf) { c1.u4 = x1.data.range(63, 32); c2.u4 = x2.data.range(63, 32); c3.f4 = c1.f4 + c2.f4; out.data.range(63, 32) = c3.u4; } if(x1.keep(11, 8) & 0xf) { c1.u4 = x1.data.range(95, 64); c2.u4 = x2.data.range(95, 64); c3.f4 = c1.f4 + c2.f4; out.data.range(95, 64) = c3.u4; } if(x1.keep(15, 12) & 0xf) { c1.u4 = x1.data.range(127, 96); c2.u4 = x2.data.range(127, 96); c3.f4 = c1.f4 + c2.f4; out.data.range(127, 96) = c3.u4; } break; case 0x01: if(x1.keep(3, 0) & 0xf) { c1.u4 = x1.data.range(31, 0); c2.u4 = x2.data.range(31, 0); c3.f4 = c1.f4 - c2.f4; out.data.range(31, 0) = c3.u4; } if(x1.keep(7, 4) & 0xf) { c1.u4 = x1.data.range(63, 32); c2.u4 = x2.data.range(63, 32); c3.f4 = c1.f4 - c2.f4; out.data.range(63, 32) = c3.u4; } if(x1.keep(11, 8) & 0xf) { c1.u4 = x1.data.range(95, 64); c2.u4 = x2.data.range(95, 64); c3.f4 = c1.f4 - c2.f4; out.data.range(95, 64) = c3.u4; } if(x1.keep(15, 12) & 0xf) { c1.u4 = x1.data.range(127, 96); c2.u4 = x2.data.range(127, 96); c3.f4 = c1.f4 - c2.f4; out.data.range(127, 96) = c3.u4; } break; case 0x02: if(x1.keep(3, 0) & 0xf) { c1.u4 = x1.data.range(31, 0); c2.u4 = x2.data.range(31, 0); c3.f4 = c1.f4 * c2.f4; out.data.range(31, 0) = c3.u4; } if(x1.keep(7, 4) & 0xf) { c1.u4 = x1.data.range(63, 32); c2.u4 = x2.data.range(63, 32); c3.f4 = c1.f4 * c2.f4; out.data.range(63, 32) = c3.u4; } if(x1.keep(11, 8) & 0xf) { c1.u4 = x1.data.range(95, 64); c2.u4 = x2.data.range(95, 64); c3.f4 = c1.f4 * c2.f4; out.data.range(95, 64) = c3.u4; } if(x1.keep(15, 12) & 0xf) { c1.u4 = x1.data.range(127, 96); c2.u4 = x2.data.range(127, 96); c3.f4 = c1.f4 * c2.f4; out.data.range(127, 96) = c3.u4; } break; default: if(x1.keep(3, 0) & 0xf) { c1.u4 = x1.data.range(31, 0); c2.u4 = x2.data.range(31, 0); c3.f4 = c1.f4 / c2.f4; out.data.range(31, 0) = c3.u4; } if(x1.keep(7, 4) & 0xf) { c1.u4 = x1.data.range(63, 32); c2.u4 = x2.data.range(63, 32); c3.f4 = c1.f4 / c2.f4; out.data.range(63, 32) = c3.u4; } if(x1.keep(11, 8) & 0xf) { c1.u4 = x1.data.range(95, 64); c2.u4 = x2.data.range(95, 64); c3.f4 = c1.f4 / c2.f4; out.data.range(95, 64) = c3.u4; } if(x1.keep(15, 12) & 0xf) { c1.u4 = x1.data.range(127, 96); c2.u4 = x2.data.range(127, 96); c3.f4 = c1.f4 / c2.f4; out.data.range(127, 96) = c3.u4; } } out.keep = x1.keep; if(i == stream_len - 1) out.last = 1; OUT << out; } }
#ifndef TIME_H #define TIME_H #include <QDialog> namespace Ui { class time; } class time : public QDialog { Q_OBJECT public: explicit time(QWidget *parent = 0); ~time(); private: Ui::time *ui; }; #endif // TIME_H
// Copyright 2017 Elias Kosunen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #ifndef SCN_TUPLE_RETURN_UTIL_H #define SCN_TUPLE_RETURN_UTIL_H #include "../util/meta.h" #include <functional> #include <tuple> namespace scn { SCN_BEGIN_NAMESPACE namespace detail { // From cppreference template <typename Fn, typename... Args, typename std::enable_if<std::is_member_pointer< typename std::decay<Fn>::type>::value>::type* = nullptr, int = 0> constexpr auto invoke(Fn&& f, Args&&... args) noexcept( noexcept(std::mem_fn(f)(std::forward<Args>(args)...))) -> decltype(std::mem_fn(f)(std::forward<Args>(args)...)) { return std::mem_fn(f)(std::forward<Args>(args)...); } template <typename Fn, typename... Args, typename std::enable_if<!std::is_member_pointer< typename std::decay<Fn>::type>::value>::type* = nullptr> constexpr auto invoke(Fn&& f, Args&&... args) noexcept( noexcept(std::forward<Fn>(f)(std::forward<Args>(args)...))) -> decltype(std::forward<Fn>(f)(std::forward<Args>(args)...)) { return std::forward<Fn>(f)(std::forward<Args>(args)...); } // From Boost.mp11 template <typename T, T... I> struct integer_sequence { }; // iseq_if_c template <bool C, typename T, typename E> struct iseq_if_c_impl; template <typename T, typename E> struct iseq_if_c_impl<true, T, E> { using type = T; }; template <typename T, typename E> struct iseq_if_c_impl<false, T, E> { using type = E; }; template <bool C, typename T, typename E> using iseq_if_c = typename iseq_if_c_impl<C, T, E>::type; // iseq_identity template <typename T> struct iseq_identity { using type = T; }; template <typename S1, typename S2> struct append_integer_sequence; template <typename T, T... I, T... J> struct append_integer_sequence<integer_sequence<T, I...>, integer_sequence<T, J...>> { using type = integer_sequence<T, I..., (J + sizeof...(I))...>; }; template <typename T, T N> struct make_integer_sequence_impl; template <typename T, T N> struct make_integer_sequence_impl_ { private: static_assert( N >= 0, "make_integer_sequence<T, N>: N must not be negative"); static T const M = N / 2; static T const R = N % 2; using S1 = typename make_integer_sequence_impl<T, M>::type; using S2 = typename append_integer_sequence<S1, S1>::type; using S3 = typename make_integer_sequence_impl<T, R>::type; using S4 = typename append_integer_sequence<S2, S3>::type; public: using type = S4; }; template <typename T, T N> struct make_integer_sequence_impl : iseq_if_c<N == 0, iseq_identity<integer_sequence<T>>, iseq_if_c<N == 1, iseq_identity<integer_sequence<T, 0>>, make_integer_sequence_impl_<T, N>>> { }; // make_integer_sequence template <typename T, T N> using make_integer_sequence = typename detail::make_integer_sequence_impl<T, N>::type; // index_sequence template <std::size_t... I> using index_sequence = integer_sequence<std::size_t, I...>; // make_index_sequence template <std::size_t N> using make_index_sequence = make_integer_sequence<std::size_t, N>; // index_sequence_for template <typename... T> using index_sequence_for = make_integer_sequence<std::size_t, sizeof...(T)>; // From cppreference template <class F, class Tuple, std::size_t... I> constexpr auto apply_impl(F&& f, Tuple&& t, index_sequence<I...>) noexcept( noexcept(detail::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...))) -> decltype(detail::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...)) { return detail::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); } // namespace detail template <class F, class Tuple> constexpr auto apply(F&& f, Tuple&& t) noexcept( noexcept(detail::apply_impl( std::forward<F>(f), std::forward<Tuple>(t), make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>{}))) -> decltype(detail::apply_impl( std::forward<F>(f), std::forward<Tuple>(t), make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>{})) { return detail::apply_impl( std::forward<F>(f), std::forward<Tuple>(t), make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>{}); } } // namespace detail SCN_END_NAMESPACE } // namespace scn #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef SVG_SUPPORT #include "modules/svg/src/svgpch.h" #ifdef SVG_SUPPORT_FILTERS #include "modules/svg/src/SVGFilterTraversalObject.h" #include "modules/svg/src/SVGDocumentContext.h" #include "modules/svg/src/SVGChildIterator.h" #include "modules/svg/src/SVGManagerImpl.h" #include "modules/svg/src/AttrValueStore.h" #include "modules/svg/src/SVGTraverse.h" #include "modules/svg/src/SVGUtils.h" #include "modules/svg/src/SVGFilter.h" #include "modules/svg/src/svgpaintnode.h" #include "modules/svg/src/svgfilternode.h" #include "modules/layout/cascade.h" #include "modules/logdoc/urlimgcontprov.h" BOOL SVGFilterElement::EvaluateChild(HTML_Element* child) { if (child->GetNsType() == NS_SVG) { Markup::Type type = child->Type(); return type == Markup::SVGE_FETILE || type == Markup::SVGE_FEBLEND || type == Markup::SVGE_FEFLOOD || type == Markup::SVGE_FEIMAGE || type == Markup::SVGE_FEMERGE || type == Markup::SVGE_FEOFFSET || type == Markup::SVGE_FECOMPOSITE || type == Markup::SVGE_FEMORPHOLOGY || type == Markup::SVGE_FETURBULENCE || type == Markup::SVGE_FECOLORMATRIX || type == Markup::SVGE_FEGAUSSIANBLUR || type == Markup::SVGE_FECONVOLVEMATRIX || type == Markup::SVGE_FEDIFFUSELIGHTING || type == Markup::SVGE_FEDISPLACEMENTMAP || type == Markup::SVGE_FESPECULARLIGHTING || type == Markup::SVGE_FECOMPONENTTRANSFER; } return FALSE; } /** * This traverser walks a filter chain */ OP_STATUS SVGFilterTraversalObject::GetFilterPrimitiveRegion(HTML_Element* prim_element, SVGRect& region) { // Handle common attributes for filter primitives // Setup an appropriate boundingbox that is used to resolve // primitive dimensions to userspace values. SVGBoundingBox bbox; if (m_filter->GetPrimitiveUnits() == SVGUNITS_OBJECTBBOX) { bbox = m_filter->GetSourceElementBBox(); } else { bbox.minx = 0; bbox.miny = 0; bbox.maxx = 1; bbox.maxy = 1; } const SVGValueContext& vcxt = GetValueContext(); if (SVGUtils::GetResolvedLengthWithUnits(prim_element, Markup::SVGA_X, SVGLength::SVGLENGTH_X, m_filter->GetPrimitiveUnits(), vcxt, region.x)) { region.x *= bbox.maxx - bbox.minx; region.x += bbox.minx; } if (SVGUtils::GetResolvedLengthWithUnits(prim_element, Markup::SVGA_Y, SVGLength::SVGLENGTH_Y, m_filter->GetPrimitiveUnits(), vcxt, region.y)) { region.y *= bbox.maxy - bbox.miny; region.y += bbox.miny; } if (SVGUtils::GetResolvedLengthWithUnits(prim_element, Markup::SVGA_WIDTH, SVGLength::SVGLENGTH_X, m_filter->GetPrimitiveUnits(), vcxt, region.width)) { region.width *= bbox.maxx - bbox.minx; } if (SVGUtils::GetResolvedLengthWithUnits(prim_element, Markup::SVGA_HEIGHT, SVGLength::SVGLENGTH_Y, m_filter->GetPrimitiveUnits(), vcxt, region.height)) { region.height *= bbox.maxy - bbox.miny; } // "A negative value is an error" if (region.width < 0 || region.height < 0) return OpSVGStatus::INVALID_ARGUMENT; return OpStatus::OK; } SVGFilterNode* SVGFilterTraversalObject::LookupInput(HTML_Element* elm, Markup::AttrType input_attr) { // Get input SVGString* in_ref; AttrValueStore::GetString(elm, input_attr, &in_ref); if (in_ref) { unsigned len = in_ref->GetLength(); if (len >= 9) { const uni_char* s = in_ref->GetString(); if (len == 13 && uni_strncmp(s, "SourceGraphic", 13) == 0) return m_filter->GetFilterInputNode(INPUTNODE_SOURCEGRAPHIC); else if (len == 11 && uni_strncmp(s, "SourceAlpha", 11) == 0) return m_filter->GetFilterInputNode(INPUTNODE_SOURCEALPHA); else if (len == 15 && uni_strncmp(s, "BackgroundImage", 15) == 0) return m_filter->GetFilterInputNode(INPUTNODE_BACKGROUNDIMAGE); else if (len == 15 && uni_strncmp(s, "BackgroundAlpha", 15) == 0) return m_filter->GetFilterInputNode(INPUTNODE_BACKGROUNDALPHA); else if (len == 9 && uni_strncmp(s, "FillPaint", 9) == 0) return m_filter->GetFilterInputNode(INPUTNODE_FILLPAINT); else if (len == 11 && uni_strncmp(s, "StrokePaint", 11) == 0) return m_filter->GetFilterInputNode(INPUTNODE_STROKEPAINT); } // Resolve named references if (m_res_store.GetCount() > 0) { // Look for matching string for (int i = m_res_store.GetCount() - 1; i >= 0; i--) { SVGString* res = m_res_store.Get(i); if (res && res->GetString() && (res->GetLength() == in_ref->GetLength()) && uni_strncmp(res->GetString(), in_ref->GetString(), res->GetLength()) == 0) return m_filter->GetFilterNodeAt(i); } } } // If no name, or the name lookup fails, the reference is implicit // and refers to either the previous primitive or the // source(graphic) (if this is the first primitive). if (m_res_store.GetCount() > 0) // Implicit - previous primitive return m_filter->GetFilterNodeAt(m_res_store.GetCount() - 1); // Implicit if nothing has been filtered prior to this return m_filter->GetFilterInputNode(INPUTNODE_SOURCEGRAPHIC); } OP_STATUS SVGFilterTraversalObject::PushNode(SVGString* result_name, SVGFilterNode* filter_node) { // Put result string on lookup stack RETURN_IF_ERROR(m_res_store.Add(result_name)); // Push node OP_STATUS status = m_filter->PushFilterNode(filter_node); if (OpStatus::IsError(status)) { // Pop the result name from the result stack just in case m_res_store.Remove(m_res_store.GetCount() - 1); } return status; } OP_STATUS SVGFEPrimitive::HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info) { return traversal_object->HandleFilterPrimitive(info); } // Create paint nodes that will be used by an 'feImage' element void SVGFilterTraversalObject::CreateFeImage(HTML_Element* feimage_element, const SVGRect& feimage_region, SVGDocumentContext* doc_ctx, SVGElementResolver* resolver, SVGPaintNode*& paint_node) { URL* url = NULL; RETURN_VOID_IF_ERROR(AttrValueStore::GetXLinkHREF(doc_ctx->GetURL(), feimage_element, url)); if (url == NULL) // Failed to get an url to an image. // (??? Set error code in order to allocate a surface and pass it along.) return; SVGAspectRatio* ar = NULL; AttrValueStore::GetPreserveAspectRatio(feimage_element, ar); URL doc_url = doc_ctx->GetURL(); URL redirected_to = doc_url.GetAttribute(URL::KMovedToURL, TRUE); if (!redirected_to.IsEmpty()) doc_url = redirected_to; BOOL same_doc = (*url == doc_url); if (!same_doc && url->GetAttribute(URL::KIsImage, TRUE)) { URLStatus url_stat = (URLStatus)url->GetAttribute(URL::KLoadStatus, TRUE); if (url_stat != URL_LOADED) // Image url, but not loaded return; /* Render as if 'image' */ OpAutoPtr<SVGRasterImageNode> fei_raster_node(OP_NEW(SVGRasterImageNode, ())); if (!fei_raster_node.get()) return; // FIXME: This will skip overflow // Just assure that we have allocated a UrlImageContentProvider, skipping that while painting UrlImageContentProvider *provider = UrlImageContentProvider::FindImageContentProvider(*url); if (!provider) { provider = OP_NEW(UrlImageContentProvider, (*url)); if (!provider) return; } FramesDocument* frm_doc = doc_ctx->GetDocument(); #ifdef _PRINT_SUPPORT_ // Call this magic function (magic to me, at least) that creates a // fitting HEListElm for images in print documents that we fetch // below. if (frm_doc->IsPrintDocument()) frm_doc->GetHLDocProfile()->AddPrintImageElement(feimage_element, IMAGE_INLINE, url); #endif // _PRINT_SUPPORT_ HEListElm* hle = feimage_element->GetHEListElm(FALSE); if (!hle) return; provider->IncRef(); // Scope so that the Image object is destroyed before the // provider. { // To force loading - we use a big rectangle to make sure that // the image isn't undisplayed by accident when the user // scrolls The best rect would be the position and size of the // svg in the document, but we don't have access to that here. // Triggers an IncVisible that the HEListElm // owns. Unfortunately gets the wrong coordinates. hle->Display(frm_doc, AffinePos(), 20000, 1000000, FALSE, FALSE); Image img = provider->GetImage(); OpStatus::Ignore(img.OnLoadAll(provider)); } provider->DecRef(); // FIXME: Clipping fei_raster_node->Reset(); fei_raster_node->SetImageAspect(ar); fei_raster_node->SetImageViewport(feimage_region); fei_raster_node->SetImageQuality(SVGPainter::IMAGE_QUALITY_NORMAL); fei_raster_node->SetImageContext(*url, feimage_element, doc_ctx->GetDocument()); paint_node = fei_raster_node.release(); } else { // Not a (raster) image BOOL has_fragid = !!url->UniRelName(); if ((!same_doc || !has_fragid) #ifdef SVG_SUPPORT_SVG_IN_IMAGE && url->ContentType() != URL_SVG_CONTENT && url->ContentType() != URL_XML_CONTENT #endif // SVG_SUPPORT_SVG_IN_IMAGE ) // Unexpected/unconforming content return; // No fragment identifier - render as image // Has fragment identifier - render as 'use' HTML_Element* target = doc_ctx->GetElementByReference(resolver, feimage_element, *url); if (!target) return; OP_ASSERT(target->Type() == Markup::SVGE_SVG || has_fragid); if (same_doc) doc_ctx->RegisterDependency(feimage_element, target); if (!same_doc) { // NOTE: Overwrites the document context that was passed in doc_ctx = AttrValueStore::GetSVGDocumentContext(target); if (!doc_ctx) return; if (!has_fragid) // FIXME: This is ugly and most likely broken in certain cases doc_ctx->ForceSize(feimage_region.width.GetIntegerValue(), feimage_region.height.GetIntegerValue()); } /* Render as if 'image' */ OpAutoPtr<SVGVectorImageNode> fei_vector_node(OP_NEW(SVGVectorImageNode, ())); if (!fei_vector_node.get()) return; SVGMatrix viewport_xfrm; // Setup viewport and coordinate system to draw in viewport_xfrm.LoadTranslation(feimage_region.x, feimage_region.y); SVGNumberPair image_viewport(feimage_region.width, feimage_region.height); if (has_fragid && m_filter->GetPrimitiveUnits() == SVGUNITS_OBJECTBBOX) { SVGBoundingBox bbox = m_filter->GetSourceElementBBox(); image_viewport.x /= bbox.maxx - bbox.minx; image_viewport.y /= bbox.maxy - bbox.miny; viewport_xfrm.PostMultScale(bbox.maxx - bbox.minx, bbox.maxy - bbox.miny); } fei_vector_node->SetTransform(viewport_xfrm); SVGElementResolverStack resolver_mark(resolver); RETURN_VOID_IF_ERROR(resolver_mark.Push(target)); SVGNullCanvas canvas; canvas.GetTransform().Copy(viewport_xfrm); SVGRenderingTreeChildIterator rtci; SVGPaintTreeBuilder tree_builder(&rtci, fei_vector_node.get()); tree_builder.SetCanvas(&canvas); tree_builder.SetupResolver(resolver); tree_builder.SetDocumentContext(doc_ctx); tree_builder.SetCurrentViewport(image_viewport); RETURN_VOID_IF_ERROR(SVGTraverser::Traverse(&tree_builder, target, NULL)); paint_node = fei_vector_node.release(); } } /** * Get a light source element (one of feDistantLight, fePointLight and feSpotLight) * * @param elm Parent element * @param light The light source structure to fill in * * @return OpStatus::OK if successful */ void SVGFilterTraversalObject::GetLightSource(HTML_Element* elm, SVGLightSource& light) { // Traverse child nodes looking for light sources (fe*Light:s) HTML_Element *child_elm = elm->FirstChild(); while (child_elm) { if (child_elm->GetNsType() != NS_SVG) { child_elm = child_elm->Suc(); continue; } switch (child_elm->Type()) { case Markup::SVGE_FEDISTANTLIGHT: { light.type = SVGLightSource::SVGLIGHTSOURCE_DISTANT; SVGNumber azimuth; SVGNumber elevation; AttrValueStore::GetNumber(child_elm, Markup::SVGA_AZIMUTH, azimuth); AttrValueStore::GetNumber(child_elm, Markup::SVGA_ELEVATION, elevation); azimuth = azimuth * SVGNumber::pi() / 180; elevation = elevation * SVGNumber::pi() / 180; // Calculate the light vector // // Lx = cos(azimuth)*cos(elevation) // Ly = sin(azimuth)*cos(elevation) // Lz = sin(elevation) // light.x = azimuth.cos() * elevation.cos(); light.y = azimuth.sin() * elevation.cos(); light.z = elevation.sin(); } return; case Markup::SVGE_FEPOINTLIGHT: { light.type = SVGLightSource::SVGLIGHTSOURCE_POINT; // Get the light position light.x = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_X, SVGLength::SVGLENGTH_X, TRUE); light.y = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_Y, SVGLength::SVGLENGTH_Y, TRUE); light.z = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_Z, SVGLength::SVGLENGTH_OTHER, FALSE); } return; case Markup::SVGE_FESPOTLIGHT: { light.type = SVGLightSource::SVGLIGHTSOURCE_SPOT; // Get the light position light.x = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_X, SVGLength::SVGLENGTH_X, TRUE); light.y = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_Y, SVGLength::SVGLENGTH_Y, TRUE); light.z = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_Z, SVGLength::SVGLENGTH_OTHER, FALSE); // Get the what the light points at light.pointsAtX = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_POINTSATX, SVGLength::SVGLENGTH_X, TRUE); light.pointsAtY = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_POINTSATY, SVGLength::SVGLENGTH_Y, TRUE); light.pointsAtZ = m_filter->GetResolvedNumber(child_elm, Markup::SVGA_POINTSATZ, SVGLength::SVGLENGTH_OTHER, FALSE); // Get light attributes (cone angle/specular exponent) SVGNumberObject* cone_ang = NULL; AttrValueStore::GetNumberObject(child_elm, Markup::SVGA_LIMITINGCONEANGLE, &cone_ang); if (cone_ang != NULL) { light.has_cone_angle = TRUE; light.cone_angle = cone_ang->value.abs(); } else { light.has_cone_angle = FALSE; } AttrValueStore::GetNumber(child_elm, Markup::SVGA_SPECULAREXPONENT, light.spec_exponent, 1); } return; default: break; } child_elm = child_elm->Suc(); } // No light source found - using distant with azimuth = elevation = 0 } static BOOL IsValidStdDev(const SVGNumberPair& stddev) { // Default == 0, 0 disables effect return !(stddev.x.Equal(0) && stddev.y.Equal(0) || stddev.x < 0 || stddev.y < 0); } static BOOL IsValidMorphRadius(const SVGNumberPair& radius) { // Default == 0, 0 disables effect return !(radius.x.Equal(0) || radius.y.Equal(0) || radius.x < 0 || radius.y < 0); } OP_STATUS SVGFilterTraversalObject::HandleFilterPrimitive(SVGElementInfo& info) { HTML_Element* layouted_elm = info.layouted; Markup::Type type = layouted_elm->Type(); OpAutoPtr<SVGFilterNode> filter_node(NULL); const HTMLayoutProperties& props = *info.props->GetProps(); const SvgProperties *svg_props = props.svg; // Determine filtertype, and prepare as needed switch (type) { // The following filters has no 'in' attribute case Markup::SVGE_FETURBULENCE: { SVGNumberPair base_freq; SVGUtils::GetNumberOptionalNumber(layouted_elm, Markup::SVGA_BASEFREQUENCY, base_freq); SVGNumber num_octaves; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_NUMOCTAVES, num_octaves, 1); SVGNumber seed; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_SEED, seed, 0); SVGStitchType stitch_type = (SVGStitchType)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_STITCHTILES, SVGENUM_STITCHTILES, SVGSTITCH_NOSTITCH); SVGTurbulenceType turb_type = (SVGTurbulenceType)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_TYPE, SVGENUM_TURBULENCETYPE, SVGTURBULENCE_TURBULENCE); SVGGeneratorFilterNode* gen_filter_node = SVGGeneratorFilterNode::CreateNoise(turb_type, base_freq, num_octaves, seed, stitch_type); if (!gen_filter_node) return OpStatus::ERR_NO_MEMORY; filter_node.reset(gen_filter_node); } break; case Markup::SVGE_FEIMAGE: { // This is a bit of hack, but we need the primitive region // before creating the filter node, so that we can setup // the paint node correctly. Since the default subregion // is trivial on 'feImage' this is no biggy. SVGRect primitive_region = m_filter->GetFilterRegion(); RETURN_IF_ERROR(GetFilterPrimitiveRegion(layouted_elm, primitive_region)); SVGPaintNode* image_paint_node = NULL; CreateFeImage(layouted_elm, primitive_region, m_doc_ctx, m_resolver, image_paint_node); SVGGeneratorFilterNode* gen_filter_node = SVGGeneratorFilterNode::CreateImage(image_paint_node); if (!gen_filter_node) { if (image_paint_node) image_paint_node->Free(); return OpStatus::ERR_NO_MEMORY; } filter_node.reset(gen_filter_node); } break; case Markup::SVGE_FEFLOOD: { OP_ASSERT(svg_props->floodcolor.GetColorType() != SVGColor::SVGCOLOR_CURRENT_COLOR && "Hah! currentColor not resolved"); UINT32 flood_color = svg_props->floodcolor.GetRGBColor(); UINT8 flood_opacity = svg_props->floodopacity; SVGGeneratorFilterNode* gen_filter_node = SVGGeneratorFilterNode::CreateFlood(flood_color, flood_opacity); if (!gen_filter_node) return OpStatus::ERR_NO_MEMORY; filter_node.reset(gen_filter_node); } break; case Markup::SVGE_FEDIFFUSELIGHTING: case Markup::SVGE_FESPECULARLIGHTING: case Markup::SVGE_FECONVOLVEMATRIX: { SVGScaledUnaryFilterNode* sclu_filter_node; if (type == Markup::SVGE_FECONVOLVEMATRIX) { SVGVector* kernmat = NULL; AttrValueStore::GetVector(layouted_elm, Markup::SVGA_KERNELMATRIX, kernmat); if (kernmat == NULL) { SVG_NEW_ERROR(layouted_elm); SVG_REPORT_ERROR((UNI_L("Missing attribute kernelMatrix."))); } SVGNumberPair order; SVGUtils::GetNumberOptionalNumber(layouted_elm, Markup::SVGA_ORDER, order, 3); /* Calculate default divisor (SUM(kernel))*/ SVGNumber def_div = 0; if (kernmat) { for (unsigned int i = 0; i < kernmat->GetCount(); i++) if (SVGNumberObject* nval = static_cast<SVGNumberObject*>(kernmat->Get(i))) def_div += nval->value; } SVGNumber divisor; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_DIVISOR, divisor, def_div); if (divisor.Equal(0)) /* if the sum is zero, the default divisor is 1 */ divisor = 1; SVGNumber bias; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_BIAS, bias, 0); SVGNumberPair tgt; // If order is busted, then ignore target if (order.x > 0 && order.y > 0) { AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_TARGETX, tgt.x, order.x / 2); AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_TARGETY, tgt.y, order.y / 2); if (tgt.x < 0 || tgt.x >= order.x) tgt.x = order.x / 2; if (tgt.y < 0 || tgt.y >= order.y) tgt.y = order.y / 2; } bool preserve_alpha = !!AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_PRESERVEALPHA, SVGENUM_BOOLEAN, FALSE); SVGConvolveEdgeMode edge_mode = (SVGConvolveEdgeMode)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_EDGEMODE, SVGENUM_CONVOLVEEDGEMODE, SVGCONVOLVEEDGEMODE_DUPLICATE); sclu_filter_node = SVGScaledUnaryFilterNode::CreateConvolve(kernmat, order, tgt, divisor, bias, preserve_alpha, edge_mode); } else { OP_ASSERT(type == Markup::SVGE_FEDIFFUSELIGHTING || type == Markup::SVGE_FESPECULARLIGHTING); // Fetch common light configuration SVGLightSource light; GetLightSource(layouted_elm, light); SVGNumber surf_scale; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_SURFACESCALE, surf_scale, 1); OP_ASSERT(svg_props->lightingcolor.GetColorType() != SVGColor::SVGCOLOR_CURRENT_COLOR && "Hah! currentColor not resolved"); UINT32 light_color = svg_props->lightingcolor.GetRGBColor(); if (type == Markup::SVGE_FESPECULARLIGHTING) { // Fetch specular configuration SVGNumber ks, spec_exp; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_SPECULARCONSTANT, ks, 1); if (ks < 0) ks = 0; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_SPECULAREXPONENT, spec_exp, 1); if (spec_exp < 1) spec_exp = 1; else if (spec_exp > 128) spec_exp = 128; sclu_filter_node = SVGScaledUnaryFilterNode::CreateLighting(light, surf_scale, light_color, true /* specular */, ks, spec_exp); } else { // Fetch diffuse configuration SVGNumber kd; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_DIFFUSECONSTANT, kd, 1); sclu_filter_node = SVGScaledUnaryFilterNode::CreateLighting(light, surf_scale, light_color, false /* diffuse */, kd); } } if (!sclu_filter_node) return OpStatus::ERR_NO_MEMORY; // Fetch possible kernelUnitLength if (AttrValueStore::HasObject(layouted_elm, Markup::SVGA_KERNELUNITLENGTH, NS_IDX_SVG)) { SVGNumberPair unit_len = m_filter->GetResolvedNumberOptionalNumber(layouted_elm, Markup::SVGA_KERNELUNITLENGTH, 1); if (unit_len.x > 0 && unit_len.y > 0) sclu_filter_node->SetUnitLength(unit_len); } SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); sclu_filter_node->SetInput(input_node); filter_node.reset(sclu_filter_node); } break; case Markup::SVGE_FEGAUSSIANBLUR: { SVGNumberPair stddev = m_filter->GetResolvedNumberOptionalNumber(layouted_elm, Markup::SVGA_STDDEVIATION, 0); if (!IsValidStdDev(stddev)) { stddev.x = 0; stddev.y = 0; } SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateGaussian(stddev); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FEMORPHOLOGY: { SVGNumberPair radius = m_filter->GetResolvedNumberOptionalNumber(layouted_elm, Markup::SVGA_RADIUS, 0); // FIXME: Should < 0 be handled as zero, or as before (i.e, empty result)? // The below handles it as zero if (!IsValidMorphRadius(radius)) { radius.x = 0; radius.y = 0; } SVGMorphologyOperator morphop = (SVGMorphologyOperator)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_OPERATOR, SVGENUM_MORPHOLOGYOPERATOR, SVGMORPHOPERATOR_ERODE); SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateMorphology(morphop, radius); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FEOFFSET: { SVGNumberPair offset; offset.x = m_filter->GetResolvedNumber(layouted_elm, Markup::SVGA_DX, SVGLength::SVGLENGTH_X, FALSE); offset.y = m_filter->GetResolvedNumber(layouted_elm, Markup::SVGA_DY, SVGLength::SVGLENGTH_Y, FALSE); SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateOffset(offset); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FECOMPONENTTRANSFER: { /* Red = 0, Green = 1, Blue = 2, Alpha = 3 */ SVGCompFunc* funcs = OP_NEWA(SVGCompFunc, 4); if (!funcs) return OpStatus::ERR_NO_MEMORY; // Collect child nodes (feFuncX:s) for (HTML_Element* child_elm = layouted_elm->FirstChild(); child_elm; child_elm = child_elm->Suc()) { if (child_elm->GetNsType() != NS_SVG) continue; int func_idx = 0; switch (child_elm->Type()) { case Markup::SVGE_FEFUNCR: func_idx = 0; break; case Markup::SVGE_FEFUNCG: func_idx = 1; break; case Markup::SVGE_FEFUNCB: func_idx = 2; break; case Markup::SVGE_FEFUNCA: func_idx = 3; break; default: continue; } funcs[func_idx].type = (SVGFuncType)AttrValueStore::GetEnumValue(child_elm, Markup::SVGA_TYPE, SVGENUM_FUNCTYPE, SVGFUNC_IDENTITY); AttrValueStore::GetVector(child_elm, Markup::SVGA_TABLEVALUES, funcs[func_idx].table); AttrValueStore::GetNumber(child_elm, Markup::SVGA_SLOPE, funcs[func_idx].slope, 1); AttrValueStore::GetNumber(child_elm, Markup::SVGA_INTERCEPT, funcs[func_idx].intercept, 0); AttrValueStore::GetNumber(child_elm, Markup::SVGA_AMPLITUDE, funcs[func_idx].amplitude, 1); AttrValueStore::GetNumber(child_elm, Markup::SVGA_EXPONENT, funcs[func_idx].exponent, 1); AttrValueStore::GetNumber(child_elm, Markup::SVGA_OFFSET, funcs[func_idx].offset, 0); SVGObject::IncRef(funcs[func_idx].table); } SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateComponentTransfer(funcs); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FECOLORMATRIX: { SVGColorMatrixType colmattype = (SVGColorMatrixType)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_TYPE, SVGENUM_COLORMATRIXTYPE, SVGCOLORMATRIX_MATRIX); SVGVector* values = NULL; if (OpStatus::IsError(AttrValueStore::GetVectorWithStatus(layouted_elm, Markup::SVGA_VALUES, values))) { // These settings should be equal to using an identity matrix, // which happens to match the default values for the types where // 'values' are applicable colmattype = SVGCOLORMATRIX_MATRIX; values = NULL; } SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateColorMatrix(colmattype, values); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FETILE: { SVGFilterNode* input_node = LookupInput(layouted_elm, Markup::SVGA_IN); SVGRect in_region = input_node ? input_node->GetRegion() : m_filter->GetFilterRegion(); SVGSimpleUnaryFilterNode* unary_filter_node = SVGSimpleUnaryFilterNode::CreateTile(in_region); if (!unary_filter_node) return OpStatus::ERR_NO_MEMORY; unary_filter_node->SetInput(input_node); filter_node.reset(unary_filter_node); } break; case Markup::SVGE_FEBLEND: case Markup::SVGE_FECOMPOSITE: case Markup::SVGE_FEDISPLACEMENTMAP: { // Binary operations SVGBinaryFilterNode* binary_filter_node; if (type == Markup::SVGE_FEBLEND) { SVGBlendMode bmode = (SVGBlendMode)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_MODE, SVGENUM_BLENDMODE, SVGBLENDMODE_NORMAL); binary_filter_node = SVGBinaryFilterNode::CreateBlend(bmode); } else if (type == Markup::SVGE_FECOMPOSITE) { SVGCompositeOperator comp_op = (SVGCompositeOperator)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_OPERATOR, SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_OVER); /* Parameters for 'arithmetic' */ SVGNumber k1, k2, k3, k4; AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_K1, k1, 0); AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_K2, k2, 0); AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_K3, k3, 0); AttrValueStore::GetNumber(layouted_elm, Markup::SVGA_K4, k4, 0); binary_filter_node = SVGBinaryFilterNode::CreateComposite(comp_op, k1, k2, k3, k4); } else /* Markup::SVGE_FEDISPLACEMENTMAP */ { OP_ASSERT(type == Markup::SVGE_FEDISPLACEMENTMAP); SVGNumber scale = m_filter->GetResolvedNumber(layouted_elm, Markup::SVGA_SCALE, SVGLength::SVGLENGTH_OTHER, FALSE); SVGDisplacementSelector x_chan_sel = (SVGDisplacementSelector)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_XCHANNELSELECTOR, SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_A); SVGDisplacementSelector y_chan_sel = (SVGDisplacementSelector)AttrValueStore::GetEnumValue(layouted_elm, Markup::SVGA_YCHANNELSELECTOR, SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_A); binary_filter_node = SVGBinaryFilterNode::CreateDisplacement(x_chan_sel, y_chan_sel, scale); } if (!binary_filter_node) return OpStatus::ERR_NO_MEMORY; // This might look odd, but is intended SVGFilterNode* input2 = LookupInput(layouted_elm, Markup::SVGA_IN); SVGFilterNode* input1 = LookupInput(layouted_elm, Markup::SVGA_IN2); if (type == Markup::SVGE_FEDISPLACEMENTMAP) { // For the displacement filter, 'in' is the input to // displace, and 'in2' is the actual displacement map. SVGFilterNode* tmp = input1; input1 = input2; input2 = tmp; } binary_filter_node->SetFirstInput(input1); binary_filter_node->SetSecondInput(input2); filter_node.reset(binary_filter_node); } break; case Markup::SVGE_FEMERGE: { // This is a potentially N-ary operation // Collect all child nodes (feMergeNode:s) HTML_Element *child_elm = layouted_elm->FirstChild(); unsigned int input_count = 0; while (child_elm) { if (child_elm->IsMatchingType(Markup::SVGE_FEMERGENODE, NS_SVG)) input_count++; child_elm = child_elm->Suc(); } SVGNaryFilterNode* merge_filter_node = SVGNaryFilterNode::Create(input_count); if (!merge_filter_node) return OpStatus::ERR_NO_MEMORY; child_elm = layouted_elm->FirstChild(); input_count = 0; while (child_elm) { if (child_elm->IsMatchingType(Markup::SVGE_FEMERGENODE, NS_SVG)) { SVGFilterNode* input_node = LookupInput(child_elm, Markup::SVGA_IN); merge_filter_node->SetInputAt(input_count, input_node); input_count++; } child_elm = child_elm->Suc(); } filter_node.reset(merge_filter_node); } break; default: break; } if (filter_node.get()) { // Resolve the colorspace for this node SVGColorInterpolation colorinterp = (SVGColorInterpolation)svg_props->rendinfo.color_interpolation_filters; filter_node->ResolveColorSpace(colorinterp); // Calculate the default subregion filter_node->CalculateDefaultSubregion(m_filter->GetFilterRegion()); // Fetch and setup the primitive region SVGRect primitive_region = filter_node->GetRegion(); RETURN_IF_ERROR(GetFilterPrimitiveRegion(layouted_elm, primitive_region)); filter_node->SetRegion(primitive_region); // Get 'result' attribute SVGString* result_ref; AttrValueStore::GetString(layouted_elm, Markup::SVGA_RESULT, &result_ref); // Add node (and result reference) to filter RETURN_IF_ERROR(PushNode(result_ref, filter_node.get())); // Filter node is now owned by the SVGFilter - let go of the // reference filter_node.release(); } return OpStatus::OK; } #endif // SVG_SUPPORT_FILTERS #endif // SVG_SUPPORT
#include<iostream> #include<conio.h> using namespace std; main() { int inches; cout<<"enter a height in inches"; cin>>inches; cout<<"the height is "; int a=inches/12; int b=inches%12; cout<<a<<"'"<<" "<<b<<"''"<< endl; return 0; }