text
stringlengths
8
6.88M
//=========================================================================== /* This file is part of the CHAI 3D visualization and haptics libraries. Copyright (C) 2003-2004 by CHAI 3D. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License("GPL") version 2 as published by the Free Software Foundation. For using the CHAI 3D libraries with software that can not be combined with the GNU GPL, and for taking advantage of the additional benefits of our support services, please contact CHAI 3D about acquiring a Professional Edition License. \author: <http://www.chai3d.org> \author: Chris Sewell \version 1.1 \date 01/2004 */ //=========================================================================== //--------------------------------------------------------------------------- #include "CVertex.h" #include "CTriangle.h" #include "CCollisionBrute.h" //--------------------------------------------------------------------------- //=========================================================================== /*! Check if the given line segment intersects any triangle of the mesh. This method is called "brute force" because all triangles are checked by invoking their collision-detection methods. This method is simple but very inefficient. \fn bool cCollisionBrute::computeCollision(cVector3d& a_segmentPointA, cVector3d& a_segmentPointB, cGenericObject*& a_colObject, cTriangle*& a_colTriangle, cVector3d& a_colPoint, double& a_colSquareDistance, int a_proxyCall) \param a_segmentPointA Initial point of segment. \param a_segmentPointB End point of segment. \param a_colObject Returns pointer to nearest collided object. \param a_colTriangle Returns pointer to nearest collided triangle. \param a_colPoint Returns position of nearest collision. \param a_colSquareDistance Returns distance between ray origin and collision point. \param a_proxyCall If this is > 0, this is a call from a proxy, and the value of a_proxyCall specifies which call this is. When checking for the second and third constraint planes, only the neighbors of the triangle intersected in the first call need be checked, not the whole tree. Call with a_proxyCall = -1 for non-proxy calls. \return Return true if the line segment intersects a triangle. */ //=========================================================================== bool cCollisionBrute::computeCollision(cVector3d& a_segmentPointA, cVector3d& a_segmentPointB, cGenericObject*& a_colObject, cTriangle*& a_colTriangle, cVector3d& a_colPoint, double& a_colSquareDistance, int a_proxyCall) { // temp variables for storing results cGenericObject* colObject; cTriangle* colTriangle; cVector3d colPoint; bool hit = false; // convert two point segment into a segment described by a point and // a directional vector cVector3d dir; a_segmentPointB.subr(a_segmentPointA, dir); // compute the squared length of the segment double colSquareDistance = dir.lengthsq(); // check all triangles for collision and return the nearest one unsigned int ntriangles = m_triangles->size(); for (unsigned int i=0; i<ntriangles; i++) { // check for a collision between this triangle and the segment by // calling the triangle's collision detection method; it will only // return true if the distance between the segment origin and this // triangle is less than the current closest intersecting triangle // (whose distance squared is kept in colSquareDistance) if ((*m_triangles)[i].computeCollision( a_segmentPointA, dir, colObject, colTriangle, colPoint, colSquareDistance)) { a_colObject = colObject; a_colTriangle = colTriangle; a_colPoint = colPoint; a_colSquareDistance = colSquareDistance; hit = true; } } // return result return (hit); }
#pragma once class String { public: String(); ~String(); // 같은 방법을 하면 반대로도 바꿀 수 있음 static wstring StringToWString(string value); };
/* * Copyright 2016 Robert Bond * * 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. */ #define xpix 1280 #define ypix 960 struct loc { int px; // Pixel coords int py; double xd; // Pinhole (distored) camera coords double yd; double x; // Undistored camera cooords double y; double xm; // Mirror coord system coords double ym; double m1_theta; // Angles for mirrors double m2_theta; double m1_steps; // Steps for mirrors double m2_steps; }; class backlash; class hw { public: struct loc cur_loc; struct loc target; int last_m1; int last_m2; hw(backlash *pbl); void set_home(void); void do_move(int px, int py, int frame_index, const char *msg); double move_time(int px, int py); void do_xy_move(double x, double y, const char *msg); void do_correction(int px, int py, int frame_index, const char *msg); void switch_laser(bool laser_on); void pxy_to_loc(int px, int py, struct loc *ploc); void xy_to_loc(double x, double y, struct loc *ploc); double mm_per_pixel(int px, int py); void shutdown(void); bool hw_idle(void); bool keepout(int px, int py, int scale); private: volatile struct coms *pc; backlash *pbl; int m1_limit; int m2_limit; double px_to_xd(double px); double py_to_yd(double py); double xdyd_to_x(double xd, double yd); double xdyd_to_y(double xd, double yd); void pxy_to_xy(int px, int py, double &x, double &y); double calc_m2_theta(double x); double calc_m1_theta(double y, double m2Theta); double steps_to_theta(int steps); double theta_to_steps(double theta); bool start_move(double m1_steps, double m2_steps, bool laser_on); }; class backlash { public: backlash(); void correct(double *pm1s, double *pm2s); void start(hw* phw, double m1s, double m2s); void add_corr(hw* phw, double m1s, double m2s); void stop(hw* phw); void dumpit(); private: int last_m1; int last_m2; int m1_limit; int m2_limit; struct loc *pstart; struct loc *ptarget; struct step_list *pls; struct step_list *ple; int mvidx; void cleanup(); void actuals(struct step_list *pn, int *pm1, int *pm2); void dead_zone(struct step_list *pn, int *pm1dz, int *pm2dz); FILE *sql_out; }; extern bool verbose; #define DPRINTF if (verbose) printf
#ifndef PLAYER_H #define PLAYER_H #include <string.h> #include <time.h> #include <stdint.h> #include "Typedef.h" using namespace std; #define STATUS_PLAYER_LOGOUT 0 #define STATUS_PLAYER_INGAME 1 //正在打牌 #define GAME_END_NORMAL 0 #define GAME_END_DISCONNECT 1 #define GAME_END_DISCARD 2 #define BETNUM 5 class Player { public: Player(){}; virtual ~Player(){}; void init(); //内置函数 public: inline bool isLogout() {return m_nStatus == STATUS_PLAYER_LOGOUT;}; inline void setActiveTime(time_t t){active_time = t;} inline time_t getActiveTime(){return active_time;} inline void setEnterTime(time_t t){enter_time = t;} inline time_t getEnterTime(){return enter_time;} //行为函数 public: void leave(bool isSendToUser = true); void enter(); void reset(); bool notBetCoin(); void login(); public: int id; char name[64]; char json[1024]; char headlink[128]; short m_nHallid; short m_nStatus; short m_nTabIndex; int tax; int64_t m_lMoney; int64_t m_lWinScore; //最终输赢金币 int64_t m_lReturnScore; //自己下注的金币 int64_t m_lLoseScore; //输的金币 int64_t m_lResultArray[BETNUM]; int64_t m_lTempScore; //暂时 int tid; short source; short m_nSeatID; int m_nWin; int m_nLose; int m_nRunAway; int m_nTie; BYTE m_bisCall; //这盘是否抢了庄 int64_t m_lBetArray[BETNUM]; bool isonline; int m_nRoll; int m_nExp; bool m_bhasOpen; //是否在上庄列表 bool isbankerlist; bool isCanlcebanker; int m_nChatCostCount; //聊天花费金币 int64_t m_lRewardCoin; //中奖金币数额 int64_t m_lMaxWinMoney; int64_t m_lMaxCardValue; int m_nLastBetTime; int m_seatid; public: short pid; short cid; short sid; private: time_t active_time; //客户端最近活跃时间 time_t enter_time; //进入游戏的时间 time_t replay_time; //游戏等待时间,新一盘游戏开始时计时,用于机器人判断当前等待时间 time_t timeout_time; //游戏给他设置超时时间的时刻 }; #endif
/* ID: andonov921 TASK: lamps LANG: C++ */ #include <iostream> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <string> #include <algorithm> #include <sstream> #include <climits> #include <fstream> #include <cmath> using namespace std; /// ********* debug template by Bidhan Roy ********* template < typename F, typename S > ostream& operator << ( ostream& os, const pair< F, S > & p ) { return os << "(" << p.first << ", " << p.second << ")"; } template < typename T > ostream &operator << ( ostream & os, const vector< T > &v ) { os << "{"; typename vector< T > :: const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; } template < typename T > ostream &operator << ( ostream & os, const set< T > &v ) { os << "["; typename set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename T > ostream &operator << ( ostream & os, const unordered_set< T > &v ) { os << "["; typename unordered_set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const map< F, S > &v ) { os << "["; typename map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const unordered_map< F, S > &v ) { os << "["; typename unordered_map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } #define debug(x) cerr << #x << " = " << x << endl; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; typedef vector<bool> VB; typedef vector<int> VI; typedef vector<LL> VLL; typedef vector<string> VS; typedef vector<VB> VVB; typedef vector<VI> VVI; typedef vector<VLL> VVLL; typedef vector<VS> VVS; ifstream fin("lamps.in"); ofstream fout("lamps.out"); int num_lamps, button_presses, x; bool solved = false; VI final_conf(6, -1); // -1 = whatever, 1 = on, 0 = off void read_input(){ fin >> num_lamps; // 10 <= num_lamps <= 100 fin >> button_presses; // 0 <= button_presses <= 10000 while(fin >> x && x != -1){ final_conf[(x-1) % 6] = 1; } while(fin >> x && x != -1){ if(final_conf[(x-1) % 6] == 1){ solved = true; fout << "IMPOSSIBLE\n"; return; } final_conf[(x-1) % 6] = 0; } } bool check(VI &conf){ for(int i=0;i<final_conf.size();i++){ if(final_conf[i] != -1 && final_conf[i] != conf[i]) return false; } return true; } void update(VI &conf, int option){ int start, inc; if(option == 0){ start = 0; inc = 1; }else if(option == 1){ start = 0; inc = 2; }else if(option == 2){ start = 1; inc = 2; }else{ start = 0; inc = 3; } for(int i=start;i<conf.size();i+=inc){ conf[i] = (conf[i]) ? 0 : 1; } } void print(VI &conf){ for(int i=0;i<num_lamps;i++){ fout << conf[i % 6]; } fout << "\n"; } void solve(){ if(solved) return; set<VI> solution; int limit = 1 << 4; for(int i=0;i<limit;i++){ VI conf(6, 1); int ones = 0; for(int j=0;j<4;j++){ if(i & (1 << j)){ ones++; update(conf, j); } } if(button_presses == 0 && ones != 0) continue; if(button_presses == 1 && ones != 1) continue; if(check(conf)){ solution.insert(conf); } } if(!solution.size()){ fout << "IMPOSSIBLE\n"; return; } for(auto conf : solution){ print(conf); } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); read_input(); solve(); return 0; }
#include<bits/stdc++.h> using namespace std; main() { long long int i,sum=0,n; while(scanf("%lld",&n)==1) { if(n==0) break; else if(1<=n<=100) { for(i=n; i>=1; i--) { sum+=(i*i); } printf("%lld\n",sum); sum=0; } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Marcin Zdun (mzdun) */ #ifdef AUTO_UPDATE_SUPPORT #ifndef MAC_ASYNC_PROCESS_RUNNER_H #define MAC_ASYNC_PROCESS_RUNNER_H enum PIM_PROCESS_STATE { PIM_PROCESS_STATE_QUERY_ERROR = -1, PIM_PROCESS_RUNNING, PIM_PROCESS_FINISHED }; class PIM_MacAsyncProcessRunner: public PIM_AsyncProcessRunner, public OpTimerListener { public: PIM_MacAsyncProcessRunner(); ~PIM_MacAsyncProcessRunner(); OP_STATUS RunProcess(const OpStringC& a_app, const OpStringC& a_params); OP_STATUS KillProcess(); void OnTimeOut(OpTimer* timer); class ProcessObserver { public: virtual ~ProcessObserver() {} virtual PIM_PROCESS_STATE hasFinished(int& return_value) = 0; virtual bool start() = 0; virtual int terminate() = 0; }; protected: void KickTimer(); int Mount(const OpStringC& dmg); void Umount(); void InitAppInstaller(); OP_STATUS InitPackageInstaller(const OpStringC& pkg_path); void OnProcessFinished(int exit_code); int PackageElevation(const OpStringC& pkg_name); enum STATE { IDLE, //the START state MOUNTED, //Mount happened - we can search for installer INSTALLING, //Installer seems to be running FINISHED //Instaler stopped, the image can be Umounted }; OpString m_mount_name; OpTimer m_poll_timer; STATE m_state; OpAutoPtr<ProcessObserver> m_process; }; #endif //MAC_ASYNC_PROCESS_RUNNER_H #endif //AUTO_UPDATE_SUPPORT
#include "Credits.h" Credits::Credits(QWidget* parent) : QDialog(parent) { this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); this->setAttribute(Qt::WA_DeleteOnClose); QHBoxLayout* layout = new QHBoxLayout(this); ini(layout); this->exec(); } void Credits::ini(QHBoxLayout* layout) { QLabel* logo = new QLabel(this); QLabel* text = new QLabel( QStringLiteral("<h1>This project</h1>" "<p>This project was mainly made to showcase my skills and keep an history of my progression.</p>" "<p>The developpement started on 2nd, november 2020 and is avaible on <a href=\"https://github.com/Wizer21/Swich\" style=\"color:#d64b4b\">GitHub</a></p>" "<p>This project was only made through C++ with the Qt library.</p>" "<p>I realized the logo on Photoshop.</p></p>" "<p>Faces pictures come from the deep learning generator <a href=\"https://thispersondoesnotexist.com\" style=\"color:#d64b4b\">ThisPersonDoesNotExist</a></p>" "<p>and icons from <a href=\"https://materialdesignicons.com\" style=\"color:#d64b4b\">MaterialDesignIcons</a></p>"), this); text->setWordWrap(true); text->setTextFormat(Qt::RichText); text->setTextInteractionFlags(Qt::TextBrowserInteraction); text->setOpenExternalLinks(true); text->adjustSize(); SingleData* single = single->getInstance(); logo->setPixmap(single->getPixmap("creditLogo")); layout->addWidget(logo); layout->addWidget(text); } Credits::~Credits() { }
#ifndef TYPES_HPP #define TYPES_HPP #include <vector> #include <set> #include <utility> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/ext.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> //define global variables, some of them is not force to use, others are this are //optional names, definitely not called directly in any code, users always have //the privilege to use other names #define UNIFORM_MVP "mvp" #define UNIFORM_BONE_ARR "bone_array" #define UNIFORM_TEX_DIFFUSE "defuse_map" #define UNIFORM_TEX_SPECULAR "specular_map" #define UNIFORM_TEX_SHADOW_MAP "shadow_map" #define UNIFORM_TEX_CUBEMAP "cube_map" //define uint now typedef unsigned int uint; //well, we end up make those difficult type just to fix small bugs. Well, how //can I say. This is definitly not complete. Very first example, we can't get a //cubemap texture type here, but it is supported very well by OpenGL. enum TEX_TYPE { TEX_Diffuse=0, TEX_Specular=1, TEX_Normal=2, TEX_Ambient=3, TEX_NASSIMP_TYPE=4, //it doesnt support cubemap, we need write a specific loadCubeMap function TEX_NTexType=5, TEX_CubeMap=6, }; typedef struct { aiTextureType aiTextype; TEX_TYPE ourTextype; } sprt_tex2d_t; extern sprt_tex2d_t texture_types_supported[TEX_NASSIMP_TYPE]; class Texture { public: //GPU representation GLuint id; TEX_TYPE type; Texture(GLuint gpu_handle, TEX_TYPE type) { this->id = gpu_handle; this->type = type; } }; typedef std::vector<Texture> Material; //here is how you draw the texture if it is supported by assimp //for //for (int i = 0; i < shader->getSupported_texture_uniforms; i++) // glActiveTexture(GL_TEXTURE0 + shader->support_texture_start_indx + i) // glBindTexture(GL_TEXTURE_2D, matid_someting) //This msg_t has to be POD data type. //the message system is used by draw objects to aquire input and output data typedef union msg_t { uint32_t u; int32_t i; float f; double d; const char *name; bool b; msg_t() {this->d=0.0;} msg_t(uint32_t ud) {this->u = ud;} msg_t(int32_t id) {this->i = id;} msg_t(float fd) {this->f = fd;} msg_t(double dd) {this->d = dd;} msg_t(const char *n) {this->name = n;} msg_t(bool _b) {this->b = _b; } } msg_t; //Other more specific types typedef std::set<double> timestamps_t; struct RST { glm::vec3 t; glm::quat r; glm::vec3 s; }; struct RSTs { std::vector<glm::vec3> translations; std::vector<glm::quat> rotations; std::vector<glm::vec3> scales; //I don't remember why I implemented this way... void addInstance(const glm::vec3 p, const glm::quat r=glm::quat(glm::vec3(0.0)), const glm::vec3 s=glm::vec3(1.0f)); }; inline void RSTs::addInstance(const glm::vec3 p, const glm::quat r, const glm::vec3 s) { this->translations.push_back(p); this->rotations.push_back(r); this->scales.push_back(s); } typedef struct RSTs Instances; struct Vertex { glm::vec3 pos; glm::vec3 normal; glm::vec2 tex; }; struct Vertices { std::vector<glm::vec3> Positions; std::vector<glm::vec3> Normals; std::vector<glm::vec2> TexCoords; }; typedef glm::u32vec3 face_t; typedef std::vector<face_t> Faces; #endif /* EOF */
/************************************************************************/ /* 已知集合A和B的元素分别用不含头结点的单链表存储,函数difference()用于求解集合A与B的差集, * 并将结果保存在集合A的单链表中。 * 例如,若集合A={5,10,20,15,25,30},集合B={5,15,35,25},完成计算后A={10,20,30}。*/ /************************************************************************/ #include <vector> #include <algorithm> using namespace std; struct Node { int value; Node* next; Node(int val):value(val), next(NULL){} }; class Solution{ public: void difference(Node *A, Node *B){ vector<int> aNodeVector; vector<int> bNodeVector; vector<int> result; Node *p = A; Node *q = B; while(p){ aNodeVector.push_back(p->value); p = p->next; } while(q){ bNodeVector.push_back(q->value); q = q->next; } sort(aNodeVector.begin(), aNodeVector.end()); sort(bNodeVector.begin(), bNodeVector.end()); int i = 0, j = 0; while(i < aNodeVector.size() && j < bNodeVector.size()){ if(aNodeVector[i] < bNodeVector[j]){ result.push_back(aNodeVector[i]); ++i; } else{ if(aNodeVector[i] == bNodeVector[j]){ ++i; ++j; } else{ ++j; } } } while(i < aNodeVector.size()){ result.push_back(aNodeVector[i]); ++i; } p = A; for(int k = 0; k < result.size(); ++k, p = p->next){ p->value = result[k]; } //while(p){ // q = p; // p = p->next; // free(q); //} } }; //int main(){ // Node a(5); // Node b(40); // Node c(50); // Node d(10); // Node e(20); // Node f(30); // // a.next = &b; // b.next = &c; // c.next = &d; // d.next = &e; // e.next = &f; // // // Node g(5); // Node h(10); // Node i(20); // Node j(30); // // g.next = &h; // h.next = &i; // i.next = &j; // // Solution solution; // solution.difference(&a, &g); // // return 0; //}
#pragma once #include <Poco/SharedPtr.h> #include <Poco/ThreadPool.h> #include <Poco/Timespan.h> #include "util/Loggable.h" namespace BeeeOn { class HavingThreadPool : protected virtual Loggable { public: HavingThreadPool(); virtual ~HavingThreadPool(); void setMinThreads(int min); void setMaxThreads(int max); void setThreadIdleTime(const Poco::Timespan &time); Poco::ThreadPool &pool(); protected: void initPool(); private: int m_minThreads; int m_maxThreads; Poco::Timespan m_threadIdleTime; Poco::SharedPtr<Poco::ThreadPool> m_pool; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2002-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef CSSMANAGER_H #define CSSMANAGER_H #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/prefs/prefsmanager/opprefslistener.h" #include "modules/util/opfile/opfile.h" class CSS; class HTML_Element; class OpFile; class HLDocProfile; class OpInputAction; /** * Class used to handle local CSS files. */ class CSSManager : public PrefsCollectionFilesListener { public: /** * Enumeration describing the CSSes that are stored by the CSS manager. */ enum css_id { BrowserCSS = 0, ///< Browser's local style sheet #ifdef _WML_SUPPORT_ WML_CSS, ///< WML style sheet #endif #ifdef CSS_MATHML_STYLESHEET MathML_CSS, ///< MathML stylesheet #endif // CSS_MATHML_STYLESHEET #ifdef SUPPORT_VISUAL_ADBLOCK ContentBlockCSS, ///< css file used in content block edit mode #endif LocalCSS, ///< User's local style sheet FirstUserStyle ///< Other user stylesheets }; CSSManager(); void ConstructL(); virtual ~CSSManager(); /** * Retrieve the parsed style sheet. * * @param which The type of style sheet to retrieve. * @return The parsed style sheet. NULL if none. */ CSS* GetCSS(unsigned int which) { return m_localcss[which].css; } /** * Load all local CSSes. Will query the preferences subsystem for the * file names, and load and parse the local CSS files for the default * context. */ void LoadLocalCSSL(); #if defined LOCAL_CSS_FILES_SUPPORT /** * Update the enabled/disabled status of the extra user stylesheets * based on prefs. Call this when the prefs are changed. */ void UpdateActiveUserStyles(); #endif // LOCAL_CSS_FILES_SUPPORT /** * Gets a signal that a file preference has changed, so that CSSManager * can reload the appropriate files. * * @param which The file that has changed. * @param what File object describing the new file. */ virtual void FileChangedL(PrefsCollectionFiles::filepref which, const OpFile* what); #ifdef LOCAL_CSS_FILES_SUPPORT virtual void LocalCSSChanged(); #endif /** Create an HTML Link element as a placeholder for a local stylesheet. @return A new HTML_Element of Markup::HTE_LINK type. Leaves on OOM. */ static HTML_Element* NewLinkElementL(const uni_char* url); /** Load css from a file and return the HTML_Element tree of dummy link elements for the file itself and its imports. */ static HTML_Element* LoadCSSFileL(OpFile* file, BOOL user_defined); /** Load and parse a stylesheet based on the href. URL must be file: or data:. */ static OP_STATUS LoadCSS_URL(HTML_Element* css_he, BOOL user_defined); /** * Handle a specific action. Should be called from VisualDevice::OnInputAction. * We handle the actions from style/module.actions here. * * @param action The action. * @param handled Set to TRUE if the action was handled. * @return OpStatus::OK or the LEAVE value from LoadLocalCSSL on error. */ OP_STATUS OnInputAction(OpInputAction* action, BOOL& handled); private: struct LocalStylesheet { HTML_Element* elm; CSS* css; LocalStylesheet() : elm(NULL), css(NULL) {}; ~LocalStylesheet(); }; /** An array of LINK HTML_Element object pointers for the local stylesheets and their CSS objects. Host overrides are found in the CSSCollection objects per document. */ LocalStylesheet* m_localcss; #ifdef EXTENSION_SUPPORT public: typedef UINTPTR ExtensionStylesheetOwnerID; struct ExtensionStylesheet : public Link, public LocalStylesheet { OpString path; ExtensionStylesheetOwnerID owner; }; private: /** A linked list of LINK HTML_Element object pointers for the local stylesheets defined by extensions, and their CSS objects. */ Head m_extensionstylesheets; public: /** * Get the user style sheets that were loaded by an extension. * * @return The first user style sheet from an extension. */ ExtensionStylesheet* GetExtensionUserCSS() { return reinterpret_cast<ExtensionStylesheet*>(m_extensionstylesheets.First()); } /** * Add a user style sheet from a loaded extension. * * @param path The path to the extension user CSS file. * @param owner The owner of this user CSS file. * @return OpStatus::OK if everything went fine. */ OP_STATUS AddExtensionUserCSS(const uni_char* path, ExtensionStylesheetOwnerID owner); /** * Remove user style sheets that was loaded by an extension. * * @param owner The owner to remove all user style sheets from. */ void RemoveExtensionUserCSSes(ExtensionStylesheetOwnerID owner); #endif }; #endif // CSSMANAGER_H
//算法:DP //思路: //很容易推出:状态转移方程为: //a[i][j]=max(a[i+1][j],a[i+1][j+1])+a[i][j]; //则从最底层开始往上推 //推到顶,就得到了答案 #include<cstdio> #include<algorithm> using namespace std; int a[1010][1010],n; int main() { scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<i+1;j++) scanf("%d",&a[i][j]);//输入 for(int i=n-2;i>=0;i--) for(int j=0;j<i+1;j++) a[i][j]+=max(a[i+1][j],a[i+1][j+1]);//从底层往上层推 printf("%d",a[0][0]);//输出顶层 }
// ili9225x driver interface implementation #ifndef _ili_9225_x_cc_ #define _ili_9225_x_cc_ // ili925x.cc file - ILITEK a-Si TFT LCD Single Chip Driver // #include <esfwxe/utils.h> #define ili9225xCmdWrite(regAddr, reg) \ esguiScreenBusWriteCmdB(hdrv->hbus, (regAddr)); \ esguiScreenBusWriteDataW(hdrv->hbus, (reg)) // Entry Mode (R03h) // R/W RS D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0 // W 1 0 0 0 BGR 0 0 MDT1 MDT0 0 0 ID1 ID0 AM 0 0 0 // AM Control the GRAM update direction. When AM = “0”, the address is updated in horizontal writing direction. // When AM = “1”, the address is updated in vertical writing direction. When a window area is set by // registers R36h/R37h and R38h/R39h, only the addressed GRAM area is updated based on I/D[1:0] and // AM bits setting. // I/D[1:0] Control the address counter (AC) to automatically increase or decrease by 1 when update one pixel // display data. // // AM I/D[1:0] Register R20/R21 Start Address // 00 R20 00AFh R21 00DBh // 01 R20 0000h R21 00DBh // 0/1 10 R20 00Afh R21 0000h // 11 R20 0000h R21 0000h // // MDT1: This bit is active on the 80-system of 8-bit bus and the data for 1-pixel is transported to // the memory for 3 write cycles. // This bit is on the 80-system of 16-bit bus, and the data for 1-pixel is transported // to the memory for 2 write cycles. When the 80-system interface mode is not set in the 8-bit // or 16-bit mode, set MDT1 bit to be “0”. // MDT0: When 8-bit or 16-bit 80 interface mode and MDT1 bit=1, MDT0 defines color depth for the IC. 0 = 262K, 1 = 65K // // BGR Swap the R and B order of written data. // // set\get ili9225x screen rotation #pragma Otime static void ili9225xSetScreenRotation(ESGUI_HDRV hdrv, ESGUI_SCREEN_ROTATION rotation) { // Preserve main part of output control // SS = 0, SM,GS = 0 // We also set the line count in accordance to the display physical height esU16 outCtl = ((hdrv->height >= 220) ? 0x001C : hdrv->height / 8); // Preserve main part of entry mode // 65k, 8bit, pixel transmission is B-G-R esU16 entryMode = 0x1300; // NB! SS bit value should be paired with RGB|BGR bit value to maintain current color order esguiScreenIoBatchBegin(hdrv); hdrv->rotation = rotation; switch( rotation ) { case ESGUI_SCREEN_ROT_0: // GS = 0, SS = 1 outCtl |= 0x0100; // update AM = 0, ID = 11 // horizontal increment, vertical increment entryMode |= 0x0030; break; case ESGUI_SCREEN_ROT_180: // GS = 0, SS = 1 outCtl |= 0x0100; // update AM = 0, ID = 00 // horizontal decrement, vertical decrement break; case ESGUI_SCREEN_ROT_90CCW: // GS = 0, SS = 1 outCtl |= 0x0100; // update AM = 1, ID = 01 // horizontal increment, vertical decrement entryMode |= 0x0018; break; case ESGUI_SCREEN_ROT_90CW: // GS = 0, SS = 1 outCtl |= 0x0100; // update AM = 1, ID = 10 // horizontal decrement, vertical increment entryMode |= 0x0028; break; } // Driver output control setup ili9225xCmdWrite(0x01, outCtl); ili9225xCmdWrite(0x03, entryMode); // optional parallel data sync esguiScreenBusWriteCmdB(hdrv->hbus, 0x22); esguiScreenIoBatchEnd(hdrv); } // prepare coordinates depending on screen rotation #pragma Otime static __inline void ili9225xPreparePoint(ESGUI_HDRV hdrv, int* x, int* y) { switch( hdrv->rotation ) { case ESGUI_SCREEN_ROT_90CCW: esguiUtilsSwapInt(x, y); *y = hdrv->height - *y -1; break; case ESGUI_SCREEN_ROT_90CW: esguiUtilsSwapInt(x, y); *x = hdrv->width - *x -1; break; case ESGUI_SCREEN_ROT_180: *x = hdrv->width - *x -1; *y = hdrv->height - *y -1; break; } } // internal position setter #pragma Otime static __inline void internal_ili9225xSetPos(ESGUI_HDRV hdrv, int x, int y) { // 0-7 address ili9225xCmdWrite(0x20, x); // 8-16 address ili9225xCmdWrite(0x21, y); // optional parallel data sync esguiScreenBusWriteCmdB(hdrv->hbus, 0x22); } // set ili9225x screen position. consecutive ili9225x memory writes // will start at this position #pragma Otime static void ili9225xSetPos(ESGUI_HDRV hdrv, int x, int y) { ili9225xPreparePoint(hdrv, &x, &y); internal_ili9225xSetPos(hdrv, x, y); } // internal window setter #pragma Otime static __inline void internal_ili9225xSetWindow(ESGUI_HDRV hdrv, int x0, int y0, int x1, int y1) { // set RAM window // // horizontal start ili9225xCmdWrite(0x36, x1); // horizontal end ili9225xCmdWrite(0x37, x0); // vertical start ili9225xCmdWrite(0x38, y1); // vertical end ili9225xCmdWrite(0x39, y0); // optional parallel data sync esguiScreenBusWriteCmdB(hdrv->hbus, 0x22); // set starting position, depending on rotation switch( hdrv->rotation ) { case ESGUI_SCREEN_ROT_0: internal_ili9225xSetPos(hdrv, x0, y0); break; case ESGUI_SCREEN_ROT_180: internal_ili9225xSetPos(hdrv, x1, y1); break; case ESGUI_SCREEN_ROT_90CCW: internal_ili9225xSetPos(hdrv, x0, y1); break; case ESGUI_SCREEN_ROT_90CW: internal_ili9225xSetPos(hdrv, x1, y0); break; } } // set virtual window in which all ili9225x memory writes will go #pragma Otime static void ili9225xSetWindow(ESGUI_HDRV hdrv, int x0, int y0, int x1, int y1) { ili9225xPreparePoint(hdrv, &x0, &y0); ili9225xPreparePoint(hdrv, &x1, &y1); // normalize x & y if( x0 > x1 ) esguiUtilsSwapInt(&x0, &x1); if( y0 > y1 ) esguiUtilsSwapInt(&y0, &y1); internal_ili9225xSetWindow( hdrv, x0, y0, x1, y1); } // reset virtual window #pragma Otime static void ili9225xResetWindow(ESGUI_HDRV hdrv) { internal_ili9225xSetWindow( hdrv, 0, 0, hdrv->width-1, hdrv->height-1); } // set pixel to color at current position #pragma Otime static __inline void ili9225xSetPixel(ESGUI_HDRV hdrv, ESGUI_Color_t clr) { // Adjust color to 5-3 6-2 5-3 clr = ((clr & 0xF800) << 8) + ((clr & 0x07E0) << 5) + ((clr & 0x001F) << 3); // by our design display's always ready to receive data esguiScreenBusWriteDataW(hdrv->hbus, (esU16)(clr >> 8 & 0xFFFF) ); esguiScreenBusWriteDataB(hdrv->hbus, (esU8)(clr & 0xFF)); } // internal window filler #pragma Otime static void internal_ili9225xFillWindow(ESGUI_HDRV hdrv, int x0, int y0, int x1, int y1, ESGUI_Color_t clr) { int iTmp = x0; // perform fill operation while(y0 <= y1) { while(x0 <= x1) { ili9225xSetPixel(hdrv, clr); ++x0; } x0 = iTmp; ++y0; } } // fill current ili9225x window area with specified color #pragma Otime static void ili9225xFillWindow(ESGUI_HDRV hdrv, int x0, int y0, int x1, int y1, ESGUI_Color_t clr) { esguiScreenSetWindow( hdrv, x0, y0, x1, y1 ); internal_ili9225xFillWindow( hdrv, x0, y0, x1, y1, clr ); } // window clear #pragma Otime static void ili9225xClear(ESGUI_HDRV hdrv, ESGUI_Color_t clr) { ili9225xResetWindow( hdrv ); internal_ili9225xFillWindow( hdrv, 0, 0, hdrv->width-1, hdrv->height-1, clr ); } // Control screen power mode #pragma Otime static void ili9225xPowerModeSet(ESGUI_HDRV hdrv, ESGUI_SCREEN_PWRMODE mode) { // begin display io batch esguiScreenIoBatchBegin(hdrv); switch(mode) { case ESGUI_SCREEN_PWRON: // Start oscillator ili9225xCmdWrite(0x0F, 0x0701); msDelay(50); //< wait ~50ms ili9225xCmdWrite(0x11, 0x0018); //Set APON,PON,AON,VCI1EN,VC ili9225xCmdWrite(0x12, 0x3121); ili9225xCmdWrite(0x13, 0x006B); ili9225xCmdWrite(0x14, 0x3C4B); // Get out of standby ili9225xCmdWrite(0x10, 0x0200); msDelay(100); //< wait ~100ms // Start Auto booster circuit ili9225xCmdWrite(0x11, 0x1041); msDelay(50); //< wait ~50ms // Powert ctl3 setup (Step-up circuit amplification) ili9225xCmdWrite(0x12, 0x2012); msDelay(50); //< wait ~50ms // Power ctl4 setup (Amplifying factor for gamma voltage) ili9225xCmdWrite(0x13, 0x0033); // Power ctl5 setup (VCOM supply settings) ili9225xCmdWrite(0x14, 0x5169); // Setup gamma curve voltage ili9225xCmdWrite(0x50, 0x0000); ili9225xCmdWrite(0x51, 0x0C05); ili9225xCmdWrite(0x52, 0x0302); ili9225xCmdWrite(0x53, 0x0007); ili9225xCmdWrite(0x54, 0x0302); ili9225xCmdWrite(0x55, 0x050C); ili9225xCmdWrite(0x56, 0x0000); ili9225xCmdWrite(0x57, 0x0700); ili9225xCmdWrite(0x58, 0x1C00); ili9225xCmdWrite(0x59, 0x001C); // LCD Driving waveform control ili9225xCmdWrite(0x02, 0x0300); // No inversion, active with positive polarity // Setup display control for off-screen operations ili9225xCmdWrite(0x07, 0x0016); // Back and front porch (front porch = 8 back porch = 8 lines) ili9225xCmdWrite(0x08, 0x0808); // Set-up display frame cycle ili9225xCmdWrite(0x0B, 0x3100); // Interface control - disable RGB interface settings ili9225xCmdWrite(0x0C, 0x0001); // Set-up gate scan control ili9225xCmdWrite(0x30, 0x0000); // Disable vertical scroll ili9225xCmdWrite(0x31, hdrv->height-1); ili9225xCmdWrite(0x32, 0x0000); ili9225xCmdWrite(0x33, 0x0000); // Screen driving set-up ili9225xCmdWrite(0x34, hdrv->height-1); ili9225xCmdWrite(0x35, 0x0000); // Initialize screen rotation if(ESGUI_SCREEN_ROT_INVALID == hdrv->rotation) ili9225xSetScreenRotation(hdrv, ESGUI_SCREEN_ROT_0); else ili9225xSetScreenRotation(hdrv, hdrv->rotation); // set initial memory window and position, clear display RAM ili9225xClear(hdrv, 0); // Switch offscreen operations to onscreen mode ili9225xCmdWrite(0x07, 0x0017); // Prepare for data command esguiScreenBusWriteCmdB(hdrv->hbus, 0x22); break; case ESGUI_SCREEN_PWRSTDBY: case ESGUI_SCREEN_PWROFF: // Turn off display ili9225xCmdWrite(0x07, 0x0000); msDelay(50); //< wait ~50ms // Stop Auto booster circuit ili9225xCmdWrite(0x11, 0x0041); msDelay(50); //< wait ~50ms // Enter standby ili9225xCmdWrite(0x10, 0x0201); break; } // end display io batch esguiScreenIoBatchEnd(hdrv); } // driver initializer #pragma Otime static esBL ili9225xInit(ESGUI_HDRV hdrv, ESGUI_COLOR_FORMAT fmt) { if(!hdrv) return FALSE; // reset display hardware esguiScreenHwReset(hdrv); hdrv->chipId = ili9225xIdRead(hdrv); // read chip id if( !ili9225isValidId(hdrv) ) { hdrv->chipId = 0; return FALSE; } // execute initialization commands // // Turn off LCD first ili9225xPowerModeSet(hdrv, ESGUI_SCREEN_PWROFF); // Power display on, performing necessary initial configurations ili9225xPowerModeSet(hdrv, ESGUI_SCREEN_PWRON); return TRUE; } // misc controller - specific services #pragma Otime esU16 ili9225xIdRead(ESGUI_HDRV hdrv) { esU16 result = 0; esguiScreenIoBatchBegin(hdrv); esguiScreenBusWriteCmdB(hdrv->hbus, 0x00); esguiScreenBusWriteDataW(hdrv->hbus, 0x0001); esguiScreenBusReadDataW(hdrv->hbus, &result); // optional parallel data sync esguiScreenBusWriteCmdB(hdrv->hbus, 0x22); esguiScreenIoBatchEnd(hdrv); return result; } // driver setup #pragma Otime void ili9225xScreenDriverSetup(ESGUI_HDRV hdrv, int extx, int exty) { if( hdrv ) { esguiScreenDriverHandleInit(hdrv, sizeof(ESGUI_DRV)); // set native size of driven screen hdrv->width = extx; hdrv->height = exty; hdrv->init = ili9225xInit; hdrv->setPowerMode = ili9225xPowerModeSet; hdrv->setRotation = ili9225xSetScreenRotation; hdrv->setPos = ili9225xSetPos; hdrv->setWindow = ili9225xSetWindow; hdrv->resetWindow = ili9225xResetWindow; hdrv->setPixel = ili9225xSetPixel; hdrv->fillWindow = ili9225xFillWindow; hdrv->clear = ili9225xClear; } } // Chip ID validity check // Some chip modifications may return slightly different ID codes #pragma Otime esBL ili9225isValidId(ESGUI_HDRV hdrv) { return 0x9224 <= hdrv->chipId && 0x9227 >= hdrv->chipId; } #ifdef ESGUI_USE_ILI9225X_DRIVER_TEST // Window fill for driver testing void ili9225xWindowFillTest(ESGUI_HDRV hdrv) { int x0 = 7, x1 = 15, y0 = 19, y1 = 33; esguiScreenIoBatchBegin(hdrv); ili9225xPreparePoint(hdrv, &x0, &y0); ili9225xPreparePoint(hdrv, &x1, &y1); if( x0 > x1 ) esguiUtilsSwapInt(&x0, &x1); if( y0 > y1 ) esguiUtilsSwapInt(&y0, &y1); internal_ili9225xSetWindow( hdrv, x0, y0, x1, y1 ); internal_ili9225xFillWindow( hdrv, x0, y0, x1, y1, 0xFFFFFFFF ); esguiScreenIoBatchEnd(hdrv); } #endif #endif // _ili_9225_x_cc_
#pragma once class AI_Surface : public Hourglass::IAction { public: void LoadFromXML( tinyxml2::XMLElement* data ); void Init( Hourglass::Entity* entity ); IBehavior::Result Update( Hourglass::Entity* entity ); IBehavior* MakeCopy() const; private: StrID m_SurfaceEntityName; hg::Entity* m_SurfaceEntity; float m_StartSpeed; float m_EndSpeed; float m_Rotation; float m_StartRotation; float m_EndRotation; };
#pragma once #include<list> #include<string> #include "dataEntry.h" class entryStats { public: entryStats(std::list<dataEntry*> &entries); ~entryStats(); void updateStats(dataEntry* newEntry, std::list<dataEntry*> &prevEntries); void resetStats(); double returnEffAvg(); int returnDistTotal(); int returnFills(); double returnPriceAvg(); char* returnStatS(int choice); private: double effAvg; //average efficiency L/100km int distTotal; //total distance travelled km int fills; //total number of fills double priceAvg; //avg price per litre };
/* * Copyright (C) 2013 Tom Wong. All rights reserved. */ #ifndef __GT_USER_SERVER_H__ #define __GT_USER_SERVER_H__ #include "gtserver.h" GT_BEGIN_NAMESPACE class GtUserSession; class GtUserServerPrivate; class GT_SVCE_EXPORT GtUserServer : public GtServer { Q_OBJECT public: explicit GtUserServer(QObject *parent = 0); ~GtUserServer(); protected: GtSession* createSession(); void removeSession(GtSession *session); private: QScopedPointer<GtUserServerPrivate> d_ptr; private: Q_DISABLE_COPY(GtUserServer) Q_DECLARE_PRIVATE(GtUserServer) }; GT_END_NAMESPACE #endif /* __GT_USER_SERVER_H__ */
template <typename T> inline Matrix<T,2,3>::Matrix() : data{ Vector<T,3>(1,0,0), Vector<T,3>(0,1,0) } { } template <typename T> inline Matrix<T,2,3>::Matrix(T m00, T m01, T m02, T m10, T m11, T m12) : data{ Vector<T,3>(m00,m01,m02), Vector<T,3>(m10,m11,m12) } { } template <typename T> inline Matrix<T,2,3>::Matrix(std::initializer_list<T> l) { assert(l.size() == 6 && "Matrix 2x3 must have 6 values\n"); data[0][0] = l.begin()[0]; data[0][1] = l.begin()[1]; data[0][2] = l.begin()[2]; data[1][0] = l.begin()[3]; data[1][1] = l.begin()[4]; data[1][2] = l.begin()[5]; } template <typename T> inline Matrix<T,2,3>::Matrix(T v) : data{ Vector<T,3>(v,0,0), Vector<T,3>(0,v,0) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Vector<T,3>& u, const Vector<T,3>& v) : data{u, v} { } template <typename T> template <typename U> inline Matrix<T,2,3>::Matrix(const Matrix<U,2,3> &m) : data{ m.data[0], m.data[1] } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,2,2> &m) : data{ Vector<T,3>(m[0][0],m[0][1],0), Vector<T,3>(m[1][0],m[1][1],0) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,2,4> &m) : data{ Vector<T,3>(m[0][0],m[0][1],m[0][2]), Vector<T,3>(m[1][0],m[1][1],m[1][2]) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,3,2> &m) : data{ Vector<T,3>(m[0][0],m[0][1],0), Vector<T,3>(m[1][0],m[1][1],0) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,3,3> &m) : data{ m[0], m[1] } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,3,4> &m) : data{ Vector<T,3>(m[0][0],m[0][1],m[0][2]), Vector<T,3>(m[1][0],m[1][1],m[1][2]) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,4,2> &m) : data{ Vector<T,3>(m[0][0],m[0][1],0), Vector<T,3>(m[1][0],m[1][1],0) } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,4,3> &m) : data{ m[0], m[1] } { } template <typename T> inline Matrix<T,2,3>::Matrix(const Matrix<T,4,4> &m) : data{ Vector<T,3>(m[0][0],m[0][1],m[0][2]), Vector<T,3>(m[1][0],m[1][1],m[1][2]) } { } template <typename T> inline Matrix<T,2,3>::~Matrix() { } template <typename T> inline Matrix<T,2,3>& Matrix<T,2,3>::operator = (const Matrix<T,2,3>& m) { this->data[0] = m.data[0]; this->data[1] = m.data[1]; return *this; } template <typename T> inline Vector<T,3>& Matrix<T,2,3>::operator[](UI32 i) { assert(i < 2 && "Array Index out of bounds\n"); return this->data[i]; } template <typename T> inline const Vector<T,3>& Matrix<T,2,3>::operator[](UI32 i) const { assert(i < 2 && "Array Index out of bounds\n"); return this->data[i]; }
#include <iostream> #include <stdlib.h> #include <time.h> #include <math.h> #include <string> #include "Debug.h" #include "Game.h" #include "Util.h" #include "math/Vec2.h" #include "math/Vec3.h" //#include "Sound.h" #include <AL/al.h> #include <AL/alc.h> using namespace NoHope; Game::Game(int width, int height) :world(b2Vec2(0.0f, -20.0f)) { _graphics = new Graphics(width, height); init(); writeLog("WIDTH: %d, HEIGHT: %d", Graphics::screenWidth, Graphics::screenHeight); } Game::~Game() { delete _graphics; delete _shader; delete player; delete ground; delete ground2; delete ground3; delete ground4; delete sky; delete text; delete bg; } void Game::init() { //3D Shader* _shader3D = new Shader(Util::resourcePath + "Shaders/basicd.vert", Util::resourcePath + "Shaders/basicd.frag"); //if(Player::playerDirection == false) //{ Texture* _player = Texture::load(Util::resourcePath + "SeppoBack.tga"); //} /*Texture* _player = Texture::load(Util::resourcePath + "Seppo.tga");*/ //Texture* _enemy = Texture::load(Util::resourcePath + "Char_1.tga"); Texture *_ground = Texture::load(Util::resourcePath + "pitkaplatta.tga"); Texture *_ground2 = Texture::load(Util::resourcePath + "pitkaplatta.tga"); Texture *_ground3 = Texture::load(Util::resourcePath + "pitkaplatta.tga"); Texture *_ground4 = Texture::load(Util::resourcePath + "pitkaplatta.tga"); Texture *_sky = Texture::load(Util::resourcePath + "pitkaplatta.tga"); Texture *_bg = Texture::load(Util::resourcePath + "Backgruund.tga"); _shader = new Shader(Util::resourcePath + "Shaders/basic.vert", Util::resourcePath + "Shaders/basic.frag"); renderTexture = new RenderTexture(); fps = 0; _timer = 0.0f; srand(time(NULL)); _projection = Mat4( 2.0f / Graphics::screenWidth, 0, 0, 0, 0, 2.0f / Graphics::screenHeight, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1); float nearZ = 2; float farZ = 100; float fov = 45.0f; float aspect = Graphics::aspectRatio; float f = 1/tan(fov/2.0f); _projection3D = Mat4( f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, -((farZ+nearZ)/(farZ-nearZ)), -1, 0, 0, -(2*farZ*nearZ/(farZ-nearZ)), 0); player = new NoHope::Player(100,100, 64, 128, _player, _shader, &world); /*player->setPosition(Graphics::screenWidth/2, Graphics::screenHeight/2);*/ //player->setPosition(300,300); player->setProjectionMatrix(_projection); ground = new NoHope::Ground(0,0,412,64, _ground, _shader, &world); ground->setProjectionMatrix(_projection); ground2 = new NoHope::Ground(700,100,412,64, _ground2, _shader, &world); ground2->setProjectionMatrix(_projection); //_sound->play(); ground3 = new NoHope::Ground(1200,300,412,64, _ground3, _shader, &world); ground3->setProjectionMatrix(_projection); ground4 = new NoHope::Ground(500,500,412,64, _ground4, _shader, &world); ground4->setProjectionMatrix(_projection); //enemy = new NoHope::Player(510,510,64,128, _ground4, _shader, &world); //enemy->setProjectionMatrix(_projection); sky = new NoHope::Ground(0,800,412,64, _sky, _shader, &world); sky->setProjectionMatrix(_projection); fpsTimer = 0.f; bg = new NoHope::SpriteEntity(Graphics::screenWidth/2, Graphics::screenHeight/2, 1280, 720, _bg, _shader); bg->setProjectionMatrix(_projection); _projection = Mat4( 2.0f / Graphics::screenWidth, 0, 0, 0, 0, -2.0f / Graphics::screenHeight, 0, 0, 0, 0, 0, 0, -1, 1, 0, 1); text = new NoHope::Text("Vera.ttf", 40); text->SetText(L"FPS:"); text->AddText(L"\nJEFFREY FTW",Vec4(1,0,0,1)); text->setPosition(10, 20); text->setProjectionMatrix(_projection); } void Game::addSprite(int x, int y, int dirX, int dirY) { Sprite sprite; sprite.entity = new SpriteEntity(x, y, 64, 64, texture, _shader); sprite.entity->setProjectionMatrix(_projection); Vec2 dir = Vec2(dirX, dirY); dir.normalize(); sprite.direction = dir; sprite.speed = Util::randomRange(200, 300); sprites.push_back(sprite); //_sound2->play(); } void Game::update(float dt) { fpsTimer += dt; _timer += dt/20; //writeLog("dt %f\n",dt); if(fpsTimer > 1) { text->SetText(L"FPS:" + std::to_wstring((long long)fps)); //long long intil hyvä //unsigned long long unsigned int //long double double tai float writeLog("FPS:%d\n", fps); fpsTimer = 0; fps = 0; } _shader->setUniform("time", _timer); const float timeStep = 1.f/60.f; //if (_timer > timeStep) //{ //_timer = 0.f; world.Step(timeStep, 8, 3); //} player->update(dt); //std::cout <<"p x: "<<player->getPosition().x << "p y: "<<player->getPosition().y << std::endl; _camera.setCameraPosition(player->getPosition().x - 640.0f, player->getPosition().y - 360 ); fps++; } void Game::render() { _graphics->clear(0.2f, 0.2f, 0.2f); renderTexture->clear(Color(0.95f, 0.95f, 0.95f)); renderTexture->draw(*bg,_camera); renderTexture->draw(*ground,_camera); renderTexture->draw(*ground2,_camera); renderTexture->draw(*ground3,_camera); renderTexture->draw(*ground4,_camera); renderTexture->draw(*sky,_camera); renderTexture->draw(*player,_camera); renderTexture->draw(*text,_camera); /*renderTexture->draw(*enemy);*/ renderTexture->display(); }
// // Created by dwb on 2019-07-18. // #include "Methods.h" //函数声明 inline void getInfo(); //函数定义 inline void getInfo(){ cout << "a sample C++ program" << endl; cout << "Hello C++!" << endl; } int add(int a ,int b = 200,int c = 300,int d = !400){ return a+b+c+d; } void Methods::test() { getInfo(); int sum=add(1,2,3,4); cout << "sum:" << sum << endl; }
// // Created by 송지원 on 2020/07/23. // #include <iostream> #include <algorithm> using namespace std; int alphaCnt [26]; char ch; string word; int wordLen; int maxVal; int maxIdx; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> word; wordLen = word.length(); for (int i=0; i<wordLen; i++) { ch = word[i]; if (ch >= 'a' && ch <= 'z') { alphaCnt[ch-'a']++; if (alphaCnt[ch-'a'] > maxVal) { maxVal = alphaCnt[ch-'a']; maxIdx = ch-'a'; } } if (ch >= 'A' && ch <= 'Z') { alphaCnt[ch-'A']++; if (alphaCnt[ch-'A'] > maxVal) { maxVal = alphaCnt[ch-'A']; maxIdx = ch-'A'; } } } sort(alphaCnt, alphaCnt+26); if (alphaCnt[24] == maxVal) cout << "?"; else cout << (char)('A'+maxIdx); }
//merge sort implementation //keep dividing the array into halves //merge the sorted halves #include<iostream> using namespace std; void merge(int arr[],int l,int m,int r){ int n1=m-l+1; int n2=r-m; int L[n1]; int R[n2]; //copying fist half of array in L[] and other half in R[] int i=0; int j=0; int k=0; for(i=0;i<n1;i++){ L[i]=arr[l+i]; } for(i=0;i<n2;i++){ R[i]=arr[m+1+i]; } //now merging the sorted arrays i=0;k=l;j=0; //k=l i.e. start of the array for this subarray while(i<n1 && j<n2){ if(L[i]<=R[j]){ arr[k++]=L[i++]; } else{ arr[k++]=R[j++]; } } while(i<n1){ arr[k++]=L[i++]; } while(j<n2){ arr[k++]=R[j++]; } } void mergeSort(int arr[],int l,int r){ if(l<r){ int mid= l+(r-l)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,mid,r); } } int main(int argc, char const *argv[]) { int arr[]={5,4,3,2,1}; int n=sizeof(arr)/sizeof(arr[0]); mergeSort(arr,0,n-1); for(int i=0;i<n;i++){ std::cout << arr[i] << '\t'; } return 0; }
// // Created by Alekhya on 4/28/2020. // #ifndef FINALPROJECT_TILESTATE_H #define FINALPROJECT_TILESTATE_H namespace mylibrary { enum class TileState { kEmpty, kMiss, kHit, kSink}; } // namespace mylibrary #endif // FINALPROJECT_TILESTATE_H
#pragma once #include "StdAfx.h" #include "BallPhysics.h" #include "GameLogic.h" class GameLogic; class BallPhysics; class RacketPhysics { protected: GameLogic* gameLogic; int playerId; Ogre::Vector3 pos; Ogre::Vector3 speed; Ogre::Quaternion ori; Ogre::Vector3 angVel; bool initialized; BallPhysics* ball; float timeSinceLastHit; public: RacketPhysics(BallPhysics* ball, GameLogic* gameLogic, int playerId); virtual ~RacketPhysics(); virtual void update(float deltaT); virtual void makeService() = 0; void getPosAndOri(Ogre::Vector3& pos, Ogre::Quaternion& ori); protected: void setPosAndOri(Ogre::Vector3 pos, Ogre::Quaternion ori, float deltaT); private: void testCollisionWithBall(); };
#include <iostream> #include <stdlib.h> #include <math.h> using namespace std; //three points #define EXPECTED_ARG_COUNT 6 int main(const int argc, const char * argv[]) { int rc = 0; // Check argument count if (argc < EXPECTED_ARG_COUNT+1){ cerr << "Error: Expected " << EXPECTED_ARG_COUNT << " arguments; received " << argc-1 << "; exiting" << endl; return -1; } if (argc > EXPECTED_ARG_COUNT+1){ cerr << "Warning: Expected " << EXPECTED_ARG_COUNT << " arguments; received " << argc-1 << "; ignoring extraneous arguments" << endl; } float x1 = atof (argv[1]); float y1 = atof (argv[2]); float x2 = atof (argv[3]); float y2 = atof (argv[4]); float x3 = atof (argv[5]); float y3 = atof (argv[6]); float slope1 = (y2 - y1)/(x2 - x1); float slope2 = (y3 - y1)/(x3 - x1); float slope3 = (y3 - y2)/(x3 - x2); if ((x1 == x2) && (x2 == x3) && (x1 == x3) && (y1 == y2) && (y2 == y3) && (y1 == y3){ cout << "The points ("<<x1<<", "<<y1<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") overlap; they do not form a triangle" << endl; return rc; } if ((slope1 == slope2) & (slope2 == slope3)){ cout << "The points ("<<x1<<", "<<y1<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") form a line with slope: " << slope1 << endl; return rc; } if ((x1 == x2) & (y1 == y2)){ cout << "The points ("<<x1<<", "<<y1<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") form a line with slope: " << slope3 << endl; return rc; } else if ((x1 == x3) & (y1 == y3)){ cout << "The points ("<<x1<<", "<<y1<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") form a line with slope: " << slope1 << endl; return rc; } else if ((x2 == x3) & (y2 == y3)){ cout << "The points ("<<x2<<", "<<y2<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") form a line with slope: " << slope2 << endl; return rc; } float s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))); float s2 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3))); float s3 = sqrt(((x3-x2)*(x3-x2))+((y3-y2)*(y3-y2))); float s = ((s1 + s2 + s3)/2); float a = sqrt(s*(s-s1)*(s-s2)*(s-s3)); cout << "The area of the triangle formed by points ("<<x1<<", "<<y1<<"), ("<<x2<<", "<<y2<<"), and ("<<x3<<", "<<y3<<") is: " << a << endl; return rc; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef __FILE_CHOOSER_FUN_H__ #define __FILE_CHOOSER_FUN_H__ #include "adjunct/desktop_pi/desktop_file_chooser.h" // Move all functions below into this namespace and simplify their names namespace FileChooserUtil { /** * Save the Open/Save directory to preferences for later use * * @param action The selector action to determine what directory type to save * @param result Uses the first of te selected files (if any) as the path to save * * @return OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS SavePreferencePath(DesktopFileChooserRequest::Action action, const DesktopFileChooserResult& result); /** * Save the Open/Save directory to preferences for later use * * @param request Uses the selector action to determine what directory type to save * @param result Uses the first of te selected files (if any) as the path to save * * @return OpStatus::OK on success, otherwise an error code */ inline OP_STATUS SavePreferencePath(const DesktopFileChooserRequest& request, const DesktopFileChooserResult& result) { return SavePreferencePath( request.action, result); } /** * Create a new DesktopFileChooserRequest object and copy the state of the source object * The new object is only valid if OpStatus::OK is returned amd must be destroyed by caller * using OP_DELETE * * @param src Source object * @param copy On return the new object * * @param OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS CopySettings(const DesktopFileChooserRequest& src, DesktopFileChooserRequest*& copy); /** * Return the index of a given extension. The comparison is case insensitive * * @param extension The extension to search for * @param filters List of extensions * * @return A positive value corresponding to the first match in the list, otherwise -1 */ INT32 FindExtension(const OpStringC& extension, OpVector<OpFileSelectionListener::MediaType>* filters); /** * Reset DesktopFileChooserRequest so it can be reused * * @param request Item to reset */ void Reset(DesktopFileChooserRequest& request); /** * Appends file extension filters to the media description string if no such filters * have already beed added * * @param media_type Item to extend * * @return OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS AppendExtensionInfo(OpFileSelectionListener::MediaType& media_type); /** * Return the first extension from the default selected extension * * @param request Object that provides extensions * @param extension On return the retrived extension * * @return OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS GetInitialExtension(const DesktopFileChooserRequest& request, OpString& extension); /** * Convert a string filter of the form '| description | extensions | description | extensions...' * to the to a vector of DesktopFileChooserExtensionFilters * * @param string_filter The string filter to convert * @param extension_filters On return the list list of converted filters * * @return OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS SetExtensionFilter(const uni_char* string_filter, OpAutoVector<OpFileSelectionListener::MediaType> * extension_filters); /** * Make a copy the filter with content and append the new copy to the list * * @param filter Filter data to duplicate * @param list The target list * @param add_asterix_dot If TRUE, prepend "*." to the extensions if they do not contain it. * * @return OpStatus::OK on success, otherwise an error code describing the error */ OP_STATUS AddMediaType(const OpFileSelectionListener::MediaType* filter, OpAutoVector<OpFileSelectionListener::MediaType>* list, BOOL add_asterix_dot); }; // Hooks for compatibility with existing code. To be removed DEPRECATED(INT32 FindExtension(const OpStringC& extension, OpVector<OpFileSelectionListener::MediaType>* filters)); DEPRECATED(void ResetDesktopFileChooserRequest(DesktopFileChooserRequest& request)); DEPRECATED(OP_STATUS ExtendMediaTypeWithExtensionInfo(OpFileSelectionListener::MediaType& media_type)); DEPRECATED(OP_STATUS GetInitialExtension(const DesktopFileChooserRequest& request, OpString& extension)); DEPRECATED(OP_STATUS StringFilterToExtensionFilter(const uni_char* string_filter, OpAutoVector<OpFileSelectionListener::MediaType> * extension_filters)); DEPRECATED(OP_STATUS CopyAddMediaType(const OpFileSelectionListener::MediaType* filter, OpAutoVector<OpFileSelectionListener::MediaType>* list, BOOL add_asterix_dot)); #endif // __FILE_CHOOSER_FUN_H__
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include "../util/Vec3f.h" #include "Chunk.h" #include "../util/simplexnoise.h" const Vec3f TILES[6] = { Vec3f(0.0f, 0.0f, 0.0f), Vec3f(1.0f, 1.0f, 1.0f), Vec3f(0.5f, 0.5f, 0.5f), Vec3f(1.0f, 0.0f, 0.0f), Vec3f(0.0f, 1.0f, 0.0f), Vec3f(0.0f, 0.0f, 1.0f)}; //comment Chunk::Chunk(int x, int y) { X = x; Y = y; } void Chunk::gen() { for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE; i++) { int x = i % CHUNK_SIZE, y = i / CHUNK_SIZE; int rx = x + X*CHUNK_SIZE, ry = y + Y*CHUNK_SIZE; if (raw_noise_2d((float)rx, (float)ry) < .5) { // if (rx*rx + ry*ry < 64) { map[i] = 1; } else { map[i] = 2; } if (x + X*CHUNK_SIZE == 0 && y + Y * CHUNK_SIZE == 0) { map[i] = 3; } } } int Chunk::getId(int x, int y) { return map[y * CHUNK_SIZE + x]; } bool Chunk::setId(int x, int y, int id) { if (x < 0 || y < 0 || x >= CHUNK_SIZE || y >= CHUNK_SIZE) return false; map[y * CHUNK_SIZE + x] = id; return true; } void Chunk::draw() { if (!list) { list = glGenLists(1); glNewList(list, GL_COMPILE); glBegin(GL_QUADS); for (int i = 0; i < CHUNK_SIZE*CHUNK_SIZE; i++) { int x = i % CHUNK_SIZE, y = i / CHUNK_SIZE; Vec3f color = TILES[map[i]]; glColor3f(color.x, color.y, color.z); // glColor3f(.0f,1.0f,1.0f); glVertex3f(x , y , 0.0f); glVertex3f(x , y+1.0f, 0.0f); glVertex3f(x+1.0f, y+1.0f, 0.0f); glVertex3f(x+1.0f, y , 0.0f); } glEnd(); glEndList(); } glPushMatrix(); glTranslated(X * CHUNK_SIZE, Y * CHUNK_SIZE, 0); glCallList(list); glPopMatrix(); }
#pragma once #include <glm/glm.hpp> class Sun { public: Sun(); Sun(glm::vec3 axis, float rot, float power); void Gui(); void SetAxis(glm::vec3 axis); void SetRotation(float rot); glm::vec3 GetDirection(); float GetPower(); private: glm::vec3 _direction; float _rot; glm::vec3 _axis; float _power; };
/* Реализуйте справочник столиц стран. На вход программе поступают следующие запросы: CHANGE_CAPITAL country new_capital — изменение столицы страны country на new_capital, либо добавление такой страны с такой столицей, если раньше её не было. RENAME old_country_name new_country_name — переименование страны из old_country_name в new_country_name. ABOUT country — вывод столицы страны country. DUMP — вывод столиц всех стран. Формат ввода В первой строке содержится количество запросов Q, в следующих Q строках — описания запросов. Все названия стран и столиц состоят лишь из латинских букв, цифр и символов подчёркивания. Формат вывода Выведите результат обработки каждого запроса: В ответ на запрос CHANGE_CAPITAL country new_capital выведите Introduce new country country with capital new_capital, если страны country раньше не существовало; Country country hasn't changed its capital, если страна country до текущего момента имела столицу new_capital; Country country has changed its capital from old_capital to new_capital, если страна country до текущего момента имела столицу old_capital, название которой не совпадает с названием new_capital. В ответ на запрос RENAME old_country_name new_country_name выведите Incorrect rename, skip, если новое название страны совпадает со старым, страна old_country_name не существует или страна new_country_name уже существует; Country old_country_name with capital capital has been renamed to new_country_name, если запрос корректен и страна имеет столицу capital. В ответ на запрос ABOUT country выведите Country country doesn't exist, если страны с названием country не существует; Country country has capital capital, если страна country существует и имеет столицу capital. В ответ на запрос DUMP выведите There are no countries in the world, если пока не было добавлено ни одной страны; последовательность пар вида country/capital, описывающую столицы всех стран, если в мире уже есть хотя бы одна страна. При выводе последовательности пары указанного вида необходимо упорядочить по названию страны и разделять между собой пробелом. Пример 1 Ввод 6 CHANGE_CAPITAL RussianEmpire Petrograd RENAME RussianEmpire RussianRepublic ABOUT RussianRepublic RENAME RussianRepublic USSR CHANGE_CAPITAL USSR Moscow DUMP Вывод Introduce new country RussianEmpire with capital Petrograd Country RussianEmpire with capital Petrograd has been renamed to RussianRepublic Country RussianRepublic has capital Petrograd Country RussianRepublic with capital Petrograd has been renamed to USSR Country USSR has changed its capital from Petrograd to Moscow USSR/Moscow */ #include <iostream> #include <string> #include <map> using namespace std; int main() { int q; cin >> q; map<string, string> country_to_capital; for (int i = 0; i < q; ++i) { string operation_code; cin >> operation_code; if (operation_code == "CHANGE_CAPITAL") { string country, new_capital; cin >> country >> new_capital; if (country_to_capital.count(country) == 0) { cout << "Introduce new country " << country << " with capital " << new_capital << endl; } else { const string &old_capital = country_to_capital[country]; if (old_capital == new_capital) { cout << "Country " << country << " hasn't changed its capital" << endl; } else { cout << "Country " << country << " has changed its capital from " << old_capital << " to " << new_capital << endl; } } country_to_capital[country] = new_capital; } else if (operation_code == "RENAME") { string old_country_name, new_country_name; cin >> old_country_name >> new_country_name; if (old_country_name == new_country_name || country_to_capital.count(old_country_name) == 0 || country_to_capital.count(new_country_name) == 1) { cout << "Incorrect rename, skip" << endl; } else { cout << "Country " << old_country_name << " with capital " << country_to_capital[old_country_name] << " has been renamed to " << new_country_name << endl; country_to_capital[new_country_name] = country_to_capital[old_country_name]; country_to_capital.erase(old_country_name); } } else if (operation_code == "ABOUT") { string country; cin >> country; if (country_to_capital.count(country) == 0) { cout << "Country " << country << " doesn't exist" << endl; } else { cout << "Country " << country << " has capital " << country_to_capital[country] << endl; } } else if (operation_code == "DUMP") { if (country_to_capital.empty()) { cout << "There are no countries in the world" << endl; } else { for (const auto &country_item : country_to_capital) { cout << country_item.first << "/" << country_item.second << " "; } cout << endl; } } } return 0; }
const int TriggerPin = 8; //Trig pin const int EchoPin = 9; //Echo pin void setup () { // initialize a distance sensor pinMode(TriggerPin, OUTPUT); // Trigger is an output pin pinMode(EchoPin, INPUT); // Echo is an input pin Serial.begin (9600); } void loop () { int noise = analogRead(A0); String output = String("noise=" + String(noise)); Serial.println(output); digitalWrite(TriggerPin, LOW); delayMicroseconds(2); digitalWrite(TriggerPin, HIGH); // Trigger pin to HIGH delayMicroseconds(10); // 10us high digitalWrite(TriggerPin, LOW); // Trigger pin to HIGH long duration = 0; duration = pulseIn(EchoPin, HIGH); // Waits for the echo pin to get high // returns the Duration in microseconds long distance = Distance(duration); // Use function to calculate the distance String output2 = String("distance=" + String(distance)); Serial.println(output2); delay(250); } long Distance(long time) { // Calculates the Distance in mm // ((time)*(Speed of sound))/ toward and backward of object) * 10 long distanceCalc; // Calculation variable distanceCalc = ((time / 2.9) / 2); // Actual calculation in mm //distanceCalc = time / 74 / 2; // Actual calculation in inches return distanceCalc; // return calculated value }
// Outreachy: ceph - radosgw-admin application // Boost::program_options demo // Commands.h struct Command { int id; std::string cmd; std::string action; std::string text; }; std::ostream& operator<<(std::ostream& os, const Command& c) { return os << " " << c.cmd << " " << c.action << "\t\t" << c.text << std::endl; } enum { OPT_NO_CMD = 0, OPT_USER_CREATE, OPT_USER_INFO, OPT_USER_DELETE, OPT_USER_SUSPEND, OPT_USER_ENABLE, OPT_USER_CHECK, OPT_USER_STATS, OPT_USER_LIST, OPT_POLICY }; std::vector<Command> commands = { { OPT_USER_CREATE, "user", "create", "create a new user"}, { OPT_USER_INFO, "user", "info", "get user info"}, { OPT_USER_DELETE, "user", "delete", "remove user"}, { OPT_USER_SUSPEND, "user", "suspend", "suspend a user"}, { OPT_USER_ENABLE, "user", "enable", "re-enable user after suspension"}, { OPT_USER_CHECK, "user", "check", "check user info"}, { OPT_USER_STATS, "user", "stats", "show user stats as accounted by quota subsystem"}, { OPT_USER_LIST, "user", "list", "list users"}, { OPT_POLICY, "policy", "", "read bucket/object policy"} };
#include <cstdio> int main(){ int b, s; scanf("%d %d", &b, &s); printf("%d %d\n", s / b, b - (s % b)); return 0; }
#include <Wire.h> #include "MAX30100.h" #define REPORTING_PERIOD_MS 1000 // PulseOximeter is the higher level interface to the sensor // it offers: // * beat detection reporting // * heart rate calculation // * SpO2 (oxidation level) calculation MAX30100 pox; uint32_t tsLastReport = 0; // Callback (registered below) fired when a pulse is detected void onBeatDetected() { Serial.println("Beat!"); } void setup() { Serial.begin(115200); Serial.print("Initializing pulse oximeter.."); // Initialize the PulseOximeter instance // Failures are generally due to an improper I2C wiring, missing power supply // or wrong target chip if (!pox.begin()) { Serial.println("FAILED"); for(;;); } else { Serial.println("SUCCESS"); } } void loop() { }
#include <iostream> int main(){ std::cout << "\n\nFILE: LALALA\n"; std::cout << "\n\nTreiner file\n"; return 0; }
/*C++ is different from C program by means of Classes and Object.*/ /*Class is used to specify the form of an object.*/ /*method are used for manipulating that data into neat packages.*/ /*Data and functions within a class are called members of the class.*/ /*Class will be used to define the blueprint for a data type.*/ /*Object is create from a class.*/ /*syntax to declare a class is class class_name { access_specifier : DataType variable1 ; DataType variable2 ; DataType variable3 ; . . . DataType variable n ; } ; /*syntax of object is Class_name Object_name ; */ /*class can be accessed using member access operator ( . ) which is also called as DOT operator*/ /*In this program lets see CLASS ACCESS MODIFIERs in C++ Programming*/ /*data hiding is one of the most important features of OOPS , which a;llows preventing data access from unauthorished peoples*/ /*NOTE : access specifier is used to specify the access of that data's in a program.*/ /*There are 3 types of access Specifier PUBLIC, PRIVATE and PROTECTED.*/ /*syntax of access modifier class class_name { public: // public members go here protected: // protected members go here private: // private members go here }; */ /*Lets now see about PRIVATE MEMBER in this Program.*/ /*PRIVATE member variable or function can not be accessed or viewed oustide the class . Only the class and friend function can able to access private members*/ /*NOTE : By default all members of class will be treated as a private member ,if not specified it.*/ /*including preprocessor / headerfile in the program*/ #include <iostream> #include <string> /*using namespace*/ using namespace std ; /*creating a class named Student for this program*/ class Student { public: string Name; int RollNo; //Declaring a class memeber function which is used to access and return the PRIVATE MEMBER OF A CLASS. int printMobile( void ) ; //Declaring a class memeber function which is used to assign and access the PRIVATE MEMBER OF A CLASS. void getMobileNo ( int Mobile ); void PrintStudent(); private : int MobileNo; }; /*Definig the class member function to return the private member */ int Student :: printMobile( void ) { return MobileNo ; } /*Definig the class member function to access the private member */ void Student :: getMobileNo ( int Mobile ) { MobileNo = Mobile ; } void Student :: PrintStudent() { cout<<"\nThe student Name is : " << Name << endl ; cout<<"\nThe student RollNo is : " << RollNo << endl ; cout<<"\nThe student MobileNo is : " << printMobile() << endl ; } /*creating a main() function of the program*/ int main() { /*creating Object called student1 and student2 for the class Student*/ Student student1; Student student2; student1.Name = "Maayon" ; student1.RollNo = 1001001 ; student1.getMobileNo ( 1010101010 ) ; student2.Name = "Tech Guru" ; student2.RollNo = 1011011 ; student2.getMobileNo ( 1212121212 ) ; student1.PrintStudent ( ) ; student2.PrintStudent ( ) ; }
// // This file contains the C++ code from Program 8.9 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C++" // by Bruno R. Preiss. // // Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved. // // http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm08_09.cpp // #ifndef CHAINEDHASHTABLE_H_ #define CHAINEDHASHTABLE_H_ #include <HashTable.h> #include <Object.h> #include <Array.h> #include <LinkedList.h> #include <Visitor.h> class ChainedHashTable : public HashTable { Array<LinkedList<Object*> > array; int CompareTo(const Object & arg) const ; public: ChainedHashTable (unsigned int); ~ChainedHashTable (); void Purge (); void Insert (Object& object); void Withdraw (Object& object); Object& Find (Object const& object) const; void Accept (Visitor&) const ; bool IsMember(const Object&) const; }; #endif /*CHAINEDHASHTABLE_H_*/
#include "treeface/graphics/guts/HalfOutline.h" #include "treeface/math/Constants.h" #include "treeface/math/Mat2.h" using namespace treecore; namespace treeface { int HalfOutline::find_cross_from_head( const Vec2f& p1, const Vec2f& p2, Vec2f& p_cross, int step_limit ) const { treecore_assert( outline.size() > 1 ); treecore_assert( outline.size() == outline_bounds.size() + 1 ); SUCK_GEOM_BLK( OutlineSucker sucker( *this, "find cross from tail" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ); const BBox2f bound_input( p1, p2 ); for (int i = 0; i < outline.size() && i < step_limit; i++) { if (bound_input ^ outline_bounds[i]) { const Vec2f& p3 = outline[i]; const Vec2f& p4 = outline[i + 1]; if ( cross_test_inc( p1, p2, p3, p4, p_cross ) ) { SUCK_GEOM_BLK( OutlineSucker sucker( *this, "got cross" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.draw_vector( p1, p2 ); sucker.rgb( SUCKER_GREEN ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); sucker.draw_vtx( p_cross ); ) return i; } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "not cross" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); sucker.draw_vtx( p_cross ); ) } else { SUCK_GEOM_BLK( OutlineSucker sucker( *this, "not cross by bbox" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); ) } } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "failed to find cross" ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ) return -1; } int HalfOutline::find_cross_from_tail( const Vec2f& p1, const Vec2f& p2, Vec2f& p_cross, int step_limit ) const { treecore_assert( outline.size() > 1 ); treecore_assert( outline.size() == outline_bounds.size() + 1 ); SUCK_GEOM_BLK( OutlineSucker sucker( *this, "find cross from tail" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ); const BBox2f bound_input( p1, p2 ); for (int i = outline.size() - 2; i >= 0; i--) { if (outline.size() - i > step_limit) break; if (bound_input ^ outline_bounds[i]) { const Vec2f& p3 = outline[i]; const Vec2f& p4 = outline[i + 1]; if ( cross_test_inc( p1, p2, p3, p4, p_cross ) ) { SUCK_GEOM_BLK( OutlineSucker sucker( *this, "got cross" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.draw_vector( p1, p2 ); sucker.rgb( SUCKER_GREEN ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); sucker.draw_vtx( p_cross ); ) return i; } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "not cross" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); sucker.draw_vtx( p_cross ); ) } else { SUCK_GEOM_BLK( OutlineSucker sucker( *this, "not cross by bbox" ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( i ); sucker.draw_vtx( i + 1 ); ) } } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "failed to find cross" ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ) return -1; } void HalfOutline::add_miter_point( const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style ) { treecore_assert( std::abs( ortho_prev.length2() - 1.0f ) < 0.0001f ); treecore_assert( std::abs( ortho_curr.length2() - 1.0f ) < 0.0001f ); SUCK_GEOM_BLK( OutlineSucker sucker( *this, "add miter point" ); sucker.draw_vtx( skeleton1 ); sucker.draw_unit_vector( skeleton1, ortho_prev * -1.0f ); sucker.draw_unit_vector( skeleton1, ortho_curr ); ) // only do miter join if angle is not too sharp float turn_cosine = ortho_prev * ortho_curr; if (turn_cosine > style.miter_cutoff_cosine) { Vec2f ortho_mid = ortho_prev + ortho_curr; ortho_mid.normalize(); float half_cosine = ortho_mid * ortho_prev; treecore_assert( 0.0f < half_cosine && half_cosine < 1.0f ); Vec2f r_mid = ortho_mid * (style.half_width * side / half_cosine); add( skeleton1 + r_mid, id ); SUCK_GEOM_BLK( OutlineSucker sucker( *this, "miter point is added" ); sucker.draw_vtx( skeleton1 ); sucker.draw_unit_vector( skeleton1, ortho_prev * -1.0f ); sucker.draw_unit_vector( skeleton1, ortho_curr ); ) } } void HalfOutline::add_round_points( const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style ) { treecore_assert( std::abs( ortho_prev.length2() - 1.0f ) < 0.0001f ); treecore_assert( std::abs( ortho_curr.length2() - 1.0f ) < 0.0001f ); SUCK_GEOM_BLK( OutlineSucker sucker( *this, "add round points" ); sucker.draw_vtx( skeleton1 ); sucker.draw_unit_vector( skeleton1, ortho_prev * -1.0f ); sucker.draw_unit_vector( skeleton1, ortho_curr ); ); // calculate step float turn_angle = std::acos( ortho_prev * ortho_curr ); int num_step = turn_angle / PI * STROKE_ROUNDNESS / 2; if (num_step < 5) num_step = 5; float step_angle = turn_angle / num_step; Mat2f step_mat; step_mat.set_rotate( -side * step_angle ); // do rotation Vec2f r_tmp = ortho_prev * side * style.half_width; for (int i = 1; i < num_step; i++) { r_tmp = step_mat * r_tmp; add( skeleton1 + r_tmp, id ); } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "round points added" ); sucker.draw_vtx( skeleton1 ); sucker.draw_unit_vector( skeleton1, ortho_prev * -1.0f ); sucker.draw_unit_vector( skeleton1, ortho_curr ); ) } void HalfOutline::process_inner( const HalfOutline& outer_peer, const Vec2f& skeleton1, const JointID id1, const Vec2f& skeleton2, const Vec2f& ortho_curr, const InternalStrokeStyle& style ) { const JointID id2 = id1 + 1; Vec2f p_cross; Vec2f r_curr = ortho_curr * (side * style.half_width); Vec2f p1 = skeleton1 + r_curr; Vec2f p2 = skeleton2 + r_curr; SUCK_GEOM_BLK( OutlineSucker sucker( *this, "process inner" ); sucker.draw_outline( outer_peer ); sucker.rgb( SUCKER_BLACK ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ) { int i_self = find_cross_from_tail( p1, p2, p_cross, TAIL_FIND_LIMIT ); if (i_self >= 0) { resize( i_self + 1 ); add( p_cross, id1 ); add( p2, id2 ); sunken = false; SUCK_GEOM_BLK( OutlineSucker sucker( *this, "inner solved in same edge" ); sucker.draw_outline( outer_peer ); sucker.rgb( SUCKER_GREEN ); sucker.draw_vtx( p_cross ); sucker.draw_vtx( p2 ); ) return; } } { int i_peer = outer_peer.find_cross_from_tail( p1, p2, p_cross, TAIL_FIND_LIMIT ); if (i_peer >= 0) { add( p_cross, id1 ); add( p2, id2 ); sunken = false; SUCK_GEOM_BLK( OutlineSucker sucker( *this, "inner solved in peer edge" ); sucker.draw_outline( outer_peer ); sucker.rgb( SUCKER_GREEN ); sucker.draw_vtx( p_cross ); sucker.draw_vtx( p2 ); ) return; } } { treecore_assert( outline.size() > 0 ); treecore_assert( outer_peer.size() > 0 ); if ( cross_test_inc( outline.getFirst(), outer_peer.outline.getFirst(), p1, p2, p_cross ) ) { add( p_cross, id1 ); add( p2, id2 ); sunken = false; SUCK_GEOM_BLK( OutlineSucker sucker( *this, "inner solved in between inner edge and peer edge" ); sucker.draw_outline( outer_peer ); sucker.rgb( SUCKER_GREEN ); sucker.draw_vtx( p_cross ); sucker.draw_vtx( p2 ); ) return; } } SUCK_GEOM_BLK( OutlineSucker sucker( *this, "inner unsolved" ); sucker.draw_outline( outer_peer ); sucker.rgb( SUCKER_RED ); sucker.draw_vtx( p1 ); sucker.draw_vtx( p2 ); ) sunken = true; } void HalfOutline::accum_trip( treecore::Array<float>& results ) const { results.add( 0.0f ); for (int i = 1; i < outline.size(); i++) results.add( (outline[i] - outline[i - 1]).length() + results[i - 1] ); } } // namespace treeface
// Copyright 2011 Yandex #include "ltr/scorers/composition_scorers/median_composition_scorer.h" namespace ltr { namespace composition { string MedianCompositionScorer::toString() const { std::stringstream str; std::fixed(str); str.precision(2); str << "Median composition of " << size() << " scorers: {\n"; for (int i = 0; i < size(); ++i) { str << at(i).scorer->toString(); str << " with weight " << at(i).weight << "\n"; } str << "}"; return str.str(); } }; };
#ifndef PACKETS_ROOMS #define PACKETS_ROOMS #include <cstdint> #include "Packets/PacketBaseMessage.h" #pragma pack(push, 1) #include "Packets/PacketBaseMessage.h" struct BM_SC_GET_ROOMLIST : public TS_MESSAGE { static const uint16_t packetID = 2303; }; struct BM_SC_CREATE_ROOM : public TS_MESSAGE { char Name[24]; char password[4]; char uk[48]; uint8_t MaxPlayers; uint32_t Mode; uint8_t Level; static const uint16_t packetID = 2173; }; struct BM_SC_ENTER_ROOM : public TS_MESSAGE { uint8_t uk1; uint32_t roomid; static const uint16_t packetID = 2175; }; struct BM_SC_READY_GAME : public TS_MESSAGE { static const uint16_t packetID = 2187; }; struct BM_SC_LEAVE_ROOM : public TS_MESSAGE { static const uint16_t packetID = 2177; }; struct BM_SC_START_GAME : public TS_MESSAGE { //has some data static const uint16_t packetID = 2189; }; struct BM_SC_SELECT_MAP : public TS_MESSAGE { uint16_t mapid; static const uint16_t packetID = 2198; }; struct BM_SC_UPDATE_ROUND : public TS_MESSAGE { uint16_t uk1; static const uint16_t packetID = 2204; }; struct BM_SC_FINISH_RACE : public TS_MESSAGE { char gameid[16]; static const uint16_t packetID = 2191; }; struct BM_SC_UNKNOWN_INFO : public TS_MESSAGE { uint8_t uk1; uint32_t id; static const uint16_t packetID = 2183; }; struct BM_SC_CHARACTER_INFO_RESP : public TS_MESSAGE { char successmessage[8]; uint32_t uk1; uint32_t uk2; uint32_t uk3; uint32_t uk4; char charname[40]; uint32_t uk5; uint32_t uk6; uint8_t uk7; uint8_t chartype; uint8_t uk8; uint32_t uk9; uint32_t uk10; uint32_t uk11; uint32_t uk12; uint32_t uk13; uint32_t uk14; uint32_t uk15; uint32_t uk16; uint32_t charlevel; uint32_t uk17; uint32_t uk18; uint32_t uk19; uint32_t uk20; uint32_t uk21; uint32_t head; uint32_t face; uint32_t upper; uint32_t lower; uint32_t foot; uint32_t hand; uint32_t google; uint32_t accesoire; uint32_t theme; uint32_t mantle; uint32_t buckle; uint32_t vent; uint32_t nitro; uint32_t wheels; uint8_t uk22; uint32_t uk23; uint32_t tricksize; sg_constructor::Tricksrace tricklist[13]; static const uint16_t packetID = 2147; }; #endif
#ifndef _GUARD_EEMP_H #define _GUARD_EEMP_H #include <ostream> #include <utility> #include <vector> #include "partial_perm.h" #include "perm_group.h" /** * @file eemp.h * @brief Definitions related to inverse semigroups of partial permutations. * * This file defines several auxiliary functions used behind the scenes of * PartialPermInverseSemigroup. All functions and their implementations are * based on \cite east16. * * @author Timo Nicolai */ namespace cgtl { namespace eemp { /** Schreier tree data structure. * * Describes an OrbitGraph spanning tree. Similar to, but not to be confused * with cgtl::SchreierTree. Should be treated as opaque by * functions other than those defined in eemp.h. */ struct SchreierTree { std::vector<std::pair<unsigned, unsigned>> data; }; /** Orbit graph data structure. * * Describes an *orbit graph* according to the description of * action_component(). Should be treated as opaque by functions other than * those defined in eemp.h. */ struct OrbitGraph { std::vector<std::vector<unsigned>> data; }; /** Compute the *component of the action* of a set of partial permutations (the * *generators*) on a set of elements \f$\alpha\f$ as well an associated *orbit * graph* and spanning *Schreier tree*. * * The action component results from the repeated application of the generators * to \f$\alpha\f$ (*application* refers to the operation performed by the * PartialPerm::image() function) and all resulting sets of elements until a * fixpoint is reached. The resulting orbit graph is the unique directed graph * connecting nodes corresponding to the resulting sets with edges labelled * with the generators that produce the destination node's set when applied to * the source node's set. The Schreier tree is a spanning tree through the * orbit graph rooted at the node corresponding to \f$\alpha\f$ (in most cases * there are several possible such spanning trees, this function makes no * guarantees about which one is returned). Orbit graph and Schreier tree can * be treated as opaque by code which uses the functions defined in this header. * * \param alpha * a set of elements in the form of a vector, the first element in the * resulting action component and root of the resulting orbit graph and * Schreier tree * * \param generators a set of partial permutations in the form of a vector * * \param dom_max * the maximum over the values `PartialPerm::dom_max()` of all generators * (passed as an argument to avoid frequent recalculation) * * \param[out] schreier_tree the resulting Schreier tree * * \param[out] orbit_graph the resulting orbit graph * * \return the resulting action component in form of a vector of vectors; * Schreier tree and orbit graph are internally represented using * indices into this vector and are thus only meaningful in combination * with it */ std::vector<std::vector<unsigned>> action_component( std::vector<unsigned> const &alpha, std::vector<PartialPerm> const &generators, unsigned dom_max, SchreierTree &schreier_tree, OrbitGraph &orbit_graph); /** Find the *strongly connected components* of an orbit graph. * * The strongly connected components (short s.c.c.'s) are a partition of the * orbit graph such that all nodes in a strongly connected components can be * directly or indirectly reached from every other node in the strongly * connected component. * * \param orbit_graph orbit graph for which the s.c.c.'s are to be determined * * \return a pair in which the first element is the number of resulting s.c.c's * and the second element is a vector containing as many elements as * there are nodes in the orbit graph (and thus elements in the * corresponding action component) in which two elements have the same * value if and only if the nodes corresponding to their indices in the * vector lie in the same s.c.c. * * Example: * * Assume that an action component \f$\{\alpha_1, \alpha_2, \alpha_3, * \alpha_4\}\f$ is partitioned according to the s.c.c.'s of an associated * orbit graph as follows: \f$\{\{\alpha_1\}, \{\alpha_2, \alpha_3\}, * \{\alpha_4\}\}\f$. This function might then return `{3u, {0u, 1u, 1u, 2u}}` * (the concrete values assigned to each s.c.c. in the resulting vector are not * guaranteed). */ std::pair<unsigned, std::vector<unsigned>> strongly_connected_components( OrbitGraph const &orbit_graph); /** Find a spanning tree for a strongly connected component inside an orbit * graph. * * \param i * the resulting spanning tree will be calculated for the s.c.c. with index * `i` (i.e. all the elements at indices corresponding to elements in the * s.c.c. given by the `scc` argument have value `i`) * * \param orbit_graph the orbit graph * * \param scc * the orbit graphs s.c.c.'s, determined via strongly_connected_components() * * \return a spanning Schreier tree for the given s.c.c. rooted at the node * inside the s.c.c. which corresponds to the element with the smallest * index in the associated action component */ SchreierTree scc_spanning_tree( unsigned i, OrbitGraph const &orbit_graph, std::vector<unsigned> const &scc); /** Trace a Schreier tree * * Trace a Schreier tree for some orbit graph from a node back to its root, * i.e. determine the partial permutation which results from chaining the * partial permuation edge labels on the way through the Schreier tree from the * root to the node together. * * \param x * the action component index of the node from which the backtracing * operation through the Schreier tree should be performed. * * \param schreier_tree the Schreier tree * * \param generators * the generators which were used in the generation of the Schreier (using * action_component()) and form the Schreier tree's edge labels * * \param dom_max * the maximum over the values `PartialPerm::dom_max()` of all generators * (passed as an argument to avoid frequent recalculation) * * \param target * the index at which the backtracing operation should terminate, i.e. the * root node's index. Ordinarily this should be `0u` except when this * function is used to perform backtracing through s.c.c. spanning trees * obtain via scc_spanning_tree() */ PartialPerm schreier_trace( unsigned x, SchreierTree const &schreier_tree, std::vector<PartialPerm> const &generators, unsigned dom_max, unsigned target = 0u); /** Compute the *Schreier generators* for one strongly connected component of an * orbit graph. * * The Schreier generators form a permutation group, for details on their * theoretical significance see \cite east16. * * \param i * the resulting Schreier generators will be calculated for the s.c.c with * index `i` (i.e. all the elements at indices corresponding to elements in * the s.c.c. given by the `scc` argument have value `i`) * * \param generators * the generators used to generate the orbit graph and the corresponding * action component * * \param dom_max * the maximum over the values `PartialPerm::dom_max()` of all generators * (passed as an argument to avoid frequent recalculation) * * \param action_component the action component associated with the orbit graph * * \param schreier_tree * a spanning Schreier tree through the s.c.c. rooted at the s.c.c.'s element * with the smallest action component index * * \param orbit_graph the orbit graph * * \param sccs * the orbit graphs s.c.c.'s, determined via strongly_connected_components() */ PermGroup schreier_generators( unsigned i, std::vector<PartialPerm> const &generators, unsigned dom_max, std::vector<std::vector<unsigned>> const &action_component, SchreierTree const &schreier_tree, OrbitGraph const &orbit_graph, std::vector<unsigned> const &sccs); /** Calculate the \f$\mathscr{R}\f$-class respresentatives of an inverse partial * permutation semigroup from a corresponding Schreier tree. * * See \cite east16 for details on the theory begin \f$\mathscr{R}\f$-classes. * In the special case of an inverse semigroup of partial permutations \f$G\f$ * the \f$\mathscr{R}\f$-class representatives can be determined by first * obtaining a Schreier tree for on orbit graph constructed using a generating * set for the group and rooted at \f$\cup_{g \in G} dom(g)\f$ and then * calculating the partial permutations that result if for every path from the * Schreier tree's root to one its leaves the corresponding partial permutation * edge labels are chained together. * * \param schreier_tree * the Schreier tree rooted at \f$\cup_{g \in G} dom(g)\f$ which is traced * in order to determine the \f$\mathscr{R}\f$-class representatives * * \param generators * the partial permutations which constitute the Schreier tree's edge labels * * \return a vector containing the \f$\mathscr{R}\f$-class representatives in no * particular order */ std::vector<PartialPerm> r_class_representatives( SchreierTree const &schreier_tree, std::vector<PartialPerm> const &generators); /** Expand a compact set partition representation into an explicit which allows * iteration over the partitions. * * \param partition * a partition in form of a vector in which set elements correspond to * indices and elements belonging to the same partition are marked by equal * vector elements at their repective indices * * \return a vector of vectors, where each subvector contains all subelements in * a single partition (in ascending order) and in which the subvectors * are ordered according to their minimum elements (in ascending order) */ std::vector<std::vector<unsigned>> expand_partition( std::vector<unsigned> partition); /** Print a Schreier tree according to the notation in \cite east16. * * \param stream a stream object * * \param schreier_tree the Schreier tree * * \return `stream` */ std::ostream &operator<<(std::ostream &os, SchreierTree const &schreier_tree); /** Print an orbit graph according to the notation in \cite east16. * * \param stream a stream object * * \param orbit_graph the orbit graph * * \return a reference to `stream` */ std::ostream &operator<<(std::ostream &os, OrbitGraph const &orbit_graph); } // namespace eemp } // namespace cgtl #endif // _GUARD_EEMP_H
#include <stdio.h> #include <stdlib.h> int main() { int a, b, c, maior; printf("Digite tres numeros inteiros separados por espaco:"); scanf_s("%d %d %d", &a, &b, &c); maior = (a + b + abs(a - b)) / 2; maior = (maior + c + abs(maior - c)) / 2; printf("O maior numero eh %d.\n", maior); system("pause"); return 0; }
#ifndef __PATH_H__ #define __PATH_H__ #include <string> class Path { std::string shadersPath; std::string texturesPath; public: Path(std::string shaders_folder, std::string texture_folder) : shadersPath(shaders_folder), texturesPath(texture_folder) {} std::string sp(const std::string& name) { std::string str = shadersPath + name; return str; } std::string tp(const std::string& name) { std::string str = texturesPath + name; return str; } }; #endif
#pragma once #include "Application/Command.h" #include <vector> #include "glm/vec2.hpp" class DrawCommand : public Command { public: DrawCommand(std::vector<glm::vec2> locations, unsigned char* bitMap); ~DrawCommand(); virtual void Execute() override; virtual void Undo() override; private: std::vector<glm::vec2> m_StrokeLocations; unsigned char* m_BitMap; unsigned char* m_SavedBytes; unsigned int xOffset; unsigned int yOffset; unsigned int w; unsigned int h; };
///////////////////////////////////////////////////////////////////// // DepAnal.h - Determines depedancies based on #include // // // // Language: Visual C++ 2015 // // Platform: Lenovo Yoga, Windows 8.1 // // Application: Code Publisher - CSE 687 Project 3 // // Author: Soumyashree Mohan Reddy SUID:291434954 // ///////////////////////////////////////////////////////////////////// /* Dependency Analyzer gives the determines dependensies based on #include * Required Files: * --------------- * DepAnal.h DepAnal.cpp Executive.h Executive.cpp * Public Interface: * ================= * DepAnal(sourcefiles) * Display() * Maintanence History: * -------------------- * Added DependencyAnalyzer class which helps in the finding Deprndencies */ #include <string> #include <regex> #include <fstream> #include <iostream> #include <unordered_map> using Files = std::vector<std::string>; class DependencyAnalyzer { public: DependencyAnalyzer(); std::unordered_map<std::string, std::vector<std::string>> DepAnal(Files sourcefiles); void Display(); private: Files FilesForAnal; std::unordered_map<std::string, std::vector<std::string>> FileDependencies; };
#ifndef LIGHTSOURCE_HPP #define LIGHTSOURCE_HPP #include "RT_Object.hpp" #include "RT_Vec3.hpp" class LightSource { protected: RT_Vec3 m_Position; // ambient RT_Vec3 m_Ka; // diffuse RT_Vec3 m_Kd; // specular RT_Vec3 m_Ks; public: LightSource(); LightSource(const RT_Vec3& pos, const RT_Vec3& ka, \ const RT_Vec3& kd, const RT_Vec3& ks); void setPosition(const RT_Vec3&); void setKa(const RT_Vec3&); void setKd(const RT_Vec3&); void setKs(const RT_Vec3&); RT_Vec3 getPosition() const; RT_Vec3 getKa() const; RT_Vec3 getKd() const; RT_Vec3 getKs() const; virtual RT_Vec3 ambient_calc(const RT_Vec3& material_Ka) \ const = 0; virtual RT_Vec3 diffuse_calc(const RT_Vec3& material_Kd, \ const RT_Vec3& normal, const RT_Vec3& rayDirection) const = 0; virtual RT_Vec3 specular_calc(const RT_Vec3& material_Ks, const RT_Vec3& normal, const RT_Vec3& rayDirection, const RT_Vec3& cameraDirection, double material_shinness) \ const = 0; virtual RT_Vec3 color_calc(const RT_Object* obj, \ const RT_Vec3& point, const RT_Vec3& cameraPosition) const = 0; virtual RT_Vec3 get_light_dir(const RT_Vec3& point) const = 0; }; #endif
#include <bits/stdc++.h> #include <vector> #include<iostream> using namespace std; template<typename T> class statistic{ static int size; public: float Mean(vector<T> &vect); float median(vector< T> &vect); vector<T> mode(vector<T> &vect); }; template<typename T> float statistic<T>:: Mean(vector<T> &vect) { size=vect.size(); float mean=0; int rem=0; for(auto it=vect.begin();it!=vect.end();it++) { try{ if(sizeof(*it)==1) throw *it; } catch(T x){ cout <<"Exception caught ,"<<x <<"is not a int or float\n"; return 0; } mean+=(*it)/size; rem+= (int)(*it)%size; } if(rem>size) mean+=rem/size; return mean; } template<typename T> float statistic<T>:: median(vector<T> &vect) { int mid; float mid_ele; vector<T>v1=vect; sort(v1.begin(),v1.end()); mid=size/2; if(size%2==0) mid_ele=(float)(v1[mid] +v1[mid-1])/2; else mid_ele=v1[mid]; return mid_ele; } template<typename T> vector<T> statistic<T>:: mode(vector<T> &vect) { vector<T>v1; int max_count=0,max=0,i=0; int size=vect.size(); auto it=vect.begin(); bool hash[123456]={0}; while(it!=vect.end()) { max=count(vect.begin(),vect.end(),*it); if(max>max_count) max_count=max; it++; } it=vect.begin(); while(it!=vect.end()) { if(hash[(int)*it]==0){ if(count(vect.begin(),vect.end(),*it)==max_count) { v1.push_back(*it); } } hash[(int)*it]=1; it++; } return v1; } template<typename T> int statistic<T> :: size=0; int main() { vector<float> vect; statistic<float> obj; int n; float ele; cout<<"enter the size for list : "; cin>> n; cout<<"\n enter elements for list :"; for(int i=0;i<n;i++){ cin >>ele; vect.push_back(ele); } cout<<"Mean = "<<obj.Mean(vect); cout<<"\nMedian= "<<obj.median(vect); cout<<"\nmode= "; vector<float>v1=obj.mode(vect); for(auto it=v1.begin();it!=v1.end();it++) cout<<*it <<" "; cout<<endl; }
/* * MidiQueue.cpp * * Created on: Feb 4, 2019 * Author: juniper */ #include "MidiQueue.h" //#ifdef ON_BELA //#include <libpd/z_libpd.h> //extern "C" { //#include <libpd/s_stuff.h> //}; //#else //#include <z_libpd.h> //extern "C" { //#include <s_stuff.h> //}; //#endif MidiQueue* MidiQueue::instance_; boost::circular_buffer<MidiMessage> MidiQueue::queue_; MidiQueue::MidiQueue() { } MidiQueue* MidiQueue::get_instance() { if (instance_ == NULL) { instance_ = new MidiQueue(); } return instance_; } void MidiQueue::resize(boost::circular_buffer<MidiMessage>::size_type size) { queue_.resize(size); } void MidiQueue::push_back(MidiMessage message) { queue_.push_back(message); } MidiMessage MidiQueue::pop_front() { MidiMessage result = queue_.front(); queue_.pop_front(); return result; } void MidiQueue::process() { MidiMessage currentMessage; for (unsigned int i = 0; i < queue_.size(); ++i) { currentMessage = queue_.front(); queue_.pop_front(); switch (currentMessage.getType()) { #ifdef ON_BELA case kMidiMessageNoteOff: libpd_noteon(currentMessage.getChannel(), currentMessage.getNote(), 0); break; case kMidiMessageNoteOn: libpd_noteon(currentMessage.getChannel(), currentMessage.getNote(), currentMessage.getVelocity()); break; #endif default: break; } } } void MidiQueue::prettyPrint(MidiMessage message) { printf("Sending pd MIDI message: " "channel = %d, " "type = %d, " "pitch = %d, " "velocity = %d\n", message.getChannel(), message.getType(), message.getNote(), message.getVelocity()); }
// Created on: 1995-03-17 // Created by: Mister rmi // Copyright (c) 1995-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 _Aspect_CircularGrid_HeaderFile #define _Aspect_CircularGrid_HeaderFile #include <Standard_Integer.hxx> #include <Aspect_Grid.hxx> class Aspect_CircularGrid : public Aspect_Grid { DEFINE_STANDARD_RTTIEXT(Aspect_CircularGrid, Aspect_Grid) public: //! creates a new grid. By default this grid is not //! active. Standard_EXPORT Aspect_CircularGrid(const Standard_Real aRadiusStep, const Standard_Integer aDivisionNumber, const Standard_Real XOrigin = 0, const Standard_Real anYOrigin = 0, const Standard_Real aRotationAngle = 0); //! defines the x step of the grid. Standard_EXPORT void SetRadiusStep (const Standard_Real aStep); //! defines the step of the grid. Standard_EXPORT void SetDivisionNumber (const Standard_Integer aNumber); Standard_EXPORT void SetGridValues (const Standard_Real XOrigin, const Standard_Real YOrigin, const Standard_Real RadiusStep, const Standard_Integer DivisionNumber, const Standard_Real RotationAngle); //! returns the point of the grid the closest to the point X,Y Standard_EXPORT virtual void Compute (const Standard_Real X, const Standard_Real Y, Standard_Real& gridX, Standard_Real& gridY) const Standard_OVERRIDE; //! returns the x step of the grid. Standard_EXPORT Standard_Real RadiusStep() const; //! returns the x step of the grid. Standard_EXPORT Standard_Integer DivisionNumber() const; Standard_EXPORT virtual void Init() Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; private: Standard_Real myRadiusStep; Standard_Integer myDivisionNumber; Standard_Real myAlpha; Standard_Real myA1; Standard_Real myB1; }; DEFINE_STANDARD_HANDLE(Aspect_CircularGrid, Aspect_Grid) #endif // _Aspect_CircularGrid_HeaderFile
// ========================================================================== // Wrapper code to interface g_Element // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: Jochen Lang // Email: jlang@site.uottawa.ca // ========================================================================== // $Rev: 3834 $ // $LastChangedBy: jlang $ // $LastChangedDate: 2013-04-11 16:03:39 -0400 (Thu, 11 Apr 2013) $ // ========================================================================== #ifndef WRAPPER_G_ELEMENT_CPP #define WRAPPER_G_ELEMENT_CPP #include "g_Element.h" #include "g_Node.h" #include "g_PEdge.h" using std::cerr; using std::endl; void g_Element::node( g_Node* n ) { d_nodes.insert(n); n->element(*this); } int g_Element::id() const { return d_id; } g_NodeContainer g_Element::nodes() const { return d_nodes; } // Make an edge list for current face g_PEdgeContainer g_Element::pEdges() const { g_PEdgeContainer edges; g_NodeContainer::const_iterator prev = d_nodes.begin(); for ( g_NodeContainer::const_iterator nIt = ++d_nodes.begin(); nIt != d_nodes.end(); ++nIt ) { // cerr << "At: " << (*nIt)->id() << endl; edges.insert(new g_PEdge(**prev,**nIt)); prev = nIt; } edges.insert(new g_PEdge(**(--d_nodes.end()),**d_nodes.begin())); return edges; } void g_Element::emptyNodeList() { #if 0 // May leave pointers to this node around for ( g_NodeContainer::iterator nIt = ++d_nodes.begin(); nIt != d_nodes.end(); ++nIt ) { (*nIt)->removeElement( this ); } #endif d_nodes.clear(); return; } void g_Element::replaceNodeAt( int& index, g_Node*& n) { d_nodes[index] = n; return; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 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 URL_FILTER #include "modules/content_filter/content_filter.h" ContentFilterModule::ContentFilterModule() : url_filter(NULL) { } void ContentFilterModule::InitL(const OperaInitInfo& info) { url_filter = OP_NEW_L(URLFilter, ()); if(url_filter) { url_filter->InitL(); } } void ContentFilterModule::Destroy() { OP_DELETE(url_filter); url_filter = NULL; } #endif // URL_FILTER
/* Name: °´²ã´òÓ¡¶þ²æÊ÷ Copyright: Author: Xiao Dong, Xiao Date: 2019/8/21 15:22:31 Description: TODO δ֪´íÎó */ #include <bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { if (root == nullptr) return {}; TreeNode* last = root; TreeNode* qlast = root; stack<vector<int>> stk; queue<TreeNode*> que; que.push(root); while (!que.empty()) { auto a = que.front(); que.pop(); if (a->left) { que.push(a->left); qlast = a->left; } if (a->right) { que.push(a->right); qlast = a->right; } stk.top().push_back(a->val); if (a == last) { stk.push({}); last = qlast; } } vector<vector<int>> ans; while (!stk.empty()) { ans.push_back(stk.top()); stk.pop(); } return ans; } }; int main() { /* code here */ return 0; }
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; struct Stat { int d, s; Stat(){} Stat(int d, int s):d(d),s(s){} }; bool operator<(const Stat &r, const Stat &s) { return r.d > s.d; } int n, S; int s[N], a[N], b[N], d[N]; Stat stats[N]; long long pres[N]; long long cp(long long len) { long long ans = 0; for(int i = 1; i <= n; i++) { if(pres[i] <= len) { ans += (long long)stats[i].s * stats[i].d; } else { ans += (long long)(len - pres[i-1]) * stats[i].d; break; } } return ans; } long long calc(long long s, long long more) { vector<int> vc; for(int i = 1; i <= n; i++) { if(pres[i] >= s) { for(int j = 1; j <= pres[i] - s + 1 && more >= 1; j++) { vc.push_back(stats[i].d); more--; } for(int ii = i + 1; ii <= n && more >= 1; ii++) for(int j = 1; j <= stats[ii].s && more >= 1; j++) { vc.push_back(stats[ii].d); more--; } long long ans = 0; for(int t = 0; t < (int)vc.size(); t++) { if(vc[t] > 0) ans += vc[t]; } return ans; } } return 0; } int main() { scanf("%d%d", &n, &S); long long sum = 0, ans = 0; for(int i = 1; i <= n; i++) { scanf("%d%d%d", s+i, a+i, b+i); sum += s[i]; ans += (long long)b[i] * s[i]; stats[i] = Stat(a[i] - b[i], s[i]); } sort(stats+1, stats+1+n); for(int i = 1; i <= n; i++) pres[i] = pres[i-1] + stats[i].s; long long m = (sum + S - 1) / S; long long sub = 0; if(stats[n].d >= 0) { for(int i = 1; i <= n; i++) sub += (long long)stats[i].d * stats[i].s; ans += sub; printf("%lld\n", ans); } else { for(int i = 1; i <= n; i++) { if(stats[i].d < 0) { long long subans = ans + cp(pres[i-1] / S * S); long long more = S * m - sum; subans = max(subans, ans + cp(pres[i-1] / S * S + S - more) + calc(pres[i - 1] / S * S + S - more + 1, more)); printf("%lld\n", subans); break; } } } }
#include <iostream> //standard input-output stream using namespace std; //standard namespace. cout, cin and a lot of other things are defined in it. int main() { int num1, num2, num3; int smallest, largest; // declaration cout << "Input three different integers: "; // prompt cin >> num1 >> num2 >> num3; // input largest = num1; // programme assumes first number to be largest if (num2 > largest) // is num2 larger? largest = num2; // if yes then the largest is num2 if (num3 > largest) // is num3 larger? largest = num3; // if yes then the largest is num3 smallest = num1; // programme assumes first number to be smallest if (num2 < smallest) //if num2 smaller smallest = num2; //if yes then the smallest is num2 if (num3 < smallest) //if num3 smaller smallest = num3; //if yes then the smallest is num3 cout << "Sum is " << num1 + num2 + num3 // addition output << "\nAverage is " << (num1 + num2 + num3) / 3 //Average output << "\nProduct is " << num1 * num2 * num3 //Product output << "\nSmallest is " << smallest //Smallest number << "\nLargest is " << largest << endl; //Largest number return 0; }
#include <iostream> int toPal(int n, bool even); bool base2Pal(int n); int main() { int sum = 0; for (int n = 0; n < 1000; n++) { int pal1 = toPal(n, false); int pal2 = toPal(n, true); if (base2Pal(pal1)) sum += pal1; if (base2Pal(pal2)) sum += pal2; } std::cout << sum << "\n"; } int toPal(int n, bool even) { if (even) n = n * 10 + n % 10; for (int tempN = (even?n/100:n/10); tempN > 0; tempN /= 10) n = n * 10 + tempN % 10; return n; } bool base2Pal(int n) { int reversedN = 0; for (int power = 0; n >= 1 << power; power++) reversedN = reversedN * 2 + ((n & (1 << power)) ? 1 : 0); return reversedN == n; }
#include "aeMath.h" namespace aeEngineSDK { aeRay::aeRay() { } aeRay::aeRay(const aeRay & A) { *this = A; } aeRay::~aeRay() { } }
#include <iostream> #include <random> #include <utility> #include <vector> #include <ctime> #include <fstream> #include <list> using namespace std; int seed; mt19937 getRand(seed); struct node { string key, value; node *prev; node *next; node(string _key, string _value) { key = move(_key); value = move(_value); prev = nullptr; next = nullptr; } }; class LinkedMap { private: long long p = 93563; vector<list<node>> _array; long long a; long long b; node *pre; int hash(string &item) { long long h = 0; for (int i = 0; i < (int) item.size(); i++) { h = (h + (int) ((a + i) * item[i] + b)) % p; } return (int) h; } public: LinkedMap() { _array = vector<list<node>>((int)p); a = getRand() % p; b = getRand() % p; pre = nullptr; } void insert(string &key, string &value) { node *cur = _insert(key, value); if (cur != nullptr) { if (pre) pre->next = cur; cur->prev = pre; pre = cur; } } node *_insert(string &key, string &value) { int h = hash(key); auto &v = _array[h]; auto f = find(key, h); if (f == v.end()) { v.emplace_back(key, value); return &v.back(); } else { f->value = value; return nullptr; } } list<node>::iterator find(string &key, int h) { list<node> &v = _array[h]; for (auto i = v.begin(); i != v.end(); i++) { if (i->key == key) { return i; } } return v.end(); } string prev(string &key) { int h = hash(key); auto &v = _array[h]; auto f = find(key, h); if (f == v.end() || !f->prev) { return "none"; } else { return f->prev->value; } } string next(string &key) { int h = hash(key); auto &v = _array[h]; auto f = find(key, h); if (f == v.end() || !f->next) { return "none"; } else { return f->next->value; } } string get(string &key) { int h = hash(key); auto f = find(key, h); auto &v = _array[h]; return f == v.end() ? "none" : f->value; } string operator[](string &key) { return get(key); } void remove(string &key) { int h = hash(key); auto &v = _array[h]; auto f = find(key, h); if (f == v.end()) return; if (f->prev != nullptr) f->prev->next = f->next; if (f->next != nullptr) f->next->prev = f->prev; if (&*f == pre) { pre = f->prev; } v.erase(f); } }; int main() { seed = time(nullptr); string command, key, value; LinkedMap m; ifstream fin("linkedmap.in"); ofstream fout("linkedmap.out"); while (fin >> command) { fin >> key; if (command == "put") { fin >> value; m.insert(key, value); } else if (command == "get") { fout << m[key] << endl; } else if (command == "prev") { fout << m.prev(key) << endl; } else if (command == "next") { fout << m.next(key) << endl; } else { m.remove(key); } } return 0; }
#pragma once namespace game { class Player; } namespace jsplayer { JSBool createPlayerObject(JSContext* cx, JSObject* parent, const char* name, game::Player* player); }
/*Boost asio implementation (compilation optimization).*/ #include "cc/asio/boost_asio_utils.h" #include <boost/asio/impl/src.hpp>
#pragma once #include "CritlSec.h" #define BUFFER_SIZE 1024 #define QUEUE_SIZE 10240000 class Element { public: Element(int nIndex, double lfRatio): m_nElemIndex(nIndex), m_lfRatio(lfRatio) { } ~Element() { } int m_nElemIndex = 0; double m_lfRatio = 0; }; using elemntList = vector<Element>; class CResult { public: CResult(double lfScore, int nElementCount, const unsigned long* pElementIndexList, const unsigned long* pElementRatioList): m_lfScore(lfScore) { for (int i = 0; i < nElementCount; i++) { m_listElements.push_back(Element(pElementIndexList[i], pElementRatioList[i])); } } CResult() { } ~CResult() { } bool operator < (const CResult& rfValue) { return m_lfScore > rfValue.m_lfScore; } wstring ConvertToRow() { wstring strRow; double lfRatios[8] = { 0 }; wchar_t str[BUFFER_SIZE] = { 0 }; for (const auto& element : m_listElements) { lfRatios[element.m_nElemIndex] = element.m_lfRatio; } StringCbPrintf(str, BUFFER_SIZE * sizeof(wchar_t), L"%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf", m_lfScore, lfRatios[0], lfRatios[1], lfRatios[2], lfRatios[3], lfRatios[4], lfRatios[5], lfRatios[6], lfRatios[7]); strRow = str; return strRow; } double m_lfScore = 0; elemntList m_listElements; }; class CResultQueue { public: CResultQueue() { m_resultQueue.resize(m_ulQueueSize); m_hQueueEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); } ~CResultQueue() { } void PushResult(double lfScore, int nElementCount, const unsigned long* pElementIndexList, const unsigned long* pElementRatioList) { m_resultQueue[m_nQueueHead] = CResult(lfScore, nElementCount, pElementIndexList, pElementRatioList); m_nQueueHead++; if (m_nQueueHead >= m_ulQueueSize) { m_nQueueHead = m_nQueueHead % m_ulQueueSize; if (m_nQueueHead == m_nQueueTail) { m_ulQueueSize = m_ulQueueSize * 2; m_resultQueue.resize(m_ulQueueSize); } } SetEvent(m_hQueueEvent); } void ClearEvent() { ResetEvent(m_hQueueEvent); } wstring PeekResult() { wstring strResult = m_resultQueue[m_nQueueTail].ConvertToRow(); m_nQueueTail++; if (m_nQueueTail >= m_ulQueueSize) { m_nQueueTail = m_nQueueTail % m_ulQueueSize; } return strResult; } void Clear() { m_resultQueue.clear(); } HANDLE GetQueueEvent() { return m_hQueueEvent; } bool IsEmpty() { return m_nQueueHead == m_nQueueTail; } private: vector<CResult> m_resultQueue; CCritSec m_csRsultQueueLock; HANDLE m_hQueueEvent = nullptr; unsigned long m_ulQueueSize = QUEUE_SIZE; int m_nQueueHead = 0; int m_nQueueTail = 0; };
// Client Widget // // Copyright (C) 2008 // Center for Perceptual Systems // University of Texas at Austin // // jsp Mon Aug 4 14:38:43 CDT 2008 #ifndef CLIENT_WIDGET_H #define CLIENT_WIDGET_H #include <QAction> #include <QComboBox> #include <QDebug> #include <QHBoxLayout> #include <QIntValidator> #include <QLabel> #include <QLineEdit> #include <QToolBar> #include <QToolButton> #include <stdexcept> #include "client.h" namespace flying_dragon { /// @brief Widget that controls a client /// /// The widget allows you to connect to a server. class ClientWidget : public QToolBar { Q_OBJECT public: /// @brief Constructor /// @param parent Parent widget /// @param client Client ClientWidget (QWidget *parent, Client *client) : QToolBar (parent) , client_ (client) , address_ (0) , port_ (0) , connect_action_ (0) { setObjectName (QString ("ClientWidget")); SetupUI (); } private slots: void on_ConnectAction_triggered () { client_->Connect (address_->text (), port_->text ().toInt ()); } private: void SetupUI () { QIcon connect_icon; connect_icon = QIcon (QString::fromUtf8 (":/flying_dragon/images/new_connection.png")); connect_action_ = new QAction (connect_icon, "Connect", this); connect_action_->setObjectName(QString("ConnectAction")); connect_action_->setCheckable (false); connect_action_->setToolTip ("Connect to server"); connect_action_->setShortcut(QKeySequence ("Ctrl+C")); addAction (connect_action_); address_ = new QLineEdit (this); address_->setObjectName(QString("Address")); address_->setText (QString ("localhost")); address_->setToolTip ("Server address"); addWidget (address_); addSeparator (); //addWidget (new QLabel ("Port", this)); port_ = new QLineEdit ("Port", this); port_->setText ("7480"); port_->setValidator (new QIntValidator (this)); port_->setToolTip ("Server port"); port_->setVisible (false); //addWidget (port_); QMetaObject::connectSlotsByName (this); } Client *client_; QLineEdit *address_; QLineEdit *port_; QAction *connect_action_; }; } // namespace flying_dragon #endif // CLIENT_WIDGET_H
// // main.cpp // 2017.2.26.15.25.1.7 // // Created by Thai Cao Ngoc on 26/2/17. // Copyright © 2017 Thai Cao Ngoc. All rights reserved. // #include <iostream> #include <cstdlib> #include <ctime> #include <iomanip> class Rotate { public: void rotate (int** matrix, size_t N) { for (size_t layer = 0; layer < N/2; ++layer) { for (size_t j = layer; j < N - 1 - layer; ++j) { int temp = matrix[layer][j]; matrix[layer][j] = matrix[N - 1 - j][layer]; matrix[N - 1 - j][layer] = matrix[N - 1 - layer][N - 1 - j]; matrix[N - 1 - layer][N - 1 - j] = matrix[j][N - 1 - layer]; matrix[j][N - 1 - layer] = temp; } } } }; int main() { srand((unsigned int)time(nullptr)); size_t size = 0; std::cout << "Size: "; std::cin >> size; int** matrix; matrix = new int*[size]; for (int i = 0; i < size; ++i) { matrix[i] = new int[size]; for (int j = 0; j < size; ++j) { matrix[i][j] = rand() % 100; std::cout << std::setw(5) << matrix[i][j]; } std::cout << std::endl; } std::cout << std::endl << std::endl; Rotate rotate; rotate.rotate(matrix, size); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { std::cout << std::setw(5) << matrix[i][j]; } delete[] matrix[i]; std::cout << std::endl; } delete[] matrix; }
//airlineTicket.h #include<string> using namespace std; class airlineTicket { public: airlineTicket(); ~airlineTicket(); int calculatePrinceInDollars(); string getPassengerName(); void setPassengerName(string inName); int getNumberOfMiles(); void setNumberOfMiles(int inMiles); bool getHasEliteSuperRewardsStatus(); void setHasEliteSuperRewardsStatus(bool inStatus); private: string mPassengerName; int mNumberOfMiles; bool fHasEliteSuperRewardsStatus; };
//对 回忆一下自己的做题思路(最近每做一题就把这个粘过去) //1.先理解题 //2.确定解题思路(选择数据结构算法什么的) 确定能解决正常情况,也不用考虑太多复杂度 //3.2达到之后, 开始考虑各种解决可能遇到的奇怪情况 然后看看有没有复杂度更低的思路 //看完题,能想出朴素算法 有个大概思路 但是不能保证不超时 然后看一看原来的代码吧 //突然发现还是按照最坏情况申请内存比较好,省了好多麻烦 //发现原来的代码也挺朴素的 简单的思路,但是45分了 思考一下能不能做出一点改进呢. //突然看到hash,想起了把字母全加起来判等,不过不知道能不能减少时间.那就先试试吧. //果然 思考多一点 速度快的不是一点 立刻就50分了 每个速度都比原来缩了好几倍 最后一组数据缩减为1/6 要多思考啊 #include<iostream> #include<cstdio> #include<string.h> using namespace std; struct box{ char* imprint=new char[10010]; int num; int sum=0; }; int match(char*a,char*b,int result,int n){ for(int i=0;i<n;++i){//2:‘n’在此作用域中尚未声明 if(b[i]==a[0]){ int num=i; int sign=9; for(int j=0,k=num;k<n;k++,j++){//3:在 ISO‘for’作用域中,‘k’的名称查找有变化 [-fpermissive](就是因为小括号后面多写了个分号) if(b[k]!=a[j]){ sign=10; break; } } if(9==sign){ for(int j=n-num,k=0;j<n;k++,j++){ if(b[k]!=a[j]){ sign=10; break; } } if(9==sign){ return result; } } } } return -1; } int main(){ int m,n; fscanf(stdin,"%d %d",&m,&n); getchar(); box data[m]; for(int i=0;i<m;++i){ gets(data[i].imprint); int length=strlen(data[i].imprint); for(int j=0;j<length;++j){ data[i].sum += data[i].imprint[j] - 'a'; } } box type[m]; int amount=0; for(int i=0;i<m;++i){ int result=-1; for(int j=0;j<amount;++j){//4:一直输出0 1 2 3 4 问题在这 j写成i了 if(data[i].sum==type[j].sum){ result=match(data[i].imprint,type[j].imprint,type[j].num,n);//4:一直输出0 1 2 3 4 问题在这 j写成i了 if(result>=0){ break; } } } if(result>=0){ fprintf(stdout,"%d\n",result); }else{ type[amount].imprint=data[i].imprint;//1:无效的数组赋值 type[amount].num=i; type[amount].sum=data[i].sum; amount=amount+1; fprintf(stdout,"%d\n",i); } } return 0; }
#ifndef __CTRL_CLSEDITOR_H #define __CTRL_CLSEDITOR_H #include "CtrlWindowBase.h" //#include "ModelClsEditor.h" //#include "IViewBrowser.h" namespace wh { class IViewClsEditor : public IViewWindow { public: IViewClsEditor(wxWindow* parent) { } IViewClsEditor(const std::shared_ptr<IViewWindow>& parent) :IViewClsEditor(parent->GetWnd()) {} virtual wxWindow* GetWnd()const override { return nullptr; } }; class ModelClsEditor : public IModelWindow {}; //----------------------------------------------------------------------------- class CtrlClsEditor final : public CtrlWindowBase<IViewClsEditor, ModelClsEditor> { sig::scoped_connection connViewCmd_Find; sig::scoped_connection connModel_AfterRefreshCls; public: CtrlClsEditor(const std::shared_ptr<IViewClsEditor>& view , const std::shared_ptr<ModelClsEditor>& model); void Insert(int64_t parent_cid); void Delete(int64_t cid); void Update(int64_t cid); }; //----------------------------------------------------------------------------- }//namespace wh{ #endif // __****_H
#include <cstdio> int main(){ char cha[4] = {'W', 'T', 'L'}; double odds[3][3]; double win[3]; char bet[4]; for(int i = 0; i < 3; i++){ int maxi = 0; double maxo = -1; for(int j = 0; j < 3; j++){ scanf("%lf", &odds[i][j]); if(odds[i][j] > maxo){ maxi = j; maxo = odds[i][j]; win[i] = maxo; } bet[i] = cha[maxi]; } } double profit; profit = (win[0] * win[1] * win[2] * 0.65 - 1) * 2; printf("%c %c %c ", bet[0], bet[1], bet[2]); printf("%.2f\n", profit); }
#ifndef ADDONS_DOMAINS_MATRIX_FIXTURES_HPP #define ADDONS_DOMAINS_MATRIX_FIXTURES_HPP namespace testing { namespace boolmatrix { using namespace boost::numeric::ublas; using namespace wali::domains; struct RandomMatrix1_3x3 { BoolMatrix::BackingMatrix mat; RandomMatrix1_3x3() : mat(3,3) { bool m[3][3] = { {1, 1, 0}, {1, 0, 1}, {0, 0, 1} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = m[i][j]; } } } }; struct RandomMatrix2_3x3 { BoolMatrix::BackingMatrix mat; RandomMatrix2_3x3() : mat(3,3) { bool m[3][3] = { {1, 0, 0}, {1, 1, 1}, {0, 0, 1} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = m[i][j]; } } } }; struct ExtendR1R2_3x3 { BoolMatrix::BackingMatrix mat; ExtendR1R2_3x3() : mat(3,3) { bool m[3][3] = { {1, 1, 1}, {1, 0, 1}, {0, 0, 1} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = m[i][j]; } } } }; struct ExtendR2R1_3x3 { BoolMatrix::BackingMatrix mat; ExtendR2R1_3x3() : mat(3,3) { bool m[3][3] = { {1, 1, 0}, {1, 1, 1}, {0, 0, 1} }; for (size_t i = 0; i< mat.size1(); ++i) { for (size_t j = 0; j < mat.size2(); ++j) { mat(i, j) = m[i][j]; } } } }; typedef ExtendR2R1_3x3 CombineR1Id_3x3; struct ZeroBackingMatrix_3x3 { BoolMatrix::BackingMatrix mat; ZeroBackingMatrix_3x3() : mat(zero_matrix<BoolMatrix::value_type>(3, 3)) {} }; struct IdBackingMatrix_3x3 { BoolMatrix::BackingMatrix mat; IdBackingMatrix_3x3() : mat(identity_matrix<BoolMatrix::value_type>(3, 3)) {} }; struct MatrixFixtures_3x3 { RandomMatrix1_3x3 r1; RandomMatrix2_3x3 r2; ExtendR1R2_3x3 ext_r1_r2; ExtendR2R1_3x3 ext_r2_r1; // no CombineR1Id because it is equal to ext_r2_r1 IdBackingMatrix_3x3 id; ZeroBackingMatrix_3x3 zero; }; } } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_IMG_IMG_MODULE_H #define MODULES_IMG_IMG_MODULE_H #include "modules/hardcore/opera/module.h" #include "modules/img/image.h" #ifdef EMBEDDED_ICC_SUPPORT class ImageColorManager; #endif // EMBEDDED_ICC_SUPPORT class ImgModule : public OperaModule { public: ImgModule() : img_manager(NULL), #ifdef EMBEDDED_ICC_SUPPORT img_color_manager(NULL), #endif // EMBEDDED_ICC_SUPPORT null_listener(NULL) {} void InitL(const OperaInitInfo& info); void Destroy(); ImageManager* img_manager; #ifdef EMBEDDED_ICC_SUPPORT ImageColorManager* img_color_manager; #endif // EMBEDDED_ICC_SUPPORT NullImageListener* null_listener; }; #define imgManager (g_opera->img_module.img_manager) #ifdef EMBEDDED_ICC_SUPPORT #define g_color_manager (g_opera->img_module.img_color_manager) #endif // EMBEDDED_ICC_SUPPORT #define null_image_listener (g_opera->img_module.null_listener) #define IMG_MODULE_REQUIRED #endif // !MODULES_IMG_IMG_MODULE_H
#pragma once #include "transform.h" #include "iovector.h" #include "mask.h" namespace hdd::gamma { class Data { public: Data(const RawData& rawData); Data(const RawData& rawData, const std::vector<FormatType>& columnType); Data(const Data& data, uint32_t startIndex, uint32_t endIndex); Data(const Data& data, const Mask& inputMask); uint32_t Size() const; uint32_t Inputs() const; uint32_t Outputs() const; const IOVector& operator[](uint32_t index) const; friend std::ostream& operator<<(std::ostream& os, const Data& data); private: const RawData& rawData_; Transform transform_; std::vector<IOVector> data_; Mask inputMask_; void CreateData(); void Masked(const IOVector& source, IOVector& dest); }; }
#include <iostream> #include <fstream> #include <bitset> #include <map> #include <cmath> #include <iomanip> #include <string> #include <algorithm> using namespace std; int cache_size[4]={4,16,64,256}; //kB cache size int block_size[5]={16,32,64,128,256}; //B block size string TXT[2]={"DCACHE","ICACHE"}; string ext=".txt"; struct Block{ int tag=0; bool valid=false; }; void compute(int a,int i,int j,int &hitCnt,int &missCnt){ ifstream input( TXT[a]+ext ); int total_blocks = (cache_size[i]<<10)/block_size[j]; map<int,Block> cache; string strIn; while(input>>hex>>strIn){ unsigned int memIn = stoul(strIn,nullptr,16); //int offset = memIn & (block_size[j]-1); memIn = memIn >> int( log2(block_size[j]) ); int index = memIn & (total_blocks-1); memIn = memIn >> int( log2(total_blocks) ); int tag = memIn; //cout<<"offset: "<<offset<<endl; //cout<<"index: "<<index<<endl; //cout<<"tag: "<<tag<<endl; if( cache[index].valid && cache[index].tag==tag ) hitCnt++; else{ missCnt++; cache[index].valid = true; cache[index].tag = tag; } //cout<<endl; } } int main(){ for(int a=0; a<2; ++a){ cout<< TXT[a] <<":"<<endl; for(int i=0; i<4; ++i){ cout<<" Cache_size: "<< cache_size[i] <<"K"<<endl; for(int j=0; j<5; ++j){ int hitCnt=0,missCnt=0; compute(a,i,j,hitCnt,missCnt); int total = hitCnt+missCnt; double hitRate = hitCnt*100.0 / total; cout<<"\tBlock_size: "<<block_size[j] <<endl; cout<<"\tHit rate: "<< fixed <<setprecision(2)<< hitRate <<"% ("<<hitCnt <<"), "; cout<<"Miss rate: " << fixed <<setprecision(2)<< 100-hitRate <<"% ("<<missCnt<<")"<< endl<<endl; } } } }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10878" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif string str; int num,digital; while( getline(cin,str) ){ if(str[0] == '_') continue; num = 0; digital = 1; for(int i = 9 ; i > 0 ; i-- ){ if( str[i] == '.' ) continue; if( str[i] == 'o' ) num = num + digital; digital = digital * 2; } char tmp = num; printf("%c", num ); } return 0; }
#include "..\include\gmath.hpp" using namespace gmath; vec4::vec4(const float& x, const float& y, const float& z, const float& w): data(new float[4]{ x, y, z, w}) { } vec4::vec4(const __m128& data): data(new float[4]) { _mm_store_ps(this->data, data); } vec4::vec4(const vec4& other): data(new float[4]) { data[0] = other.data[0]; data[1] = other.data[1]; data[2] = other.data[2]; data[3] = other.data[3]; } vec4::vec4(vec4&& other): data(nullptr) { data = other.data; other.data = nullptr; } vec4::~vec4() { if (data != nullptr) { delete[] data; data = nullptr; } } vec4& vec4::operator=(const vec4& other) { if (this != &other) { data[0] = other.data[0]; data[1] = other.data[1]; data[2] = other.data[2]; data[3] = other.data[3]; } return *this; } vec4& vec4::operator=(vec4&& other) { if (this != &other) { delete[] data; data = other.data; other.data = nullptr; } return *this; } float& vec4::operator[](const uint32_t& i) const { return data[i]; } vec4 vec4::operator-() const { const __m128 v = _mm_load_ps(this->data); return vec4(_mm_xor_ps(v, _mm_set1_ps(-0.0))); } float vec4::dot(const vec4& other) const { const vec4 result((*this) * other); return result[0] + result[1] + result[2] + result[3]; } float vec4::dot(const vec4& v1, const vec4& v2) { const vec4 result(v1 * v2); return result[0] + result[1] + result[2] + result[3]; } float vec4::magnitude() const { return sqrt(this->magnitude2()); } float vec4::magnitude2() const { return this->dot(*this); } vec4 vec4::multiply(const vec4& other) const { return ((*this) * other); } vec4 vec4::normalize() const { const float v = this->magnitude(); return *this / v; } std::string vec4::toString() const { return std::string("x: ") + std::to_string(data[0]) + std::string(" y: ") + std::to_string(data[1]) + std::string(" z: ") + std::to_string(data[2]) + std::string(" w: ") + std::to_string(data[3]); } vec4 vec4::multiply(const vec4& v1, const vec4& v2) { return v1 * v2; } vec4 gmath::operator*(const vec4& v1, const vec4& v2) { const __m128 a = _mm_load_ps(v1.data); const __m128 b = _mm_load_ps(v2.data); return vec4(_mm_mul_ps(a, b)); } vec4 gmath::operator*(const float& s, const vec4& v) { const __m128 a = _mm_set_ps1(s); const __m128 b = _mm_load_ps(v.data); return vec4(_mm_mul_ps(a, b)); } vec4 gmath::operator*(const vec4& v, const float& s) { const __m128 a = _mm_set_ps1(s); const __m128 b = _mm_load_ps(v.data); return vec4(_mm_mul_ps(a, b)); } vec4 gmath::operator/(const vec4& v, const float& s) { return (1.0f / s) * v; } vec4 gmath::operator+(const vec4& v1, const vec4& v2) { const __m128 a = _mm_load_ps(v1.data); const __m128 b = _mm_load_ps(v2.data); return vec4(_mm_add_ps(a, b)); } vec4 gmath::operator-(const vec4& v1, const vec4& v2) { const __m128 a = _mm_load_ps(v1.data); const __m128 b = _mm_load_ps(v2.data); return vec4(_mm_sub_ps(a, b)); }
#pragma once #include <map> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/System/Vector2.hpp> #include "Animation.hpp" class Player; class Weapon { public: virtual ~Weapon(); const std::string &GetAmmoType() const; int GetAmmo() const; int GetMaxAmmo() const; void Tick(float dt); void Draw(sf::RenderTarget *rt); virtual void Shoot(); virtual void Think(float dt) {}; virtual void OnShoot() {}; virtual void OnEquip() {}; virtual void OnUnEquip() {}; protected: Weapon(Player *owner, sf::Texture *tex, const sf::Vector2u &size, const std::string &ammotype, float firerate); void SetShootAnimation(const Animation<sf::Vector2i> &anim); void SetShootSound(sf::SoundBuffer *buffer); protected: sf::Texture *m_Texture; sf::Vector2u m_Size; sf::SoundBuffer *m_ShootSound; Player *m_Owner; std::string m_AmmoType; float m_FireRate; float m_NextFireTime; float m_CurTime; bool m_Animated; Animation<sf::Vector2i> m_ShootAnim; public: static std::map<std::string, unsigned int> AmmoTypes; };
#include "TableTimer.h" #include "IProcess.h" #include "Table.h" #include "Logger.h" #include "Configure.h" #include "HallManager.h" #include "UdpManager.h" #include "LogServerConnect.h" //====================CTimer_Handler==================================// int CTimer_Handler::ProcessOnTimerOut() { if(handler) return handler->ProcessOnTimerOut(this->timeid, this->uid); else return 0; } void CTimer_Handler::SetTimeEventObj(TableTimer * obj, int timeid, int uid) { this->handler = obj; this->timeid = timeid; this->uid = uid; } //==========================TableTimer==================================// void TableTimer::init(Table* table) { this->table = table; } void TableTimer::stopAllTimer() { stopBetCoinTimer(); stopKickTimer(); stopTableStartTimer(); } void TableTimer::startBetCoinTimer(int uid,int timeout) { m_BetTimer.SetTimeEventObj(this, BET_COIN_TIMER, uid); m_BetTimer.StartTimer(timeout); } void TableTimer::stopBetCoinTimer() { m_BetTimer.StopTimer(); } void TableTimer::startTableStartTimer(int timeout) { m_TableStartTimer.SetTimeEventObj(this, TABLE_START_TIMER); m_TableStartTimer.StartTimer(timeout); } void TableTimer::stopTableStartTimer() { m_TableStartTimer.StopTimer(); } void TableTimer::startKickTimer(int timeout) { m_TableKickTimer.SetTimeEventObj(this, TABLE_KICK_TIMER); m_TableKickTimer.StartTimer(timeout); } void TableTimer::stopKickTimer() { m_TableKickTimer.StopTimer(); } void TableTimer::startSendCardTimer(int timeout) { m_TableKickTimer.SetTimeEventObj(this, TABLE_SEND_TIMER); m_TableKickTimer.StartMinTimer(timeout); } void TableTimer::stopSendCardTimer() { m_TableKickTimer.StopTimer(); } int TableTimer::ProcessOnTimerOut(int Timerid, int uid) { switch (Timerid) { case BET_COIN_TIMER: return BetTimeOut(uid); case TABLE_START_TIMER: return TableGameStartTimeOut(); case TABLE_KICK_TIMER: return TableKickTimeOut(); case TABLE_SEND_TIMER: return SendCardTimeOut(); default: return 0; } return 0; } int TableTimer::BetTimeOut(int uid) { this->stopBetCoinTimer(); Player* player = table->getPlayer(uid); if(player == NULL) { _LOG_ERROR_("[BetTimeOut] uid=[%d] tid=[%d] Your not in This Table\n",uid, this->table->id); return 0; } if(uid != table->betUid) { _LOG_ERROR_("[BetTimeOut] uid=[%d] tid=[%d] current betuid[%d]\n",uid, this->table->id, table->betUid); return 0; } _LOG_INFO_("BetTimeOut tid=[%d] uid=[%d]\n", this->table->id, uid); //如果是第一轮用户就下注超时则记录下来,方便后续踢出用户 if(table->currRound == 1) player->timeoutCount++; Player* nextplayer = NULL; if(this->table->currRound != 5) { //表示此人已经弃牌 player->hascard = false; //设置下一个应该下注的用户 nextplayer = table->getNextBetPlayer(player,OP_THROW); } else { //设置当最后一轮默认帮用户开牌 nextplayer = table->getNextBetPlayer(player,OP_CHECK); } if(nextplayer) { table->setPlayerlimitcoin(nextplayer); } Json::Value data; data["BID"] = string(table->getGameID()); data["Time"]=(int)(time(NULL) - table->getStartTime()); data["currd"] = table->currRound; data["timeoutID"] = player->id; data["count"] = (double)player->betCoinList[0]; if(!table->isAllRobot()) _LOG_REPORT_(player->id, RECORD_TIME_OUT, "%s", data.toStyledString().c_str()); data["errcode"] = 0; _UDP_REPORT_(player->id, GMSERVER_BET_TIMEOUT,"%s",data.toStyledString().c_str()); int sendNum = 0; int i = 0; for(i = 0; i < GAME_PLAYER; ++i) { if(sendNum == table->countPlayer) break; if(table->player_array[i]) { if(table->currRound != 5) sendBetTimeOut(table->player_array[i], table, player, nextplayer); else sendOpenTimeOut(table->player_array[i], table, player, nextplayer); sendNum++; } } Player* winner = NULL; if(table->iscanGameOver(&winner)) return IProcess::GameOver(table, winner, true); //当前已经没有下一个用户下注了此轮结束 if(nextplayer == NULL) { table->setNextRound(); } else { table->startBetCoinTimer(nextplayer->id,Configure::getInstance()->betcointime); nextplayer->setBetCoinTime(time(NULL)); } return 0; } int TableTimer::sendBetTimeOut(Player* player, Table* table, Player* timeoutplayer,Player* nextplayer) { int svid = Configure::getInstance()->server_id; int tid = (svid << 16)|table->id; OutputPacket response; response.Begin(GMSERVER_BET_TIMEOUT, player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->status); response.WriteInt(tid); response.WriteShort(table->status); response.WriteShort(table->currRound); response.WriteInt(timeoutplayer->id); int64_t nextlimitcoin = -1; if(nextplayer) { nextlimitcoin = nextplayer->nextlimitcoin; response.WriteInt(nextplayer->id); response.WriteShort(nextplayer->optype); response.WriteInt64(nextlimitcoin); response.WriteInt64(table->currMaxCoin - nextplayer->betCoinList[table->currRound]); } else { response.WriteInt(0); response.WriteShort(0); response.WriteInt64(-1); response.WriteInt64(-1); } response.End(); _LOG_INFO_("<==[sendBetTimeOut] Push [0x%04x] to uid=[%d]\n", GMSERVER_BET_TIMEOUT, player->id); _LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n"); _LOG_DEBUG_("[Data Response] uid=[%d]\n",player->id); _LOG_DEBUG_("[Data Response] status=[%d]\n",player->status); _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tstatus=[%d]\n", table->status); _LOG_DEBUG_("[Data Response] currRound=[%d]\n", table->currRound); _LOG_DEBUG_("[Data Response] timeoutplayer_id=[%d]\n",timeoutplayer->id); _LOG_DEBUG_("[Data Response] nextplayer=[%d]\n", nextplayer ? nextplayer->id : 0); _LOG_DEBUG_("[Data Response] optype=[%d]\n", nextplayer ? nextplayer->optype : 0); _LOG_DEBUG_("[Data Response] nextlimitcoin=[%ld]\n", nextlimitcoin); _LOG_DEBUG_("[Data Response] differcoin=[%ld]\n",nextplayer ? table->currMaxCoin - nextplayer->betCoinList[table->currRound] : -1); if(HallManager::getInstance()->sendToHall(player->hallid, &response, false) < 0) _LOG_ERROR_("[BetCallProc] Send To Uid[%d] Error!\n", player->id); return 0; } int TableTimer::sendOpenTimeOut(Player* player, Table* table, Player* timeoutplayer,Player* nextplayer) { int svid = Configure::getInstance()->server_id; int tid = (svid << 16)|table->id; OutputPacket response; response.Begin(CLIENT_MSG_LOOK_CARD, player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->status); response.WriteInt(tid); response.WriteShort(table->status); response.WriteShort(table->currRound); response.WriteInt(timeoutplayer->id); int64_t nextlimitcoin = -1; if(nextplayer) { nextlimitcoin = nextplayer->nextlimitcoin; response.WriteInt(nextplayer->id); response.WriteShort(nextplayer->optype); response.WriteInt64(nextlimitcoin); response.WriteInt64(table->currMaxCoin - nextplayer->betCoinList[table->currRound]); } else { response.WriteInt(0); response.WriteShort(0); response.WriteInt64(-1); response.WriteInt64(-1); } response.End(); _LOG_INFO_("<==[sendOpenTimeOut] Push [0x%04x] to uid=[%d]\n", CLIENT_MSG_LOOK_CARD, player->id); _LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n"); _LOG_DEBUG_("[Data Response] uid=[%d]\n",player->id); _LOG_DEBUG_("[Data Response] status=[%d]\n",player->status); _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tstatus=[%d]\n", table->status); _LOG_DEBUG_("[Data Response] currRound=[%d]\n", table->currRound); _LOG_DEBUG_("[Data Response] timeoutplayer_id=[%d]\n",timeoutplayer->id); _LOG_DEBUG_("[Data Response] nextplayer=[%d]\n", nextplayer ? nextplayer->id : 0); _LOG_DEBUG_("[Data Response] optype=[%d]\n", nextplayer ? nextplayer->optype : 0); _LOG_DEBUG_("[Data Response] nextlimitcoin=[%ld]\n", nextlimitcoin); _LOG_DEBUG_("[Data Response] differcoin=[%ld]\n",nextplayer ? table->currMaxCoin - nextplayer->betCoinList[table->currRound] : -1); if(HallManager::getInstance()->sendToHall(player->hallid, &response, false) < 0) _LOG_ERROR_("[BetCallProc] Send To Uid[%d] Error!\n", player->id); return 0; } int TableTimer::TableGameStartTimeOut() { this->stopTableStartTimer(); _LOG_INFO_("TableGameStartTimeOut tid=[%d]\n", this->table->id); if(table->isActive()) { _LOG_WARN_("this table[%d] is Active\n",table->id); return 0; } int i; if (table->isCanGameStart()) { for(i = 0; i < GAME_PLAYER; ++i) { Player* getplayer = table->player_array[i]; //把没有准备的用户踢出 if(getplayer && (getplayer->isComming() || getplayer->isGameOver())) { IProcess::serverPushLeaveInfo(table, getplayer); table->playerLeave(getplayer); } } if(table->isAllReady()&&table->countPlayer > 1) return IProcess::GameStart(table); else _LOG_ERROR_("table[%d] countPlayer[%d] not all ready\n", table->id, table->countPlayer); } else _LOG_WARN_("table[%d] is Can't GameStart PlayerCount[%d]\n", table->id, table->countPlayer); return 0; } int TableTimer::TableKickTimeOut() { this->stopTableStartTimer(); _LOG_INFO_("TableKickTimeOut tid=[%d]\n", this->table->id); table->unlockTable(); if(table->isActive()) { _LOG_WARN_("this table[%d] is Active\n",table->id); return 0; } if(table->countPlayer == 1) { _LOG_WARN_("this table[%d] is One Player\n",table->id); return 0; } int i; for(i = 0; i < GAME_PLAYER; ++i) { Player* getplayer = table->player_array[i]; //把没有准备的用户踢出 if(getplayer && !getplayer->isReady()) { IProcess::serverPushLeaveInfo(table, getplayer, 2); table->playerLeave(getplayer); } } if(table->isAllReady()&&table->countPlayer > 1) return IProcess::GameStart(table); else _LOG_ERROR_("table[%d] countPlayer[%d] not all ready\n", table->id, table->countPlayer); return 0; } int TableTimer::SendCardTimeOut() { this->stopSendCardTimer(); _LOG_INFO_("SendCardTimeOut tid=[%d]\n", this->table->id); table->setNextRound(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** CREATED DG-271198 ** DESCRIPTION Win message hooks */ #include "core/pch.h" #include "platforms/windows/windows_ui/msghook.h" #include "adjunct/quick/managers/KioskManager.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "platforms/windows/win_handy.h" #include "platforms/windows/CustomWindowMessages.h" #ifndef NS4P_COMPONENT_PLUGINS #include "platforms/windows/pi/WindowsOpMessageLoop.h" #endif // !NS4P_COMPONENT_PLUGINS #include "platforms/windows/pi/WindowsOpPluginWindow.h" #include "platforms/windows/pi/WindowsOpView.h" #include "platforms/windows/pi/WindowsOpWindow.h" #include "platforms/windows/windows_ui/menubar.h" #include <xmmintrin.h> BOOL g_is_showing_menu = FALSE; extern BOOL IsPluginWnd(HWND hWnd, BOOL fTestParents); extern BOOL HandleMouseEvents(HWND hWnd, UINT message, const OpPoint& point); static HWND _hWndBelowCursor = NULL; static LRESULT CALLBACK _HookProc_Mouse ( int nCode, WPARAM wParam, LPARAM lParam ); static LRESULT CALLBACK _HookProc_WndProc ( int nCode, WPARAM wParam, LPARAM lParam ); static LRESULT CALLBACK _HookProc_CBT ( int nCode, WPARAM wParam, LPARAM lParam ); static LRESULT CALLBACK _HookProc_GetMessage ( int nCode, WPARAM wParam, LPARAM lParam ); extern UINT idMsgLostCursor; LRESULT CALLBACK _HookProc_LowLevelKeyboard ( int nCode, WPARAM wParam, LPARAM lParam ); static HHOOK _hHookLLKeyboard = 0; static HHOOK _hHookMouse = 0; static HHOOK _hHookMessageProc = 0; static HHOOK _hHookWndProc = 0; static HHOOK _hHookCBT = 0; static HHOOK _hHookGetMessage = 0; struct HOOKMAP { HHOOK *pHook; int kindOfHook; HOOKPROC pHookProc; } static _hookMap[] = { #ifdef _MSGHOOK_MOUSE { &_hHookMouse, WH_MOUSE, _HookProc_Mouse }, #endif { &_hHookLLKeyboard, WH_KEYBOARD_LL, _HookProc_LowLevelKeyboard}, #ifdef _MSGHOOK_CALLWNDPROC { &_hHookWndProc, WH_CALLWNDPROC, _HookProc_WndProc }, #endif #ifdef _MSGHOOK_CBT { &_hHookCBT, WH_CBT, _HookProc_CBT }, #endif #ifdef _MSGHOOK_GETMESSAGE { &_hHookGetMessage, WH_GETMESSAGE, _HookProc_GetMessage }, #endif }; #ifndef NS4P_COMPONENT_PLUGINS DelayedFlashMessageHandler* g_delayed_flash_message_handler = NULL; #endif // !NS4P_COMPONENT_PLUGINS #if _MSC_VER < VS2012 extern "C" BOOL __sse2_available; #endif // ___________________________________________________________________________ // InstallMouseHook // Attach the mouse hook to the calling thread (WIN32) or the current task- // handle on WIN16 // ___________________________________________________________________________ // BOOL InstallMSWinMsgHooks() { #ifndef NS4P_COMPONENT_PLUGINS if (!(g_delayed_flash_message_handler = OP_NEW(DelayedFlashMessageHandler, ()))) return FALSE; #endif // !NS4P_COMPONENT_PLUGINS for (int i=0; i<ARRAY_SIZE(_hookMap); i++) { HHOOK &hook = *_hookMap[i].pHook; // Dont hook twice if( !hook) { // // Install hook // if(_hookMap[i].kindOfHook == WH_KEYBOARD_LL && KioskManager::GetInstance()->GetEnabled()) { hook = SetWindowsHookEx( _hookMap[i].kindOfHook, _hookMap[i].pHookProc, hInst, 0); } else { hook = SetWindowsHookEx( _hookMap[i].kindOfHook, _hookMap[i].pHookProc, 0, GetCurrentThreadId()); } } } return TRUE; } // ___________________________________________________________________________ // RemoveMSWinMsgHooks() // ___________________________________________________________________________ // void RemoveMSWinMsgHooks() { for (int i=0; i<ARRAY_SIZE(_hookMap); i++) { HHOOK &hook = *_hookMap[i].pHook; if( hook) UnhookWindowsHookEx(hook); hook = NULL; } } //**************************************************************************************** LRESULT CALLBACK _HookProc_LowLevelKeyboard( int nCode, WPARAM wParam, LPARAM lParam ) { BOOL fEatKeystroke = FALSE; static bool s_l_ctrl_pressed = FALSE; static bool s_r_ctrl_pressed = FALSE; if (nCode == HC_ACTION) { switch (wParam) { case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: { PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) lParam; // julienp: Without the additionnal checks s_l_ctrl_pressed and s_r_ctrl_pressed, // CTRL+ESC still slip through if keys are pressed repeatedly and quickly, // _when Opera has focus_ (see bug 182226). // It seems like when Opera has focus, something like this happens: // +-------------------------- time -----------------------------> // | Ctrl pressed -> Hook for Ctrl -> Ctrl gets /registered/ for GetKeyState (too late) // Events| delta -> Esc Pressed -> hook for Esc (doesn't know about Ctrl) // V // If Opera is not the window with focus, it looks like that order // is changed (Ctrl gets registered before switching to the application // , maybe) // // It might be that the check of GetKeyState isn't needed anymore but keeping // it to be on the safe side. if (p->vkCode == VK_LCONTROL && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) s_l_ctrl_pressed = TRUE; if (p->vkCode == VK_LCONTROL && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) s_l_ctrl_pressed = FALSE; if (p->vkCode == VK_RCONTROL && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) s_r_ctrl_pressed = TRUE; if (p->vkCode == VK_RCONTROL && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) s_r_ctrl_pressed = FALSE; BOOL ctrl_pressed = ((GetKeyState(VK_CONTROL) & 0x8000) != 0); fEatKeystroke = ( ((p->vkCode == VK_SPACE) && ((p->flags & LLKHF_ALTDOWN) != 0)) || // ALT+SPACE ((p->vkCode == VK_TAB) && ((p->flags & LLKHF_ALTDOWN) != 0)) || // ALT+TAB ((p->vkCode == VK_ESCAPE) && ((p->flags & LLKHF_ALTDOWN) != 0)) || // ALT+ESC ((p->vkCode == VK_ESCAPE) && (ctrl_pressed || s_l_ctrl_pressed || s_r_ctrl_pressed)) || // CTRL+ESC ((p->vkCode == VK_LWIN) || (p->vkCode == VK_RWIN)) || // WINDOWSKEYS ((p->vkCode == VK_SUBTRACT) && ((p->flags & LLKHF_ALTDOWN) != 0)) || // ALT+'-' ((p->vkCode == VK_OEM_MINUS ) && ((p->flags & LLKHF_ALTDOWN) != 0)) || // ALT+'-' (KioskManager::GetInstance()->GetKioskWindows() && (p->vkCode == VK_F4) && (ctrl_pressed || s_l_ctrl_pressed || s_r_ctrl_pressed)) || (p->vkCode == VK_APPS) || // APPLICATIONS KEY (p->vkCode == VK_SNAPSHOT) || // PRINTSCREEN ((p->vkCode == VK_LMENU) && ((p->flags & LLKHF_ALTDOWN) != 0)) // ALT key altogether ); } break; default: ; } } return(fEatKeystroke ? 1 : CallNextHookEx(_hHookLLKeyboard, nCode, wParam, lParam)); } // ___________________________________________________________________________ // _HookProc_Mouse // ___________________________________________________________________________ // static LRESULT CALLBACK _HookProc_Mouse ( int nCode, // hook code WPARAM wParam, // message identifier LPARAM lParam // Pointer to a MOUSEHOOKSTRUCT structure. ) { MOUSEHOOKSTRUCT * pInfo = (MOUSEHOOKSTRUCT*)lParam; HWND hWnd = pInfo->hwnd; // If nCode is less than zero, the hook procedure must pass the message to // the CallNextHookEx function without further processing and should return // the value returned by CallNextHookEx. if (nCode < 0) goto LABEL_Done; if (nCode == HC_ACTION && (wParam == WM_RBUTTONDOWN || wParam == WM_RBUTTONDBLCLK || wParam == WM_RBUTTONUP)) { // don't allow this in kiosk mode if (KioskManager::GetInstance()->GetNoContextMenu()) { return TRUE; } } if (nCode == HC_ACTION && !g_is_showing_menu && ((wParam >= WM_NCMOUSEMOVE && wParam <= WM_NCMBUTTONDBLCLK) || (wParam >= WM_MOUSEMOVE && wParam <= WM_MBUTTONDBLCLK)) && !WindowsOpWindow::GetWindowFromHWND(hWnd) && HandleMouseEvents(hWnd, wParam, OpPoint(pInfo->pt.x, pInfo->pt.y))) { return TRUE; } switch( wParam) { case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: { HWND hWndPrev = _hWndBelowCursor; if( nCode != HC_NOREMOVE) { // Tooltip windows should not recieve any mouse events and // should not "disturb" hovered window or capture in any way. WindowsOpWindow *window = WindowsOpWindow::GetWindowFromHWND(hWnd); if (window && window->GetStyle() == OpWindow::STYLE_TOOLTIP) break; if( hWndPrev != hWnd) { if( ISWINDOW(hWndPrev)) SendMessage( hWndPrev, idMsgLostCursor, 0, 0); _hWndBelowCursor = hWnd; } } break; } } LABEL_Done: return CallNextHookEx( _hHookMouse, nCode, wParam, lParam); } // ___________________________________________________________________________ // CheckForValidOperaWindowBelowCursor // // Called from ucTimer. // Used reset _hWndBelowCursor when the cursor moves outside the Opera workspace. // ___________________________________________________________________________ // void CheckForValidOperaWindowBelowCursor() { if (!_hWndBelowCursor) return; if (_hWndBelowCursor && !ISWINDOW(_hWndBelowCursor)) { _hWndBelowCursor = NULL; return; } if (IsOperaWindow(GetCapture())) { return; } BOOL fOperaHasCursor = FALSE; POINT pt; if (GetCursorPos( &pt)) { HWND hWndBelowCursor = WindowFromPoint( pt); if (hWndBelowCursor) { fOperaHasCursor =IsOperaWindow( hWndBelowCursor); // if (!fOperaHasCursor) DEBUG_Beep(); } } if (!fOperaHasCursor) { // Notify window losing cursor PostMessage( _hWndBelowCursor, idMsgLostCursor, 0, 0); _hWndBelowCursor = NULL; }; } extern OUIMenuManager* g_windows_menu_manager; // ___________________________________________________________________________ // _HookProc_WndProc // MH_CALLWNDPROC // // Monitors messages BEFORE the system sends them to the destination window // procedure. // ___________________________________________________________________________ // #ifdef _MSGHOOK_CALLWNDPROC static LRESULT CALLBACK _HookProc_WndProc( int nCode, WPARAM key, LPARAM lParam ) { CWPSTRUCT *pInfo = (CWPSTRUCT*)lParam; if (nCode == HC_ACTION && pInfo) { static int g_DEP_enabled = 0; if (!g_DEP_enabled) { g_DEP_enabled = -1; if (IsProcessorFeaturePresent(PF_NX_ENABLED)) g_DEP_enabled = 1; } if (g_DEP_enabled > 0) { UINT wndproc = GetWindowLongW(pInfo->hwnd, GWLP_WNDPROC); if ((wndproc >> 16) == 0xFFFF) // not a real address, but a WindowProc unicode conversion handle wndproc = GetWindowLongA(pInfo->hwnd, GWLP_WNDPROC); if (wndproc) { static UINT g_known_WindowProcs[64]; for (UINT i=0; i<ARRAY_SIZE(g_known_WindowProcs) && g_known_WindowProcs[i] != wndproc; i++) { if (!g_known_WindowProcs[i]) { UINT DLL_location = 0; if (!IsBadReadPtr((LPVOID)wndproc, 0xA5) && *(UINT *)(wndproc + 0xA1) == 0xD6FF5350 && *(WORD *)(wndproc + 0x10) == 0x358B) { // special hack for SKCHUI.DLL version 1.0.1038.0 DWORD *thread_list = **(DWORD ***)(wndproc + 0x12); DWORD thread_id = GetCurrentThreadId(); while (thread_list) { if (thread_list[1] == thread_id) { DLL_location = wndproc; wndproc = thread_list[0] + 8; break; } else thread_list = (DWORD *)thread_list[2]; } } g_known_WindowProcs[i] = wndproc; MEMORY_BASIC_INFORMATION mem_inf; VirtualQuery((LPVOID)wndproc, &mem_inf, sizeof(mem_inf)); if (!(mem_inf.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY ))) { DWORD old_protect; if (VirtualProtect((LPVOID)wndproc, 32, PAGE_EXECUTE_READWRITE, &old_protect) && !DLL_location) { if (*(unsigned char*)wndproc == 0xB9) wndproc += 5; else if (*(UINT *)wndproc == 0x042444C7) wndproc += 8; if (*(unsigned char*)wndproc == 0xE9) DLL_location = *(UINT *)(wndproc+1) + wndproc+5; } PostMessage(g_main_hwnd, WM_BAD_DLL, 0, DLL_location); } break; } } } } switch (pInfo->message) { case WM_INITMENUPOPUP: if(g_windows_menu_manager) { g_windows_menu_manager->OnInitPopupMenu(pInfo->hwnd, (HMENU)pInfo->wParam, LOWORD(pInfo->lParam)); } break; case WM_ENTERMENULOOP: { g_is_showing_menu = TRUE; break; } case WM_MENUSELECT: case WM_EXITMENULOOP: { g_input_manager->ResetInput(); ReleaseCapture(); g_is_showing_menu = FALSE; break; } case WM_ACTIVATE: { if (g_windows_menu_manager) g_windows_menu_manager->CancelAltKey(); break; } case WM_KILLFOCUS: { // If the focus goes to a plugin, set the input context to be // the view closest to the plugin. if (pInfo->wParam && IsPluginWnd(reinterpret_cast<HWND>(pInfo->wParam), TRUE)) { HWND hwnd = reinterpret_cast<HWND>(pInfo->wParam); WindowsOpPluginWindow* pw = WindowsOpPluginWindow::GetPluginWindowFromHWND(hwnd); WindowsOpView* view = pw ? static_cast<WindowsOpView*>(pw->GetParentView()) : NULL; while (view) { if (view->GetParentInputContext() && view->GetParentInputContext()->GetParentInputContext()) { // This one is really dirty, only let plugin get keyboard input // and focus when clicking on it. static short primary_button = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; if ((GetAsyncKeyState(primary_button) & 0x8000)) PostThreadMessage(GetCurrentThreadId(), WM_DELAYED_FOCUS_CHANGE, reinterpret_cast<WPARAM>(view->GetParentInputContext()->GetParentInputContext()), NULL); else { if (view->GetParentView() && view->GetNativeWindow()) SetFocus(view->GetNativeWindow()->m_hwnd); } break; } view = static_cast<WindowsOpView*>(view->GetParentView()); } } break; } } } return CallNextHookEx( _hHookWndProc, nCode, key, lParam); } #endif // _MSGHOOK_CALLWNDPROC // _HookProc_GetMessage // MH_GETMESSAGE // ___________________________________________________________________________ #ifdef _MSGHOOK_GETMESSAGE #ifndef NS4P_COMPONENT_PLUGINS DelayedFlashMessageHandler::DelayedFlashMessageHandler() { g_main_message_handler->SetCallBack(this, DELAYED_FLASH_MESSAGE, (MH_PARAM_1)this); m_last_time = 0; } DelayedFlashMessageHandler::~DelayedFlashMessageHandler() { g_main_message_handler->UnsetCallBacks(this); MSG *wmsg; while ((wmsg = m_messages.Get(0))) { HandleCallback(MSG_NO_MESSAGE, 0, (MH_PARAM_2)wmsg); } } BOOL DelayedFlashMessageHandler::PostFlashMessage(MSG *msg) { UINT32 last_time = m_last_time; m_last_time = timeGetTime(); if (m_last_time - last_time < 5 || m_messages.GetCount() > 0 || g_in_synchronous_loop) { MSG *flash_msg = OP_NEW(MSG, (*msg)); if (flash_msg) { m_messages.Add(flash_msg); g_main_message_handler->PostMessage(DELAYED_FLASH_MESSAGE, (MH_PARAM_1)this, (MH_PARAM_2)flash_msg, 1); return TRUE; } } return FALSE; } void DelayedFlashMessageHandler::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if (!g_in_synchronous_loop) { DispatchMessage((MSG *)par2); m_messages.Delete((MSG *)par2); } else { g_main_message_handler->PostMessage(DELAYED_FLASH_MESSAGE, par1, par2, 1); } } #endif // !NS4P_COMPONENT_PLUGINS LRESULT CALLBACK _HookProc_GetMessage(int code, WPARAM wParam, LPARAM lParam) { #ifndef NS4P_COMPONENT_PLUGINS MSG* msg = (MSG*) lParam; if (code == HC_ACTION && msg && wParam == PM_REMOVE && g_windows_message_loop) { // message 0x401, wParam==1, is posted by Flash every time its "do the next thing" timer // runs out. Once dispatched to the Flash plugin window procedure, it will e.g. paint the // next frame. With several heavy Flash animations running, this can slow things down // to a crawl, so we delay that message if it comes more than once per millisecond if (msg->message == 0x401 && msg->wParam == 1 && !g_is_showing_menu) // added to fix bug 192167 (johan) { if (g_windows_message_loop->GetIsExiting() // Just drop completely when exiting. Possibly fixes DSK-372317. || g_delayed_flash_message_handler->PostFlashMessage(msg)) msg->wParam = 0xDEADBEEF; } g_windows_message_loop->PostMessageIfNeeded(); } #endif // !NS4P_COMPONENT_PLUGINS LRESULT res = CallNextHookEx(_hHookGetMessage, code, wParam, lParam); // Workaround for crashes caused by the buggy keyboard hooks in // AllChars v3.6.2 and MemoClip v1.35, buggy plugins, printer drivers etc. // Their Delphi library functions mess up the FPU control word, // sooner or later causing a crash in the Ecmascript engine. // The master bug for these is #109433. // This ASM code to reset the CW is a highly efficient, // but compiler-dependant replacement for // _control87(_CW_DEFAULT, ~0); #ifndef _WIN64 // _asm is only supported on Win32 _asm { push 27fh fldcw [esp] pop edx } if (__sse2_available) _mm_setcsr(0x1F80); #endif // !_WIN64 return res; } #endif // _MSGHOOK_GETMESSAGE // ___________________________________________________________________________ // ��������������������������������������������������������������������������? // _HookProc_CVT // MH_CBT // // The system calls this function before activating, creating, destroying, // minimizing, maximizing, moving, or sizing a window; before completing a // system command; before removing a mouse or keyboard event from the system // message queue; before setting the keyboard focus; or before synchronizing // with the system message queue. A computer-based training (CBT) application // uses this hook procedure to receive useful notifications from the system. // ___________________________________________________________________________ // #ifdef _MSGHOOK_CBT static LRESULT CALLBACK _HookProc_CBT( int nCode, WPARAM wParam, LPARAM lParam ) { if (nCode < 0) goto LABEL_Done; switch (nCode) { case HCBT_ACTIVATE: // The system is about to activate a window. break; case HCBT_CLICKSKIPPED: // The system has removed a mouse message from the system message queue. // Upon receiving this hook code, a CBT application must install a WH_JOURNALPLAYBACK // hook procedure in response to the mouse message. break; case HCBT_CREATEWND: // A window is about to be created. The system calls the hook procedure before sending // the WM_CREATE orWM_NCCREATE message to the window. If the hook procedure returns a // nonzero value, the system destroys the window; theCreateWindow function returns NULL, // but theWM_DESTROY message is not sent to the window. If the hook procedure returns // zero, the window is created normally. At the time of the HCBT_CREATEWND notification, // the window has been created, but its final size and position may not have been // determined and its parent window may not have been established. It is possible to // send messages to the newly created window, although it has not yet received WM_NCCREATE // or WM_CREATE messages. It is also possible to change the position in the Z order of // the newly created window by modifying the hwndInsertAfter member of the CBT_CREATEWND // structure. // Disable window shadow for OpenGL backend on XP if (GetWinType() <= WINXP && g_vegaGlobals.rasterBackend == LibvegaModule::BACKEND_HW3D && g_vegaGlobals.vega3dDevice->getDeviceType() == PrefsCollectionCore::OpenGL) { uni_char className[32]; if (GetClassName((HWND)wParam, className, 32) && uni_strcmp(className, UNI_L("SysShadow")) == 0) return 1; } break; case HCBT_DESTROYWND: // A window is about to be destroyed. break; case HCBT_KEYSKIPPED: // The system has removed a keyboard message from the system message queue. Upon // receiving this hook code, a CBT application must install a WH_JOURNALPLAYBACK_hook // hook procedure in response to the keyboard message. break; case HCBT_MINMAX: // A window is about to be minimized or maximized. break; case HCBT_MOVESIZE: // A window is about to be moved or sized. break; case HCBT_QS: // The system has retrieved a WM_QUEUESYNC message from the system message queue. break; case HCBT_SETFOCUS: // A window is about to receive the keyboard focus. break; case HCBT_SYSCOMMAND: // A system command is about to be carried out. This allows a CBT application to // prevent task switching by means of hot keys. break; } LABEL_Done: return CallNextHookEx( _hHookCBT, nCode, wParam, lParam); } #endif // _MSGHOOK_CBT
#include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--) { int g; cin>>g; while(g--) { int i,n,q,k,h_count=0,t_count=0; cin>>i>>n>>q; if (n%2 == 0) { cout<<n/2<<endl; continue; } else { if (i==1) { h_count = (n-1)/2; t_count = n - h_count; } else { t_count = (n-1)/2; h_count = n - t_count; } } if (q==1) cout<<h_count<<endl; if (q==2) cout<<t_count<<endl; } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2007-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef POSIX_MUTEX_H #define POSIX_MUTEX_H __FILE__ # ifdef POSIX_OK_THREAD #ifdef PI_MUTEX # include "modules/pi/system/OpMutex.h" #endif // PI_MUTEX #include <pthread.h> /** Implement a mutex. * * A normal mutex can be locked only once; attempts to lock it while locked, * even from the same thread, shall block. By default we make a recursive * mutex: the thread that holds it may acquire it several times (recursively). * Calling Request() counts as acquiring when it returns true. The thread must * release the mutex as many times as it acquires it. */ class PosixMutex #ifdef PI_MUTEX : public OpMutex #endif { PosixMutex(const PosixMutex&); // suppress copy-construction protected: // so PosixCondition's methods can access it: #ifdef DEBUG_ENABLE_OPASSERT pthread_t m_owner; int m_depth; #endif pthread_mutex_t m_mutex; public: enum MutexType { MUTEX_NORMAL, MUTEX_RECURSIVE }; PosixMutex(MutexType type=MUTEX_RECURSIVE); virtual ~PosixMutex(); void Acquire(); //< Acquire mutex. Block until the mutex can be acquired. void Release(); //< Release mutex. /** Try to acquire mutex; does not block. * @return True on success; else, we didn't acquire the mutex. */ bool Request(); #ifdef DEBUG_ENABLE_OPASSERT /** Assert just before a Release() that you're sure leaves this unlocked. */ bool SinglyLocked(); /** Assert when you think you're not holding this lock. */ bool NotMyLock(); #endif public: #ifndef PI_MUTEX /** * An instance of this class can be used to automatically acquire * and release a PosixMutex. The constructor acquires the mutex * (PosixMutex::Acquire()) and the destructor releases the mutex * (PosixMutex::Release()). * * Thus you don't need to add code for releasing the mutex for * each return statement. Example: * @code * int some_function(PosixMutex& mutex, int some_argument) * { * PosixMutex::AutoLock lock(mutex); * if (some_argument > 0) return 1; * else if (some_argument == 0) return 0; * else return -1; * } * @endcode * * @note If you use an instance of this class in a method on the core-thread * that may LEAVE(), be sure to ANCHOR() the AutoLock instance. */ class AutoLock { PosixMutex& m_mutex; public: AutoLock(PosixMutex& mutex) : m_mutex(mutex) { m_mutex.Acquire(); } ~AutoLock() { m_mutex.Release(); } }; #endif // !PI_MUTEX #ifdef POSIX_ASYNC_CANCELLATION /** * When you use a PosixMutex on a cancelable thread you should push this * cleanup handler using pthread_cleanup_push() to the thread's stack of * thread-cancellation clean-up handlers. Thus the PosixMutex can be * released if the thread is cancelled. * * Example: * @code * PosixMutex* mutex = ...; * mutex->Acquire(); * pthread_cleanup_push(PosixMutex::CleanupRelease, mutex); * ... * // do something, if this thread is cancelled, the cleanup handler * // will be executed and release the mutex. * ... * pthread_cleanup_pop(0); // don't execute the handler * mutex->Release(); * @endcode * * @param mutex is the PosixMutex instance to release. * @see PosixThread::Cancel() */ static void CleanupRelease(void* mutex) { if (mutex) static_cast<PosixMutex*>(mutex)->Release(); } #endif // POSIX_ASYNC_CANCELLATION }; # endif // POSIX_OK_THREAD #endif // POSIX_MUTEX_H
#ifndef GALAXY_H #define GALAXY_H #include <QVector> #include "quadrant.h" class Galaxy { private: QVector<QVector<Quadrant*>> matrix; int height; int width; int quadrantSize; public: Galaxy(); int getHeight() const; int getWidth() const; int getQuadrantSize() const; void setQuadrant(Quadrant* quadrant, int x, int y); Quadrant* getQuadrant(int x, int y) const; }; #endif // GALAXY_H
/* * @lc app=leetcode.cn id=174 lang=cpp * * [174] 地下城游戏 */ // @lc code=start #include<iostream> #include<algorithm> #include<vector> using namespace std; class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int n = dungeon.size(); int m = dungeon[0].size(); vector<vector<int> > dp(n+1, vector<int>(m+1, INT_MAX)); dp[n][m-1] = dp[n-1][m] = 1; for(int i=n-1;i>=0;i--) { for(int j=m-1;j>=0;j--){ int minn = min(dp[i+1][j], dp[i][j+1]); dp[i][j] = max(minn - dungeon[i][j], 1); } } return dp[0][0]; } }; // @lc code=end
// // Path.cpp // yearLong // // Created by Surya on 01/04/13. // // #include "Path.h" Path::Path(){ } Path::Path(int x, int y, int x1 ,int y1){ radius = 5; start = ofVec2f(x,y); end = ofVec2f(x1,y1); //end.he } void Path::display(){ ofSetColor(255); ofLine(start.x, start.y, end.x, end.y); }
#include <bits/stdc++.h> #define isNum(x) ('0'<=x&&x<='9') using namespace std; const int maxn = 200010; int read(); int n, ans, a[maxn], val[maxn], pos[maxn]; bool dis[maxn]; int main() { memset(val, 0, sizeof(val)); n = read(); for (int i = 1; i <= n; i++) a[i] = read(); ans = n; int i, j, k; for (int i = 1; i <= n; i++) if (!dis[i]) { k = 1, dis[i] = 1, j = a[i]; while (!dis[j]) k++, dis[j] = 1, j = a[j]; ans = max(ans, k); } printf("%d\n", &ans); return 0; } char get; int ret; int read() { get = getchar(), ret = 0; while (!isNum(get)) get = getchar(); while (isNum(get)) { ret = ret * 10 + get - '0'; get = getchar(); } return ret; }
/* Name: ¾ØÕóÖеÄ·¾¶ Copyright: Author: Hill Bamboo Date: 2019/9/7 18:54:16 Description: */ #include <bits/stdc++.h> using namespace std; const int maxc = 1e4 + 10; const int maxr = 1e4 + 10; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; bool vis[maxr][maxc]; char* t; int r, c; void print_vis() { for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { cout << vis[i][j] << " "; } cout << endl; } } bool inside(int x, int y) { return 0 < x && x <= r && 0 < y && y <= c; } class Solution { public: bool hasPath(char* mat, int rows, int cols, char* str) { if (rows < 1 || cols < 1 || str == nullptr || mat == nullptr) return false; t = str; r = rows; c = cols; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { memset(vis, 0, sizeof(vis)); if (mat[i * r + j] == t[0] && walk(mat, i, j, 0)) { print_vis(); return true; } } } print_vis(); return false; } bool walk(char* mat, int sx, int sy, int ss) { vis[sx][sy] = 1; if (t[ss + 1] == '\0') return true; for (int i = 0; i < 4; ++i) { int nx = sx + dx[i]; int ny = sy + dy[i]; if (inside(nx, ny) && !vis[nx][ny] && mat[nx * r + ny] == t[ss]) { if (walk(mat, nx, ny, ss + 1)) return true; } } return false; } }; int main() { char* mat = "ABCESFCSADEE"; int rows = 3; int cols = 4; char* t = "ABCCE"; cout << Solution().hasPath(mat, rows, cols, t) << endl; return 0; }
#include <iostream> using namespace std; int main() { std::ios::sync_with_stdio(false); int T,E,N,ans; cin>>T; while(T>0) { cin>>E>>N; ans=(E+N)/3; if(E<ans) ans=E; else if(N<ans) ans=N; cout<<ans<<endl; T--; } return 0; }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 1000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; LL table[310][MAXN+10]; int main(int argc, char const *argv[]) { memset(table, 0, sizeof(table)); table[0][0] = 1; for(int i = 0 ; i < 305 ; i++ ) for(int j = 0 ; i+j < 305 ; j++ ) for(int k = 1 ; k < MAXN+5 ; k++ ) table[i+j][k] += table[j][k-1]; string str; int num[5]; while( getline(cin, str) ){ stringstream ss(str); int k = 0; while( ss >> num[k++] ); switch(k){ case 2: cout << table[num[0]][MAXN] << endl; break; case 3: cout << table[num[0]][num[1]] << endl; break; case 4: if( num[1] == 0 ) cout << table[num[0]][num[2]] << endl; else cout << table[num[0]][num[2]]-table[num[0]][num[1]-1] << endl; break; } } return 0; }
// Created on: 1991-02-26 // Created by: Isabelle GRIGNON // Copyright (c) 1991-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 _Extrema_ECC_HeaderFile #define _Extrema_ECC_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <math_Vector.hxx> #include <TColStd_SequenceOfReal.hxx> #include <TColgp_HArray1OfPnt.hxx> class Adaptor3d_Curve; class Extrema_CurveTool; class Extrema_POnCurv; class gp_Pnt; class gp_Vec; class Extrema_ECC { public: DEFINE_STANDARD_ALLOC //! Calculates all the distances as above //! between Uinf and Usup for C1 and between Vinf and Vsup //! for C2. Standard_EXPORT Extrema_ECC(); //! It calculates all the distances. //! The function F(u,v)=distance(C1(u),C2(v)) has an //! extremum when gradient(f)=0. The algorithm uses //! Evtushenko's global optimization solver. Standard_EXPORT Extrema_ECC(const Adaptor3d_Curve& C1, const Adaptor3d_Curve& C2); //! Calculates all the distances as above //! between Uinf and Usup for C1 and between Vinf and Vsup //! for C2. Standard_EXPORT Extrema_ECC(const Adaptor3d_Curve& C1, const Adaptor3d_Curve& C2, const Standard_Real Uinf, const Standard_Real Usup, const Standard_Real Vinf, const Standard_Real Vsup); //! Set params in case of empty constructor is usage. Standard_EXPORT void SetParams (const Adaptor3d_Curve& C1, const Adaptor3d_Curve& C2, const Standard_Real Uinf, const Standard_Real Usup, const Standard_Real Vinf, const Standard_Real Vsup); Standard_EXPORT void SetTolerance (const Standard_Real Tol); //! Set flag for single extrema computation. Works on parametric solver only. Standard_EXPORT void SetSingleSolutionFlag (const Standard_Boolean theSingleSolutionFlag); //! Get flag for single extrema computation. Works on parametric solver only. Standard_EXPORT Standard_Boolean GetSingleSolutionFlag () const; //! Performs calculations. Standard_EXPORT void Perform(); //! Returns True if the distances are found. Standard_EXPORT Standard_Boolean IsDone() const; //! Returns state of myParallel flag. Standard_EXPORT Standard_Boolean IsParallel() const; //! Returns the number of extremum distances. Standard_EXPORT Standard_Integer NbExt() const; //! Returns the value of the Nth square extremum distance. Standard_EXPORT Standard_Real SquareDistance (const Standard_Integer N = 1) const; //! Returns the points of the Nth extremum distance. //! P1 is on the first curve, P2 on the second one. Standard_EXPORT void Points (const Standard_Integer N, Extrema_POnCurv& P1, Extrema_POnCurv& P2) const; protected: private: Standard_Boolean myIsFindSingleSolution; // Default value is false. Standard_Boolean myParallel; Standard_Real myCurveMinTol; math_Vector myLowBorder; math_Vector myUppBorder; TColStd_SequenceOfReal myPoints1; TColStd_SequenceOfReal myPoints2; Standard_Address myC[2]; Standard_Boolean myDone; }; #endif // _Extrema_ECC_HeaderFile
// MarsColonisation.cpp : main project file. #include "Base.hpp" #include "Graph.hpp" #include "Neighbourhood_generator.hpp" #include "Edge.hpp" #include "Point.hpp" #include "SA.hpp" #include "Solution.hpp" #include "Validator.hpp" #include "MainForm.h" #include <cstdlib> #include <ctime> #include <Windows.h> #include <iostream> #include <Windows.h> #include "stdafx.h" using namespace System; [System::STAThread] int main(array<System::String ^> ^args) { auto x = static_cast<unsigned int>(std::time(0)); std::srand(x); MarsColonisation::MainForm myForm(args); myForm.ShowDialog(); return 0; }
#include <iostream> using namespace std; class Student { private: int age, standard; string last_name, first_name; public: void to_string(int age, string fn, string ln, int standard) { cout << age << endl; cout << ln << ", " << fn << endl; cout << standard << endl; cout << "\n"; cout << age << "," << fn << "," << ln << "," << standard << endl; } int get_age() {return age;} string get_fn() {return first_name;} string get_ln() {return last_name;} int get_standard() {return standard;} void set_age(int new_age) {age = new_age;} void set_fn(string new_fn) {first_name = new_fn;} void set_ln(string new_ln) {last_name = new_ln;} void set_standard(int new_standard) {standard = new_standard;} }; int main() { Student st; int age, standard; string first_name, last_name; cin >> age >> first_name >> last_name >> standard; st.set_age(age); st.set_fn(first_name); st.set_ln(last_name); st.set_standard(standard); st.to_string(st.get_age(), st.get_fn(), st.get_ln(), st.get_standard()); return 0; }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #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 100 #define MOD 1000000007 #define pb push_back /* add vars here */ vector<ll> a,b,c; /* add your algorithm here */ int main() { ll n; cin >> n; rep(i,n) { ll t; cin >> t; a.pb(t); } rep(i,n) { ll t; cin >> t; b.pb(t); } rep(i,n) { ll t; cin >> t; c.pb(t); } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); cout << *(a.begin()) << " " << a[0] << endl; cout << *(a.end()) << " " << a[n] << endl; ll ans = 0; rep(i,n) { ll tar = b[i]; ll ta, tc; tc = c.end() - upper_bound(c.begin(), c.end(), tar); ta = lower_bound(a.begin(), a.end(), tar) - a.begin(); ans += ta * tc; } cout << ans << endl; }
/******************************************************************************** ** Form generated from reading UI file 'accountcreation.ui' ** ** Created by: Qt User Interface Compiler version 5.13.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ACCOUNTCREATION_H #define UI_ACCOUNTCREATION_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> QT_BEGIN_NAMESPACE class Ui_AccountCreation { public: QPushButton *pushButton_ok; QLineEdit *lineEdit_username; QLineEdit *lineEdit_password; QLineEdit *lineEdit_confirmpassword; QLabel *label; QLabel *label_2; QLabel *label_3; QLabel *label_4; QPushButton *pushButton_back; QLineEdit *lineEdit_email; QLabel *label_5; void setupUi(QDialog *AccountCreation) { if (AccountCreation->objectName().isEmpty()) AccountCreation->setObjectName(QString::fromUtf8("AccountCreation")); AccountCreation->resize(400, 300); pushButton_ok = new QPushButton(AccountCreation); pushButton_ok->setObjectName(QString::fromUtf8("pushButton_ok")); pushButton_ok->setGeometry(QRect(210, 220, 80, 21)); lineEdit_username = new QLineEdit(AccountCreation); lineEdit_username->setObjectName(QString::fromUtf8("lineEdit_username")); lineEdit_username->setGeometry(QRect(150, 120, 113, 21)); lineEdit_password = new QLineEdit(AccountCreation); lineEdit_password->setObjectName(QString::fromUtf8("lineEdit_password")); lineEdit_password->setGeometry(QRect(150, 150, 113, 21)); lineEdit_password->setEchoMode(QLineEdit::Password); lineEdit_confirmpassword = new QLineEdit(AccountCreation); lineEdit_confirmpassword->setObjectName(QString::fromUtf8("lineEdit_confirmpassword")); lineEdit_confirmpassword->setGeometry(QRect(150, 180, 113, 21)); lineEdit_confirmpassword->setEchoMode(QLineEdit::Password); label = new QLabel(AccountCreation); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(90, 120, 61, 16)); label_2 = new QLabel(AccountCreation); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(90, 150, 51, 20)); label_3 = new QLabel(AccountCreation); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(50, 180, 91, 20)); label_4 = new QLabel(AccountCreation); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setGeometry(QRect(170, 60, 91, 16)); pushButton_back = new QPushButton(AccountCreation); pushButton_back->setObjectName(QString::fromUtf8("pushButton_back")); pushButton_back->setGeometry(QRect(120, 220, 80, 21)); lineEdit_email = new QLineEdit(AccountCreation); lineEdit_email->setObjectName(QString::fromUtf8("lineEdit_email")); lineEdit_email->setGeometry(QRect(150, 90, 113, 21)); label_5 = new QLabel(AccountCreation); label_5->setObjectName(QString::fromUtf8("label_5")); label_5->setGeometry(QRect(90, 90, 47, 13)); retranslateUi(AccountCreation); QMetaObject::connectSlotsByName(AccountCreation); } // setupUi void retranslateUi(QDialog *AccountCreation) { AccountCreation->setWindowTitle(QCoreApplication::translate("AccountCreation", "Dialog", nullptr)); pushButton_ok->setText(QCoreApplication::translate("AccountCreation", "Ok", nullptr)); label->setText(QCoreApplication::translate("AccountCreation", "Username:", nullptr)); label_2->setText(QCoreApplication::translate("AccountCreation", "Password:", nullptr)); label_3->setText(QCoreApplication::translate("AccountCreation", "Confirm Password:", nullptr)); label_4->setText(QCoreApplication::translate("AccountCreation", "New Account", nullptr)); pushButton_back->setText(QCoreApplication::translate("AccountCreation", "back", nullptr)); label_5->setText(QCoreApplication::translate("AccountCreation", "Email", nullptr)); } // retranslateUi }; namespace Ui { class AccountCreation: public Ui_AccountCreation {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ACCOUNTCREATION_H
// // Created by dylan on 10-3-2020. // Cpp file containing the function definitons for the drawable class // #include "drawable.hpp" drawable::drawable(sf::Vector2f position, sf::Vector2f size, sf::Color Color ): position(position), size(size), Color(Color) {} //Jump function that instantly moves a drawable object to the given position //Keep in mind that the function puts the middle point of the drawable object at the target location void drawable::jump(sf::Vector2f target) { position = target; } //creates a temporary float rectangle around the drawable object //It then checks if the given point is inside the rectangle //And returns if that's true or not bool drawable::contains(const sf::Vector2i & point){ sf::FloatRect clickbox(position, size); return clickbox.contains(point.x, point.y); } //Function to write the drawable objects position to the txt file void drawable::writeGeneral(std::ofstream & output){ output << "(" << position.x << "," << position.y << ") "; } //Function that writes the color of an object to a txt file //It gets the color from the object and then finds that color in the struct //Then it gets the text version of that color and writes that to the txt file void drawable::writeColor(std::ostream& output) { const struct { const char* name; sf::Color color; } colors[]{ { "yellow", sf::Color::Yellow }, { "red", sf::Color::Red }, { "green", sf::Color::Green }, { "blue", sf::Color::Blue }, { "black", sf::Color::Black }, { "white", sf::Color::White }, }; for (auto const & colour : colors) { if (colour.color == Color) { output << colour.name << " "; } } } //Function that returns the drawable objects position; sf::Vector2f drawable::getPosition(){return position;}
#ifndef ENTITY_H #define ENTITY_H #include "scenenode.h" class Entity : public SceneNode { public: explicit Entity(int hitpoints); void setVelocity (sf::Vector2f velocity); void setVelocity (float vx, float vy); void accelerate (sf::Vector2f velocity); void accelerate (float vx, float vy); sf::Vector2f getVelocity (); int getHitpoints () const; int getScore () const; void repair (int points); void damage (int points); void destroy (); void adapt (sf::FloatRect worldBounds); virtual void remove (); virtual bool isDestroyed () const; void setRect (sf::FloatRect rect); sf::FloatRect getRect () const; protected: virtual void updateCurrent (sf::Time dt, CommandQueue& commands); void correctBoundingRect (); private: sf::Vector2f mVelocity; int mHitpoints; const int mScore; sf::FloatRect mBoundingRect; }; #endif // ENTITY_H
#include<iostream> #define FOR(i,n) for(i=0;i<n;i++) using namespace std; long C[1001]; int main() { long i,t,n,ans,sum; cin>>t; while(t--) { cin>>n; FOR(i,n) cin>>C[i]; sum=0;ans=0; for(i=0;i<n;i++) { sum+=C[i]; if(i+1<n) { if(sum<C[i+1])ans++; else sum-=C[i]; } else ans++; } cout<<ans<<endl; } return 0; }
#ifndef _AK_CGUIWINDOW_H_ #define _AK_CGUIWINDOW_H_ #include "cocos2d.h" #include "Ak_Transform.h" class Ak_CGUIWindow : public Ak_CTransform { public: Ak_CGUIWindow(); virtual ~Ak_CGUIWindow(); public: void Create(unsigned int id, bool isRootWindow = false); void Update(float delta); void Destroy(); public: unsigned int GetID(); cocos2d::Layer* GetLayer(); public: void SetParent(Ak_CGUIWindow* pParent); void AddChild(Ak_CGUIWindow* pWindow); void RemoveChild(Ak_CGUIWindow* pWindow); public: void SetColor(unsigned char r, unsigned char g, unsigned char b, unsigned char opacity); public: void SetTexture(const char* c_szFileName); public: void SetWidth(float width); void SetHeight(float height); public: float GetWidth(); float GetHeight(); protected: virtual void OnModifyTransform(); virtual void OnRefreshWindow(); private: void RefreshSprite(); void RefreshDefaultOutline(); private: float m_width; float m_height; unsigned char m_red; unsigned char m_green; unsigned char m_blue; unsigned char m_opacity; bool m_isRefreshWindow; private: bool m_isRootWindow; Ak_CGUIWindow* m_pParent; std::list<Ak_CGUIWindow*> m_childList; private: unsigned int m_id; private: cocos2d::Layer* m_pLayer; cocos2d::LayerColor* m_pColorLayerIn; cocos2d::LayerColor* m_pColorLayerOut; cocos2d::Sprite* m_pSprite; }; #endif
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Optional.h> #include <quic/QuicException.h> #include <quic/congestion_control/CongestionController.h> #include <quic/congestion_control/third_party/windowed_filter.h> #include <quic/state/AckEvent.h> #include <quic/state/StateData.h> #include <limits> namespace quic { using namespace std::chrono_literals; constexpr std::chrono::microseconds kMinRTTWindowLength{10s}; /** * Algorithm description https://fb.quip.com/kgubABy1yuYR * Original paper * https://www.usenix.org/system/files/conference/nsdi18/nsdi18-arun.pdf */ class Copa : public CongestionController { public: explicit Copa(QuicConnectionStateBase& conn); void onRemoveBytesFromInflight(uint64_t) override; void onPacketSent(const OutstandingPacketWrapper& packet) override; void onPacketAckOrLoss( const AckEvent* FOLLY_NULLABLE, const LossEvent* FOLLY_NULLABLE) override; void onPacketAckOrLoss( folly::Optional<AckEvent> ack, folly::Optional<LossEvent> loss) { onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer()); } uint64_t getWritableBytes() const noexcept override; uint64_t getCongestionWindow() const noexcept override; CongestionControlType type() const noexcept override; bool inSlowStart(); uint64_t getBytesInFlight() const noexcept; void setAppIdle(bool, TimePoint) noexcept override; void setAppLimited() override; bool isAppLimited() const noexcept override; void setBandwidthUtilizationFactor( float /*bandwidthUtilizationFactor*/) noexcept override {} bool isInBackgroundMode() const noexcept override { return false; } void getStats(CongestionControllerStats& stats) const override; private: void onPacketAcked(const AckEvent&); void onPacketLoss(const LossEvent&); struct VelocityState { uint64_t velocity{1}; enum Direction { None, Up, // cwnd is increasing Down, // cwnd is decreasing }; Direction direction{None}; // number of rtts direction has remained same uint64_t numTimesDirectionSame{0}; // updated every srtt uint64_t lastRecordedCwndBytes; folly::Optional<TimePoint> lastCwndRecordTime{folly::none}; }; void checkAndUpdateDirection(const TimePoint ackTime); void changeDirection( VelocityState::Direction newDirection, const TimePoint ackTime); QuicConnectionStateBase& conn_; uint64_t cwndBytes_; bool isSlowStart_; // time at which cwnd was last doubled during slow start folly::Optional<TimePoint> lastCwndDoubleTime_{folly::none}; WindowedFilter< std::chrono::microseconds, MinFilter<std::chrono::microseconds>, uint64_t, uint64_t> minRTTFilter_; // To get min RTT over 10 seconds WindowedFilter< std::chrono::microseconds, MinFilter<std::chrono::microseconds>, uint64_t, uint64_t> standingRTTFilter_; // To get min RTT over srtt/2 VelocityState velocityState_; /** * deltaParam determines how latency sensitive the algorithm is. Lower * means it will maximime throughput at expense of delay. Higher value means * it will minimize delay at expense of throughput. */ double deltaParam_{0.05}; // Whether we should use Copa's RTTstanding mechanism bool useRttStanding_{false}; }; } // namespace quic
#ifndef _BAG_H_ #define _BAG_H_ #include <iostream> #include <initializer_list> #include <stdexcept> template <typename Item> class Bag { private: int sz; int capacity; Item *items; public: Bag() : sz(0), capacity(4), items(new Item[4]) {} Bag(int c) : sz(0), capacity(c), items(new Item[c]) {} Bag(const Bag<Item> &b) : sz(b.sz), capacity(b.capacity), items(new Item[b.capacity]) { for (int i = 0; i < sz; i++) { items[i] = b.items[i]; } } Bag<Item> &operator=(const Bag<Item> &b) { delete[] items; sz = b.sz; capacity = b.capacity; items = new Item[capacity]; for (int i = 0; i < sz; i++) { items[i] = b.items[i]; } return *this; } Bag(std::initializer_list<Item> lst) : sz(0), capacity(lst.size()), items(new Item[lst.size()]) { for (Item i : lst) { items[sz++] = i; } } Bag<Item> &add(Item i) { if (sz == capacity) { Item *newItems = new Item[2 * capacity]; for (int j = 0; j < sz; j++) { newItems[j] = items[j]; } capacity = 2 * capacity; delete[] items; items = newItems; } items[sz++] = i; return *this; } Bag<Item> &removeLast() { sz--; return *this; } Item *begin() { return items; } Item *end() { return items + sz; } Item operator[](int i) const { if (i < 0 || i >= sz) { throw std::runtime_error("Out of bounds"); } return items[i]; } Item &operator[](int i) { if (i < 0 || i >= sz) { throw std::runtime_error("Out of bounds"); } return items[i]; } int getSize() const { return sz; } int getCapacity() const { } friend std::ostream &operator<<(std::ostream &out, Bag<Item> &bag) { for (int i = 0; i < bag.sz; i++) { out << bag.items[i] << " "; } return out; } ~Bag() { delete[] items; items = nullptr; } }; #endif
#pragma once #include <stddef.h> #include <utility> #include "triangulation.hpp" namespace space { template <typename Func, typename I> void Interpolate(Func &&f, I *root) { for (auto node : root->Bfs()) { // Create dual space basis. StaticVector<std::pair<std::pair<double, double>, double>, 3> eval_space; auto space_vertex = node->node()->vertex(); eval_space.emplace_back(std::pair{space_vertex->x, space_vertex->y}, 1.0); if (node->node()->level()) { eval_space.emplace_back(std::pair{space_vertex->godparents[0]->x, space_vertex->godparents[0]->y}, -0.5); eval_space.emplace_back(std::pair{space_vertex->godparents[1]->x, space_vertex->godparents[1]->y}, -0.5); } double val = 0; for (auto [pt, coeff] : eval_space) { auto [x, y] = pt; val += coeff * f(x, y); } node->set_value(val); } } } // namespace space
#include <iostream> using namespace std; void changeArgument(int x) { x = x + 5; } int main() { int y = 4; changeArgument( y ); cout << y; // still prints 4 return 0; }
class Solution { public: bool isRectangleCover(vector<vector<int>>& rectangles) { unordered_set<string> se; int x1 = INT_MAX, y1 = INT_MAX, x2 = INT_MIN, y2 = INT_MIN, area = 0; for(auto rect: rectangles){ x1 = min(rect[0], x1); y1 = min(rect[1], y1); x2 = max(rect[2], x2); y2 = max(rect[3], y2); area += (rect[2] - rect[0]) * (rect[3] - rect[1]); vector<string> strs; for(int i = 0; i < 3; i=i+2){ for(int j = 1; j < 4; j=j+2){ strs.push_back(to_string(rect[i]) + " " + to_string(rect[j])); } } for(string str: strs){ if(se.count(str)) se.erase(str); else se.insert(str); } } string s1 = to_string(x1) +" "+ to_string(y1); string s2 = to_string(x1) +" "+ to_string(y2); string s3 = to_string(x2) +" "+ to_string(y1); string s4 = to_string(x2) +" "+ to_string(y2); return area == (x2-x1)*(y2-y1) && se.size() == 4 && se.count(s1) && se.count(s2) && se.count(s3) && se.count(s4); /* [[0,0,1,1],[0,0,2,1],[1,0,2,1],[0,2,2,3]] if only area and 4 corner points condition, it's not true. we need to ensure the only 4 is the final 4 corner. */ } };
// Tina Greenfield /* This program is designed to calculate a concrete bridge's surface temperature. It is initialized with RWIS bridge and air temperatures, all else from MM5 or some other weather model. MM5 supplies atmospheric conditions at regular intervals, which are used to force the bridge temperature. MM5 values are not altered in this program */ //anticipated publication (as of June 2004): //Greenfield, T. M., 2004: Bridge frost prediction by heat and mass transfer methods. // M.S. thesis, Dept. of Geological and Atmospheric Science, Iowa State University #include <iostream.h> #include <fstream.h> #include <string> #include <iomanip.h> #include <stdlib.h> #include <math.h> #include "RWIS.h" float radiative( float, float, float, float, float,float ); float convection( float, float, float ); float initialize( float, float, float, float, float, double, int, int ); float precipitation( float, float, float, float, float, float, float, float, float, float &, float &, float &, int &, int ); float evaporation(float, float, float, float, float, float); float bridgelevels( float, float, float, float, float, float, float, double, int, int ); int main (int argc, const char * argv[]) { if (argc != 4) { cerr << "usage: bridgemodel <rwis file> <mm5 file> <bridgeProperties>" << endl; return 1; } allRWIS rwisfile( argv[1] ); ifstream mm5file( argv[2] ); ifstream bridgeProperties( argv[3] ); // returned values from functions residual, convection, frost, // precipitation, initialize,and bridgelevels float radiation, h, frostDepth, bridgeTemp, latentFlux, rwisAir; float initialTemp; int condition; //stuff from MM5 float oSWradiationIn,oLWradiationIn, oprecipRate, otempA, owind, oqa; //"old" values for interpolation float nSWradiationIn,nLWradiationIn, nprecipRate, ntempA, nwind, nqa; //"new" values for interpolation float cSWradiationIn,cLWradiationIn, cprecipRate, ctempA, cwind, cqa; //"current" values from interpolation nprecipRate = 0.0; float nprecip, oprecip; float minutesf; // stuff for model interpolation int oldMinutes; float difference; //timestamp stuff. Updates the timestamp for interpolated values. int year, month, day, hour; int yearO, monthO, dayO, hourO; float junky; char junk; //stuff from the property file. Bridge thickness, solar absorptivity //longwave absorptivity, conductivity, and thermal diffusivity float thickness, swAbs, lwAbs, kbridge, density, cp; float thermalDiffusivity; if( mm5file.good() == false ) { cerr << "Can't open file " << argv[2] << endl; exit( 1 ); } if( bridgeProperties.good() == false ) { cerr << "Can't open file " << argv[3] << endl; exit( 41 ); } ofstream outfile( "pavetemp.out" , ios::out); if (!outfile) { cerr << "file could not be opened: " << endl; exit (2); } bridgeProperties>>thickness>>kbridge>>swAbs>>lwAbs>>density>>cp; thermalDiffusivity = kbridge / ( density * cp); // initializing the bridge deck layer temperatures int initialcounter = 1; for ( int i = 0; i < rwisfile.TotalMinutesInFile(); i++ ) { RWISdata currentData; currentData = rwisfile.DataAtMinutesFromStart(i); bridgeTemp = currentData.surfaceTemp; h = convection(currentData.wind, currentData.airTemp, currentData.surfaceTemp); for ( int c = 0; c < 19; c++) { initialTemp = initialize( bridgeTemp, currentData.airTemp, h, kbridge, thickness, thermalDiffusivity, c, initialcounter); } initialcounter = initialcounter + 1; rwisAir = currentData.airTemp; } // All RWIS initialization is done. // Beginning of loop for calculations for forecasted bridge temperature int linecounter = 0; int check = 0; int z = 0;//minutes keeper float zz = 0;//minutes between model values while( mm5file>>year>>junk>>month>>junk>>day>>junk>>hour>>junk>>junky>>minutesf>> ntempA>>nqa>>nwind>>nSWradiationIn>>nLWradiationIn>>nprecipRate ) { //cout<<nprecipRate<<endl; int minutes=(int)minutesf; if ( linecounter == 0 && fabs(ntempA - rwisAir) > 15.0 ) { cerr << "15+ gap MM5 & input air temperature " << ntempA<<" "<<rwisAir<<endl; return 23; } // mm5 data is hourly. It needs to be interpolated for minute by minute. if ( linecounter != 0 ) { // slope-point for the minute by minute data difference = minutes - oldMinutes; nprecip = nprecipRate; nprecipRate = nprecip - oprecip; if ( nprecipRate < 0.0) { nprecipRate = 0.0; } while ( z < minutes ) { zz = z - oldMinutes; cqa = ( nqa - oqa ) / ((float) difference) * (zz) + oqa; cwind = ( nwind - owind ) / ((float) difference) * (zz) + owind; cSWradiationIn = ( nSWradiationIn - oSWradiationIn ) / ((float) difference) * (zz) + oSWradiationIn; cLWradiationIn = ( nLWradiationIn - oLWradiationIn ) / ((float) difference) * (zz) + oLWradiationIn; cprecipRate = ( nprecipRate - oprecipRate ) / ((float) difference) * (zz) + oprecipRate; ctempA = ( ntempA - otempA ) / ((float) difference) * (zz) + otempA; //cout<<" New"<<nprecipRate<<" current"<<cprecipRate<<" old"<<oprecipRate; //cout<<linecounter<<" "; // quality checks if ( ctempA > 410 || ctempA < 200 ) { cerr << " bad MM5 air temperature input " <<ctempA<< endl; return 4; } if ( cqa > 1 || cqa < 0 ) { cerr << " bad MM5 humidity input " << cqa<<endl; return 5; } if ( cwind > 70 || cwind < 0 ) { cerr << " bad MM5 windspeed input " <<cwind<< endl; return 6; } if ( cSWradiationIn> 1000 || cSWradiationIn < 0 ) { cerr << " bad MM5 SWradiation input "<<cSWradiationIn<< endl; return 7; } if ( cLWradiationIn> 2000 || cLWradiationIn < 50 ) { cerr << " bad MM5 LWradiation input " << cLWradiationIn << endl; return 8; } if ( cprecipRate > 40 || cprecipRate < 0 ) { cerr << " bad MM5 precipitation input " <<cprecipRate<< endl; return 9; } //calling functions h = convection(cwind, ctempA, bridgeTemp); latentFlux = precipitation(cprecipRate, h, ctempA, cqa, cwind, kbridge, thickness,density,cp,bridgeTemp, frostDepth, swAbs, condition, check ); radiation = radiative(cSWradiationIn, cLWradiationIn, bridgeTemp, swAbs, lwAbs, ctempA); bridgeTemp = bridgelevels(radiation, latentFlux, bridgeTemp,ctempA, h, thickness, kbridge, thermalDiffusivity, check, z ); check++; // calculating DEW (not frost) point temperature for output purposes only. float Td; Td = 5.42*pow(10,3) / (log( 2.53 * pow(10,8) * 0.622 / ( cqa * 100.0))); float d; d = log(cqa*1000.0/(0.622*6.1078))/21.875; float Tf; Tf = (-7.66*d +273.0)/(1.0-d); //cout<<Td<<" "<<Tf<< endl; if(hourO == 24) { hourO = 0; dayO++; } //writing the calculated bridge temperature to file. //different outputs to make timestap correct outfile << yearO <<"-"<<monthO<<"-"<<dayO<<"_"<<hourO <<":" << ( (z%60) < 10 ? "0" : "" ) << (z%60) << " " << ctempA<< " " << cwind << " "<<cSWradiationIn<<" " <<cLWradiationIn<<" "<<h<<" "<<latentFlux<<" " << bridgeTemp << " "<<frostDepth <<" "<<Tf << " "; switch (condition) { case 1: outfile<<"frosty"; break; case 2: outfile<<"Icy/Snowy"; break; case 3: outfile<< "Melting"; break; case 4: outfile<<"Freezing"; break; case 5: outfile<<"Wet"; break; case 0: outfile<<"Dry"; break; } outfile<< endl; z++;// sends it through the minute loop again unless its at the next hour } } //turn the "new" data into the "old" data otempA = ntempA; oqa = nqa; owind = nwind; oSWradiationIn = nSWradiationIn; oLWradiationIn = nLWradiationIn; oprecipRate = nprecipRate; oprecip = nprecip; yearO = year; monthO = month; dayO = day; hourO = hour; linecounter = linecounter + 1; oldMinutes = minutes; z = oldMinutes; } // end of bridge surface calculator loop. outfile.close(); return 0; }//end of main float initialize( float bridgeTemp, float tempA, float h, float kbridge, float thickness, double thermalDiffusivity, int c, int i ) { /* this function is used to initialize the bridge layer temps before the forecasted temperatures are calculated. It uses the RWIS air and surface temperatures to force the lower level temperatures since only the surface temperature is actually measured. It runs using the previous surface and air temperatures.*/ static float nexttempB[19];// array to temporarily store the new values so //they dont interfere with the following calculations. static float tempB[19]; // returns the calculated value to "bridgelevel" and skips any additional calculations if ( i == 0 ) { return tempB[c]; // array to store the node temperatures. Initially set to airTemp. } static float depth; depth = thickness / 19.0; // distance in meters between nodes static const float M = ((depth * depth) / (thermalDiffusivity * 60.0)); // unitless coefficient for heat transfer rates in concrete. if ( i == 1) { tempB[c] = tempA ; } else { nexttempB[0] = 1 / M * ( bridgeTemp + tempB[1] ) + ( 1 - ( 2 / M ) ) * tempB[0]; if ( c > 0 && c < 18 ) { nexttempB[c] = 1 / M * ( tempB[c-1] + tempB[c+1] ) + ( 1 - ( 2 / M ) ) * tempB[c]; } nexttempB[18] = (2 / M) * (h * depth / kbridge * tempA + tempB[17]) + (1 - (2 / M) * (h * depth / kbridge + 1)) * tempB[18]; tempB[c] = nexttempB[c]; } return tempB[c]; } float precipitation( float precip, float h, float airTemp, float qa, float wind, float kbridge, float thick,float concreteDensity, float Cc, float &bridgeTemp, float &frostDepth, float &abs, int &condition, int i ) { /* MM5 calculates precip rate in centimeters per hour, and the bridge will not hold all the water that falls on it. This function divides the precip rate into kilograms per minute, calculates total precip. accumulation, and truncates the precip amount if more were to fall than the bridge will hold. The truncation will help keep unreasonable amounts of water from cooling the bridge through latent effects. The evaporation rate and latent heat effects are calculated and the heat flux is returned to main. The total frost depth is calculated.*/ static const float waterDensity = 1000 ; //kg m-3 //static const float iceDensity = 917; // kg m-3 static const float cp = 1007 ; // specific heat of air J/(kg k) static const float Le = 0.907;//Lewis#=thermal diffusivity of water / mass diffusivity //approximately constant. Le = Lewis # raised to the 2/3 power. static const float R = 0.08314; // m3 bar/ kmol K Universal gas constatant static const float M = 18.0; // Kg/Kmol molecular weight of water. static const float epsilon = 0.622; //constant Ratio of mol. weight of water/dry air static const float Lf = 3.34 * pow ( 10,5); //latent heat of freezing J/kg static const float Lv = 2.5 * pow ( 10,6); //latent heat of condensation J/kg water static const float Cw = 4218 ; // J/K kg specific heat of water static float thickness;// depth of the top concrete layer thickness = thick / 38.0; static float Mc;// mass of concrete in one node layer per unit area kg Mc = concreteDensity * thickness; static float Tw; // temperature of the water already accumulated on the bridge static float precipDepth; // meters static float frozen; // depth of water that is frozen on the bridge static float totalDepth; // total depth of water accum. Includes condensation/frost static float Mw; // per unit area mass of existing accum. Mw = (precipDepth) * waterDensity ; float evapRate; // kg s-1 m-2 float Patm;// pressure of water vapor in the surrounding air static float oldabs;//original solar absorptivity Patm = qa / epsilon; // * 1000mb -- `in bars float airDensity; // density of air = p/(RT) kg/m3 assuming pressure = 1000 mb airDensity = 100000/ ( 287 * airTemp); float hm; // mass transfer coefficient hm = h / (airDensity * cp * Le ); float Mf; // per unit area mass of water that just fell as precip float Te; // equilibrium temp of bridge and fallen precip float heatFlux; // latent heat flux lost or gained to the bridge. Returned to residual float freezeRate; // kg/s of water freezing or melting. evapRate = 0; // makes sure evapRate is not carried over from last iteration heatFlux = 0; precip = precip / 6000.0 ; // centimeters per hour to meters per minute Mf = precip * waterDensity ; if ( i == 0 ) // sets initial depth to zero { precipDepth = 0; frostDepth = 0; oldabs = abs; Tw = airTemp; } precipDepth += precip;//incriments total precipitation depth //cout<<precipDepth<<" "<<precip<<"new "; if ( precipDepth > 0.0011 ) // derived experimentally { precipDepth = 0.0011; } if (Tw <= 273.16 && bridgeTemp <= 273.16 ) // snow on bridge. { // only 0.025 in water (~.25 in. of snow) allowed because of plowing //Snow density assumed 1/10 of water. if ( precipDepth > 0.00063 ) { precipDepth = 0.00063; } } if ( precipDepth == 0 ) { Tw = airTemp; } //this is the equilibrium temperature between precip accumulation and the bridge Te = ( Cw * (Mw * Tw + Mf*airTemp) + Cc * Mc * bridgeTemp ) / (Cw * (Mw + Mf) + Cc * Mc ); if ( precipDepth > 0 ) { totalDepth = precipDepth + frostDepth / 10.0; frostDepth = 0; } //phase change stuff if ( Tw > 273.16 && bridgeTemp > 273.16 ) // just evaporation or condensation { evapRate = evaporation ( hm, M, R, bridgeTemp, Patm, airTemp); condition = 0;//dry if(totalDepth > 0.0) { condition = 5;//wet } } if ( Tw >= 273.16 && bridgeTemp <= 273.16 ) // freezing/condensation/evaporation { Tw = bridgeTemp = Te; if ( Te >= 273.16 ) // no freezing -- evaporation or condensation { evapRate = evaporation ( hm, M, R, bridgeTemp, Patm, airTemp); condition = 5;//wet } else // freezing { heatFlux = kbridge * ( 273.16 - Te ) / (thickness);//q' = k dT/dx freezeRate = heatFlux / Lf;//the amount that will freeze with the amount // of excess energy available between the equilibrium temperature and 273.16 if (freezeRate/waterDensity * 60 <= (totalDepth - frozen)) { frozen = freezeRate/waterDensity * 60 + frozen; condition = 4; //freezing } else// if possible freezing exceeds whats available to freeze (all frozen) { heatFlux = (totalDepth - frozen) / 60.0 * waterDensity; frozen = totalDepth; condition = 2;//icy/snowy } Tw = 273.16; if ( frozen > precipDepth )//takes care of straggling precip { condition = 2;//icy/snowy if (frostDepth > 0.0 ) { condition = 1;//frosty } Tw = Te; frozen = totalDepth; heatFlux = 0; } } } else if ( Tw <= 273.16 && bridgeTemp <= 273.16 ) // snow/frost. sublimation, no melting { // frost accumulation/evaporation possible // this version does allow frost formation over existing precipitation accumulation, but // it will not be labeled as "frost," just additional accumulation of snow/ice. evapRate = evaporation ( hm, M, R, bridgeTemp, Patm, airTemp); if ( precipDepth ==0 ) { //frost will form if evapRate is negative -- water flux toward the bridge surface // depth after a minute of accumulation/evap. Density is a tenth of water. frostDepth += ( -600 * evapRate / waterDensity ); condition = 1;//frosty if (frostDepth <= 0 ) { frostDepth =0.0; heatFlux = 0.0; condition = 0; //dry } totalDepth = frostDepth / 10.0;//total depth is in liquid equivalent Tw = bridgeTemp; //if(evapRate < 0.0) //{ cout<<evapRate<<" "<<precipDepth<<" "<<frostDepth<<endl;} } // only 0.025 in water (~.25 in. of snow) allowed because of plowing //Snow density assumed 1/10 of water. //cout<<Tw<<" "<<bridgeTemp<<" "<<Te<<endl; Tw = bridgeTemp = Te; if (precipDepth >0 && frostDepth == 0) { condition = 2;//icy/snowy //frost will form over snow if evapRate is negative -- flux toward the bridge surface } //reduces the sw absorptivity when frost, ice, or snow is present if (totalDepth > 0.0) { abs = oldabs * (1-(700.0*totalDepth)); } } else if ( Tw <= 273.16 && bridgeTemp > 273.16 ) // melting possible { Tw = bridgeTemp = Te; if ( Te <= 273.16 ) // no melting { heatFlux = 0; condition = 2;//snowy/icy if (frostDepth > 0.0 ) { condition = 1;//frosty } } else // melting - heat taken from bridge { heatFlux = kbridge * ( 273.16 - Te ) / (thickness);//q' = k dT/dx freezeRate = heatFlux / Lf;//the amount that will melt with the amount // of excess energy available between the equilibrium temperature and 273.16 if (freezeRate/waterDensity * 60 <= frozen) { frozen = freezeRate/waterDensity * 60 + frozen; condition = 3;//melting } else// if possible melting exceeds whats available to melt { heatFlux = frozen / 60.0 * waterDensity; frozen = 0; condition = 5;//wet } frostDepth = freezeRate/waterDensity * 60 + frostDepth; Tw = 273.16; if ( frozen < 0 || frostDepth <0)// just in case frostDepth or frozen goes - { Tw = Te; bridgeTemp = Te; frostDepth =0; heatFlux = 0; frozen = 0; condition = 5; //wet } Tw = 273.16; } } // if statements make sure evaporation rate does not exceed totalDepth, //the amount on the bridge //decreases or increases the total depth based on evaporation rate. // doesn't alter melting or freezing values if (condition != 3 && condition != 4) { if ( totalDepth > (evapRate * 60 / waterDensity) ) { totalDepth = totalDepth - (evapRate * 60 / waterDensity); precipDepth = precipDepth - (evapRate * 60 / waterDensity); if(frostDepth > 0.0) { precipDepth = 0.0; } heatFlux = -1 * evapRate * Lv; if (condition == 2 || condition == 1) { heatFlux = -1 * evapRate * (Lv + Lf); } //cout<<evapRate<<"evap "<<totalDepth<<" td bigger "<<heatFlux<<" "<<(evapRate * 60 / waterDensity)<<endl; } else // when evapRate exceeds total depth { heatFlux = -1 * totalDepth * waterDensity * Lv / 60.0; if (condition == 2 || condition == 1) { heatFlux = -1 * totalDepth * waterDensity * (Lv + Lf) / 60.0; } totalDepth = 0; precipDepth = 0; Mw = 0; condition = 0;//dry //cout<<heatFlux<<" evap exceeds "<<i<<endl; } } //corrects if totalDepth or precipDepth go negative for some reason if ( totalDepth < 0 || precipDepth < 0 || frostDepth < 0) { heatFlux = 0.0; totalDepth = 0.0; precipDepth = 0.0; condition = 0;//dry frostDepth = 0.0; } //cout<<"precipdepth"<<precipDepth<<" "; return heatFlux; } float evaporation (float hm, float M, float R, float bridgeTemp, float Patm, float airTemp) { //this is a function to calculate the evaporation rate over water or ice, depending on // bridge temperature. static float Psat;// pressure of water vapor at saturation static float evapRate;//evaporation rate kg/s/m2 if (bridgeTemp > 273.16) { Psat = 6.112 * exp( 17.67 * ( bridgeTemp - 273.16)/( bridgeTemp - 29.5))/1000.0;//bars } else { Psat = 6.1115* exp(( 23.036 - ( bridgeTemp - 273.16) /333.7) * ( bridgeTemp - 273.16) / (6.82 + bridgeTemp))/1000.0;//bars //this is over ice. this is different from saturation over water! Buck, JAM 1981 } evapRate = hm * M / R * ( Psat / bridgeTemp - Patm / airTemp); // kg/sec per unit area return evapRate; } float radiative(float SW, float LW, float tempSfc, float absorptivitySW, float absorptivityLW, float airtemp) { // This function is used to find the radiative energy flux available // to influence the bridge temperature LW =LW*1.13; static const float stephanBoltz = 5.67 * pow(10,-8); //(W m-2 K-4) float radiation; //energy flux ( W m-2) received from atmosphere // incoming radiation minus emitted radiation radiation = ( absorptivityLW * LW ) + ( absorptivitySW * SW ) - absorptivityLW * stephanBoltz * pow(tempSfc,4.0) ; return radiation; } float convection( float wind, float Ta, float Ts ) { /* this function finds the right convection heat transfer coefficient (in Wm-2) given windspeed and the temperature difference between the air and bridge surface. It will be the average coefficient over a 10 meter span of bridge. h is computed for "tripped" flow, where turbulence begins at the very edge of the bridge. Immediately turbulent flow is a good assumption because of bridge rails and other bridge complexities.*/ float h, reynoldsNumber;//, Cf, xCrit; static const float kair = 2.4 * pow(10,-2);// conductivity of air Wm-1k-1 static const float length = 10 ; //meters. length of bridge exposed to air flow static const float prandtlNumber = 0.71;// for air static const float kinematicViscosity = 1.4 * pow(10,-5) ;//m2 s-1 for air static const float g = 9.8;// ms-2 gravity static float Gr; // Grashof # ratio of bouyancy to viscous forces static float Ra; // Rayleigh # = Gr*Pr static float Nuf; //Nusselt# for forced conv. //Nu=hL/k = Dimensionless temp gradient at the surface. static float Nun; //Nusselt # for natural conv static float Nu; // total Nusselt number = Nuf+-Nun. //Stability suppresses total conv, Instability inhances it. wind = wind - 0.96; if (wind <= 0) { wind =0.01; // keeps the reynolds number from going to zero. } //forced convection... reynoldsNumber = wind * length / kinematicViscosity; Nuf = 0.037*1.5*pow(reynoldsNumber,(0.8)) * pow(prandtlNumber,(1/3.0)); // now for natural conv... Gr = g * (2/(Ta+Ts))*(Ts-Ta)*pow(length,3)/pow(kinematicViscosity,2); Ra = prandtlNumber*Gr; if((Ts-Ta)>=0) { Nun = 0.15* pow(Ra,0.3333); Nu = pow((pow(Nuf,3.0) + pow(Nun,3.0)),0.333); } else { Ra = Ra *(-1.0); Nun = 0.27*pow(Ra,0.25); if ((pow(Nuf,3.0) - pow(Nun,3.0))<=0.0) { Nu = 0.001; } else { Nu = pow((pow(Nuf,3.0) - pow(Nun,3.0)),0.333); } } h = kair * Nu / length; return h; } float bridgelevels (float radiation, float latentHeat, float tempSfc, float tempAir, float h, float thickness, float kbridge, double thermalDiffusivity,int l, int t) { /* n is used for node definition, it gives the vertical position of the node. At n = 0, is a node representing the top surface of the bridge. Since the bridge is much longer and wider than deep, a temperature gradient is assumed to exist only in the verical. Max n = 19, total depth is determined by the property file. The second array dimension is t, the time in minutes. The temperature of any node at any time is stored in the two dimensional array, temperature. Nodes are initialized with the temperatures found in"initialize". */ static float length = thickness / 19.0;// m distance between nodes //heat transfer rate coefficient, timestep =60 s static float M = ((length * length) / (thermalDiffusivity * 60.0)); float N ; N = (1+(h*length/kbridge)) / M ; float dummy[6] = {0};// useless floats to pass to function "initialize" static float temperature[20][3000]; if ( N > 0.5 ) { //WARNING: thickness, h, and thermal diffusivity combination creates //numerical instability. Should be less than 0.5. This usually doesn't //cause noticable effects. setting N to the largest stable number N = 0.499; } if ( t > 3000 ) { cerr << " file will be shortened to 3000 minutes " << endl; exit( 31 ); } // sets initial bridge node temperatures if ( l == 0 ) { int i = 0; temperature[0][t] = tempSfc; for ( int c = 1; c < 20; c++) { temperature[c][t] = initialize( dummy[0], dummy[1], dummy[2], dummy[3], dummy[4], dummy[5], (c-1), i ); if ( temperature[c][t] == 0 ) { cerr<< " intialization = 0. insufficient rwis initialization" << endl; exit(20); } } } // for any other time, t // for top level, there is conduction, convection, and residual //(radiative, and latent heat) processes at work else { temperature[0][t-1] = tempSfc;//makes sure that the surface temperature //from the latentHeat function is used temperature[0][t] = (2 / M) * ( h * length / kbridge * tempAir + ( (radiation + latentHeat) * length / kbridge ) + temperature[1][t-1]) + ( 1 - (2 * N)) * temperature[0][t-1]; // for lower levels: just conduction for middle layers, // convection for the lowest level. for (int n = 1; n < 19; n++ ) { temperature[n][t] = ( 1 / M * (temperature[n-1][t-1] + temperature[n+1][t-1] ) + (1 - 2 /M ) * temperature[n][t-1]); } temperature[19][t] = (2 / M) * (h * length / kbridge * tempAir + temperature[18][t-1]) + (1 - (2 * N)) * temperature[19][t-1]; if ( t > 0 && fabs(temperature[0][t-1] - temperature[0][t]) > 8 ) { cout << " heating/cooling rate too high. check inputs "<< temperature[0][t-1] <<" "<<temperature[0][t] << " "<<t<<endl; //exit(25); } } if ( temperature[0][t] < 200 ) { cerr<< "bad calculated surface temperature: check inputs " <<temperature[0][t]<<" time: "<<t<<endl; exit(10); } return temperature[0][t]; }
#include <assert.h> #include <algorithm> #include <climits> #include <functional> #include <iostream> #include <numeric> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define ll long long using namespace std; int n; struct Solution { void solve() { int res = 0; vector<bool> ps(n + 1, true); for (int i = 2; i <= n; ++i) { if (!ps[i]) continue; for (int j = i * i; j <= n; j += i) { ps[j] = false; } res++; for (int j = i * i; j <= n; j *= i) { res++; } } cout << res << endl; for (int i = 2; i <= n; ++i) { if (!ps[i]) continue; cout << i << " "; for (int j = i * i; j <= n; j *= i) { cout << j << " "; } } } }; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; Solution test; test.solve(); cout << flush; }
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.12.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTabWidget> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout; QDialogButtonBox *buttonBox; QTabWidget *tabWidget; QWidget *tab; QGridLayout *gridLayout_3; QLabel *label_3; QLabel *label_7; QLabel *label_4; QLineEdit *srcSheet; QLineEdit *dstColumn1; QPushButton *srcBrowserBtn; QLineEdit *srcColumn1; QLabel *label; QSpacerItem *horizontalSpacer; QLineEdit *srcExcelPath; QLabel *label_9; QLineEdit *srcModuleIndex; QWidget *tab_2; QGridLayout *gridLayout_2; QLineEdit *srcColumn2; QLineEdit *dstSheet; QLabel *label_5; QLabel *label_6; QLabel *label_8; QLabel *label_2; QLineEdit *dstExcelPath; QSpacerItem *horizontalSpacer_2; QPushButton *dstBrowserBtn; QLineEdit *dstColumn2; QLabel *label_10; QLineEdit *dstModuleIndex; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QString::fromUtf8("MainWindow")); MainWindow->resize(466, 277); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); buttonBox = new QDialogButtonBox(centralWidget); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); gridLayout->addWidget(buttonBox, 1, 0, 1, 1); tabWidget = new QTabWidget(centralWidget); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tab = new QWidget(); tab->setObjectName(QString::fromUtf8("tab")); gridLayout_3 = new QGridLayout(tab); gridLayout_3->setSpacing(6); gridLayout_3->setContentsMargins(11, 11, 11, 11); gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3")); label_3 = new QLabel(tab); label_3->setObjectName(QString::fromUtf8("label_3")); gridLayout_3->addWidget(label_3, 3, 0, 1, 1); label_7 = new QLabel(tab); label_7->setObjectName(QString::fromUtf8("label_7")); gridLayout_3->addWidget(label_7, 0, 0, 1, 1); label_4 = new QLabel(tab); label_4->setObjectName(QString::fromUtf8("label_4")); gridLayout_3->addWidget(label_4, 4, 0, 1, 1); srcSheet = new QLineEdit(tab); srcSheet->setObjectName(QString::fromUtf8("srcSheet")); gridLayout_3->addWidget(srcSheet, 1, 1, 1, 1); dstColumn1 = new QLineEdit(tab); dstColumn1->setObjectName(QString::fromUtf8("dstColumn1")); gridLayout_3->addWidget(dstColumn1, 4, 1, 1, 1); srcBrowserBtn = new QPushButton(tab); srcBrowserBtn->setObjectName(QString::fromUtf8("srcBrowserBtn")); gridLayout_3->addWidget(srcBrowserBtn, 0, 3, 1, 1); srcColumn1 = new QLineEdit(tab); srcColumn1->setObjectName(QString::fromUtf8("srcColumn1")); gridLayout_3->addWidget(srcColumn1, 3, 1, 1, 1); label = new QLabel(tab); label->setObjectName(QString::fromUtf8("label")); gridLayout_3->addWidget(label, 1, 0, 1, 1); horizontalSpacer = new QSpacerItem(201, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout_3->addItem(horizontalSpacer, 3, 2, 1, 2); srcExcelPath = new QLineEdit(tab); srcExcelPath->setObjectName(QString::fromUtf8("srcExcelPath")); gridLayout_3->addWidget(srcExcelPath, 0, 1, 1, 2); label_9 = new QLabel(tab); label_9->setObjectName(QString::fromUtf8("label_9")); gridLayout_3->addWidget(label_9, 2, 0, 1, 1); srcModuleIndex = new QLineEdit(tab); srcModuleIndex->setObjectName(QString::fromUtf8("srcModuleIndex")); gridLayout_3->addWidget(srcModuleIndex, 2, 1, 1, 1); tabWidget->addTab(tab, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QString::fromUtf8("tab_2")); gridLayout_2 = new QGridLayout(tab_2); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")); srcColumn2 = new QLineEdit(tab_2); srcColumn2->setObjectName(QString::fromUtf8("srcColumn2")); gridLayout_2->addWidget(srcColumn2, 3, 1, 1, 1); dstSheet = new QLineEdit(tab_2); dstSheet->setObjectName(QString::fromUtf8("dstSheet")); gridLayout_2->addWidget(dstSheet, 1, 1, 1, 1); label_5 = new QLabel(tab_2); label_5->setObjectName(QString::fromUtf8("label_5")); gridLayout_2->addWidget(label_5, 4, 0, 1, 1); label_6 = new QLabel(tab_2); label_6->setObjectName(QString::fromUtf8("label_6")); gridLayout_2->addWidget(label_6, 3, 0, 1, 1); label_8 = new QLabel(tab_2); label_8->setObjectName(QString::fromUtf8("label_8")); gridLayout_2->addWidget(label_8, 0, 0, 1, 1); label_2 = new QLabel(tab_2); label_2->setObjectName(QString::fromUtf8("label_2")); gridLayout_2->addWidget(label_2, 1, 0, 1, 1); dstExcelPath = new QLineEdit(tab_2); dstExcelPath->setObjectName(QString::fromUtf8("dstExcelPath")); gridLayout_2->addWidget(dstExcelPath, 0, 1, 1, 2); horizontalSpacer_2 = new QSpacerItem(201, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout_2->addItem(horizontalSpacer_2, 3, 2, 1, 2); dstBrowserBtn = new QPushButton(tab_2); dstBrowserBtn->setObjectName(QString::fromUtf8("dstBrowserBtn")); gridLayout_2->addWidget(dstBrowserBtn, 0, 3, 1, 1); dstColumn2 = new QLineEdit(tab_2); dstColumn2->setObjectName(QString::fromUtf8("dstColumn2")); gridLayout_2->addWidget(dstColumn2, 4, 1, 1, 1); label_10 = new QLabel(tab_2); label_10->setObjectName(QString::fromUtf8("label_10")); gridLayout_2->addWidget(label_10, 2, 0, 1, 1); dstModuleIndex = new QLineEdit(tab_2); dstModuleIndex->setObjectName(QString::fromUtf8("dstModuleIndex")); gridLayout_2->addWidget(dstModuleIndex, 2, 1, 1, 1); tabWidget->addTab(tab_2, QString()); gridLayout->addWidget(tabWidget, 0, 0, 1, 1); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 466, 23)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QString::fromUtf8("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QString::fromUtf8("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); tabWidget->setCurrentIndex(1); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr)); label_3->setText(QApplication::translate("MainWindow", "srccolumn:", nullptr)); label_7->setText(QApplication::translate("MainWindow", "srcexcel:", nullptr)); label_4->setText(QApplication::translate("MainWindow", "dstcolumn:", nullptr)); srcSheet->setText(QApplication::translate("MainWindow", "Sheet1", nullptr)); dstColumn1->setText(QApplication::translate("MainWindow", "G", nullptr)); srcBrowserBtn->setText(QApplication::translate("MainWindow", "Browser", nullptr)); srcColumn1->setText(QApplication::translate("MainWindow", "B", nullptr)); label->setText(QApplication::translate("MainWindow", "srcsheet:", nullptr)); label_9->setText(QApplication::translate("MainWindow", "contextcolumn:", nullptr)); srcModuleIndex->setText(QApplication::translate("MainWindow", "A", nullptr)); tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("MainWindow", "Source Settings", nullptr)); srcColumn2->setText(QApplication::translate("MainWindow", "B", nullptr)); dstSheet->setText(QApplication::translate("MainWindow", "Sheet1", nullptr)); label_5->setText(QApplication::translate("MainWindow", "dstcolumn:", nullptr)); label_6->setText(QApplication::translate("MainWindow", "srccolumn:", nullptr)); label_8->setText(QApplication::translate("MainWindow", "dstexcel:", nullptr)); label_2->setText(QApplication::translate("MainWindow", "dstsheet:", nullptr)); dstBrowserBtn->setText(QApplication::translate("MainWindow", "Browser", nullptr)); dstColumn2->setText(QApplication::translate("MainWindow", "G", nullptr)); label_10->setText(QApplication::translate("MainWindow", "contextcolumn:", nullptr)); dstModuleIndex->setText(QApplication::translate("MainWindow", "A", nullptr)); tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("MainWindow", "Dist Settings", nullptr)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H