blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
8692215e54ce1ecffa12bf06633944c5915b4a0f
730730a87bbe1f8084eac5f7bd6d624528af2513
/delaunay_test_02/src/ofApp.cpp
5feb463a2842dd5ee3dd39b671192ab37f452f2c
[]
no_license
numbersinmotion/numbersinmotion_of_v0.9.8
816e597de75bfd2df2903e0cf40e8d3cb8457ac1
bd27852af1b90fba6c6ce7ff6b00e8f24624d214
refs/heads/master
2020-03-31T03:21:54.269361
2018-10-06T17:07:36
2018-10-06T17:07:36
151,862,199
0
0
null
null
null
null
UTF-8
C++
false
false
4,505
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ countFrames = 100; saveFrames = false; ofSetFrameRate(30); framePad = 1.25; countPoints = 1000; noiseResolution = 2; offsetRadius = 0; minZoom = 1; maxZoom = 3; img.load("images/image_01.png"); ofPixels pixelData = img.getPixels(); myTexture.allocate(pixelData); myTexture.bind(); for (int i = 0; i < countPoints; i++) { float x = framePad * ofRandom(-ofGetWidth() / 2, ofGetWidth() / 2); float y = framePad * ofRandom(-ofGetHeight() / 2, ofGetHeight() / 2); triangulation.addPoint(ofPoint(x,y)); } triangulation.triangulate(); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); sceneRatio = (float(ofGetFrameNum()) - 1) / countFrames; ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); vector<ofMeshFace> faces = triangulation.triangleMesh.getUniqueFaces(); ofSetColor(255); for (int i = 0; i < faces.size(); i++) { ofMeshFace face = faces[i]; ofPoint p0 = face.getVertex(0); ofPoint p1 = face.getVertex(1); ofPoint p2 = face.getVertex(2); ofPoint centroid = ofPoint((p0.x + p1.x + p2.x) / 3, (p0.y + p1.y + p2.y) / 3) * 1.25; ofPoint transTexToCenter = ofPoint(ofGetWidth() / 2, ofGetHeight() / 2); float thetaNoise = 3 * PI * ofxeasing::map(ofSignedNoise(p0.x / (noiseResolution * ofGetWidth()), p0.y / (noiseResolution * ofGetHeight())), -1, 1, -1, 1, ofxeasing::linear::easeInOut); ofPoint randOffset = ofPoint(offsetRadius * cos(thetaNoise + 2 * PI * sceneRatio), offsetRadius * sin(thetaNoise + 2 * PI * sceneRatio)); float scale = ofMap(sin(thetaNoise + 2 * PI * sceneRatio), -1, 1, minZoom, maxZoom); float rotate = 0 * thetaNoise; ofPoint t0 = (p0 - centroid).rotateRad(rotate, ofVec3f(0, 0, 1)) * scale + centroid; ofPoint t1 = (p1 - centroid).rotateRad(rotate, ofVec3f(0, 0, 1)) * scale + centroid; ofPoint t2 = (p2 - centroid).rotateRad(rotate, ofVec3f(0, 0, 1)) * scale + centroid; ofMesh newFace; newFace.addVertex(p0); newFace.addTexCoord(t0 + randOffset + transTexToCenter + ofPoint(100, 100)); newFace.addVertex(p1); newFace.addTexCoord(t1 + randOffset + transTexToCenter + ofPoint(100, 100)); newFace.addVertex(p2); newFace.addTexCoord(t2 + randOffset + transTexToCenter + ofPoint(100, 100)); newFace.draw(); } if (saveFrames) { if (ofGetFrameNum() < countFrames) { ofSaveViewport(ofToString(ofGetFrameNum() + 0 * countFrames, 4, '0') + ".png"); ofSaveViewport(ofToString(ofGetFrameNum() + 1 * countFrames, 4, '0') + ".png"); ofSaveViewport(ofToString(ofGetFrameNum() + 2 * countFrames, 4, '0') + ".png"); ofSaveViewport(ofToString(ofGetFrameNum() + 3 * countFrames, 4, '0') + ".png"); } else exit(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
5ca0205cb6da35e655ffbd411c4472587466b9d2
bdc27c22522a99b5bff2ec4cfa95fadcba65747d
/source/adios2/toolkit/shm/SerializeProcesses.cpp
146dc8046eeb721595b885b3262a7e36b5a709b7
[ "Apache-2.0" ]
permissive
ornladios/ADIOS2
a34e257b28adb26e6563b800502266ebb0c9088c
c8b7b66ed21b03bfb773bd972d5aeaaf10231e67
refs/heads/master
2023-08-31T18:11:22.186415
2023-08-29T20:45:03
2023-08-29T20:45:03
75,750,830
243
140
Apache-2.0
2023-09-14T11:15:00
2016-12-06T16:39:55
C++
UTF-8
C++
false
false
1,658
cpp
SerializeProcesses.cpp
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * SerializeProcesses.cpp * * Created on: Oct 12, 2021 * Author: Norbert Podhorszki pnorbert@ornl.gov */ #include "SerializeProcesses.h" #include <chrono> #include <thread> namespace adios2 { namespace shm { SerializeProcesses::SerializeProcesses(helper::Comm *comm) : m_NodeComm(comm), m_Rank(comm->Rank()), m_nProc(comm->Size()) { if (m_nProc > 1) { char *ptr; if (!m_Rank) { m_Win = m_NodeComm->Win_allocate_shared(sizeof(int), 1, &ptr); } else { m_Win = m_NodeComm->Win_allocate_shared(0, 1, &ptr); size_t shmsize; int disp_unit; m_NodeComm->Win_shared_query(m_Win, 0, &shmsize, &disp_unit, &ptr); } m_ShmValue = reinterpret_cast<int *>(ptr); if (!m_Rank) { *m_ShmValue = 0; } } else { m_ShmValue = new int; } }; SerializeProcesses::~SerializeProcesses() { if (m_nProc > 1) { m_NodeComm->Win_free(m_Win); } else { delete m_ShmValue; } } void SerializeProcesses::Wait() { while (*m_ShmValue != m_Rank) { std::this_thread::sleep_for(std::chrono::duration<double>(0.00001)); } } bool SerializeProcesses::IsMyTurn() { return (*m_ShmValue == m_Rank); } void SerializeProcesses::Done() { if (m_Rank < m_NodeComm->Size() - 1) { ++(*m_ShmValue); } else { *m_ShmValue = 0; } } } // end namespace shm } // end namespace adios2
d3ba3751bec5a1e845362442ff1a4de0492ebefb
84b82544af71f93c4e01e51603a250106d26f492
/src/Sensor.cpp
213b723d5d01b144d135c37a5bb3e8861e0ea020
[]
no_license
sonir/1509_tone-r2
96c4bd4e909314a7abbe077ce7a7f45c8e2cb7d1
e2e85ba9569202872740bceb060a452c5a14e03f
refs/heads/master
2016-09-11T09:17:03.722629
2015-09-05T21:35:36
2015-09-05T21:35:36
41,949,284
0
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
Sensor.cpp
// // Pd.cpp // tone_r2 // // Created by sonir on 9/5/15. // // #include "Sensor.h" //using namespace std; void Sensor::fireMessage(ofxOscMessage *m){ if(m->getAddress() == "/sensor_val"){ cout << "test" << endl; float fnum = m->getArgAsFloat(0); sys->test(); }else if(m->getAddress() == "/acs/motion"){ int round = m->getArgAsInt32(0); float spd = m->getArgAsFloat(1); sys->setSensorValue(spd, round); }else if(m->getAddress() == "/rec_sw"){ int flg = m->getArgAsInt32(0); if(flg)sys->rec(true); else sys->rec(false); } }
b53b76dfa15919db1da7fa0cb75358ae66e677ad
0ba8576e02f77c413dec6dccdfd85c1b76b356ba
/프로그래머스/프로그래머스-스킬트리.cpp
28a6fc421791048f21fa02001956a7ce22e22ee7
[]
no_license
ltnscp9028/C_plus_plus
2fb99fac7595c8cad34aecced4695849f4bfa50d
92d6d89e3250735c9ee7fc49ee0f1726bb9b2e2f
refs/heads/master
2022-04-30T08:22:49.036614
2022-04-19T20:28:21
2022-04-19T20:28:21
205,290,886
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
프로그래머스-스킬트리.cpp
#include<bits/stdc++.h> using namespace std; int i,le,sle,j,k; int solution(string s, vector<string> v) { int answer = 0; sle = s.length(); le = v.size(); for(i=0;i<le;i++){ vector<int>t; string str = v[i],tmp=""; int cnt = 0; for(cnt=j=0;j<str.length();j++) for(k=0;k<sle;k++)if(str[j]==s[k])tmp+=str[j]; for(j=0;j<tmp.length();j++)if(s[j]!=tmp[j])cnt++; if(cnt==0)answer++; } return answer; }
dd580a3f27c090d02f92ac678e1b5e697d1a7f3a
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/multimedia/directx/dxg/dd/ddraw/blitlib/blt0824p.hxx
b86ba9c5da3416231b463fa071298756783affc7
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
3,012
hxx
blt0824p.hxx
void Blt08to24P_NoBlend_NoTrans_Hcopy_SRCCOPY_Vcopy( BYTE* pbSrcScanLine, int iSrcScanStride, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, COLORREF* rgcrColor); void Blt08to24P_NoBlend_NoTrans_Hcopy_SRCCOPY_NoVcopy( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, COLORREF* rgcrColor); void Blt08to24P_NoBlend_NoTrans_NoHcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcCols, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, int iHorizMirror, COLORREF* rgcrColor); void Blt08to24P_NoBlend_Trans_Hcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, BYTE bTransparentIndex, COLORREF* rgcrColor); void Blt08to24P_NoBlend_Trans_NoHcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcCols, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, int iHorizMirror, BYTE bTransparentIndex, COLORREF* rgcrColor); void Blt08to24P_Blend_NoTrans_Hcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, ALPHAREF arAlpha, COLORREF* rgcrColor); void Blt08to24P_Blend_NoTrans_NoHcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcCols, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, int iHorizMirror, ALPHAREF arAlpha, COLORREF* rgcrColor); void Blt08to24P_Blend_Trans_Hcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, BYTE bTransparentIndex, ALPHAREF arAlpha, COLORREF* rgcrColor); void Blt08to24P_Blend_Trans_NoHcopy_SRCCOPY( BYTE* pbSrcScanLine, int iSrcScanStride, int iNumSrcCols, int iNumSrcRows, BYTE* pbDstScanLine, int iDstScanStride, int iNumDstCols, int iNumDstRows, int iHorizMirror, BYTE bTransparentIndex, ALPHAREF arAlpha, COLORREF* rgcrColor);
7a3f655067c34db3aec7cc59355ab4aeda5e7620
a078b20c748c9dafa9902588c0678e0ef757d426
/cross_section_data.cpp
0c0b8c9e925831f05944a46c2a2d87d644ffba09
[]
no_license
hemicuda71/MC-3
ed7f66e137a10cfe6bd11a9a33558fe03dd542bd
d03328355c6467c19a73e0d01081ae641c1cc875
refs/heads/master
2020-12-24T20:33:47.138406
2016-05-08T20:41:10
2016-05-08T20:41:10
58,330,438
0
0
null
null
null
null
UTF-8
C++
false
false
851
cpp
cross_section_data.cpp
// g++ -std=c++11 -O3 cross_section_data.cpp #include <iostream> #include <fstream> #include <iomanip> #include <cmath> #include <string> using namespace std; const double A1 = 4.15; const double A2 = 0.531; const double A3 = 67.3; double cross_section(double E) { double core = A1 - A2*log(E); double tail = 1.0 - exp(-A3/E); return log(core*core * pow(tail,4.5)); } int main(int argc, char* argv[]) { double Emin = 0.005, Emax = 250.0, E; string str(argv[1]); size_t sz; int Ne = std::stoi(str, &sz); //= argv[1]; //cout << Ne << endl; ofstream datafile("data.txt"); ofstream posfile("pos.txt"); for(int i = 0; i < Ne; i++) { E = Emin + (Emax-Emin) * i / double(Ne-1.0); posfile << setprecision(10) << E << endl; datafile << setprecision(10) << cross_section(E) << endl; } datafile.close(); posfile.close(); return 0; }
cd6e2cbbcbfaa2bc7c443fc8c99361884a9655c7
130ec5d1406aec24d1b7fc1bf0963f621098a71d
/Sierpinski.cpp
f54424918186672267723f02ab16cba938ca98ef
[]
no_license
reidmcy/OpenGL-Fractals
aec64bca62e1456b0b6190cea167d77000c0e138
63c6fd93fb166b4f7eda8437825d3f0bbabcd8c7
refs/heads/master
2021-01-21T13:49:20.080156
2015-05-08T20:29:18
2015-05-08T20:29:18
31,181,542
1
1
null
null
null
null
UTF-8
C++
false
false
2,437
cpp
Sierpinski.cpp
// // Sierpinski.cpp // Fractal // // Created by Reid on 2015-02-22. // Copyright (c) 2015 Reid. All rights reserved. // #include "Sierpinski.h" template <class T> bool withinCheck(T x, T min, T max) { //Helper function for iterator function if (x >= min && x <= max) { return true; } else { return false; } } template <class T> com<T> Spoint<T>::f(com<T> x) { T tmpR = pow(1 / (T) 3, this->iterations - 1); com<T> ret = x; if (withinCheck<T>(std::real(x), tmpR, 2 * tmpR) && withinCheck<T>(std::imag(x), tmpR, 2 * tmpR)) { return {2, 2}; } if(withinCheck<T>(std::real(x), tmpR, 2 * tmpR)){ ret = {std::real(x) - tmpR, std::imag(ret)}; } else if(withinCheck<T>(std::real(x), 2 * tmpR, 3 * tmpR)){ ret = {std::real(x) - 2 * tmpR, std::imag(ret)}; } if(withinCheck<T>(std::imag(x), tmpR, 2 * tmpR)){ ret = {std::real(ret), std::imag(x) - tmpR}; } else if(withinCheck<T>(std::imag(x), 2 * tmpR, 3 * tmpR)){ ret = {std::real(ret),std::imag(x) - 2 * tmpR}; } return ret; } template <class T> Sfield<T>::Sfield(int sx, int sy, bool square) : Field<T>(sx, sy, square, false) { T centx = sx / (T) 2; T centy = sy / (T) 2; if (square) { int dim = (sx < sy) ? sx : sy; T cent = dim / (T) 2; for (int y = 0; y < this->dimy; y++) { this->pfield[y] = new Spoint<T>[this->dimx]; for (int x = 0; x < this->dimx; x++) { if (std::abs( 2 * (x - centx)) > dim || std::abs(2 * (y - centy)) > dim) { this->pfield[y][x].makeExterior(); this->pfield[y][x].set(0,0); } else { this->pfield[y][x].set((x - centx) / centx, (y - centy) / centy, ((x - centx) / cent + 1) / 2,((y - centy) / cent + 1) / 2); } } } } else{ for (int y = 0; y < this->dimy; y++) { this->pfield[y] = new Spoint<T>[this->dimx]; for (int x = 0; x < this->dimx; x++) { this->pfield[y][x].set((x - centx) / centx, (y - centy) / centy, ((x - centx) / centx + 1) / 2,((y - centy) / centy + 1) / 2); } } } } template <class T> Sfield<T>::~Sfield() { for (int y = 0; y < this->dimy; y++) { delete [] this->pfield[y]; } } template class Spoint<double>; template class Sfield<double>;
b1a852bc025c7fff7341231614e5c49e7b612eee
55bfe899250607e99aa6ed20c5d688200ce4225f
/spot_real/Control/Teensy/SpotMiniMini/lib/ros_lib/moveit_msgs/ChangeControlDimensions.h
5442d70c4170eb3083a45697eb42eb0f7ae17d6d
[ "MIT" ]
permissive
OpenQuadruped/spot_mini_mini
96aef59505721779aa543aab347384d7768a1f3e
c7e4905be176c63fa0e68a09c177b937e916fa60
refs/heads/spot
2022-10-21T04:14:29.882620
2022-10-05T21:33:53
2022-10-05T21:33:53
251,706,548
435
125
MIT
2022-09-02T07:06:56
2020-03-31T19:13:59
C++
UTF-8
C++
false
false
6,437
h
ChangeControlDimensions.h
#ifndef _ROS_SERVICE_ChangeControlDimensions_h #define _ROS_SERVICE_ChangeControlDimensions_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace moveit_msgs { static const char CHANGECONTROLDIMENSIONS[] = "moveit_msgs/ChangeControlDimensions"; class ChangeControlDimensionsRequest : public ros::Msg { public: typedef bool _control_x_translation_type; _control_x_translation_type control_x_translation; typedef bool _control_y_translation_type; _control_y_translation_type control_y_translation; typedef bool _control_z_translation_type; _control_z_translation_type control_z_translation; typedef bool _control_x_rotation_type; _control_x_rotation_type control_x_rotation; typedef bool _control_y_rotation_type; _control_y_rotation_type control_y_rotation; typedef bool _control_z_rotation_type; _control_z_rotation_type control_z_rotation; ChangeControlDimensionsRequest(): control_x_translation(0), control_y_translation(0), control_z_translation(0), control_x_rotation(0), control_y_rotation(0), control_z_rotation(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_control_x_translation; u_control_x_translation.real = this->control_x_translation; *(outbuffer + offset + 0) = (u_control_x_translation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_x_translation); union { bool real; uint8_t base; } u_control_y_translation; u_control_y_translation.real = this->control_y_translation; *(outbuffer + offset + 0) = (u_control_y_translation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_y_translation); union { bool real; uint8_t base; } u_control_z_translation; u_control_z_translation.real = this->control_z_translation; *(outbuffer + offset + 0) = (u_control_z_translation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_z_translation); union { bool real; uint8_t base; } u_control_x_rotation; u_control_x_rotation.real = this->control_x_rotation; *(outbuffer + offset + 0) = (u_control_x_rotation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_x_rotation); union { bool real; uint8_t base; } u_control_y_rotation; u_control_y_rotation.real = this->control_y_rotation; *(outbuffer + offset + 0) = (u_control_y_rotation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_y_rotation); union { bool real; uint8_t base; } u_control_z_rotation; u_control_z_rotation.real = this->control_z_rotation; *(outbuffer + offset + 0) = (u_control_z_rotation.base >> (8 * 0)) & 0xFF; offset += sizeof(this->control_z_rotation); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_control_x_translation; u_control_x_translation.base = 0; u_control_x_translation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_x_translation = u_control_x_translation.real; offset += sizeof(this->control_x_translation); union { bool real; uint8_t base; } u_control_y_translation; u_control_y_translation.base = 0; u_control_y_translation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_y_translation = u_control_y_translation.real; offset += sizeof(this->control_y_translation); union { bool real; uint8_t base; } u_control_z_translation; u_control_z_translation.base = 0; u_control_z_translation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_z_translation = u_control_z_translation.real; offset += sizeof(this->control_z_translation); union { bool real; uint8_t base; } u_control_x_rotation; u_control_x_rotation.base = 0; u_control_x_rotation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_x_rotation = u_control_x_rotation.real; offset += sizeof(this->control_x_rotation); union { bool real; uint8_t base; } u_control_y_rotation; u_control_y_rotation.base = 0; u_control_y_rotation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_y_rotation = u_control_y_rotation.real; offset += sizeof(this->control_y_rotation); union { bool real; uint8_t base; } u_control_z_rotation; u_control_z_rotation.base = 0; u_control_z_rotation.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->control_z_rotation = u_control_z_rotation.real; offset += sizeof(this->control_z_rotation); return offset; } const char * getType(){ return CHANGECONTROLDIMENSIONS; }; const char * getMD5(){ return "64c0dd6d519e78f5ce2626b06dab34c1"; }; }; class ChangeControlDimensionsResponse : public ros::Msg { public: typedef bool _success_type; _success_type success; ChangeControlDimensionsResponse(): success(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.real = this->success; *(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF; offset += sizeof(this->success); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.base = 0; u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->success = u_success.real; offset += sizeof(this->success); return offset; } const char * getType(){ return CHANGECONTROLDIMENSIONS; }; const char * getMD5(){ return "358e233cde0c8a8bcfea4ce193f8fc15"; }; }; class ChangeControlDimensions { public: typedef ChangeControlDimensionsRequest Request; typedef ChangeControlDimensionsResponse Response; }; } #endif
8531e99a49b6170989b74c24c45a0d447248c92c
9ab802db7b2e693f4f3f1e5c3a010d3c5587261a
/src/master/master.cc
fa6b9e05b8156725a6b9a5a4144929eab005522e
[]
no_license
atemaguer/chunky
3f8b2a7f8747c0e66adef281528b0fe4a0a9e471
ef3f9e19f1adffb4ae9bb4ebbaa712c139250fa4
refs/heads/master
2022-10-23T20:30:59.699574
2020-06-12T17:27:54
2020-06-12T17:27:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,742
cc
master.cc
#include <chrono> #include <iostream> #include <memory> #include <string> #include <thread> #include <grpcpp/grpcpp.h> #include "src/protos/master/master.grpc.pb.h" #include "absl/flags/flag.h" #include "absl/flags/usage.h" #include "absl/flags/parse.h" #include "src/master/master_grpc.h" #include "src/master/master_track_chunkservers.h" ABSL_FLAG(std::string, self_ip, "0.0.0.0", "my ip"); ABSL_FLAG(std::string, self_port, "50052", "my port"); // Print Current Time void print_time_point(std::chrono::system_clock::time_point timePoint) { std::time_t timeStamp = std::chrono::system_clock::to_time_t(timePoint); std::cout << std::ctime(&timeStamp) << std::endl; } void RunServer(MasterTrackChunkservers* trackchunkservers) { std::string my_ip = absl::GetFlag(FLAGS_self_ip); std::string my_port = absl::GetFlag(FLAGS_self_port); std::string my_address = my_ip + ":" + my_port; std::cout << "Master's own address: " << my_address << std::endl; MasterServiceImpl service(trackchunkservers); ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(my_address, grpc::InsecureServerCredentials()); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to an *synchronous* service. builder.RegisterService(&service); // Finally assemble the server. std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Master Server listening on " << my_address << std::endl; // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); } void PrintState(MasterTrackChunkservers *trackchunkservers) { // Query the last-heard times of all chunkservers while(true) { std::cout << "Printing state" << std::endl; /* trackchunkservers->show_last_heard(); */ trackchunkservers->show_master_state_view(); std::this_thread::sleep_for (std::chrono::milliseconds(100)); } } int main(int argc, char **argv) { absl::SetProgramUsageMessage("A master that receives messages from chunkservers"); // Parse command line arguments absl::ParseCommandLine(argc, argv); // Create implementation class std::cout << "Creating MasterTrackChunkServers in master" << std::endl; MasterTrackChunkservers trackchunkservers(3); // Begin the server in a separate thread std::thread th(&RunServer, &trackchunkservers); // Begin the state printer in a separate thread std::thread thread_state_print(&PrintState, &trackchunkservers); // Wait for the server to exit std::cout << "Waiting for the server to exit" << std::endl; th.join(); return 0; }
cd756d6a4e0cb351757cdc8a779d449104eba567
5ab7032615235c10c68d738fa57aabd5bc46ea59
/average.cpp
d1185b62edf795a3f59860e92ed1a078fe812e04
[]
no_license
g-akash/spoj_codes
12866cd8da795febb672b74a565e41932abf6871
a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0
refs/heads/master
2021-09-07T21:07:17.267517
2018-03-01T05:41:12
2018-03-01T05:41:12
66,132,917
2
0
null
null
null
null
UTF-8
C++
false
false
1,009
cpp
average.cpp
#include <iostream> #include <vector> //#include <unordered_map> #include <string> #include <math.h> //#include <map> #include <queue> #include <stack> #include <algorithm> #include <list> using namespace std; #define ll long long int #define ull unsigned ll #define umm(x,y) unordered_map<x,y > #define mm(x,y) map<x,y > #define pb push_back #define foi(n) for(int i=0;i<n;i++) #define foj(n) for(int j=0;j<n;j++) #define foi1(n) for(int i=1;i<=n;i++) #define foj1(n) for(int j=1;j<=n;j++) #define vi vector<int> #define vb vector<bool> #define vvi vector<vi > #define vvb vector<vb > #define vll vector<ll> #define vvll vector<vll > #define si size() int main() { int n,var; cin>>n; vi vec(n); foi(n) { cin>>var; vec[i]=var; } sort(vec.begin(),vec.end()); int ans=0; foi(n) { int tmp = 2*vec[i],x=0,y=n-1; while(y-x>=1) { if(vec[x]+vec[y]==tmp) { ans++; break; } else if(vec[x]+vec[y]>tmp) { y--; } else x++; } } cout<<ans<<endl; }
cd78698f81b11f80540e533f5825024d776ccb05
071b24c51c9114200e743806919160cac6ccdeb1
/advanced/1088/Run2.cpp
849b6b708bd29adf8170b393c1d4f446f78f8249
[]
no_license
CJeffrey/PAT
afcd9993a2a7570f5c986deb0936b7a82c1f4abc
33c94f481c0a07d7cb5274db953fac6da11d8278
refs/heads/master
2021-01-22T04:36:49.014554
2015-02-07T11:58:21
2015-02-07T11:58:21
28,181,181
0
0
null
null
null
null
UTF-8
C++
false
false
991
cpp
Run2.cpp
#include <cstdio> int gcd(int a, int b) { if (a == 0 || b == 0) return a > b ? a : b; for (int t; t = a % b; a = b, b = t); return b; } void simplify(int &a, int &b) { int x = gcd(a<0 ? -a : a, b); a /= x, b /= x; } void f(int a, int b) { if (b == 0) { printf("Inf"); return; } if (b < 0) a = -a, b = -b; simplify(a, b); bool flag = 0; if (a < 0) a = -a, flag = 1; if (flag) printf("(-"); if (a % b == 0) printf("%d", a / b); else if (a < b) printf("%d/%d", a, b); else printf("%d %d/%d", a / b, a % b, b); if (flag) printf(")"); } int main2() { int a1, b1, a2, b2; scanf("%d/%d %d/%d", &a1, &b1, &a2, &b2); f(a1, b1); printf(" + "); f(a2, b2); printf(" = "); f(a1*b2+a2*b1, b1*b2); printf("\n"); f(a1, b1); printf(" - "); f(a2, b2); printf(" = "); f(a1*b2-a2*b1, b1*b2); printf("\n"); f(a1, b1); printf(" * "); f(a2, b2); printf(" = "); f(a1*a2, b1*b2); printf("\n"); f(a1, b1); printf(" / "); f(a2, b2); printf(" = "); f(a1*b2, a2*b1); printf("\n"); return 0; }
8a01415ebaeb812f5edc43cd6c8ba1086aba4c68
e572189d60a70df27b95fc84b63cc24048b90d09
/bjoj/2562.cpp
794b0b521c648ad4564c6e5d6e369efa03f0f789
[]
no_license
namhong2001/Algo
00f70a0f6132ddf7a024aa3fc98ec999fef6d825
a58f0cb482b43c6221f0a2dd926dde36858ab37e
refs/heads/master
2020-05-22T12:29:30.010321
2020-05-17T06:16:14
2020-05-17T06:16:14
186,338,640
0
0
null
null
null
null
UTF-8
C++
false
false
281
cpp
2562.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int N = 9; vector<int> arr(N); for (int i=0; i<N; ++i) cin >> arr[i]; auto m = max_element(arr.begin(), arr.end()); cout << *m << '\n'; cout << m - arr.begin() + 1; return 0; }
d8a01017a4983571bb57eb511e54739addcff561
a4e96191599d3cc915e18167891dc8d9363b5d9a
/opengl-vs/Project1/Mesh.h
bcf71fd5bbabc4f18608ac6f88bd92386431224a
[]
no_license
LixinSy/opengl
8ea52864f56aaab357b5a371f6e2f607a31c9ba6
e3d03428dee02edd85067bf98c5ba1cbb79f4d7e
refs/heads/master
2020-03-22T05:37:40.686382
2018-07-03T12:24:05
2018-07-03T12:24:05
139,579,660
2
0
null
null
null
null
GB18030
C++
false
false
1,117
h
Mesh.h
#ifndef MESH_H #define MESH_H #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace std; #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "Shader.h" struct Vertex { //顶点 glm::vec3 position; glm::vec3 normal; glm::vec2 texCoords; }; struct Texture { //文理 GLuint id; string type; aiString path; }; struct Material // 表示材质属性 { glm::vec3 ambient; glm::vec3 diffuse; glm::vec3 specular; float shininess; vector<Texture> textures; }; class Mesh { public: Mesh(vector<Vertex> vertices, vector<GLuint> indices, vector<Texture> textures); ~Mesh(); //渲染mesh void Draw(); void setShader(Shader shader); Shader getShader(); void tranlate(); void rotate(); void scale(); //private: // 初始化VAO,VBO,EBO void setupMesh(); Shader shader; vector<Vertex> vertices; vector<GLuint> indices; vector<Texture> textures; GLuint VAO, VBO, EBO; }; #endif
1cb835fa768e8455598cf7c0d31fb2a03c1cba3e
bcf2032393a1d1384c779f64ca9744124cab5446
/Licenta/Last/Motorscontrol/Motorscontrol.cpp
fa0734f2ef962739edef683b82824495c3ea3942
[]
no_license
raul7alex/Arduino
346b72a27d177a12e3975cd760ab44cf65f21333
4d525bab21b6300dd5ddadc497bb003e30714dce
refs/heads/master
2020-05-02T21:15:01.324386
2019-03-28T14:09:50
2019-03-28T14:09:50
178,214,928
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
Motorscontrol.cpp
#include "Motorscontrol.h" #include "Arduino.h" Motorscontrol::Motorscontrol(int motorPin, int in1, int in2, int speed) { _motorPin=motorPin; _in1=in1; _in2=in2; _speed=speed; pinMode(_motorPin, OUTPUT); pinMode(_in1, OUTPUT); pinMode(_in2, OUTPUT); } void Motorscontrol::stop(){ analogWrite(_motorPin,0); digitalWrite(_in1, LOW); digitalWrite(_in2, LOW); } void Motorscontrol::forward(int _speed) { analogWrite(_motorPin,_speed); digitalWrite(_in1, LOW); digitalWrite(_in2, HIGH); } void Motorscontrol::backward(int _speed) { analogWrite(_motorPin,_speed); digitalWrite(_in1, HIGH); digitalWrite(_in2, LOW); }
72a6add45196ccff1ec4c36af62687b9dc7e0300
cd72b19d2030f36f78dab52390d092ed3dc8005f
/apps/src/libvideostitch-gui/mainwindow/timeconverter.cpp
36624d7af369e9fe0c872f98c8b161de78ba8318
[ "MIT", "DOC" ]
permissive
stitchEm/stitchEm
08c5a3ef95c16926c944c1835fdd4ab4b6855580
4a0e9fc167f10c7dde46394aff302927c15ce6cb
refs/heads/master
2022-11-27T20:13:45.741733
2022-11-22T17:26:07
2022-11-22T17:26:07
182,059,770
250
68
MIT
2022-11-22T17:26:08
2019-04-18T09:36:54
C++
UTF-8
C++
false
false
3,447
cpp
timeconverter.cpp
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "timeconverter.hpp" #include "libvideostitch/logging.hpp" #include <QStringList> #include <cmath> QString TimeConverter::frameToTimeDisplay(const frameid_t currentFrame, VideoStitch::FrameRate frameRate) { if ((currentFrame == -1) || (frameRate.num <= 0) || (frameRate.den == 0)) { return "-1"; } const qint64 seconds = (currentFrame * frameRate.den) / frameRate.num; const QString secondsStr = QString("%0").arg(seconds % 60, 2, 10, QLatin1Char('0')); const qint64 minutes = seconds / 60; const QString minutesStr = QString("%0").arg(minutes % 60, 2, 10, QLatin1Char('0')); const qint64 remainder = currentFrame - ceil((seconds * frameRate.num) / double(frameRate.den)); const QString framesStr = QString("%0").arg(remainder, 2, 10, QLatin1Char('0')); QString ret = minutesStr + ":" + secondsStr + ":" + framesStr; const int hours = minutes / 60; if (hours > 0) { ret = QString::number(hours) + ":" + ret; } return ret; } QString TimeConverter::dateToTimeDisplay(const mtime_t currentDate) { if (currentDate == -1) { return "-1"; } const qint64 seconds = currentDate / 1000000; const QString secondsStr = QString("%0").arg(seconds % 60, 2, 10, QLatin1Char('0')); const qint64 minutes = seconds / 60; const QString minutesStr = QString("%0").arg(minutes % 60, 2, 10, QLatin1Char('0')); const qint64 remainderInMicroSeconds = currentDate - seconds * 1000000; const QString framesStr = QString("%0").arg(remainderInMicroSeconds / 10000, 2, 10, QLatin1Char('0')); QString ret = minutesStr + ":" + secondsStr + ":" + framesStr; const int hours = minutes / 60; if (hours > 0) { QString hoursStr = QString::number(hours); ret = hoursStr + ":" + ret; } return ret; } frameid_t TimeConverter::timeDisplayToFrame(const QString time, VideoStitch::FrameRate frameRate, bool* ok) { if (time == "0") { return 0; } if (time == "-1") { return -1; } QStringList elements = time.split(":"); if (elements.size() < 3) { return 0; } // Partial time, complete with 00 for (int i = 0; i < elements.size(); ++i) { if (elements.at(i).isEmpty()) { elements[i] = "00"; } } // Parse the frame number double frameNumber = elements.last().toDouble(ok); if (ok && !*ok) { return 0; } elements.pop_back(); // Parse the seconds double seconds = elements.last().toDouble(ok); if (ok && !*ok) { return 0; } elements.pop_back(); // Parse the minutes seconds += elements.last().toDouble(ok) * 60.0; if (ok && !*ok) { return 0; } elements.pop_back(); // Parse the hours, if there are... if (elements.size()) { seconds += elements.last().toDouble(ok) * 3600.0; if (ok && !*ok) { return 0; } elements.pop_back(); } frameNumber += seconds * double(frameRate.num) / double(frameRate.den); return ceil(frameNumber); } bool TimeConverter::isLongerThanAnHour(const frameid_t curFrame, VideoStitch::FrameRate frameRate) { return frameToTimeDisplay(curFrame, frameRate).split(":").size() >= 4; } int TimeConverter::numberOfDigitsOfIntegerPart(VideoStitch::FrameRate frameRate) { return QString::number(std::floor(frameRate.num / frameRate.den)).size(); } bool TimeConverter::hasMoreThanThreeIntDigits(VideoStitch::FrameRate frameRate) { return numberOfDigitsOfIntegerPart(frameRate) >= 3; }
83476045cf98a4818e6a3e98f4f1a5a0b13704a2
51074c73a23bba8a62b422908bb2730319823e25
/TCPClient/main.cpp
ba4fe0f70b1031a1515154c893d9015baadd3170
[]
no_license
Noon-R/TCPTest
50701e67e3c03ea196bcd2e5a4bc72c86fe6e38a
66ead8b45cf87609ebe29b1463b7787bd4382d9c
refs/heads/master
2023-05-03T04:53:23.366011
2021-05-30T10:26:58
2021-05-30T10:26:58
372,184,621
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,172
cpp
main.cpp
#include <stdio.h> #include <Windows.h> #include <winsock2.h> #include <ws2tcpip.h> #define PORT 8000 //接続に使うポート番号(サーバークライアント共通) #define MAX_BUF_SIZE 32 //受信するメッセージの最大文字数 int main () { WSADATA wsaData; //winsock情報を保管 struct sockaddr_in server_addr; //サーバーのipアドレスとポート番号情報格納 SOCKET sock; //クライアントのソケット char buf[MAX_BUF_SIZE]; //受信したメッセージを格納 //winsock2の初期化 WSAStartup (MAKEWORD (2, 0), &wsaData); //ソケットの作成 sock = socket (AF_INET, SOCK_STREAM, 0); //接続先指定用構造体の準備 server_addr.sin_family = AF_INET; server_addr.sin_port = htons (PORT); InetPton (AF_INET, ("127.0.0.1"), &server_addr.sin_addr.s_addr); //サーバに接続 connect (sock, (struct sockaddr*) & server_addr, sizeof (server_addr)); //サーバからデータを受信 memset (buf, 0, sizeof (buf)); recv (sock, buf, sizeof (buf), 0); printf ("%s\n", buf); //winsock2の終了 WSACleanup (); return 0; }
145148ed94966763ff5c0322a8dfaf6bc4ba74ba
51835b8233eccfb53cffe96c071fc6fcf3d84f9b
/src/ClassFilter.cpp
2349bb18d1d10edd3aac80d5ea81e48ba7d94a8d
[ "MIT" ]
permissive
GoldbergData/newWorldSimulation
eda3dc31df52c15ff19c3cb78a0001f1ac0bd6c3
9534592ac2c9f5909bd0aba126fa678a40cf0408
refs/heads/main
2023-05-15T02:14:00.805514
2021-06-18T02:46:05
2021-06-18T02:46:05
373,677,715
0
0
MIT
2021-06-09T03:14:35
2021-06-04T00:32:16
C++
UTF-8
C++
false
false
1,706
cpp
ClassFilter.cpp
/** * @file ClassFilter.cpp * @author John Nguyen, Joshua Goldberg (jvn1567@gmail.com, J.GOLDBERG4674@edmail.edcc.edu) * @version 0.1 * @date 2021-06-12 * * @copyright Copyright (c) 2021 * */ #include "ClassFilter.h" #include "Orbits.h" #include "Planet.h" #include "Star.h" #include "ToxicWasteland.h" #include "IceWorld.h" #include "PurpleGas.h" #include "RockSlide.h" #include "Greenhouse.h" #include "Zed.h" #include "Patawlian.h" #include "PinkGoblin.h" #include "Saveela.h" void initializeSpaceObject(string type, SpaceObject** spaceObject, Movesets moveset) { if (type == "Star") { *spaceObject = new Star(); } else if (type == "Planet") { *spaceObject = new Planet(moveset); } else if (type == "ToxicWasteland") { *spaceObject = new ToxicWasteland(moveset); } else if (type == "IceWorld") { *spaceObject = new IceWorld(moveset); } else if (type == "PurpleGas") { *spaceObject = new PurpleGas(moveset); } else if (type == "RockSlide") { *spaceObject = new RockSlide(moveset); } else if (type == "Greenhouse") { *spaceObject = new Greenhouse(moveset); } else { *spaceObject = nullptr; } } void initializeAlienBase(string type, AlienBase** alienBase) { if (type == "AlienBase") { *alienBase = new AlienBase(); } else if (type == "Zed") { *alienBase = new Zed(); } else if (type == "Patawlian") { *alienBase = new Patawlian(); } else if (type == "PinkGoblin") { *alienBase = new PinkGoblin(); } else if (type == "Saveela") { *alienBase = new Saveela(); } else { *alienBase = nullptr; } }
2d0b6f094630468336c1d0fa5fb3ac1c2a617fbb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_3064_httpd-2.2.0.cpp
f8c469b1ca8925c525e6a58195f21a8153a75077
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,825
cpp
httpd_repos_function_3064_httpd-2.2.0.cpp
int parse_output_file_name(char *arg, command_t *cmd_data) { char *name = strrchr(arg, '/'); char *ext = strrchr(arg, '.'); char *newarg = NULL; int pathlen; cmd_data->fake_output_name = arg; if (name) { name++; } else { name = strrchr(arg, '\\'); if (name == NULL) { name = arg; } else { name++; } } if (!ext) { cmd_data->basename = arg; cmd_data->output = otProgram; #if defined(_OSD_POSIX) cmd_data->options.pic_mode = pic_AVOID; #endif newarg = (char *)malloc(strlen(arg) + 5); strcpy(newarg, arg); #ifdef EXE_EXT strcat(newarg, EXE_EXT); #endif cmd_data->output_name = newarg; return 1; } ext++; pathlen = name - arg; if (strcmp(ext, "la") == 0) { assert(cmd_data->mode == mLink); cmd_data->basename = arg; cmd_data->static_name.normal = gen_library_name(arg, 0); cmd_data->shared_name.normal = gen_library_name(arg, 1); cmd_data->module_name.normal = gen_library_name(arg, 2); cmd_data->static_name.install = gen_install_name(arg, 0); cmd_data->shared_name.install = gen_install_name(arg, 1); cmd_data->module_name.install = gen_install_name(arg, 2); #ifdef TRUNCATE_DLL_NAME if (shared) { arg = truncate_dll_name(arg); } #endif cmd_data->output_name = arg; return 1; } if (strcmp(ext, "lo") == 0) { cmd_data->basename = arg; cmd_data->output = otObject; newarg = (char *)malloc(strlen(arg) + 2); strcpy(newarg, arg); ext = strrchr(newarg, '.') + 1; strcpy(ext, OBJECT_EXT); cmd_data->output_name = newarg; return 1; } return 0; }
3c9670d289fc5b1eb2b98e02616054907d388160
d0a5a6e3f5f57a537bce6c4b9cf60e92923ca756
/Practice/LAPIN/a.cpp
cfadd8c4b1ad745b72c2b7fa0b1afb2cb8c87a4e
[]
no_license
bbackspace/codechef
0c8435b839296e727e1030c90b0420509374823f
8cea9d903eb79b534a507facbbedb70b489526e2
refs/heads/master
2016-09-06T00:32:52.923699
2015-06-19T12:50:13
2015-06-19T12:50:13
28,696,031
1
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
a.cpp
#include<stdio.h> int freq[26]; char a[1001]; int T, i, flag; int main() { scanf("%d ", &T); while(T--) { scanf("%s ", a); for(i = 0; i < 26; i++) freq[i] = 0; for(i = 0; i < strlen(a) / 2; i++) freq[a[i] - 'a']++; for(i = (strlen(a) + 1) / 2; a[i]; i++) freq[a[i] - 'a']--; flag = 0; for(i = 0; i < 26; i++) if(freq[i] != 0) { flag = 1; break; } if(!flag) write(1, "YES\n", 4); else write(1, "NO\n", 3); } return 0; }
833a0cdbbab5140b012d4c6be7597ecfa4e91ab9
e23eaec0adcce9069c19c6cca072785776f1ddfb
/Interview Play CPP/a1196HowManyApplesCanYouPutintotheBasket.cpp
5f615197ac805e492637cbb887d39f9ed98ae6eb
[]
no_license
rjtsdl/CPlusPlus
a4703ba11bcd4a918fa9b20d4de44cf9e021ebf6
a5e8f14716dc1edf975039393fa3a653b406a8c5
refs/heads/master
2021-09-08T07:49:47.998796
2021-09-03T18:05:01
2021-09-03T18:05:01
33,706,235
0
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
a1196HowManyApplesCanYouPutintotheBasket.cpp
// // a1196HowManyApplesCanYouPutintotheBasket.cpp // Interview Play CPP // // Created by Jingtao Ren on 9/25/20. // Copyright © 2020 Jingtao Ren. All rights reserved. // #include <stdio.h> #include <vector> using namespace std; class Solution { public: int maxNumberOfApples(vector<int>& arr) { int l = 0; int r = arr.size()-1; bool add = true; int totalsum = 0; while (l <= r){ int m = (l +r) / 2; nth_element(arr.begin()+l,arr.begin()+m,arr.begin()+r+1); if (add){ totalsum += currsum(arr,l,m); }else{ totalsum -= currsum(arr,m+1,r+1); } if (totalsum == 5000){ return m; }else if (totalsum < 5000){ add = true; l = m+1; }else{ add = false; r = m-1; } } return r+1; } int currsum (vector<int> & arr, int l, int m ){ int sum=0; for (int i =l;i<=m;i++)sum+= arr[i]; return sum; } };
94b22f949180d2b6f9880f36760a6ebf90b3ac19
a4b492a5093bb3745fe4d2c9ea96dc4ddeb3058e
/BikeWheel/BikeWheel.ino
1d526de3bab73b6151da22149eebecca6a392bed
[]
no_license
pariesz/BikeWheel
c6cc88656e1fe33e175ad60f19bd65fb4bffb775
ae0ffbb9d8c18048cd42ab1c939d23e91f59b797
refs/heads/master
2021-07-18T11:05:05.795667
2020-06-22T12:49:10
2020-06-22T12:49:10
181,702,406
0
0
null
null
null
null
UTF-8
C++
false
false
4,153
ino
BikeWheel.ino
/* Persistence of vision is a theory which attempts to explain how the human eye/brain can be "fooled" into seeing continuous motion when presented with a sequence of discrete still images (film or video frames) at a rate of 10 frames per second (fps) or greater. We have 4 stips so the wheel must turn 10/4 = 2.5 times a second. The is a rate of change og about 163 angle/ms. To stop flicker at the threashold we add a buffer zone. Turn on at ~360 deg/ms and off at ~450 deg/s. */ #define LOGGING 1 // When used as analog pins, the Arduino software uses a separate set of zero-based numbers, // so pin 0 (used with pinMode, digitalWrite, analogWrite, and digitalRead) is different than analog pin 0. #define BATTERY_PIN 0 #define BLUETOOTH Serial1 #include <shared.h> // 31 frames a second inline uint16_t get_frame_count() { return (millis() >> 5) & 0xFFFF; } uint16_t frame_count = get_frame_count(); Mpu mpu; MainProgram program; void setup(void) { #if LOGGING == 1 Serial.begin(9600); while (!Serial); log_val("Serial", F("Connected")); #endif BLUETOOTH.begin(9600); //pinMode(BATTERY_PIN, INPUT); // Get offsets calibrated using ../MPU6050 Calibration/MPU6050Calibration.ino int16_t mpu_offsets[] = { -1288, 979, 1242, // accl x, y, z 39, -17, 164 // gyro x, y, z }; mpu.setup(mpu_offsets); Leds::setup(144, 11, 13, DOTSTAR_BGR); } void loop(void) { mpu.update(); if (frame_count != get_frame_count()) { read_serial(); frame_count = get_frame_count(); program.update(mpu.get_rotation_rate()); } program.render(mpu.get_angle()); Leds::leds.show(); } uint8_t command = 0; SerialMessage* message = new SerialMessage(&BLUETOOTH); void read_serial() { while (BLUETOOTH.available()) { uint8_t ch = BLUETOOTH.read(); // only read whats available so its non-blocking if (command == 0) { free(message); message = new SerialMessage(&BLUETOOTH); command = ch; BLUETOOTH.write(command); // echo the command back log_val("cmd", ch); switch (command) { case CMD_SET_EEPROM: message = new EEPROMSetSerialMessage(&BLUETOOTH, &program); continue; case CMD_GET_EEPROM: message = new EEPROMGetSerialMessage(&BLUETOOTH); continue; case CMD_BATTERY: log_val("battery", analogRead(BATTERY_PIN)); BLUETOOTH.println(analogRead(BATTERY_PIN)); break; case CMD_ANGLE: log_val("angle", mpu.get_angle()); BLUETOOTH.println(mpu.get_angle()); break; case CMD_ROTATION_RATE: log_val("rotation rate", mpu.get_rotation_rate()); BLUETOOTH.println(mpu.get_rotation_rate()); break; case CMD_SET_MOVING_PROGRAM: message = new SetMovingProgramSerialMessage(&BLUETOOTH, &program); continue; case CMD_GET_MOVING_PROGRAM: log_val("moving program", program.getMovingProgram()); BLUETOOTH.println(program.getMovingProgram()); break; case CMD_SET_STATIONARY_PROGRAM: message = new SetStationaryProgramSerialMessage(&BLUETOOTH, &program); continue; case CMD_GET_STATIONARY_PROGRAM: log_val("stationary program", program.getStationaryProgram()); BLUETOOTH.println(program.getStationaryProgram()); break; default: log_val("command err", ch); BLUETOOTH.println("err"); break; } } else if (!message->consume(ch)) { continue; } // command has been executed, clear it command = 0; } }
f3ab04b93889645dec2ff8b0b9f23dec4cce7b5f
0b70aa790b9646617f7b61b74e767d402379b212
/main.cpp
a3a05884232f26d35348c99cd923da7a321a15ff
[]
no_license
jaldouseri/BigInt
f201ad7658ddbfaf3b957443e586ac540554e205
11477b825b6a6837b0b8c290f1e22aa8acbe013a
refs/heads/main
2023-02-18T18:38:42.961823
2021-01-18T05:20:47
2021-01-18T05:20:47
329,755,205
0
0
null
null
null
null
UTF-8
C++
false
false
3,806
cpp
main.cpp
#include <cstdlib> #include <iostream> #include <string> #include <iomanip> #include "BigInt.h" using namespace std; int main() { BigInt a, b, c, d, e, f, g, h; int i=-7; bool bo = true; a = "123456922434343"; b = "-12"; // 15 c = "-343433336433333333333433333333333333333344333"; // 17 d = "-3000000000000000000000000000000000000000000000000000000000000000000000000000000"; e = "0"; f = "-1"; g = "-123456922434343"; h = "4"; cout << " a: " << a << endl << " b: " << b << endl << " c: " << c << endl; cout << " d: " << d << endl << " e: " << e << endl << " f: " << f << endl; cout << " g: " << g << endl; if (b <= a) cout << " b <= a true " << endl; else cout << " b <= a false " << endl; if (a - b >= e) cout << " a - b > e true " << endl; else cout << " a - b > e false " << endl; cout << endl << endl; cout << " a + b : " << a + b << endl; cout << " a - b : " << a - b << endl; cout << " b - d : " << b - d << endl; cout << " c * b : " << c * b << endl; cout << " c * d : " << c * d << endl; cout << " a / b : " << a / b << endl; cout << " b / a : " << b / a << endl; cout << " e / a : " << e / a << endl; cout << " d / g : " << d / g << endl; cout << " d / b : " << d / b << endl; cout << " a % b : " << a % b << endl; cout << " b % a : " << b % a << endl; cout << " e % a : " << e % a << endl; cout << " d % g : " << d % g << endl; cout << " d % b : " << d % b << endl; cout << " a.BigIntToBinary : " << a.BigIntToBinary() << endl; cout << " b.BigIntToBinary : " << b.BigIntToBinary() << endl; cout << " c.BigIntToBinary : " << c.BigIntToBinary() << endl; cout << " d.BigIntToBinary : " << d.BigIntToBinary() << endl; cout << " e.BigIntToBinary : " << e.BigIntToBinary() << endl; cout << " f.BigIntToBinary : " << f.BigIntToBinary() << endl; cout << " g.BigIntToBinary : " << g.BigIntToBinary() << endl << endl; cout << " a.BinaryToBigInt : " << a.BinaryToBigInt("11100000100100010001110000000011011101100100111") << endl; cout << " b.BinaryToBigInt : " << b.BinaryToBigInt("1100") << endl; cout << " c.BinaryToBigInt : " << c.BinaryToBigInt("1111011001100110101111011101111111011100011011111010000010010001101111001110010100111111011000000001001101011011100001001011110101011000000001001101") << endl; cout << " d.BinaryToBigInt : " << d.BinaryToBigInt("110011110100010010011110100111100100010011111011001010111000000100100101010100000001110111001011101000101011010001100100110100101011111111101110111100111011011110001000110101010111011000000000000000000000000000000000000000000000000000000000000000000000000000000") << endl; cout << " e.BinaryToBigInt : " << e.BinaryToBigInt("0") << endl; cout << " f.BinaryToBigInt : " << f.BinaryToBigInt("1") << endl; cout << " g.BinaryToBigInt : " << g.BinaryToBigInt("11100000100100010001110000000011011101100100111") << endl; cout << endl; f = a << h; cout << " a << 4 : " << f << endl; f = b << h; cout << " b << 4 : " << f << endl; f = c << 4; cout << " c << 4 : " << f << endl; f = d << 4; cout << " d << 4 : " << f << endl; f = e << 4; cout << " e << 4 : " << f << endl; cout << endl; f = a >> h; cout << " a >> 4 : " << f << endl; f = b >> h; cout << " b >> 4 : " << f << endl; f = c >> h; cout << " c >> 4 : " << f << endl; f = d >> 4; cout << " d >> 4 : " << f << endl; f = e >> 4; cout << " e >> 4 : " << f << endl; cout << endl; cout << " a.pow(g) : " << a.pow(g) << endl; cout << " a.pow(b) : " << a.pow(b) << endl; return 0; }
0ee12a12faf58859cff5d6c44c30be87f7a9877f
b27ed8aacb480f8dfbb224fadb8c163ef66be3ce
/2. Filters/FilterTests/AllpassFilterTests.cpp
fdc4c47dc67d962598b3256867c2674accf0bfcb
[]
no_license
Sinecure-Audio/TestsTalk
a8dd63d9aa8b168ffc31681048c9b9aed83d57b8
f460bb010044f185dfd3509f2ec67d0221e68763
refs/heads/main
2023-01-27T16:09:31.398300
2020-12-07T15:45:10
2020-12-07T15:45:10
314,315,859
17
0
null
2020-12-07T15:45:11
2020-11-19T17:06:25
C++
UTF-8
C++
false
false
1,984
cpp
AllpassFilterTests.cpp
#include <catch2/catch.hpp> #include "../../Utilities/Random.h" #include "../Signal Analysis/FFT/FFT.h" #include "../../Utilities/DecibelMatchers.h" #include "../FilterMeasurementUtilities.h" //Test the spectrum shape and gain of an allapss filter // TODO: check why using references in the test context for the noise stuff // doesn't work in just this test TEMPLATE_TEST_CASE("Allpass Filter Spectrum Shape", "[Allpass Filter] " "[Filter]", float, double) { using SampleType = TestType; //Initialize the filter and noise we'll use in the test auto testContext = getFilterContext<juce::dsp::IIR::Filter<SampleType>, FilterResponse::Allpass, SampleType>(); //Set the tolerance to something tighter than normal testContext.tolerance = Decibel{SampleType{-1.5}}; constexpr auto FFTSize = testContext.SpectrumSize/2; //Get the buffer a generate its spectrum const auto inputNoiseSpectrum = makeSpectrum<SampleType, 1024>(testContext.noiseBuffer); //Get the spectrum of the noise run through the filter const auto filteredSpectrum = getFilteredSpectrum<SampleType>(testContext.fft, testContext.noiseBuffer, testContext.filter); // For every bin in the buffer, // get the difference between the input and output levels // And check to see if they're within the threshold for (size_t i = 0; i < FFTSize/2; ++i) { const auto noiseLevel = Decibel{Amplitude{inputNoiseSpectrum[i].getAverage()}}; const auto filteredLevel = Decibel{Amplitude{filteredSpectrum[i].getAverage()}}; REQUIRE_THAT(noiseLevel, WithinDecibels(filteredLevel, testContext.tolerance)); } }
82726cb592d5183b54560a46465f11b0111d0060
2f557f60fc609c03fbb42badf2c4f41ef2e60227
/RecoLocalTracker/SiPixelRecHits/interface/SiPixelTemplateReco2D.h
675cb10767dd9f0cbd12de3be7e8d302af0563c7
[ "Apache-2.0" ]
permissive
CMS-TMTT/cmssw
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
refs/heads/TMTT_1060
2020-03-24T07:49:39.440996
2020-03-04T17:21:36
2020-03-04T17:21:36
142,576,342
3
5
Apache-2.0
2019-12-05T21:16:34
2018-07-27T12:48:13
C++
UTF-8
C++
false
false
2,301
h
SiPixelTemplateReco2D.h
// // SiPixelTemplateReco2D.cc (Version 2.60) // Updated to work with the 2D template generation code // 2.10 - Add y-lorentz drift to estimate starting point [for FPix] // 2.10 - Remove >1 pixel requirement // 2.20 - Fix major bug, change chi2 scan to 9x5 [YxX] // 2.30 - Allow one pixel clusters, improve cosmetics for increased style points from judges // 2.50 - Add variable cluster shifting to make the position parameter space more symmetric, // also fix potential problems with variable size input clusters and double pixel flags // 2.55 - Fix another double pixel flag problem and a small pseudopixel problem in the edgegflagy = 3 case. // 2.60 - Modify the algorithm to return the point with the best chi2 from the starting point scan when // the iterative procedure does not converge [eg 1 pixel clusters] // // // Created by Morris Swartz on 7/13/17. // // #ifndef SiPixelTemplateReco2D_h #define SiPixelTemplateReco2D_h 1 #ifndef SI_PIXEL_TEMPLATE_STANDALONE #include "CondFormats/SiPixelTransient/interface/SiPixelTemplateDefs.h" #include "CondFormats/SiPixelTransient/interface/SiPixelTemplate2D.h" #else #include "SiPixelTemplateDefs.h" #include "SiPixelTemplate2D.h" #endif #include <vector> #ifndef SiPixelTemplateClusMatrix2D #define SiPixelTemplateClusMatrix2D 1 namespace SiPixelTemplateReco2D { struct ClusMatrix { float & operator()(int x, int y) { return matrix[mcol*x+y];} float operator()(int x, int y) const { return matrix[mcol*x+y];} float * matrix; bool * xdouble; bool * ydouble; int mrow, mcol; }; #endif int PixelTempReco2D(int id, float cotalpha, float cotbeta, float locBz, float locBx, int edgeflagy, int edgeflagx, ClusMatrix & cluster, SiPixelTemplate2D& templ, float& yrec, float& sigmay, float& xrec, float& sigmax, float& probxy, float& probQ, int& qbin, float& deltay, int& npixel); int PixelTempReco2D(int id, float cotalpha, float cotbeta, float locBz, float locBx, int edgeflagy, int edgeflagx, ClusMatrix & cluster, SiPixelTemplate2D& templ, float& yrec, float& sigmay, float& xrec, float& sigmax, float& probxy, float& probQ, int& qbin, float& deltay); } #endif
0c2ec8865e9549e84b86d9e34f830d6ece54814a
9d68821a51ab196a97e7d78d4330a3d020b63255
/cpp/chapter4/structBit.cpp
a67919597b3400400b1516830d867891ba907ec5
[]
no_license
wkgreat/practice
42ebb0710a76e942336432d8d1d3bfb42607b6a6
a30f2d20b8e2dc2ad174b5f9264b67243bb6f5f7
refs/heads/master
2020-12-24T12:29:41.419500
2016-11-06T13:58:56
2016-11-06T13:58:56
72,993,982
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
structBit.cpp
#include<iostream> int main() { using namespace std; struct B { unsigned b1: 1; unsigned b2: 1; unsigned b3: 1; unsigned b4: 1; unsigned b5: 1; unsigned b6: 1; unsigned b7: 1; unsigned b8: 1; }; int pa = -1; B *pb = (B*)&pa; cout << pb->b1; cout << pb->b2; cout << pb->b3; cout << pb->b4; cout << pb->b5; cout << pb->b6; cout << pb->b7; cout << pb->b8 << endl; return 0; }
0e29d8aa10542230f95eaf37472de094ab331901
f8abb8f004b93edc4c51efbb6804f9459304a15d
/mainwindow.h
9d7cfdf0f64cf31a9adf5bf46f11d04246436d79
[]
no_license
FlierKing/GUI-of-Game-of-the-Amazons
d9966321b633fc5ae2e310d9fd150fc4ee309b1b
2d7090d3aa91c0e7589159b6af4c9d8f821e918d
refs/heads/master
2020-04-11T20:57:23.966251
2018-12-17T07:25:16
2018-12-17T07:25:16
162,089,726
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QObject> #include <QLabel> #include <QPushButton> #include <QSignalMapper> #include <QString> #include <QFile> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); QSignalMapper *signalMapper; QString outFileName; QString path; QFile outFile; private: Ui::MainWindow *ui; QPushButton *b; public slots: void exit(); void loadGame(); void newGameFirst(); void newGameSecond(); void initChessboard(); void deleteButtons(); void continueGame(); void loadStepInGame(int step); void reloadStep(); void initGame(); void createLogFile(); QByteArray getAIResult(); void achieveStepInGame(int x0, int y0, int x1, int y1, int x2, int y2); void achieveAIStep(QByteArray step); void endGame(); bool isGameOver(int color); void showResult(int winner); void showMessage(QString x, QString y); }; #endif // MAINWINDOW_H
648a06dece9dbce327b040966e3e925ea8248077
796120379f6c9ee88fb3e9ae0c7e41f880c4e69d
/cpp/src/exercise/e0200/e0131.cpp
95b9c331fe35619f8e84ad54df345e5b9075019e
[ "MIT" ]
permissive
ajz34/LeetCodeLearn
45e3e15bf3b57fec0ddb9471f17134102db4c209
70ff8a3c17199a100819b356735cd9b13ff166a7
refs/heads/master
2022-04-26T19:04:11.605585
2020-03-29T08:43:12
2020-03-29T08:43:12
238,162,924
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
e0131.cpp
// https://leetcode-cn.com/problems/palindrome-partitioning/ #include "extern.h" class S0131 { void partionInner( const vector<vector<int>>& stat, const string& s, vector<string>& vec, int idx, vector<vector<string>>& result) { if (idx == s.size()) { result.push_back(vec); return; } for (int r : stat[idx]) { vec.push_back(s.substr(idx, r - idx + 1)); partionInner(stat, s, vec, r + 1, result); vec.pop_back(); } } public: vector<vector<string>> partition(string s) { vector<vector<int>> stat(s.size(), vector<int>{}); for (int i = 0; i < s.size() * 2 - 1; ++i) { int l = i / 2, r = (i + 1) / 2; while (l >= 0 && r < s.size()) { if (s[l] != s[r]) break; stat[l].push_back(r); --l, ++r; } } vector<string> vec{}; vector<vector<string>> result; partionInner(stat, s, vec, 0, result); return result; } }; TEST(e0200, e0131) { auto res = S0131().partition("aab"); vector<vector<string>> ans{ {"a", "a", "b"}, {"aa", "b"} }; ASSERT_THAT(vec_to_set<vector<string>>(res), vec_to_set<vector<string>>(ans)); }
9703d599d7716234fc120870033c4968362d5240
6e979e707eda7535db2e259c463c809ba36c960e
/T43/mainwindow.cpp
57d1081478e9e9dce1703da6d2634fbae743c934
[]
no_license
milashe/Shrek-is-life
e45f33701d44ec21bbb9ade795321d5a0f8a4575
a843ccee2155d97b799c23058c18aef90eb4d855
refs/heads/main
2023-06-01T08:22:15.805665
2021-06-11T13:59:42
2021-06-11T13:59:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,156
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_db = QSqlDatabase::addDatabase("QSQLITE"); //соединение объекта базы данных // с СУБД m_db.setDatabaseName("myDB51"); //определение имени базы данных query = new QSqlQuery(m_db); // создание объекта для запроса if(!m_db.open()) // проверка на ошибку при открытии или создании базы данных throw "can't open database"; if(!m_db.tables().contains("Dota4")) // если в базе не существует таблица Person, { //то создание таблицы Person и заполнение данными query->clear(); // очистка запроса query->exec("CREATE TABLE Dota4 (id INTEGER PRIMARY KEY,name VARCHAR,ch VARCHAR,role VARCHAR,hp INTEGER,pickR INTEGER);"); // исполнение запроса на добавление записи query->clear(); query->exec("INSERT INTO Dota4 (id,name,ch,role,hp,pickR) VALUES (1,'Doom','Sila','Carry',720,100);"); query->clear(); query->exec("INSERT INTO Dota4 (id,name,ch,role,hp,pickR) VALUES (2,'Mirana','Lov','Sup',560,100);"); } model = new QSqlTableModel(this,m_db); // создание // редактируемой модели базы данных model->setTable("Dota4"); // создание модели таблицы Person model->select(); // заполнение модели данными model->setEditStrategy(QSqlTableModel::OnFieldChange); // выбор стратегии // сохранения изменений в базе данных //- сохранение происходит при переходе к другому полю ui->tableView->setModel(model); // соединение модели // и ее табличного представления в форме } MainWindow::~MainWindow() { delete ui; delete query; delete model; } void MainWindow::on_pushButtonall_clicked() { model->setFilter(""); model->select(); ui->tableView->setModel(model); QMessageBox::information(0,tr("Action"),tr("HEY COMPADRE"));// Сообщение, не обязательно } void MainWindow::on_pushButtonhpb_clicked() { model->setFilter("Hp>600"); model->select(); ui->tableView->setModel(model); QMessageBox::information(0,"Action","Filter"); //Сообщение, не обязательно } void MainWindow::on_pushButtonhpm_clicked() { model->setFilter("Hp<600"); model->select(); ui->tableView->setModel(model); } void MainWindow::on_pushButtonadd_clicked() { if(ui->lineEdit_id->text().isEmpty()||ui->lineEdit_name->text().isEmpty()||ui->lineEdit_ch->text().isEmpty()||ui->lineEdit_role->text().isEmpty()||ui->lineEdit_hp->text().isEmpty()||ui->lineEdit_pickR->text().isEmpty()) return; QString id = ui->lineEdit_id->text(); QString name = ui->lineEdit_name->text(); QString ch = ui->lineEdit_ch->text(); QString role = ui->lineEdit_role->text(); QString hp = ui->lineEdit_hp->text(); QString pickR = ui->lineEdit_pickR->text(); QString buf = tr("INSERT INTO Dota4 (id,name,ch,role,hp,pickR) VALUES (")+id+tr(",'")+name+tr("','")+ch+tr("','")+role+tr("',")+hp+tr(",")+pickR+tr(");"); query->clear(); query->exec(buf); model->select(); } void MainWindow::on_pushButton_rem_clicked() { if(ui->lineEdit_id->text().isEmpty()) return; QString id = ui->lineEdit_id->text(); query->clear(); query->exec(tr("DELETE FROM Dota4 WHERE ID=")+id); model->select(); } void MainWindow::on_dial_valueChanged(int value) { if (value == 1) { model->setFilter("role='Carry'"); model->select(); ui->tableView->setModel(model); } else if (value == 2) { model->setFilter("role='Support'"); model->select(); ui->tableView->setModel(model); } else if (value == 3) { model->setFilter("role='Mider'"); model->select(); ui->tableView->setModel(model); } else if (value == 4) { model->setFilter("role='Roamer'"); model->select(); ui->tableView->setModel(model); } else if (value == 0) { model->setFilter(""); model->select(); ui->tableView->setModel(model); } } void MainWindow::on_pushButton_clicked() { if(ui->lineEdit_id->text().isEmpty()||ui->lineEdit_name->text().isEmpty()||ui->lineEdit_ch->text().isEmpty()||ui->lineEdit_hp->text().isEmpty()||ui->lineEdit_role->text().isEmpty()||ui->lineEdit_pickR->text().isEmpty()) return; QString id = ui->lineEdit_id->text(); QString name = ui->lineEdit_name->text(); QString ch = ui->lineEdit_ch->text(); QString hp = ui->lineEdit_hp->text(); QString role = ui->lineEdit_role->text(); QString pickR = ui->lineEdit_pickR->text(); QString buf = tr("UPDATE Dota4 SET name='")+name+tr("' WHERE id =")+id+tr(";"); query->clear(); query->exec(buf); model->select(); buf = tr("UPDATE Dota4 SET ch='")+ch+tr("' WHERE id =")+id+tr(";"); query->clear(); query->exec(buf); model->select(); buf = tr("UPDATE Dota4 SET hp=")+hp+tr(" WHERE id =")+id+tr(";"); query->clear(); query->exec(buf); model->select(); buf = tr("UPDATE Dota4 SET role='")+role+tr("' WHERE id =")+id+tr(";"); query->clear(); query->exec(buf); model->select(); buf = tr("UPDATE Dota4 SET pickR=")+pickR+tr(" WHERE id =")+id+tr(";"); query->clear(); query->exec(buf); model->select(); }
cdb6f4d7f8208bb93419058498c09cb589f40daf
a495a7a2b6d4bf10a4820593a028242aac20f06c
/chap09_Examples/StringComp.cpp
fedc4a6f93be91de8ee2cf940adb20d78ec66bd6
[]
no_license
hasy73/Cclass
90b73a863f92f8791ce58155fb63ab7de40036b4
ee67751794e626ebadbf615ea194f09c96edeb78
refs/heads/master
2021-01-17T05:30:36.700828
2016-06-03T09:47:19
2016-06-03T09:47:19
60,336,659
0
1
null
null
null
null
UTF-8
C++
false
false
350
cpp
StringComp.cpp
/* StringComp.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char s1[]="Money does't grow on trees.\n"; char s2[]="Money does't come easily."; /* int strcmp(const char *str1,const char *str2); */ /* int strncmp(const char *str1,const char *str2,size_t len); */ system("pause"); }
fb3dbc945c9acea97a500c6e6bb4cf2e925055b6
2248658cdf230eba7cbfe6e362d7999632f61414
/Project/GDNative/src/Chunk.h
ec9c4f6916f9b70b5ba9d0d4c82695311b0be06d
[]
no_license
blockspacer/ThornBack
7e0bbe6869a7fd9726bc342f71c3d6739ef4d867
c71aa1463080879b5632fd2ebfa2ae3fd1959b4b
refs/heads/master
2020-12-06T21:28:43.970783
2019-10-09T07:20:26
2019-10-09T07:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
h
Chunk.h
#ifndef CHUNK_H #define CHUNK_H #include <Godot.hpp> #include <MeshInstance.hpp> #include <map> #include <array> #include <ArrayMesh.hpp> #include <StaticBody.hpp> #include <Material.hpp> #include "WorldData.h" #include "BlockLibrary.h" namespace godot { class Chunk : public MeshInstance { GODOT_CLASS(Chunk, MeshInstance) std::map<unsigned, BlockLibrary::SurfaceData> surfaces; std::pair<int, int> coords; Ref<BlockLibrary> blockLibrary; public: Ref<WorldData> worldData; StaticBody* staticBody; bool mustRemesh; static bool wireframe; static void _register_methods(); void _init(); void _ready(); void _process(float delta); void init(int x, int y, Ref<WorldData> worldData, Ref<BlockLibrary> blockLibrary); void setBlock(const unsigned x, const unsigned y, const unsigned z, const unsigned type); void clearBlock(const unsigned x, const unsigned y, const unsigned z); void updateMesh(); void collisionMesher(); void setWireframe(bool wireframe); bool getWireframe(); }; } #endif
fa9931a5a7be867bddc565cba2c4862c1b442e3a
d7bd0cd8e016fc213ac3e0149487c77e8ef523ba
/Algorithmic_Problem_Solving/hw6_2.cpp
4baed25c91a9f8583926736890f7f46f6824971b
[]
no_license
Michael98Liu/Competitive-Programming
eafa6fa063efedeec8da10a85ad7a9b8900728b3
dc5752a1e90bcd3a908e7f307776baf0d349af34
refs/heads/master
2021-01-01T20:03:04.073372
2019-02-14T15:31:39
2019-02-14T15:31:39
98,750,625
0
0
null
null
null
null
UTF-8
C++
false
false
4,482
cpp
hw6_2.cpp
#include <iostream> #include <string> #include <vector> #include <map> #include <bitset> #include <unordered_set> #include <algorithm> #include <string.h> using namespace std; int nChoosek( int n, int k ){ /* code of combinatorial is from: https://stackoverflow.com/questions/9330915/number-of-combinations-n-choose-r-in-c */ if (k > n) return 0; if (k * 2 > n) k = n-k; if (k == 0) return 1; int result = n; for( int i = 2; i <= k; ++i ) { result *= (n-i+1); result /= i; } return result; } int main(){ map<char, int> index; for( int i = 50; i <= 57; i++ ){ index[char(i)] = i-50; } index['X'] = 8; index['J'] = 9; index['Q'] = 10; index['K'] = 11; index['A'] = 12; string cards("23456789XJQKA"); int n, k; scanf("%d %d\n", &n, &k); string common, reaction; getline(cin, common); getline(cin, reaction); //printf("%s %s\n", common.c_str(), reaction.c_str()); bitset<13> mask, mustHave; mask.set(); // optional cards mustHave.reset(); // all the cards that must have unordered_set<char> seen, notHave; int occur[13]; for( int i =0; i < 13; i++ ){ occur[i] = 4; } for( int i = 0; i < common.size(); i ++ ){ occur[index[common[i]]] -= 1; if( reaction[i] == 'n' ){ auto it = seen.find(common[i]); if( it != seen.end() ){ printf("impossible\n"); return 0; } //printf("%d\n", index[common[i]]); mask.reset(index[common[i]]); // cannot have this card notHave.insert(common[i]); seen.insert(common[i]); } else if( reaction[i] == 'y'){ auto it = seen.find(common[i]); if( it == seen.end() ){ mustHave.set(index[common[i]]); seen.insert(common[i]); } mask.reset(index[common[i]]); } if( mustHave.count() > k ){ printf("impossible\n"); return 0; } if( notHave.size()*4 > 52 - k ){ printf("impossible\n"); return 0; } } //printf("%s %s\n", mask.to_string().c_str(), mustHave.to_string().c_str()); vector<int> mustHaveVec; // check must have card must at least have one left for( int i = 0; i < 13; i++){ if( mustHave.test(i) ){ if( occur[i] == 0 ){ printf("impossible\n"); return 0; } mustHaveVec.push_back(i); occur[i] -= 1; } } vector<int> pool; int limit = k - mustHaveVec.size(); // limit of occurances of each card int min_limit = 0; for( int i =0; i < 13; i++ ){ //printf("%d\n", occur[i]); if( mustHave.test(i) || mask.test(i) ){ min_limit = min(limit, occur[i]); for( int j = 0; j < min_limit; j++ ){ pool.push_back(i); } } } //printf("pool size %lu\n", pool.size()); vector< vector<int> > results; // selector vector vector<bool> v(pool.size()); fill(v.end() - (k-mustHaveVec.size()), v.end(), true); vector<int> oneCase; vector<int> prev; do{ for (int i = 0; i < v.size(); i++){ if( v[i] ){ oneCase.push_back(pool[i]); } } //oneCase.insert(oneCase.end(), mustHaveVec.begin(), mustHaveVec.end()); //sort(oneCase.begin(), oneCase.end()); results.push_back(oneCase); oneCase.clear(); }while(next_permutation(v.begin(), v.end())); sort(results.begin(), results.end()); auto it = results.begin(); while( it != results.end()){ bool same = true; if( it == results.begin() ){ prev = (*it); it ++; } if( it == results.end() ) break; for( int i=0; i < it->size(); i++ ){ if( (*it)[i] != prev[i] ){ same = false; break; } } if( same == true ) it = results.erase(it); else{ prev = (*it); it ++; } } printf("%lu\n", results.size()); for( auto it = results.begin(); it != results.end(); it ++){ for( auto iit = it->begin(); iit != it->end(); iit++){ printf("%c", cards[*iit]); } printf("\n" ); } return 0; }
c9b81077c8e2655e43ca921b2c935aec53b08cab
e75cd4fb8800eb4f8e78baa2f5b4bfb7581e4ac4
/RemoteControlClient/Compression.h
e7f551f6f45cf42d855c95dd528d47aa2cf9bc85
[]
no_license
lzp9421/remote_control
afeaa441927956bf543331f61f1ec1b23177c952
be627666b33c3146a29c649bd5b82d101146c12d
refs/heads/master
2020-03-26T13:19:35.118502
2018-08-16T03:41:19
2018-08-16T03:41:19
144,932,947
1
0
null
null
null
null
UTF-8
C++
false
false
517
h
Compression.h
//Download by http://www.NewXing.com #if !defined(COMPRESSION_H) #define COMPRESSION_H #include <windows.h> #include <windowsx.h> #include <stdio.h> // Compression Level Class for Message Handling class CCompression { public: // Constructor and Destructor CCompression(); ~CCompression(); // Message Handling Function Prototypes BOOL OnInitDialog(HWND hDlg,HWND hwndFocus, LPARAM lParam); void OnCommand(HWND hDlg,int iId,HWND hWndCtl,UINT iCodeNotify); // Variables int m_iCompressionLevel; }; #endif
b3b095353db2cf2bfa127ec1df9dff212272ea0e
1b826c72f53925ae366f854801ba07f1c62fe1b1
/oscc/firmware/brake/kia_soul_ev_niro/tests/features/step_definitions/setup.cpp
83b415020c04386165e5c0fcb46d0dc8cf41034c
[ "LicenseRef-scancode-warranty-disclaimer", "CC-BY-SA-4.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-copyleft" ]
permissive
OAkyildiz/oscc-joystick-commander
035a319829efdf0994941f1f992b908e78f15b31
c3cacef72b7fe02c84ffb6f697cbbe303b845304
refs/heads/master
2020-07-25T23:59:24.301670
2019-10-06T16:09:47
2019-10-06T16:09:47
208,462,518
0
0
MIT
2019-09-14T15:45:50
2019-09-14T15:45:50
null
UTF-8
C++
false
false
867
cpp
setup.cpp
#include "communications.h" #include "brake_control.h" #include "can_protocols/brake_can_protocol.h" #include "can_protocols/fault_can_protocol.h" #include "globals.h" /** Define the module name under test * * In order to implement reusable test fixtures and steps, those fixtures * need the name of the module under test defined. * * \sa firmware/common/testing/step_definitions/common.cpp */ #define FIRMWARE_NAME "brake" /** Define aliases to the brake control state * * \sa firmware/common/testing/step_definitions/fault_checking.cpp */ #define g_vcm_control_state g_brake_control_state extern volatile brake_control_state_s g_brake_control_state; /** Define the origin ID that brake faults should be associated with * * \sa firmware/common/testing/step_definitions/fault_checking.cpp */ const int MODULE_FAULT_ORIGIN_ID = FAULT_ORIGIN_BRAKE;
edcf406a4dac9256bba5f9f40f9e3216e68a955f
487b04076d5c6c8a4af29c7bf2a86fde17b71a4c
/src/editor/glwidget.cpp
d00a2604e2de047f2f5aa0d5c078cf86e26aa29a
[]
no_license
youZhuang/qco-editor
0e155e78065585f6ec5d11e50be1fd2ebbe2fe10
85382f86e660fe816c8b39789bba1489cab9bd82
refs/heads/master
2020-07-30T22:06:10.325702
2019-10-12T13:57:59
2019-10-12T13:57:59
210,375,737
1
0
null
2019-09-23T14:26:03
2019-09-23T14:26:03
null
UTF-8
C++
false
false
6,427
cpp
glwidget.cpp
 #include "glwidget.h" #include <QTimer> #include <QElapsedTimer> #include <QOpenGLContext> #include <QMouseEvent> #include <QCoreApplication> #include <QMessageBox> #include <QScreen> #include <QMimeData> #include <base/CCDirector.h> #include <platform/CCApplication.h> #include <renderer/CCRenderer.h> #include "qtglview.h" #include "tools/log_tool.h" #include "resource_mime.h" #include "framework.h" USING_NS_CC; DEFINE_LOG_COMPONENT(LOG_PRIORITY_DEBUG, "GLWidget"); GLWidget::GLWidget(QWidget *parent) : QOpenGLWidget(parent) , timer_(NULL) , isCocosInitialized_(false) , elapsedTimer_(nullptr) , mouseMoveEvent_(nullptr) , cocosInitializeResult(true) { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setProfile(QSurfaceFormat::CoreProfile); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setSamples(4); //format.setVersion(3, 2); //format.setRenderableType(QSurfaceFormat::OpenGLES); setFormat(format); LOG_DEBUG("construct."); } GLWidget::~GLWidget() { delete timer_; delete elapsedTimer_; LOG_DEBUG("destruct."); } void GLWidget::initializeGL() { LOG_DEBUG("initializeGL"); connect(context(), SIGNAL(aboutToBeDestroyed()), this, SLOT(cleanupCocos())); timer_ = new QTimer(); connect(timer_, SIGNAL(timeout()), this, SLOT(onTimerUpdate())); timer_->start(1000 / 60); elapsedTimer_ = new QElapsedTimer(); elapsedTimer_->start(); } void GLWidget::paintGL() { if(!isCocosInitialized_ || !cocosInitializeResult) { return; } if(mouseMoveEvent_ != nullptr) { flushMouseMoveEvent(); } Director::getInstance()->mainLoop(); } void GLWidget::onTimerUpdate() { //因为GLWidget::initializeGL函数中,默认的FrameBuffer还没有创建完成 //cocos将无法获得正确的FrameBuffer,需要延迟到渲染这里。 if(!isCocosInitialized_ && isValid()) { makeCurrent(); isCocosInitialized_ = true; if(!initializeCocos()) { QMessageBox::critical(nullptr, tr("Error"), tr("Initialize application failed! For more information plase see the log.")); QCoreApplication::instance()->quit(); return; } } double delta = elapsedTimer_->elapsed() * 0.001; emit signalTick((float)delta); elapsedTimer_->restart(); this->update(); } void GLWidget::resizeGL(int width, int height) { makeCurrent(); auto director = cocos2d::Director::getInstance(); GLView* view = director->getOpenGLView(); if (view) { float scale = context()->screen()->devicePixelRatio(); view->setFrameSize(width * scale, height * scale); view->setDesignResolutionSize(width, height, ResolutionPolicy::SHOW_ALL); // view->setViewPortInPoints(0, 0, width, height); } emit signalResize(width, height); } bool GLWidget::initializeCocos() { Application::getInstance()->initGLContextAttrs(); auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = QtGLViewImpl::create(this); director->setOpenGLView(glview); } cocosInitializeResult = false; do { if(!Application::getInstance()->applicationDidFinishLaunching()) { break; } if(!Editor::Framework::instance()->init()) { break; } cocosInitializeResult = true; }while(0); if(!cocosInitializeResult) { LOG_ERROR("Failed to init application!!!"); } return cocosInitializeResult; } // cleanup opengl resource here. void GLWidget::cleanupCocos() { LOG_DEBUG("GL will destroy."); makeCurrent(); Director::getInstance()->end(); Director::getInstance()->mainLoop(); doneCurrent(); } void GLWidget::mouseMoveEvent(QMouseEvent *event) { QOpenGLWidget::mouseMoveEvent(event); if(mouseMoveEvent_ != nullptr) { delete mouseMoveEvent_; } mouseMoveEvent_ = new QMouseEvent(*event); mousePosition_.setX(event->x()); mousePosition_.setY(event->y()); } void GLWidget::mousePressEvent(QMouseEvent *event) { QOpenGLWidget::mousePressEvent(event); mousePosition_.setX(event->x()); mousePosition_.setY(event->y()); makeCurrent(); emit signalMouseEvent(event); doneCurrent(); } void GLWidget::mouseReleaseEvent(QMouseEvent *event) { QOpenGLWidget::mouseReleaseEvent(event); mousePosition_.setX(event->x()); mousePosition_.setY(event->y()); makeCurrent(); if(mouseMoveEvent_ != nullptr) { flushMouseMoveEvent(); } emit signalMouseEvent(event); doneCurrent(); } void GLWidget::wheelEvent(QWheelEvent * event) { QOpenGLWidget::wheelEvent(event); makeCurrent(); emit signalWheelEvent(event); doneCurrent(); } void GLWidget::keyPressEvent(QKeyEvent *event) { QOpenGLWidget::keyPressEvent(event); makeCurrent(); emit signalKeyEvent(event); doneCurrent(); } void GLWidget::keyReleaseEvent(QKeyEvent *event) { QOpenGLWidget::keyReleaseEvent(event); makeCurrent(); emit signalKeyEvent(event); doneCurrent(); } void GLWidget::flushMouseMoveEvent() { CCAssert(mouseMoveEvent_ != nullptr, "flushMouseMoveEvent"); emit signalMouseEvent(mouseMoveEvent_); delete mouseMoveEvent_; mouseMoveEvent_ = nullptr; } void GLWidget::dragEnterEvent(QDragEnterEvent * event) { const QMimeData *data = event->mimeData(); if(data->hasFormat(Editor::MIME_STRING_LIST)) { event->acceptProposedAction(); event->setDropAction(Qt::CopyAction); } else { event->ignore(); } } void GLWidget::dropEvent(QDropEvent * event) { const QMimeData *data = event->mimeData(); if(data->hasFormat(Editor::MIME_STRING_LIST)) { event->accept(); event->setDropAction(Qt::CopyAction); QStringList paths; Editor::parseMimeStringList(paths, data->data(Editor::MIME_STRING_LIST)); cocos2d::Vec2 pt(event->posF().x(), event->posF().y()); pt = cocos2d::Director::getInstance()->convertToUI(pt); EDITOR_LOCK_GL_SCOPE(); emit signalDropFiles(paths, pt); } else { event->ignore(); } }
54c9469fb03f8dffeb98d928a8bacf2b6e8ad515
478cf52036b4b36ed5daf197db54d1502e372937
/DirectX Classes/Framework/Resource.cpp
9b51bd6e7ae076a36d65cb74acb7a3bc7fa36da1
[]
no_license
Dolvic/DirectX-Classes
bd90f8e9154af671ba78bb771c0c7a1151876fea
428d0a430bcb5af1875ddff919e08f4cb3cb9abe
refs/heads/master
2016-09-06T17:50:23.043935
2013-01-08T21:34:42
2013-01-08T21:34:42
7,509,455
1
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
Resource.cpp
#include "Includes\Resource.h" #include "Includes\Texture2D.h" Resource::Resource() : resource(nullptr) { } Resource::Resource(const CComPtr<ID3D11Resource>& res) : resource(res) { } Resource::~Resource() { } unique_ptr<Texture2D> Resource::convertToTexture2D() { if(resource == nullptr) return nullptr; return unique_ptr<Texture2D>(new Texture2D(resource)); }
3f667d9dcc2f64d6a5d2b30757a64b47023d3c9e
f976dd088077f33e3c617d8ae83940cc2296ffce
/WO_GameServer/Sources/ObjectsCode/obj_ServerLockbox.cpp
0354e8eec00e0589d7747f548602fb681cf22179
[]
no_license
HexPang/warz-server
739ad2224fdb11c7d9ab6d08db317bdb848a486e
93e7b8a43550cc2f5299afcfa0675484c58d02bb
refs/heads/master
2020-12-02T15:02:27.343558
2015-12-22T08:28:13
2015-12-22T08:28:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,100
cpp
obj_ServerLockbox.cpp
#include "r3dPCH.h" #include "r3d.h" #include "GameCommon.h" #include "multiplayer/P2PMessages.h" #include "obj_ServerPlayer.h" #include "obj_ServerLockbox.h" #include "ServerGameLogic.h" #include "../EclipseStudio/Sources/ObjectsCode/weapons/WeaponArmory.h" #include "../../GameEngine/ai/AutodeskNav/AutodeskNavMesh.h" #include "Async_ServerObjects.h" IMPLEMENT_CLASS(obj_ServerLockbox, "obj_ServerLockbox", "Object"); AUTOREGISTER_CLASS(obj_ServerLockbox); const static int LOCKBOX_NOT_USED_EXPIRE_TIME = 21 * 24 * 60 * 60; // lockbox will expire if not opened for three weeks const static int LOCKBOX_LOCKDOWN_TIME = 5; obj_ServerLockbox::obj_ServerLockbox() { ObjTypeFlags |= OBJTYPE_GameplayItem; ObjFlags |= OBJFLAG_SkipCastRay; m_ItemID = 0; m_ObstacleId = -1; maxItems = 30; // for now hard coded nextInventoryID = 1; m_AccessCodeS[0] = 0; m_IsLocked = 0; lockboxOwnerId = 0; m_nextLockdownClear = r3dGetTime() + 60.0f; srvObjParams_.ExpireTime = r3dGetTime() + LOCKBOX_NOT_USED_EXPIRE_TIME; } obj_ServerLockbox::~obj_ServerLockbox() { } BOOL obj_ServerLockbox::OnCreate() { r3dOutToLog("obj_ServerLockbox[%d] created. ItemID:%d numItems:%d OwnerID:%d\n", srvObjParams_.ServerObjectID, m_ItemID, items.size(), srvObjParams_.CustomerID); // set FileName based on itemid for ReadPhysicsConfig() in OnCreate() r3dPoint3D bsize(1, 1, 1); if(m_ItemID == WeaponConfig::ITEMID_Lockbox) { FileName = "Data\\ObjectsDepot\\Weapons\\Item_Lockbox_01.sco"; bsize = r3dPoint3D(1.0900440f, 1.2519419f, 0.79267800f); } else r3dError("unknown lockbox item %d\n", m_ItemID); parent::OnCreate(); // add navigational obstacle r3dBoundBox obb; obb.Size = bsize; obb.Org = r3dPoint3D(GetPosition().x - obb.Size.x/2, GetPosition().y, GetPosition().z - obb.Size.z/2); m_ObstacleId = gAutodeskNavMesh.AddObstacle(this, obb, GetRotationVector().x); // calc 2d radius m_Radius = R3D_MAX(obb.Size.x, obb.Size.z) / 2; gServerLogic.NetRegisterObjectToPeers(this); lockboxOwnerId = srvObjParams_.CustomerID; // convert old lockboxes with unlimited expire time to current expiration time if((int)(srvObjParams_.ExpireTime - r3dGetTime()) > LOCKBOX_NOT_USED_EXPIRE_TIME) { UpdateServerData(); } return 1; } BOOL obj_ServerLockbox::OnDestroy() { if(m_ObstacleId >= 0) { gAutodeskNavMesh.RemoveObstacle(m_ObstacleId); } PKT_S2C_DestroyNetObject_s n; n.spawnID = toP2pNetId(GetNetworkID()); gServerLogic.p2pBroadcastToActive(this, &n, sizeof(n)); return parent::OnDestroy(); } wiInventoryItem* obj_ServerLockbox::FindItemWithInvID(__int64 invID) { for(size_t i =0; i<items.size(); ++i) { if(items[i].InventoryID == invID) return &items[i]; } return NULL; } bool obj_ServerLockbox::AddItemToLockbox(const wiInventoryItem& itm, int quantity) { for(size_t i=0; i<items.size(); ++i) { if(items[i].CanStackWith(itm)) { items[i].quantity += quantity; UpdateServerData(); return true; } } if(items.size() < maxItems) { wiInventoryItem itm2 = itm; itm2.InventoryID = nextInventoryID++; itm2.quantity = quantity; items.push_back(itm2); UpdateServerData(); return true; } return false; } void obj_ServerLockbox::RemoveItemFromLockbox(__int64 invID, int amount) { r3d_assert(amount >= 0); for(size_t i=0; i<items.size(); ++i) { if(items[i].InventoryID == invID) { r3d_assert(amount <= items[i].quantity); items[i].quantity -= amount; // remove from lockbox items array if(items[i].quantity <= 0) { items.erase(items.begin() + i); } UpdateServerData(); return; } } // invId must be validated first r3d_assert(false && "no invid in lockbox"); return; } BOOL obj_ServerLockbox::Update() { const float curTime = r3dGetTime(); // erase entries with expire lockdown. to avoid large memory usage if every player will try to unlock it :) if(curTime > m_nextLockdownClear) { m_nextLockdownClear = curTime + 60.0f; for(std::vector<lock_s>::iterator it = m_lockdowns.begin(); it != m_lockdowns.end(); ) { if(curTime > it->lockEndTime) { it = m_lockdowns.erase(it); } else { ++it; } } // keep uses for 5 min, lockEndTime used as lockbox opening time for(std::vector<lock_s>::iterator it = m_uses.begin(); it != m_uses.end(); ) { if(curTime > it->lockEndTime + 5 * 60) { it = m_uses.erase(it); } else { ++it; } } } return parent::Update(); } void obj_ServerLockbox::setAccessCode(const char* newCodeS) { r3dscpy(m_AccessCodeS, newCodeS); m_IsLocked = 1; UpdateServerData(); } void obj_ServerLockbox::SendContentToPlayer(obj_ServerPlayer* plr) { PKT_S2C_LockboxOpReq_s n2; n2.op = PKT_S2C_LockboxOpReq_s::LBOR_StartingToSendContent; n2.lockboxID = toP2pNetId(GetNetworkID()); gServerLogic.p2pSendToPeer(plr->peerId_, this, &n2, sizeof(n2)); PKT_S2C_LockboxContent_s n; for(uint32_t i=0; i<items.size(); ++i) { n.item = items[i]; gServerLogic.p2pSendToPeer(plr->peerId_, this, &n, sizeof(n)); } n2.op = PKT_S2C_LockboxOpReq_s::LBOR_DoneSendingContent; n2.lockboxID = toP2pNetId(GetNetworkID()); gServerLogic.p2pSendToPeer(plr->peerId_, this, &n2, sizeof(n2)); } bool obj_ServerLockbox::IsLockdownActive(const obj_ServerPlayer* plr) { const float curTime = r3dGetTime(); for(size_t i=0; i<m_lockdowns.size(); i++) { lock_s& lock = m_lockdowns[i]; if(lock.CustomerID == plr->profile_.CustomerID && curTime < lock.lockEndTime) { lock.tries++; // technically user can use issue only one attempt per 1.5 sec (item use time) // so we check if user issued them faster that 1sec if(lock.tries > LOCKBOX_LOCKDOWN_TIME) { gServerLogic.LogCheat(plr->peerId_, PKT_S2C_CheatWarning_s::CHEAT_Lockbox, false, "Lockbox", "tries %d", lock.tries); } return true; } } return false; } void obj_ServerLockbox::SetLockdown(DWORD CustomerID) { float lockEndTime = r3dGetTime() + LOCKBOX_LOCKDOWN_TIME; for(size_t i=0; i<m_lockdowns.size(); i++) { if(m_lockdowns[i].CustomerID == CustomerID) { m_lockdowns[i].lockEndTime = lockEndTime; m_lockdowns[i].tries = 0; return; } } lock_s lock; lock.CustomerID = CustomerID; lock.lockEndTime = lockEndTime; lock.tries = 0; m_lockdowns.push_back(lock); } bool obj_ServerLockbox::IsLockboxAbused(const obj_ServerPlayer* plr) { const float curTime = r3dGetTime(); for(size_t i=0; i<m_uses.size(); i++) { lock_s& lock = m_uses[i]; if(lock.CustomerID == plr->profile_.CustomerID) { if(curTime > lock.lockEndTime + 60) { // used at least minute ago, reset timer (lockEndTime used as lockbox opening time) lock.lockEndTime = curTime - 0.001f; lock.tries = 0; } // there was a 'possible' dupe method that allowed to fire alot of requests to update lockbox // hoping that they will be executed in wrong order on API side if was put to different job queues lock.tries++; float ups = (float)lock.tries / (curTime - lock.lockEndTime); if(lock.tries > 10 && ups > 20) { // on local machine using UI i was able to put about 5 requests per sec, so 20 usages per sec is exploit. gServerLogic.LogCheat(plr->peerId_, PKT_S2C_CheatWarning_s::CHEAT_Lockbox, true, "UsagePerSec", "tries %d, ups:%.1f", lock.tries, ups); return true; } return false; } } lock_s lock; lock.CustomerID = plr->profile_.CustomerID; lock.lockEndTime = curTime; lock.tries = 1; m_uses.push_back(lock); return false; } void obj_ServerLockbox::DestroyLockbox() { setActiveFlag(0); g_AsyncApiMgr->AddJob(new CJobDeleteServerObject(this)); } void obj_ServerLockbox::UpdateServerData() { // if lockbox was used, extend expire time for 2 weeks srvObjParams_.ExpireTime = srvObjParams_.CreateTime + LOCKBOX_NOT_USED_EXPIRE_TIME; g_AsyncApiMgr->AddJob(new CJobUpdateServerObject(this)); } DefaultPacket* obj_ServerLockbox::NetGetCreatePacket(int* out_size) { static PKT_S2C_CreateNetObject_s n; n.spawnID = toP2pNetId(GetNetworkID()); n.itemID = m_ItemID; n.pos = GetPosition(); n.var1 = GetRotationVector().x; n.var4 = GetNetworkHelper()->srvObjParams_.CustomerID; *out_size = sizeof(n); return &n; } void obj_ServerLockbox::LoadServerObjectData() { m_ItemID = srvObjParams_.ItemID; // deserialize from xml IServerObject::CSrvObjXmlReader xml(srvObjParams_.Var1); r3dscpy(m_AccessCodeS, xml.xmlObj.attribute("accessCode").value()); m_IsLocked = xml.xmlObj.attribute("locked").as_int(); uint32_t numItems = xml.xmlObj.attribute("numItems").as_uint(); pugi::xml_node xmlItem = xml.xmlObj.child("item"); for(uint32_t i=0; i<numItems; ++i) { if(xmlItem.empty()) // should never be empty { return; // bail out } wiInventoryItem it; it.InventoryID = nextInventoryID++; it.itemID = xmlItem.attribute("id").as_uint(); // verify itemID is valid if(g_pWeaponArmory->getConfig(it.itemID)==NULL) return; // bail out it.quantity = xmlItem.attribute("q").as_uint(); it.Var1 = xmlItem.attribute("v1").as_int(); it.Var2 = xmlItem.attribute("v2").as_int(); if(xmlItem.attribute("v3").value()[0]) it.Var3 = xmlItem.attribute("v3").as_int(); else it.Var3 = wiInventoryItem::MAX_DURABILITY; it.ResetClipIfFull(); // in case when full clip was saved before 2013-4-18 items.push_back(it); xmlItem = xmlItem.next_sibling(); } } void obj_ServerLockbox::SaveServerObjectData() { srvObjParams_.ItemID = m_ItemID; IServerObject::CSrvObjXmlWriter xml; xml.xmlObj.append_attribute("accessCode").set_value(m_AccessCodeS); xml.xmlObj.append_attribute("locked") = m_IsLocked; xml.xmlObj.append_attribute("numItems") = items.size(); for(size_t i=0; i<items.size(); ++i) { pugi::xml_node xmlItem = xml.xmlObj.append_child(); xmlItem.set_name("item"); xmlItem.append_attribute("id") = items[i].itemID; xmlItem.append_attribute("q") = items[i].quantity; xmlItem.append_attribute("v1") = items[i].Var1; xmlItem.append_attribute("v2") = items[i].Var2; xmlItem.append_attribute("v3") = items[i].Var3; } xml.save(srvObjParams_.Var1); }
66a688c94492c6382c316161bbdac662b8f05808
22938e866c53436c721074adda227e2a9d9185f6
/Day 04/ex01/Character.cpp
3ce63ca8708635f268d37b20c92a1eb4996e6b07
[]
no_license
olehsamoilenko/Piscine-CPP
125a3f3ca575f8c6e5ea81fc05674a2b8e183399
dc7311b09892d06909f4d0a44aaacd5c7f2d7418
refs/heads/master
2020-06-02T11:23:10.661165
2019-07-04T17:40:14
2019-07-04T17:40:14
191,138,844
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
cpp
Character.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: osamoile <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/28 14:53:25 by osamoile #+# #+# */ /* Updated: 2019/06/28 14:53:27 by osamoile ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" Character::Character(std::string const & name) { _name = name; _ap = 40; _weapon = NULL; } int Character::getAP(void) const { return (_ap); } std::string Character::getName(void) const { return (_name); } AWeapon * Character::getWeapon(void) const { return (_weapon); } void Character::recoverAP(void) { _ap += 10; if (_ap > 40) _ap = 40; } void Character::attack(Enemy * enemy) { if (_weapon == NULL) std::cout << "No weapon :(" << std::endl; else if (_ap < _weapon->getAPCost()) std::cout << "Not enough AP :(" << std::endl; else if (enemy->getHP() == 0) std::cout << enemy->getType() << " dead :(" << std::endl; else { _ap -= _weapon->getAPCost(); std::cout << _name << " attacks " << enemy->getType() << " with a " << _weapon->getName() << std::endl; _weapon->attack(); enemy->takeDamage(_weapon->getDamage()); std::cout << enemy->getType() << ": " << enemy->getHP() << "HP left" << std::endl; if (enemy->getHP() <= 0) delete enemy; } } void Character::equip(AWeapon * weapon) { _weapon = weapon; } std::ostream & operator<<(std::ostream & o, Character const & src) { o << src.getName() << " has " << src.getAP() << " AP and "; if (src.getWeapon() != NULL) o << "wields a " << src.getWeapon()->getName(); else o << "is unarmed"; o << std::endl; return (o); } Character::Character(void) { } Character::~Character(void) { } Character & Character::operator=(Character const & src) { if (this != &src) { _name = src._name; _ap = src._ap; _weapon = src._weapon; } return (*this); } Character::Character(Character const & src) { *this = src; }
f2dc61f7904e1f9a69ca58531d626039dd62a50f
5eb4034da187c4e39c0a7695e8fb396e9078b0a9
/MiNiSQL/MiniSQL/IndexCatalogPage.cpp
6bc78ec26cc7d5d885172c4f1559f4f782aa3c05
[]
no_license
Yaxin-Lu/MiniSQL-Design-and-Implementation
70f9da7bc0cf5558918e8e6df482497234ef2cc6
78e6639cf51e74aa3e36efddfc574adcf8707bbb
refs/heads/master
2022-12-13T10:17:27.654692
2020-09-04T06:34:07
2020-09-04T06:34:07
292,757,976
1
0
null
null
null
null
UTF-8
C++
false
false
4,356
cpp
IndexCatalogPage.cpp
#include "BufferManager.hpp" #include "IndexCatalogPage.hpp" #include <string> #include "Global.h" using namespace std; //由于index信息只存在一个文件内,因此用第一页来存放总体信息 //pageData[0..3]表示当前index条目总数,pageData[4..7]表示最后一个被删除的条目编号,如果没有则为-1 void IndexCatalogPage::writeInitialPage() { BufferManager buffer; *(int*)pageData=0; *(int*)(pageData+4)=-1; buffer.writePage(*this); } int IndexCatalogPage::readPrevDel(int indexPos) { int i,j,x,rec; BufferManager buffer; rec=pageIndex; //由于这个函数是临时调用,因此先记录下此前所在页面 i=(indexPos-1)/recordLimit+2; j=(indexPos-1)%recordLimit+1; pageIndex=i; //改为要读取的页号,并且读取内容 buffer.readPage(*this); x=*(int*)(pageData+(j-1)*400+300); pageIndex=rec; //读完内容,改回原页号,并且重新读取内容 buffer.readPage(*this); return x; } string IndexCatalogPage::readIndexName(int indexPos) { int i,j,k; string s=""; BufferManager buffer; i=(indexPos-1)/recordLimit+2; j=(indexPos-1)%recordLimit+1; pageIndex=i; buffer.readPage(*this); for (k=(j-1)*400+200; pageData[k]!=0; k++) s=s+pageData[k]; return s; } string IndexCatalogPage::readTableName(int indexPos) { int i,j,k; string s=""; BufferManager buffer; i=(indexPos-1)/recordLimit+2; j=(indexPos-1)%recordLimit+1; pageIndex=i; buffer.readPage(*this); for (k=(j-1)*400; pageData[k]!=0; k++) s=s+pageData[k]; return s; } string IndexCatalogPage::readAttrName(int indexPos) { int i,j,k; string s=""; BufferManager buffer; i=(indexPos-1)/recordLimit+2; j=(indexPos-1)%recordLimit+1; pageIndex=i; buffer.readPage(*this); for (k=(j-1)*400+100; pageData[k]!=0; k++) s=s+pageData[k]; return s; } //在本页写 void IndexCatalogPage::writeCont(int start, string cont) { int i,len; len=(int)cont.length(); for (i=0; i<len; i++) pageData[start+i]=cont[i]; pageData[start+i]=0; } //储存格式:表名、属性名、索引名、上一个被删除的位置(如果当前条目并未被删除,则此项为0) int IndexCatalogPage::writeIndex(string tableName, string attrName, string indexName) { int n,m,i,j,x,target; BufferManager buffer; pageIndex=1; buffer.readPage(*this); n = *(int*)pageData; n++; *(int*)pageData = n; m = *(int*)(pageData+4); if (m==-1) //没有删除的条目,即目前为满排列,直接插到最后 { target=n; i=(n-1)/recordLimit+2; //i为页数 j=(n-1)%recordLimit+1; //j为行数 } else //有删除的条目,插到最后一次删除的位置,并更改删除信息 { target=m; i=(m-1)/recordLimit+2; j=(m-1)%recordLimit+1; buffer.writePage(*this);//由于下一行要调用一个更改页的函数,这里必须先write一次以免pageData丢失 x=readPrevDel(m); *(int*)(pageData+4)=x; } buffer.writePage(*this); //改首页信息,包括:总数增加了1,以及如果占用了已删除位置,还需要更改这项信息 pageIndex=i; //强行改成第i页并读第i页数据 buffer.readPage(*this); writeCont((j-1)*400, tableName); writeCont((j-1)*400+100, attrName); writeCont((j-1)*400+200, indexName); *(int*)(pageData+(j-1)*400+300) = 0; buffer.writePage(*this); return target; } void IndexCatalogPage::deleteIndex(int indexPos) { int m,n,i,j; BufferManager buffer; pageIndex=1; //读取最后被删除的位置编号 buffer.readPage(*this); n = *(int*)pageData; m = *(int*)(pageData+4); *(int*)pageData = n-1; *(int*)(pageData+4) = indexPos; buffer.writePage(*this); //更改首页信息 i=(indexPos-1)/recordLimit+2; j=(indexPos-1)%recordLimit+1; pageIndex=i; //跳到当前删除的位置,并修改删除信息 buffer.readPage(*this); *(int*)(pageData+(j-1)*400+300) = m; buffer.writePage(*this); }
6aac045e6936ad42b4e5da3c6cbd090ea74ccc34
3ccc76a528ac69b83bb7e81e99fde595e9dbf0a3
/C++/level order good.cpp
423549f657bb679cc5d65ee7f972dca5fbe8adc4
[]
no_license
as99if/Algorithm
0773e2ac2e621068ce5c41e596b46e7a2864ed5c
8c9d27ad4579c15167337954e8b6e7db0d837a00
refs/heads/master
2020-07-29T19:12:28.826490
2019-09-21T05:14:01
2019-09-21T05:14:01
209,927,674
0
0
null
null
null
null
UTF-8
C++
false
false
1,495
cpp
level order good.cpp
#include<iostream> #include<queue> using namespace std; struct list{ char data; struct list *left, *right; }; typedef struct list node; void level_traverse(node* root) { queue<node*> q; node *temp_node; if(!root){ return; } for(q.push(root); !q.empty() ; q.pop()) { temp_node = q.front(); cout<<temp_node->data<<" "; if (temp_node->left) { q.push(temp_node->left); } if (temp_node->right) { q.push(temp_node->right); } } } void createBTree(node *root){ node *left, *right; char ch; cout<<"\nDoes "<<root->data<<" has any left child ? <y/n> "; cin>>ch; if(ch=='y'){ root->left=new node; root->left->left=NULL; root->left->right=NULL; cout<<"Enter left child data : "; cin>>root->left->data; createBTree(root->left); } cout<<"\nDoes "<<root->data<<" has any Right child ? <y/n> "; cin>>ch; if(ch=='y'){ root->right=new node; root->right->left=NULL; root->right->right=NULL; cout<<"Enter right child data : "; cin>>root->right->data; createBTree(root->right); } } int main(){ node *root; root=new node(); root->right=NULL; root->left=NULL; cout<<"Input root : "; cin>>root->data; createBTree(root); level_traverse(root); return 0; }
2381b7b1f26e826b149be6436fcdaa252121d865
d0e2aa848f35efe2aae72e649ea9267d2443472c
/SW_Academy_Samsung/sw_1946.cpp
1db08ec6def012420cd48c4ffb0c8a48eecbb888
[]
no_license
ddjddd/Algorithm-Study
376f72849506841be0351dfdfe9b1ca95d197956
6ec72ae4de9d52592b76af6e4e8246c9fdeb946f
refs/heads/master
2023-04-14T10:05:09.303548
2023-04-06T14:16:50
2023-04-06T14:16:50
121,474,738
0
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
sw_1946.cpp
#include <iostream> using namespace std; int main () { int tC; cin>>tC; for(int tc = 1; tc <= tC; tc++) { int num; cin >> num; int count = 0; cout << '#' << tc; for(int i = 0; i < num; i++) { char c; int t; cin >> c >> t; for(int j = 0; j < t; j++) { if (!(count%10)) cout << endl; cout << c; count++; } } cout << endl; } return 0; }
5308bda6665751d516bf82e1307491d6f9bf1273
4f4e43bed2e86a9bd1c59597caadfa57a0ec1f72
/server_test.cpp
8dfe8e87d775df7a0e70eb0ccf1b281e93392ae6
[]
no_license
jazzdan/simple-cpp-kvs
879c0e09ccf8c9b74386b02474f5c5a1e95c2518
7cd006101980ffabdc6097d9f50ec2f4be707489
refs/heads/master
2023-01-06T20:43:00.775013
2020-10-19T21:26:32
2020-10-19T21:26:32
288,501,359
0
0
null
null
null
null
UTF-8
C++
false
false
181
cpp
server_test.cpp
#include "gtest/gtest.h" #include "kvslib.h" TEST(ServerShould, Set) { auto myKVS = InMemoryKVS<std::string>(); myKVS.put("foo", "bar"); EXPECT_EQ(myKVS.get("foo"), "bar"); }
42f05b9ae06c0044369914e99f52736e44ef680c
22b5e1f6745261d76461c300e4cb49b4baeac2c4
/src/HTTPConnection.hpp
8fb44ac475599b5f8b3a02b56913d397bf12a1c2
[ "MIT" ]
permissive
jeancode/esp32_https_server
5e33ab3d5db43b9d4db3eab62bdf0f193ea445d9
da80324fb6b81a097888ef5c9351e1bfbdbe5cb1
refs/heads/master
2020-12-01T18:06:29.612995
2019-12-25T00:31:31
2019-12-25T00:31:31
230,721,502
1
0
MIT
2019-12-29T08:06:33
2019-12-29T08:06:32
null
UTF-8
C++
false
false
5,415
hpp
HTTPConnection.hpp
#ifndef SRC_HTTPCONNECTION_HPP_ #define SRC_HTTPCONNECTION_HPP_ #include <Arduino.h> #include <string> #include <mbedtls/base64.h> #include <hwcrypto/sha.h> #include <functional> // Required for sockets #include "lwip/netdb.h" #undef read #include "lwip/sockets.h" #include "HTTPSServerConstants.hpp" #include "ConnectionContext.hpp" #include "HTTPHeaders.hpp" #include "HTTPHeader.hpp" #include "ResourceResolver.hpp" #include "ResolvedResource.hpp" #include "ResourceNode.hpp" #include "HTTPRequest.hpp" #include "HTTPResponse.hpp" #include "WebsocketHandler.hpp" #include "WebsocketNode.hpp" namespace httpsserver { /** * \brief Represents a single open connection for the plain HTTPServer, without TLS */ class HTTPConnection : private ConnectionContext { public: HTTPConnection(ResourceResolver * resResolver); virtual ~HTTPConnection(); virtual int initialize(int serverSocketID, HTTPHeaders *defaultHeaders); virtual void closeConnection(); virtual bool isSecure(); void loop(); bool isClosed(); bool isError(); protected: friend class HTTPRequest; friend class HTTPResponse; friend class WebsocketInputStreambuf; virtual size_t writeBuffer(byte* buffer, size_t length); virtual size_t readBytesToBuffer(byte* buffer, size_t length); virtual bool canReadData(); virtual size_t pendingByteCount(); // Timestamp of the last transmission action unsigned long _lastTransmissionTS; // Timestamp of when the shutdown was started unsigned long _shutdownTS; // Internal state machine of the connection: // // O --- > STATE_UNDEFINED -- initialize() --> STATE_INITIAL -- get / http/1.1 --> STATE_REQUEST_FINISHED --. // | | | | // | | | | Host: ...\r\n // STATE_ERROR <- on error-----------------------<---------------------------------------< | Foo: bar\r\n // ^ | | | \r\n // | shutdown .--> STATE_CLOSED | | | \r\n // | fails | | | | // | | close() | | | // STATE_CLOSING <---- STATE_WEBSOCKET <-. | | | // ^ | | | | // `---------- close() ---------- STATE_BODY_FINISHED <-- Body received or GET -- STATE_HEADERS_FINISHED <-´ // enum { // The order is important, to be able to use state <= STATE_HEADERS_FINISHED etc. // The connection has not been established yet STATE_UNDEFINED, // The connection has just been created STATE_INITIAL, // The request line has been parsed STATE_REQUEST_FINISHED, // The headers have been parsed STATE_HEADERS_FINISHED, // The body has been parsed/the complete request has been processed (GET has body of length 0) STATE_BODY_FINISHED, // The connection is in websocket mode STATE_WEBSOCKET, // The connection is about to close (and waiting for the client to send close notify) STATE_CLOSING, // The connection has been closed STATE_CLOSED, // An error has occured STATE_ERROR } _connectionState; enum { CSTATE_UNDEFINED, CSTATE_ACTIVE, CSTATE_CLOSED } _clientState; private: void raiseError(uint16_t code, std::string reason); void readLine(int lengthLimit); bool isTimeoutExceeded(); void refreshTimeout(); int updateBuffer(); size_t pendingBufferSize(); void signalClientClose(); void signalRequestError(); size_t readBuffer(byte* buffer, size_t length); size_t getCacheSize(); bool checkWebsocket(); // The receive buffer char _receiveBuffer[HTTPS_CONNECTION_DATA_CHUNK_SIZE]; // First index on _receive_buffer that has not been processed yet (anything before may be discarded) int _bufferProcessed; // The index on the receive_buffer that is the first one which is empty at the end. int _bufferUnusedIdx; // Socket address, length etc for the connection struct sockaddr _sockAddr; socklen_t _addrLen; int _socket; // Resource resolver used to resolve resources ResourceResolver * _resResolver; // The parser line. The struct is used to read the next line up to the \r\n in readLine() struct { std::string text = ""; bool parsingFinished = false; } _parserLine; // HTTP properties: Method, Request, Headers std::string _httpMethod; std::string _httpResource; HTTPHeaders * _httpHeaders; // Default headers that are applied to every response HTTPHeaders * _defaultHeaders; // Should we use keep alive bool _isKeepAlive; //Websocket connection WebsocketHandler * _wsHandler; }; void handleWebsocketHandshake(HTTPRequest * req, HTTPResponse * res); std::string websocketKeyResponseHash(std::string const &key); void validationMiddleware(HTTPRequest * req, HTTPResponse * res, std::function<void()> next); } /* namespace httpsserver */ #endif /* SRC_HTTPCONNECTION_HPP_ */
4e13bd70e1b360f1ceab892727a74090dea22c8a
c2914177edf376ec09a3923c95e40c7a0e8cf836
/Project1/WinMain.cpp
ddf71ec61c48d9693d0bc5123452e1ac69bdd257
[]
no_license
leixing999/chatHook
ab77c567608975556f580cdb056e2c063d8b1864
035465273ecd6141158c1bb1ef81b86e8ae076ef
refs/heads/main
2023-07-14T21:14:00.601672
2021-08-30T11:19:44
2021-08-30T11:19:44
401,310,895
0
0
null
null
null
null
GB18030
C++
false
false
1,567
cpp
WinMain.cpp
#include<windows.h> #include <tchar.h> #include <windows.h> #include <iostream> #include "MyClass.h" #pragma comment(lib,"MyDll.lib")/*静态链接*/ using namespace std; /// <summary> /// dll基础学习 /// </summary> /// <param name="hMoudle"></param> void DllBasic(HMODULE hMoudle) { if (!hMoudle) { cout << "加载失败" << endl; } else { cout << "加载成功" << endl; } int varLabel = *(int*)GetProcAddress(hMoudle, "varlabel");/*得到dll变量*/ typedef int (*Func)(); cout << varLabel << endl; Func dllFunc = (Func)GetProcAddress(hMoudle, "add1");/*得到dll函数地址*/ cout << dllFunc() << endl; MyClass myClass; cout << myClass.add(10, 10) << endl; } int _tmain(int argc, _TCHAR* argv[]) { HMODULE dll = LoadLibrary("Mydll"); if (!dll) { cout << "加载失败" << endl; } else { cout << "加载成功" << endl; } //DllBasic(dll); /*1:普通获取dll函数方式 typedef HHOOK(*StartHook)(CHAR hookType, DWORD threadId); StartHook DllStartHook = (StartHook)GetProcAddress(dll, "startHook");*/ /*2:强制函数转换*/ HHOOK(*StartHook)(CHAR hookType, DWORD threadId) = (HHOOK(*)(CHAR hookType, DWORD threadId))GetProcAddress(dll, "StartHook");/*启动钩子函数*/ bool(*UnHook)(HHOOK hHook) = (bool(*)(HHOOK hHook))GetProcAddress(dll, "UnHook");/*卸载钩子函数*/ /*===============================================*/ HHOOK hookInstance = StartHook(9, 0);/*启动线程钩子*/ short szInput = 0; while (szInput == 0) { cin >> szInput; } UnHook(hookInstance);/*卸载线程钩子*/ Sleep(20000); }
44dbb8113c448de7583078b56897214bfbd3e616
76c08c54733e57d2386698dc77a0c46e4066fcd3
/Stack.h
2e4a461c95b263bc40df12217f4951d896ee87dd
[]
no_license
Youssefares/ScriptingLang
0a8964f31d8795c67c1d80e59521f887107ff179
b01c6078793ff844f71ac1ccb908ea249b4692cb
refs/heads/master
2021-01-01T04:51:51.677827
2016-05-17T14:01:56
2016-05-17T14:01:56
56,968,977
0
0
null
null
null
null
UTF-8
C++
false
false
831
h
Stack.h
/* * Implementation of a Singly-Linked Earthed Stack ADT */ #include "StackInterface.h" using namespace std; template<typename item> Stack<item>::Stack(){ top = NULL; } template<typename item> bool Stack<item>::isEmpty(){ return top == NULL; } /* * returns data at head of linked list (top). */ template<typename item> item Stack<item>::peak(){ return top->data; } /* * removes & returns data at head of linked list (top). */ template<typename item> item Stack<item>::pop(){ Node* doomed = top; top = top->next; return doomed->data; } /* * adds at head of linked list (top). */ template<typename item> void Stack<item>::push(item data){ Node* newTop = new Node(); newTop->data = data; newTop->next = top; top = newTop; return; }
ca00f853bdf011119bb5244397f5d9945baba731
69ca61664eb5b75586e83e38e9b980d8a0f24530
/dados_pessoas/main.cpp
6154c1999148f37d7e66280636b91ce7c66f1828
[]
no_license
tlima1011/LinguagemCpp
5de0b352beec5341146439768c49f46c7f188371
fa4aebb5861d6af943bc1b227aa9b595b5b380c8
refs/heads/master
2022-12-04T18:27:43.970123
2020-08-19T13:08:25
2020-08-19T13:08:25
287,820,838
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n = 0, qtde_mulheres = 0, qtde_homens = 0; double menor_altura = 0, maior_altura = 0, soma_mulheres = 0, media = 0; cout << "Quantas pessoas serao digitadas? "; cin >> n; double alturas[n]; char generos[n]; for(int i = 0; i < n; i++){ cout << "Altura da " << i + 1 << ". pessoa: "; cin >> alturas[i]; cout << "Genero da " << i + 1 << ". pessoa: "; cin >> generos[i]; generos[i] = toupper(generos[i]); } menor_altura = alturas[0]; maior_altura = alturas[0]; for(int i = 1; i < n; i++){ if (alturas[i] > maior_altura){ maior_altura = alturas[i]; } if (alturas[i] < menor_altura){ menor_altura = alturas[i]; } } for(int i = 0; i < n; i++){ if(generos[i] == 'M'){ qtde_homens++; }else if(generos[i] == 'F'){ qtde_mulheres++; soma_mulheres += alturas[i]; } } media = soma_mulheres / qtde_mulheres; cout << fixed << setprecision(2); cout << "Menor altura = " << menor_altura << endl; cout << "Maior altura = " << maior_altura << endl; cout << "Media das alturas das mulheres = " << media << endl; cout << "Numero de homens = " << qtde_homens << endl; return 0; }
15775bd3fc1b8b47573232422a96985e1700c21b
78ac84a3850ef78b53f21355d7d15016947df852
/[FancyPlanet]_Client/FancyPlanet/GameFramework.h
4a8def0b52ad6eb057557328a08c1ca595715144
[]
no_license
ysk1965/Fancy_Planet
c534ef0755583004c8fe940d3b09e452498851f7
89b63465fe9ab35bdd2314b61a04e070f86a03e0
refs/heads/master
2021-06-15T02:03:04.015785
2019-07-29T05:09:22
2019-07-29T05:09:22
112,574,439
2
0
null
2018-01-17T18:39:24
2017-11-30T06:35:41
C++
UHC
C++
false
false
6,470
h
GameFramework.h
#pragma once #define FRAME_BUFFER_WIDTH 1024 #define FRAME_BUFFER_HEIGHT 768 #include "Timer.h" #include "Player.h" #include "Scene.h" #include "FmodSound.h" #include "ComputShader.h" #include <chrono> enum { NUM_SUBSETS = 4, NUM_COMMANDLIST = 4 }; enum { TERRAIN, EFFECT, CHARACTER, OBJECT }; enum class BACKSOUND { BACKGROUND_ROBBY, BACKGROUND_INGAME, BACKGROUND_END, }; enum class EFFECTSOUND { ROBBY_CLICK, ROBBY_CHANGECHARACTER, HUMAN_SHOT, HUMAN_DIED, HUMAN_JUMP, HUMANSKILL_1, HUMANSKILL_2, DRONE_SHOT, DRONE_DIED, DRONE_JUMP, DRONESKILL_1, DRONESKILL_2, CREATURE_SHOT, CREATURE_DIED, CREATURE_JUMP, CREATURESKILL_1, CREATURESKILL_2, INGAME_CHARGE, INGAME_COMPLETE }; using namespace std; class CGameFramework { public: CGameFramework(); ~CGameFramework(); bool GetLobbyState() { return m_nIsLobby; } void SendBulletPacket(); void BuildLobby(); void BuildLightsAndMaterials(); bool OnCreate(HINSTANCE hInstance, HWND hMainWnd); void OnDestroy(); void CreateSwapChain(); void CreateDirect3DDevice(); void CreateRtvAndDsvDescriptorHeaps(); void CreateSwapChainRenderTargetViews(); void CreateLightsAndMaterialsShaderVariables(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList); void CreateDepthStencilView(); void CreateCommandQueueAndList(); void OnResizeBackBuffers(); void BuildThreadsAndEvents(); void BuildObjects(); void ReleaseObjects(); void ProcessInput(); void AnimateObjects(); void FrameAdvance(); void FrameAdvanceInLobby(); void FrameAdvanceInEnd(); void WaitForGpuComplete(); void MoveToNextFrame(); void RenderSubset(int iIndex); void NotifyIdleState(); void OnProcessingMouseMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam); void OnProcessingKeyboardMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK OnProcessingWindowMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam); void UpdateLightsAndMaterialsShaderVariables(); XMFLOAT4X4& GetPlayerMatrix() { return m_pPlayer->GetPlayerWorldTransform(); }; void PrepareFrame(); private: ID3D12GraphicsCommandList * m_pd3dScreenCommandList; ID3D12CommandAllocator *m_pd3dScreenCommandAllocator; ID3D12GraphicsCommandList * m_pd3dPreShadowCommandList; ID3D12CommandAllocator *m_pd3dPreShadowCommandAllocator; CComputShader* m_pComputeShader = NULL; UIShader* m_pUIShader = NULL; CShadowShader* m_pShadowShader = NULL; UINT m_nIsLobby; HINSTANCE m_hInstance; HWND m_hWnd; int m_nWndClientWidth; int m_nWndClientHeight; int m_nCharacterType = 0; int m_iSceneState = INGAMEROOM; XMFLOAT3 xmf3PickDirection; IDXGIFactory4 *m_pdxgiFactory = NULL; IDXGISwapChain3 *m_pdxgiSwapChain = NULL; ID3D12Device *m_pd3dDevice = NULL; bool m_bMsaa4xEnable = false; UINT m_nMsaa4xQualityLevels = 0; static const UINT m_nSwapChainBuffers = 2; UINT m_nSwapChainBufferIndex; D3D12_CPU_DESCRIPTOR_HANDLE m_pd3dRtvSwapChainBackBufferCPUHandles[m_nSwapChainBuffers]; D3D12_CPU_DESCRIPTOR_HANDLE m_d3dDsvDepthStencilBufferCPUHandle; ID3D12Resource *m_ppd3dSwapChainBackBuffers[m_nSwapChainBuffers]; ID3D12DescriptorHeap *m_pd3dRtvDescriptorHeap = NULL; UINT m_nRtvDescriptorIncrementSize; ID3D12Resource *m_pd3dDepthStencilBuffer = NULL; ID3D12DescriptorHeap *m_pd3dDsvDescriptorHeap = NULL; UINT m_nDsvDescriptorIncrementSize; ID3D12CommandAllocator **m_ppd3dCommandAllocators; ID3D12GraphicsCommandList **m_ppd3dCommandLists; ID3D12CommandAllocator **m_ppd3dShadowCommandAllocators; ID3D12GraphicsCommandList **m_ppd3dShadowCommandLists; ID3D12CommandQueue *m_pd3dCommandQueue = NULL; ID3D12Fence *m_pd3dFence = NULL; UINT64 m_nFenceValues[m_nSwapChainBuffers]; HANDLE m_hFenceEvent; bool m_bIsVictory = true; bool m_bReady = false; #if defined(_DEBUG) ID3D12Debug *m_pd3dDebugController; #endif CGameTimer m_GameTimer; CScene **m_ppScenes = NULL; CPlayer *m_pPlayer = NULL; CCamera *m_pCamera = NULL; POINT m_ptOldCursorPos; _TCHAR m_pszFrameRate[50]; static CGameFramework* Get() { return m_pGFforMultiThreads; } struct ThreadParameter { int threadIndex; }; ThreadParameter m_threadParameters[NUM_SUBSETS]; HANDLE m_workerBeginRenderFrame[NUM_SUBSETS]; HANDLE m_workerFinishedRenderFrame[NUM_SUBSETS]; HANDLE m_workerFinishShadowPass[NUM_SUBSETS]; HANDLE m_threadHandles[NUM_SUBSETS]; static CGameFramework* m_pGFforMultiThreads; // FMOD CFmodSound m_FmodSound; //서버 private: SOCKET g_mysocket; WSABUF send_wsabuf; char send_buffer[BUF_SIZE]; WSABUF recv_wsabuf; char recv_buffer[BUF_SIZE]; char packet_buffer[BUF_SIZE]; DWORD in_packet_size = 0; int saved_packet_size = 0; int g_myid; // 내 아이디 PLAYER_INFO g_my_info; array <PLAYER_INFO, MAX_USER> g_player_info; std::chrono::system_clock::time_point m_bulletstart; bool keystate = false; std::chrono::system_clock::time_point idlestatepoint; std::chrono::system_clock::time_point start; std::chrono::system_clock::time_point mousestart; bool istime = false; XMFLOAT3 m_xmf3PrePosition; float m_fgametime;// 게임시간. float m_fgravity; //중력 세기. XMFLOAT3 m_xmf3ObjectsPos[OBJECTS_NUMBER]; XMFLOAT4 m_xmf4ObjectsQuaternion[OBJECTS_NUMBER]; bool m_isMoveInput = false; bool m_isMovePacketRecv = false; ID3D12Resource *m_pd3dcbLights = NULL; LIGHTS *m_pcbMappedLights = NULL; ID3D12Resource *m_pd3dcbMaterials = NULL; MATERIALS *m_pcbMappedMaterials = NULL; LIGHTS * m_pLights = NULL; MATERIALS *m_pMaterials = NULL; int m_nMaterials = 0; public: void ProcessPacket(char *ptr); void ReadPacket(SOCKET sock); void InitNetwork(HWND main_window); TEAM Team[Team_NUMBER]; BASE Base[STATION_NUMBER]; };
cae9182c5ca8a070991a2422b01519d04716915f
84b7fe34b67839a2f08da10857a678a10042e181
/scene_projections/src/Grain.cpp
f9bd4589ec3fa78cf641e42a6fbcbbb5025c71a5
[]
no_license
jbloit/sound2graphics2sound
5fcd6b91badb70635620ad415f620c91d17468a0
06f60c75b45f7be186cfa55fcb228c695bdf5d28
refs/heads/master
2021-01-16T19:09:18.899999
2014-10-13T07:52:18
2014-10-13T07:52:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
99
cpp
Grain.cpp
// // Grain.cpp // shissss // // Created by Julien Bloit on 24/09/14. // // #include "Grain.h"
ed78dafaaff71a939e4c1141014a6c126a9512da
749e6814d6488aea461676385780d847e07fd380
/GDJS/GDJS/Events/CodeGeneration/EventsCodeGenerator.cpp
af1c1507f3ab0b93e5ae3ffb4c8b55d64c5428f6
[ "MIT" ]
permissive
4ian/GDevelop
258a007a2aa74bfd97c75a6c1753bc3fd48e634f
134886eedcfaeaa04139463aaf826b71c11819c5
refs/heads/master
2023-08-18T23:14:56.149709
2023-08-18T20:39:40
2023-08-18T20:39:40
21,331,090
4,722
748
NOASSERTION
2023-09-14T21:40:54
2014-06-29T19:58:38
JavaScript
UTF-8
C++
false
false
54,961
cpp
EventsCodeGenerator.cpp
/* * GDevelop JS Platform * Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights * reserved. This project is released under the MIT License. */ #include "GDCore/Events/CodeGeneration/EventsCodeGenerator.h" #include <algorithm> #include "GDCore/CommonTools.h" #include "GDCore/Events/CodeGeneration/EventsCodeGenerationContext.h" #include "GDCore/Events/Tools/EventsCodeNameMangler.h" #include "GDCore/Extensions/Metadata/EventMetadata.h" #include "GDCore/Extensions/Metadata/ExpressionMetadata.h" #include "GDCore/Extensions/Metadata/InstructionMetadata.h" #include "GDCore/Extensions/Metadata/MetadataProvider.h" #include "GDCore/Extensions/Metadata/ParameterMetadataTools.h" #include "GDCore/IDE/EventsFunctionTools.h" #include "GDCore/IDE/SceneNameMangler.h" #include "GDCore/Project/Behavior.h" #include "GDCore/Project/EventsBasedBehavior.h" #include "GDCore/Project/EventsBasedObject.h" #include "GDCore/Project/EventsFunction.h" #include "GDCore/Project/ExternalEvents.h" #include "GDCore/Project/Layout.h" #include "GDCore/Project/Object.h" #include "GDCore/Project/ObjectsContainer.h" #include "GDCore/Project/Project.h" #include "GDJS/Events/CodeGeneration/EventsCodeGenerator.h" #include "GDJS/Extensions/JsPlatform.h" using namespace std; namespace gdjs { gd::String EventsCodeGenerator::GenerateEventsListCompleteFunctionCode( gdjs::EventsCodeGenerator& codeGenerator, gd::String fullyQualifiedFunctionName, gd::String functionArgumentsCode, gd::String functionPreEventsCode, const gd::EventsList& events, gd::String functionPostEventsCode, gd::String functionReturnCode) { // Prepare the global context unsigned int maxDepthLevelReached = 0; gd::EventsCodeGenerationContext context(&maxDepthLevelReached); // Generate whole events code // Preprocessing then code generation can make changes to the events, so we // need to do the work on a copy of the events. gd::EventsList generatedEvents = events; codeGenerator.PreprocessEventList(generatedEvents); gd::String wholeEventsCode = codeGenerator.GenerateEventsListCode(generatedEvents, context); // Extra declarations needed by events gd::String globalDeclarations; for (auto& declaration : codeGenerator.GetCustomGlobalDeclaration()) globalDeclarations += declaration + "\n"; // Global objects lists auto allObjectsDeclarationsAndResets = codeGenerator.GenerateAllObjectsDeclarationsAndResets( maxDepthLevelReached); gd::String globalObjectLists = allObjectsDeclarationsAndResets.first; gd::String globalObjectListsReset = allObjectsDeclarationsAndResets.second; gd::String output = // clang-format off codeGenerator.GetCodeNamespace() + " = {};\n" + globalDeclarations + globalObjectLists + "\n\n" + codeGenerator.GetCustomCodeOutsideMain() + "\n\n" + fullyQualifiedFunctionName + " = function(" + functionArgumentsCode + ") {\n" + functionPreEventsCode + "\n" + globalObjectListsReset + "\n" + wholeEventsCode + "\n" + functionPostEventsCode + "\n" + functionReturnCode + "\n" + "}\n"; // clang-format on return output; } gd::String EventsCodeGenerator::GenerateLayoutCode( const gd::Project& project, const gd::Layout& scene, const gd::String& codeNamespace, std::set<gd::String>& includeFiles, bool compilationForRuntime) { EventsCodeGenerator codeGenerator(project, scene); codeGenerator.SetCodeNamespace(codeNamespace); codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime); gd::String output = GenerateEventsListCompleteFunctionCode( codeGenerator, codeGenerator.GetCodeNamespaceAccessor() + "func", "runtimeScene", "runtimeScene.getOnceTriggers().startNewFrame();\n", scene.GetEvents(), "", "return;\n"); includeFiles.insert(codeGenerator.GetIncludeFiles().begin(), codeGenerator.GetIncludeFiles().end()); return output; } gd::String EventsCodeGenerator::GenerateEventsFunctionCode( gd::Project& project, const gd::EventsFunctionsContainer& functionsContainer, const gd::EventsFunction& eventsFunction, const gd::String& codeNamespace, std::set<gd::String>& includeFiles, bool compilationForRuntime) { gd::ObjectsContainer globalObjectsAndGroups; gd::ObjectsContainer objectsAndGroups; gd::EventsFunctionTools::FreeEventsFunctionToObjectsContainer( project, functionsContainer, eventsFunction, globalObjectsAndGroups, objectsAndGroups); EventsCodeGenerator codeGenerator(globalObjectsAndGroups, objectsAndGroups); codeGenerator.SetCodeNamespace(codeNamespace); codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime); gd::String output = GenerateEventsListCompleteFunctionCode( codeGenerator, codeGenerator.GetCodeNamespaceAccessor() + "func", codeGenerator.GenerateEventsFunctionParameterDeclarationsList( eventsFunction.GetParametersForEvents(functionsContainer), 0, true), codeGenerator.GenerateFreeEventsFunctionContext( eventsFunction.GetParametersForEvents(functionsContainer), "runtimeScene.getOnceTriggers()", eventsFunction.IsAsync()), eventsFunction.GetEvents(), "", codeGenerator.GenerateEventsFunctionReturn(eventsFunction)); includeFiles.insert(codeGenerator.GetIncludeFiles().begin(), codeGenerator.GetIncludeFiles().end()); return output; } gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode( gd::Project& project, const gd::EventsBasedBehavior& eventsBasedBehavior, const gd::EventsFunction& eventsFunction, const gd::String& codeNamespace, const gd::String& fullyQualifiedFunctionName, const gd::String& onceTriggersVariable, const gd::String& preludeCode, std::set<gd::String>& includeFiles, bool compilationForRuntime) { gd::ObjectsContainer globalObjectsAndGroups; gd::ObjectsContainer objectsAndGroups; gd::EventsFunctionTools::BehaviorEventsFunctionToObjectsContainer( project, eventsBasedBehavior, eventsFunction, globalObjectsAndGroups, objectsAndGroups); EventsCodeGenerator codeGenerator(globalObjectsAndGroups, objectsAndGroups); codeGenerator.SetCodeNamespace(codeNamespace); codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime); // Generate the code setting up the context of the function. gd::String fullPreludeCode = preludeCode + "\n" + "var that = this;\n" + // runtimeScene is supposed to be always accessible, read // it from the behavior "var runtimeScene = this._runtimeScene;\n" + // By convention of Behavior Events Function, the object is accessible // as a parameter called "Object", and thisObjectList is an array // containing it (for faster access, without having to go through the // hashmap). "var thisObjectList = [this.owner];\n" + "var Object = Hashtable.newFrom({Object: thisObjectList});\n" + // By convention of Behavior Events Function, the behavior is accessible // as a parameter called "Behavior". "var Behavior = this.name;\n" + codeGenerator.GenerateBehaviorEventsFunctionContext( eventsBasedBehavior, eventsFunction.GetParametersForEvents( eventsBasedBehavior.GetEventsFunctions()), onceTriggersVariable, eventsFunction.IsAsync(), // Pass the names of the parameters considered as the current // object and behavior parameters: "Object", "Behavior"); gd::String output = GenerateEventsListCompleteFunctionCode( codeGenerator, fullyQualifiedFunctionName, codeGenerator.GenerateEventsFunctionParameterDeclarationsList( eventsFunction.GetParametersForEvents( eventsBasedBehavior.GetEventsFunctions()), 2, false), fullPreludeCode, eventsFunction.GetEvents(), "", codeGenerator.GenerateEventsFunctionReturn(eventsFunction)); includeFiles.insert(codeGenerator.GetIncludeFiles().begin(), codeGenerator.GetIncludeFiles().end()); return output; } gd::String EventsCodeGenerator::GenerateObjectEventsFunctionCode( gd::Project& project, const gd::EventsBasedObject& eventsBasedObject, const gd::EventsFunction& eventsFunction, const gd::String& codeNamespace, const gd::String& fullyQualifiedFunctionName, const gd::String& onceTriggersVariable, const gd::String& preludeCode, const gd::String& endingCode, std::set<gd::String>& includeFiles, bool compilationForRuntime) { gd::ObjectsContainer globalObjectsAndGroups; gd::ObjectsContainer objectsAndGroups; gd::EventsFunctionTools::ObjectEventsFunctionToObjectsContainer( project, eventsBasedObject, eventsFunction, globalObjectsAndGroups, objectsAndGroups); EventsCodeGenerator codeGenerator(globalObjectsAndGroups, objectsAndGroups); codeGenerator.SetCodeNamespace(codeNamespace); codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime); // Generate the code setting up the context of the function. gd::String fullPreludeCode = preludeCode + "\n" + "var that = this;\n" + // runtimeScene is supposed to be always accessible, read // it from the object "var runtimeScene = this._instanceContainer;\n" + // By convention of Object Events Function, the object is accessible // as a parameter called "Object", and thisObjectList is an array // containing it (for faster access, without having to go through the // hashmap). "var thisObjectList = [this];\n" + "var Object = Hashtable.newFrom({Object: thisObjectList});\n"; // Add child-objects for (auto& childObject : eventsBasedObject.GetObjects()) { // child-object are never picked because they are not parameters. const auto& childName = ManObjListName(childObject->GetName()); fullPreludeCode += "var this" + childName + "List = [...runtimeScene.getObjects(" + ConvertToStringExplicit(childObject->GetName()) + ")];\n" + "var " + childName + " = Hashtable.newFrom({" + ConvertToStringExplicit(childObject->GetName()) + ": this" + childName + "List});\n"; } fullPreludeCode += codeGenerator.GenerateObjectEventsFunctionContext( eventsBasedObject, eventsFunction.GetParametersForEvents( eventsBasedObject.GetEventsFunctions()), onceTriggersVariable, eventsFunction.IsAsync(), // Pass the names of the parameters considered as the current // object and behavior parameters: "Object"); gd::String output = GenerateEventsListCompleteFunctionCode( codeGenerator, fullyQualifiedFunctionName, codeGenerator.GenerateEventsFunctionParameterDeclarationsList( // TODO EBO use constants for firstParameterIndex eventsFunction.GetParametersForEvents( eventsBasedObject.GetEventsFunctions()), 1, false), fullPreludeCode, eventsFunction.GetEvents(), endingCode, codeGenerator.GenerateEventsFunctionReturn(eventsFunction)); includeFiles.insert(codeGenerator.GetIncludeFiles().begin(), codeGenerator.GetIncludeFiles().end()); return output; } gd::String EventsCodeGenerator::GenerateEventsFunctionParameterDeclarationsList( const vector<gd::ParameterMetadata>& parameters, int firstParameterIndex, bool addsSceneParameter) { gd::String declaration = addsSceneParameter ? "runtimeScene" : ""; for (size_t i = 0; i < parameters.size(); ++i) { const auto& parameter = parameters[i]; if (i < firstParameterIndex) { // By convention, the first two arguments of a behavior events function // are the object and the behavior, which are not passed to the called // function in the generated JS code. continue; } declaration += (declaration.empty() ? "" : ", ") + (parameter.GetName().empty() ? "_" : parameter.GetName()); } declaration += gd::String(declaration.empty() ? "" : ", ") + "parentEventsFunctionContext"; return declaration; } gd::String EventsCodeGenerator::GenerateFreeEventsFunctionContext( const vector<gd::ParameterMetadata>& parameters, const gd::String& onceTriggersVariable, bool isAsync) { gd::String objectsGettersMap; gd::String objectArraysMap; gd::String behaviorNamesMap; return GenerateEventsFunctionContext(parameters, onceTriggersVariable, objectsGettersMap, objectArraysMap, behaviorNamesMap, isAsync); } gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionContext( const gd::EventsBasedBehavior& eventsBasedBehavior, const vector<gd::ParameterMetadata>& parameters, const gd::String& onceTriggersVariable, bool isAsync, const gd::String& thisObjectName, const gd::String& thisBehaviorName) { // See the comment at the start of the GenerateEventsFunctionContext function gd::String objectsGettersMap; gd::String objectArraysMap; gd::String behaviorNamesMap; // If we have an object considered as the current object ("this") (usually // called Object in behavior events function), generate a slightly more // optimized getter for it (bypassing "Object" hashmap, and directly return // the array containing it). if (!thisObjectName.empty()) { objectsGettersMap += ConvertToStringExplicit(thisObjectName) + ": " + thisObjectName + "\n"; objectArraysMap += ConvertToStringExplicit(thisObjectName) + ": thisObjectList\n"; } if (!thisBehaviorName.empty()) { // If we have a behavior considered as the current behavior ("this") // (usually called Behavior in behavior events function), generate a // slightly more optimized getter for it. behaviorNamesMap += ConvertToStringExplicit(thisBehaviorName) + ": " + thisBehaviorName + "\n"; // Add required behaviors from properties for (size_t i = 0; i < eventsBasedBehavior.GetPropertyDescriptors().GetCount(); i++) { const gd::NamedPropertyDescriptor& propertyDescriptor = eventsBasedBehavior.GetPropertyDescriptors().Get(i); const std::vector<gd::String>& extraInfo = propertyDescriptor.GetExtraInfo(); if (propertyDescriptor.GetType() == "Behavior") { // Generate map that will be used to transform from behavior name used // in function to the "real" behavior name from the caller. gd::String comma = behaviorNamesMap.empty() ? "" : ", "; behaviorNamesMap += comma + ConvertToStringExplicit(propertyDescriptor.GetName()) + ": this._get" + propertyDescriptor.GetName() + "()\n"; } } } return GenerateEventsFunctionContext(parameters, onceTriggersVariable, objectsGettersMap, objectArraysMap, behaviorNamesMap, isAsync, thisObjectName, thisBehaviorName); } gd::String EventsCodeGenerator::GenerateObjectEventsFunctionContext( const gd::EventsBasedObject& eventsBasedObject, const vector<gd::ParameterMetadata>& parameters, const gd::String& onceTriggersVariable, bool isAsync, const gd::String& thisObjectName) { // See the comment at the start of the GenerateEventsFunctionContext function gd::String objectsGettersMap; gd::String objectArraysMap; gd::String behaviorNamesMap; // If we have an object considered as the current object ("this") (usually // called Object in behavior events function), generate a slightly more // optimized getter for it (bypassing "Object" hashmap, and directly return // the array containing it). if (!thisObjectName.empty()) { objectsGettersMap += ConvertToStringExplicit(thisObjectName) + ": " + thisObjectName + "\n"; objectArraysMap += ConvertToStringExplicit(thisObjectName) + ": thisObjectList\n"; // Add child-objects for (auto& childObject : eventsBasedObject.GetObjects()) { const auto& childName = ManObjListName(childObject->GetName()); // child-object are never picked because they are not parameters. objectsGettersMap += ", " + ConvertToStringExplicit(childObject->GetName()) + ": " + childName + "\n"; objectArraysMap += ", " + ConvertToStringExplicit(childObject->GetName()) + ": this" + childName + "List\n"; } } return GenerateEventsFunctionContext(parameters, onceTriggersVariable, objectsGettersMap, objectArraysMap, behaviorNamesMap, isAsync, thisObjectName); } gd::String EventsCodeGenerator::GenerateEventsFunctionContext( const vector<gd::ParameterMetadata>& parameters, const gd::String& onceTriggersVariable, gd::String& objectsGettersMap, gd::String& objectArraysMap, gd::String& behaviorNamesMap, bool isAsync, const gd::String& thisObjectName, const gd::String& thisBehaviorName) { // When running in the context of a function generated from events, we // need some indirection to deal with objects, behaviors and parameters in // general: // // * Each map of objects passed as parameter needs to be queryable as an array // of objects. // * Behaviors are passed as string, representing the name of the behavior. // This can differ from the name used to refer to the behavior in the events // of the function (for example, a behavior can simply be called "Behavior" in // the parameter name). // * For other parameters, allow to access to them without transformation. // Conditions/expressions are available to deal with them in events. gd::String argumentsGetters; for (const auto& parameter : parameters) { if (parameter.GetName().empty()) continue; if (gd::ParameterMetadata::IsObject(parameter.GetType())) { if (parameter.GetName() == thisObjectName) { continue; } // Generate map that will be used to get the lists of objects passed // as parameters (either as objects lists or array). gd::String comma = objectsGettersMap.empty() ? "" : ", "; objectsGettersMap += comma + ConvertToStringExplicit(parameter.GetName()) + ": " + parameter.GetName() + "\n"; objectArraysMap += comma + ConvertToStringExplicit(parameter.GetName()) + ": gdjs.objectsListsToArray(" + parameter.GetName() + ")\n"; } else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) { if (parameter.GetName() == thisBehaviorName) { continue; } // Generate map that will be used to transform from behavior name used in // function to the "real" behavior name from the caller. gd::String comma = behaviorNamesMap.empty() ? "" : ", "; behaviorNamesMap += comma + ConvertToStringExplicit(parameter.GetName()) + ": " + parameter.GetName() + "\n"; } else { argumentsGetters += "if (argName === " + ConvertToStringExplicit(parameter.GetName()) + ") return " + parameter.GetName() + ";\n"; } } const gd::String async = isAsync ? " task: new gdjs.ManuallyResolvableTask(),\n" : ""; return gd::String("var eventsFunctionContext = {\n") + // The async task, if there is one async + // The object name to parameter map: " _objectsMap: {\n" + objectsGettersMap + "},\n" // The object name to arrays map: " _objectArraysMap: {\n" + objectArraysMap + "},\n" // The behavior name to parameter map: " _behaviorNamesMap: {\n" + behaviorNamesMap + "},\n" // Function that will be used to query objects, when a new object list // is needed by events. We assume it's used a lot by the events // generated code, so we cache the arrays in a map. " getObjects: function(objectName) {\n" + " return eventsFunctionContext._objectArraysMap[objectName] || " "[];\n" + " },\n" + // Function that can be used in JS code to get the lists of objects // and filter/alter them (not actually used in events). " getObjectsLists: function(objectName) {\n" + " return eventsFunctionContext._objectsMap[objectName] || null;\n" " },\n" + // Function that will be used to query behavior name (as behavior name // can be different between the parameter name vs the actual behavior // name passed as argument). " getBehaviorName: function(behaviorName) {\n" + // TODO EBO Handle behavior name collision between parameters and // children " return eventsFunctionContext._behaviorNamesMap[behaviorName] || " "behaviorName;\n" " },\n" + // Creator function that will be used to create new objects. We // need to check if the function was given the context of the calling // function (parentEventsFunctionContext). If this is the case, use it // to create the new object as the object names used in the function // are not the same as the objects available in the scene. " createObject: function(objectName) {\n" " const objectsList = " "eventsFunctionContext._objectsMap[objectName];\n" + // TODO: we could speed this up by storing a map of object names, but // the cost of creating/storing it for each events function might not // be worth it. " if (objectsList) {\n" + " const object = parentEventsFunctionContext ?\n" + " " "parentEventsFunctionContext.createObject(objectsList.firstKey()) " ":\n" + " runtimeScene.createObject(objectsList.firstKey());\n" + // Add the new instance to object lists " if (object) {\n" + " objectsList.get(objectsList.firstKey()).push(object);\n" + " " "eventsFunctionContext._objectArraysMap[objectName].push(object);\n" + " }\n" + " return object;" + " }\n" + // Unknown object, don't create anything: " return null;\n" + " },\n" // Function to count instances on the scene. We need it here because // it needs the objects map to get the object names of the parent // context. " getInstancesCountOnScene: function(objectName) {\n" " const objectsList = " "eventsFunctionContext._objectsMap[objectName];\n" + " let count = 0;\n" + " if (objectsList) {\n" + " for(const objectName in objectsList.items)\n" + " count += parentEventsFunctionContext ?\n" + "parentEventsFunctionContext.getInstancesCountOnScene(objectName) " ":\n" + " runtimeScene.getInstancesCountOnScene(objectName);\n" + " }\n" + " return count;\n" + " },\n" // Allow to get a layer directly from the context for convenience: " getLayer: function(layerName) {\n" " return runtimeScene.getLayer(layerName);\n" " },\n" // Getter for arguments that are not objects " getArgument: function(argName) {\n" + argumentsGetters + " return \"\";\n" + " },\n" + // Expose OnceTriggers (will be pointing either to the runtime scene // ones, or the ones from the behavior): " getOnceTriggers: function() { return " + onceTriggersVariable + "; }\n" + "};\n"; } gd::String EventsCodeGenerator::GenerateEventsFunctionReturn( const gd::EventsFunction& eventsFunction) { if (eventsFunction.IsAsync()) return "return eventsFunctionContext.task"; // We don't use IsCondition because ExpressionAndCondition event functions // don't need a boolean function. They use the expression function with a // relational operator. if (eventsFunction.GetFunctionType() == gd::EventsFunction::Condition) { return "return !!eventsFunctionContext.returnValue;"; } else if (eventsFunction.IsExpression()) { if (eventsFunction.GetExpressionType().IsNumber()) { return "return Number(eventsFunctionContext.returnValue) || 0;"; } else { // Default on string because it's more likely that future expression // types are strings. return "return \"\" + eventsFunctionContext.returnValue;"; } } return "return;"; } std::pair<gd::String, gd::String> EventsCodeGenerator::GenerateAllObjectsDeclarationsAndResets( unsigned int maxDepthLevelReached) { gd::String globalObjectLists; gd::String globalObjectListsReset; auto generateDeclarations = [this, &maxDepthLevelReached, &globalObjectLists, &globalObjectListsReset](const gd::Object& object) { // Generate declarations for the objects lists for (unsigned int j = 1; j <= maxDepthLevelReached; ++j) { globalObjectLists += GetCodeNamespaceAccessor() + ManObjListName(object.GetName()) + gd::String::From(j) + "= [];\n"; globalObjectListsReset += GetCodeNamespaceAccessor() + ManObjListName(object.GetName()) + gd::String::From(j) + ".length = 0;\n"; } }; for (std::size_t i = 0; i < globalObjectsAndGroups.GetObjectsCount(); ++i) generateDeclarations(globalObjectsAndGroups.GetObject(i)); for (std::size_t i = 0; i < objectsAndGroups.GetObjectsCount(); ++i) generateDeclarations(objectsAndGroups.GetObject(i)); return std::make_pair(globalObjectLists, globalObjectListsReset); } gd::String EventsCodeGenerator::GenerateObjectFunctionCall( gd::String objectListName, const gd::ObjectMetadata& objMetadata, const gd::ExpressionCodeGenerationInformation& codeInfo, gd::String parametersStr, gd::String defaultOutput, gd::EventsCodeGenerationContext& context) { if (codeInfo.staticFunction) return "(" + codeInfo.functionCallName + "(" + parametersStr + "))"; if (context.GetCurrentObject() == objectListName && !context.GetCurrentObject().empty()) return "(" + GetObjectListName(objectListName, context) + "[i]." + codeInfo.functionCallName + "(" + parametersStr + "))"; else return "(( " + GetObjectListName(objectListName, context) + ".length === 0 ) ? " + defaultOutput + " :" + GetObjectListName(objectListName, context) + "[0]." + codeInfo.functionCallName + "(" + parametersStr + "))"; } gd::String EventsCodeGenerator::GenerateObjectBehaviorFunctionCall( gd::String objectListName, gd::String behaviorName, const gd::BehaviorMetadata& autoInfo, const gd::ExpressionCodeGenerationInformation& codeInfo, gd::String parametersStr, gd::String defaultOutput, gd::EventsCodeGenerationContext& context) { if (codeInfo.staticFunction) return "(" + codeInfo.functionCallName + "(" + parametersStr + "))"; if (context.GetCurrentObject() == objectListName && !context.GetCurrentObject().empty()) return "(" + GetObjectListName(objectListName, context) + "[i].getBehavior(" + GenerateGetBehaviorNameCode(behaviorName) + ")." + codeInfo.functionCallName + "(" + parametersStr + "))"; else return "(( " + GetObjectListName(objectListName, context) + ".length === 0 ) ? " + defaultOutput + " :" + GetObjectListName(objectListName, context) + "[0].getBehavior(" + GenerateGetBehaviorNameCode(behaviorName) + ")." + codeInfo.functionCallName + "(" + parametersStr + "))"; } gd::String EventsCodeGenerator::GenerateFreeCondition( const std::vector<gd::String>& arguments, const gd::InstructionMetadata& instrInfos, const gd::String& returnBoolean, bool conditionInverted, gd::EventsCodeGenerationContext& context) { // Generate call gd::String predicate; if (instrInfos.codeExtraInformation.type == "number" || instrInfos.codeExtraInformation.type == "string") { predicate = GenerateRelationalOperatorCall( instrInfos, arguments, instrInfos.codeExtraInformation.functionCallName); } else { predicate = instrInfos.codeExtraInformation.functionCallName + "(" + GenerateArgumentsList(arguments) + ")"; } // Add logical not if needed bool conditionAlreadyTakeCareOfInversion = false; for (std::size_t i = 0; i < instrInfos.parameters.size(); ++i) // Some conditions already have a "conditionInverted" parameter { if (instrInfos.parameters[i].GetType() == "conditionInverted") conditionAlreadyTakeCareOfInversion = true; } if (!conditionAlreadyTakeCareOfInversion && conditionInverted) predicate = GenerateNegatedPredicate(predicate); // Generate condition code return GenerateBooleanFullName(returnBoolean, context) + " = " + predicate + ";\n"; } gd::String EventsCodeGenerator::GenerateObjectCondition( const gd::String& objectName, const gd::ObjectMetadata& objInfo, const std::vector<gd::String>& arguments, const gd::InstructionMetadata& instrInfos, const gd::String& returnBoolean, bool conditionInverted, gd::EventsCodeGenerationContext& context) { gd::String conditionCode; // Prepare call gd::String objectFunctionCallNamePart = GetObjectListName(objectName, context) + "[i]." + instrInfos.codeExtraInformation.functionCallName; // Create call gd::String predicate; if ((instrInfos.codeExtraInformation.type == "number" || instrInfos.codeExtraInformation.type == "string")) { predicate = GenerateRelationalOperatorCall( instrInfos, arguments, objectFunctionCallNamePart, 1); } else { predicate = objectFunctionCallNamePart + "(" + GenerateArgumentsList(arguments, 1) + ")"; } if (conditionInverted) predicate = GenerateNegatedPredicate(predicate); // Generate whole condition code conditionCode += "for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) + ".length;i<l;++i) {\n"; conditionCode += " if ( " + predicate + " ) {\n"; conditionCode += " " + GenerateBooleanFullName(returnBoolean, context) + " = true;\n"; conditionCode += " " + GetObjectListName(objectName, context) + "[k] = " + GetObjectListName(objectName, context) + "[i];\n"; conditionCode += " ++k;\n"; conditionCode += " }\n"; conditionCode += "}\n"; conditionCode += GetObjectListName(objectName, context) + ".length = k;\n"; return conditionCode; } gd::String EventsCodeGenerator::GenerateBehaviorCondition( const gd::String& objectName, const gd::String& behaviorName, const gd::BehaviorMetadata& autoInfo, const std::vector<gd::String>& arguments, const gd::InstructionMetadata& instrInfos, const gd::String& returnBoolean, bool conditionInverted, gd::EventsCodeGenerationContext& context) { gd::String conditionCode; // Prepare call gd::String objectFunctionCallNamePart = GetObjectListName(objectName, context) + "[i].getBehavior(" + GenerateGetBehaviorNameCode(behaviorName) + ")." + instrInfos.codeExtraInformation.functionCallName; // Create call gd::String predicate; if ((instrInfos.codeExtraInformation.type == "number" || instrInfos.codeExtraInformation.type == "string")) { predicate = GenerateRelationalOperatorCall( instrInfos, arguments, objectFunctionCallNamePart, 2); } else { predicate = objectFunctionCallNamePart + "(" + GenerateArgumentsList(arguments, 2) + ")"; } if (conditionInverted) predicate = GenerateNegatedPredicate(predicate); // Verify that object has behavior. vector<gd::String> behaviors = gd::GetBehaviorsOfObject( globalObjectsAndGroups, objectsAndGroups, objectName); if (find(behaviors.begin(), behaviors.end(), behaviorName) == behaviors.end()) { cout << "Error: bad behavior \"" << behaviorName << "\" requested for object \'" << objectName << "\" (condition: " << instrInfos.GetFullName() << ")." << endl; } else { conditionCode += "for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) + ".length;i<l;++i) {\n"; conditionCode += " if ( " + predicate + " ) {\n"; conditionCode += " " + GenerateBooleanFullName(returnBoolean, context) + " = true;\n"; conditionCode += " " + GetObjectListName(objectName, context) + "[k] = " + GetObjectListName(objectName, context) + "[i];\n"; conditionCode += " ++k;\n"; conditionCode += " }\n"; conditionCode += "}\n"; conditionCode += GetObjectListName(objectName, context) + ".length = k;\n"; } return conditionCode; } gd::String EventsCodeGenerator::GenerateObjectAction( const gd::String& objectName, const gd::ObjectMetadata& objInfo, const gd::String& functionCallName, const std::vector<gd::String>& arguments, const gd::InstructionMetadata& instrInfos, gd::EventsCodeGenerationContext& context, const gd::String& optionalAsyncCallbackName) { gd::String actionCode; // Prepare call gd::String objectPart = GetObjectListName(objectName, context) + "[i]."; // Create call gd::String call; if (instrInfos.codeExtraInformation.type == "number" || instrInfos.codeExtraInformation.type == "string") { if (instrInfos.codeExtraInformation.accessType == gd::InstructionMetadata::ExtraInformation::MutatorAndOrAccessor) call = GenerateOperatorCall( instrInfos, arguments, objectPart + functionCallName, objectPart + instrInfos.codeExtraInformation.optionalAssociatedInstruction, 1); else if (instrInfos.codeExtraInformation.accessType == gd::InstructionMetadata::ExtraInformation::Mutators) call = GenerateMutatorCall( instrInfos, arguments, objectPart + functionCallName, 1); else call = GenerateCompoundOperatorCall( instrInfos, arguments, objectPart + functionCallName, 1); } else { call = objectPart + functionCallName + "(" + GenerateArgumentsList(arguments, 1) + ")"; } if (!optionalAsyncCallbackName.empty()) { actionCode += "{\nconst asyncTaskGroup = new gdjs.TaskGroup();\n"; call = "asyncTaskGroup.addTask(" + call + ")"; } actionCode += "for(var i = 0, len = " + GetObjectListName(objectName, context) + ".length ;i < len;++i) {\n"; actionCode += " " + call + ";\n"; actionCode += "}\n"; if (!optionalAsyncCallbackName.empty()) { actionCode += "runtimeScene.getAsyncTasksManager().addTask(asyncTaskGroup, " + optionalAsyncCallbackName + ")\n}"; } return actionCode; } gd::String EventsCodeGenerator::GenerateBehaviorAction( const gd::String& objectName, const gd::String& behaviorName, const gd::BehaviorMetadata& autoInfo, const gd::String& functionCallName, const std::vector<gd::String>& arguments, const gd::InstructionMetadata& instrInfos, gd::EventsCodeGenerationContext& context, const gd::String& optionalAsyncCallbackName) { gd::String actionCode; // Prepare call gd::String objectPart = GetObjectListName(objectName, context) + "[i].getBehavior(" + GenerateGetBehaviorNameCode(behaviorName) + ")."; // Create call gd::String call; if ((instrInfos.codeExtraInformation.type == "number" || instrInfos.codeExtraInformation.type == "string")) { if (instrInfos.codeExtraInformation.accessType == gd::InstructionMetadata::ExtraInformation::MutatorAndOrAccessor) call = GenerateOperatorCall( instrInfos, arguments, objectPart + functionCallName, objectPart + instrInfos.codeExtraInformation.optionalAssociatedInstruction, 2); else if (instrInfos.codeExtraInformation.accessType == gd::InstructionMetadata::ExtraInformation::Mutators) call = GenerateMutatorCall( instrInfos, arguments, objectPart + functionCallName, 2); else call = GenerateCompoundOperatorCall( instrInfos, arguments, objectPart + functionCallName, 2); } else { call = objectPart + functionCallName + "(" + GenerateArgumentsList(arguments, 2) + ")"; } // Verify that object has behavior. vector<gd::String> behaviors = gd::GetBehaviorsOfObject( globalObjectsAndGroups, objectsAndGroups, objectName); if (find(behaviors.begin(), behaviors.end(), behaviorName) == behaviors.end()) { cout << "Error: bad behavior \"" << behaviorName << "\" requested for object \'" << objectName << "\" (action: " << instrInfos.GetFullName() << ")." << endl; } else { if (!optionalAsyncCallbackName.empty()) { actionCode += "{\n const asyncTaskGroup = new gdjs.TaskGroup();\n"; call = "asyncTaskGroup.addTask(" + call + ")"; } actionCode += "for(var i = 0, len = " + GetObjectListName(objectName, context) + ".length ;i < len;++i) {\n"; actionCode += " " + call + ";\n"; actionCode += "}\n"; if (!optionalAsyncCallbackName.empty()) { actionCode += "runtimeScene.getAsyncTasksManager().addTask(asyncTaskGroup, " + optionalAsyncCallbackName + ");\n };"; } } return actionCode; } gd::String EventsCodeGenerator::GetObjectListName( const gd::String& name, const gd::EventsCodeGenerationContext& context) { return GetCodeNamespaceAccessor() + ManObjListName(name) + gd::String::From(context.GetLastDepthObjectListWasNeeded(name)); } gd::String EventsCodeGenerator::GenerateGetBehaviorNameCode( const gd::String& behaviorName) { if (HasProjectAndLayout()) { return ConvertToStringExplicit(behaviorName); } else { return "eventsFunctionContext.getBehaviorName(" + ConvertToStringExplicit(behaviorName) + ")"; } } gd::String EventsCodeGenerator::GenerateObjectsDeclarationCode( gd::EventsCodeGenerationContext& context) { auto declareObjectListFromParent = [this](gd::String object, gd::EventsCodeGenerationContext& context) { gd::String objectListName = GetObjectListName(object, context); if (!context.GetParentContext()) { std::cout << "ERROR: During code generation, a context tried to use an " "already declared object list without having a parent" << std::endl; return "/* Could not declare " + objectListName + " */"; } if (context.ShouldUseAsyncObjectsList(object)) { gd::String copiedListName = "asyncObjectsList.getObjects(" + ConvertToStringExplicit(object) + ")"; return "gdjs.copyArray(" + copiedListName + ", " + objectListName + ");\n"; } //*Optimization*: Avoid expensive copy of the object list if we're using // the same list as the one from the parent context. if (context.IsSameObjectsList(object, *context.GetParentContext())) return "/* Reuse " + objectListName + " */"; gd::String copiedListName = GetObjectListName(object, *context.GetParentContext()); return "gdjs.copyArray(" + copiedListName + ", " + objectListName + ");\n"; }; gd::String declarationsCode; for (auto object : context.GetObjectsListsToBeDeclared()) { gd::String objectListDeclaration = ""; if (!context.ObjectAlreadyDeclaredByParents(object)) { objectListDeclaration += "gdjs.copyArray(" + GenerateAllInstancesGetterCode(object, context) + ", " + GetObjectListName(object, context) + ");"; } else objectListDeclaration = declareObjectListFromParent(object, context); declarationsCode += objectListDeclaration + "\n"; } for (auto object : context.GetObjectsListsToBeEmptyIfJustDeclared()) { gd::String objectListDeclaration = ""; if (!context.ObjectAlreadyDeclaredByParents(object)) { objectListDeclaration = GetObjectListName(object, context) + ".length = 0;\n"; } else objectListDeclaration = declareObjectListFromParent(object, context); declarationsCode += objectListDeclaration + "\n"; } for (auto object : context.GetObjectsListsToBeDeclaredEmpty()) { gd::String objectListDeclaration = ""; if (!context.ObjectAlreadyDeclaredByParents(object)) { objectListDeclaration = GetObjectListName(object, context) + ".length = 0;\n"; } else objectListDeclaration = GetObjectListName(object, context) + ".length = 0;\n"; declarationsCode += objectListDeclaration + "\n"; } return declarationsCode; } gd::String EventsCodeGenerator::GenerateAllInstancesGetterCode( const gd::String& objectName, gd::EventsCodeGenerationContext& context) { if (HasProjectAndLayout()) { return "runtimeScene.getObjects(" + ConvertToStringExplicit(objectName) + ")"; } else { return "eventsFunctionContext.getObjects(" + ConvertToStringExplicit(objectName) + ")"; } } gd::String EventsCodeGenerator::GenerateEventsListCode( gd::EventsList& events, gd::EventsCodeGenerationContext& context) { // *Optimization*: generating all JS code of events in a single, enormous // function is badly handled by JS engines and in particular the garbage // collectors, leading to intermittent lag/freeze while the garbage collector // is running. This is especially noticeable on Android devices. To reduce the // stress on the JS engines, we generate a new function for each list of // events. gd::String code = gd::EventsCodeGenerator::GenerateEventsListCode(events, context); gd::String parametersCode = GenerateEventsParameters(context); // Generate a unique name for the function. gd::String uniqueId = gd::String::From(GenerateSingleUsageUniqueIdForEventsList()); gd::String functionName = GetCodeNamespaceAccessor() + "eventsList" + uniqueId; // The only local parameters are runtimeScene and context. // List of objects, conditions booleans and any variables used by events // are stored in static variables that are globally available by the whole // code. AddCustomCodeOutsideMain(functionName + " = function(" + parametersCode + ") {\n" + code + "\n" + "};"); // Replace the code of the events by the call to the function. This does not // interfere with the objects picking as the lists are in static variables // globally available. return functionName + "(" + parametersCode + ");"; } gd::String EventsCodeGenerator::GenerateConditionsListCode( gd::InstructionsList& conditions, gd::EventsCodeGenerationContext& context) { gd::String outputCode; outputCode += GenerateBooleanInitializationToFalse( "isConditionTrue", context); for (std::size_t cId = 0; cId < conditions.size(); ++cId) { if (cId != 0) { outputCode += "if (" + GenerateBooleanFullName("isConditionTrue", context) + ") {\n"; } gd::String conditionCode = GenerateConditionCode(conditions[cId], "isConditionTrue", context); if (!conditions[cId].GetType().empty()) { outputCode += GenerateBooleanFullName("isConditionTrue", context) + " = false;\n"; outputCode += conditionCode; } } // Close nested "if". for (std::size_t cId = 0; cId < conditions.size(); ++cId) { if (cId != 0) outputCode += "}\n"; } maxConditionsListsSize = std::max(maxConditionsListsSize, conditions.size()); return outputCode; } gd::String EventsCodeGenerator::GenerateParameterCodes( const gd::Expression& parameter, const gd::ParameterMetadata& metadata, gd::EventsCodeGenerationContext& context, const gd::String& lastObjectName, std::vector<std::pair<gd::String, gd::String> >* supplementaryParametersTypes) { gd::String argOutput; // Code only parameter type if (metadata.GetType() == "currentScene") { argOutput = "runtimeScene"; } // Code only parameter type else if (metadata.GetType() == "objectsContext") { argOutput = "(typeof eventsFunctionContext !== 'undefined' ? eventsFunctionContext " ": runtimeScene)"; } // Code only parameter type else if (metadata.GetType() == "eventsFunctionContext") { argOutput = "(typeof eventsFunctionContext !== 'undefined' ? eventsFunctionContext " ": undefined)"; } else return gd::EventsCodeGenerator::GenerateParameterCodes( parameter, metadata, context, lastObjectName, supplementaryParametersTypes); return argOutput; } gd::String EventsCodeGenerator::GenerateObject( const gd::String& objectName, const gd::String& type, gd::EventsCodeGenerationContext& context) { //*Optimization:* when a function need objects, it receive a map of //(references to) objects lists. We statically declare and construct them to // avoid re-creating them at runtime. Arrays are passed as reference in JS and // we always use the same static arrays, making this possible. auto declareMapOfObjects = [this](const std::vector<gd::String>& declaredObjectNames, const gd::EventsCodeGenerationContext& context, const std::vector<gd::String>& notDeclaredObjectNames = {}) { // The map name must be unique for each set of objects lists. // We generate it from the objects lists names. gd::String objectsMapName = GetCodeNamespaceAccessor() + "mapOf"; gd::String mapDeclaration; // Map each declared object to its list. for (auto& objectName : declaredObjectNames) { objectsMapName += ManObjListName(GetObjectListName(objectName, context)); if (!mapDeclaration.empty()) mapDeclaration += ", "; mapDeclaration += "\"" + ConvertToString(objectName) + "\": " + GetObjectListName(objectName, context); } // Map each object not declared to an empty list. // Useful for parameters willing to get objects lists without // picking the objects for future instructions. for (auto& objectName : notDeclaredObjectNames) { objectsMapName += "Empty" + ManObjListName(objectName); if (!mapDeclaration.empty()) mapDeclaration += ", "; mapDeclaration += "\"" + ConvertToString(objectName) + "\": []"; } // TODO: this should be de-duplicated. AddCustomCodeOutsideMain(objectsMapName + " = Hashtable.newFrom({" + mapDeclaration + "});\n"); return objectsMapName; }; gd::String output; if (type == "objectList") { std::vector<gd::String> realObjects = ExpandObjectsName(objectName, context); for (auto& objectName : realObjects) context.ObjectsListNeeded(objectName); gd::String objectsMapName = declareMapOfObjects(realObjects, context); output = objectsMapName; } else if (type == "objectListOrEmptyIfJustDeclared") { std::vector<gd::String> realObjects = ExpandObjectsName(objectName, context); for (auto& objectName : realObjects) context.ObjectsListNeededOrEmptyIfJustDeclared(objectName); gd::String objectsMapName = declareMapOfObjects(realObjects, context); output = objectsMapName; } else if (type == "objectListOrEmptyWithoutPicking") { std::vector<gd::String> realObjects = ExpandObjectsName(objectName, context); // Find the objects not yet declared, and handle them separately so they are // passed as empty object lists. std::vector<gd::String> objectToBeDeclaredNames; std::vector<gd::String> objectNotYetDeclaredNames; for (auto& objectName : realObjects) { if (context.ObjectAlreadyDeclaredByParents(objectName) || context.IsToBeDeclared(objectName)) { objectToBeDeclaredNames.push_back(objectName); } else { objectNotYetDeclaredNames.push_back(objectName); } } gd::String objectsMapName = declareMapOfObjects( objectToBeDeclaredNames, context, objectNotYetDeclaredNames); output = objectsMapName; } else if (type == "objectPtr") { std::vector<gd::String> realObjects = ExpandObjectsName(objectName, context); if (find(realObjects.begin(), realObjects.end(), context.GetCurrentObject()) != realObjects.end() && !context.GetCurrentObject().empty()) { // If object currently used by instruction is available, use it directly. output = GetObjectListName(context.GetCurrentObject(), context) + "[i]"; } else { for (std::size_t i = 0; i < realObjects.size(); ++i) { context.ObjectsListNeeded(realObjects[i]); output += "(" + GetObjectListName(realObjects[i], context) + ".length !== 0 ? " + GetObjectListName(realObjects[i], context) + "[0] : "; } output += GenerateBadObject(); for (std::size_t i = 0; i < realObjects.size(); ++i) output += ")"; } } return output; } gd::String EventsCodeGenerator::GenerateGetVariable( const gd::String& variableName, const VariableScope& scope, gd::EventsCodeGenerationContext& context, const gd::String& objectName) { gd::String output; const gd::VariablesContainer* variables = NULL; if (scope == LAYOUT_VARIABLE) { output = "runtimeScene.getScene().getVariables()"; if (HasProjectAndLayout()) { variables = &GetLayout().GetVariables(); } } else if (scope == PROJECT_VARIABLE) { output = "runtimeScene.getGame().getVariables()"; if (HasProjectAndLayout()) { variables = &GetProject().GetVariables(); } } else { std::vector<gd::String> realObjects = ExpandObjectsName(objectName, context); output = "gdjs.VariablesContainer.badVariablesContainer"; for (std::size_t i = 0; i < realObjects.size(); ++i) { context.ObjectsListNeeded(realObjects[i]); // Generate the call to GetVariables() method. if (context.GetCurrentObject() == realObjects[i] && !context.GetCurrentObject().empty()) output = GetObjectListName(realObjects[i], context) + "[i].getVariables()"; else output = "((" + GetObjectListName(realObjects[i], context) + ".length === 0 ) ? " + output + " : " + GetObjectListName(realObjects[i], context) + "[0].getVariables())"; } if (HasProjectAndLayout()) { if (GetLayout().HasObjectNamed( objectName)) // We check first layout's objects' list. variables = &GetLayout().GetObject(objectName).GetVariables(); else if (GetProject().HasObjectNamed( objectName)) // Then the global objects list. variables = &GetProject().GetObject(objectName).GetVariables(); } } // Optimize the lookup of the variable when the variable is declared. //(In this case, it is stored in an array at runtime and we know its // position.) if (variables && variables->Has(variableName)) { std::size_t index = variables->GetPosition(variableName); if (index < variables->Count()) { output += ".getFromIndex(" + gd::String::From(index) + ")"; return output; } } output += ".get(" + ConvertToStringExplicit(variableName) + ")"; return output; } gd::String EventsCodeGenerator::GenerateUpperScopeBooleanFullName( const gd::String& boolName, const gd::EventsCodeGenerationContext& context) { if (context.GetCurrentConditionDepth() <= 0) return "/* Code generation error: the referenced boolean can't exist as " "the context has a condition depth of 0. */"; return boolName + "_" + gd::String::From(context.GetCurrentConditionDepth() - 1); } gd::String EventsCodeGenerator::GenerateBooleanInitializationToFalse( const gd::String& boolName, const gd::EventsCodeGenerationContext& context) { return "let " + GenerateBooleanFullName(boolName, context) + " = false;\n"; } gd::String EventsCodeGenerator::GenerateBooleanFullName( const gd::String& boolName, const gd::EventsCodeGenerationContext& context) { return boolName + "_" + gd::String::From(context.GetCurrentConditionDepth()); } gd::String EventsCodeGenerator::GenerateProfilerSectionBegin( const gd::String& section) { if (GenerateCodeForRuntime()) return ""; return "if (runtimeScene.getProfiler()) { runtimeScene.getProfiler().begin(" + ConvertToStringExplicit(section) + "); }"; } gd::String EventsCodeGenerator::GenerateProfilerSectionEnd( const gd::String& section) { if (GenerateCodeForRuntime()) return ""; return "if (runtimeScene.getProfiler()) { runtimeScene.getProfiler().end(" + ConvertToStringExplicit(section) + "); }"; } EventsCodeGenerator::EventsCodeGenerator(const gd::Project& project, const gd::Layout& layout) : gd::EventsCodeGenerator(project, layout, JsPlatform::Get()) {} EventsCodeGenerator::EventsCodeGenerator( gd::ObjectsContainer& globalObjectsAndGroups, const gd::ObjectsContainer& objectsAndGroups) : gd::EventsCodeGenerator( JsPlatform::Get(), globalObjectsAndGroups, objectsAndGroups) {} EventsCodeGenerator::~EventsCodeGenerator() {} } // namespace gdjs
45a052caad59b43f13c7c3619fdc4911c125dd85
f56e4b0bbbc578af0e6b89a4f29484000c96dec1
/Lavio/Lavio/Source/IO/Utilities/FileUtility.h
fb810f23cb1bb5569b092a6b4dc6aea2d720ad1d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
landon912/Lavio
8f57ae5dbe854d8485c97ff51425bf6fd156d3ab
c726f43ed98f630d68ea6bc234f367b67578c918
refs/heads/master
2020-04-13T02:48:29.917812
2019-08-27T18:26:11
2019-08-27T18:26:11
162,912,765
1
0
null
null
null
null
UTF-8
C++
false
false
548
h
FileUtility.h
// **************************************** Lavio Engine **************************************** // **************************** Copyright (c) 2017 All Rights Reserved ************************** // ***************************** Landon Kirk (landonaddison@yahoo.com) ************************** #pragma once #include <fstream> namespace Lavio { namespace IO { struct FileUtility { static std::string ReadFile(const char *filepath); private: FileUtility() {} ~FileUtility() {} FileUtility(const FileUtility& other); }; } }
cd070838395cb3f1674a68521871c44143e6e4b8
7522723724c15e558461323d0ee3dc20a72e4771
/systems/framework/input_port_base.cc
cc9520d01a0d0c904ecc76e79c2bd988d4072059
[ "BSD-3-Clause" ]
permissive
plancherb1/drake
7b981ef17f613249be0cc1efe585b5dcae6a4969
397cd5cc202de54128f8f9806c81805caefc556c
refs/heads/master
2020-04-15T18:42:10.561203
2019-07-03T21:35:38
2019-07-03T21:35:38
164,921,421
1
0
NOASSERTION
2019-01-09T19:05:27
2019-01-09T19:04:56
C++
UTF-8
C++
false
false
1,024
cc
input_port_base.cc
#include "drake/systems/framework/input_port_base.h" #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace systems { InputPortBase::InputPortBase(SystemBase* owning_system, std::string name, InputPortIndex index, DependencyTicket ticket, PortDataType data_type, int size, const optional<RandomDistribution>& random_type) : owning_system_(*owning_system), index_(index), ticket_(ticket), data_type_(data_type), size_(size), name_(std::move(name)), random_type_(random_type) { DRAKE_DEMAND(owning_system != nullptr); DRAKE_DEMAND(!name_.empty()); if (size_ == kAutoSize) { DRAKE_ABORT_MSG("Auto-size ports are not yet implemented."); } if (is_random() && data_type_ != kVectorValued) { DRAKE_ABORT_MSG("Random input ports must be vector valued."); } } InputPortBase::~InputPortBase() = default; } // namespace systems } // namespace drake
5a593dc9d598c44bf2034ad8e17820f32856ad0f
11fd93b0ca97d25d21f5fe58f33a7cb07a7df9f4
/src/ToggleWindow.h
27570e9283ce866427020f747e5b61d2e9a48a50
[ "BSD-3-Clause" ]
permissive
membranesoftware/membrane-control
d539526139d972a3dd84ea0f757717367bb73c4f
e22498170b1a4e5793db9e7d0686969ca95fe3da
refs/heads/master
2022-08-15T08:29:38.368208
2022-07-18T17:39:49
2022-07-18T17:39:49
147,160,088
0
0
null
null
null
null
UTF-8
C++
false
false
3,553
h
ToggleWindow.h
/* * Copyright 2018-2022 Membrane Software <author@membranesoftware.com> https://membranesoftware.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Panel that holds a Toggle widget and a label or image #ifndef TOGGLE_WINDOW_H #define TOGGLE_WINDOW_H #include "StdString.h" #include "Toggle.h" #include "Label.h" #include "Image.h" #include "Sprite.h" #include "Panel.h" class ToggleWindow : public Panel { public: ToggleWindow (Toggle *toggle); virtual ~ToggleWindow (); // Read-write data members Widget::EventCallbackContext stateChangeCallback; // Read-only data members bool isChecked; bool isRightAligned; bool isInverseColor; // Set the toggle to show a text label void setText (const StdString &text); // Set the toggle to show an icon image void setIcon (Sprite *iconSprite); // Set the window's right-aligned option. If enabled, the window places the toggle on the right side instead of the left side. void setRightAligned (bool enable); // Set the window's inverse color state. If enabled, the window uses an inverse color scheme. void setInverseColor (bool inverse); // Set the draw color for the toggle's button images void setImageColor (const Color &imageColor); // Set the toggle's checked state and invoke any configured change callback unless shouldSkipChangeCallback is true void setChecked (bool checked, bool shouldSkipChangeCallback = false); protected: // Return a string that should be included as part of the toString method's output StdString toStringDetail (); // Reset the panel's widget layout as appropriate for its content and configuration void refreshLayout (); private: // Callback functions static void mouseEntered (void *windowPtr, Widget *widgetPtr); static void mouseExited (void *windowPtr, Widget *widgetPtr); static void mousePressed (void *windowPtr, Widget *widgetPtr); static void mouseReleased (void *windowPtr, Widget *widgetPtr); static void mouseClicked (void *windowPtr, Widget *widgetPtr); static void toggleStateChanged (void *windowPtr, Widget *widgetPtr); Toggle *toggle; Label *label; Image *iconImage; }; #endif
73c4284cd407559fb46aec239ee492825ad9bca3
a5f3b0001cdb692aeffc444a16f79a0c4422b9d0
/main/sc/inc/reftokenhelper.hxx
88a650920c91b9cb0d5480f6e9cb117302290a84
[ "Apache-2.0", "CPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive", "Zlib", "LZMA-exception", "LGPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-philippe-de-muyter", "OFL-1.1", "LGPL-2.1-only", "MPL-1.1", "X11", "LGPL-2.1-or-later", "GPL-2.0-only", "OpenSSL", "LicenseRef-scancode-cpl-0.5", "GPL-1.0-or-later", "NPL-1.1", "MIT", "MPL-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "MPL-1.0", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "LicenseRef-scancode-docbook", "LicenseRef-scancode-mit-old-style", "Python-2.0", "BSD-3-Clause", "IJG", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later", "LGPL-2.0-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "BSD-2-Clause", "Autoconf-exception-generic", "PSF-2.0", "NTP", "LicenseRef-scancode-python-cwi", "Afmparse", "W3C", "W3C-19980720", "curl", "LicenseRef-scancode-x11-xconsortium-veillard", "Bitstream-Vera", "HPND-sell-variant", "ICU" ]
permissive
apache/openoffice
b9518e36d784898c6c2ea3ebd44458a5e47825bb
681286523c50f34f13f05f7b87ce0c70e28295de
refs/heads/trunk
2023-08-30T15:25:48.357535
2023-08-28T19:50:26
2023-08-28T19:50:26
14,357,669
907
379
Apache-2.0
2023-08-16T20:49:37
2013-11-13T08:00:13
C++
UTF-8
C++
false
false
2,675
hxx
reftokenhelper.hxx
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_REFTOKENHELPER_HXX #define SC_REFTOKENHELPER_HXX #include "token.hxx" #include <vector> namespace rtl { class OUString; } class ScDocument; class ScRange; class ScRangeList; class ScRefTokenHelper { private: ScRefTokenHelper(); ScRefTokenHelper(const ScRefTokenHelper&); ~ScRefTokenHelper(); public: /** * Compile an array of reference tokens from a data source range string. * The source range may consist of multiple ranges separated by ';'s. */ static void compileRangeRepresentation( ::std::vector<ScSharedTokenRef>& rRefTokens, const ::rtl::OUString& rRangeStr, ScDocument* pDoc, ::formula::FormulaGrammar::Grammar eGrammar = ::formula::FormulaGrammar::GRAM_ENGLISH); static bool getRangeFromToken(ScRange& rRange, const ScSharedTokenRef& pToken, bool bExternal = false); static void getRangeListFromTokens(ScRangeList& rRangeList, const ::std::vector<ScSharedTokenRef>& pTokens); /** * Create a double reference token from a range object. */ static void getTokenFromRange(ScSharedTokenRef& pToken, const ScRange& rRange); static void getTokensFromRangeList(::std::vector<ScSharedTokenRef>& pTokens, const ScRangeList& rRanges); static bool SC_DLLPUBLIC isRef(const ScSharedTokenRef& pToken); static bool SC_DLLPUBLIC isExternalRef(const ScSharedTokenRef& pToken); static bool SC_DLLPUBLIC intersects(const ::std::vector<ScSharedTokenRef>& rTokens, const ScSharedTokenRef& pToken); static void SC_DLLPUBLIC join(::std::vector<ScSharedTokenRef>& rTokens, const ScSharedTokenRef& pToken); static bool getDoubleRefDataFromToken(ScComplexRefData& rData, const ScSharedTokenRef& pToken); }; #endif
21ff84062b9b5f80b18c172627937ddaaf3d703d
8337d33d0506f19aedfce9d51ad08631f38ed918
/DL2/TOOL-INC/CACHE.INC
3fe046bd54d0e8f11a39fea89d259ca7d6c72329
[]
no_license
shsmith/TSBBS
aae2958be00181601e361f8b85cb2eb48e2c290b
5c7797bf9e6fc63e8dc0f0b657179b1cee564eb6
refs/heads/master
2022-10-29T10:10:40.341691
2020-06-06T14:24:50
2020-06-06T14:24:50
269,168,480
3
0
null
null
null
null
UTF-8
C++
false
false
3,373
inc
CACHE.INC
TYPE byte = 0..255; system_status_type = PACKED RECORD enabled: BOOLEAN; buffered_write_enabled: BOOLEAN; buffered_read_enabled: BOOLEAN; sounds_enabled: BOOLEAN; autodismount_enabled: BOOLEAN; reserved_3: BOOLEAN; reserved_4: BOOLEAN; reserved_5: BOOLEAN; em_assigned: BOOLEAN; emulated_emm: BOOLEAN; single_sector_bonus: byte; sticky_max: byte; write_sector_bonus: byte; bonus_threshold: byte; flush_interval: CARDINAL; flush_count: INTEGER; reserve_pool_size: INTEGER; reserve_pool_remaining: INTEGER; rqd_free_memory: CARDINAL; total_sectors, dirty_sectors: INTEGER; track_buffer_size: byte; filler2: byte; END; drive_status_type = PACKED RECORD dos_drive: byte; bios_drive: byte; max_sector: byte; max_head: byte; read_buffer_size: byte; write_buffer_size: byte; last_status: byte; enabled: BOOLEAN; buffered_write_enabled: BOOLEAN; buffered_read_enabled: BOOLEAN; in_use: BOOLEAN; cylinder_flush: BOOLEAN; filler0: BOOLEAN; sectors_per_track: byte; sector_size: INTEGER; sectors_assigned: CARDINAL; dirty_sectors: CARDINAL; reserved_sectors: CARDINAL; read_error_count: CARDINAL; write_error_count: CARDINAL; rio_count: LONGINT; miss_count: LONGINT; wio_count: LONGINT; dio_count: LONGINT; END; all_drive_status_type = ARRAY[0..15] OF drive_status_type; {==============================================================================} { Drive translation table } { } { This table is used to generate an index into each of the drive status } { tables. Drive A is element zero of the drive_index array, drive B is } { element 1, etc. If the index extracted is not 255, then the drive is valid } { and it may be used to index into the status tables. } { } {==============================================================================} drive_index_type = PACKED ARRAY[0..31] OF 0..255; cache_status_type = RECORD CASE INTEGER OF 0: ( system: system_status_type ); 1: ( drive: all_drive_status_type; ); 2: ( access_frequency: ARRAY[1..30] OF CARDINAL ); 3: ( drive_index: drive_index_type; ); END; 
cfe56e45c07b936f3068ac2827ef7a83f8c774a1
c06fb959f82475c6a64f1dbc270217c44dc73834
/src/ecs/components/Transform.cpp
527790b00e52b4afa9f82735f70b808aab064416
[ "MIT" ]
permissive
cstegel/opengl-fireworks
c2adb9322f453e7c6d357468742e5354c9d7209f
5acc2e2e937cae632bf2cf8074d209ea22d719c8
refs/heads/master
2021-03-19T16:37:27.146042
2016-12-10T06:37:10
2016-12-10T06:37:10
76,093,572
1
0
null
null
null
null
UTF-8
C++
false
false
2,151
cpp
Transform.cpp
#include "ecs/components/Transform.hpp" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> #include <Ecs.hh> namespace fw { Transform::Transform(glm::vec3 position) { Translate(position); } Transform::Transform(float x, float y, float z) { Translate(x, y, z); } glm::mat4 Transform::GetModelTransform() { glm::mat4 model; if (relativeTo != ecs::Entity()) { if (!relativeTo.Has<Transform>()) { throw std::runtime_error("cannot be relative to something that does not have a transform"); } model = relativeTo.Get<Transform>()->GetModelTransform(); } return model * this->translate * GetRotateMatrix() * this->scale; } glm::vec3 Transform::GetForward(const glm::vec3 & worldForward) { glm::mat4 normalMatWorldToModel((GetModelTransform())); return glm::normalize(glm::vec3(normalMatWorldToModel * glm::vec4(worldForward, 0))); } glm::vec3 Transform::GetPosition() { return glm::vec3(GetModelTransform() * glm::vec4(0, 0, 0, 1)); } void Transform::SetRelativeTo(ecs::Entity ent) { if (!ent.Has<Transform>()) { std::stringstream ss; ss << "Cannot set placement relative to " << ent << " because it does not have a placement."; throw std::runtime_error(ss.str()); } this->relativeTo = ent; } void Transform::Rotate(float radians, glm::vec3 axis) { this->rotate = glm::rotate(this->rotate, radians, axis); } void Transform::Translate(glm::vec3 xyz) { this->translate = glm::translate(this->translate, xyz); } void Transform::Translate(float x, float y, float z) { Translate(glm::vec3(x, y, z)); } void Transform::Scale(glm::vec3 xyz) { this->scale = glm::scale(this->scale, xyz); } void Transform::Scale(float x, float y, float z) { Scale(glm::vec3(x, y, z)); } void Transform::Scale(float amount) { Scale(glm::vec3(amount, amount, amount)); } glm::mat4 Transform::GetRotateMatrix() { return glm::mat4_cast(rotate); } void Transform::LookAt(glm::vec3 center, glm::vec3 worldUp) { rotate = glm::quat_cast( glm::inverse(glm::lookAt( glm::vec3(translate*glm::vec4(0, 0, 0, 1)), center, worldUp )) ); } }
8c4deb6cbb21ef6cdc6ad99e37d95fe84591d89a
3d0e8a4a9bf29d2619224c964cd32f7361807d42
/include/grammar/unusing/GrammarBuilder.h
167d8f86d88fe67caeb73974f08dd143cadb5a9e
[]
no_license
ageev-aleksey/HGrammStateMachine
760b2163deda7fc74f856a32761eab4c0ec532e2
09befa8b3c380f46676af2266a0b8f8541621231
refs/heads/master
2022-04-14T13:34:35.767827
2020-04-08T12:43:39
2020-04-08T12:43:39
244,901,890
0
0
null
null
null
null
UTF-8
C++
false
false
470
h
GrammarBuilder.h
#include "grammar/Grammar.h" #include "grammar/SetSymbols.h" #include "grammar/Symbol.h" #include "grammar/Productions.h" #include <map> class GrammarBuilder { public: GrammBuilder& setTerminalSet(SetSymbols terminalSet); GrammBuilder& setNonTerminalSet(SetSymbols nonTerminalSet); GrammBuilder& setAxiom(Symbol axiom); GrammBuilder& createInplaceProduction(SymbolsChain alpha, SymbolsChain betta); Grammar build(); private: GrammarBuilder(); };
64b37abd502b14b146852e4ce42108e7b655c14f
cbd0a3af7c57e901896a5132928287ed78527c5b
/modules/kernel/src/butler/ButlerMemCheck.cc
e45e31ca8c293f2b8185ce706cca572184739b93
[ "LicenseRef-scancode-unknown-license-reference", "Beerware", "BSD-2-Clause" ]
permissive
eryjus/century-os
ad81a8a29e8b6c8cf0d65242dcb030a5346b5dc9
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
refs/heads/master
2021-06-03T11:45:02.476664
2020-04-17T22:50:05
2020-04-17T22:50:05
134,635,625
13
2
NOASSERTION
2020-06-06T16:15:41
2018-05-23T23:21:18
C++
UTF-8
C++
false
false
1,361
cc
ButlerMemCheck.cc
//=================================================================================================================== // // ButlerMemCheck.cc -- Check the memory frame to see if it can be freed // // Copyright (c) 2017-2020 -- Adam Clark // Licensed under "THE BEER-WARE LICENSE" // See License.md for details. // // Up to 4MB, check the memory to see if it can be freed. // // ------------------------------------------------------------------------------------------------------------------ // // Date Tracker Version Pgmr Description // ----------- ------- ------- ---- --------------------------------------------------------------------------- // 2020-Apr-11 Initial v0.6.1b ADCL Initial version // //=================================================================================================================== #include "types.h" #include "pmm.h" #include "butler.h" // // -- Check the memory to see if it is eligible to be freed // ----------------------------------------------------- EXTERN_C EXPORT LOADER bool ButlerMemCheck(frame_t frame) { archsize_t addr = frame << 12; archsize_t krnBeg = 0x100000; archsize_t krnEnd = krnStabPhys + krnStabSize; if (frame < 0x100) return LowMemCheck(frame); if (addr >= krnBeg && addr < krnEnd) return false; return true; }
12d1542877eb3bc7f495bfb1a66fe89bb4e89769
ea5abb606afbae6e5774072ffd9b69e6418d0389
/tests/ProtoclVersionTest.cpp
82bebd8337057733adcefe7d7c3da97ad20e7629
[ "MIT" ]
permissive
stormlord/tarm-io
a4487316a4034b654f89fb081e880bb4f3e4a928
6aebd85573f65017decf81be073c8b13ce6ac12c
refs/heads/master
2023-07-01T11:24:38.077682
2021-08-08T08:02:37
2021-08-08T08:02:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
cpp
ProtoclVersionTest.cpp
/*---------------------------------------------------------------------------------------------- * Copyright (c) 2020 - present Alexander Voitenko * Licensed under the MIT License. See License.txt in the project root for license information. *----------------------------------------------------------------------------------------------*/ #include "UTCommon.h" #include "net/ProtocolVersion.h" #include <openssl/ssl.h> #include <vector> struct ProtocolVersionTest : public testing::Test, public LogRedirector { }; TEST_F(ProtocolVersionTest, tls) { #if OPENSSL_VERSION_NUMBER < 0x1000100fL // 1.0.1 ASSERT_EQ(io::net::TlsVersion::V1_0, io::net::min_supported_tls_version()); ASSERT_EQ(io::net::TlsVersion::V1_0, io::net::max_supported_tls_version()); #elif OPENSSL_VERSION_NUMBER < 0x1010100fL // 1.1.1 ASSERT_EQ(io::net::TlsVersion::V1_0, io::net::min_supported_tls_version()); ASSERT_EQ(io::net::TlsVersion::V1_2, io::net::max_supported_tls_version()); #else ASSERT_EQ(io::net::TlsVersion::V1_0, io::net::min_supported_tls_version()); ASSERT_EQ(io::net::TlsVersion::V1_3, io::net::max_supported_tls_version()); #endif } TEST_F(ProtocolVersionTest, dtls) { #if OPENSSL_VERSION_NUMBER < 0x1000200fL // 1.0.2 ASSERT_EQ(io::net::DtlsVersion::V1_0, io::net::min_supported_dtls_version()); ASSERT_EQ(io::net::DtlsVersion::V1_0, io::net::max_supported_dtls_version()); #else ASSERT_EQ(io::net::DtlsVersion::V1_0, io::net::min_supported_dtls_version()); ASSERT_EQ(io::net::DtlsVersion::V1_2, io::net::max_supported_dtls_version()); #endif }
8b339b33d61625c550dc07800d0a620447c3ffc1
1449d0e1ff6342d46417f48f3d288e42b6c3a236
/src/mypackage/MyDisplayVertices2.h
435977503c711e16973e79ee3e0c7cac008d8ed8
[]
no_license
fjug/ZIBAmiraLocal
493c49d4c8360dcdae9271d892f5f280554cd894
c40519411f0b5f4052ea34d2d9e084dffcd0dd5c
refs/heads/master
2016-09-02T05:43:30.664770
2014-02-07T17:51:00
2014-02-07T17:51:00
16,622,545
1
1
null
null
null
null
UTF-8
C++
false
false
1,211
h
MyDisplayVertices2.h
/////////////////////////////////////////////////////////////////////// // // Example of a display module (version 2) // /////////////////////////////////////////////////////////////////////// #ifndef MY_DISPLAY_VERTICES2_H #define MY_DISPLAY_VERTICES2_H #include <mclib/McHandle.h> // smart pointer template class #include <hxcore/HxModule.h> // include declaration of base class #include <hxcore/HxPortIntSlider.h> // provides integer slider #include <hxcolor/HxPortColormap.h> // connection to a colormap #include <mypackage/api.h> // storage-class specification #include <Inventor/nodes/SoSeparator.h> class MYPACKAGE_API MyDisplayVertices2 : public HxModule { HX_HEADER(MyDisplayVertices2); public: // Constructor. MyDisplayVertices2(); // Destructor. ~MyDisplayVertices2(); // Connection to a colormap. HxPortColormap portColormap; // Input parameter. HxPortIntSlider portNumTriangles; // This is called when an input port changes. virtual void compute(); // Tcl command interface. virtual int parse(Tcl_Interp* t, int argc, char **argv); protected: float scale; McHandle<SoSeparator> scene; }; #endif
49c1424160b0ceb2f5d8b892e3e819119208d98d
1dbed0f84a670c787d2217d97ae3984401c7edb3
/atcoder/arc085_c.cpp
630c2abcfdda0acd74f4fc558595b5d3fb82f7d0
[]
no_license
prprprpony/oj
311d12a25f06e6c54b88bc2bcd38003f7b6696a9
84988be500c06cb62130585333fddd1a278f0aaa
refs/heads/master
2021-07-13T16:03:54.398841
2021-03-27T14:19:52
2021-03-27T14:19:52
46,796,050
9
0
null
null
null
null
UTF-8
C++
false
false
1,996
cpp
arc085_c.cpp
#include<bits/stdc++.h> using namespace std; const int N = 206; typedef long long ll; const ll C = 1e12, inf = 1e18; struct { struct edge { int v; ll r,f; }; vector<edge> e; vector<int> g[N]; int n,s,t, d[N], pr[N]; bitset<N> inq; void init(int _n,int _s,int _t) { n=_n,s=_s,t=_t; } void addE(int u,int v,ll c) { g[u].push_back(e.size()); e.push_back(edge{v,c,0}); g[v].push_back(e.size()); e.push_back(edge{u,0,0}); } ll aug() { fill_n(pr,n,-1); fill_n(d,n,N); d[s] = 0; queue<int> q; inq.reset(); q.push(s); while (q.size()) { int u = q.front(); q.pop(); inq[u] = false; for (int i : g[u]) { if (e[i].r) { int w = d[u] + 1; if (w < d[e[i].v]) { d[e[i].v] = w; pr[e[i].v] = i; if (!inq[e[i].v]) { q.push(e[i].v); inq[e[i].v] = true; } } } } } ll f=inf; for (int u = t; pr[u] != -1; u = e[pr[u]^1].v) f = min(f, e[pr[u]].r); for (int u = t; pr[u] != -1; u = e[pr[u]^1].v) { e[pr[u]].r -= f; e[pr[u]].f += f; e[pr[u]^1].r += f; e[pr[u]^1].f -= f; } return f; } } f; int n,a[N]; int main() { cin >> n; f.init(n+2,0,n+1); ll ans = 0; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (a[i] > 0) { ans += a[i]; f.addE(i,f.t,a[i]); } else { f.addE(f.s,i,-a[i]); } for (int j = i * 2; j <= n; j += i) f.addE(i,j,inf); } ll w; while ((w = f.aug()) != inf) ans -= w; cout << ans << '\n'; }
0e264c9345aa5c5186df91572fa76a27b85d9a7c
1dacbf90eeb384455ab84a8cf63d16e2c9680a90
/pkgs/libdynd-0.7.2-0/include/dynd/memblock/fixed_size_pod_memory_block.hpp
012c0c00aee05ecc121e20b1657000748a03c650
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
wangyum/Anaconda
ac7229b21815dd92b0bd1c8b7ec4e85c013b8994
2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6
refs/heads/master
2022-10-21T15:14:23.464126
2022-10-05T12:10:31
2022-10-05T12:10:31
76,526,728
11
10
Apache-2.0
2022-10-05T12:10:32
2016-12-15T05:26:12
Python
UTF-8
C++
false
false
954
hpp
fixed_size_pod_memory_block.hpp
// // Copyright (C) 2011-15 DyND Developers // BSD 2-Clause License, see LICENSE.txt // #pragma once #include <iostream> #include <string> #include <dynd/memblock/memory_block.hpp> namespace dynd { struct fixed_size_pod_memory_block : memory_block_data { fixed_size_pod_memory_block(long use_count) : memory_block_data(use_count, fixed_size_pod_memory_block_type) {} }; /** * Creates a memory block of a pre-determined fixed size. A pointer to the * memory allocated for data is placed in the output parameter. */ DYNDT_API intrusive_ptr<memory_block_data> make_fixed_size_pod_memory_block(intptr_t size_bytes, intptr_t alignment, char **out_datapointer); DYNDT_API void fixed_size_pod_memory_block_debug_print(const memory_block_data *memblock, std::ostream &o, const std::string &indent); } // namespace dynd
6a62d6970b2119b417cf14c36b3f6af4345fbf00
961c75e9ee1b3a99ae0e23efaa65ff1e5891a971
/include/items/weapon.hpp
15fbe13a03168d8777279f3971ceabd025c2a565
[]
no_license
TheyDidItForLulz/RLRPG
294405b9e192a5826c8c44e999cfd03b048a3168
91c82c217c00eb65f0f0c2f327440cb77cb9d1a4
refs/heads/master
2021-01-25T05:56:59.804974
2020-03-09T12:17:54
2020-03-11T06:06:24
80,707,821
5
3
null
2020-08-15T22:26:13
2017-02-02T08:47:23
C++
UTF-8
C++
false
false
1,498
hpp
weapon.hpp
#ifndef RLRPG_ITEMS_WEAPON_HPP #define RLRPG_ITEMS_WEAPON_HPP #include<items/item.hpp> #include<ptr.hpp> #include<enable_clone.hpp> #include<vector> class Ammo; class Weapon : public Item , public EnableClone<Weapon> { public: class Cartridge { std::vector<Ptr<Ammo>> loaded; int capacity = 0; public: explicit Cartridge(int capacity = 0); Cartridge(Cartridge const &); Cartridge & operator =(Cartridge const &); // returns the bullet if fails to load it Ptr<Ammo> load(Ptr<Ammo> bullet); Ptr<Ammo> unloadOne(); Ammo const & next() const; Ammo & next(); Ammo const * operator [](int ind) const; auto begin() const -> decltype(loaded.begin()); auto end() const -> decltype(loaded.end()); int getCapacity() const; int getCurrSize() const; bool isEmpty() const; bool isFull() const; }; static int const COUNT = 25; /* JUST FOR !DEBUG!!*/ Cartridge cartridge; int damage; int range; // Ranged bullets have additional effect on this paramether int damageBonus; // And on this too bool isRanged = false; bool canDig = false; Type getType() const override { return Type::Weapon; } Ptr<Item> cloneItem() const override { return std::make_unique<Weapon>(*this); } }; #endif // RLRPG_ITEMS_WEAPON_HPP
3c3149e8b3eea5072ec364748daa0cdec2661b2d
ff9777b39a21e763a0cf8f52bb7682a90f3ab919
/finalproj/Final-Project/gameboard.h
90735d6bab3d766e8b1a696df1e403b7ed36de6a
[]
no_license
ahchoi1005/Final-Project
1a7c1e8bde1777f0352da9af0271dc26817ef9ab
fa459f1cf472ca3fc5ffbdac2a3396dfaba7ce82
refs/heads/master
2020-05-01T18:04:56.986820
2019-04-27T16:14:25
2019-04-27T16:14:25
177,616,354
0
0
null
null
null
null
UTF-8
C++
false
false
346
h
gameboard.h
#include <iostream> using namespace std; class gameBoard{ public: gameBoard(); void clear(); bool empty(int, int); void print(); bool rowfive(int, int); bool colfive(int, int); bool diag1five(int, int); bool diag2five(int, int); void piece(int, int, char); private: char board[19][19]; char player1; char player2; };
d4957a7d79aba746b7427e2a3dd2d5479ba35c7e
937b96e51beca873ab52077da98bd049ebde20ef
/monoCode/Inventory.cpp
b49f5179cfeebabf627d9fb65785ddec369b0f0a
[]
no_license
hemantsharma98/CEG-4120-
42492b1e856389fd5d0448c092d8f0c574c34046
175eb58d70b5a4b9aa24092bfc13629a43358aed
refs/heads/main
2023-04-15T18:14:15.576315
2021-04-21T17:15:41
2021-04-21T17:15:41
340,968,684
0
0
null
null
null
null
UTF-8
C++
false
false
738
cpp
Inventory.cpp
#include "Inventory.h" #include <iostream> #include "Property.h" using namespace std; int Inventory::getMoney() { return money; } void Inventory::addMoney(int m) { money += m; } void Inventory::subMoney(int m) { money -= m; } int Inventory::getpID() { return pID; } void Inventory::setpID(int p) { pID = p; } int Inventory::getLoc() { return loc; } void Inventory::setLoc(int l) { loc = l; } int Inventory::getNumPropOwned() { return numPropOwned; } void Inventory::setNumPropOwned(int n) { numPropOwned = n; } void Inventory::numPropPlusOne() { numPropOwned += 1; } void Inventory::numPropMinusOne() { numPropOwned -= 1; }
23050b859946e312d928b658491b837831bad421
bf6efd89cb0d86f059dcc995feb3e189b20a046a
/listacorreos.cpp
8348169f9ccaec05c87e6c629afe613fd0000dec
[]
no_license
Nhala86/Practica5
95192182431c5274214a1f4b90171fe3d94967e1
f25fc4b496d278331ed270b343dc38cf47e146b4
refs/heads/master
2020-12-25T15:09:10.908973
2015-09-14T10:55:55
2015-09-14T10:55:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,023
cpp
listacorreos.cpp
#include<iostream> #include<fstream> #include<string> #include<math.h> using namespace std; #include"ListaCorreos.h" void inicializar(tListaCorreos & correos, int capacidad){ correos.correo = new tCorreo [capacidad]; correos.contador = 0; correos.capacidad = capacidad; } bool cargar(tListaCorreos & correos, string dominio){ bool esCargar; ifstream archivo; float elementos, redondeo; string ficheroCorreo = dominio + "_" + mailCorreo; archivo.open(ficheroCorreo); if (archivo.is_open()){ tCorreo correo; archivo >> elementos; redondeo = (ceil(elementos / 10)) * 10; inicializar(correos, (int) redondeo); for(int i = 0; i < elementos; i++){ cargar (correo, archivo); insertar(correos, correo); } archivo.close(); esCargar = true; } else{ inicializar(correos, MAIL_INICIAL); esCargar = false; } return esCargar; } void guardar (const tListaCorreos & correos, string dominio){ ofstream archivo; string ficheroCorreo = dominio + "_" + mailCorreo; archivo.open(ficheroCorreo); if (archivo.is_open()){ archivo << correos.contador << endl; for(int i = 0; i < correos.contador; i++){ guardar(correos.correo[i], archivo); } archivo.close(); } else{ cout << "No sé puedo guardar el archivo" << endl; } } void insertar(tListaCorreos & correos, const tCorreo & correo){ int posicion; if (correos.contador == correos.capacidad){ redimensionar (correos); } buscar(correos, correo.identificador, posicion); for(int i = correos.contador; i > posicion; i--) correos.correo[i] = correos.correo[i - 1]; correos.correo[posicion] = correo; correos.contador++; } bool buscar (const tListaCorreos & correos, string id, int & pos){ bool encontrado = false; pos = 0; while (pos < correos.contador && !encontrado){ if(id == correos.correo[pos].identificador){ encontrado = true; } else{ pos++; } } return encontrado; } bool borrar(tListaCorreos &correos, string id){ bool borrado = false; int posicion; if(buscar(correos, id , posicion)){ system("pause"); for (posicion; posicion < correos.contador; posicion++){ correos.correo[posicion] = correos.correo[posicion + 1]; } correos.contador--; borrado = true; } return borrado; } void ordenar_AF(tListaCorreos & correos){ int i = 0; bool esOrdenar = true; while ((i < correos.contador) && esOrdenar){ esOrdenar = false; for (int j = correos.contador - 1; j > i; j--){ if (correos.correo[j] < correos.correo[j - 1]){ tCorreo tmp; tmp = correos.correo[j]; correos.correo[j] = correos.correo[j - 1]; correos.correo[j - 1] = tmp; esOrdenar = true; } } if (esOrdenar) i++; } } void destruir (tListaCorreos & correos){ delete[] correos.correo; } void redimensionar (tListaCorreos & correos){ tListaCorreos listaNueva; int i = 0; int capacidadNueva = (correos.capacidad * 3) / 2 + 1; inicializar (listaNueva, capacidadNueva); while (i < correos.contador){ insertar(listaNueva, correos.correo[i++]); } correos = listaNueva; }
90183294800f2cc3bad37ac0ca5a891e6d77ce33
329296673f4b54d286fb260b29ca599e0fbce241
/MFCShellTreeCtrlEx.cpp
304ae8792298d3dfe8ca2a131cbada095a81f0ce
[]
no_license
okrymus/WindowMania
6bf4d03a4becdf001351bec9093c5eb2ea5c32d0
9d0b22a1f3fb2832d28252387f2ba4775f66e3b8
refs/heads/master
2020-04-22T03:17:01.048072
2019-02-17T01:32:37
2019-02-17T01:32:37
170,081,298
0
0
null
null
null
null
UTF-8
C++
false
false
13,015
cpp
MFCShellTreeCtrlEx.cpp
// MFCShellTreeCtrlEx.cpp : implementation file // #include "StdAfx.h" #include "MFCShellUtils.h" #include "MFCShellTreeCtrlEx.h" #include "io.h" // CMFCShellTreeCtrlEx IMPLEMENT_DYNAMIC(CMFCShellTreeCtrlEx, CMFCShellTreeCtrl) CMFCShellTreeCtrlEx::CMFCShellTreeCtrlEx(DWORD dwProp) : m_dwProp(dwProp), m_bFullRootPath(FALSE) { } CMFCShellTreeCtrlEx::~CMFCShellTreeCtrlEx() { } BEGIN_MESSAGE_MAP(CMFCShellTreeCtrlEx, CMFCShellTreeCtrl) ON_WM_CREATE() ON_NOTIFY_REFLECT(TVN_DELETEITEM, &CMFCShellTreeCtrlEx::OnDeleteitem) ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, &CMFCShellTreeCtrlEx::OnItemexpanding) END_MESSAGE_MAP() // CMFCShellTreeCtrlEx message handlers void CMFCShellTreeCtrlEx::RefreshEx() { ASSERT_VALID(this); DeleteAllItems(); GetRootItemsEx(); TreeView_SetScrollTime(GetSafeHwnd(), 100); } void CMFCShellTreeCtrlEx::InitTreeEx() { TCHAR szWinDir[MAX_PATH + 1]; if (GetWindowsDirectory(szWinDir, MAX_PATH) > 0) { SHFILEINFO sfi; SetImageList(CImageList::FromHandle((HIMAGELIST)SHGetFileInfo(szWinDir, 0, &sfi, sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_SMALLICON)), 0); } RefreshEx(); } int CMFCShellTreeCtrlEx::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CTreeCtrl::OnCreate(lpCreateStruct) == -1) return -1; if (afxShellManager == NULL) { TRACE0("You need to initialize CShellManager first\n"); return -1; } InitTreeEx(); return 0; } void CMFCShellTreeCtrlEx::PreSubclassWindow() { CTreeCtrl::PreSubclassWindow(); _AFX_THREAD_STATE* pThreadState = AfxGetThreadState(); if (pThreadState->m_pWndInit == NULL) InitTreeEx(); } void CMFCShellTreeCtrlEx::SetFlagsEx(DWORD dwFlags, BOOL bRefresh) { ASSERT_VALID(this); m_dwFlags = dwFlags; if (bRefresh && GetSafeHwnd() != NULL) RefreshEx(); } void CMFCShellTreeCtrlEx::SetRootFolder(LPCTSTR szRootDir, BOOL bFullPath, DWORD *pdwProp) { m_bFullRootPath = bFullPath; if (szRootDir) { // Check if szRootDir is not an empty string and points to a valid folder patname if (lstrlen(szRootDir) != 0 && _taccess(szRootDir, 0) != 0) return; // If root folder didn't change => exit if (!m_cRootDir.CompareNoCase(szRootDir)) return; } // If root folder didn't change => exit else if (m_cRootDir.IsEmpty()) return; if (pdwProp) m_dwProp = *pdwProp; m_cRootDir = szRootDir ? szRootDir : _T(""); if (m_hWnd) { // Re-populate tree items RefreshEx(); HTREEITEM hRootItem = GetRootItem(); if (hRootItem) SelectItem(hRootItem); } } BOOL CMFCShellTreeCtrlEx::GetRootItemsEx() { ASSERT_VALID(this); ENSURE(afxShellManager != NULL); ASSERT_VALID(afxShellManager); LPITEMIDLIST pidl; LPSHELLFOLDER pParentFolder = NULL; if (FAILED(SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOP, &pidl))) return FALSE; if (FAILED(SHGetDesktopFolder(&pParentFolder))) return FALSE; LPAFX_SHELLITEMINFOEX pItem = (LPAFX_SHELLITEMINFOEX)GlobalAlloc(GPTR, sizeof(AFX_SHELLITEMINFOEX)); ENSURE(pItem != NULL); pItem->pidlRel = pidl; pItem->pidlFQ = afxShellManager->CopyItem(pidl); // The desktop doesn't have a parent folder, so make this NULL: pItem->pParentFolder = NULL; CString cFolderPath = IsCustomRoot() ? m_cRootDir : CMFCShellUtils::GetDisplayName(pParentFolder, pidl, TRUE); // If a custim root folder was set... if (IsCustomRoot()) { // Just going through the full path from desktop to the custom root folder // to get correct LPAFX_SHELLITEMINFOEX member values for our root item CStringArray cDirPartArr; // The first child item is "Computer", specified by its CSIDL CString cComputer; cComputer.Format(_T("%d*"), (int)CSIDL_DRIVES); cDirPartArr.Add(cComputer); // Tokenizing full folder path to get the remaining child items int nPos = 0; CString cDirPart; cDirPart = m_cRootDir.Tokenize(_T("\\"), nPos); while (cDirPart != _T("")) { // Appendig '\' to the drive item if (cDirPartArr.GetSize() == 1) cDirPart += _T("\\"); cDirPartArr.Add(cDirPart); cDirPart = m_cRootDir.Tokenize(_T("\\"), nPos); } BOOL bResult = TRUE; int nCount = cDirPartArr.GetSize(); // Updating pItem members... for (int i = 0; i < nCount; i++) { bResult = GetFullRootPIDL(pParentFolder, cDirPartArr, i, (LPAFX_SHELLITEMINFO)pItem); if (bResult) { bResult = SUCCEEDED(pItem->pParentFolder->BindToObject(pItem->pidlRel, NULL, IID_IShellFolder, (LPVOID*)&pParentFolder)); // Releasing pItem->pParentFolder interface for each consequtive child item except for the last one (our root folder) if (i < nCount - 1 && pItem->pParentFolder != NULL) pItem->pParentFolder->Release(); } if (!bResult) break; } // If failed to find all child items => free all allocated resources if (!bResult) { afxShellManager->FreeItem(pItem->pidlFQ); afxShellManager->FreeItem(pItem->pidlRel); if (pItem->pParentFolder != NULL) pItem->pParentFolder->Release(); GlobalFree((HGLOBAL)pItem); return FALSE; } } // Performing default CMFCShellTreeCtrl logic to insert top level item TV_ITEM tvItem; tvItem.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_CHILDREN; tvItem.lParam = (LPARAM)pItem; CString strItem = (IsCustomRoot() && m_bFullRootPath) ? cFolderPath : OnGetItemText((LPAFX_SHELLITEMINFO)pItem); tvItem.pszText = strItem.GetBuffer(strItem.GetLength()); tvItem.iImage = OnGetItemIcon((LPAFX_SHELLITEMINFO)pItem, FALSE); tvItem.iSelectedImage = OnGetItemIcon((LPAFX_SHELLITEMINFO)pItem, TRUE); // Assume the desktop has children: tvItem.cChildren = TRUE; // Fill in the TV_INSERTSTRUCT structure for this item: TV_INSERTSTRUCT tvInsert; tvInsert.item = tvItem; tvInsert.hInsertAfter = TVI_LAST; tvInsert.hParent = TVI_ROOT; HTREEITEM hParentItem = InsertItem(&tvInsert); if (!IsCustomRoot()) pParentFolder->Release(); OnItemInserted(hParentItem, cFolderPath); Expand(hParentItem, TVE_EXPAND); return TRUE; } // Enumerating child objects of the folder specified by pParentFolder IShellFolder object // and searching for the item specified by nIndex parameter. // (item names are stored in cDirPartArr array) BOOL CMFCShellTreeCtrlEx::GetFullRootPIDL(LPSHELLFOLDER pParentFolder, CStringArray& cDirPartArr, int nIndex, LPAFX_SHELLITEMINFO pItem) { LPENUMIDLIST pEnum = NULL; HRESULT hr = pParentFolder->EnumObjects(NULL, m_dwFlags, &pEnum); if (FAILED(hr) || pEnum == NULL) return FALSE; LPITEMIDLIST pidlTemp; DWORD dwFetched = 1; CString cDirPart = cDirPartArr[nIndex]; int nLen = cDirPart.GetLength(); int nCSIDL = (cDirPart[nLen - 1] == _T('*')) ? _ttoi(cDirPart) : -1; BOOL bDrive = (nCSIDL >= 0) ? FALSE : (cDirPart[nLen - 1] == _T('\\')); BOOL bFound = FALSE; while (SUCCEEDED(pEnum->Next(1, &pidlTemp, &dwFetched)) && dwFetched) { // If the item is specified by its CSIDL ("Computer")... if (nCSIDL >= 0) { // check if current item is a special folder with the same CSIDL LPITEMIDLIST pidl = NULL; bFound = SUCCEEDED(SHGetSpecialFolderLocation(m_hWnd, nCSIDL, &pidl)); if (bFound) bFound = (pidlTemp->mkid.cb == pidl->mkid.cb) ? !memcmp(pidlTemp->mkid.abID, pidl->mkid.abID, pidl->mkid.cb) : FALSE; afxShellManager->FreeItem(pidl); } else { // Otherwise compare item names (use full pathname for a drive folder) CString cFolderName = CMFCShellUtils::GetDisplayName(pParentFolder, pidlTemp, bDrive); bFound = !cFolderName.CompareNoCase(cDirPart); } // If item is found if (bFound) { // Use AddRef to create another instance of pParentFolder // (the original one will be released) pParentFolder->AddRef(); pItem->pParentFolder = pParentFolder; pItem->pidlRel = pidlTemp; // concatinate current pidl to the root one pItem->pidlFQ = afxShellManager->ConcatenateItem(pItem->pidlFQ, pidlTemp); break; } } pParentFolder->Release(); pEnum->Release(); return bFound; } HRESULT CMFCShellTreeCtrlEx::EnumObjects(HTREEITEM hParentItem, LPSHELLFOLDER pParentFolder, LPITEMIDLIST pidlParent) { ASSERT_VALID(this); ASSERT_VALID(afxShellManager); LPENUMIDLIST pEnum = NULL; HRESULT hr = pParentFolder->EnumObjects(NULL, m_dwFlags, &pEnum); if (FAILED(hr) || pEnum == NULL) { return hr; } LPITEMIDLIST pidlTemp; DWORD dwFetched = 1; // Enumerate the item's PIDLs: while (SUCCEEDED(pEnum->Next(1, &pidlTemp, &dwFetched)) && dwFetched) { TVITEM tvItem; ZeroMemory(&tvItem, sizeof(tvItem)); // Fill in the TV_ITEM structure for this item: tvItem.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_CHILDREN; // AddRef the parent folder so it's pointer stays valid: pParentFolder->AddRef(); // Put the private information in the lParam: LPAFX_SHELLITEMINFOEX pItem = (LPAFX_SHELLITEMINFOEX)GlobalAlloc(GPTR, sizeof(AFX_SHELLITEMINFOEX)); ENSURE(pItem != NULL); pItem->pidlRel = pidlTemp; pItem->pidlFQ = afxShellManager->ConcatenateItem(pidlParent, pidlTemp); pItem->pParentFolder = pParentFolder; tvItem.lParam = (LPARAM)pItem; CString strItem = OnGetItemText((LPAFX_SHELLITEMINFO)pItem); tvItem.pszText = strItem.GetBuffer(strItem.GetLength()); tvItem.iImage = OnGetItemIcon((LPAFX_SHELLITEMINFO)pItem, FALSE); tvItem.iSelectedImage = OnGetItemIcon((LPAFX_SHELLITEMINFO)pItem, TRUE); // Determine if the item has children: DWORD dwAttribs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER | SFGAO_DISPLAYATTRMASK | SFGAO_CANRENAME | SFGAO_FILESYSANCESTOR | SFGAO_REMOVABLE; pParentFolder->GetAttributesOf(1, (LPCITEMIDLIST*)&pidlTemp, &dwAttribs); // If SHELLTREEEX_QUICK_CHLDDETECT was set ignoring SFGAO_FILESYSANCESTOR mask DWORD dwMask = (m_dwProp & SHELLTREEEX_QUICK_CHLDDETECT) != 0 ? SFGAO_HASSUBFOLDER | SFGAO_REMOVABLE : SFGAO_HASSUBFOLDER | SFGAO_FILESYSANCESTOR; tvItem.cChildren = (dwAttribs & dwMask) != 0; // Determine if the item is shared: if (dwAttribs & SFGAO_SHARE) { tvItem.mask |= TVIF_STATE; tvItem.stateMask |= TVIS_OVERLAYMASK; tvItem.state |= INDEXTOOVERLAYMASK(1); //1 is the index for the shared overlay image } // Fill in the TV_INSERTSTRUCT structure for this item: TVINSERTSTRUCT tvInsert; tvInsert.item = tvItem; tvInsert.hInsertAfter = TVI_LAST; tvInsert.hParent = hParentItem; HTREEITEM hItem = InsertItem(&tvInsert); CString cFolderPath = (CA2T) CMFCShellUtils::GetDisplayName(pParentFolder, pItem->pidlRel, TRUE); OnItemInserted(hItem, cFolderPath); // If SHELLTREEEX_EXPAND_ALL flag was set expand the folder if (IsCustomRoot() && tvItem.cChildren && ((m_dwProp & SHELLTREEEX_EXPAND_ALL) != 0)) { Expand(hItem, TVE_EXPAND); } dwFetched = 0; } pEnum->Release(); return S_OK; } DWORD_PTR CMFCShellTreeCtrlEx::GetItemDataEx(HTREEITEM hItem) const { LPAFX_SHELLITEMINFOEX pItem = hItem ? (LPAFX_SHELLITEMINFOEX)GetItemData(hItem) : NULL; return pItem ? pItem->dwItemData : 0; } BOOL CMFCShellTreeCtrlEx::SetItemDataEx(HTREEITEM hItem, DWORD_PTR dwData) { LPAFX_SHELLITEMINFOEX pItem = hItem ? (LPAFX_SHELLITEMINFOEX)GetItemData(hItem) : NULL; if (!pItem) return FALSE; pItem->dwItemData = dwData; return TRUE; } void CMFCShellTreeCtrlEx::OnDeleteitem(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; ENSURE(pNMTreeView != NULL); LPAFX_SHELLITEMINFOEX pItem = (LPAFX_SHELLITEMINFOEX)pNMTreeView->itemOld.lParam; // Calling FreeItemData to free custom item data if (pItem) FreeItemData(pNMTreeView->itemOld.hItem, pItem->dwItemData); CMFCShellTreeCtrl::OnDeleteitem(pNMHDR, pResult); } void CMFCShellTreeCtrlEx::OnItemexpanding(NMHDR* pNMHDR, LRESULT* pResult) { // If SHELLTREEEX_KEEP_CHILDREN was set performing the defaul logic if ((m_dwProp & SHELLTREEEX_KEEP_CHILDREN) == 0) { CMFCShellTreeCtrl::OnItemexpanding(pNMHDR, pResult); return; } // Otherwise... NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; ENSURE(pNMTreeView != NULL); HTREEITEM hItem = pNMTreeView->itemNew.hItem; ENSURE(hItem != NULL); switch (pNMTreeView->action) { case TVE_EXPAND: // Only populating child items if parent folder has no children if (GetChildItem(hItem) == NULL) { GetChildItems(hItem); if (GetChildItem(hItem) == NULL) { // Remove '+': TV_ITEM tvItem; ZeroMemory(&tvItem, sizeof(tvItem)); tvItem.hItem = hItem; tvItem.mask = TVIF_CHILDREN; SetItem(&tvItem); } } break; case TVE_COLLAPSE: { for (HTREEITEM hItemSel = GetSelectedItem(); hItemSel != NULL;) { HTREEITEM hParentItem = GetParentItem(hItemSel); if (hParentItem == hItem) { SelectItem(hItem); break; } hItemSel = hParentItem; } // Collapsing the branch (but not removing child items!) Expand(hItem, TVE_COLLAPSE); } break; } *pResult = 0; }
28ecb977db53d66fba376d6582f1631acb3ead63
28c2ed3928906fdf86eeddee1df535e88840a09c
/Engine/include/Render/IndexBuffer/icIndexBufGL.h
f70fbcaf249bd8a4a09c085445c57e66b1d2ac0a
[ "MIT" ]
permissive
binofet/ice
567332ffeb01a8e173b474d99f53114aa34ce7ae
dee91da76df8b4f46ed4727d901819d8d20aefe3
refs/heads/master
2020-04-16T16:28:30.530556
2015-08-16T03:05:46
2015-08-16T03:05:46
40,782,766
0
0
null
null
null
null
UTF-8
C++
false
false
823
h
icIndexBufGL.h
#ifndef __IC_INDEX_BUFFER_GL_H__ #define __IC_INDEX_BUFFER_GL_H__ #include "Render/IndexBuffer/icIndexBuf.h" #ifdef ICGL #include "Core/GXDevice/icGLext.h" class icIndexBufGL : public icIndexBuf { public: ////////////////////////////////////////////////////////////////////////// // LIFECYCLE icIndexBufGL(void); virtual ~icIndexBufGL(void) {Cleanup();}; virtual ICRESULT Cleanup(void); ////////////////////////////////////////////////////////////////////////// // OPERATIONS virtual ICRESULT Lock(icIndexLock* pIndexLock); virtual ICRESULT Unlock(void); void* GetLocked() {return m_LockBuf;}; GLuint& GetName() {return m_Name;}; static bool m_bHardware; private: GLuint m_Name; void* m_LockBuf; }; #endif //ICGL #endif //__IC_INDEX_BUFFER_GL_H__
7b86f2b669ec8a8dd83ed98ae4e03c1f26359771
9b54ae5d188ebd8281fa4a568622620b5432723b
/module03/ex03/NinjaTrap.cpp
e3ff23dbb011ab9e6ac520e4706289760ae7b287
[]
no_license
mohit-ashar/CPP
5796f907c19e9e5cf158723d76c681fedda8d031
9d7d0dd6930b77adf7155dbc10887ad91f86563a
refs/heads/master
2021-05-17T11:30:22.383339
2020-05-07T13:10:53
2020-05-07T13:10:53
250,754,900
0
1
null
null
null
null
UTF-8
C++
false
false
1,983
cpp
NinjaTrap.cpp
#include "NinjaTrap.hpp" NinjaTrap::NinjaTrap( void ) { std::cout << "Default NinjaTrap constructor called." << std::endl; NinjaTrap("Unnamed"); } NinjaTrap::NinjaTrap(std::string n): ClapTrap(60, 60, 120, 120, 1, n, 60, 5, 0) { std::cout << "N!NJ4-TP " << "Spawning " << n << " in Level: " << this->getLevel() <<" to take on the Mighty N!NJ4Trap!!! (Parametric Constructor called)" << std::endl; } NinjaTrap::NinjaTrap(NinjaTrap & trap) { *this = trap; } NinjaTrap::~NinjaTrap( void ) { std::cout << "N!NJ4-TP " << "Hahaha, destroyed N!NJ4! " << this->getName() << ". You ain't got the Power mate!!! (Destructor called)" << std::endl; } void NinjaTrap::getClapType() { std::cout << "(I am a robot Ninja.)N!NJ4-TP" << std::endl; } void NinjaTrap::ninjaShoeBox(ClapTrap &cp) { std::cout << "Opening the box... Guess who appeared?" << std::endl; cp.getClapType(); } void NinjaTrap::ninjaShoeBox(ScavTrap &cp) { std::cout << "Opening the box... Guess who appeared?" << std::endl; cp.getClapType(); } void NinjaTrap::ninjaShoeBox(NinjaTrap &cp) { std::cout << "Opening the box... Guess who appeared?" << std::endl; cp.getClapType(); } void NinjaTrap::ninjaShoeBox(FragTrap &cp) { std::cout << "Opening the box... Guess who appeared?" << std::endl; cp.getClapType(); } NinjaTrap& NinjaTrap::operator=(NinjaTrap const & trap) { this->setHitPoints(trap.getHitPoints()); this->setMaxEnergyPoints(trap.getMaxEnergyPoints()); this->setEnergyPoints(trap.getEnergyPoints()); this->setMaxHitPoints(trap.getMaxHitPoints()); this->setLevel(trap.getLevel()); this->setName(trap.getName()); this->setMeleeAttackDamage(trap.getMeleeAttackDamage()); this->setRangedAttackDamage(trap.getRangedAttackDamage()); this->setArmorDamageReduction(trap.getArmorDamageReduction()); return (*this); }
f78e8356a5cdbed67a6f1cd74e9ae59ac9268869
4e9aa6d8635d6bfcbaeecbb9420ebdc4c4489fba
/ARXTest/ARX_FFC/DefGE/WorkSurface.h
c2dcb0ff80c0dd402614423535313b6712644763
[]
no_license
softwarekid/myexercise
4daf73591917c8ba96f81e620fd2c353323a1ae5
7bea007029c4c656c49490a69062648797084117
refs/heads/master
2021-01-22T11:47:01.421922
2014-03-15T09:47:41
2014-03-15T09:47:41
18,024,710
0
3
null
null
null
null
GB18030
C++
false
false
894
h
WorkSurface.h
#pragma once #include "../MineGE/LinkedGE.h" #include "dlimexp.h" // 工作面(目前与巷道Tunnel的定义是一样的) class DEFGE_EXPORT_API WorkSurface : public LinkedGE { public: ACRX_DECLARE_MEMBERS(WorkSurface) ; protected: static Adesk::UInt32 kCurrentVersionNumber ; public: WorkSurface () ; WorkSurface (const AcGePoint3d& startPt, const AcGePoint3d& endPt) ; virtual ~WorkSurface () ; bool getArrowDir() const; // 获取回采箭头方向 virtual Acad::ErrorStatus dwgOutFields (AcDbDwgFiler *pFiler) const; virtual Acad::ErrorStatus dwgInFields (AcDbDwgFiler *pFiler); protected: virtual void pushKeyParamToWriter(DrawParamWriter& writer) const; virtual void pullKeyParamFromReader(DrawParamReader& reader); private: bool m_clockWise; // 回采箭头方向(逆时针或顺时针) } ; #ifdef DEFGE_MODULE ACDB_REGISTER_OBJECT_ENTRY_AUTO(WorkSurface) #endif
02a9f6160a94798f5b23953c005a9dff3d5687c2
14248aaedfa5f77c7fc5dd8c3741604fb987de5c
/luogu/P2744.cpp
b64deb982b232f0c15567a15bb1f41000cae404a
[]
no_license
atubo/online-judge
fc51012465a1bd07561b921f5c7d064e336a4cd2
8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b
refs/heads/master
2021-11-22T19:48:14.279016
2021-08-29T23:16:16
2021-08-29T23:16:16
13,290,232
2
0
null
null
null
null
UTF-8
C++
false
false
1,394
cpp
P2744.cpp
// https://www.luogu.org/problemnew/show/P2744 // [USACO5.3]量取牛奶Milk Measuring #include <bits/stdc++.h> using namespace std; const int MAXN = 110; const int MAXQ = 20010; int Q, P; int DMAX; int A[MAXN]; bool B[MAXQ], last[MAXN][MAXQ]; int sol[MAXN]; void save(int x) { for (int i = 0; i <= Q; i++) { last[x][i] = B[i]; } } void restore(int x) { for (int i = 0;i <= Q; i++) { B[i] = last[x][i]; } } bool dfs(int d, int p) { if (d > DMAX) return false; if (B[Q]) return true; if (d == DMAX) return false; for (int i = p+1; i < P; i++) { save(d); int x = A[i]; for (int j = 0; j <= Q; j++) { if (B[j]) { for (int y = j; y <= Q; y += x) { B[y] = true; } } } sol[d+1] = i; if (dfs(d+1, i)) return true; restore(d); } return false; } int main() { scanf("%d%d", &Q, &P); for (int i = 0; i < P; i++) { scanf("%d", &A[i]); } sort(A, A+P); P = unique(A, A+P) - A; while (A[P-1] > Q) P--; B[0] = true; int ans = 0; for (DMAX = 1; DMAX <= 100; DMAX++) { if (dfs(0, -1)) { ans = DMAX; break; } } printf("%d ", ans); for (int i = 1; i <= ans; i++) { printf("%d ", A[sol[i]]); } return 0; }
93b913b19855a309716e8238f7589a6eb6d1744b
3d7e3b5bc0f743cc178b7ac506857f7b0118d68b
/legacy-dont-use/testBrute.cpp
0a3ee2be9be9c34e9ca210fdcb8428463275cc15
[]
no_license
agudallago/left-truncatable-primes-gen
07840129d1894fb00074622671eeb1f93de67853
e42ef5abd6e77e7dc48cf5f61bc6b57851a982ae
refs/heads/master
2021-01-10T19:02:50.645314
2015-02-28T17:35:18
2015-02-28T17:35:18
31,469,902
0
0
null
null
null
null
UTF-8
C++
false
false
4,068
cpp
testBrute.cpp
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> //#include <vector> #define MAX_INPUT_NUM 2166 #define MAX_SEARCH_NUM 1000000000 // There are 2166 left-truncatable primes under 1,000,000,000. #define INPUT_PARAM argv[1] bool isPrime(long p) { // 1 is not prime by definition if (p == 1) return false; // 2 is the only even number which is prime if (p == 2) return true; // the remaining are not (they are divisible by 2) if (p % 2 == 0) return false; // Given it is an odd number different from 1, then check primality until we get to the sqrt of p (greater checks are redundant) long sqrtP = long(sqrt(p)); for (long i = 3; i <= sqrtP; i += 2) { if (p % i == 0) return false; } return true; } long getNthTruncatablePrimeByBruteForce(int nthTruncatable) { if (nthTruncatable <= 0 || nthTruncatable > MAX_INPUT_NUM) { return -1; } size_t truncatableCounter = 0; // iterate over every possible number in range for (size_t j = 0; j < MAX_SEARCH_NUM; j++) { size_t testNum = j; // Will test if i is prime. If it is, then the same will be asked for the truncated version of i. // This will eventually conclude that i is a left truncatable prime number. Then the truncatableCounter // will be incremented until we get to the number we are looking for. while (isPrime(testNum)) { int mult = 10; while (testNum/mult != 0) mult *= 10; mult /= 10; if (mult == 1) { if (nthTruncatable == ++truncatableCounter) { return j; } } testNum -= testNum/mult*mult; } } return -1; // should never get here } /* long getNthTruncatablePrime(long nthTruncatable) { if(nthTruncatable <= 0) return -1; size_t initial_size = 200; long lastPrimes; lastPrimes.reserve( initial_size ); lastPrimes.push_back(2); lastPrimes.push_back(3); lastPrimes.push_back(5); lastPrimes.push_back(7); // trivial case: when asking for first 4 truncatable primes (i.e. first 4 primes) if(nthTruncatable < 5) return lastPrimes[nthTruncatable -1]; int truncatable_primes = 4; const int max_power = 9; ///iterate through powers (10s, 100s, 1000s, etc.) for(int power = 1, mult_factor = 10; power <= max_power; ++power, mult_factor *= 10) { std::vector< long > current_primes; current_primes.reserve( initial_size ); ///iterate through smaller powers inside the outer power (10s in 100s, 100s in 1000s) for(int i = 1; i <= max_power; ++i) { ///construct a new truncatable prime from previous truncatable primes std::vector<long>::const_iterator itEnd = lastPrimes.end(); for(std::vector<long>::const_iterator itBegin = lastPrimes.begin(); itBegin != itEnd ; ++itBegin) { const long result = mult_factor * (i) + *itBegin; if(isPrime( result ) ) { ++truncatable_primes; if(truncatable_primes == nthTruncatable) return result; current_primes.push_back( result ); } } } lastPrimes = current_primes; } return -1; } */ int main(int argc, char **argv) { int msec; // Will try brute force version clock_t start = clock(), diff; printf("%li\n", getNthTruncatablePrimeByBruteForce(atoi(INPUT_PARAM))); diff = clock() - start; msec = diff * 1000 / CLOCKS_PER_SEC; printf("Brute Force: Time taken %d seconds %d milliseconds\n", msec/1000, msec%1000); // Will try optimized version /* start = clock(); printf("%li\n", getNthTruncatablePrime(atoi(INPUT_PARAM))); diff = clock() - start; msec = diff * 1000 / CLOCKS_PER_SEC; printf("Optimized: Time taken %d seconds %d milliseconds\n", msec/1000, msec%1000);*/ return EXIT_SUCCESS; }
567328d23672d3f60e169bb2e5246ae9d91b699a
30e1dc84fe8c54d26ef4a1aff000a83af6f612be
/src/external/boost/boost_1_68_0/boost/format/detail/workarounds_stlport.hpp
447caf6a6243c9c835ce472eab15a4227c7b8ca5
[ "BSL-1.0", "BSD-3-Clause" ]
permissive
Sitispeaks/turicreate
0bda7c21ee97f5ae7dc09502f6a72abcb729536d
d42280b16cb466a608e7e723d8edfbe5977253b6
refs/heads/main
2023-05-19T17:55:21.938724
2021-06-14T17:53:17
2021-06-14T17:53:17
385,034,849
1
0
BSD-3-Clause
2021-07-11T19:23:21
2021-07-11T19:23:20
null
UTF-8
C++
false
false
1,375
hpp
workarounds_stlport.hpp
// ---------------------------------------------------------------------------- // workarounds_stlport.hpp : workaround STLport issues // ---------------------------------------------------------------------------- // Copyright Samuel Krempp 2003. Use, modification, and distribution are // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // see http://www.boost.org/libs/format for library home page // ---------------------------------------------------------------------------- #ifndef BOOST_MACROS_STLPORT_HPP #define BOOST_MACROS_STLPORT_HPP // *** This should go to "boost/config/stdlib/stlport.hpp". // If the streams are not native and there are problems with using templates // accross namespaces, we define some macros to enable a workaround for this. // STLport 4.5 #if !defined(_STLP_OWN_IOSTREAMS) && defined(_STLP_USE_NAMESPACES) && defined(BOOST_NO_USING_TEMPLATE) # define BOOST_IO_STD # define BOOST_IO_NEEDS_USING_DECLARATION #endif // STLport 4.0 #if !defined(__SGI_STL_OWN_IOSTREAMS) && defined(__STL_USE_OWN_NAMESPACE) && defined(BOOST_NO_USING_TEMPLATE) # define BOOST_IO_STD # define BOOST_IO_NEEDS_USING_DECLARATION #endif // ---------------------------------------------------------------------------- #endif // BOOST_MACROS_STLPORT_HPP
a6fb32a7b755dff9a13e1030b4401b3a092963fd
1c73444fa5c8c2bb9a89f4abcddf5956e00c0a00
/current.cpp
2a5af4db4e596fca0ce85c36adea8d44d0cfb9a0
[]
no_license
NicholasHeim/Project_Euler
d307796eb89cfc371193d4c154dfe5485330c800
3bd741703e278ebfe4c720dd89f19274ad5bbf6e
refs/heads/master
2022-05-30T07:09:57.302810
2020-04-29T07:46:30
2020-04-29T07:46:30
229,246,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
cpp
current.cpp
/* * Project Name: Project Euler * File Name: current.cpp * Creation Date: Dec 20, 2018 * Creator: Nicholas Heim * School Email: nwh8@zips.uakron.edu * Purpose: */ #include "current.hpp" #include "HEADER_LIST.hpp" // Problem 017 void numberLetterCount() { } // Problem 018 void maximumPathSum() { ifstream input("Problem_018.txt", std::ios::in); vector<string> file; string temp; // Read in the file line by line // Note: The file MUST NOT have an extra /n at the end. The end must be on the last line of numbers. while(!input.eof()) { getline(input, temp); file.push_back(temp); } int left, right; vector<int> sums; // Initialize with bottom row of the triangle // Checking to see if there are extra lines in the file can be done, // but since I made the file, I do not care to check. for (int i = 0; i < file[file.size() - 1].size(); i += 3) sums.push_back(std::stoi(file[file.size() - 1].substr(i, 2), nullptr, 10)); // In a loop, extract a number from the string, keep the position of it. // Set the sum of that position equal to the new number + max{sums[position], sums[position + 1]} // Iterate through all lines of the file in the vector, the maximum will end at position 0. // Bounds checking is not needed here, as edge values have both values below it. }
1b7449e5fe142f5f94dab784ca3a7db6d6f1ceb2
b63a6de87d4dbf3383fc2d95e2f80292321c1a0d
/Recursive/228 (5).cpp
70442104a5d4c78ccc1ae0b923155f1da081646e
[]
no_license
produdez/C-Fundamental-182
bd23d628f484347d7e152ddad3694d486203a731
d06bc64f56a71d7bd4448cf9294e3ce81dd8fbce
refs/heads/master
2023-01-12T10:42:55.760652
2020-11-17T03:18:41
2020-11-17T03:18:41
313,491,316
0
0
null
null
null
null
UTF-8
C++
false
false
253
cpp
228 (5).cpp
#include <iostream> #define N 5 using namespace std; int fibonacci (int pos,int a=0,int b=1) { if(pos==1) { cout<<a+b<<' '; return a+b; } cout<<a+b<<" "; return fibonacci(pos-1,b,a+b); } main() { fibonacci(N); }
39ef738aaed90f65f7383041bcbae6d7678f018b
bb5533119c3b8ffbfbaa948fae09699c6737d2af
/5_shared_ptr/3_replace_raw_pointer_with_make_shared.cpp
808ddaff43380d7e2900a54fb739f3331c32e63e
[]
no_license
lfq361234/CPPNote
d7e397a9caf1cd74f2730aa0a7e7755561871f80
2287ff1364b39b857d6b4bbaba9caadc6a0ccf75
refs/heads/master
2020-06-01T18:31:51.665367
2019-06-08T12:09:05
2019-06-08T12:09:05
190,884,293
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
3_replace_raw_pointer_with_make_shared.cpp
#include<iostream> #include<string> #include<memory> //for shared_ptr using namespace std; class Dog{ string _name; public: Dog(string name){ cout << "Dog is created: "<< name <<endl; _name=name; } ~Dog(){ cout << "Dog is destroyed: "<< _name<<endl; } void bark(){ cout << "Dog " << _name << " barks"<<endl; } }; void foo(){ shared_ptr<Dog> p(new Dog("Gun")); //Count==1 p.use_count()==1 (calculate how many shared_ptr point to this memory address) { shared_ptr<Dog> p2=p; //Count==2 p.use_count()==2, p2.use_count()==2 p2->bark(); cout<< p.use_count()<<endl; //2 } //count==1 (when get out of scope, p2 is no longer accessible, so the number of shared_ptr reduce to one) p->bark(); }//count==0 (when the count of the shared_ptr=0, free the memory of Dog("Gun") automatically) int main(){ foo(); //An object should be assigned to a smart pointer as soon as it is created. Raw pointer should not be used Dog* d =new Dog("Tank");//bad idea shared_ptr<Dog> p=make_shared<Dog>("Tank");//faster and saver (*p).bark(); system("pause"); return 0; }
7a2c06e76db9a5e82096edc7d862bc22cdc21b0e
b2139a7f5e04114c39faea797f0f619e69b8b4ae
/src/misc/learningEndEffectorWrench/src/sharedArea.cpp
68fe735905e28c2065409366b20b816e33bba666
[]
no_license
hychyc07/contrib_bk
6b82391a965587603813f1553084a777fb54d9d7
6f3df0079b7ea52d5093042112f55a921c9ed14e
refs/heads/master
2020-05-29T14:01:20.368837
2015-04-02T21:00:31
2015-04-02T21:00:31
33,312,790
5
1
null
null
null
null
UTF-8
C++
false
false
749
cpp
sharedArea.cpp
#include "iCub/learningEndEffectorWrench/sharedArea.h" /************************************************************************/ void sharedArea::setF(const Vector& _f) { fMutex.wait(); f = _f; fMutex.post(); } /************************************************************************/ void sharedArea::setQ(const Vector& _q) { qMutex.wait(); q = _q; qMutex.post(); } /************************************************************************/ Vector sharedArea::getQ() { qMutex.wait(); Vector _q=q; qMutex.post(); return _q; } /************************************************************************/ Vector sharedArea::getF() { fMutex.wait(); Vector _f=f; fMutex.post(); return _f; }
2dbf6d3d1234474924fd66cd43411ae466696707
47f07b00ab6b37306e4a4e66294000dbda4c006d
/821.cc
2a042c7047f4a23e2680f78e29f2a68fa64c774e
[]
no_license
lindsay-ablonczy/UVa
6937fadbf0038c2a9fae605ce34a4cf289ae3247
a4f07dce112b9525dd2617188a04c7a8fd53bd75
refs/heads/master
2021-01-22T23:25:53.665693
2014-07-18T22:01:28
2014-07-18T22:01:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
cc
821.cc
#include <iostream> #include <map> #include <vector> #include <sstream> #include <iterator> #include <iomanip> #include <queue> using namespace std; int onedist(map<int,vector<int> >& arr,const int from){ bool vis[100] = {0}; int tdist=0,v=0,lvl=0,count=0,temp=0,sz=1; queue<int> list; list.push(from); while(!list.empty()){ if(v == arr.size()) break; else if(!vis[list.front()-1]){ tdist+=lvl; for(int i = 0;i < arr[list.front()].size();i++) list.push(arr[list.front()][i]); temp += arr[list.front()].size(); vis[list.front()-1] = true; v++;} count++; if(count == sz){ sz = temp; count = temp = 0; lvl++;} list.pop();} return tdist;} int main(){ string line; int trial = 1; cout << fixed; while(getline(cin,line) && line != "0 0"){ istringstream ins(line); int p1,p2,pairs=0,total=0; double avg; map<int,vector<int> > relate; while(ins >> p1 >> p2){ if(p1 != 0 && p2 != 0) relate[p1].push_back(p2);} for(map<int,vector<int> >::iterator it=relate.begin();it != relate.end();it++){ int temp = onedist(relate,it->first); total+=temp;} pairs = relate.size()*(relate.size()-1); avg = total*1.0/pairs; cout << "Case " << trial << ": average length between pages = " << setprecision(3) << avg << " clicks" << endl; trial++;}}
02eabe3029ff029f3eb92c1a2d93a0cdf514f41f
90bc69020ddd6c76bcbbed4ec19cccc378d3cf2a
/HDL2Redstone/src/Component.cpp
09d2e104658ec6c3bfef7b6a9a57c44bc4e346d6
[ "MIT" ]
permissive
tech4me/HDL2Redstone
d57e15de0e9185f83f198d355ec5330cf21f3ed8
738bc080e42b8fd2c1827069ded4ca5135e8c8e1
refs/heads/master
2022-04-17T15:21:20.918247
2020-04-09T09:41:46
2020-04-09T09:41:46
204,271,089
1
0
null
null
null
null
UTF-8
C++
false
false
5,474
cpp
Component.cpp
#include <Component.hpp> using namespace HDL2Redstone; Component::Component(const Cell* CellPtr_) : CellPtr(CellPtr_), ForcePlaced(false), Placed(false) {} Facing Component::getPinFacing(const std::string& PinName_) const { auto tempDir = CellPtr->getPinFacing(PinName_); if (tempDir == Facing::Up || tempDir == Facing::Down) return tempDir; if (P.Orient == Orientation::ZeroCW) { return tempDir; } else if (P.Orient == Orientation::OneCW) { if (tempDir == Facing::North) return Facing::East; if (tempDir == Facing::East) return Facing::South; if (tempDir == Facing::South) return Facing::West; if (tempDir == Facing::West) return Facing::North; } else if (P.Orient == Orientation::TwoCW) { if (tempDir == Facing::North) return Facing::South; if (tempDir == Facing::East) return Facing::West; if (tempDir == Facing::South) return Facing::North; if (tempDir == Facing::West) return Facing::East; } else { if (tempDir == Facing::North) return Facing::West; if (tempDir == Facing::East) return Facing::North; if (tempDir == Facing::South) return Facing::East; if (tempDir == Facing::West) return Facing::South; } return tempDir; } std::tuple<uint16_t, uint16_t, uint16_t> Component::getPinLocation(const std::string& PinName_) const { auto tempLoc = CellPtr->getPinLocation(PinName_); if (P.Orient == Orientation::ZeroCW) { return std::make_tuple(std::get<0>(tempLoc) + P.X, std::get<1>(tempLoc) + P.Y, std::get<2>(tempLoc) + P.Z); } else if (P.Orient == Orientation::OneCW) { return std::make_tuple(-std::get<2>(tempLoc) - 1 + P.X, std::get<1>(tempLoc) + P.Y, std::get<0>(tempLoc) + P.Z); } else if (P.Orient == Orientation::TwoCW) { return std::make_tuple(-std::get<0>(tempLoc) - 1 + P.X, std::get<1>(tempLoc) + P.Y, -std::get<2>(tempLoc) - 1 + P.Z); } else { return std::make_tuple(std::get<2>(tempLoc) + P.X, std::get<1>(tempLoc) + P.Y, -std::get<0>(tempLoc) - 1 + P.Z); } } Coordinate Component::getPinLocationWithPlacement(const std::string& PinName_, const Placement& P_) const { auto tempLoc = CellPtr->getPinLocation(PinName_); if (P_.Orient == Orientation::ZeroCW) { return Coordinate{.X = static_cast<uint16_t>(std::get<0>(tempLoc) + P_.X), .Y = static_cast<uint16_t>(std::get<1>(tempLoc) + P_.Y), .Z = static_cast<uint16_t>(std::get<2>(tempLoc) + P_.Z)}; } else if (P_.Orient == Orientation::OneCW) { return Coordinate{.X = static_cast<uint16_t>(-std::get<2>(tempLoc) - 1 + P_.X), .Y = static_cast<uint16_t>(std::get<1>(tempLoc) + P_.Y), .Z = static_cast<uint16_t>(std::get<0>(tempLoc) + P_.Z)}; } else if (P_.Orient == Orientation::TwoCW) { return Coordinate{.X = static_cast<uint16_t>(-std::get<0>(tempLoc) - 1 + P_.X), .Y = static_cast<uint16_t>(std::get<1>(tempLoc) + P_.Y), .Z = static_cast<uint16_t>(-std::get<2>(tempLoc) - 1 + P_.Z)}; } else { return Coordinate{.X = static_cast<uint16_t>(std::get<2>(tempLoc) + P_.X), .Y = static_cast<uint16_t>(std::get<1>(tempLoc) + P_.Y), .Z = static_cast<uint16_t>(-std::get<0>(tempLoc) - 1 + P_.Z)}; } } std::pair<Coordinate, Coordinate> Component::getRangeWithPlacement(const Placement& Placement_) const { const auto& P = Placement_; uint16_t x1, y1, z1, x2, y2, z2; Schematic S = CellPtr->getSchematic(); uint16_t Width = S.getWidth(); uint16_t Height = S.getHeight(); uint16_t Length = S.getLength(); if (P.Orient == Orientation::ZeroCW) { x1 = P.X; y1 = P.Y; z1 = P.Z; x2 = P.X + Width; y2 = P.Y + Height; z2 = P.Z + Length; } else if (P.Orient == Orientation::OneCW) { x1 = P.X - Length; y1 = P.Y; z1 = P.Z; x2 = P.X; y2 = P.Y + Height; z2 = P.Z + Width; } else if (P.Orient == Orientation::TwoCW) { x1 = P.X - Width; y1 = P.Y; z1 = P.Z - Length; x2 = P.X; y2 = P.Y + Height; z2 = P.Z; } else { x1 = P.X; y1 = P.Y; z1 = P.Z - Width; x2 = P.X + Length; y2 = P.Y + Height; z2 = P.Z; } return std::pair(Coordinate{.X = x1, .Y = y1, .Z = z1}, Coordinate{.X = x2, .Y = y2, .Z = z2}); } namespace HDL2Redstone { std::ostream& operator<<(std::ostream& out, const Component& Component_) { out << "Module Type: " << Component_.CellPtr->getType(); if (Component_.Placed) { int CW; if (Component_.P.Orient == Orientation::ZeroCW) { CW = 0; } else if (Component_.P.Orient == Orientation::OneCW) { CW = 1; } else if (Component_.P.Orient == Orientation::TwoCW) { CW = 2; } else { CW = 3; } out << " Location: " << Component_.P.X << " " << Component_.P.Y << " " << Component_.P.Z << " Number of CW: " << CW << std::endl; } else { out << std::endl; } return out; } } // namespace HDL2Redstone
8a887ac107dc96552444de85d1145f51d424407e
f96bf888cab3d8ae7c3778d589d82eec4bde3d7e
/src/settingcontent.h
97096b59d22e40580ed7258526cba7714605b271
[]
no_license
yisy/curveplot
3d5242315a125a1c1a4930bd9aabac8874d7ba3e
1a783631e0b88346a48ee2b7e21d5d98599654a0
refs/heads/master
2021-01-21T10:30:29.080175
2017-05-19T00:58:10
2017-05-19T00:58:10
91,694,439
1
0
null
null
null
null
UTF-8
C++
false
false
432
h
settingcontent.h
#ifndef SETTINGCONTENT_H #define SETTINGCONTENT_H #include <QFrame> #include <QListWidget> #include <QStackedWidget> namespace Ui { class SettingContent; } class SettingContent : public QFrame { Q_OBJECT public: explicit SettingContent(QFrame *parent = 0); ~SettingContent(); private: QListWidget *styleSelect; QStackedWidget *styleContent; private: Ui::SettingContent *ui; }; #endif // SETTINGCONTENT_H
58120fa0faf9c93a20859d2f0bdfa4c159cb2714
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/cwp/include/tencentcloud/cwp/v20180228/model/BaselineFix.h
b82291cb2ff0890587948bde24b80109aa58bae2
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
8,453
h
BaselineFix.h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CWP_V20180228_MODEL_BASELINEFIX_H_ #define TENCENTCLOUD_CWP_V20180228_MODEL_BASELINEFIX_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cwp/v20180228/model/MachineExtraInfo.h> namespace TencentCloud { namespace Cwp { namespace V20180228 { namespace Model { /** * 基线密码修复 */ class BaselineFix : public AbstractModel { public: BaselineFix(); ~BaselineFix() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取修复项名称 * @return ItemName 修复项名称 * */ std::string GetItemName() const; /** * 设置修复项名称 * @param _itemName 修复项名称 * */ void SetItemName(const std::string& _itemName); /** * 判断参数 ItemName 是否已赋值 * @return ItemName 是否已赋值 * */ bool ItemNameHasBeenSet() const; /** * 获取主机Ip * @return HostIp 主机Ip * */ std::string GetHostIp() const; /** * 设置主机Ip * @param _hostIp 主机Ip * */ void SetHostIp(const std::string& _hostIp); /** * 判断参数 HostIp 是否已赋值 * @return HostIp 是否已赋值 * */ bool HostIpHasBeenSet() const; /** * 获取首次检测时间 * @return CreateTime 首次检测时间 * */ std::string GetCreateTime() const; /** * 设置首次检测时间 * @param _createTime 首次检测时间 * */ void SetCreateTime(const std::string& _createTime); /** * 判断参数 CreateTime 是否已赋值 * @return CreateTime 是否已赋值 * */ bool CreateTimeHasBeenSet() const; /** * 获取最后检测时间 * @return ModifyTime 最后检测时间 * */ std::string GetModifyTime() const; /** * 设置最后检测时间 * @param _modifyTime 最后检测时间 * */ void SetModifyTime(const std::string& _modifyTime); /** * 判断参数 ModifyTime 是否已赋值 * @return ModifyTime 是否已赋值 * */ bool ModifyTimeHasBeenSet() const; /** * 获取修复时间 * @return FixTime 修复时间 * */ std::string GetFixTime() const; /** * 设置修复时间 * @param _fixTime 修复时间 * */ void SetFixTime(const std::string& _fixTime); /** * 判断参数 FixTime 是否已赋值 * @return FixTime 是否已赋值 * */ bool FixTimeHasBeenSet() const; /** * 获取基线检测项结果ID * @return Id 基线检测项结果ID * */ int64_t GetId() const; /** * 设置基线检测项结果ID * @param _id 基线检测项结果ID * */ void SetId(const int64_t& _id); /** * 判断参数 Id 是否已赋值 * @return Id 是否已赋值 * */ bool IdHasBeenSet() const; /** * 获取主机额外信息 注意:此字段可能返回 null,表示取不到有效值。 * @return MachineExtraInfo 主机额外信息 注意:此字段可能返回 null,表示取不到有效值。 * */ MachineExtraInfo GetMachineExtraInfo() const; /** * 设置主机额外信息 注意:此字段可能返回 null,表示取不到有效值。 * @param _machineExtraInfo 主机额外信息 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetMachineExtraInfo(const MachineExtraInfo& _machineExtraInfo); /** * 判断参数 MachineExtraInfo 是否已赋值 * @return MachineExtraInfo 是否已赋值 * */ bool MachineExtraInfoHasBeenSet() const; private: /** * 修复项名称 */ std::string m_itemName; bool m_itemNameHasBeenSet; /** * 主机Ip */ std::string m_hostIp; bool m_hostIpHasBeenSet; /** * 首次检测时间 */ std::string m_createTime; bool m_createTimeHasBeenSet; /** * 最后检测时间 */ std::string m_modifyTime; bool m_modifyTimeHasBeenSet; /** * 修复时间 */ std::string m_fixTime; bool m_fixTimeHasBeenSet; /** * 基线检测项结果ID */ int64_t m_id; bool m_idHasBeenSet; /** * 主机额外信息 注意:此字段可能返回 null,表示取不到有效值。 */ MachineExtraInfo m_machineExtraInfo; bool m_machineExtraInfoHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CWP_V20180228_MODEL_BASELINEFIX_H_
921a880804021b016a59dfda7e1056674de26941
b19ccf55ca03cf746f90952e1d48a0c77fb42601
/lab2/addtimer.h
eeab9d1627a95b9aaae3fc5bb7f30c428a351d24
[ "MIT" ]
permissive
Raikils/K-28_Ivan_Murzin_lab
1be027bf2b54511e6357bcd1d545b200866975b3
bca269412c95621d1f07accf97d46152f13ff052
refs/heads/master
2023-01-22T21:37:16.806615
2020-12-06T09:12:59
2020-12-06T09:12:59
298,974,090
0
0
null
null
null
null
UTF-8
C++
false
false
684
h
addtimer.h
#ifndef ADDTIMER_H #define ADDTIMER_H #include <QDialog> #include <QObject> #include <QMediaPlayer> #include <QString> #include "timer.h" namespace Ui { class AddTimer; } class AddTimer : public QDialog { Q_OBJECT public: explicit AddTimer(QWidget *parent = nullptr); ~AddTimer(); signals: void TimerAdded(Timer timer); void test(); private slots: void on_CreateButton_clicked(); void on_radioButton_2_clicked(); void on_radioButton_clicked(); void on_pushButtonPlay_clicked(); void on_pushButtonStop_clicked(); private: Ui::AddTimer *ui; QString played; bool is_played; QMediaPlayer *sound; }; #endif // ADDTIMER_H
520ca68af7728bc095ecca6d7490f6baa6be3717
19c2a79069874f30f57976e228deb3ab530af37a
/cpp/674.cpp
f22e210b7bb1fed85815cd9fe25bf6b00f3d2aaf
[]
no_license
chaoyuxie/L_C
c67c7c7e9ca15b90971d046087780c05a353048a
6bee9702e76bfd5b0af600a34918f90dacc90549
refs/heads/master
2021-06-04T06:21:31.593795
2020-05-14T14:08:43
2020-05-14T14:08:43
134,550,969
1
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
674.cpp
class Solution { public: int findLengthOfLCIS(vector<int> &nums) { int max_length = 1, length = 1; if (nums.size() == 0) return 0; for (int i = 1; i < nums.size(); i++) { if (nums[i] > nums[i - 1]) max_length = max(++length, max_length); else length = 1; } return max_length; } };
06602b7314bf9e5fffc0d8624ab4cb2927b20b63
d2e4c76bb8c7396492ab1c289fd62043ce2b74c3
/src/AISMsgUIBase.cpp
771684a6966374a24de689b9d79a168ba502d0cf
[]
no_license
cryptik/aismsg_pi
232ed16e9d88eedf6f3bc5e0c5002217a3393312
a5b3f3074260a1c1c783b5c257c20ce80ec83e35
refs/heads/master
2020-03-23T11:45:19.322460
2018-07-30T01:51:58
2018-07-30T01:51:58
141,519,685
0
0
null
null
null
null
UTF-8
C++
false
false
9,029
cpp
AISMsgUIBase.cpp
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version May 29 2018) // http://www.wxformbuilder.org/ // // PLEASE DO *NOT* EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "AISMsgUIBase.h" /////////////////////////////////////////////////////////////////////////// AISMsgUIDialogBase::AISMsgUIDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); m_stMsgTextLabel1 = new wxStaticText( this, wxID_ANY, _("Message Thread:"), wxDefaultPosition, wxDefaultSize, 0 ); m_stMsgTextLabel1->Wrap( -1 ); bSizer1->Add( m_stMsgTextLabel1, 0, wxALL, 5 ); m_tcMsgThread = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,-1 ), wxTE_LEFT|wxTE_MULTILINE|wxTE_READONLY|wxTE_RICH|wxTE_WORDWRAP ); m_tcMsgThread->SetMinSize( wxSize( 350,200 ) ); bSizer1->Add( m_tcMsgThread, 0, wxALL|wxEXPAND, 5 ); m_stMsgTextLabel2 = new wxStaticText( this, wxID_ANY, _("Enter Message Text:"), wxDefaultPosition, wxDefaultSize, 0 ); m_stMsgTextLabel2->Wrap( -1 ); bSizer1->Add( m_stMsgTextLabel2, 0, wxALL, 5 ); m_tcMsgText = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,-1 ), 0 ); bSizer1->Add( m_tcMsgText, 0, wxALL|wxEXPAND, 5 ); m_rbMsgTypeBBM = new wxRadioButton( this, wxID_ANY, _("Binary Broadcast (BBM)"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer1->Add( m_rbMsgTypeBBM, 0, wxALL, 5 ); m_rbMsgTypeABM = new wxRadioButton( this, wxID_ANY, _("Addressed Binary (ABM)"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer1->Add( m_rbMsgTypeABM, 0, wxALL, 5 ); wxGridSizer* gSizer1; gSizer1 = new wxGridSizer( 1, 2, 0, 0 ); m_btnDebug = new wxButton( this, wxID_ANY, _("Debug"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_btnDebug, 0, wxALL|wxALIGN_RIGHT, 5 ); m_btnSend = new wxButton( this, wxID_ANY, _("Send"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_btnSend, 0, wxALIGN_CENTER|wxALL|wxALIGN_RIGHT, 5 ); bSizer1->Add( gSizer1, 0, wxALIGN_RIGHT, 5 ); this->SetSizer( bSizer1 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( AISMsgUIDialogBase::OnDialogClose ) ); m_rbMsgTypeBBM->Connect( wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler( AISMsgUIDialogBase::OnSetMsgType ), NULL, this ); m_rbMsgTypeABM->Connect( wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler( AISMsgUIDialogBase::OnSetMsgType ), NULL, this ); m_btnDebug->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgUIDialogBase::OnDebug ), NULL, this ); m_btnSend->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgUIDialogBase::OnSndMsg ), NULL, this ); } AISMsgUIDialogBase::~AISMsgUIDialogBase() { // Disconnect Events this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( AISMsgUIDialogBase::OnDialogClose ) ); m_rbMsgTypeBBM->Disconnect( wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler( AISMsgUIDialogBase::OnSetMsgType ), NULL, this ); m_rbMsgTypeABM->Disconnect( wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler( AISMsgUIDialogBase::OnSetMsgType ), NULL, this ); m_btnDebug->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgUIDialogBase::OnDebug ), NULL, this ); m_btnSend->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgUIDialogBase::OnSndMsg ), NULL, this ); } AISMsgPrefsDialogBase::AISMsgPrefsDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer2; bSizer2 = new wxBoxSizer( wxVERTICAL ); m_cbEnableBBM = new wxCheckBox( this, wxID_ANY, _("Enable BBM"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); bSizer2->Add( m_cbEnableBBM, 0, wxALL|wxEXPAND, 5 ); m_cbEnableABM = new wxCheckBox( this, wxID_ANY, _("Enable ABM"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); bSizer2->Add( m_cbEnableABM, 0, wxALL|wxEXPAND, 5 ); m_stMsgTextLabel1 = new wxStaticText( this, wxID_ANY, _("Ownship MMSI:"), wxDefaultPosition, wxDefaultSize, 0 ); m_stMsgTextLabel1->Wrap( -1 ); bSizer2->Add( m_stMsgTextLabel1, 0, wxALL|wxEXPAND, 5 ); m_tcOwnshipMMSI = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); m_tcOwnshipMMSI->SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY ); m_tcOwnshipMMSI->SetValidator( wxTextValidator( wxFILTER_NUMERIC, &m_wsOwnMMSI ) ); bSizer2->Add( m_tcOwnshipMMSI, 0, wxALL|wxEXPAND, 5 ); m_sdbSizer1 = new wxStdDialogButtonSizer(); m_sdbSizer1OK = new wxButton( this, wxID_OK ); m_sdbSizer1->AddButton( m_sdbSizer1OK ); m_sdbSizer1Cancel = new wxButton( this, wxID_CANCEL ); m_sdbSizer1->AddButton( m_sdbSizer1Cancel ); m_sdbSizer1->Realize(); bSizer2->Add( m_sdbSizer1, 1, wxEXPAND, 5 ); this->SetSizer( bSizer2 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events m_cbEnableBBM->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnEnableBBM ), NULL, this ); m_cbEnableABM->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnEnableABM ), NULL, this ); m_sdbSizer1OK->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnOk ), NULL, this ); } AISMsgPrefsDialogBase::~AISMsgPrefsDialogBase() { // Disconnect Events m_cbEnableBBM->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnEnableBBM ), NULL, this ); m_cbEnableABM->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnEnableABM ), NULL, this ); m_sdbSizer1OK->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgPrefsDialogBase::OnOk ), NULL, this ); } AISMsgDebugDialogBase::AISMsgDebugDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( 640,460 ), wxDefaultSize ); wxBoxSizer* bSizer3; bSizer3 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer4; bSizer4 = new wxBoxSizer( wxHORIZONTAL ); wxStaticBoxSizer* sbSizer1; sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Filter Messages") ), wxHORIZONTAL ); m_cbFilterNMEA = new wxCheckBox( sbSizer1->GetStaticBox(), wxID_ANY, _("NMEA"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); sbSizer1->Add( m_cbFilterNMEA, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_cbFilterAIS = new wxCheckBox( sbSizer1->GetStaticBox(), wxID_ANY, _("AIS"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); sbSizer1->Add( m_cbFilterAIS, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_cbFilterNMEAEvents = new wxCheckBox( sbSizer1->GetStaticBox(), wxID_ANY, _("Events"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); sbSizer1->Add( m_cbFilterNMEAEvents, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_cbFilterInternal = new wxCheckBox( sbSizer1->GetStaticBox(), wxID_ANY, _("Internal"), wxDefaultPosition, wxDefaultSize, wxCHK_2STATE ); sbSizer1->Add( m_cbFilterInternal, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); bSizer4->Add( sbSizer1, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); m_tcTextStats = new wxTextCtrl( this, wxID_ANY, _("C: 999999 / L: 9999"), wxDefaultPosition, wxSize( -1,-1 ), wxTE_CENTRE|wxTE_READONLY|wxNO_BORDER ); m_tcTextStats->SetMinSize( wxSize( 240,-1 ) ); bSizer4->Add( m_tcTextStats, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_btnPause = new wxButton( this, wxID_ANY, _("Pause"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer4->Add( m_btnPause, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); bSizer3->Add( bSizer4, 0, wxEXPAND|wxALL, 5 ); m_tcAisStream = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,-1 ), wxTE_LEFT|wxTE_MULTILINE|wxTE_READONLY|wxTE_RICH|wxTE_WORDWRAP ); m_tcAisStream->SetMinSize( wxSize( 350,200 ) ); bSizer3->Add( m_tcAisStream, 1, wxALL|wxEXPAND, 5 ); this->SetSizer( bSizer3 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( AISMsgDebugDialogBase::OnDialogClose ) ); m_btnPause->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgDebugDialogBase::OnPause ), NULL, this ); } AISMsgDebugDialogBase::~AISMsgDebugDialogBase() { // Disconnect Events this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( AISMsgDebugDialogBase::OnDialogClose ) ); m_btnPause->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( AISMsgDebugDialogBase::OnPause ), NULL, this ); }
31ffa758aceb0f498f291991f6d9de9fa6421a82
1abf9817e862fb4258881b3cdc4601ca5ed7e40b
/terrain/terrain.cpp
48e4a53b726d6ec245ae951798bd5c64678599c1
[]
no_license
Hankang-Hu/OpenGL
49966fdd3dd0e5b77536b9722ebb6c26d90255be
792535f229c5829add6d1886884376296a97f28e
refs/heads/master
2020-03-10T14:00:42.050870
2018-05-24T07:19:39
2018-05-24T07:19:39
129,414,961
1
0
null
2018-05-11T14:33:10
2018-04-13T14:40:39
C++
UTF-8
C++
false
false
4,958
cpp
terrain.cpp
#include <GL/glut.h> #include <math.h> #include <fstream> #include <stdlib.h> #include <iostream> using namespace std; GLfloat lightx=0.0,lighty=40.0,lightz=100.0,spotx=0.0,spoty=0.0,spotz=50.0; GLfloat lookatX=100.0,lookatY=0.0,lookatZ=100.0,lookcenterX=0.0,lookcenterY=0.0,lookcenterZ=0.0,topX=0.0,topY=0.0,topZ=100.0; GLfloat scale=1.0; GLfloat angle=0.0,R; struct Vec { float x,y,z; }; Vec data[101][101][2]; //GLfloat X=0.0,Y=0.0,Z=0.0; //读取顶点数据 void Data() { ifstream infile("Vertexdata.dat",ios::in); if(!infile){ cout << "open error!" << endl; exit(1); } for(int i = 0; i < 101; i++){ for(int j = 0; j < 101; j++) { infile >> data[i][j][0].x >> data[i][j][0].y >> data[i][j][0].z >> data[i][j][1].x >> data[i][j][1].y >> data[i][j][1].z; } } } //初始化 void init() { glShadeModel(GL_SMOOTH); glClearColor(0.7f,0.7f,0.7f,0.0f); glEnable(GL_DEPTH_TEST); } //绘制图形 void drawTrangle() { for(int i = 0; i < 100; i++) { glBegin(GL_TRIANGLE_STRIP); for(int j = 0; j < 101; j++) { glNormal3f(data[i][j][1].x,data[i][j][1].y,data[i][j][1].z); glVertex3f(data[i][j][0].x,data[i][j][0].y,data[i][j][0].z); glNormal3f(data[i+1][j][1].x,data[i+1][j][1].y,data[i+1][j][1].z); glVertex3f(data[i+1][j][0].x,data[i+1][j][0].y,data[i+1][j][0].z); } glEnd(); } } //键盘 void keyboard(int key,int x,int y) { int mode; switch(key) { case GLUT_KEY_LEFT: mode=glutGetModifiers(); if(mode==GLUT_ACTIVE_CTRL) { angle-=3.0; } else { if(spoty>-50.0) spoty-=2.0; } break; case GLUT_KEY_RIGHT: mode=glutGetModifiers(); if(mode==GLUT_ACTIVE_CTRL) { angle+=3.0; } else { if(spoty<50.0) spoty+=2.0; } break; case GLUT_KEY_UP: mode=glutGetModifiers(); if(mode==GLUT_ACTIVE_CTRL) { if(lookatZ<200.0) lookatZ+=2.0; } else { if(spotx>-50.0) spotx-=2.0; } break; case GLUT_KEY_DOWN: mode=glutGetModifiers(); if(mode==GLUT_ACTIVE_CTRL) { if(lookatZ>-100.0) lookatZ-=2.0; } else { if(spotx<50.0) spotx+=2.0; } break; default: break; } glutPostRedisplay(); return; } void mouse(int button,int state,int x,int y) { if(button == GLUT_WHEEL_DOWN) { scale+=0.01; glutPostRedisplay(); } else if(button == GLUT_WHEEL_UP) { scale-=0.01; glutPostRedisplay(); } } //窗口改变时的回调函数 void ChangeSize(GLint w,GLint h) { //GLfloat ratio;//横宽比 //GLfloat coordinatesize = 100.0f;//设置坐标系 glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70.0,(GLfloat)w/(GLfloat)h,10.0,300.0); //ratio = (GLfloat)w/(GLfloat)h; //glOrtho(-coordinatesize,coordinatesize,-coordinatesize,coordinatesize,-coordinatesize*2.5,coordinatesize*2.5); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void light() { GLfloat light_position[]={lightx,lighty,lightz,0.0}; //cout << lightx <<" "<< lighty << " " << lightz << endl; GLfloat light_ambient[]={0.3,0.3,0.3,1.0}; GLfloat light_diffuse[]={0.0,1.0,0.0,1.0}; GLfloat light_specular[]={0.5,0.5,0.5,1.0}; GLfloat M_diffuse[]={0.9,0.9,0.9,1.0}; //glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_FALSE); glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,M_diffuse); glLightfv(GL_LIGHT0,GL_POSITION,light_position); glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient); glLightfv(GL_LIGHT0,GL_SPECULAR,light_specular); glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse); glEnable(GL_LIGHT0); //glEnable(GL_LIGHTING); } void spot_light() { GLfloat position[] = {spotx,spoty,spotz,1.0}; GLfloat diffuse[] = {0.9,0.9,0.9,1.0}; GLfloat specular[] = {0.6,0.6,0.6,1.0}; GLfloat direction[] = {0.0,0.0,-1.0}; glLightf(GL_LIGHT1,GL_SPOT_CUTOFF,10.0); glLightfv(GL_LIGHT1,GL_POSITION,position); glLightf(GL_LIGHT1,GL_SPOT_EXPONENT,0.6); glLightfv(GL_LIGHT1,GL_SPOT_DIRECTION,direction); glLightfv(GL_LIGHT1,GL_DIFFUSE,diffuse); glLightfv(GL_LIGHT1,GL_SPECULAR,specular); glEnable(GL_LIGHT1); glEnable(GL_LIGHTING); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glPushMatrix(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //light(); //spot_light(); R = sqrt(lookatX*lookatX+lookatY*lookatY); gluLookAt(R*cos(M_PI/180*angle)*scale,R*sin(M_PI/180*angle)*scale,lookatZ*scale,lookcenterX,lookcenterY,lookcenterZ,topX,topY,topZ); light(); spot_light(); //glutSolidCone(M_PI/180*angle*60.0,60.0,100,100); //cout << lookatX <<" "<< lookatY << " " << lookatZ << " " << topZ << endl; //glScalef(scale,scale,scale); drawTrangle(); //glPopMatrix(); glFlush(); } int main(int argc,char *argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(700,700); glutInitWindowPosition(200,200); glutCreateWindow("..."); Data(); glutDisplayFunc(display); glutReshapeFunc(ChangeSize); glutSpecialFunc(keyboard); glutMouseFunc(mouse); init(); glutMainLoop(); return 0; }
be5516706bdd9c7c5786bc8b060df658b8e3ed8f
066517a18bf680315a47b56613ac76c240818444
/include/rts/segment/DictionarySegment.hpp
5180b4f2b0d8fbf59ecc2ef39b5caac049d5459d
[]
no_license
YeXiaoRain/rdf3x-0.3.8
0da62625b6e547b84740d909983af5b0906ad10c
5970ee5228f78d3bcb4ccea70c56b6895d14d7b2
refs/heads/master
2021-01-20T12:10:25.299856
2017-02-21T06:51:00
2017-02-21T06:51:00
82,644,389
6
1
null
null
null
null
UTF-8
C++
false
false
4,214
hpp
DictionarySegment.hpp
#ifndef H_rts_segment_DictionarySegment #define H_rts_segment_DictionarySegment //--------------------------------------------------------------------------- // RDF-3X // (c) 2008 Thomas Neumann. Web site: http://www.mpi-inf.mpg.de/~neumann/rdf3x // // This work is licensed under the Creative Commons // Attribution-Noncommercial-Share Alike 3.0 Unported License. To view a copy // of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // or send a letter to Creative Commons, 171 Second Street, Suite 300, // San Francisco, California, 94105, USA. //--------------------------------------------------------------------------- #include "infra/util/Type.hpp" #include "rts/segment/Segment.hpp" #include <string> #include <vector> //--------------------------------------------------------------------------- class DatabaseBuilder; //--------------------------------------------------------------------------- /// A dictionary mapping strings to ids and backwards class DictionarySegment : public Segment { public: /// The segment id static const Segment::Type ID = Segment::Type_Dictionary; /// Possible actions enum Action { Action_UpdateMapping }; /// A literal struct Literal { /// The string std::string str; /// The type ::Type::ID type; /// The sub-type (if any, otherwise 0) unsigned subType; /// Comparison bool operator==(const Literal& l) const { return (type==l.type)&&(subType==l.subType)&&(str==l.str); } /// Comparison bool operator<(const Literal& l) const { return (type<l.type)||((type==l.type)&&((subType<l.subType)||((subType==l.subType)&&(str<l.str)))); } }; /// A source for strings class StringSource { public: /// Destructor virtual ~StringSource(); /// Get a new string virtual bool next(unsigned& len,const char*& data,::Type::ID& type,unsigned& subType) = 0; /// Remember a string position and hash virtual void rememberInfo(unsigned page,unsigned ofs,unsigned hash) = 0; }; /// A source for (id) -> hash,ofsLen updates class IdSource { public: /// Destructor virtual ~IdSource(); /// Get the next entry virtual bool next(unsigned& page,unsigned& ofsLen) = 0; }; /// A source for hash->page updates class HashSource { public: /// Destructor virtual ~HashSource(); /// Get the next entry virtual bool next(unsigned& hash,unsigned& page) = 0; }; class HashIndexImplementation; class HashIndex; private: /// The start of the raw string table unsigned tableStart; /// The next id after the existing ones unsigned nextId; /// The mapping table(s) (id->page) std::vector<std::pair<unsigned,unsigned> > mappings; /// The root of the index b-tree unsigned indexRoot; /// Refresh segment info stored in the partition void refreshInfo(); /// Refresh the mapping table if needed void refreshMapping(); /// Lookup an id for a given string on a certain page in the raw string table bool lookupOnPage(unsigned pageNo,const std::string& text,::Type::ID type,unsigned subType,unsigned hash,unsigned& id); /// Load the raw strings (must be in id order) void loadStrings(StringSource& source); /// Load the string mappings (must be in id order) void loadStringMappings(IdSource& source); /// Write the string index (must be in hash order) void loadStringHashes(HashSource& source); friend class DatabaseBuilder; public: /// Constructor DictionarySegment(DatabasePartition& partition); /// Get the type Segment::Type getType() const; /// Lookup an id for a given string bool lookup(const std::string& text,::Type::ID type,unsigned subType,unsigned& id); /// Lookup a string for a given id bool lookupById(unsigned id,const char*& start,const char*& stop,::Type::ID& type,unsigned& subType); /// Get the next id unsigned getNextId() const { return nextId; } /// Load new literals into the dictionary void appendLiterals(const std::vector<Literal>& strings); }; //--------------------------------------------------------------------------- #endif
58ea89b6ac51c10450befa06075997e24143d312
9fbd67e5f14b85c9b980625665dbe8164f1f3954
/array.cpp
1b02d62c51ec87527b4cb78f339dea99aadbfaed
[]
no_license
S-Ng/CompSci31_UCLA
d5a1030085902f4f19a61f61916b6367ef5f5abb
125b51a5e4bae03229b19f9887ba2899eabb0a71
refs/heads/master
2020-06-14T11:55:08.581354
2020-05-15T16:20:11
2020-05-15T16:20:11
194,998,369
0
0
null
null
null
null
UTF-8
C++
false
false
26,519
cpp
array.cpp
#include <iostream> #include <string> #include <cassert> #include <cctype> using namespace std; // Declare all functions int countMatches(const string a[], int n, string target); int detectMatch(const string a[], int n, string target); bool detectSequence(const string a[], int n, string target, int& begin, int& end); int detectMin(const string a[], int n); int moveToBack(string a[], int n, int pos); int moveToFront(string a[], int n, int pos); int detectDifference(const string a1[], int n1, const string a2[], int n2); int deleteDups(string a[], int n); bool contains(const string a1[], int n1, const string a2[], int n2); int meld(const string a1[], int n1, const string a2[], int n2, string result[], int max); int split(string a[], int n, string splitter); string strToUpper(string str); void strArrComp(string a1[], string a2[], int len); bool isNondecreasingOrder(const string a[], int n); int main() { const int len = 6; string list[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; // Test countMatches bool TestcountMatches = true; if (TestcountMatches) { assert(countMatches(list, len, "CS31") == 2); // function works assert(countMatches(list, 3, "CS31") == 1); // size limit works assert(countMatches(list, 2, "CS31") == 0); // size limit works assert(countMatches(list, len, "Fdsa") == 0); // doesn't accept absent strings assert(countMatches(list, len, "Scand") == 0); // partial equality doesnt matter assert(countMatches(list, len, "SCand40") == 0); // case matters assert(countMatches(list, len, "Scand40") == 1); // case matters assert(countMatches(list, 0, "BE110") == 0); // 0 is fine and doesn't look at BE110 assert(countMatches(list, -1, "BE110") == -1); // negatives not allowed cout << "all countMatches tests succeeded" << endl; } // Test detectMatch bool TestdetectMatch = true; if (TestdetectMatch) { assert(detectMatch(list, len, "CS31") == 2); // function works assert(detectMatch(list, len, "CS31") != 5); // function doesn't count later occurrances assert(detectMatch(list, 2, "CS31") == -1); // returns -1 if not found assert(detectMatch(list, len, "Scand") == -1); // partial equality doesnt matter assert(detectMatch(list, len, "SCand40") == -1); // case matters assert(detectMatch(list, len, "Scand40") == 4); // case matters/function works assert(detectMatch(list, 0, "BE110") == -1); // 0 is fine and doesn't look at BE110 assert(detectMatch(list, -1, "BE110") == -1); // negatives not allowed cout << "all detectMatch tests succeeded" << endl; } // Test detectSequece bool TestdetectSequence = true; if (TestdetectSequence) { string list[len] = { "BE110", "CS31", "CS31", "CS31", "Scand40", "CS31" }; int b = 999; int e = 999; assert(detectSequence(list, -1, "CS31", b, e) == false); // negative array length assert(b == 999 && e == 999); // b and e unchanged for false result assert(detectSequence(list, len, "CS31", b, e) == true); // function returns true for present target assert(detectSequence(list, -1, "CS31", b, e) == false); // negative array length assert(detectSequence(list, 0, "BE110", b, e) == false); // BE110 not evaluated at 0 assert(detectSequence(list, len, "CompSci31", b, e) == false); // return false for no target occurances detectSequence(list, len, "CS31", b, e); assert(b == 1 && e == 3); // fill b and e correctly b = 999; e = 999; detectSequence(list, 3, "CS31", b, e); assert(b == 1 && e == 2); // array length cutoff works b = 999; e = 999; detectSequence(list, len, "Scand40", b, e); assert(b == 4 && e == 4); // same b and e for one occurance cout << "all detectSequence tests succeeded" << endl; } // Test detectMin bool TestdetectMin = true; if (TestdetectMin) { string list1[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; assert(detectMin(list1, len) == 0); // first element can be smallest assert(detectMin(list1, -2) == -1); // negative array length caught string list2[len] = { "BE167", "be110", "CS31", "LS7C", "Scand40", "CS31" }; assert(detectMin(list2, len) == 1); // BE110 is smallest despite capitalization string list3[len] = { "BE167", "be110", "be110", "LS7C", "Scand40", "CS31" }; assert(detectMin(list3, len) == 1); // first be110 is returned as lowest string list4[len] = { "BE167", "be110", "be110", "LS7C", "AOS30", "CS31" }; assert(detectMin(list4, len) == 4); // returns AOS30 string list5[len] = { "BE167", "be110", "110", "LS7C", "AOS30", "CS31" }; assert(detectMin(list5, len) == 2); // returns 110 string list6[len] = { "BE110", "be110", "BE", "BE110", "Be110", "be110" }; assert(detectMin(list6, len) == 2); // returns BE string list7[len] = { "BE167", "be110", "B110", "LS7C", "AOS30", "CS31" }; assert(detectMin(list7, len) == 4); // character value has precedence over length string list8[len] = { "BE167", "be110", "B110", "LS7C", "AOS30", "AAA" }; assert(detectMin(list8, len) == 5); // last element correctly evaluated cout << "all detectMin tests succeeded" << endl; } /*Investigate .compare() function string str1 = "Bd110"; string str2 = "BE110"; for (int i = 0; i != str1.size(); i++) str1[i] = toupper(str1[i]); if (str1.compare(str2) == 0) cout << "Equal" << endl; else if (str1.compare(str2) < 0) cout << "Str1 smaller than Str2" << endl; else if (str1.compare(str2) > 0) cout << "Str1 larger than Str2" << endl;*/ // Test moveToBack bool TestmoveToBack = true; if (TestmoveToBack) { string list1[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; assert(moveToBack(list1, len, 0) == 0); // returns position moved to back assert(moveToBack(list1, -1, 4) == -1); // negatives array length tested string list2[len] = { "BE167L", "CS31", "LS7C", "Scand40", "CS31", "BE110" }; strArrComp(list1, list2, len); // was rearrangement successful assert(moveToBack(list2, len, 2) == 2); // returns position moved to back string list3[len] = { "BE167L", "CS31", "Scand40", "CS31", "BE110", "LS7C" }; strArrComp(list3, list2, len); // was rearrangement successful cout << "all moveToBack tests succeeded" << endl; } // Test moveToFront bool TestmoveToFront = true; if (TestmoveToFront) { string list1[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; assert(moveToFront(list1, len, 3) == 3); // outputs pos assert(moveToFront(list1, -1, 0) == -1); // negative array length string list2[len] = { "LS7C", "BE110", "BE167L", "CS31", "Scand40", "CS31" }; strArrComp(list1, list2, len); // was rearrangement successful cout << "all moveToFront tests succeeded" << endl; } // Test detectDifference bool TestdetectDifference = true; if (TestdetectDifference) { string list4[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; string list2[len] = { "BE110", "BE167L", "CompSci31", "LS7C", "Scand40", "CS31" }; assert(detectDifference(list4, len, list2, len) == 2); string list3[len - 1] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40" }; assert(detectDifference(list4, len, list3, len - 1) == 5); //[ITS THE POSITION 4 BUT NUMBER 5. WHICH TAKES PRECENDENCE?] assert(detectDifference(list4, len, list2, 2) == 2); // test liming array size assert(detectDifference(list4, len, list2, 1) == 1); // test limiting array size assert(detectDifference(list4, -1, list2, 1) == -1); // negative array length not allowed cout << "all detectDifference tests succeeded" << endl; } // Test deleteDups bool testdeleteDups = true; if (testdeleteDups) { string list1[len] = { "BE110", "BE110", "CS31", "CS31", "Scand40", "CS31" }; //cout << deleteDups(list1, len); assert(deleteDups(list1, len) == 4); // outputs 4 retained elements string list1_1[len] = { "BE110", "CS31", "Scand40", "CS31" , "BE110", "CS31" }; strArrComp(list1, list1_1, 4); // test that it correctly cuts duplicates string list2[len] = { "BE167L", "CS31", "CS31", "CS31", "CS31", "CS31" }; assert(deleteDups(list2, len) == 2); // outputs 2 retained elements (can remove from end) assert(deleteDups(list1, -1) == -1); // negative array length returns -1 string list3[2] = { "BE167L", "CS31" }; strArrComp(list2, list3, 2); // test that it correctly cuts duplicates cout << "all deleteDups tests succeeded" << endl; } // Test contains bool testcontains = true; if (testcontains) { string big[10] = { "danvers", "thor", "stark", "banner", "romanoff", "stark" }; string little1[10] = { "thor", "banner", "romanoff" }; assert(contains(big, 6, little1, 3)); // searches past inbetween elements string little2[10] = { "stark", "thor" }; assert(!contains(big, 6, little2, 2)); // doesn't search entire array each time string little3[10] = { "thor", "stark", "stark" }; assert(contains(big, 6, little3, 3)); // registers multiple of same element string little4[10] = { "thor", "thor", "stark" }; assert(!contains(big, 6, little4, 3)); // returns false assert(contains(big, 6, little4, 0)); // returns true assert(!contains(big, -1, little4, 0)); // negative array length string little5[10] = { "danvers", "thor", "stark", "banner", "romanoff", "stark", "simon", "simon" }; assert(!contains(big, 6, little5, 8)); // longer compare array than search array cout << "all contains tests were successful" << endl; } // Test isNondecreasingOrder bool testisNondecreasingOrder = true; if (testisNondecreasingOrder) { string str[3] = { "abs", "bca", "bca" }; if (isNondecreasingOrder(str, 3)) cout << "isNondecreasingOrder test successful" << endl; } // Test meld bool testmeld = true; if (testmeld) { string x[5] = { "banner", "rhodes", "rogers", "stark", "tchalla" }; string y[4] = { "danvers", "rogers", "rogers", "thor" }; string z[20]; assert(meld(x, 5, y, 4, z, 20) == 9); // returns correct size of result string comp[20] = { "banner", "danvers" ,"rhodes" ,"rogers", "rogers", "rogers", "stark", "tchalla", "thor" }; strArrComp(z, comp, 20); // generally works as desired string y2[4] = { "rogers", "danvers", "rogers", "thor" }; assert(meld(x, 5, y2, 4, z, 20) == -1); // one input not in nondecreasing order assert(meld(x, 5, y, 4, z, 8) == -1); // max < size needed for array [but having max is unecessary. It's not used at all] assert(meld(x, -1, y, 4, z, 10) == -1); // negative array size cout << "all meld tests succeeded" << endl; } // Test split bool testsplit = true; if (testsplit) { string f[6] = { "rhodes", "banner", "stark", "danvers", "thor", "rogers" }; assert(split(f, 6, "romanoff")==4); // returns 4 // f might now be // "rhodes" "banner" "rogers" "danvers" "thor" "stark" // or "rogers" "danvers" "banner" "rhodes" "stark" "thor" // or several other orderings. // The first 4 elements are < "romanoff"; the last 2 aren't. string g[4] = { "romanoff", "rogers", "thor", "banner" }; assert(split(g, 4, "rogers")==1); // returns 1 string list1[len] = { "BE110", "BE167L", "CS31", "LS7C", "Scand40", "CS31" }; assert(split(list1, len, "AOS50") == len); // no elements shorter than splitter assert(split(list1, -1, "BE100") == -1); // negative array length cout << "all split tests succeeded" << endl; } string h[7] = { "romanoff", "thor", "rogers", "banner", "", "danvers", "rogers" }; assert(countMatches(h, 7, "rogers") == 2); assert(countMatches(h, 7, "") == 1); assert(countMatches(h, 7, "rhodes") == 0); assert(countMatches(h, 0, "rogers") == 0); assert(detectMatch(h, 7, "rogers") == 2); assert(detectMatch(h, 2, "rogers") == -1); int bg; int en; assert(detectSequence(h, 7, "banner", bg, en) && bg == 3 && en == 3); string g[4] = { "romanoff", "thor", "banner", "danvers" }; assert(detectMin(g, 4) == 2); assert(detectDifference(h, 4, g, 4) == 2); assert(contains(h, 7, g, 4)); assert(moveToBack(g, 4, 1) == 1 && g[1] == "banner" && g[3] == "thor"); string f[4] = { "danvers", "banner", "thor", "rogers" }; assert(moveToFront(f, 4, 2) == 2 && f[0] == "thor" && f[2] == "banner"); string e[5] = { "danvers", "danvers", "danvers", "thor", "thor" }; //cout << deleteDups(e, 5); string comp[5] = { "danvers","thor", "thor", "danvers", "danvers" }; //strArrComp(e, comp, 5); assert(deleteDups(e, 5) == 2); // outputs 3 assert(e[1] == "thor"); string x[4] = { "rhodes", "rhodes", "tchalla", "thor" }; string y[4] = { "banner", "danvers", "rhodes", "rogers" }; string z[10]; assert(meld(x, 4, y, 4, z, 10) == 8 && z[5] == "rogers"); assert(split(h, 7, "rogers") == 3); cout << "All provided tests succeeded" << endl; } int countMatches(const string a[], int n, string target) { /* Return the number of strings in the array that are equal to target.[Of course, in this and other functions, if n is negative, the paragraph above that starts "Notwithstanding" trumps this by requiring that the function return −1.Also, in the description of this function and the others, when we say "the array", we mean the n elements that the function is aware of.] As noted above, case matters: Do not consider "thor" to be equal to "ThoR".Here's an example: string d[9] = { "thor", "romanoff", "danvers", "danvers", "stark", "stark", "stark", "danvers", "danvers" }; int i = countMatches(d, 9, "danvers"); // returns 4 int j = countMatches(d, 5, "stark"); // returns 1 int k = countMatches(d, 9, "barton"); // returns 0 */ if (n < 0) // invalid input return -1; int matches = 0; for (int i = 0; i != n; i++) { if (a[i] == target) matches++; } return matches; } int detectMatch(const string a[], int n, string target) { /* Return the position of a string in the array that is equal to target; if there is more than one such string, return the smallest position number of such a matching string.Return −1 if there is no such string. As noted above, case matters: Do not consider "tHOR" to be equal to "Thor". string people[5] = { "danvers", "thor", "stark", "banner", "romanoff" }; int j = detectMatch(people, 5, "banner"); // returns 3 */ if (n < 0) // invalid input return -1; int i = 0; for (i = 0; i != n; i++) { if (a[i] == target) return i; // return position of first match } return -1; // target string not present } bool detectSequence(const string a[], int n, string target, int& begin, int& end) { /* Find the earliest occurrence in a of one or more consecutive strings that are equal to target; set begin to the position of the first occurrence of target, set end to the last occurrence of target in that earliest consecutive sequence, and return true.If n is negative or if no string in a is equal to target, leave begin and end unchanged and return false.Here's an example: string d[9] = { "thor", "romanoff", "danvers", "danvers", "stark", "stark", "stark", "danvers", "danvers" }; int b; int e; bool b1 = detectSequence(d, 9, "danvers", b, e); // returns true and // sets b to 2 and e to 3 bool b2 = detectSequence(d, 9, "romanoff", b, e); // returns true and // sets b to 1 and e to 1 bool b3 = detectSequence(d, 9, "rogers", b, e); // returns false and // leaves b and e unchanged */ if (n < 0) // negative array length return false; for (int i = 0; i != n; i++) { if (a[i] == target) { // first occurance begin = i; // set begin to first occurance while (a[i] == target && i != n) { end = i; // set end i++; } return true; // begin and end set. break out of loop } } return false; // no occurance of target } int detectMin(const string a[], int n) { /* Return the position of a string in the array such that that string is <= every string in the array. If there is more than one such string, return the smallest position number of such a string. Return −1 if the function should examine no elements of the array.Here's an example: string people[5] = { "danvers", "thor", "stark", "banner", "romanoff" }; int j = detectMin(people, 5); // returns 3, since banner is earliest // in alphabetic order */ if (n <= 0) // invalid input or if function should examine no elements of the array return -1; int lowestLoc = 0; // default lowest character location is first string string lowestStr = strToUpper(a[0]); // default lowest capitalized string is first array entry for (int i = 1; i != n; i++) { string compStr = strToUpper(a[i]); // capitalize next string to compare if (compStr.compare(lowestStr) < 0) { // new string is smaller or lower character than previously lowest string lowestLoc = i; lowestStr = compStr; } } return lowestLoc; } int moveToBack(string a[], int n, int pos) { /* Eliminate the item at position pos by copying all elements after it one place to the left.Put the item that was thus eliminated into the last position of the array.Return the original position of the item that was moved to the end.Here's an example: string people[5] = { "danvers", "thor", "stark", "banner", "romanoff" }; int j = moveToBack(people, 5, 1); // returns 1 // people now contains: "danvers" "stark" "banner", "romanoff" "thor" */ if (n < 0) // invalid input return -1; string strToBack = a[pos]; for (int i = pos + 1; i != n; i++) { // iterate though positions after string to move back a[i - 1] = a[i]; // copy value of current string into previous location (starting with copying one after pos into pos) } a[n-1] = strToBack; // move element at pos to back return pos; } int moveToFront(string a[], int n, int pos) { /* Eliminate the item at position pos by copying all elements before it one place to the right. Put the item that was thus eliminated into the first position of the array.Return the original position of the item that was moved to the beginning.Here's an example: string people[5] = { "danvers", "thor", "stark", "banner", "romanoff" }; int j = moveToFront(people, 5, 2); // returns 2 // people now contains: "stark" "danvers" "thor" "banner", "romanoff" */ if (n < 0) // invalid input return -1; string strToFront = a[pos]; for (int i = pos; i > 0; i--) { // iterate though positions a[i] = a[i - 1]; // copy value of string left } a[0] = strToFront; // move element at pos to back return pos; } int detectDifference(const string a1[], int n1, const string a2[], int n2) { /*Return the position of the first corresponding elements of a1 and a2 that are not equal. n1 is the number of interesting elements in a1, and n2 is the number of interesting elements in a2. If the arrays are equal up to the point where one or both runs out, return whichever value of n1 and n2 is less than or equal to the other. Here's an example: string cast[5] = { "danvers", "thor", "stark", "banner", "romanoff" }; string roles[4] = { "danvers", "thor", "barton", "rhodes" }; int k = detectDifference(cast, 5, roles, 4); // returns 2 int m = detectDifference(cast, 2, roles, 1); // returns 1*/ int limit = n2; // default n2 is limiting factor if (n1 < n2) // n1 smaller than n2 limit = n1; // n1 is limiting factor if (limit < 0) // invalid input return -1; for (int i = 0; i != limit; i++) { if (a1[i] != a2[i]) { return i; } } return limit; } int deleteDups(string a[], int n) { /*For every sequence of consecutive identical items in a, retain only one item of that sequence. Suppose we call the number of retained items r.Then when this functions returns, elements 0 through r - 1 of a must contain the retained items(in the same relative order they were in originally), and the remaining elements may have whatever values you want. Return the number of retained items.Here's an example: string d[9] = { "thor", "romanoff", "danvers", "danvers", "stark", "stark", "stark", "danvers", "danvers" }; int p = deleteDups(d, 9); // returns 5 // d[0] through d[4] now contain "thor" "romanoff" "danvers" "stark" "danvers" // We no longer care what strings are in d[5] and beyond. string e[5] = { "danvers", "danvers", "danvers", "thor", "thor" }; string comp[5] = { "danvers","thor", "thor", "danvers", "danvers" }; */ if (n < 0) // invalid input return -1; int moved = 0; for (int i = 1; i != n-moved; i++) { if (a[i - 1] == a[i]) { // compare consecutive strings starting at beginning moveToBack(a, n, i); // move duplicate string to the end and all others forward i--; moved++; } } return n-moved; } bool contains(const string a1[], int n1, const string a2[], int n2) { /*If all n2 elements of a2 appear in a1, in the same order(though not necessarily consecutively), then return true. Return false if a1 does not so contain a2. (Of course, every sequence, even a sequence of 0 elements, contains a sequence of 0 elements.) Return false (instead of −1) if this function is passed any bad arguments.Here's an example: string big[10] = { "danvers", "thor", "stark", "banner", "romanoff", "stark" }; string little1[10] = { "thor", "banner", "romanoff" }; bool b1 = contains(big, 6, little1, 3); // returns true string little2[10] = { "stark", "thor" }; bool b2 = contains(big, 6, little2, 2); // returns false string little3[10] = { "thor", "stark", "stark" }; bool b3 = contains(big, 6, little3, 3); // returns true string little4[10] = { "thor", "thor", "stark" }; bool b4 = contains(big, 6, little4, 3); // returns false bool b5 = contains(big, 6, little4, 0); // returns true*/ //string big[10] = { "danvers", "thor", "stark", "banner", "romanoff", "stark" }; //string little2[10] = { "stark", "thor" }; if (n1 < n2 || n2 < 0) // fewer elements in bigger array than smaller one or a negative input return false; int start = 0; int matches = 0; for (int i = 0; i != n2; i++) { // iterate through little array for (int k = start; k != n1; k++) { // iterate though big array if (a2[i] == a1[k]) { // entry in little arary matches big array start = k+1; // next iteration, can only look at elements past k matches++; // count that a match was made break; } } } if (matches == n2) return true; else return false; } int meld(const string a1[], int n1, const string a2[], int n2, string result[], int max) { /*If a1 has n1 elements in nondecreasing order, and a2 has n2 elements in nondecreasing order, place in result all the elements of a1 and a2, arranged in nondecreasing order, and return the number of elements so placed.Return −1 if the result would have more than max elements or if a1 and/or a2 are not in nondecreasing order. (Note: nondecreasing order means that no item is > the one that follows it.) Here's an example: string x[5] = { "banner", "rhodes", "rogers", "stark", "tchalla" }; string y[4] = { "danvers", "rogers", "rogers", "thor" }; string z[20]; int n = meld(x, 5, y, 4, z, 20); // returns 9 // z has banner danvers rhodes rogers rogers rogers stark tchalla thor*/ if (n2 < 0 || n1 < 0 || // n1 or n2 negative !isNondecreasingOrder(a1, n1) || !isNondecreasingOrder(a2, n2) || // or a1 and/or a2 are not in nondecreasing order (n1+n2) > max) // or result would have more than max elements return -1; int len = n1 + n2; for (int i = 0; i != n1; i++) result[i] = a1[i]; // copy a1 into result for (int k = n1; k != len; k++) result[k] = a2[k-n1]; // copy a2 into result while (!isNondecreasingOrder(result, len)) { // repeat until result is in nondecreasing order for (int j = 0; j != len; j++) { if (strToUpper(result[j]).compare(strToUpper(result[j + 1])) > 0) // first element is larger than previous element, move to back moveToBack(result, len, j); // move larger element to back } } return (len); } int split(string a[], int n, string splitter) { /*Rearrange the elements of the array so that all the elements whose value is < splitter come before all the other elements, and all the elements whose value is > splitter come after all the other elements.Return the position of the first element that, after the rearrangement, is not < splitter, or n if there are no such elements.Here's an example: string f[6] = { "rhodes", "banner", "stark", "danvers", "thor", "rogers" }; int r = split(f, 6, "romanoff"); // returns 4 // f might now be // "rhodes" "banner" "rogers" "danvers" "thor" "stark" // or "rogers" "danvers" "banner" "rhodes" "stark" "thor" // or several other orderings. // The first 4 elements are < "romanoff"; the last 2 aren't. string g[4] = { "romanoff", "rogers", "thor", "banner" }; int s = split(g, 4, "rogers"); // returns 1 // g must now be either "banner" "rogers" "romanoff" "thor" or "banner" "rogers" "thor" "romanoff" // All elements < "rogers" (i.e., "banner") come before all others. // All elements > "rogers" (i.e., "thor" and "romanoff") come after all others.*/ if (n < 0) // invalid input return -1; int postSplitLoc = 0; for (int i = 0; i != n; i++) { // iterate through entire string if (strToUpper(a[i]).compare(strToUpper(splitter)) < 0) { // evaluated string is less than splitter moveToFront(a, n, i); // move smaller string to the front postSplitLoc++; // will give final position of first element that, after the rearrangement, is not < splitter } } if (postSplitLoc == 0) return n; else return postSplitLoc; } string strToUpper(string str) { //strToUpper capitalizes all letters in a string for (int i = 0; i != str.size(); i++) if (isalpha(str[i])) // if a letter (this shouldn't actually matter. toupper works with non-alphabetic characters) str[i] = toupper(str[i]); // convert to uppercase return str; } void strArrComp(string a1[], string a2[], int len) { for (int i = 0; i != len;i++) assert(a1[i] == a2[i]); } bool isNondecreasingOrder(const string a[], int n) { int lessthan = 0; for (int i = 1; i != n; i++) { string a1 = a[i - 1]; string a2 = a[i]; int result = strToUpper(a1).compare(strToUpper(a2)); if (result < 0 || result == 0) // a1[i-1] is less than or = a1[i] (capitalized) lessthan++; } if (lessthan == n - 1) return true; else return false; }
5d6949bba07a4d361209bf1fdb14340fae09c567
f8db3ffcabb41e8fa9642fe70f0ca9c5c60fce1f
/basic/include/basic/Collection.h
0c34673f48a46cba50f01cfed0cb905022214967
[ "BSD-2-Clause" ]
permissive
qsphan/the-omega-project
322bb6f85278557c3748de51eee6471166c56de3
3bfed2fc7478aadb39138521aa53fa7f59a1695a
refs/heads/master
2021-08-28T12:47:07.829531
2021-08-08T06:02:07
2021-08-08T06:02:07
43,459,934
1
1
BSD-2-Clause
2021-08-08T06:02:07
2015-09-30T21:21:38
C
UTF-8
C++
false
false
1,315
h
Collection.h
#if !defined Already_Included_Collection #define Already_Included_Collection //#include <basic/enter_Iterator.h> //#include <basic/enter_Collection.h> namespace omega { template<class T> class Iterator; template<class T> class Any_Iterator; /* * protocol for any kind of collection */ template<class T> class Collection { public: Collection() {} virtual ~Collection() {} virtual Iterator<T> *new_iterator() = 0; virtual Any_Iterator<T> any_iterator() { return Any_Iterator<T>(new_iterator()); } virtual int size() const = 0; }; /* * protocol for collections whose elements are ordered * by the way they are entered into the collection, and * whose elements can be accessed by "index" * * note that the implementation need not be a linked list */ template<class T> class Sequence : public Collection<T> { public: Sequence() {} virtual ~Sequence() {} virtual const T &operator[](int) const = 0; virtual T &operator[](int) = 0; virtual int index(const T &) const = 0; // Y in X --> X[X.index(Y)] == Y }; #define instantiate_Collection(T) template class Collection<T>; \ instantiate_Any_Iterator(T) #define instantiate_Sequence(T) template class Sequence<T>; \ instantiate_Collection(T) } // end of namespace omega #endif
42f795b44f2e40822872d35c2a3103835b06a1d5
0d99b2cf7691f22af22666fb966281cc7c873806
/E-01/horario.cpp
28d4fc0a38b75dff9551d918ef7cc06008d05d73
[]
no_license
pibloo94/TADs
f6ff274573afb5e90cfe79a37bdfe5b38fa019ce
75411bdc2e4ad5a4f004a3480ec10bb04929663e
refs/heads/master
2020-04-26T04:47:49.553679
2019-06-24T16:20:34
2019-06-24T16:20:34
173,313,927
3
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
horario.cpp
#include "horario.h" #include <iostream> #include <iomanip> horario::horario(int hora, int min, int seg): hora(hora), min(min), seg(seg){ if (hora < 0 || hora >= 24 || min < 0 || min >= 60 || seg < 0 || seg >= 60) { throw std::domain_error("ERROR\n"); } }; horario::horario() {}; horario::~horario() {}; bool horario::operator<(horario const &other) { if (other.hora > hora) { return true; } else if (other.hora < hora) { return false; } else { if (other.min > min) { return true; } else if (other.min < min) { return false; } else { if (other.seg >= seg) { return true; } else { return false; } } } } void horario::print() { std::cout << std::setw(2) << std::setfill('0') << hora << ":" << std::setw(2) << std::setfill('0') << min << ":" << std::setw(2) << std::setfill('0') << seg << "\n"; }
cdfb0f4a008806cacd5447f8ecd1049bf3564168
85e5e67b0ddb32701b6aad5c3d2a428c768bb41c
/Engine/LineDefaultMaterial.cpp
459512053a129a20958d50287643a539b076f065
[]
no_license
lim-james/Allure
a6ebca6b2ca1c70bc2108f8ae710c2a88117657d
6d837a49254d181babf546d829fc871e468d66db
refs/heads/master
2021-07-18T04:31:08.130059
2020-08-21T03:30:54
2020-08-21T03:30:54
205,639,206
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
LineDefaultMaterial.cpp
#include "LineDefaultMaterial.h" Material::LineDefault::LineDefault() { shader = new Shader("Files/Shaders/line.vert", "Files/Shaders/standard2D.frag"); } void Material::LineDefault::SetAttributes() { }
5c96f7d812c3a187052a9496168822101daa64e0
8973dd51588517ac8755230820e97b8215cadc92
/cores/Cosa/api/Cosa/Wireless/Driver/VWI/Codec/Block4B5BCodec.cpp
c57c97adff7ffd192bbae51376f79b00b10494f5
[ "BSD-3-Clause" ]
permissive
UECIDE/UECIDE_data
3fa6b17113743de7bcb7d3cb8d430637efb494b6
96bf6b15910ec3794bd7c13e5274e5ac03379aa9
refs/heads/master
2016-09-06T17:38:44.223404
2014-02-15T00:48:46
2014-02-15T00:48:46
13,354,806
0
1
null
null
null
null
UTF-8
C++
false
false
2,015
cpp
Block4B5BCodec.cpp
/** * @file Cosa/Wireless/Driver/VWI/Codec/Block4B5BCodec.cpp * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Wireless/Driver/VWI/Codec/Block4B5BCodec.hh" /* * Calculating the start symbol JK (5-bits per symbol): * 0x18, 0x11 => 11000.10001 => 10001.11000 => 10.0011.1000 => 0x238 */ const uint8_t Block4B5BCodec::preamble[] __PROGMEM = { 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x18, 0x11 }; const uint8_t Block4B5BCodec::symbols[] __PROGMEM = { 0b11110, 0b01001, 0b10100, 0b10101, 0b01010, 0b01011, 0b01110, 0b01111, 0b10010, 0b10011, 0b10110, 0b10111, 0b11010, 0b11011, 0b11100, 0b11101 }; const uint8_t Block4B5BCodec::codes[] __PROGMEM = { 0xff, // 0: 0b00000 0xff, // 1: 0b00001 0xff, // 2: 0b00010 0xff, // 3: 0b00011 0xff, // 4: 0b00100 0xff, // 5: 0b00101 0xff, // 6: 0b00110 0xff, // 7: 0b00111 0xff, // 8: 0b01000 1, // 9: 0b01001 4, // 10: 0b01010 5, // 11: 0b01011 0xff, // 12: 0b01100 0xff, // 13: 0b01101 6, // 14: 0b01110 7, // 15: 0b01111 0xff, // 16: 0b10000 0xff, // 17: 0b10001 8, // 18: 0b10010 9, // 19: 0b10011 2, // 20: 0b10100 3, // 21: 0b10101 10, // 22: 0b10110 11, // 23: 0b10111 0xff, // 24: 0b11000 0xff, // 25: 0b11001 12, // 26: 0b11010 13, // 27: 0b11011 14, // 28: 0b11100 15, // 29: 0b11101 0, // 30: 0b11110 0xff // 31: 0b11111 };
f7104be9b6634870678ee25c104a92c94048bca8
5ff639eea1a30752a4edeb03cdf78261b08a0404
/Source/DCS/Components/EquipmentComponent.h
7a1cca474d790f94664eb42ec5a8f28bd0fbd71b
[]
no_license
ssapo/DCS
84a7b23503a4661926de51619b171f18537c2f89
36e61846bf1b03f6f9456b1e65a35bbcdcc4b1ed
refs/heads/master
2021-08-06T22:32:04.482197
2020-05-01T19:19:12
2020-05-01T19:19:12
213,244,840
3
1
null
2020-04-26T15:11:05
2019-10-06T21:13:42
C++
UTF-8
C++
false
false
4,903
h
EquipmentComponent.h
#pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Structs.h" #include "DelegateCombinations.h" #include "EquipmentComponent.generated.h" class UInventoryComponent; class AGameMode; class ADisplayedItem; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class DCS_API UEquipmentComponent : public UActorComponent { GENERATED_BODY() public: UEquipmentComponent(); virtual void InitializeComponent() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; void Initialize(); void Finalize(); FORCEINLINE TArray<FEquipmentSlots> GetEquipmentSlots() const { return EquipmentSlots; } FORCEINLINE bool IsInCombat() const { return bIsInCombat; } FORCEINLINE EItem GetSelectedMainHandType() const { return SelectedMainHandType; } FORCEINLINE ECombat GetCombatType() const { return CombatType; } const FStoredItem* GetActiveItem(EItem InType, int32 Index) const; const FStoredItem* GetItemInSlot(EItem InType, int32 SlotIndex, int32 ItemIndex) const; const FStoredItem* GetWeapon() const; int32 GetActiveItemIndex(EItem InType, int32 Index) const; ADisplayedItem* GetDisplayedItem(EItem InType, int32 Index) const; bool IsSlotHidden(EItem InType, int32 Index) const; bool IsEquippedItem(const FGuid& InItemID) const; bool IsActiveItem(const FGuid& InItemID) const; bool IsActiveItemIndex(EItem InType, int32 SlotIndex, int32 ItemIndex) const; bool IsShieldEquipped() const; bool IsTwoHandedWeaponEquipped() const; bool CanBlock() const; void ToggleCombat(); private: void OnGameLoaded(); void OnItemModified(const FStoredItem& InItem); void ActiveItemChanged(const FStoredItem& Old , const FStoredItem& New, EItem InType, int32 SlotIndex, int32 ItemIndex); void SetCombat(bool InValue); void SetSlotActiveIndex(EItem Type, int32 SlotIndex, int32 NewActiveIndex); void SetSlotHidden(EItem Type, int32 SlotIndex, bool bInHidden); void SetItemInSlot(EItem Type, int32 SlotIndex, int32 ItemIndex, const FStoredItem& InItem); void UpdateItemInSlot(EItem Type, int32 SlotIndex, int32 ItemIndex, const FStoredItem& InItem, EHandleSameItemMethod Method); void UpdateDisplayedItem(EItem InType, int32 SlotIndex); void AttachDisplayedItem(EItem InType, int32 SlotIndex); void UpdateCombatType(); void BuildEquipment(const TArray<FEquipmentSlots>& EquipmentSlots); TTuple<EItem, int32, int32> FindItem(const FStoredItem& InItem); int32 GetEquipmentSlotsIndex(EItem InType) const; bool IsSlotIndexValid(EItem InType, int32 Index) const; bool IsItemIndexValid(EItem InType, int32 Index, int32 ItemIndex) const; bool IsValidItem(const FStoredItem& Item) const; bool IsValidItem(const FStoredItem* Item) const; bool IsItemTwoHanded(const FStoredItem& NewItem) const; bool IsRangeTypeCurrentMainHand() const; bool IsRangeTypeCurrentCombat() const; EItem GetItemType(const FStoredItem& InItem) const; // start declare events. public: DECLARE_EVENT_FiveParams(UEquipmentComponent, FOnItemInSlotChanged, const FStoredItem&, const FStoredItem&, EItem, int32, int32); FOnItemInSlotChanged& OnInSlotChanged() { return ItemInSlotChangedEvent; } DECLARE_EVENT_FiveParams(UEquipmentComponent, FOnActiveItemChanged, const FStoredItem&, const FStoredItem&, EItem, int32, int32); FOnActiveItemChanged& OnActiveItemChanged() { return ActiveItemChangedEvent; } DECLARE_EVENT_FourParams(UEquipmentComponent, FOnSlotHiddenChanged, EItem, int32, const FStoredItem&, bool); FOnSlotHiddenChanged& OnSlotHiddenChanged() { return SlotHiddenChangedEvent; } DECLARE_EVENT_OneParam(UEquipmentComponent, FOnCombatChanged, bool); FOnCombatChanged& OnCombatChanged() { return CombatStatusChangedEnvet; } DECLARE_EVENT_OneParam(UEquipmentComponent, FOnWeaponTypeChanged, EWeapon); FOnWeaponTypeChanged& OnWeaponTypeChanged() { return WeaponTypeChangedEvent; } DECLARE_EVENT_OneParam(UEquipmentComponent, FOnMainHandTypeChanged, EItem); FOnMainHandTypeChanged& OnMainHandTypeChanged() { return MainHandTypeChangedEvent; } DECLARE_EVENT_OneParam(UEquipmentComponent, FOnCombatTypeChanged, ECombat); FOnCombatTypeChanged& OnCombatTypeChanged() { return CombatTypeChangedEvent; } private: FOnWeaponTypeChanged WeaponTypeChangedEvent; FOnMainHandTypeChanged MainHandTypeChangedEvent; FOnSlotHiddenChanged SlotHiddenChangedEvent; FOnItemInSlotChanged ItemInSlotChangedEvent; FOnActiveItemChanged ActiveItemChangedEvent; FOnCombatChanged CombatStatusChangedEnvet; FOnCombatTypeChanged CombatTypeChangedEvent; // end declare events. private: TWeakObjectPtr<UInventoryComponent> WP_Inventory; UPROPERTY(EditAnywhere) TArray<FEquipmentSlots> EquipmentSlots; TArray<EItem> MainHandTypes; TArray<FGuid> EquippedItems; TArray<FGuid> ActiveItems; TMap<EItem, FDisplayedItems> DisplayedItems; ECombat CombatType; EWeapon WeaponType; EItem SelectedMainHandType; bool bIsInCombat; };
5b4d4a73edcd1b114385c1d5c24687cc3e6cb5ee
d58f7add8e1c6cbaad45e71b08720ae3cdab047d
/1025 - The Specials Menu.cpp
2b07e38803b05e8e1dd2388eeaaa8c670a276643
[]
no_license
habibrahmanbd/Light-Online-Judge
b1bb1fe53e85a1d50a0559618eff440f3cdd1e4b
a9e8adc7217ca22094cc73bc42c5d4eb279c653f
refs/heads/master
2021-06-01T06:29:24.453721
2016-07-28T11:02:52
2016-07-28T11:02:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
cpp
1025 - The Specials Menu.cpp
using namespace std; #include<bits/stdc++.h> #define db double #define ll long long #define ull unsigned long long #define vi vector<int> #define vl vector<long> #define vll vector<ll> #define pi pair<int,int> #define pl pair<long,long> #define pll pair<ll,ll> #define pb push_back #define mp make_pair #define pf printf #define sf scanf #define mii map<int,int> #define mll map<ll,ll> #define II ({int a; sf("%d",&a); a;}) #define IL ({long a; sf("%ld",&a); a;}) #define ILL ({ll a; sf("%lld",&a); a;}) #define ID ({db a; sf("%lf",&a); a;}) #define IF ({float a; sf("%f",&a); a;}) #define IC ({char a; sf("%c",&a); a;}) #define FRI(a,b,c) for(int i=a; i<=b; i+=c) #define FRL(a,b,c) for(long i=a; i<=b; i+=c) #define FRLL(a,b,c) for(ll i=a; i<=b; i+=c) #define all(V) V.begin(),V.end() #define in freopen("in.txt","r",stdin) #define out freopen("out.txt","w",stdout) #define PI 2*acos(0.0) #define mod 1000000007 #define INF LLONG_MAX #define endl '\n' template <class T> inline T bigmod(T p,T e,T M) { ll ret = 1; for(; e > 0; e >>= 1) { if(e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a,T b) { if(b==0)return a; return gcd(b,a%b); } template <class T> inline T modinverse(T a,T M) { return bigmod(a,M-2,M); } //------------------------------------------------------ ll dp[60][60]; bool visit[60][60]; string w; ll solve(int i, int j) { if(j<i) // i and j cross themselves. return 0; if(j==i) //pointing the same character of the string return 1; if(!visit[i][j]) { if(w[i]==w[j]) dp[i][j]=(1+solve(i+1,j)+solve(i,j-1)); // this expression basically is- 1 + solve(i+1,j-1) + ( solve(i+1,j) + solve(i, j-1) - solve(i+1, j-1)) else { dp[i][j]=solve(i+1,j)+solve(i,j-1)-solve(i+1,j-1); // inclusion and exclusion is done here for the reason of over counting of solve(i+1, j-1) } } visit[i][j]=1; return dp[i][j]; } // the solution technique is given in http://codeforces.com/blog/entry/15372 int main() { int t=II; for(int cs=1; cs<=t; cs++) { cin>>w; memset(dp, -1, sizeof dp); memset(visit, 0, sizeof visit); pf("Case %d: %lld\n", cs, solve(0,w.length()-1)); } return 0; }
7065ca980d96bb14ba89c6135a5d57b124db3957
561cab2985b30a3b29552d3da6beac470644d8b6
/DisplayApp/audio/RtAudioMicrophoneWrapper.h
27f792f818cbc523310f1af6085063850603b6b9
[]
no_license
AlexWuDDD/Raspberry
aa1f88ec26e5c25b67825d6ec349c9f5d3fea4b1
2beab1cd082f7418fb61dbf2afbdd2d72dbc5f91
refs/heads/master
2020-06-20T15:21:58.118831
2019-09-24T01:39:19
2019-09-24T01:39:19
197,162,419
0
0
null
null
null
null
UTF-8
C++
false
false
2,438
h
RtAudioMicrophoneWrapper.h
#ifndef __RTAUDIOMICROPHONEWRAPER_H__ #define __RTAUDIOMICROPHONEWRAPER_H__ #include <assert.h> #include <iostream> #include <memory> #include "RtAudio.h" #include <boost/lockfree/spsc_queue.hpp> typedef signed short MICROPHONE_MY_TYPE; const unsigned int MICROPHONE_BUFF_FRAMES = 1024; // for WAV 16bit stream, this number should be 256, for AAC stream should be 1024 const int MICROPHONE_CHANNELS = 2; const int MICROPHONE_AUDIOBUFFERLEN = MICROPHONE_BUFF_FRAMES * MICROPHONE_CHANNELS; struct MicrophoneAudioData { MICROPHONE_MY_TYPE data[MICROPHONE_AUDIOBUFFERLEN]; double stream_time; }; class RtAudioMicrophoneWrapper { public: typedef boost::lockfree::spsc_queue<MicrophoneAudioData, boost::lockfree::capacity<16>> lockfreequeue_type; /// \brief Constructor of RtAudioMicrophoneWrapper /// \return no return RtAudioMicrophoneWrapper(); /// \brief Constructor of RtAudioMicrophoneWrapper /// \param device_id microphone device id /// \param num_channel sound channels /// \param sample_rate sound sample per seconds 44100 etc. /// \return no return RtAudioMicrophoneWrapper(int device_id, int num_channel, int sample_rate); /// \brief Destructor of RtAudioMicrophoneWrapper /// \return no return ~RtAudioMicrophoneWrapper(); /// \brief Open microphone device /// \param device_id device id /// \return true for success, false for fail bool open(const int divice_id); /// \brief list available devices /// \return no return void list_devices(); /// \brief grab a sound sample from device /// \return true for success, false for fail bool grab(); /// \brief retrieve a sound sample to audio data /// \param audio_data audio data content /// \return true for success, false for fail bool retrieve(MicrophoneAudioData &audio_data); /// \brief generate wav header for writing audio data to file /// \param data audio audio data /// \param len audio data length /// \return no return void generate_wav_header(char *data, const int len); private: void init(); RtAudioMicrophoneWrapper(const RtAudioMicrophoneWrapper&) {}; RtAudioMicrophoneWrapper& operator=(const RtAudioMicrophoneWrapper&) {}; std::shared_ptr<RtAudio> rtaudio_; // audio data stuff lockfreequeue_type v_audiodata_; MicrophoneAudioData audio_data_; // audio information stuff int device_id_; int num_channels_; int sample_rate_; unsigned int buffer_frames_; bool is_grabed_; }; #endif // !__RTAUDIOWRAPER_H__
15ddb29666f42f7d5b2483baa665df14608893cb
61deafb2dcf4820d46f2500d12497a89ff66e445
/2143.cpp
3aefe0d2586b75ab70e0db0e6bdaca089c4c18b8
[]
no_license
Otrebus/timus
3495f314587beade3de67890e65b6f72d53b3954
3a1dca43dc61b27c8f903a522743afeb69d38df2
refs/heads/master
2023-04-08T16:54:07.973863
2023-04-06T19:59:07
2023-04-06T19:59:07
38,758,841
72
40
null
null
null
null
UTF-8
C++
false
false
2,592
cpp
2143.cpp
/* 2143. Victoria! - http://acm.timus.ru/problem.aspx?num=2143 * * Strategy: * Dynamic programming over B[n][m] which represents the greatest number of passengers we can seat * in the plane from row n and forward with row n configured according to bitmask m. We update * B[n][m] for each m by iterating over B[n-1][m2] for all m2 that fit according to the given rules. * * Performance: * O(n), runs the tests in 0.031s using 228KB memory. */ #include <stdio.h> int A[102]; // Existing passengers int B[102][1<<6]; // DP array int P[102][1<<6]; // Previous value on best path int n, k; bool set(int i, int m) { // Checks if bit i of mask m is set return i >= 0 && i <= 5 && (m & (1<<i)); } bool test(int i, int m) { // Returns true if seat i can't be filled if the front row is bitmask m return set(i-1, m) && i != 3 || set(i, m) || set(i+1, m) && i != 2; } int count(int m) { // Counts the number of bits in m int ret = 0; for(int i = 0; i < 6; i++) ret += !!(m & (1 << i)); return ret; } bool check(int m, int m2, int i) { // Checks that configuration m is valid with m2 above it if(m & A[i]) // Can't sit on occupied seats return false; for(int s = 0; s < 5; s++) // Can't have two seats next to each other except for the aisle if(s != 2 && (m & (3<<s)) == (3<<s)) return false; for(int j = 0; j < 6; j++) // Can't sit close to someone in the front if((m & (1 << j)) && test(j, m2)) return false; return true; } int main() { scanf("%d %d", &n, &k); for(int i = 1; i <= n; i++) { // Read each row of the input for(int j = 0; j < 6; j++) { char c = 0; while(c != '.' && c != '*') scanf("%c", &c); A[i] |= ((c == '*') << j); } } for(int i = 1; i <= n+1; i++) // Do the dp for(int m2 = 0; m2 < (1<<6); m2++) // For every config in the front for(int m = 0; m < (1<<6); m++) // For every config we try if(check(m, m2, i) && B[i][m] < count(m) + B[i-1][m2]) // If valid and better P[i][m] = m2, B[i][m] = B[i-1][m2] + count(m); if(B[n+1][0] < k) // Check if the last virtual n+1 row with 0 passengers can have k in front return printf("PORAZHENIE"), 0; printf("POBEDA\n"); // Otherwise, use the P array to rewind the actual configuration int m = 0, r = 0; for(int i = n+1; i >= 1; m = P[i--][m]) for(int j = 0; j < 6; j++) if((m & (1 << j)) && r < k) printf("%d%c\n", i, 'A'+j), r++; }
2e2d64cd40db2791a47e757b34af14ad896a78d1
577efc77810f5da7e525f03ad36c056fdeb30148
/src/commandbuffer.cpp
bbeff5c49a52cbabbb62f5683049db6d9984be61
[]
no_license
Elzair/simple-renderer
95be5a6149cb48de3fa73aebdfed2bcd60b9ff83
0bcef34b7d32e91b3da468f4514f7d59443714df
refs/heads/master
2020-06-22T07:31:26.396080
2017-01-01T23:47:53
2017-01-01T23:47:53
74,597,444
0
0
null
null
null
null
UTF-8
C++
false
false
18,735
cpp
commandbuffer.cpp
#include "common.hpp" #include "commandbuffer.hpp" void CommandPool::init( Device* device, VkQueue queue, uint32_t queueIdx ) { this->device = device; this->queue = queue; VkCommandPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolCreateInfo.flags = 0; poolCreateInfo.queueFamilyIndex = this->device->graphicsQueueIdx; VK_CHECK_RESULT( this->device->createCommandPool( &poolCreateInfo, &this->id ) ); } void CommandPool::deinit() { this->device->destroyCommandPool( this->id ); } void CommandPool::reset() { this->device->resetCommandPool( this->id, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT ); } void CommandPool::allocateCommandBuffer( VkCommandBuffer* cmdbuf ) { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = this->id; allocInfo.commandBufferCount = 1; this->device->allocateCommandBuffers( &allocInfo, cmdbuf ); } void CommandPool::freeCommandBuffer( VkCommandBuffer* commandBuffer ) { this->device->freeCommandBuffers( this->id, 1, commandBuffer ); } void CommandBuffer::init( Device* device, VkQueue queue, CommandPool* pool ) { this->device = device; this->queue = queue; this->pool = pool; this->pool->allocateCommandBuffer( &this->id ); } void CommandBuffer::deinit() { this->id = VK_NULL_HANDLE; this->pool = nullptr; this->queue = VK_NULL_HANDLE; this->device = nullptr; this->began = false; this->renderPass = false; this->ended = false; } // Basic Commands void CommandBuffer::begin( CommandBufferUsage usage ) { assert( !this->began ); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; switch( usage ) { case CommandBufferUsage::ONE_TIME: beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; break; case CommandBufferUsage::SIMULTANEOUS_USE: beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; break; } vkBeginCommandBuffer( this->id, &beginInfo ); this->began = true; } void CommandBuffer::end() { assert( this->began && !this->ended ); VK_CHECK_RESULT( vkEndCommandBuffer( this->id ) ); this->ended = true; } // RenderPass Commands void CommandBuffer::beginRenderPass( RenderPass& renderPass, VkFramebuffer framebuffer, VkRect2D renderArea, std::vector<VkClearValue>& clearValues, VkSubpassContents contents ) { assert( this->began && !this->ended && !this->renderPass ); VkRenderPassBeginInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; createInfo.renderPass = renderPass.renderPass; createInfo.framebuffer = framebuffer; createInfo.renderArea = renderArea; createInfo.clearValueCount = clearValues.size(); createInfo.pClearValues = clearValues.data(); vkCmdBeginRenderPass( this->id, &createInfo, contents ); this->renderPass = true; } void CommandBuffer::nextSubpass( VkSubpassContents contents ) { assert( this->began && !this->ended && this->renderPass ); vkCmdNextSubpass( this->id, contents ); } void CommandBuffer::endRenderPass() { assert( this->began && !this->ended && this->renderPass ); vkCmdEndRenderPass( this->id ); this->renderPass = false; } void CommandBuffer::executeCommands( uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers ) { assert( this->began ); vkCmdExecuteCommands( this->id, commandBufferCount, pCommandBuffers ); } // State Commands void CommandBuffer::bindPipeline( VkPipelineBindPoint pipelineBindPoint, GraphicsPipeline& pipeline ) { assert( this->began ); vkCmdBindPipeline( this->id, pipelineBindPoint, pipeline.pipeline ); } void CommandBuffer::bindDescriptorSets( VkPipelineBindPoint pipelineBindPoint, GraphicsPipeline& pipeline, PipelineLayout& layout, uint32_t firstSet, //uint32_t descriptorSetCount, //const VkDescriptorSet* pDescriptorSets, const std::vector<DescriptorSet>& descriptorSets, uint32_t dynamicOffsetCount, const uint32_t* pDynamicOffsets ) { assert( this->began ); std::vector<VkDescriptorSet> internalDescSets; internalDescSets.reserve( descriptorSets.size() ); for ( auto& dset : descriptorSets ) { internalDescSets.emplace_back( dset.id ); } vkCmdBindDescriptorSets( this->id, pipelineBindPoint, layout.id, firstSet, // descriptorSetCount, // pDescriptorSets, internalDescSets.size(), internalDescSets.data(), dynamicOffsetCount, pDynamicOffsets ); } void CommandBuffer::bindVertexBuffers( uint32_t firstBinding, std::vector<Buffer>& buffers, const VkDeviceSize* pOffsets ) { assert( this->began ); std::vector<VkBuffer> vkbuffers; vkbuffers.resize( buffers.size() ); for ( auto i = 0; i < vkbuffers.size(); i++ ) { //vkbuffers.emplace_back( buf.id ); vkbuffers[ i ] = buffers[ i ].id; } vkCmdBindVertexBuffers( this->id, firstBinding, vkbuffers.size(), vkbuffers.data(), pOffsets ); } void CommandBuffer::bindVertexBuffer( uint32_t binding, Buffer& buffer, VkDeviceSize offset ) { assert( this->began ); vkCmdBindVertexBuffers( this->id, binding, 1, &buffer.id, &offset ); } void CommandBuffer::bindIndexBuffer( Buffer& buffer, VkDeviceSize offset, VkIndexType indexType ) { assert( this->began ); vkCmdBindIndexBuffer( this->id, buffer.id, offset, indexType ); } // Clear Commands void CommandBuffer::clearColorImage( VkImage image, VkImageLayout imageLayout, const VkClearColorValue* pColor, uint32_t rangeCount, const VkImageSubresourceRange* pRanges ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdClearColorImage( this->id, image, imageLayout, pColor, rangeCount, pRanges ); } void CommandBuffer::clearDepthStencilImage( VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange* pRanges ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdClearDepthStencilImage( this->id, image, imageLayout, pDepthStencil, rangeCount, pRanges ); } void CommandBuffer::clearAttachments( uint32_t attachmentCount, const VkClearAttachment* pAttachments, uint32_t rectCount, const VkClearRect* pRects ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdClearAttachments( this->id, attachmentCount, pAttachments, rectCount, pRects ); } void CommandBuffer::fillBuffer( VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdFillBuffer( this->id, dstBuffer, dstOffset, size, data ); } void CommandBuffer::updateBuffer( VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const uint32_t* pData ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdUpdateBuffer( this->id, dstBuffer, dstOffset, dataSize, pData ); } // Copy Commands void CommandBuffer::copyBuffer( VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy* pRegions ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdCopyBuffer( this->id, srcBuffer, dstBuffer, regionCount, pRegions ); } void CommandBuffer::copyImage( VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy* pRegions ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdCopyImage( this->id, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions ); } void CommandBuffer::copyBufferToImage( VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy* pRegions ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdCopyBufferToImage( this->id, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions ); } void CommandBuffer::copyImageToBuffer( VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdCopyImageToBuffer( this->id, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions ); } void CommandBuffer::blitImage( VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit* pRegions, VkFilter filter ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdBlitImage( this->id, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter ); } void CommandBuffer::resolveImage( VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve* pRegions ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdResolveImage( this->id, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions ); } // Drawing Commands void CommandBuffer::draw( uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance ) { assert( this->began && !this->ended && this->renderPass ); vkCmdDraw( this->id, vertexCount, instanceCount, firstVertex, firstInstance ); } void CommandBuffer::drawIndexed( uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance ) { assert( this->began && !this->ended && this->renderPass ); vkCmdDrawIndexed( this->id, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance ); } void CommandBuffer::drawIndirect( VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride ) { assert( this->began && !this->ended && this->renderPass ); vkCmdDrawIndirect( this->id, buffer, offset, drawCount, stride ); } void CommandBuffer::drawIndexedIndirect( VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride ) { assert( this->began && !this->ended && this->renderPass ); vkCmdDrawIndexedIndirect( this->id, buffer, offset, drawCount, stride ); } // Fragment Operations void CommandBuffer::setScissor( uint32_t firstScissor, uint32_t scissorCount, const VkRect2D* pScissors ) { assert( this->began ); vkCmdSetScissor( this->id, firstScissor, scissorCount, pScissors ); } void CommandBuffer::setDepthBounds( float minDepthBounds, float maxDepthBounds ) { assert( this->began ); vkCmdSetDepthBounds( this->id, minDepthBounds, maxDepthBounds ); } void CommandBuffer::setStencilCompareMask( VkStencilFaceFlags faceMask, uint32_t compareMask ) { assert( this->began ); vkCmdSetStencilCompareMask( this->id, faceMask, compareMask ); } void CommandBuffer::setStencilWriteMask( VkStencilFaceFlags faceMask, uint32_t writeMask ) { assert( this->began ); vkCmdSetStencilWriteMask( this->id, faceMask, writeMask ); } void CommandBuffer::setStencilReference( VkStencilFaceFlags faceMask, uint32_t reference ) { assert( this->began ); vkCmdSetStencilReference( this->id, faceMask, reference ); } // Viewport Commands void CommandBuffer::setViewport( uint32_t firstViewport, uint32_t viewportCount, const VkViewport* pViewports ) { assert( this->began ); vkCmdSetViewport( this->id, firstViewport, viewportCount, pViewports ); } // Rasterization Commands void CommandBuffer::setLineWidth( float lineWidth ) { assert( this->began ); vkCmdSetLineWidth( this->id, lineWidth ); } void CommandBuffer::setDepthBias( float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor ) { assert( this->began ); vkCmdSetDepthBias( this->id, depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor ); } // Framebuffer Commands void CommandBuffer::setBlendConstants( const float blendConstants[ 4 ] ) { assert( this->began ); vkCmdSetBlendConstants( this->id, blendConstants ); } // Dispatch Commands void CommandBuffer::dispatch( uint32_t x, uint32_t y, uint32_t z ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdDispatch( this->id, x, y, z ); } void CommandBuffer::dispatchIndirect( VkBuffer buffer, VkDeviceSize offset ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdDispatchIndirect( this->id, buffer, offset ); } // Synchronization Commands void CommandBuffer::pipelineBarrier( VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers ) { assert( this->began && !this->ended && !this->renderPass ); vkCmdPipelineBarrier( this->id, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers ); } // PushConstant Commands void CommandBuffer::pushConstants( VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void* pValues ) { assert( this->began ); vkCmdPushConstants( this->id, layout, stageFlags, offset, size, pValues ); } //TODO: Remove when other cmdbuf methods have been added VkCommandBuffer* CommandBuffer::getHandle() { return &this->id; }
311a9db2fa4586a8a6a30d9bacad4adc02186c11
4bccc0bc10cc1f9dabd53caeb34f658af0954583
/AsteroidsServer/Parameter.h
634a19b5f4f9e07041243b4c14b3232fd5cf0ef0
[]
no_license
LikeTheBossOne/Asteroids-Game
5fc698b2935dc350af95bd1be26078ce32dfd861
d2a66ee3f9f24c7af4cdbabce6947be8586417c1
refs/heads/master
2023-03-17T01:24:27.045632
2021-03-09T20:33:16
2021-03-09T20:33:16
346,126,643
0
0
null
null
null
null
UTF-8
C++
false
false
211
h
Parameter.h
#pragma once #include <string> #include "JumpComponent.h" #include "ParameterType.h" class Parameter { public: Parameter() = default; virtual ~Parameter() = default; virtual ParameterType getType() = 0; };
cd576f30006f6c640c258133214268352479e04a
5a1ab89fd273eb62dfcd4c79e8ce604fd98f9af8
/include/Renderer/Texture.h
68c050aee7dd29fe7d8f67c183945d358b523de4
[]
no_license
I-Hudson/Engine-Framework
934642433a366e1fe191506d91cbbbbcb333eaf8
6affaa66c7b4290dc818b64a40c4a2d3e47e466f
refs/heads/master
2022-04-16T12:08:30.201932
2020-02-21T17:20:41
2020-02-21T17:20:41
207,166,735
0
0
null
2020-02-15T14:57:25
2019-09-08T20:02:41
C++
UTF-8
C++
false
false
2,484
h
Texture.h
#pragma once #include <string> #include <unordered_map> #include <memory> #include "Log.h" #include "stbi/stb_image.h" namespace Framework { namespace Renderer { enum TextureType { DIFFUSE, SPECULAR, AMBIENT, EMISSIVE, HEIGHT, NORMALS, SHININESS, OPACITY, DISPLACEMENT, LIGHTMAP, REFLECTION, UNKNOWN }; class Texture { public: virtual ~Texture() = default; virtual void Bind() = 0; virtual void Unbind() = 0; virtual void Load(const std::string& a_filePath, const TextureType& type) = 0; virtual void Release() = 0; virtual const std::string& GetName() = 0; TextureType GetType() const { return m_type; } uint32_t GetId() const { return m_ID; } std::string TextureTypeToString(const TextureType& type = TextureType::UNKNOWN) { TextureType localType = type; if (type == TextureType::UNKNOWN) { localType = m_type; } switch (localType) { case TextureType::DIFFUSE: return std::string("diffuse"); case TextureType::SPECULAR: return std::string("specular"); case TextureType::AMBIENT: return std::string("ambient"); case TextureType::EMISSIVE: return std::string("emissive"); case TextureType::HEIGHT: return std::string("height"); case TextureType::NORMALS: return std::string("normals"); case TextureType::SHININESS: return std::string("shininess"); case TextureType::OPACITY: return std::string("opacity"); case TextureType::DISPLACEMENT: return std::string("displacement"); case TextureType::LIGHTMAP: return std::string("lightmap"); case TextureType::REFLECTION: return std::string("reflection"); default: break; } return std::string("Unknown"); } static std::shared_ptr<Texture> Create(const std::string& a_name, const std::string& a_filePath, const TextureType& type); protected: uint32_t m_ID; TextureType m_type; }; class TextureLibrary { public: void Add(const std::string& a_name, const std::shared_ptr<Texture>& a_texture); std::shared_ptr<Texture> GetTexture(const std::string& a_name); std::shared_ptr<Texture> Load(const std::string a_name, const std::string& a_filePath, const TextureType& type); void Release(const std::string a_name); void ReleaseAll(); bool Exists(const std::string& a_name); private: std::unordered_map<std::string, std::shared_ptr<Texture>> m_textures; }; } }
c31aa73e740b036fe777bb7a9b7ea04b3d001dd0
619b04b1dd36e4133fb2e84834d2cbfe3cc33970
/tcp-socket-state.cc
7bdcecae1a0b5f0ae173ba21902af665fac0b013
[]
no_license
Niwedita17/Implementation-of-ICTCP-in-ns3
fbfadf052065c03c199596c20095a063da256b82
eb021b42c36ccfc0e37181d9d2edd4f5a71cb007
refs/heads/master
2020-08-09T17:35:50.784217
2019-11-22T04:00:03
2019-11-22T04:00:03
214,134,459
0
1
null
null
null
null
UTF-8
C++
false
false
5,127
cc
tcp-socket-state.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2018 Natale Patriciello <natale.patriciello@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tcp-socket-state.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpSocketState); TypeId TcpSocketState::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpSocketState") .SetParent<Object> () .SetGroupName ("Internet") .AddConstructor <TcpSocketState> () .AddAttribute ("EnablePacing", "Enable Pacing", BooleanValue (false), MakeBooleanAccessor (&TcpSocketState::m_pacing), MakeBooleanChecker ()) .AddAttribute ("MaxPacingRate", "Set Max Pacing Rate", DataRateValue (DataRate ("4Gb/s")), MakeDataRateAccessor (&TcpSocketState::m_maxPacingRate), MakeDataRateChecker ()) .AddTraceSource ("CongestionWindow", "The TCP connection's congestion window", MakeTraceSourceAccessor (&TcpSocketState::m_cWnd), "ns3::TracedValueCallback::Uint32") .AddTraceSource ("CongestionWindowInflated", "The TCP connection's inflated congestion window", MakeTraceSourceAccessor (&TcpSocketState::m_cWndInfl), "ns3::TracedValueCallback::Uint32") .AddTraceSource ("SlowStartThreshold", "TCP slow start threshold (bytes)", MakeTraceSourceAccessor (&TcpSocketState::m_ssThresh), "ns3::TracedValueCallback::Uint32") .AddTraceSource ("CongState", "TCP Congestion machine state", MakeTraceSourceAccessor (&TcpSocketState::m_congState), "ns3::TracedValueCallback::TcpCongState") .AddTraceSource ("EcnState", "Trace ECN state change of socket", MakeTraceSourceAccessor (&TcpSocketState::m_ecnState), "ns3::TracedValueCallback::EcnState") .AddTraceSource ("HighestSequence", "Highest sequence number received from peer", MakeTraceSourceAccessor (&TcpSocketState::m_highTxMark), "ns3::TracedValueCallback::SequenceNumber32") .AddTraceSource ("NextTxSequence", "Next sequence number to send (SND.NXT)", MakeTraceSourceAccessor (&TcpSocketState::m_nextTxSequence), "ns3::TracedValueCallback::SequenceNumber32") .AddTraceSource ("BytesInFlight", "The TCP connection's congestion window", MakeTraceSourceAccessor (&TcpSocketState::m_bytesInFlight), "ns3::TracedValueCallback::Uint32") .AddTraceSource ("RTT", "Last RTT sample", MakeTraceSourceAccessor (&TcpSocketState::m_lastRtt), "ns3::TracedValueCallback::Time") // My code .AddTraceSource("ReceiveWindowSize", "The TCP connection's receive Window Size", MakeTraceSourceAccessor(&TcpSocketState::m_rWnd), "ns3::TracedValue::Uint32Callback") ; return tid; } TcpSocketState::TcpSocketState (const TcpSocketState &other) : Object (other), m_cWnd (other.m_cWnd), m_ssThresh (other.m_ssThresh), m_initialCWnd (other.m_initialCWnd), m_initialSsThresh (other.m_initialSsThresh), m_segmentSize (other.m_segmentSize), m_lastAckedSeq (other.m_lastAckedSeq), m_congState (other.m_congState), m_ecnState (other.m_ecnState), m_highTxMark (other.m_highTxMark), m_nextTxSequence (other.m_nextTxSequence), m_rcvTimestampValue (other.m_rcvTimestampValue), m_rcvTimestampEchoReply (other.m_rcvTimestampEchoReply), m_pacing (other.m_pacing), m_maxPacingRate (other.m_maxPacingRate), m_currentPacingRate (other.m_currentPacingRate), m_minRtt (other.m_minRtt), m_bytesInFlight (other.m_bytesInFlight), m_lastRtt (other.m_lastRtt), // My code m_rWnd(other.m_rWnd) { } const char* const TcpSocketState::TcpCongStateName[TcpSocketState::CA_LAST_STATE] = { "CA_OPEN", "CA_DISORDER", "CA_CWR", "CA_RECOVERY", "CA_LOSS" }; const char* const TcpSocketState::EcnStateName[TcpSocketState::ECN_CWR_SENT + 1] = { "ECN_DISABLED", "ECN_IDLE", "ECN_CE_RCVD", "ECN_SENDING_ECE", "ECN_ECE_RCVD", "ECN_CWR_SENT" }; } //namespace ns3
434dc91aeac7c6acb2364862f3b69cd13c7b1e4e
126e18d87dcd274477dfea3c8c81ee58c3f7517b
/src/zoj2481.cpp
31e8452b06730bc35bc92d0708253e8df611fb80
[]
no_license
hzqtc/zoj-solutions
260014b9ac8a5acf46ef118d210d8486089adc7f
76efc95fb0c4d5a6e62f62c5d07e61cc9fdc5109
refs/heads/master
2021-01-18T14:58:00.753417
2012-06-26T04:07:07
2012-06-26T04:07:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
zoj2481.cpp
#include <iostream> #include <map> #include <cstdlib> using namespace std; int cmp(const void* a,const void* b); int main() { int seqlen; const int MAX = 110; int t; int num[MAX]; while(cin >> seqlen , seqlen > 0) { map<int,int> seq; int numcount = 0; for(int i = 0;i<seqlen;i++) { cin >> t; seq[t]++; if(seq[t] == 1) num[numcount++] = t; } qsort(num,numcount,sizeof(int),cmp); cout << num[0]; for(int i = 1;i<numcount;i++) cout << ' ' << num[i]; cout << endl; } return 0; } int cmp(const void* a,const void* b) { return *(int*)a - *(int*)b; }
2b0c3576e5687b7784bdab52e7279089532346cd
f879434ededbe74c92b19cdc0cc0294c3be27f0f
/src/Vulkan-Texture/cube.cpp
ffe2c0e2e324665324f8cb311bf6b9675e637add
[]
no_license
byhj/byhj-Render
7bd0cea526286624f609fff15b07b79f9f09aadf
5ca2746eabc952c8cff8e552d429cda880460db0
refs/heads/master
2021-01-21T04:42:10.246612
2016-07-02T06:23:00
2016-07-02T06:23:00
49,644,368
2
2
null
null
null
null
UTF-8
C++
false
false
22,413
cpp
cube.cpp
#include "Cube.h" namespace byhj { void Cube::init(VkDevice device) { m_timer.reset(); m_timer.start(); m_device = device; m_triangleShader.init(device); init_vertex(); init_ubo(); init_texture(); init_descriptorSetLayout(); init_descriptorPool(); init_descriptorSet(); } void Cube::update() { m_timer.count(); update_ubo(); } void Cube::render() { } void Cube::shutdown() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(m_device, m_pipeline, nullptr); vkDestroyPipelineLayout(m_device, m_pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(m_device, m_descriptorSetLayout, nullptr); vkDestroyBuffer(m_device, m_vertices.buffer, nullptr); vkFreeMemory(m_device, m_vertices.memory, nullptr); vkDestroyBuffer(m_device, m_indices.buffer, nullptr); vkFreeMemory(m_device, m_indices.memory, nullptr); vkDestroyBuffer(m_device, m_uniform.buffer, nullptr); vkFreeMemory(m_device, m_uniform.memory, nullptr); } void Cube::setupCmd(const VkCommandBuffer drawCmdBuffer) { //Bing desciptor sets describing shader binding points vkCmdBindDescriptorSets(drawCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, &m_descriptorSet, 0, NULL); //Bind the rendering pipeline (including the shaders) vkCmdBindPipeline(drawCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); //Bind Cube vertices VkDeviceSize offsets[1] ={ 0 }; vkCmdBindVertexBuffers(drawCmdBuffer, VERTEX_BUFFER_BIND_ID, 1, &m_vertices.buffer, offsets); //Bind Cube indices vkCmdBindIndexBuffer(drawCmdBuffer, m_indices.buffer, 0, VK_INDEX_TYPE_UINT32); //Draw indexed Cube //vkCmdDraw(drawCmdBuffer, m_indices.count, 1, 0, 0); vkCmdDrawIndexed(drawCmdBuffer, m_indices.count, 1, 0, 0, 0); } //Setups vertex and index buffers for an indexed Cube //uploads them to the vram and sets binding points and attribute //descriptions to match locations inside the shaders static const glm::vec3 vd[] ={ glm::vec3(-1.0f,-1.0f,-1.0f), // -X side glm::vec3(-1.0f,-1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f,-1.0f), glm::vec3(-1.0f,-1.0f,-1.0f), glm::vec3(-1.0f,-1.0f,-1.0f), // -Z side glm::vec3(1.0f, 1.0f,-1.0f), glm::vec3(1.0f,-1.0f,-1.0f), glm::vec3(-1.0f,-1.0f,-1.0f), glm::vec3(-1.0f, 1.0f,-1.0f), glm::vec3(1.0f, 1.0f,-1.0f), glm::vec3(-1.0f,-1.0f,-1.0f), // -Y side glm::vec3(1.0f,-1.0f,-1.0f), glm::vec3(1.0f,-1.0f, 1.0f), glm::vec3(-1.0f,-1.0f,-1.0f), glm::vec3(1.0f,-1.0f, 1.0f), glm::vec3(-1.0f,-1.0f, 1.0f), glm::vec3(-1.0f, 1.0f,-1.0f), // +Y side glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f,-1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f,-1.0f), glm::vec3(1.0f, 1.0f,-1.0f), // +X side glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f,-1.0f, 1.0f), glm::vec3(1.0f,-1.0f, 1.0f), glm::vec3(1.0f,-1.0f,-1.0f), glm::vec3(1.0f, 1.0f,-1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), // +Z side glm::vec3(-1.0f,-1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(-1.0f,-1.0f, 1.0f), glm::vec3(1.0f,-1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), }; static const glm::vec2 tb[] ={ glm::vec2(0.0f, 0.0f), // -X side glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f), // -Z side glm::vec2(0.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 1.0f), glm::vec2(1.0f, 1.0f), // -Y side glm::vec2(1.0f, 0.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(0.0f, 1.0f), glm::vec2(1.0f, 1.0f), // +Y side glm::vec2(0.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 1.0f), // +X side glm::vec2(0.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 1.0f), // +Z side glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f), glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 1.0f), }; void Cube::init_vertex() { struct Vertex { Vertex() {} Vertex(const glm::vec3 &pos, const glm::vec2 &tc) :position(pos), texcoord(tc) {} glm::vec3 position; glm::vec2 texcoord; }; // Setup m_vertices std::vector<Vertex> vertexBuffer(36); for (int i = 0; i != 36; ++i) { vertexBuffer[i] = Vertex(vd[i], tb[i]); } auto vertexBufferSize = vertexBuffer.size() * sizeof(Vertex); //Setup m_indices std::vector<uint32_t> indexBuffer(36); for (int i = 0; i != indexBuffer.size(); ++i) { indexBuffer[i] = i; } int indexBufferSize = indexBuffer.size() * sizeof(uint32_t); VkMemoryAllocateInfo memoryAlloc ={}; memoryAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memoryAlloc.pNext = NULL; memoryAlloc.allocationSize = 0; memoryAlloc.memoryTypeIndex = 0; VkMemoryRequirements memoryReqs; VkResult res; void *data = nullptr; //Generate vertex buffer //Setup VkBufferCreateInfo bufferIno ={}; bufferIno.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferIno.pNext = nullptr; bufferIno.size = vertexBufferSize; bufferIno.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; bufferIno.flags = 0; //Copy vertex data to VRAM memset(&m_vertices, 0, sizeof(m_vertices)); res = vkCreateBuffer(m_device, &bufferIno, nullptr, &m_vertices.buffer); assert(!res); vkGetBufferMemoryRequirements(m_device, m_vertices.buffer, &memoryReqs); memoryAlloc.allocationSize = memoryReqs.size; Vulkan::getMemoryType({}, memoryReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memoryAlloc.memoryTypeIndex); vkAllocateMemory(m_device, &memoryAlloc, nullptr, &m_vertices.memory); res = vkMapMemory(m_device, m_vertices.memory, 0, memoryAlloc.allocationSize, 0, &data); assert(!res); memcpy(data, vertexBuffer.data(), vertexBufferSize); vkUnmapMemory(m_device, m_vertices.memory); vkBindBufferMemory(m_device, m_vertices.buffer, m_vertices.memory, 0); //Generate index buffer VkBufferCreateInfo indexbufferInfo ={}; indexbufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; indexbufferInfo.pNext = nullptr; indexbufferInfo.size = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; indexbufferInfo.flags = 0; //Copy index data to vram memset(&m_indices, 0, sizeof(m_indices)); res = vkCreateBuffer(m_device, &indexbufferInfo, nullptr, &m_indices.buffer); assert(!res); vkGetBufferMemoryRequirements(m_device, m_indices.buffer, &memoryReqs); memoryAlloc.allocationSize = memoryReqs.size; Vulkan::getMemoryType({}, memoryReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memoryAlloc.memoryTypeIndex); res = vkAllocateMemory(m_device, &memoryAlloc, nullptr, &m_indices.memory); assert(!res); res = vkMapMemory(m_device, m_indices.memory, 0, indexBufferSize, 0, &data); assert(!res); memcpy(data, indexBuffer.data(), indexBufferSize); vkUnmapMemory(m_device, m_indices.memory); res = vkBindBufferMemory(m_device, m_indices.buffer, m_indices.memory, 0); assert(!res); m_indices.count = indexBuffer.size(); //Bind description m_vertices.bindingDescs.resize(1); m_vertices.bindingDescs[0].binding = VERTEX_BUFFER_BIND_ID; m_vertices.bindingDescs[0].stride = sizeof(Vertex); m_vertices.bindingDescs[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; //Attribute descriptions //Describes memory layout and shader attribute locations m_vertices.attributeDescs.resize(2); //Location 0: Position m_vertices.attributeDescs[0].binding = VERTEX_BUFFER_BIND_ID; m_vertices.attributeDescs[0].location = 0; m_vertices.attributeDescs[0].format = VK_FORMAT_R32G32B32_SFLOAT; m_vertices.attributeDescs[0].offset = 0; //Location 1: TexCoord m_vertices.attributeDescs[1].binding = VERTEX_BUFFER_BIND_ID; m_vertices.attributeDescs[1].location = 1; m_vertices.attributeDescs[1].format = VK_FORMAT_R32G32_SFLOAT; m_vertices.attributeDescs[1].offset = sizeof(float) * 3; //Assign to vertex buffer m_vertices.inputStateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; m_vertices.inputStateInfo.pNext = nullptr; m_vertices.inputStateInfo.vertexBindingDescriptionCount = m_vertices.bindingDescs.size(); m_vertices.inputStateInfo.pVertexBindingDescriptions = m_vertices.bindingDescs.data(); m_vertices.inputStateInfo.vertexAttributeDescriptionCount = m_vertices.attributeDescs.size(); m_vertices.inputStateInfo.pVertexAttributeDescriptions = m_vertices.attributeDescs.data(); } void Cube::init_ubo() { //Prepare and initialize uniform buffer containing shader uniforms //Vertex shader uniform buffer block VkMemoryAllocateInfo allocInfo ={}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.allocationSize = 0; allocInfo.memoryTypeIndex = 0; VkBufferCreateInfo bufferInfo ={}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = sizeof(m_uniform); bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; //Create a new buffer VkResult res = VK_SUCCESS; res = vkCreateBuffer(m_device, &bufferInfo, nullptr, &m_uniform.buffer); assert(!res); //Get memory requirements including size, alignment and memory type VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(m_device, m_uniform.buffer, &memReqs); allocInfo.allocationSize = memReqs.size; //Get the appropriate memory type for this type of buffer allocation //Only memory types that are visible to the host Vulkan::getMemoryType({}, memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex); //Allocate memory for the uniform buffer res = vkAllocateMemory(m_device, &allocInfo, nullptr, &m_uniform.memory); assert(!res); //Bind memory to buffer res = vkBindBufferMemory(m_device, m_uniform.buffer, m_uniform.memory, 0); assert(!res); //Store information in the uniform's descriptor m_uniform.desc.buffer = m_uniform.buffer; m_uniform.desc.offset = 0; m_uniform.desc.range = sizeof(Uniform); update_ubo(); } void Cube::init_texture() { VulkanTextureLoader::getInstance()->loadTexture( "../../media/textures/vulkan_space_rgba8.ktx", VK_FORMAT_R8G8B8A8_UNORM, &m_texture); } void Cube::init_descriptorSetLayout() { //Setup layout of descriptors used in this example //Basically connects the different shader stages to descriptors //for binding uniform buffers, image samplers, etc. //so every shader binding should map to one descriptor set layout binding std::vector<VkDescriptorSetLayoutBinding> layoutBindings(2); //Binding 0: Uniform Buffer (Vertex Shader) layoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; layoutBindings[0].descriptorCount = 1; layoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; layoutBindings[0].binding = 0; layoutBindings[0].pImmutableSamplers = nullptr; // Binding 1 : Fragment shader image sampler layoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, layoutBindings[1].descriptorCount = 1; layoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, layoutBindings[1].pImmutableSamplers = nullptr; layoutBindings[1].binding = 1; VkDescriptorSetLayoutCreateInfo descSetLayoutInfo ={}; descSetLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descSetLayoutInfo.pNext = nullptr; descSetLayoutInfo.bindingCount = layoutBindings.size(); descSetLayoutInfo.pBindings = &layoutBindings[0]; VkResult res = vkCreateDescriptorSetLayout(m_device, &descSetLayoutInfo, nullptr, &m_descriptorSetLayout); assert(!res); // Create the pipeline layout that is used to generate the rendering pipelines that are based on this // descriptor set layout // In a more complex scenario you would have different pipeline layouts for different descriptor set // Layouts that could be reused. VkPipelineLayoutCreateInfo pipelineLayoutInfo ={}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.pNext = NULL; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &m_descriptorSetLayout; res = vkCreatePipelineLayout(m_device, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); assert(!res); } void Cube::init_pipeline(VkRenderPass &renderPass, VkPipelineCache &pipelineCache) { //Create out rendering pipeline used in this example //Vulkan uses the concept of rendering pipelines to encapsulate fixed states //This replaces OpenGL's hube(and cumbersome) state machine //A pipeline is then storeed and hashed on the GPU making pipleine changes //much faster than having to set dozens of states //In a real world application you'd have dozens of pipelines for every shader //set used in a scene //Note that there are a few states that are not stored with the pipeline //These are called dynamic states and the pipeline only stores that they are //used with this pipeline, but not their states VkResult res = VK_SUCCESS; //Vertex input state //Describes the topolo used with this pipeline VkPipelineInputAssemblyStateCreateInfo inputAssemblyState ={}; inputAssemblyState.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; //Rasterization state VkPipelineRasterizationStateCreateInfo rasterizationState ={}; rasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT; rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationState.depthClampEnable = VK_FALSE; rasterizationState.rasterizerDiscardEnable = VK_FALSE; rasterizationState.depthBiasEnable = VK_FALSE; //Color blend state //Describes blend modes and color masks VkPipelineColorBlendStateCreateInfo colorBlendState ={}; colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; //One blend attachment state //Blending is not used in this example VkPipelineColorBlendAttachmentState blendAttachmentState[1] ={}; blendAttachmentState[0].colorWriteMask = 0xf; blendAttachmentState[0].blendEnable = VK_FALSE; colorBlendState.attachmentCount = 1; colorBlendState.pAttachments = blendAttachmentState; //Viewport state VkPipelineViewportStateCreateInfo viewportState ={}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.scissorCount = 1; //Enable dynamic states //Descibes the dynamic states to be used with this pipeline //Dynamic states can be set even after pipeline has been created //So there is no need to create new pipelines just for changing //a viewport's demensions or a scissor box //The dynamic state properties themselves are stored in the command buffer std::vector<VkDynamicState> dynamicStatesEnables; dynamicStatesEnables.push_back(VK_DYNAMIC_STATE_VIEWPORT); dynamicStatesEnables.push_back(VK_DYNAMIC_STATE_SCISSOR); VkPipelineDynamicStateCreateInfo pipelineDynamicState ={}; pipelineDynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; pipelineDynamicState.pDynamicStates = dynamicStatesEnables.data(); pipelineDynamicState.dynamicStateCount = dynamicStatesEnables.size(); //Depth and stencil state //Describes depth and stenctil test and compare ops // Basic depth compare setup with depth writes and depth test enabled, No stencil used VkPipelineDepthStencilStateCreateInfo depthStencilState ={}; depthStencilState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencilState.depthTestEnable = VK_TRUE; depthStencilState.depthWriteEnable = VK_TRUE; depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; depthStencilState.depthBoundsTestEnable = VK_FALSE; depthStencilState.back.failOp = VK_STENCIL_OP_KEEP; depthStencilState.back.passOp = VK_STENCIL_OP_KEEP; depthStencilState.back.compareOp = VK_COMPARE_OP_ALWAYS; depthStencilState.stencilTestEnable = VK_FALSE; depthStencilState.front = depthStencilState.back; //Multi sampling state, No multi sampling used in this example VkPipelineMultisampleStateCreateInfo multiSampleState ={}; multiSampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multiSampleState.pSampleMask = nullptr; multiSampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; #ifdef USE_GLSL m_triangleShader.loadGLSL(VK_SHADER_STAGE_VERTEX_BIT, "texture.vert"); m_triangleShader.loadGLSL(VK_SHADER_STAGE_FRAGMENT_BIT, "texture.frag"); #else m_triangleShader.loadSPIR(VK_SHADER_STAGE_VERTEX_BIT, "Cube.vert.spv"); m_triangleShader.loadSPIR(VK_SHADER_STAGE_FRAGMENT_BIT, "Cube.frag.spv"); #endif std::vector<VkPipelineShaderStageCreateInfo> shaderStages = m_triangleShader.getStages(); VkGraphicsPipelineCreateInfo pipelineCreateInfo ={}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.layout = m_pipelineLayout; pipelineCreateInfo.renderPass = renderPass; //Assign states, two shader stages pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pVertexInputState = &m_vertices.inputStateInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multiSampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = &shaderStages[0]; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.pDynamicState = &pipelineDynamicState; res = vkCreateGraphicsPipelines(m_device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &m_pipeline); assert(!res); } void Cube::init_descriptorPool() { //We need to tell the api the number of max requessted descriptors per type VkDescriptorPoolSize typeCounts[2] ={}; //This example only uses one descriptor type (uniform buffer) and only requests one descriptor of this type typeCounts[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; typeCounts[0].descriptorCount = 1; typeCounts[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; typeCounts[1].descriptorCount = 1; VkDescriptorPoolCreateInfo descPoolInfo ={}; descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descPoolInfo.pNext = nullptr; descPoolInfo.poolSizeCount = 2; descPoolInfo.pPoolSizes = typeCounts; // Set the max. number of sets that can be requested // Requesting descriptors beyond maxSets will result in an error descPoolInfo.maxSets = 2; VkResult res = vkCreateDescriptorPool(m_device, &descPoolInfo, nullptr, &m_descriptorPool); assert(!res); } void Cube::init_descriptorSet() { //Update descirptor sets determing the shader binding points //For every binding point used in a shader there needs to be one //Descriptor set matching that binding point VkResult res = VK_SUCCESS; VkDescriptorSetAllocateInfo descAllocInfo ={}; descAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; descAllocInfo.descriptorPool = m_descriptorPool; descAllocInfo.descriptorSetCount = 1; descAllocInfo.pSetLayouts = &m_descriptorSetLayout; res = vkAllocateDescriptorSets(m_device, &descAllocInfo, &m_descriptorSet); assert(!res); // Image descriptor for the color map texture VkDescriptorImageInfo descriptorImageInfo ={}; descriptorImageInfo.sampler = m_texture.sampler; descriptorImageInfo.imageView = m_texture.view; descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; //Binding 0: Uniform buffer std::vector<VkWriteDescriptorSet> writeDescSets(2); writeDescSets[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescSets[0].dstSet = m_descriptorSet; writeDescSets[0].descriptorCount = 1; writeDescSets[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescSets[0].pBufferInfo = &m_uniform.desc; writeDescSets[0].dstBinding = 0; writeDescSets[0].descriptorCount = 1; // Binding 1 : Fragment shader texture samplers writeDescSets[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescSets[1].dstSet = m_descriptorSet; writeDescSets[1].descriptorCount = 1; writeDescSets[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, writeDescSets[1].pImageInfo = &descriptorImageInfo; writeDescSets[1].dstBinding = 1; writeDescSets[1].descriptorCount = 1; vkUpdateDescriptorSets(m_device, writeDescSets.size(), &writeDescSets[0], 0, nullptr); } void Cube::update_ubo() { static float deltaTime = 0.0f; deltaTime += m_timer.getDeltaTime(); m_matrix.model = glm::rotate(glm::mat4(1.0f), deltaTime, glm::vec3(0.0f, 1.0f, 0.0f)); m_matrix.view = glm::lookAt(glm::vec3(0.0f, 0.0f, 5.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); m_matrix.proj = glm::perspective(45.0f, 1.5f, 0.1f, 1000.0f); //Map uniform buffer and update it uint8_t *pData; VkResult res = vkMapMemory(m_device, m_uniform.memory, 0, sizeof(m_matrix), 0, (void**)&pData); assert(!res); memcpy(pData, &m_matrix, sizeof(MVPMatrix)); vkUnmapMemory(m_device, m_uniform.memory); } }
fe0e7cca3262b749d474e7be88983a28186f982b
db1afb84d61a2722be95ca066de6c848b243dda7
/lab03_20/lab031test/lab031test.cpp
b6617fc5c9d892853323e6817668ffa97db435b0
[]
no_license
orazaev-sergej/klyuOOP20
fb16e78470f243404e39a25405ee801dfd3f8f37
ffc1d7b053bcb0aea17559f8875d05e589f5390a
refs/heads/master
2022-11-21T20:26:48.036088
2020-07-23T14:07:04
2020-07-23T14:07:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,829
cpp
lab031test.cpp
// lab031cCatchTests.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include "../lab031/CCar.h" void PrintCarState(const CCar& aCar) { std::cout << "Engine: " << aCar.GetEngineState() << " "; std::cout << "Moving direction: " << (int)aCar.GetMovingDirection() << " "; std::cout << "Gear mode: " << aCar.GetGearNum() << " "; std::cout << "Speed: " << aCar.GetSpeedValue() << std::endl; } TEST_CASE("Turning the engine on and off") { CCar Zhiguli; CHECK(Zhiguli.TurnOnEngine() == true); CHECK(Zhiguli.TurnOnEngine() == false); // пытаемся выключить работающий двигатель CHECK(Zhiguli.TurnOffEngine() == true); CHECK(Zhiguli.TurnOffEngine() == false); // пытаемся выключить неработающий двигатель std::cout << "Test on engine turning on/off is Ok" << std::endl; } TEST_CASE("Changing gear on stop when engine off: only neutral allowed; can choose -1, 0, 1 gear on stop but others") { CCar Zhiguli; GIVEN("Engine turned off") { PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(-1) == false); // двигатель не включен -> нельзя включить реверс PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // при выключенном двигателе передача и так нейтральная PrintCarState(Zhiguli); } CHECK(Zhiguli.TurnOnEngine() == true); // включаем выключенный двигатель PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(-1) == true); // можно стоя на месте включить реверс PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // а можно стоя с реверса на первую PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(2) == false); // а на вторую нельзя PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // на нейтраль, чтобы затем выключить PrintCarState(Zhiguli); CHECK(Zhiguli.TurnOffEngine() == true); // выключаем двигатель PrintCarState(Zhiguli); std::cout << "Test on gear handling on stop is Ok" << std::endl; } TEST_CASE("Test on well forward moving") { CCar Zhiguli; CHECK(Zhiguli.TurnOnEngine() == true); // включаем двигатель PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // 1-я передача PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(100) == false); CHECK(Zhiguli.GetSpeedValue() == 30); // слишком большая скорость PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(20) == true); // а такая скорость годится PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(2) == true); // 2-я передача PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(50) == true); // такая скорость годится PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(4) == true); // 2-я передача PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(80) == true); // такая скорость годится PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(5) == true); // 2-я передача PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(200) == false); // такая скорость недоступна машине CHECK(Zhiguli.GetSpeedValue() == 150); PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(140) == true); // такая скорость годится PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(90) == true); // замедляемся PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(4) == true); // понижаем передачу PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(60) == true); // замедляемся PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(3) == true); // понижаем передачу PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(20) == false); // пытаемся замедлиться сверх возможного CHECK(Zhiguli.GetSpeedValue() == 30); PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(30) == true); // замедляемся PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // понижаем передачу до 1-ой PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(0) == true); // остановились PrintCarState(Zhiguli); CHECK(Zhiguli.TurnOffEngine() == false); // выключили двигатель, безуспешно -- нужна нейтраль PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // нейтраль PrintCarState(Zhiguli); CHECK(Zhiguli.TurnOffEngine() == true); // выключили двигатель, успешно PrintCarState(Zhiguli); std::cout << "Test on moving forward is Ok" << std::endl; } TEST_CASE("Test with reverse moving") { CCar Zhiguli; CHECK(Zhiguli.TurnOnEngine() == true); // включаем двигатель PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // первая передача, стоим на месте CHECK(Zhiguli.GetMovingDirection() == Direction::Stop); PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(10) == true); // первая передача, едем вперед 10 CHECK(Zhiguli.GetMovingDirection() == Direction::Forward); PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(-1) == false); // переключаемся на реверс -- безуспешно PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // переключаемся на нейтраль, но едем вперед CHECK(Zhiguli.GetMovingDirection() == Direction::Forward); PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(-1) == false); // переключаемся на реверс -- безуспешно PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(0) == true); // останавливаемся на нейтрали PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // первая передача, стоим на месте PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(-1) == true); // переключаемся на реверс, стоя на месте CHECK(Zhiguli.GetMovingDirection() == Direction::Stop); PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(15) == true); // едем назад 15 CHECK(Zhiguli.GetMovingDirection() == Direction::Backward); PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == false); // переключаемся на первую -- безуспешно PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // переключаемся на нейтраль, едем назад PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == false); // переключаемся на первую -- безуспешно PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(12) == true); CHECK(Zhiguli.GetMovingDirection() == Direction::Backward); PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(0) == true); // останавливаемся CHECK(Zhiguli.GetMovingDirection() == Direction::Stop); PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(1) == true); // переключаемся на первую PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(20) == true); // 20 вперед CHECK(Zhiguli.GetMovingDirection() == Direction::Forward); PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(0) == true); // переключаемся на нейтраль, едем вперед PrintCarState(Zhiguli); CHECK(Zhiguli.SetGear(3) == false); // слишком высокая передача для данной скорости 20 PrintCarState(Zhiguli); CHECK(Zhiguli.SetSpeed(0) == true); // останавливаемся PrintCarState(Zhiguli); CHECK(Zhiguli.TurnOffEngine() == true); // выключаем двигатель PrintCarState(Zhiguli); std::cout << "Test on moving with reverse is Ok" << std::endl; }