blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6bb8c405f52a281117fa2dccaead0ea4f9179002
f35d27bfbdcf0ca5aae57ec7164bf277b7cfefc8
/include/tracker/predictor/particle/ParticleFilter.h
0642d5dcdfc08016b64c314436c1f6d157acf143
[]
no_license
smartcai/VideoSynopsis
ea3c07e69117201b43316412a914d152a4151a7f
319701e2ab65d483daa5e38383c5c111fd72a3d7
refs/heads/master
2020-04-26T02:22:20.030069
2018-05-03T03:07:05
2018-05-03T03:07:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,364
h
#ifndef CPP_PARTICLEFILTER_H #define CPP_PARTICLEFILTER_H #include "tracker/predictor/particle/Particle.h" #include "util/BoundingBox.h" #include <dlib/matrix.h> class ParticleFilter { public: static constexpr int numStates = 7; // [x, y, area, ratio, vx, vy, area_change] static constexpr int numParticles = 2000; public: ParticleFilter(const BoundingBox &initialState); virtual ~ParticleFilter() = default; ParticleFilter(ParticleFilter &&rhs); ParticleFilter &operator=(ParticleFilter &&rhs); // Prevent copying ParticleFilter(const ParticleFilter &rhs) = delete; ParticleFilter &operator=(const ParticleFilter &rhs) = delete; /** * Move all particles using current velocities. */ void update(); /** * Move all particles using current velocities. Update weights and resample based on observation */ void update(const BoundingBox &bb); /** * Compute the predicted next state by moving all particles one time step and computing the mean. */ BoundingBox getPrediction() const; /** * Compute the mean of all particles. */ BoundingBox getCurrentEstimate() const; private: std::vector<std::shared_ptr<Particle>> particles; dlib::matrix<double, numStates, numStates> velocityModel; void resample(); }; #endif //CPP_PARTICLEFILTER_H
[ "zg9uagfv@gmail.com" ]
zg9uagfv@gmail.com
c0123e6f00b436757fdbb6d2b7d4ef82ae3f6cfd
8ff3f1af6ad1cac12b53859bd95c0779f6d68968
/ihealthEx/control_card.h
bee579f3246e05c7998609c879b910d38bad4eef
[]
no_license
AlexZhanghao/ihealthex
af5ff1e03fbcc15891f5cd3af0db1e6ff647b972
6986433e8eb245cc908b101547bb4a0213924ad4
refs/heads/master
2020-03-21T11:52:17.172306
2019-06-09T02:51:42
2019-06-09T02:51:42
138,525,752
0
0
null
null
null
null
GB18030
C++
false
false
1,490
h
#pragma once #include "APS168.h" #include "ErrorCodeDef.h" #include "APS_define.h" #include "type_def.h" #define MOTOR_ON (1) #define MOTOR_OFF (0) #define CLUTCH_ON (0) #define CLUTCH_OFF (1) #define YES (1) #define NO (0) #define __MAX_DO_CH (24) #define __MAX_DI_CH (24) #define SHOULDER_AXIS_ID (0) #define ELBOW_AXIS_ID (1) #define VEL_TO_PALSE (0.009) //为了将速度转化为脉冲 #define MOVE_VELOCITY (4) class ControlCard { public: ControlCard(); ~ControlCard() = default; I32 Initial(); void SetAxisParamZero(); void SetClutch(bool on_or_off = CLUTCH_ON); void SetMotor(bool on_or_off = MOTOR_ON); void GetLimitSwitchStatus(); void GetEncoderData(); void GetEncoderData(double buf[2]); void MotorVelocityMove(I32 axis_id, double velocity); void MotorAbsoluteMove(I32 axis_id, double position, double velocity); bool IsMoveFinish(); void PositionReset(); void StopMove(); public: double shoulder_position_in_degree; double elbow_position_in_degree; double shoulder_error_in_degree; double elbow_error_in_degree; private: bool axis_status_; bool clutch_status_; long card_name_; long board_id_; int total_axis_; bool is_card_initialed_; bool shoulder_limit_switch_status_[2]{ 0 }; bool elbow_limit_switch_status_[2]{ 0 }; private: I32 FindSuitableControlCard(I32 borad_id_in_bits); void ShoulderMotorVelocityMove(double velocity); void ElbowMotorVelocityMove(double velocity); void MoveInVelocityMode(I32 axis_id, double velocity); };
[ "363040909@qq.com" ]
363040909@qq.com
63963c461f015983b06d6fb37d95592cce262b3a
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/thirdparty/eigen-3.3.3/doc/snippets/MatrixBase_cwiseSign.cpp
efd717955fdcf50e9b1a235354821da486e91a24
[ "MIT", "GPL-3.0-only", "LGPL-2.1-only", "BSD-3-Clause", "LGPL-2.0-or-later", "MPL-2.0", "LGPL-2.1-or-later", "Minpack" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C++
false
false
80
cpp
MatrixXd m(2,3); m << 2, -4, 6, -5, 1, 0; cout << m.cwiseSign() << endl;
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
a325d2edf1f18b8b34547ae7a468d3e2a6c767db
0ad1e75df68fb14976c79c8921249dcd6e74f967
/Lcs as Increasig Palandromic Sequence.cpp
5317436fd3ecd382faad24885fc5f43c0181aa0a
[]
no_license
variablemayank/competetive-programming-codes
9010d215832f4937735d6b35b1df35df0f8a59e6
71bbc70049089fcc24444471dd4504b1d29c371f
refs/heads/master
2021-09-06T04:17:29.052221
2018-02-02T08:57:56
2018-02-02T08:57:56
119,955,414
1
1
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include<bits/stdc++.h> using namespace std; int lcs(string x,string y,int n,int m); int increasing(string s,int n) { string s1=s; reverse(s1.begin(),s1.end()); return (n-lcs(s,s1,n,n)); } int lcs(string x,string y,int n,int m) { int A[n+1][n+1]; for(int i=0;i<=m;i++) { for(int j=0;j<=n;j++) { if(i==0||j==0) A[i][j]=0; else if(x[i-1]==y[j-1]) { A[i][j]=A[i-1][j-1]+1; } else { A[i][j]=max(A[i-1][j],A[i][j-1]); } } } return A[m][n]; } int main() { int t; cin>>t; while(t--) { string s; cin>>s; int len=s.length(); cout<<increasing(s,len); } }
[ "mayank202020@rediffmail.com" ]
mayank202020@rediffmail.com
f035ec8f20768f3e386530cbd5c8691d719b9fe4
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/74/1046.c
ca7d6cdc39341b715f726ec054054ddca4b76a32
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
524
c
void main() { int F(int i); int G(int i); int m,n,i,a[400],b=0; scanf("%d %d",&m,&n); for(i=m;i<=n;i++) { if((F(i)==1)&&(G(i)==1)) { a[b]=i;b++; } } if(b!=0) { printf("%d",a[0]); for(i=1;i<b;i++) printf(",%d",a[i]); } else printf("no"); } int F(int i) { int e,k; k=sqrt(i); for(e=2;e<=k;e++) if(i%e==0) break; if(e>k) return(1); else return(0); } int G(int i) { int f,g=0; f=i; while(g<f) {g=g*10+i%10;i=i/10;} if(g==f) return(1); else return(0); }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
7d33a084dce0f482a8b20a85197ce0c38d7bd9ab
0bc8d7cc71f94ddbc7c2ab641828f6e404464d33
/gazebo/util/SteamAudio.hh
af8b3e9734b6f97351c175602b878e572c5feb06
[ "Apache-2.0" ]
permissive
dagiopia/gazebo-as
3aa492d2304f9b5107191f77c0d8b63c485b689d
3bb84baff23ba18050cc4236cc679a83cca6d6d3
refs/heads/master
2023-04-08T19:26:17.629175
2019-03-20T14:42:02
2019-03-20T14:42:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,316
hh
/* * Copyright (C) 2019 Open Source Robotics Foundation * * 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 _GAZEBO_UTIL_STEAMAUDIO_HH_ #define _GAZEBO_UTIL_STEAMAUDIO_HH_ #include <algorithm> #include <iterator> #include <vector> #include <phonon.h> #include <sdf/sdf.hh> #include <ignition/math/Vector3.hh> #include <ignition/math/Pose3.hh> #include "gazebo/common/SingletonT.hh" #include "gazebo/common/common.hh" #include "gazebo/util/UtilTypes.hh" #include "gazebo/gazebo_config.h" #include "gazebo/util/system.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/transport/transport.hh" namespace gazebo { namespace util { /// \addtogroup gazebo_util Utility /// \{ /// \class SteamAudio SteamAudio.hh util/util.hh /// \brief Physics Based Audio Simulation class GZ_UTIL_VISIBLE SteamAudio : public SingletonT<SteamAudio> { /// \brief Constructor private: SteamAudio(); /// \brief Destructor private: ~SteamAudio(); /// \brief Load the SteamAudio server. /// \return True on success. public: bool Load(sdf::ElementPtr _sdf = sdf::ElementPtr()); /// \brief Finalize. public: void Fini(); /// \brief Get a list of available audio devices /// \return A list of audio device names public: std::set<std::string> DeviceList() const; /// \brief Initialize SteamAudio private: void Init(); /// \brief Set the SOFA file /// \param[in] The URI of the SOFA file public: void SetSOFA(const std::string &_filename); /// \brief Get url of the SOFA file /// \return The URI of the SOFA file, empty if none loaded public: std::string GetSOFAuri() const; /// \brief Set Listener Pose /// \param[in] World Pose of the Audio Listener link public: void SetListenerPose(const ignition::math::Pose3d &_pose); /// \brief Set Generator Pose /// \param[in] World Pose of the Audio Generator Link public: void SetGeneratorPose(const ignition::math::Pose3d &_pose); /// \brief Apply binaural effect /// \param[in] _buf input audio /// \param[in] _bufSize number of samples in buffer /// \return std::vector<float> of the output audio public: std::vector<float> SteamBinauralEffect(float *_buf, long _bufSize); /// \internal /// \brief Convert Gazebo style mesh to Steam style /// \param[in] std::string _meshURI mesh uri from sdf /// \return std::vector<IPLTriangle> Steam style mesh triangles private: void ConvertMesh(std::string _meshURI); /// \brief Steam Error Check private: bool SteamErrorCheck(IPLerror errCode); /// \internal /// \brief WorldUpdate Event Callback private: void Update(); /// \internal /// \brief WorldCreated Event Callback private: void WorldCreated(); /// \internal /// \brief Audio Generator Pose private: ignition::math::Pose3d generatorPose; /// \internal /// \brief Audio Listener Pose private: ignition::math::Pose3d listenerPose; /// \internal /// \brief Audio Listener Relative Location private: ignition::math::Vector3d listenerLocation; /// \internal /// \brief SteamAudio Direction Vector private: IPLVector3 listenerDirection; /// \internal /// \brief Audio Input object private: event::ConnectionPtr worldCreatedEventCon; /// \internal /// \brief Audio Input object private: event::ConnectionPtr worldUpdateEventCon; /// \internal /// \brief Audio Input object private: common::Audio *iAudio; /// \internal /// \brief Audio Output object private: common::Audio *oAudio; /// \internal /// \brief Audio Buffer private: float *audioBuffer; /// \internal /// \brief Audio Buffer Size private: long bufferSize; /// \internal /// \brief SteamAudio Context private: IPLhandle steamContext{nullptr}; /// \internal /// \brief SteamAudio Rendering settings private: IPLRenderingSettings steamRendSettings; /// \internal /// \brief SteamAudio Mono Audio Format private: IPLAudioFormat monoAudio; /// \internal /// \brief SteamAudio Stereo Audio Format private: IPLAudioFormat stereoAudio; /// \internal /// \brief SteamAudio Binaural Renderer private: IPLhandle steamBinauralRenderer{nullptr}; /// \internal /// \brief SteamAudio Binaural Effect private: IPLhandle steamBinauralEffect{nullptr}; /// \internal /// \brief SteamAudio Scene private: IPLhandle steamScene{nullptr}; /// \internal /// \brief SteamAudio Environment Object private: IPLhandle steamEnvObj{nullptr}; /// \internal /// \brief SteamAudio Environmental Renderer private: IPLhandle steamEnvRenderer{nullptr}; /// \internal /// \brief SteamAudio Direct Sound Path private: IPLDirectSoundPath steamDirectSoundPath; /// \internal /// \brief SteamAudio Direct Sound Effect Options private: IPLDirectSoundEffectOptions directSoundMode; /// \internal /// \brief SteamAudio Direct Sound Effect private: IPLhandle steamDirectSoundEffect{nullptr}; /// \internal /// \brief Input Audio Buffer private: std::vector<float> inputAudio; /// \internal /// \brief SteamAudio Input Audio Buffer - mono private: IPLAudioBuffer inputAudioBuffer; /// \internal /// \brief Output Audio Buffer private: std::vector<float> outputAudio; /// \internal /// \brief SteamAudio Output Audio Buffer - stereo private: IPLAudioBuffer outputAudioBuffer; /// \internal /// \brief SOFA file private: std::string SOFAfile; /// \internal /// \brief Indices of Triangles of Meshes private: std::vector<std::vector<IPLTriangle> > triangles; /// \internal /// \brief Vertices of Triangles of Meshes private: std::vector<std::vector<IPLVector3> > vertices; /// \internal /// \brief Material name private: std::vector<std::string> materialName; /// \internal /// \brief Preset Material Acoustic Properties private: std::map<std::string, IPLMaterial> materialAcousticProp; /// \internal /// \brief Material Acoustic Properties private: std::vector<IPLMaterial> materialProperties; /// \internal /// \brief Steam Audio Static Mesh Objects private: std::vector<IPLhandle> staticMeshes; /// \brief This is a singleton private: friend class SingletonT<SteamAudio>; }; /// \} } } #endif
[ "dagiopia@gmail.com" ]
dagiopia@gmail.com
1bbfd625e3891eece46d774ecd299797d73dc208
604c3a16454625d5589fb768b0ea032ed234035c
/Aula07_08/Carro/Carro.h
add87bd91f042fa1d1102bb5d5b27b92badb260b
[]
no_license
marcosmn/LP1_2020.5
035ffa14c2d3f44735f1066d193289f1bf344af8
61b102495c0215161ddf63527e0e477b496c2fc9
refs/heads/master
2022-11-15T06:12:29.322254
2020-07-20T18:27:55
2020-07-20T18:27:55
274,411,676
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
#include <string> #include "Motor.h" using namespace std; class Carro { public: static int quantidadeCarros; string tipo; string placa; int numPortas; int velocidade; string cor; Motor motor; Carro(string cor); Carro(); void acelera(int velocidade); void freia(int velocidade); void ligaCarro(); };
[ "marcosmnobrega@gmail.com" ]
marcosmnobrega@gmail.com
34e0d9dba3afdc6f2d42f233f2cbfc1380d545cf
eaf70918553f10097c42b3a71fc5c153f170675b
/P4Plugin/Source/r19.1/include/p4/handler.h
d09aa1a0f06022cc9d3acce6856a3fa27189d825
[ "LicenseRef-scancode-public-domain", "OpenSSL", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows" ]
permissive
Unity-Technologies/NativeVersionControlPlugins
ee07857c736cfc9cb66035b1d4ee27e1f5859f09
04e1897510d0c71e7d7306afe299c88ac007e59b
refs/heads/master
2022-08-17T16:16:03.257820
2022-08-05T14:30:29
2022-08-05T14:30:29
204,474,261
34
9
NOASSERTION
2022-08-05T14:30:31
2019-08-26T12:47:30
C++
UTF-8
C++
false
false
2,113
h
/* * Copyright 1995, 1996 Perforce Software. All rights reserved. * * This file is part of Perforce - the FAST SCM System. */ /* * handler.h - last chance handlers to keep track of loose objects * * Handlers provide a way of associating an object with a string so * context can be retained across RPC dispatched function calls. * This is used for file transfers, which are carried out in a series * of RPC calls. The sender picks a handle name and then uses that * consistenly during the transfer. The receiver uses the provided handle * name to stash and retrieve the object the represents the open file. * * Handlers also provide a means of tracking across objects. If any * object encounters an error, it can mark the handle so that a subsequent * call to AnyErrors() can report so. * * Public classes: * * Handlers - a list of LastChance objects * LastChance - a virtual base class that gets deleted with the * handlers. */ class LastChance; struct Handler { StrBuf name; int anyErrors; LastChance *lastChance; } ; class LastChance { public: LastChance() { handler = 0; isError = 0; deleteOnRelease = 0; } virtual ~LastChance(); void Install( Handler *h ) { handler = h; handler->lastChance = this; } void SetError() { isError = 1; } void SetError( Error *e ) { if( e->Test() ) isError = 1; } int IsError() { return isError; } int DeleteOnRelease() { return deleteOnRelease; } protected: int deleteOnRelease; private: Handler *handler; int isError; } ; const int maxHandlers = 10; class Handlers { public: Handlers(); ~Handlers(); void Install( const StrPtr *name, LastChance *lastChance, Error *e ); LastChance * Get( const StrPtr *name, Error *e = 0 ); int AnyErrors( const StrPtr *nane ); void SetError( const StrPtr *name, Error *e ); void Release(); private: int numHandlers; Handler table[maxHandlers]; Handler *Find( const StrPtr *handle, Error *e = 0 ); } ;
[ "daniel.hompanera@unity3d.com" ]
daniel.hompanera@unity3d.com
980212346634b7ff3306fda98f78d84fb69c496e
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/libcxx/containers/sequences/list/list.modifiers/insert_iter_value_db1.pass.cpp
4a4ebbbf9e67d9ccf065226260aa355048cd0c9c
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Can't test the system lib because this test enables debug mode // UNSUPPORTED: with_system_cxx_lib // <list> // iterator insert(const_iterator position, const value_type& x); #define _LIBCPP_DEBUG 1 #define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0)) #include <list> #include <cstdlib> #include <cassert> int main() { std::list<int> v1(3); std::list<int> v2(3); int i = 4; v1.insert(v2.begin(), i); assert(false); }
[ "1848@shanchain.com" ]
1848@shanchain.com
8507ad5290cc55be64b0cf0d7c26923b9d14c866
67d18d4bb54f3e7da06674c2bb65e4658d4538ba
/frontend/include/g++_HEADERS/hdrs1/ext/pb_ds/detail/cc_hash_table_map_/resize_no_store_hash_fn_imps.hpp
e2d0b03edf0ae2eb4f719f42c6eb441bbdc676a8
[ "MIT" ]
permissive
uwplse/stng
8c1f483a96c8313b8ec36a15791db75d20cfcf33
b077f4d469edf4971c356367f6019132047d6a3b
refs/heads/master
2022-05-06T08:28:27.139569
2022-04-05T05:01:49
2022-04-05T05:01:49
63,819,139
15
7
null
2017-01-13T11:56:50
2016-07-20T22:32:32
C++
UTF-8
C++
false
false
91
hpp
/usr/include/c++/4.4/./ext/pb_ds/detail/cc_hash_table_map_/resize_no_store_hash_fn_imps.hpp
[ "akcheung@cs.washington.edu" ]
akcheung@cs.washington.edu
4026ea2c81b988f27e7d7c62460f7dd4493db416
a2683e71d103165f459f91235f9a4108852251e0
/march/passfail.cpp
0ed3226e8c1081f74e40fec9526f292d9da08e24
[]
no_license
DustWolverine/codingblocks
b2b1ea57f8834be53db59531b9b2e33775fd7e31
25c35136425a030859cd19d47a82d2034c41bb6c
refs/heads/main
2023-06-25T23:53:21.016932
2021-05-11T16:02:47
2021-05-11T16:02:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include<bits/stdc++.h> #define endl "\n" using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--){ int am,bm,cm,tm,a,b,c; cin>>am>>bm>>cm>>tm>>a>>b>>c; int sum=am+bm+cm; if(sum>=tum and a>=am and b>=bm and c>=cm){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } return 0: }
[ "rajakash7001@gmail.con" ]
rajakash7001@gmail.con
c8f1b3fb3c39f96d335039c1700a6f78eb3bb287
3e45eb6d621659714b79192568c54e53be9ef290
/admin/thirdparty/bbclone/ip2ext/189.inc
c1e1fc966d3f91e148e4f02752e645d36499aca3
[]
no_license
Rafaj-Design/WebGuru
233317c39bafced10c1ee728d2f0a05031c7d15a
f6bf85f149d14630deda57a06d361fd6758817eb
refs/heads/master
2021-05-26T16:54:20.748036
2013-04-26T12:20:13
2013-04-26T12:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
62
inc
br|3170893824|4194304 ie|3175088128|2048 mx|3179282432|5242880
[ "ondrej.rafaj@fuerteint.com" ]
ondrej.rafaj@fuerteint.com
117a7979bd25555f350b678a86812844babb8755
e0f83c30ba1ca820f2148d484ec7171d6073a95b
/src/shrpx_spdy_upstream.cc
ede2625ba0715a6b5f00b2683b9cad97a616d092
[ "MIT" ]
permissive
cofyc/nghttp2
518557da2cde0caa1d69514333d8dca99f2e9895
4dea318b5ba4210f5ef7e8d48f8ad2c9fbbbf425
refs/heads/master
2023-03-22T08:37:48.709815
2015-02-07T15:49:56
2015-02-07T15:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,334
cc
/* * nghttp2 - HTTP/2 C Library * * Copyright (c) 2012 Tatsuhiro Tsujikawa * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "shrpx_spdy_upstream.h" #include <netinet/tcp.h> #include <assert.h> #include <cerrno> #include <sstream> #include <nghttp2/nghttp2.h> #include "shrpx_client_handler.h" #include "shrpx_downstream.h" #include "shrpx_downstream_connection.h" #include "shrpx_config.h" #include "shrpx_http.h" #include "shrpx_worker_config.h" #include "http2.h" #include "util.h" #include "template.h" using namespace nghttp2; namespace shrpx { namespace { ssize_t send_callback(spdylay_session *session, const uint8_t *data, size_t len, int flags, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); auto handler = upstream->get_client_handler(); auto wb = handler->get_wb(); if (wb->wleft() == 0) { return SPDYLAY_ERR_WOULDBLOCK; } auto nread = wb->write(data, len); return nread; } } // namespace namespace { ssize_t recv_callback(spdylay_session *session, uint8_t *buf, size_t len, int flags, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); auto handler = upstream->get_client_handler(); auto rb = handler->get_rb(); if (rb->rleft() == 0) { return SPDYLAY_ERR_WOULDBLOCK; } auto nread = std::min(rb->rleft(), len); memcpy(buf, rb->pos, nread); rb->drain(nread); return nread; } } // namespace namespace { void on_stream_close_callback(spdylay_session *session, int32_t stream_id, spdylay_status_code status_code, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Stream stream_id=" << stream_id << " is being closed"; } auto downstream = upstream->find_downstream(stream_id); if (!downstream) { return; } upstream->consume(stream_id, downstream->get_request_datalen()); downstream->reset_request_datalen(); if (downstream->get_request_state() == Downstream::CONNECT_FAIL) { upstream->remove_downstream(downstream); // downstrea was deleted return; } downstream->set_request_state(Downstream::STREAM_CLOSED); if (downstream->get_response_state() == Downstream::MSG_COMPLETE) { // At this point, downstream response was read if (!downstream->get_upgraded() && !downstream->get_response_connection_close()) { // Keep-alive downstream->detach_downstream_connection(); } upstream->remove_downstream(downstream); // downstrea was deleted return; } // At this point, downstream read may be paused. // If shrpx_downstream::push_request_headers() failed, the // error is handled here. upstream->remove_downstream(downstream); // downstrea was deleted // How to test this case? Request sufficient large download // and make client send RST_STREAM after it gets first DATA // frame chunk. } } // namespace namespace { void on_ctrl_recv_callback(spdylay_session *session, spdylay_frame_type type, spdylay_frame *frame, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); switch (type) { case SPDYLAY_SYN_STREAM: { if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Received upstream SYN_STREAM stream_id=" << frame->syn_stream.stream_id; } auto downstream = upstream->add_pending_downstream( frame->syn_stream.stream_id, frame->syn_stream.pri); downstream->reset_upstream_rtimer(); auto nv = frame->syn_stream.nv; if (LOG_ENABLED(INFO)) { std::stringstream ss; for (size_t i = 0; nv[i]; i += 2) { ss << TTY_HTTP_HD << nv[i] << TTY_RST << ": " << nv[i + 1] << "\n"; } ULOG(INFO, upstream) << "HTTP request headers. stream_id=" << downstream->get_stream_id() << "\n" << ss.str(); } for (size_t i = 0; nv[i]; i += 2) { downstream->add_request_header(nv[i], nv[i + 1]); } if (downstream->index_request_headers() != 0) { if (upstream->error_reply(downstream, 400) != 0) { ULOG(FATAL, upstream) << "error_reply failed"; } return; } auto path = downstream->get_request_header(http2::HD__PATH); auto scheme = downstream->get_request_header(http2::HD__SCHEME); auto host = downstream->get_request_header(http2::HD__HOST); auto method = downstream->get_request_header(http2::HD__METHOD); bool is_connect = method && "CONNECT" == method->value; if (!path || !host || !method || !http2::non_empty_value(host) || !http2::non_empty_value(path) || !http2::non_empty_value(method) || (!is_connect && (!scheme || !http2::non_empty_value(scheme)))) { upstream->rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); return; } downstream->set_request_method(method->value); if (is_connect) { downstream->set_request_http2_authority(path->value); } else { downstream->set_request_http2_scheme(scheme->value); downstream->set_request_http2_authority(host->value); downstream->set_request_path(path->value); } if (!(frame->syn_stream.hd.flags & SPDYLAY_CTRL_FLAG_FIN)) { downstream->set_request_http2_expect_body(true); } downstream->inspect_http2_request(); downstream->set_request_state(Downstream::HEADER_COMPLETE); if (frame->syn_stream.hd.flags & SPDYLAY_CTRL_FLAG_FIN) { if (!downstream->validate_request_bodylen()) { upstream->rst_stream(downstream, SPDYLAY_PROTOCOL_ERROR); return; } downstream->disable_upstream_rtimer(); downstream->set_request_state(Downstream::MSG_COMPLETE); } upstream->start_downstream(downstream); break; } default: break; } } } // namespace void SpdyUpstream::start_downstream(Downstream *downstream) { auto next_downstream = downstream_queue_.pop_pending(downstream->get_stream_id()); assert(next_downstream); if (downstream_queue_.can_activate( downstream->get_request_http2_authority())) { initiate_downstream(std::move(next_downstream)); return; } downstream_queue_.add_blocked(std::move(next_downstream)); } void SpdyUpstream::initiate_downstream(std::unique_ptr<Downstream> downstream) { int rv = downstream->attach_downstream_connection( handler_->get_downstream_connection()); if (rv != 0) { // If downstream connection fails, issue RST_STREAM. rst_stream(downstream.get(), SPDYLAY_INTERNAL_ERROR); downstream->set_request_state(Downstream::CONNECT_FAIL); downstream_queue_.add_failure(std::move(downstream)); return; } rv = downstream->push_request_headers(); if (rv != 0) { rst_stream(downstream.get(), SPDYLAY_INTERNAL_ERROR); downstream_queue_.add_failure(std::move(downstream)); return; } downstream_queue_.add_active(std::move(downstream)); } namespace { void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); auto downstream = upstream->find_downstream(stream_id); if (!downstream) { upstream->consume(stream_id, len); return; } downstream->reset_upstream_rtimer(); if (downstream->push_upload_data_chunk(data, len) != 0) { upstream->rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); upstream->consume(stream_id, len); return; } if (!upstream->get_flow_control()) { return; } // If connection-level window control is not enabled (e.g, // spdy/3), spdylay_session_get_recv_data_length() is always // returns 0. if (spdylay_session_get_recv_data_length(session) > std::max(SPDYLAY_INITIAL_WINDOW_SIZE, 1 << get_config()->http2_upstream_connection_window_bits)) { if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Flow control error on connection: " << "recv_window_size=" << spdylay_session_get_recv_data_length(session) << ", window_size=" << (1 << get_config()->http2_upstream_connection_window_bits); } spdylay_session_fail_session(session, SPDYLAY_GOAWAY_PROTOCOL_ERROR); return; } if (spdylay_session_get_stream_recv_data_length(session, stream_id) > std::max(SPDYLAY_INITIAL_WINDOW_SIZE, 1 << get_config()->http2_upstream_window_bits)) { if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Flow control error: recv_window_size=" << spdylay_session_get_stream_recv_data_length( session, stream_id) << ", initial_window_size=" << (1 << get_config()->http2_upstream_window_bits); } upstream->rst_stream(downstream, SPDYLAY_FLOW_CONTROL_ERROR); return; } } } // namespace namespace { void on_data_recv_callback(spdylay_session *session, uint8_t flags, int32_t stream_id, int32_t length, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); auto downstream = upstream->find_downstream(stream_id); if (downstream && (flags & SPDYLAY_DATA_FLAG_FIN)) { if (!downstream->validate_request_bodylen()) { upstream->rst_stream(downstream, SPDYLAY_PROTOCOL_ERROR); return; } downstream->disable_upstream_rtimer(); downstream->end_upload_data(); downstream->set_request_state(Downstream::MSG_COMPLETE); } } } // namespace namespace { void on_ctrl_not_send_callback(spdylay_session *session, spdylay_frame_type type, spdylay_frame *frame, int error_code, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Failed to send control frame type=" << type << ", error_code=" << error_code << ":" << spdylay_strerror(error_code); } if (type == SPDYLAY_SYN_REPLY && error_code != SPDYLAY_ERR_STREAM_CLOSED && error_code != SPDYLAY_ERR_STREAM_CLOSING) { // To avoid stream hanging around, issue RST_STREAM. auto stream_id = frame->syn_reply.stream_id; auto downstream = upstream->find_downstream(stream_id); if (downstream) { upstream->rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); } } } } // namespace namespace { void on_ctrl_recv_parse_error_callback(spdylay_session *session, spdylay_frame_type type, const uint8_t *head, size_t headlen, const uint8_t *payload, size_t payloadlen, int error_code, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Failed to parse received control frame. type=" << type << ", error_code=" << error_code << ":" << spdylay_strerror(error_code); } } } // namespace namespace { void on_unknown_ctrl_recv_callback(spdylay_session *session, const uint8_t *head, size_t headlen, const uint8_t *payload, size_t payloadlen, void *user_data) { auto upstream = static_cast<SpdyUpstream *>(user_data); if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "Received unknown control frame."; } } } // namespace namespace { // Infer upstream RST_STREAM status code from downstream HTTP/2 // error code. uint32_t infer_upstream_rst_stream_status_code(uint32_t downstream_error_code) { // Only propagate *_REFUSED_STREAM so that upstream client can // resend request. if (downstream_error_code == NGHTTP2_REFUSED_STREAM) { return SPDYLAY_REFUSED_STREAM; } else { return SPDYLAY_INTERNAL_ERROR; } } } // namespace SpdyUpstream::SpdyUpstream(uint16_t version, ClientHandler *handler) : downstream_queue_( get_config()->http2_proxy ? get_config()->downstream_connections_per_host : get_config()->downstream_proto == PROTO_HTTP ? get_config()->downstream_connections_per_frontend : 0, !get_config()->http2_proxy), handler_(handler), session_(nullptr) { spdylay_session_callbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); callbacks.send_callback = send_callback; callbacks.recv_callback = recv_callback; callbacks.on_stream_close_callback = on_stream_close_callback; callbacks.on_ctrl_recv_callback = on_ctrl_recv_callback; callbacks.on_data_chunk_recv_callback = on_data_chunk_recv_callback; callbacks.on_data_recv_callback = on_data_recv_callback; callbacks.on_ctrl_not_send_callback = on_ctrl_not_send_callback; callbacks.on_ctrl_recv_parse_error_callback = on_ctrl_recv_parse_error_callback; callbacks.on_unknown_ctrl_recv_callback = on_unknown_ctrl_recv_callback; int rv; rv = spdylay_session_server_new(&session_, version, &callbacks, this); assert(rv == 0); if (version >= SPDYLAY_PROTO_SPDY3) { int val = 1; flow_control_ = true; initial_window_size_ = 1 << get_config()->http2_upstream_window_bits; rv = spdylay_session_set_option( session_, SPDYLAY_OPT_NO_AUTO_WINDOW_UPDATE2, &val, sizeof(val)); assert(rv == 0); } else { flow_control_ = false; initial_window_size_ = 0; } // TODO Maybe call from outside? std::array<spdylay_settings_entry, 2> entry; entry[0].settings_id = SPDYLAY_SETTINGS_MAX_CONCURRENT_STREAMS; entry[0].value = get_config()->http2_max_concurrent_streams; entry[0].flags = SPDYLAY_ID_FLAG_SETTINGS_NONE; entry[1].settings_id = SPDYLAY_SETTINGS_INITIAL_WINDOW_SIZE; entry[1].value = initial_window_size_; entry[1].flags = SPDYLAY_ID_FLAG_SETTINGS_NONE; rv = spdylay_submit_settings(session_, SPDYLAY_FLAG_SETTINGS_NONE, entry.data(), entry.size()); assert(rv == 0); if (version >= SPDYLAY_PROTO_SPDY3_1 && get_config()->http2_upstream_connection_window_bits > 16) { int32_t delta = (1 << get_config()->http2_upstream_connection_window_bits) - SPDYLAY_INITIAL_WINDOW_SIZE; rv = spdylay_submit_window_update(session_, 0, delta); assert(rv == 0); } handler_->reset_upstream_read_timeout( get_config()->http2_upstream_read_timeout); handler_->signal_write(); } SpdyUpstream::~SpdyUpstream() { spdylay_session_del(session_); } int SpdyUpstream::on_read() { int rv = 0; rv = spdylay_session_recv(session_); if (rv < 0) { if (rv != SPDYLAY_ERR_EOF) { ULOG(ERROR, this) << "spdylay_session_recv() returned error: " << spdylay_strerror(rv); } return rv; } handler_->signal_write(); return 0; } // After this function call, downstream may be deleted. int SpdyUpstream::on_write() { int rv = 0; rv = spdylay_session_send(session_); if (rv != 0) { ULOG(ERROR, this) << "spdylay_session_send() returned error: " << spdylay_strerror(rv); return rv; } if (spdylay_session_want_read(session_) == 0 && spdylay_session_want_write(session_) == 0 && handler_->get_wb()->rleft() == 0) { if (LOG_ENABLED(INFO)) { ULOG(INFO, this) << "No more read/write for this SPDY session"; } return -1; } return 0; } ClientHandler *SpdyUpstream::get_client_handler() const { return handler_; } int SpdyUpstream::downstream_read(DownstreamConnection *dconn) { auto downstream = dconn->get_downstream(); if (downstream->get_request_state() == Downstream::STREAM_CLOSED) { // If upstream SPDY stream was closed, we just close downstream, // because there is no consumer now. Downstream connection is also // closed in this case. remove_downstream(downstream); // downstrea was deleted return 0; } if (downstream->get_response_state() == Downstream::MSG_RESET) { // The downstream stream was reset (canceled). In this case, // RST_STREAM to the upstream and delete downstream connection // here. Deleting downstream will be taken place at // on_stream_close_callback. rst_stream(downstream, infer_upstream_rst_stream_status_code( downstream->get_response_rst_stream_error_code())); downstream->pop_downstream_connection(); dconn = nullptr; } else if (downstream->get_response_state() == Downstream::MSG_BAD_HEADER) { if (error_reply(downstream, 502) != 0) { return -1; } downstream->pop_downstream_connection(); // dconn was deleted dconn = nullptr; } else { auto rv = downstream->on_read(); if (rv == SHRPX_ERR_EOF) { return downstream_eof(dconn); } if (rv != 0) { if (rv != SHRPX_ERR_NETWORK) { if (LOG_ENABLED(INFO)) { DCLOG(INFO, dconn) << "HTTP parser failure"; } } return downstream_error(dconn, Downstream::EVENT_ERROR); } // Detach downstream connection early so that it could be reused // without hitting server's request timeout. if (downstream->get_response_state() == Downstream::MSG_COMPLETE && !downstream->get_response_connection_close()) { // Keep-alive downstream->detach_downstream_connection(); } } handler_->signal_write(); // At this point, downstream may be deleted. return 0; } int SpdyUpstream::downstream_write(DownstreamConnection *dconn) { int rv; rv = dconn->on_write(); if (rv == SHRPX_ERR_NETWORK) { return downstream_error(dconn, Downstream::EVENT_ERROR); } if (rv != 0) { return -1; } return 0; } int SpdyUpstream::downstream_eof(DownstreamConnection *dconn) { auto downstream = dconn->get_downstream(); if (LOG_ENABLED(INFO)) { DCLOG(INFO, dconn) << "EOF. stream_id=" << downstream->get_stream_id(); } if (downstream->get_request_state() == Downstream::STREAM_CLOSED) { // If stream was closed already, we don't need to send reply at // the first place. We can delete downstream. remove_downstream(downstream); // downstream was deleted return 0; } // Delete downstream connection. If we don't delete it here, it will // be pooled in on_stream_close_callback. downstream->pop_downstream_connection(); // dconn was deleted dconn = nullptr; // downstream wil be deleted in on_stream_close_callback. if (downstream->get_response_state() == Downstream::HEADER_COMPLETE) { // Server may indicate the end of the request by EOF if (LOG_ENABLED(INFO)) { ULOG(INFO, this) << "Downstream body was ended by EOF"; } downstream->set_response_state(Downstream::MSG_COMPLETE); // For tunneled connection, MSG_COMPLETE signals // downstream_data_read_callback to send RST_STREAM after pending // response body is sent. This is needed to ensure that RST_STREAM // is sent after all pending data are sent. on_downstream_body_complete(downstream); } else if (downstream->get_response_state() != Downstream::MSG_COMPLETE) { // If stream was not closed, then we set MSG_COMPLETE and let // on_stream_close_callback delete downstream. if (error_reply(downstream, 502) != 0) { return -1; } } handler_->signal_write(); // At this point, downstream may be deleted. return 0; } int SpdyUpstream::downstream_error(DownstreamConnection *dconn, int events) { auto downstream = dconn->get_downstream(); if (LOG_ENABLED(INFO)) { if (events & Downstream::EVENT_ERROR) { DCLOG(INFO, dconn) << "Downstream network/general error"; } else { DCLOG(INFO, dconn) << "Timeout"; } if (downstream->get_upgraded()) { DCLOG(INFO, dconn) << "Note: this is tunnel connection"; } } if (downstream->get_request_state() == Downstream::STREAM_CLOSED) { remove_downstream(downstream); // downstream was deleted return 0; } // Delete downstream connection. If we don't delete it here, it will // be pooled in on_stream_close_callback. downstream->pop_downstream_connection(); // dconn was deleted dconn = nullptr; if (downstream->get_response_state() == Downstream::MSG_COMPLETE) { // For SSL tunneling, we issue RST_STREAM. For other types of // stream, we don't have to do anything since response was // complete. if (downstream->get_upgraded()) { // We want "NO_ERROR" error code but SPDY does not have such // code for RST_STREAM. rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); } } else { if (downstream->get_response_state() == Downstream::HEADER_COMPLETE) { if (downstream->get_upgraded()) { on_downstream_body_complete(downstream); } else { rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); } } else { unsigned int status; if (events & Downstream::EVENT_TIMEOUT) { status = 504; } else { status = 502; } if (error_reply(downstream, status) != 0) { return -1; } } downstream->set_response_state(Downstream::MSG_COMPLETE); } handler_->signal_write(); // At this point, downstream may be deleted. return 0; } int SpdyUpstream::rst_stream(Downstream *downstream, int status_code) { if (LOG_ENABLED(INFO)) { ULOG(INFO, this) << "RST_STREAM stream_id=" << downstream->get_stream_id(); } int rv; rv = spdylay_submit_rst_stream(session_, downstream->get_stream_id(), status_code); if (rv < SPDYLAY_ERR_FATAL) { ULOG(FATAL, this) << "spdylay_submit_rst_stream() failed: " << spdylay_strerror(rv); DIE(); } return 0; } namespace { ssize_t spdy_data_read_callback(spdylay_session *session, int32_t stream_id, uint8_t *buf, size_t length, int *eof, spdylay_data_source *source, void *user_data) { auto downstream = static_cast<Downstream *>(source->ptr); auto upstream = static_cast<SpdyUpstream *>(downstream->get_upstream()); auto body = downstream->get_response_buf(); assert(body); auto dconn = downstream->get_downstream_connection(); if (body->rleft() == 0 && dconn && downstream->get_response_state() != Downstream::MSG_COMPLETE) { // Try to read more if buffer is empty. This will help small // buffer and make priority handling a bit better. if (upstream->downstream_read(dconn) != 0) { return SPDYLAY_ERR_CALLBACK_FAILURE; } } auto nread = body->remove(buf, length); auto body_empty = body->rleft() == 0; if (nread == 0 && downstream->get_response_state() == Downstream::MSG_COMPLETE) { if (!downstream->get_upgraded()) { *eof = 1; } else { // For tunneling, issue RST_STREAM to finish the stream. if (LOG_ENABLED(INFO)) { ULOG(INFO, upstream) << "RST_STREAM to tunneled stream stream_id=" << stream_id; } upstream->rst_stream( downstream, infer_upstream_rst_stream_status_code( downstream->get_response_rst_stream_error_code())); } } if (body_empty) { downstream->disable_upstream_wtimer(); } else { downstream->reset_upstream_wtimer(); } if (nread > 0 && downstream->resume_read(SHRPX_NO_BUFFER, nread) != 0) { return SPDYLAY_ERR_CALLBACK_FAILURE; } if (nread == 0 && *eof != 1) { return SPDYLAY_ERR_DEFERRED; } if (nread > 0) { downstream->add_response_sent_bodylen(nread); } return nread; } } // namespace int SpdyUpstream::error_reply(Downstream *downstream, unsigned int status_code) { int rv; auto html = http::create_error_html(status_code); downstream->set_response_http_status(status_code); auto body = downstream->get_response_buf(); body->append(html.c_str(), html.size()); downstream->set_response_state(Downstream::MSG_COMPLETE); spdylay_data_provider data_prd; data_prd.source.ptr = downstream; data_prd.read_callback = spdy_data_read_callback; std::string content_length = util::utos(html.size()); std::string status_string = http2::get_status_string(status_code); const char *nv[] = {":status", status_string.c_str(), ":version", "http/1.1", "content-type", "text/html; charset=UTF-8", "server", get_config()->server_name, "content-length", content_length.c_str(), nullptr}; rv = spdylay_submit_response(session_, downstream->get_stream_id(), nv, &data_prd); if (rv < SPDYLAY_ERR_FATAL) { ULOG(FATAL, this) << "spdylay_submit_response() failed: " << spdylay_strerror(rv); return -1; } return 0; } Downstream *SpdyUpstream::add_pending_downstream(int32_t stream_id, int32_t priority) { auto downstream = make_unique<Downstream>(this, stream_id, priority); auto res = downstream.get(); downstream_queue_.add_pending(std::move(downstream)); return res; } void SpdyUpstream::remove_downstream(Downstream *downstream) { if (downstream->accesslog_ready()) { handler_->write_accesslog(downstream); } auto next_downstream = downstream_queue_.remove_and_pop_blocked(downstream->get_stream_id()); if (next_downstream) { initiate_downstream(std::move(next_downstream)); } } Downstream *SpdyUpstream::find_downstream(int32_t stream_id) { return downstream_queue_.find(stream_id); } spdylay_session *SpdyUpstream::get_http2_session() { return session_; } // WARNING: Never call directly or indirectly spdylay_session_send or // spdylay_session_recv. These calls may delete downstream. int SpdyUpstream::on_downstream_header_complete(Downstream *downstream) { if (downstream->get_non_final_response()) { // SPDY does not support non-final response. We could send it // with HEADERS and final response in SYN_REPLY, but it is not // official way. downstream->clear_response_headers(); return 0; } if (LOG_ENABLED(INFO)) { DLOG(INFO, downstream) << "HTTP response header completed"; } if (!get_config()->http2_proxy && !get_config()->client_proxy && !get_config()->no_location_rewrite) { downstream->rewrite_location_response_header( get_client_handler()->get_upstream_scheme(), get_config()->port); } size_t nheader = downstream->get_response_headers().size(); // 8 means server, :status, :version and possible via header field. auto nv = make_unique<const char *[]>( nheader * 2 + 8 + get_config()->add_response_headers.size() * 2 + 1); size_t hdidx = 0; std::string via_value; std::string status_string = http2::get_status_string(downstream->get_response_http_status()); nv[hdidx++] = ":status"; nv[hdidx++] = status_string.c_str(); nv[hdidx++] = ":version"; nv[hdidx++] = "HTTP/1.1"; for (auto &hd : downstream->get_response_headers()) { if (hd.name.empty() || hd.name.c_str()[0] == ':') { continue; } auto token = http2::lookup_token(hd.name); switch (token) { case http2::HD_CONNECTION: case http2::HD_KEEP_ALIVE: case http2::HD_PROXY_CONNECTION: case http2::HD_TRANSFER_ENCODING: case http2::HD_VIA: case http2::HD_SERVER: continue; } nv[hdidx++] = hd.name.c_str(); nv[hdidx++] = hd.value.c_str(); } if (!get_config()->http2_proxy && !get_config()->client_proxy) { nv[hdidx++] = "server"; nv[hdidx++] = get_config()->server_name; } else { auto server = downstream->get_response_header(http2::HD_SERVER); if (server) { nv[hdidx++] = "server"; nv[hdidx++] = server->value.c_str(); } } auto via = downstream->get_response_header(http2::HD_VIA); if (get_config()->no_via) { if (via) { nv[hdidx++] = "via"; nv[hdidx++] = via->value.c_str(); } } else { if (via) { via_value = via->value; via_value += ", "; } via_value += http::create_via_header_value( downstream->get_response_major(), downstream->get_response_minor()); nv[hdidx++] = "via"; nv[hdidx++] = via_value.c_str(); } for (auto &p : get_config()->add_response_headers) { nv[hdidx++] = p.first.c_str(); nv[hdidx++] = p.second.c_str(); } nv[hdidx++] = 0; if (LOG_ENABLED(INFO)) { std::stringstream ss; for (size_t i = 0; nv[i]; i += 2) { ss << TTY_HTTP_HD << nv[i] << TTY_RST << ": " << nv[i + 1] << "\n"; } ULOG(INFO, this) << "HTTP response headers. stream_id=" << downstream->get_stream_id() << "\n" << ss.str(); } spdylay_data_provider data_prd; data_prd.source.ptr = downstream; data_prd.read_callback = spdy_data_read_callback; int rv; rv = spdylay_submit_response(session_, downstream->get_stream_id(), nv.get(), &data_prd); if (rv != 0) { ULOG(FATAL, this) << "spdylay_submit_response() failed"; return -1; } return 0; } // WARNING: Never call directly or indirectly spdylay_session_send or // spdylay_session_recv. These calls may delete downstream. int SpdyUpstream::on_downstream_body(Downstream *downstream, const uint8_t *data, size_t len, bool flush) { auto body = downstream->get_response_buf(); body->append(data, len); if (flush) { spdylay_session_resume_data(session_, downstream->get_stream_id()); downstream->ensure_upstream_wtimer(); } return 0; } // WARNING: Never call directly or indirectly spdylay_session_send or // spdylay_session_recv. These calls may delete downstream. int SpdyUpstream::on_downstream_body_complete(Downstream *downstream) { if (LOG_ENABLED(INFO)) { DLOG(INFO, downstream) << "HTTP response completed"; } if (!downstream->validate_response_bodylen()) { rst_stream(downstream, SPDYLAY_PROTOCOL_ERROR); downstream->set_response_connection_close(true); return 0; } spdylay_session_resume_data(session_, downstream->get_stream_id()); downstream->ensure_upstream_wtimer(); return 0; } bool SpdyUpstream::get_flow_control() const { return flow_control_; } void SpdyUpstream::pause_read(IOCtrlReason reason) {} int SpdyUpstream::resume_read(IOCtrlReason reason, Downstream *downstream, size_t consumed) { if (get_flow_control()) { assert(downstream->get_request_datalen() >= consumed); if (consume(downstream->get_stream_id(), consumed) != 0) { return -1; } downstream->dec_request_datalen(consumed); } handler_->signal_write(); return 0; } int SpdyUpstream::on_downstream_abort_request(Downstream *downstream, unsigned int status_code) { int rv; rv = error_reply(downstream, status_code); if (rv != 0) { return -1; } handler_->signal_write(); return 0; } int SpdyUpstream::consume(int32_t stream_id, size_t len) { int rv; rv = spdylay_session_consume(session_, stream_id, len); if (rv != 0) { ULOG(WARN, this) << "spdylay_session_consume() returned error: " << spdylay_strerror(rv); return -1; } return 0; } int SpdyUpstream::on_timeout(Downstream *downstream) { if (LOG_ENABLED(INFO)) { ULOG(INFO, this) << "Stream timeout stream_id=" << downstream->get_stream_id(); } rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); return 0; } void SpdyUpstream::on_handler_delete() { for (auto &ent : downstream_queue_.get_active_downstreams()) { if (ent.second->accesslog_ready()) { handler_->write_accesslog(ent.second.get()); } } } int SpdyUpstream::on_downstream_reset(bool no_retry) { int rv; for (auto &ent : downstream_queue_.get_active_downstreams()) { auto downstream = ent.second.get(); if ((downstream->get_request_state() != Downstream::HEADER_COMPLETE && downstream->get_request_state() != Downstream::MSG_COMPLETE) || downstream->get_response_state() != Downstream::INITIAL) { rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); downstream->pop_downstream_connection(); continue; } downstream->pop_downstream_connection(); downstream->add_retry(); if (no_retry || downstream->no_more_retry()) { if (on_downstream_abort_request(downstream, 503) != 0) { return -1; } return 0; } // downstream connection is clean; we can retry with new // downstream connection. rv = downstream->attach_downstream_connection( handler_->get_downstream_connection()); if (rv != 0) { rst_stream(downstream, SPDYLAY_INTERNAL_ERROR); downstream->pop_downstream_connection(); continue; } } handler_->signal_write(); return 0; } MemchunkPool *SpdyUpstream::get_mcpool() { return &mcpool_; } } // namespace shrpx
[ "tatsuhiro.t@gmail.com" ]
tatsuhiro.t@gmail.com
1aea78d1335f704f7072e7d724beedd93b08dad6
875e7de8cf26033fabfa511a2045ae9377da5679
/src/JSONAdapterInterface/IJSONSchemaValidator.h
96c72a1646d4fbc17e6ec9e0a47dff575fee3e4b
[]
no_license
jonasrodriguez/seed-cpp
ca2d62a3de622fe797ac481061529ee34b4f7387
375efd271ab5022937d103caffc993e5ed87ccb7
refs/heads/master
2020-04-23T16:50:37.899364
2019-02-28T10:13:09
2019-02-28T10:13:09
171,311,826
1
0
null
2019-02-18T15:50:41
2019-02-18T15:50:41
null
UTF-8
C++
false
false
269
h
#pragma once #include <string> namespace systelab { namespace json_adapter { class IJSONDocument; class IJSONSchemaValidator { public: virtual ~IJSONSchemaValidator() {}; virtual bool validate(const IJSONDocument&, std::string& reason) const = 0; }; }}
[ "36737101+joaquimvila@users.noreply.github.com" ]
36737101+joaquimvila@users.noreply.github.com
2d8b50d257686aea1d8aadc792ecc093d03b0b72
7d26e96f1dab6955fc96cf0eb69018deb8a31fe7
/source/engine/adl_physics/adl_bullet/adlBullet_physics.h
8a786f4d1b105773b7f82efcb235f478b327b508
[ "MIT" ]
permissive
AtakanFire/adlGame
9220d3ea98e6e7ff9cf996bd9f38eac968253c42
d617988b166c1cdd50dd7acb26507231a502a537
refs/heads/master
2020-04-03T12:37:47.862949
2019-06-14T17:38:28
2019-06-14T17:38:28
155,257,817
0
0
null
null
null
null
UTF-8
C++
false
false
3,488
h
#ifndef adl_bullet_physics_h__ #define adl_bullet_physics_h__ #pragma warning(push, 0) #include "btBulletCollisionCommon.h" #include "btBulletDynamicsCommon.h" #pragma warning(pop) #include "../adlIPhysics.h" #include "adlBullet_debug_drawer.h" #include <map> #include <set> class adlBullet_physics : public adlIPhysics { public: adlBullet_physics(); virtual ~adlBullet_physics(); virtual bool initialize() override; virtual void sync_physics_to_rendering() override; virtual void update(float dt) override; virtual void sync_scene() override; virtual void add_box(adlBounding_box bb, adlTransform initial_transform, adlEntity_shared_ptr entity) override; virtual void add_sphere(float radius, adlTransform initial_transform, adlEntity_shared_ptr entity) override; virtual void add_terrain(const std::vector<float>& heightfield, int width, int height) override; virtual void add_static_plane() override; virtual void remove_collision_object(btCollisionObject* obj); virtual void remove_entity(adlEntity_shared_ptr entity) override; virtual void apply_force(const adlVec3& direction, float newtons, adlEntity_shared_ptr entity) override; virtual void apply_torque(const adlVec3& direction, float magnitude, adlEntity_shared_ptr entity) override; virtual void kinematic_move(adlTransform transform, adlEntity_shared_ptr entity) override; virtual void stop(adlEntity_shared_ptr entity) override; virtual void set_static(adlEntity_shared_ptr entity, bool is_static) override; virtual const adlTransform& get_transform(adlEntity_shared_ptr entity) override; virtual adlVec3 get_velocity(adlEntity_shared_ptr entity) override; virtual void set_velocity(adlEntity_shared_ptr entity, const adlVec3& velocity) override; virtual adlVec3 get_angular_velocity(adlEntity_shared_ptr entity) override; virtual void set_angular_velocity(adlEntity_shared_ptr entity, const adlVec3& velocity) override; //Do not call these functions multiple times for the same ray. virtual std::vector<adlEntity_shared_ptr> get_all_raycast_hits(adlRay ray) override; virtual adlEntity_shared_ptr get_first_raycast_hit(adlRay ray) override; virtual void render_diagnostics() override; protected: static void bullet_internal_tick_callback(btDynamicsWorld* const world, btScalar const time_step); private: btDynamicsWorld* dynamics_world_; btBroadphaseInterface* broadphase_; btCollisionDispatcher* dispatcher_; btConstraintSolver* solver_; btDefaultCollisionConfiguration* collision_configuration_; btIDebugDraw* debug_drawer_; btRigidBody* terrain_body_; //Entity to body map typedef std::map<adlEntity_shared_ptr, btRigidBody*> Entity_to_body_map; Entity_to_body_map entity_to_body_map_; btRigidBody* get_body(adlEntity_shared_ptr entity) { return entity_to_body_map_[entity]; } //Body to entity map typedef std::map<btRigidBody const*, adlEntity_shared_ptr> Body_to_entity_map; Body_to_entity_map body_to_entity_map_; adlEntity_shared_ptr get_entity(btRigidBody const* body) { return body_to_entity_map_[body]; } typedef std::pair<btRigidBody const*, btRigidBody const*> Collision_pair; typedef std::set<Collision_pair> Collision_pairs; Collision_pairs previous_tick_collision_pairs_; std::vector<adlEntity_shared_ptr> previous_mouse_ray_collisions_; void add_shape(adlEntity_shared_ptr actor, btCollisionShape* shape, float mass, const std::string& material); btVector3 to_btVec3(const adlVec3& vector); }; #endif //adl_bullet_physics_h__
[ "doga.uzunali@gmail.com" ]
doga.uzunali@gmail.com
bba595fd6c3f5daa73ee5a339fe3684ce3fa327e
b965f7b94a52fcdc698a4d5ff8fc3d7f98c0259d
/prata.14.2.definitions.cpp
f1d8d58c6cdaa8e9e7336bbd14a6d3dc89ab1ba5
[]
no_license
gevorghakobyan/prata-solutions
22122fa28608c71ab4e10e5bbcd77c5321ebbc99
94c448058cd782bdb2f1199b230b681d5e9ea151
refs/heads/master
2020-03-16T15:15:22.285284
2018-11-23T07:06:58
2018-11-23T07:06:58
132,735,296
1
0
null
null
null
null
UTF-8
C++
false
false
1,198
cpp
#include "prata.14.2.h" template<class T1, class T2> T1 & Pair<T1, T2>::first() { return a; }; template<class T1, class T2> T2 & Pair<T1, T2>::second() { return b; }; Wine::Wine() : name("no name"), year_num(0), PairArray(ArrayInt(0), ArrayInt(0)) { }; Wine::Wine(const char * l, int y) : name(l), year_num(y), PairArray(ArrayInt(year_num), ArrayInt(year_num)) { }; Wine::Wine(const char * l, int y, const int yr[], const int bot[]) : PairArray(ArrayInt(yr, y), ArrayInt(bot, y)), name(l), year_num(y) { }; void Wine::GetBottles() { std::cout << "Enter " << Label() << " data for " << year_num << " year(s):" << std::endl; for (int i = 0; i < year_num; ++i) { std::cout << "Enter year: "; std::cin >> first()[i]; std::cout << "Enter bottles for that year: "; std::cin >> second()[i]; }; }; int Wine::sum() { int sum = 0; for (int i = year_num - 1; i > -1; --i) { sum += second()[i]; }; return sum; }; std::string Wine::Label() { return name; }; void Wine::Show() { std::cout << "Wine: \t " << Label() << std::endl; std::cout << "Year\tBottles\n"; for (int i = 0; i < year_num; ++i) { std::cout << "\t" << first()[i] << "\t" << second()[i] << std::endl; }; };
[ "ggh1401@gmail.com" ]
ggh1401@gmail.com
482302238a67c2c6aa26c378aa7e673c916f442c
256a688878ed861dcbb534d02e02210a1b5bf1fa
/prac/linked_List/main.cpp
1f9d3b83268e6d2aa99d649a9f02ab7834a76473
[]
no_license
kakanghosh/Data-Structure
15555702726ef919ad27da82d9d8383dc4b620df
8ad57c8cdf6b5ff0a0066fa47dd6b7988294474a
refs/heads/master
2021-09-07T06:13:11.628034
2018-02-18T16:42:40
2018-02-18T16:42:40
121,969,576
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
#include <iostream> using namespace std; class node{ public: int data; node *link; }; int main() { node *new_node = new node; node *start = new_node; new_node->link = NULL; char choice; while( true ){ cout << "Enter data: "; cin >> new_node->data; cout << "Create new node? Y / N " ; cin >> choice; if( choice == 'Y' || choice == 'y' ){ new_node = new_node->link = new node; }else if ( choice == 'N' || choice == 'n' ) { new_node->link = NULL; break; } } new_node = start; while( new_node != NULL ){ cout << new_node->data << " -> "; new_node = new_node->link; } cout << "NULL" << endl; node *b = new node; node *c = new node; start = a; a->link = b; b->link = c; c->link = NULL; cin >> a->data; cin >> b->data; cin >> c->data; cout << a->data << " " << b->data << " " << c->data << endl; a->link = new node; a->link->link = new node; a->link->link->link = NULL; cin >> a->data; cin >> a->link->data; cin >> a->link->link->data; start = a; while( start != NULL ){ cout << start->data << " -> "; start = start->link; } cout << "NULL" << endl; return 0; } /// /////////////////////////////////////////////////////////////// /// /////////////Funtions are define here///////////////////// /// /////////////////////////////////////////////////////////////// node *newNode(){ }
[ "kakanghosh69@gmail.com" ]
kakanghosh69@gmail.com
76c7b29d2cc09c90b84e408225e4b08c60a234ea
7f18e34f75364ae009c9276b288a4aadad94f7be
/Engine Hack Base Min/SvcMessage.h
374ac92cc1dbcc0ac6322cba1c56a51596008235
[]
no_license
YuhBoyMatty/Engine-Hack-Base-Min
a0ae52a217af342d9e46ed9b7b0feb7d4ea58ebf
354484e70af6a9955b5462ed78cbaf9e7dbd5b67
refs/heads/master
2023-03-18T05:12:48.956517
2019-10-03T10:31:39
2019-10-03T10:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,358
h
#ifndef __SVC_MESSAGE_H__ #define __SVC_MESSAGE_H__ // SVC Hook by _or_75 #include "Main.h" class AutoOffset; extern int* MSG_ReadCount; extern int* MSG_CurrentSize; extern int* MSG_BadRead; extern int MSG_SavedReadCount; typedef void (*TEmptyCallback)(); typedef int (*HL_MSG_ReadByte)(); typedef int (*HL_MSG_ReadShort)(); typedef int (*HL_MSG_ReadLong)(); typedef float ( *HL_MSG_ReadFloat )( ); typedef char* (*HL_MSG_ReadString)(); typedef void (*HL_MSG_CBuf_AddText)(char* text); extern HL_MSG_ReadByte MSG_ReadByte; extern HL_MSG_ReadShort MSG_ReadShort; extern HL_MSG_ReadLong MSG_ReadLong; extern HL_MSG_ReadFloat MSG_ReadFloat; extern HL_MSG_ReadString MSG_ReadString; extern HL_MSG_CBuf_AddText CBuf_AddText_Orign; extern TEmptyCallback SVC_StuffText_Orign; extern TEmptyCallback SVC_SendCvarValue_Orign; extern TEmptyCallback SVC_SendCvarValue2_Orign; extern TEmptyCallback SVC_Director_Orign; extern TEmptyCallback SVC_Sound_Orign; void MSG_SaveReadCount(); void MSG_RestoreReadCount(); TEmptyCallback HookServerMsg(const unsigned Index, void* CallBack,AutoOffset* Offset); bool IsCvarGood(const char *str); bool IsCommandGood(const char *str); bool SanitizeCommands(char *str); void CBuf_AddText(char* text); void SVC_StuffText(); void SVC_SendCvarValue(); void SVC_SendCvarValue2(); void SVC_Director(); void SVC_Sound(); #endif
[ "or.75@ya.ru" ]
or.75@ya.ru
cdacac5fb2b49f471510543d14db56daf50e5e6a
c85c0de8b733431349f536ba8d68513e575f3e3a
/Revue3/ControleurDeSerre/controleurDeSerre.h
02fa176d537edc85af0c4491838d5cc186491b8e
[]
no_license
TheoMichaud/PROJET
a64f2a21c1d48425b52d2f81bf5ac0e8ef8664e8
521a0cf9002aabed77429c672b54fdf40c7fc46b
refs/heads/master
2020-06-03T00:34:21.927706
2019-06-11T11:59:34
2019-06-11T11:59:34
191,361,048
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
#ifndef CONTROLEURDESERRE_H #define CONTROLEURDESERRE_H #include <driver/gpio.h> #include <string.h> #include "timer.h" #include <WString.h> #include "BluetoothSerial.h" #include <Wire.h> #include "zone.h" class ControleurDeSerre { public: ControleurDeSerre(); ~ControleurDeSerre(); Zone *zones[4]; void Piloter(); private: String incoming; BluetoothSerial liaisonSmartphone; char commande; char carlu; char numZone; }; #endif /* CONTROLEURDESERRE_H */
[ "tmichaud@pommier4.depinfo.touchard.edu" ]
tmichaud@pommier4.depinfo.touchard.edu
9dc89f49502a742db69988e0f33e6f305470f3d7
26ad4c0310e04951bb68877576303a424341c458
/codechef/DSA learning series/CARVANS;.cpp
13f57d711ed61aec3afeb171fde35a8a28546107
[]
no_license
mohitkumartoshniwal/CompetitiveCoding
e05151072f6ae93553df6de2f26f530e1746cbd7
531dce505b1a4bf56c24eae70d7de968a92a7234
refs/heads/master
2022-06-21T04:24:22.814287
2020-05-05T19:32:31
2020-05-05T19:32:31
258,241,421
0
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
// /Carvans #include <bits/stdc++.h> using namespace std; void fastscan(int &x) { bool neg = false; register int c; x = 0; c = getchar(); if (c == '-') { neg = true; c = getchar(); } for (; (c > 47 && c < 58); c = getchar()) x = (x << 1) + (x << 3) + c - 48; if (neg) x *= -1; } #define gc getchar_unlocked void inline scanint(int *x) { register int c = gc(); *x = 0; for (; (c < 48 || c > 57); c = gc()) ; for (; c > 47 && c < 58; c = gc()) { *x = (*x << 1) + (*x << 3) + c - 48; } } int main() { // your code goes here int t; // fastscan(t); while (t--) { int n; fastscan(n); vector<int> cars(n, 0); int var; if (n == 1) { fastscan(var); printf("1 \n"); continue; } for (int i = 0; i < n; i++) { fastscan(var); cars[i] = var; } // for(int i=0;i<n;i++){ // cout<<cars[i]<<" "; // } int minspeed = cars[0], finalCount = 1; for (int i = 1; i < n; i++) { if (cars[i] <= minspeed) { finalCount++; minspeed = min(minspeed, cars[i]); } } printf("%d \n", finalCount); } return 0; }
[ "mohitkrtoshniwal.com" ]
mohitkrtoshniwal.com
d87c01abc7bbfa4511904452ccb126b6f22f184d
c4639b391b2968d3ee0a13e6ff689544087f26ac
/week-02/day-01/15 - StudentCounter/main.cpp
053dfd1a7038df936258f900d0931bde205a67d2
[]
no_license
green-fox-academy/hbence97
8174c320c4cf2fe43efd5107dacb1bf8269d1534
200704eeb822ed4d5bb4b453f3c6db2be4b7f964
refs/heads/master
2020-04-16T18:51:54.922147
2019-07-16T09:51:38
2019-07-16T09:51:38
165,837,873
0
0
null
null
null
null
UTF-8
C++
false
false
2,406
cpp
#include <iostream> #include <string> #include <vector> #include <utility> //for std::pair #include <map> std::vector<std::string> getChildrenWithMoreThanFourCandies(const std::vector<std::pair<std::string, std::map<std::string, int>>>& students) { for (int i = 0; i < students.size(); i++){ if (int i < 4) } } int sumOfAgeWithLessThanFiveCandies(const std::vector<std::pair<std::string, std::map<std::string, int>>>& students) { } int main(int argc, char* args[]) { std::vector<std::pair<std::string, std::map<std::string, int>>> students; std::map<std::string, int> TheodorData; TheodorData.insert(std::make_pair("age", 9)); TheodorData.insert(std::make_pair("candies", 2)); students.push_back(std::make_pair("Theodor", TheodorData)); std::map<std::string, int> PaulData; PaulData.insert(std::make_pair("age", 10)); PaulData.insert(std::make_pair("candies", 1)); students.push_back(std::make_pair("Paul", PaulData)); std::map<std::string, int> MarkData; MarkData.insert(std::make_pair("age", 7)); MarkData.insert(std::make_pair("candies", 3)); students.push_back(std::make_pair("Mark", MarkData)); std::map<std::string, int> PeterData; PeterData.insert(std::make_pair("age", 12)); PeterData.insert(std::make_pair("candies", 5)); students.push_back(std::make_pair("Peter", PeterData)); std::map<std::string, int> OlafData; OlafData.insert(std::make_pair("age", 12)); OlafData.insert(std::make_pair("candies", 7)); students.push_back(std::make_pair("Olaf", OlafData)); std::map<std::string, int> GeorgeData; GeorgeData.insert(std::make_pair("age", 3)); GeorgeData.insert(std::make_pair("candies", 2)); students.push_back(std::make_pair("George", GeorgeData)); // Display the following things: // - The names of students who have more than 4 candies // - The sum of the age of children who have less than 5 candies std::cout << "Children with more than 4 candies: "; std::vector<std::string> childrenWithManyCandies = getChildrenWithMoreThanFourCandies(students); for(int i = 0; i < childrenWithManyCandies.size(); ++i) { std::cout << childrenWithManyCandies[i] << " "; } std::cout << std::endl; std::cout << "Sum of those who have less than 5 candies: " << sumOfAgeWithLessThanFiveCandies(students) << std::endl; return 0; }
[ "hegyesbence@gmail.com" ]
hegyesbence@gmail.com
6efa116d89659a76507bbb93d95ae70f838ddc7e
394a26df043fac5e9e0f98da3d0e781b9fe06766
/Multifunktionstachometer_Testing/Testprogramm_Funktion_maxgesch.cpp
ded25633d278a03888b3cff3bc966ca24844ff95
[]
no_license
Viiiiet/Viet
7262eb7e2bb0e082af77fb7b5732b95e3e1f0b68
dd17daed1138a9e681849b5609d49a589c0f08c3
refs/heads/master
2021-01-19T22:08:56.082540
2017-07-19T15:38:45
2017-07-19T15:38:45
88,760,469
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,028
cpp
#include <iostream> #include "Klasse_Gesch.h" using namespace std; double maxgesch = 25; //fiktiver Wert für die Maximalgeschwindigkeit double gesch = 30; //fiktiver Wert für Geschwindigkeit double testergebnis = 0; //Speicherplatz für das Testergebnis double sollwert = 30; //Vorgabe eines Sollwertes für die Testbedingung int main() { cout << "Start des Tests" << endl; cout << endl; Gesch MG; //Erschaffen eines Objektes zum testen MG.setmaxgesch(maxgesch); //Übermitlung der fiktiven Werte an das Objekt MG MG.setgesch(gesch); testergebnis = MG.getmaxgesch(); //Aufruf der zu testenden Funktion getmaxgesch if (testergebnis <= (sollwert+0.1) && testergebnis > (sollwert-0.1)) //Bedingung für den Erfolg des Testes { //Wenn das Testergebnis inerhalb eines bestimmten cout << "Test erfolgreich" << endl; //Tolleranzbereiches von 0.1 um den sollwert liegt ist cout << endl; //der Test erfolgreich. cout << "Testergebnis ist" << testergebnis; //Testergebnis wird ausgegeben cout << endl; } else //Wenn das Testergebnis nicht stimmt führt { //dies zum Fehlschlag des Tests cout << "Test fehlgeschlagen" << endl; cout << "Testergebnis ist" << testergebnis; //Testergebnis wird ausgegeben cout << endl; } return 0; }
[ "h.le@tu-bs.de" ]
h.le@tu-bs.de
14612eb0cad27dec65ad50ea1c3191aec111f6fb
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.h
5360dce7eebf794887eb07a0985c9d243051c90f
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
1,427
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POINTER_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POINTER_HANDLER_H_ #include "base/compiler_specific.h" #include "base/memory/weak_ptr.h" #include "base/prefs/public/pref_member.h" #include "chrome/browser/chromeos/system/pointer_device_observer.h" #include "chrome/browser/ui/webui/options/options_ui.h" namespace chromeos { namespace options { // Pointer settings overlay page UI handler. class PointerHandler : public ::options::OptionsPageUIHandler, public chromeos::system::PointerDeviceObserver::Observer { public: PointerHandler(); virtual ~PointerHandler(); // OptionsPageUIHandler implementation. virtual void GetLocalizedValues(DictionaryValue* localized_strings) OVERRIDE; private: // PointerDeviceObserver implementation. virtual void TouchpadExists(bool exists) OVERRIDE; virtual void MouseExists(bool exists) OVERRIDE; // Set the title dynamically based on whether a touchpad and/or mouse is // detected. void UpdateTitle(); bool has_touchpad_; bool has_mouse_; DISALLOW_COPY_AND_ASSIGN(PointerHandler); }; } // namespace options } // namespace chromeos #endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POINTER_HANDLER_H_
[ "rjogrady@google.com" ]
rjogrady@google.com
38bc5231c98b3af8e32971ca6487864c45450b15
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/GCE2d_MakeMirror.hxx
80c81738e9641ecb0285e50add553f25dba1375a
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,288
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _GCE2d_MakeMirror_HeaderFile #define _GCE2d_MakeMirror_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _Handle_Geom2d_Transformation_HeaderFile #include <Handle_Geom2d_Transformation.hxx> #endif class Geom2d_Transformation; class gp_Pnt2d; class gp_Ax2d; class gp_Lin2d; class gp_Dir2d; //! This class implements elementary construction algorithms for a <br> //! symmetrical transformation in 2D space about a point <br> //! or axis. The result is a Geom2d_Transformation transformation. <br> //! A MakeMirror object provides a framework for: <br> //! - defining the construction of the transformation, <br> //! - implementing the construction algorithm, and <br> //! - consulting the result. <br> class GCE2d_MakeMirror { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } Standard_EXPORT GCE2d_MakeMirror(const gp_Pnt2d& Point); Standard_EXPORT GCE2d_MakeMirror(const gp_Ax2d& Axis); Standard_EXPORT GCE2d_MakeMirror(const gp_Lin2d& Line); //! Make a symetry transformation af axis defined by <br> //! <Point> and <Direc>. <br> Standard_EXPORT GCE2d_MakeMirror(const gp_Pnt2d& Point,const gp_Dir2d& Direc); //! Returns the constructed transformation. <br> Standard_EXPORT const Handle_Geom2d_Transformation& Value() const; Standard_EXPORT const Handle_Geom2d_Transformation& Operator() const; Standard_EXPORT operator Handle_Geom2d_Transformation() const; protected: private: Handle_Geom2d_Transformation TheMirror; }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
e4b0960907cde562a8b0759bc0b2af0493b4499f
f9b7dcbd841a0b3dd0fcd2f0941d498346f88599
/chrome/browser/ui/content_settings/framebust_block_browsertest.cc
22a95942fc3884f9b32c582c8d3f078213d5c122
[ "BSD-3-Clause" ]
permissive
browser-auto/chromium
58bace4173da259625cb3c4725f9d7ec6a4d2e03
36d524c252b60b059deaf7849fb6b082bee3018d
refs/heads/master
2022-11-16T12:38:05.031058
2019-11-18T12:28:56
2019-11-18T12:28:56
222,449,220
1
0
BSD-3-Clause
2019-11-18T12:55:08
2019-11-18T12:55:07
null
UTF-8
C++
false
false
14,776
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstddef> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" #include "base/optional.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/ui/blocked_content/framebust_block_tab_helper.h" #include "chrome/browser/ui/blocked_content/url_list_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/content_settings/content_setting_bubble_model.h" #include "chrome/browser/ui/content_settings/fake_owner.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_types.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/event_constants.h" #include "url/gurl.h" #if defined(OS_CHROMEOS) #include "chrome/browser/web_applications/system_web_app_manager.h" #include "chrome/browser/web_applications/web_app_provider.h" #endif namespace { const int kAllowRadioButtonIndex = 0; const int kDisallowRadioButtonIndex = 1; } // namespace class FramebustBlockBrowserTest : public InProcessBrowserTest, public UrlListManager::Observer { public: FramebustBlockBrowserTest() = default; // InProcessBrowserTest: void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); current_browser_ = InProcessBrowserTest::browser(); FramebustBlockTabHelper::FromWebContents(GetWebContents()) ->manager() ->AddObserver(this); } // UrlListManager::Observer: void BlockedUrlAdded(int32_t id, const GURL& blocked_url) override { if (!blocked_url_added_closure_.is_null()) std::move(blocked_url_added_closure_).Run(); } content::WebContents* GetWebContents() { return browser()->tab_strip_model()->GetActiveWebContents(); } FramebustBlockTabHelper* GetFramebustTabHelper() { return FramebustBlockTabHelper::FromWebContents(GetWebContents()); } void OnClick(const GURL& url, size_t index, size_t total_size) { clicked_url_ = url; clicked_index_ = index; } Browser* browser() { return current_browser_; } void CreateAndSetBrowser() { current_browser_ = CreateBrowser(browser()->profile()); } bool NavigateIframeToUrlWithoutGesture(content::WebContents* contents, const std::string iframe_id, const GURL& url) { const char kScript[] = R"( var iframe = document.getElementById('%s'); iframe.src='%s' )"; content::TestNavigationObserver load_observer(contents); bool result = content::ExecuteScriptWithoutUserGesture( contents, base::StringPrintf(kScript, iframe_id.c_str(), url.spec().c_str())); load_observer.Wait(); return result; } protected: base::Optional<GURL> clicked_url_; base::Optional<size_t> clicked_index_; base::OnceClosure blocked_url_added_closure_; Browser* current_browser_; }; // Tests that clicking an item in the list of blocked URLs trigger a navigation // to that URL. IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, ModelAllowsRedirection) { const GURL blocked_urls[] = { GURL(chrome::kChromeUIHistoryURL), GURL(chrome::kChromeUISettingsURL), GURL(chrome::kChromeUIVersionURL), }; // Signal that a blocked redirection happened. auto* helper = GetFramebustTabHelper(); for (const GURL& url : blocked_urls) { helper->AddBlockedUrl(url, base::BindOnce(&FramebustBlockBrowserTest::OnClick, base::Unretained(this))); } EXPECT_TRUE(helper->HasBlockedUrls()); // Simulate clicking on the second blocked URL. ContentSettingFramebustBlockBubbleModel framebust_block_bubble_model( browser()->content_setting_bubble_model_delegate(), GetWebContents()); EXPECT_FALSE(clicked_index_.has_value()); EXPECT_FALSE(clicked_url_.has_value()); content::TestNavigationObserver observer(GetWebContents()); framebust_block_bubble_model.OnListItemClicked(/* index = */ 1, ui::EF_LEFT_MOUSE_BUTTON); observer.Wait(); EXPECT_TRUE(clicked_index_.has_value()); EXPECT_TRUE(clicked_url_.has_value()); EXPECT_EQ(1u, clicked_index_.value()); EXPECT_EQ(GURL(chrome::kChromeUISettingsURL), clicked_url_.value()); EXPECT_FALSE(helper->HasBlockedUrls()); EXPECT_EQ(blocked_urls[1], GetWebContents()->GetLastCommittedURL()); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, AllowRadioButtonSelected) { const GURL url = embedded_test_server()->GetURL("/iframe.html"); ui_test_utils::NavigateToURL(browser(), url); // Signal that a blocked redirection happened. auto* helper = GetFramebustTabHelper(); helper->AddBlockedUrl(url, base::BindOnce(&FramebustBlockBrowserTest::OnClick, base::Unretained(this))); EXPECT_TRUE(helper->HasBlockedUrls()); HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); EXPECT_EQ(CONTENT_SETTING_BLOCK, settings_map->GetContentSetting( url, GURL(), ContentSettingsType::POPUPS, std::string())); // Create a content bubble and simulate clicking on the first radio button // before closing it. ContentSettingFramebustBlockBubbleModel framebust_block_bubble_model( browser()->content_setting_bubble_model_delegate(), GetWebContents()); std::unique_ptr<FakeOwner> owner = FakeOwner::Create( framebust_block_bubble_model, kDisallowRadioButtonIndex); owner->SetSelectedRadioOptionAndCommit(kAllowRadioButtonIndex); EXPECT_EQ(CONTENT_SETTING_ALLOW, settings_map->GetContentSetting( url, GURL(), ContentSettingsType::POPUPS, std::string())); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, DisallowRadioButtonSelected) { const GURL url = embedded_test_server()->GetURL("/iframe.html"); ui_test_utils::NavigateToURL(browser(), url); // Signal that a blocked redirection happened. auto* helper = GetFramebustTabHelper(); helper->AddBlockedUrl(url, base::BindOnce(&FramebustBlockBrowserTest::OnClick, base::Unretained(this))); EXPECT_TRUE(helper->HasBlockedUrls()); HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); EXPECT_EQ(CONTENT_SETTING_BLOCK, settings_map->GetContentSetting( url, GURL(), ContentSettingsType::POPUPS, std::string())); // Create a content bubble and simulate clicking on the second radio button // before closing it. ContentSettingFramebustBlockBubbleModel framebust_block_bubble_model( browser()->content_setting_bubble_model_delegate(), GetWebContents()); std::unique_ptr<FakeOwner> owner = FakeOwner::Create(framebust_block_bubble_model, kAllowRadioButtonIndex); owner->SetSelectedRadioOptionAndCommit(kDisallowRadioButtonIndex); EXPECT_EQ(CONTENT_SETTING_BLOCK, settings_map->GetContentSetting( url, GURL(), ContentSettingsType::POPUPS, std::string())); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, ManageButtonClicked) { #if defined(OS_CHROMEOS) web_app::WebAppProvider::Get(browser()->profile()) ->system_web_app_manager() .InstallSystemAppsForTesting(); #endif const GURL url = embedded_test_server()->GetURL("/iframe.html"); ui_test_utils::NavigateToURL(browser(), url); // Signal that a blocked redirection happened. auto* helper = GetFramebustTabHelper(); helper->AddBlockedUrl(url, base::BindOnce(&FramebustBlockBrowserTest::OnClick, base::Unretained(this))); EXPECT_TRUE(helper->HasBlockedUrls()); // Create a content bubble and simulate clicking on the second radio button // before closing it. ContentSettingFramebustBlockBubbleModel framebust_block_bubble_model( browser()->content_setting_bubble_model_delegate(), GetWebContents()); content::TestNavigationObserver navigation_observer(nullptr); navigation_observer.StartWatchingNewWebContents(); framebust_block_bubble_model.OnManageButtonClicked(); navigation_observer.Wait(); EXPECT_TRUE(base::StartsWith(navigation_observer.last_navigation_url().spec(), chrome::kChromeUISettingsURL, base::CompareCase::SENSITIVE)); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, SimpleFramebust_Blocked) { ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL("/iframe.html")); GURL child_url = embedded_test_server()->GetURL("a.com", "/title1.html"); NavigateIframeToUrlWithoutGesture(GetWebContents(), "test", child_url); content::RenderFrameHost* child = content::ChildFrameAt(GetWebContents()->GetMainFrame(), 0); EXPECT_EQ(child_url, child->GetLastCommittedURL()); GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); base::RunLoop block_waiter; blocked_url_added_closure_ = block_waiter.QuitClosure(); child->ExecuteJavaScriptForTests( base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", redirect_url.spec().c_str())), base::NullCallback()); block_waiter.Run(); EXPECT_TRUE( base::Contains(GetFramebustTabHelper()->blocked_urls(), redirect_url)); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, FramebustAllowedByGlobalSetting) { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); settings_map->SetDefaultContentSetting(ContentSettingsType::POPUPS, CONTENT_SETTING_ALLOW); // Create a new browser to test in to ensure that the render process gets the // updated content settings. CreateAndSetBrowser(); ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL("/iframe.html")); NavigateIframeToUrlWithoutGesture( GetWebContents(), "test", embedded_test_server()->GetURL("a.com", "/title1.html")); content::RenderFrameHost* child = content::ChildFrameAt(GetWebContents()->GetMainFrame(), 0); ASSERT_TRUE(child); GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); content::TestNavigationObserver observer(GetWebContents()); child->ExecuteJavaScriptForTests( base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", redirect_url.spec().c_str())), base::NullCallback()); observer.Wait(); EXPECT_TRUE(GetFramebustTabHelper()->blocked_urls().empty()); } IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, FramebustAllowedBySiteSetting) { GURL top_level_url = embedded_test_server()->GetURL("/iframe.html"); HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); settings_map->SetContentSettingDefaultScope( top_level_url, GURL(), ContentSettingsType::POPUPS, std::string(), CONTENT_SETTING_ALLOW); // Create a new browser to test in to ensure that the render process gets the // updated content settings. CreateAndSetBrowser(); ui_test_utils::NavigateToURL(browser(), top_level_url); NavigateIframeToUrlWithoutGesture( GetWebContents(), "test", embedded_test_server()->GetURL("a.com", "/title1.html")); content::RenderFrameHost* child = content::ChildFrameAt(GetWebContents()->GetMainFrame(), 0); ASSERT_TRUE(child); GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); content::TestNavigationObserver observer(GetWebContents()); child->ExecuteJavaScriptForTests( base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", redirect_url.spec().c_str())), base::NullCallback()); observer.Wait(); EXPECT_TRUE(GetFramebustTabHelper()->blocked_urls().empty()); } // Regression test for https://crbug.com/894955, where the framebust UI would // persist on subsequent navigations. IN_PROC_BROWSER_TEST_F(FramebustBlockBrowserTest, FramebustBlocked_SubsequentNavigation_NoUI) { ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL("/iframe.html")); GURL child_url = embedded_test_server()->GetURL("a.com", "/title1.html"); NavigateIframeToUrlWithoutGesture(GetWebContents(), "test", child_url); content::RenderFrameHost* child = content::ChildFrameAt(GetWebContents()->GetMainFrame(), 0); EXPECT_EQ(child_url, child->GetLastCommittedURL()); GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); base::RunLoop block_waiter; blocked_url_added_closure_ = block_waiter.QuitClosure(); child->ExecuteJavaScriptForTests( base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", redirect_url.spec().c_str())), base::NullCallback()); block_waiter.Run(); EXPECT_TRUE( base::Contains(GetFramebustTabHelper()->blocked_urls(), redirect_url)); // Now, navigate away and check that the UI went away. ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL("/title2.html")); // TODO(csharrison): Ideally we could query the actual UI here. For now, just // look at the internal state of the framebust tab helper. EXPECT_FALSE(GetFramebustTabHelper()->HasBlockedUrls()); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
fb2e06ca1c5059de37d554fe74e1b057a32d0637
011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3
/codeChef/ELEVSTRS.cpp
1942db4c12d90ff1667fb834e92f64b87b38f7b1
[]
no_license
ay2306/Competitive-Programming
34f35367de2e8623da0006135cf21ba6aec34049
8cc9d953b09212ab32b513acf874dba4fa1d2848
refs/heads/master
2021-06-26T16:46:28.179504
2021-01-24T15:32:57
2021-01-24T15:32:57
205,185,905
5
3
null
null
null
null
UTF-8
C++
false
false
417
cpp
#include<iostream> #include<math.h> using namespace std; int main(){ int t; cin >> t; while(t--){ float n,v1,v2; cin >> n >> v1 >> v2; float d_e = n; float d_s = n*sqrt(2); float t_e = n/v2; t_e*=2; float t_s = d_s/v1; if(t_s<t_e){ cout << "Stairs\n"; }else{ cout << "Elevator\n"; } } return 0; }
[ "mahajan.ayush2306@gmail.com" ]
mahajan.ayush2306@gmail.com
13891c9402c9ac0ed529ca39dcaf8244f1d7c206
b09e3db4e3d10c8f1b13564864408250261ebce0
/src/LuaTinker/lua_tinker.cpp
9a1da647bf729de18824ba71bd5af4732b514cc9
[]
no_license
cuiopen/GameServer-7
fe9a9f8970fb3034591eaaefc63c6f668fee5947
2e9e09b1d2c03dd6c908e8bad186c08e9adae816
refs/heads/master
2020-03-19T15:48:00.984575
2016-06-02T01:58:56
2016-06-02T01:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,613
cpp
// lua_tinker.cpp // // LuaTinker - Simple and light C++ wrapper for Lua. // // Copyright (c) 2005-2007 Kwon-il Lee (zupet@hitel.net) // // please check Licence.txt file for licence and legal issues. #include <iostream> #include <lua5.1/lua.h> #include <lua5.1/lualib.h> #include <lua5.1/lauxlib.h> #include "lua_tinker.h" /*---------------------------------------------------------------------------*/ /* init */ /*---------------------------------------------------------------------------*/ void lua_tinker::init(lua_State *L) { init_s64(L); init_u64(L); } /*---------------------------------------------------------------------------*/ /* __s64 */ /*---------------------------------------------------------------------------*/ static int tostring_s64(lua_State *L) { char temp[64]; sprintf(temp, "%lld", *(long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } /*---------------------------------------------------------------------------*/ static int eq_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) == 0); return 1; } /*---------------------------------------------------------------------------*/ static int lt_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) < 0); return 1; } /*---------------------------------------------------------------------------*/ static int le_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) <= 0); return 1; } /*---------------------------------------------------------------------------*/ void lua_tinker::init_s64(lua_State *L) { const char* name = "__s64"; lua_pushstring(L, name); lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_s64, 0); lua_rawset(L, -3); lua_settable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* __u64 */ /*---------------------------------------------------------------------------*/ static int tostring_u64(lua_State *L) { char temp[64]; sprintf(temp, "%lld", *(unsigned long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } /*---------------------------------------------------------------------------*/ static int eq_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) == 0); return 1; } /*---------------------------------------------------------------------------*/ static int lt_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) < 0); return 1; } /*---------------------------------------------------------------------------*/ static int le_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) <= 0); return 1; } /*---------------------------------------------------------------------------*/ void lua_tinker::init_u64(lua_State *L) { const char* name = "__u64"; lua_pushstring(L, name); lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_u64, 0); lua_rawset(L, -3); lua_settable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* excution */ /*---------------------------------------------------------------------------*/ void lua_tinker::dofile(lua_State *L, const char *filename) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if(luaL_loadfile(L, filename) == 0) { lua_pcall(L, 0, 1, errfunc); } else { print_error(L, "%s", lua_tostring(L, -1)); } lua_remove(L, errfunc); lua_pop(L, 1); } /*---------------------------------------------------------------------------*/ void lua_tinker::dostring(lua_State *L, const char* buff) { lua_tinker::dobuffer(L, buff, strlen(buff)); } /*---------------------------------------------------------------------------*/ void lua_tinker::dobuffer(lua_State *L, const char* buff, size_t len) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if(luaL_loadbuffer(L, buff, len, "lua_tinker::dobuffer()") == 0) { lua_pcall(L, 0, 1, errfunc); } else { print_error(L, "%s", lua_tostring(L, -1)); } lua_remove(L, errfunc); lua_pop(L, 1); } /*---------------------------------------------------------------------------*/ /* debug helpers */ /*---------------------------------------------------------------------------*/ static void call_stack(lua_State* L, int n) { lua_Debug ar; if(lua_getstack(L, n, &ar) == 1) { lua_getinfo(L, "nSlu", &ar); const char* indent; if(n == 0) { indent = "->\t"; lua_tinker::print_error(L, "\t<call stack>"); } else { indent = "\t"; } if(ar.name) lua_tinker::print_error(L, "%s%s() : line %d [%s : line %d]", indent, ar.name, ar.currentline, ar.source, ar.linedefined); else lua_tinker::print_error(L, "%sunknown : line %d [%s : line %d]", indent, ar.currentline, ar.source, ar.linedefined); call_stack(L, n+1); } } /*---------------------------------------------------------------------------*/ int lua_tinker::on_error(lua_State *L) { print_error(L, "%s", lua_tostring(L, -1)); call_stack(L, 0); return 0; } /*---------------------------------------------------------------------------*/ void lua_tinker::print_error(lua_State *L, const char* fmt, ...) { char text[4096]; va_list args; va_start(args, fmt); vsprintf(text, fmt, args); va_end(args); lua_pushstring(L, "_ALERT"); lua_gettable(L, LUA_GLOBALSINDEX); if(lua_isfunction(L, -1)) { lua_pushstring(L, text); lua_call(L, 1, 0); } else { printf("%s\n", text); lua_pop(L, 1); } } /*---------------------------------------------------------------------------*/ void lua_tinker::enum_stack(lua_State *L) { int top = lua_gettop(L); print_error(L, "Type:%d", top); for(int i=1; i<=lua_gettop(L); ++i) { switch(lua_type(L, i)) { case LUA_TNIL: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; case LUA_TBOOLEAN: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_toboolean(L, i)?"true":"false"); break; case LUA_TLIGHTUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TNUMBER: print_error(L, "\t%s %f", lua_typename(L, lua_type(L, i)), lua_tonumber(L, i)); break; case LUA_TSTRING: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_tostring(L, i)); break; case LUA_TTABLE: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TFUNCTION: print_error(L, "\t%s() 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TTHREAD: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; } } } /*---------------------------------------------------------------------------*/ /* read */ /*---------------------------------------------------------------------------*/ template<> char* lua_tinker::read(lua_State *L, int index) { return (char*)lua_tostring(L, index); } template<> const char* lua_tinker::read(lua_State *L, int index) { return (const char*)lua_tostring(L, index); } template<> char lua_tinker::read(lua_State *L, int index) { return (char)lua_tonumber(L, index); } template<> unsigned char lua_tinker::read(lua_State *L, int index) { return (unsigned char)lua_tonumber(L, index); } template<> short lua_tinker::read(lua_State *L, int index) { return (short)lua_tonumber(L, index); } template<> unsigned short lua_tinker::read(lua_State *L, int index) { return (unsigned short)lua_tonumber(L, index); } template<> long lua_tinker::read(lua_State *L, int index) { return (long)lua_tonumber(L, index); } template<> unsigned long lua_tinker::read(lua_State *L, int index) { return (unsigned long)lua_tonumber(L, index); } template<> int lua_tinker::read(lua_State *L, int index) { return (int)lua_tonumber(L, index); } template<> unsigned int lua_tinker::read(lua_State *L, int index) { return (unsigned int)lua_tonumber(L, index); } template<> float lua_tinker::read(lua_State *L, int index) { return (float)lua_tonumber(L, index); } template<> double lua_tinker::read(lua_State *L, int index) { return (double)lua_tonumber(L, index); } template<> bool lua_tinker::read(lua_State *L, int index) { if(lua_isboolean(L, index)) return lua_toboolean(L, index) != 0; else return lua_tonumber(L, index) != 0; } template<> void lua_tinker::read(lua_State *L, int index) { return; } template<> long long lua_tinker::read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (long long)lua_tonumber(L, index); else return *(long long*)lua_touserdata(L, index); } template<> unsigned long long lua_tinker::read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (unsigned long long)lua_tonumber(L, index); else return *(unsigned long long*)lua_touserdata(L, index); } template<> lua_tinker::table lua_tinker::read(lua_State *L, int index) { return table(L, index); } /*---------------------------------------------------------------------------*/ /* push */ /*---------------------------------------------------------------------------*/ template<> void lua_tinker::push(lua_State *L, char ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned char ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, short ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned short ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, long ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned long ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, int ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned int ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, float ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, double ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, char* ret) { lua_pushstring(L, ret); } template<> void lua_tinker::push(lua_State *L, const char* ret) { lua_pushstring(L, ret); } template<> void lua_tinker::push(lua_State *L, bool ret) { lua_pushboolean(L, ret); } template<> void lua_tinker::push(lua_State *L, lua_value* ret) { if(ret) ret->to_lua(L); else lua_pushnil(L); } template<> void lua_tinker::push(lua_State *L, long long ret) { *(long long*)lua_newuserdata(L, sizeof(long long)) = ret; lua_pushstring(L, "__s64"); lua_gettable(L, LUA_GLOBALSINDEX); lua_setmetatable(L, -2); } template<> void lua_tinker::push(lua_State *L, unsigned long long ret) { *(unsigned long long*)lua_newuserdata(L, sizeof(unsigned long long)) = ret; lua_pushstring(L, "__u64"); lua_gettable(L, LUA_GLOBALSINDEX); lua_setmetatable(L, -2); } template<> void lua_tinker::push(lua_State *L, lua_tinker::table ret) { lua_pushvalue(L, ret.m_obj->m_index); } /*---------------------------------------------------------------------------*/ /* pop */ /*---------------------------------------------------------------------------*/ template<> void lua_tinker::pop(lua_State *L) { lua_pop(L, 1); } template<> lua_tinker::table lua_tinker::pop(lua_State *L) { return table(L, lua_gettop(L)); } /*---------------------------------------------------------------------------*/ /* Tinker Class Helper */ /*---------------------------------------------------------------------------*/ static void invoke_parent(lua_State *L) { lua_pushstring(L, "__parent"); lua_rawget(L, -2); if(lua_istable(L,-1)) { lua_pushvalue(L,2); lua_rawget(L, -2); if(!lua_isnil(L,-1)) { lua_remove(L,-2); } else { lua_remove(L, -1); invoke_parent(L); lua_remove(L,-2); } } } /*---------------------------------------------------------------------------*/ int lua_tinker::meta_get(lua_State *L) { lua_getmetatable(L,1); lua_pushvalue(L,2); lua_rawget(L,-2); if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->get(L); lua_remove(L, -2); } else if(lua_isnil(L,-1)) { lua_remove(L,-1); invoke_parent(L); if(lua_isnil(L,-1)) { lua_pushfstring(L, "can't find '%s' class variable. (forgot registering class variable ?)", lua_tostring(L, 2)); lua_error(L); } } lua_remove(L,-2); return 1; } /*---------------------------------------------------------------------------*/ int lua_tinker::meta_set(lua_State *L) { lua_getmetatable(L,1); lua_pushvalue(L,2); lua_rawget(L,-2); if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->set(L); } else if(lua_isnil(L, -1)) { lua_pushvalue(L,2); lua_pushvalue(L,3); lua_rawset(L, -4); } lua_settop(L, 3); return 0; } /*---------------------------------------------------------------------------*/ void lua_tinker::push_meta(lua_State *L, const char* name) { lua_pushstring(L, name); lua_gettable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* table object on stack */ /*---------------------------------------------------------------------------*/ lua_tinker::table_obj::table_obj(lua_State* L, int index) :m_L(L) ,m_index(index) ,m_ref(0) { if(lua_isnil(m_L, m_index)) { m_pointer = NULL; lua_remove(m_L, m_index); } else { m_pointer = lua_topointer(m_L, m_index); } } lua_tinker::table_obj::~table_obj() { if(validate()) { lua_remove(m_L, m_index); } } void lua_tinker::table_obj::inc_ref() { ++m_ref; } void lua_tinker::table_obj::dec_ref() { if(--m_ref == 0) delete this; } bool lua_tinker::table_obj::validate() { if(m_pointer != NULL) { if(m_pointer == lua_topointer(m_L, m_index)) { return true; } else { int top = lua_gettop(m_L); for(int i=1; i<=top; ++i) { if(m_pointer == lua_topointer(m_L, i)) { m_index = i; return true; } } m_pointer = NULL; return false; } } else { return false; } } /*---------------------------------------------------------------------------*/ /* Table Object Holder */ /*---------------------------------------------------------------------------*/ lua_tinker::table::table(lua_State* L) { lua_newtable(L); m_obj = new table_obj(L, lua_gettop(L)); m_obj->inc_ref(); } lua_tinker::table::table(lua_State* L, const char* name) { lua_pushstring(L, name); lua_gettable(L, LUA_GLOBALSINDEX); if(lua_istable(L, -1) == 0) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, name); lua_pushvalue(L, -2); lua_settable(L, LUA_GLOBALSINDEX); } m_obj = new table_obj(L, lua_gettop(L)); } lua_tinker::table::table(lua_State* L, int index) { if(index < 0) { index = lua_gettop(L) + index + 1; } m_obj = new table_obj(L, index); m_obj->inc_ref(); } lua_tinker::table::table(const table& input) { m_obj = input.m_obj; m_obj->inc_ref(); } lua_tinker::table::~table() { m_obj->dec_ref(); } /*---------------------------------------------------------------------------*/
[ "471812013@qq.com" ]
471812013@qq.com
aafdfb0c8e6214b602da48ce8c924f2727dce5f3
6b9198b7f93ba7bb73bffd7878a3a1c5432c2882
/NendModule/Common/NendRewardItem.h
09f4527d4fe27587ea7167a6bf358e6968838300
[]
no_license
fan-ADN/nendSDK-Cocos2dx-pub
c41ee4fda11c713c6095f0d7c6755e904ac12c18
b62a0a97414cee49515d30cd370c90111127198f
refs/heads/master
2021-06-10T16:12:14.564608
2020-01-30T01:32:08
2020-01-30T01:32:08
102,311,264
0
0
null
null
null
null
UTF-8
C++
false
false
511
h
// // NendRewardItem.h // NendModuleProj // #ifndef NendRewardItem_h #define NendRewardItem_h #include <string> #include "NendVideoAdMacros.h" NS_NEND_BEGIN struct RewardItem { const std::string name_; const int amount_; RewardItem(const std::string& name, const int amount) : name_(name), amount_(amount) {}; const std::string& getName() const { return name_; } const int getAmount() const { return amount_; } }; NS_NEND_END #endif /* NendRewardItem_h */
[ "t_kinami@fancs.com" ]
t_kinami@fancs.com
0a5f9eb1aa76172d23404427e013762d6f1ee7fc
a78fb83be8e2fc90b3a185daff8b2778e0530a3e
/bucket_49/qt6-qtbase/patches/patch-src_platformsupport_input_evdevtouch_qevdevtouchhandler.cpp
1bfae7500c9211d6fd64e8b158febfb207130faf
[ "ISC" ]
permissive
kraileth/ravensource
f8cd02edd422922b6f632e4ba4e4a74bb5d560b8
bd1150741139f5cd9fc5894aa10ee9c64861ecc3
refs/heads/master
2023-03-15T01:39:59.773861
2023-02-07T18:39:44
2023-02-07T18:39:44
106,436,199
0
0
null
2017-10-10T15:32:09
2017-10-10T15:31:56
C
UTF-8
C++
false
false
354
cpp
--- src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp.orig 2022-11-16 07:54:24 UTC +++ src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp @@ -17,11 +17,7 @@ #include <mutex> -#ifdef Q_OS_FREEBSD -#include <dev/evdev/input.h> -#else #include <linux/input.h> -#endif #ifndef input_event_sec #define input_event_sec time.tv_sec
[ "draco@marino.st" ]
draco@marino.st
bb9dfd1ec2ba9d355834ca58fa389415aa8ec5f8
dbc0e3582d65bcf9d8fba29d872d6407454f9e28
/CodeForces/1263A.cpp
0f079292b1ada41b6886e47bf0f39466432c0f2a
[]
no_license
sirAdarsh/CP-files
0b7430e2146620535451e0ab8959f70047bd7ea2
8d411224293fec547a3caa2708eed351c977ebed
refs/heads/master
2023-04-05T09:07:21.554361
2021-04-08T19:57:33
2021-04-08T19:57:33
297,582,418
0
0
null
null
null
null
UTF-8
C++
false
false
789
cpp
/*----- || Hare Krishna || -----*/ /* "WHY DO WE FALL, BRUCE?" */ #include<bits/stdc++.h> #define ll long long #define endl '\n' #define elif else if #define PI 3.1415926535897932384 #define MOD 1000000007 using namespace std; char alpha[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; string s; int t; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); cin >> t; while(t--){ int a[3]; for(int i=0; i<3; i++){ cin >> a[i]; } sort(a,a+3); int s = a[1]+a[2]; int days = a[0]; s -= a[0]; a[1]=min(a[1],s/2); a[2]= s-a[1] ; days += min(a[1],a[2]); cout << days << endl; } }
[ "aksinha.dhn@gmail.com" ]
aksinha.dhn@gmail.com
69ac70146edee78a3a73b9df8a7a021a709ddfa5
9beee850d1d1df8caee011e0923cd20ae555456a
/ultrasonicSensor_Servo/ultrasonicSensor_Servo.ino
a861d687dc06c41f96ff52ae8453d02a9ae61c49
[]
no_license
Railway-RMUTP/Medium_2-14
11c937aa5d800461b7e585649edb2ecef8e0c4a4
e404e6be75b50839b775371b37ae4a588574930e
refs/heads/master
2022-12-04T23:56:13.917803
2020-08-21T14:00:44
2020-08-21T14:00:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,702
ino
#include <ESP32Servo.h> Servo servo1; int minUs = 1000; int maxUs = 2000; int servo1Pin = 18; const int LEDPin = 13; //กำหนด pin ที่ต้องการใช้งานคือ pin 13 const int trigPin = 26; //กำหนด pin ที่ต้องการใช้งานคือ pin 26 const int echoPin = 27; //กำหนด pin ที่ต้องการใช้งานคือ pin 27 long duration; int distance; void setup() { Serial.begin(9600); servo1.setPeriodHertz(50); servo1.attach(servo1Pin, minUs, maxUs); //Servopin 18 pinMode(LEDPin, OUTPUT); //คำสั่งที่มีไว้สำหรับกำหนดการทำงานของ pin //ให้ทำงานเป็นแบบ INPUT หรือ OUTPUT pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // Clears the trigPin digitalWrite(trigPin, LOW); //กำหนดให้ trigpin มีสถานะ low หรือไม่ทำงานเป็นเวลา 2 ไมโครวินาที delayMicroseconds(2); digitalWrite(trigPin, HIGH);//กำหนดให้ trigpin มีสถานะ high หรือทำงานเป็นเวลา 10 ไมโครวินาที delayMicroseconds(10); digitalWrite(trigPin, LOW); //กำหนดให้ trigpin มีสถานะ low หรือไม่ทำงาน duration = pulseIn(echoPin, HIGH); //อ่าน echoPin, คลื่นเสียงที่สะท้อนกลับมาเป็นไมโครวินาที distance = duration / 29 / 2; //เป็นค่าที่ได้จากการคำนวณระยะทางของเสียงที่ได้จากการสะท้อนกลับ //duration คือค่าที่ได้จาก echo นำมาหาร 29 microseconds/cm ซึ่งก็คือความเร็วของเสียง //และนำมาหารด้วย 2 อีกครั้ง เพราะใช้เวลาเดินทางเพียงครึ่งเดียว if (distance <= 10) { //เป็นการกำหนดเงื่อนไขของระยะทาง.. servo1.write(180); //ชูนิ้ว digitalWrite(LEDPin, HIGH); //กำหนดให้มีสถานะ logic เป็น1(high = ไฟติด) //หรือ 0(low = ไฟดับ) } else { servo1.write(0); //งอนิ้ว digitalWrite(LEDPin, LOW); } Serial.print("Distance: "); Serial.println(distance); }
[ "65149622+Railway-RMUTP@users.noreply.github.com" ]
65149622+Railway-RMUTP@users.noreply.github.com
f2baafe4feaa9a5cb6f992dd1143952e49abca07
e7cdddb3f82ae553d6c53463950dd94d65e0599c
/Codeforces/mostafa-saad/6B.cpp
ebded79264103c2d589ebed8c5b6923f04c8fd1f
[]
no_license
IAMWILLROCK/Competetive-Programming
9d06aaa8efc6cf6d3ac683ac08767ab8d180a428
4b6fe6680542ee568ee25603321283afa954abe8
refs/heads/master
2023-01-28T14:09:41.640729
2020-12-10T12:50:18
2020-12-10T12:50:18
284,974,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,950
cpp
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; const int MAX_N = 1e5 + 5; const int MAX_L = 20; // ~ Log N const long long MOD = 1e9 + 7; const long long INF = 1e9 + 7; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<vi> vvi; #define LSOne(S) (S & (-S)) #define isBitSet(S, i) ((S >> i) & 1) int a[101][101]; void solve() { int n, m, target_row; target_row = 0; cin >> n >> m; char c; cin >> c; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char temp; cin >> temp; if (temp == c) target_row = i; a[i][j] = temp; } } int p_row[m]; int ans = 0; for (int i = 0; i < m; i++) { p_row[i] = a[target_row][i]; } for (int i = 0; i < n; ++i) { if (i == target_row) continue; int h, k; bool found = false; h = 0; k = m - 1; while (h < m) { if (p_row[h] == a[i][h]) { h++; continue; } if ((p_row[h] != a[i][h]) && h - 1 >= 0 && (a[i][h] != '.') && p_row[h] != '.') { if (p_row[h - 1] == a[i][h - 1]) { ans++; found = true; break; } } else break; } // cout << ans << " found: " << found << endl; if (found == false) { while (k >= 0) { if (p_row[k] == a[i][k]) { k--; continue; } if ((p_row[k] != a[i][k]) && k + 1 >= 0 && (a[i][k] != '.') && p_row[k] != '.') { if (p_row[k + 1] == a[i][k + 1]) { ans++; break; } } else break; } } } cout << ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // int tc; cin >> tc; // for (int t = 1; t <= tc; t++) { //cout << "Case #" << t << ": "; solve(); // } }
[ "sfardinhussain@gmail.com" ]
sfardinhussain@gmail.com
536c357edb75b373aa5b9f08a84c85a5ec72cb36
971869c5c84d82b0ee277f2da7a1a7d7b402371e
/ouzel/graphics/Buffer.cpp
06a2850b04fe13ee0410896da49c6cdac2b3eda9
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
chrdwhdhxtszpzclljxk/ouzel
c5938f785d850264e5f08ee66b63ae82f4d8fa55
1f538e9a0acedb18bc6e1ddb90ff7f0f4ae207d5
refs/heads/master
2021-05-15T09:24:11.335856
2017-10-23T11:21:31
2017-10-23T11:21:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,020
cpp
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "Buffer.hpp" #include "BufferResource.hpp" #include "Renderer.hpp" #include "RenderDevice.hpp" #include "core/Engine.hpp" namespace ouzel { namespace graphics { Buffer::Buffer() { resource = sharedEngine->getRenderer()->getDevice()->createBuffer(); } Buffer::~Buffer() { if (sharedEngine && resource) sharedEngine->getRenderer()->getDevice()->deleteResource(resource); } bool Buffer::init(Usage newUsage, uint32_t newFlags, uint32_t newSize) { usage = newUsage; flags = newFlags; sharedEngine->getRenderer()->executeOnRenderThread(std::bind(static_cast<bool(BufferResource::*)(Usage, uint32_t, uint32_t)>(&BufferResource::init), resource, newUsage, newFlags, newSize)); return true; } bool Buffer::init(Usage newUsage, const void* newData, uint32_t newSize, uint32_t newFlags) { return init(newUsage, std::vector<uint8_t>(static_cast<const uint8_t*>(newData), static_cast<const uint8_t*>(newData) + newSize), newFlags); } bool Buffer::init(Usage newUsage, const std::vector<uint8_t>& newData, uint32_t newFlags) { usage = newUsage; flags = newFlags; sharedEngine->getRenderer()->executeOnRenderThread(std::bind(static_cast<bool(BufferResource::*)(Buffer::Usage, const std::vector<uint8_t>&, uint32_t)>(&BufferResource::init), resource, newUsage, newData, newFlags)); return true; } bool Buffer::setData(const void* newData, uint32_t newSize) { return setData(std::vector<uint8_t>(static_cast<const uint8_t*>(newData), static_cast<const uint8_t*>(newData) + newSize)); } bool Buffer::setData(const std::vector<uint8_t>& newData) { sharedEngine->getRenderer()->executeOnRenderThread(std::bind(&BufferResource::setData, resource, newData)); return true; } } // namespace graphics } // namespace ouzel
[ "elviss@elviss.lv" ]
elviss@elviss.lv
b094274e264990f004b001191c5404f5d09a2e90
b4c73f1625352f3837ec1de69b93c7f00b382182
/lesson-1/multiple-threads.cpp
2fa5a13b6a8ad9afaec8108dda62f100d4dd5bd6
[ "MIT" ]
permissive
jbarneyVBFD/concurrency-practice
50f087e29aa96785047ab77875e3f09235dcbf86
f40cbab88a7ddaebce78385bfa6c0af2a176caba
refs/heads/master
2022-06-21T07:42:04.124292
2020-05-05T14:05:13
2020-05-05T14:05:13
256,850,980
0
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
#include <iostream> #include <vector> #include <thread> void printHello() { //perform work std::cout << "Hello from worker thread #" << std::this_thread::get_id() << std::endl; } int main() { //create threads std::vector<std::thread> threads; for (size_t i = 0; i <5; ++i) { //copying thread objects causes a compile error /* std::thread t(printHello); threads.push_back(t); */ //moving thread objects will work threads.emplace_back(std::thread(printHello)); } //do something in main std::cout << "Hello from main thread #" << std::this_thread::get_id() << std::endl; //call join on all thread objects using range based loop for (auto &t : threads) t.join(); return 0; }
[ "jfbarney1986@yahoo.com" ]
jfbarney1986@yahoo.com
1d5d5699d68405e082901bffeaf143ff8ab1b947
0df8cf14ccff38b0aad793b9b72d19422feaf5a0
/anomalousfield.cpp
5dfaf3b1ef0e8814bc35767f8447e026d78ff788
[]
no_license
kirill15/electric_field
f7e14cf6d55d8a9f2733bb1abbfb85dd7d5188a0
45e083dd5bde45a21bf0cf396e84d13bceeff25e
refs/heads/master
2016-09-06T07:21:56.515066
2014-05-30T22:30:18
2014-05-30T22:30:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,547
cpp
#include "anomalousfield.h" using namespace std; AnomalousField::AnomalousField() : grid(nullptr), matrix(nullptr), f(nullptr), v0(nullptr), v(nullptr), eps(1e-15) { } double AnomalousField::getEps() const { return eps; } void AnomalousField::setEps(double value) { eps = value; } Grid3D *AnomalousField::getGrid() const { return grid; } void AnomalousField::setGrid(Grid3D *value) { grid = value; } MatrixFEM *AnomalousField::getMatrix() const { return matrix; } void AnomalousField::setMatrix(MatrixFEM *value) { matrix = value; } /*double AnomalousField::GetUg(Coord3D p, int nvk) { return 0.0; //return 1.0 / (2.0 * M_PI * sqrt(p.x * p.x + p.y *p.y + p.z * p.z) * 0.01); //return p.x * p.x * p.y *p.y * p.z * p.z; //return exp(p.x * p.y * p.z); //return p.x * p.y * p.z; }*/ double AnomalousField::getV0(Coord3D p) { double r = sqrt((p.x - pSourcePlus.x) * (p.x - pSourcePlus.x) + (p.y - pSourcePlus.y) * (p.y - pSourcePlus.y)); Coord rz(r, p.z); double v0B = v0->getValue(rz); rz.r = sqrt((p.x - pSourceMinus.x) * (p.x - pSourceMinus.x) + (p.y - pSourceMinus.y) * (p.y - pSourceMinus.y)); double v0A = v0->getValue(rz); return v0B - v0A; } /* double AnomalousField::getF(Coord3D p, int nvk) { return 0.0; //return -2.0 * (p.y*p.y * p.z*p.z + p.x*p.x * p.z*p.z + p.x*p.x * p.y*p.y); //return -2.0 * exp(p.x * p.y * p.z) * (p.y*p.y * p.z*p.z + p.x*p.x * p.z*p.z + p.x*p.x * p.y*p.y); } */ void AnomalousField::localG_1D(double G[2][2], double h) { G[0][0] = G[1][1] = 1.0 / h; G[0][1] = G[1][0] = -G[0][0]; } void AnomalousField::localM_1D(double M[2][2], double h) { M[0][0] = M[1][1] = h / 3.0; M[0][1] = M[1][0] = h / 6.0; } void AnomalousField::firstBoundaryConditionOnFace(set<unsigned> *list, size_t startIndex, size_t stepOutside, size_t sizeInside, size_t limit, size_t stepInside) { ////////////////////////////////////////// Matrix a = matrix->matrix(); if (!limit) limit = a.n; for (size_t i = startIndex; i < limit; i += stepOutside) for (size_t j = 0; j < sizeInside; j += stepInside) { size_t index = i + j; a.di[index] = 1.0; f[index] = 0.0; // Обнуляем столбец выше элемента и строку левее него for (size_t i = a.ig[index]; i < a.ig[index + 1]; i++) a.ggl[i] = 0.0; // Обнуляем правее и ниже for (auto node = list[index].begin(); node != list[index].end(); node++) { size_t indexInIg = a.ig[*node]; // Выбираем нужный столбец while (a.jg[indexInIg] != index) indexInIg++; a.ggl[indexInIg] = 0.0; } } ////////////////////////////////////////// /* Matrix a = matrix->matrix(); if (!limit) limit = a.n; for (size_t i = startIndex; i < limit; i += stepOutside) for (size_t j = 0; j < sizeInside; j += stepInside) { size_t el = i + j; a.di[el] = 1.0; f[el] = 0.0; // Обнуляем столбец выше элемента и строку левее него for(size_t i = a.ig[el]; i < a.ig[el+1]; i++) a.ggl[i] = 0.0; // Обнуляем Aik // Обнуляем правее и ниже for(size_t i = el + 1; i < a.n; i++) { size_t left = a.ig[i], // Начальное значение левой границы поиска right = a.ig[i+1] - 1; // Начальное значение правой границы поиска while(a.jg[left] < el && left <= right) // Бинарный поиск нужного столбца (если он есть) { size_t mid = (left + right) / 2; if(a.jg[mid] < el) left = mid + 1; else right = mid; } if(a.jg[left] == el) // Проверяем, а вдруг в этом столбце вообще нет элемента a.ggl[left] = 0.0; } } */ } int AnomalousField::createGrid(string fileWithArea, string fileWithGrid, size_t fragmentation) { if (grid) delete grid; else grid = new Grid3D; // Считываем область if (grid->readArea(fileWithArea)) { cerr << "Не удалось считать область" << endl; return -1; } // Считываем разбиения области if (grid->readPartitions(fileWithGrid, fragmentation)) { cerr << "Не удалось считать разбиение области" << endl; return -1; } // Создаем сетку grid->createGrid(); return 0; } void AnomalousField::createPortrait() { if (matrix) delete matrix; else matrix = new MatrixFEM; matrix->generatePortrait(grid, 8); } double *AnomalousField::getV(unsigned &size) const { size = matrix->matrix().n; return v; } void AnomalousField::setSource(const Coord3D &plus, const Coord3D &minus) { pSourcePlus = plus; pSourceMinus = minus; } void AnomalousField::setNormalField(NormalField *v) { v0 = v; } double AnomalousField::getValue(Coord3D xyz) { Coord3D *coords = grid->xyz; size_t sizeX = grid->getSizeX(); size_t sizeY = grid->getSizeY(); size_t sizeZ = grid->getSizeZ(); if (xyz.x < coords[0].x || xyz.x > coords[sizeX - 1].x || xyz.y < coords[0].y ||xyz.y > coords[sizeX * sizeY - 1].y ||xyz.z < coords[0].z || xyz.z > coords[sizeX * sizeY * sizeZ - 1].z) throw "Point doesn't lie in the field of"; size_t sizeXY = sizeX * sizeY; // Получаем координату, которая ограничивает искомый элемент с большей стороны size_t p, s, l; /* p - индекс координаты по Х, s - по Y, l - по Z */ size_t first = 1, last = sizeX; // last - номер элемента в массиве, СЛЕДУЮЩЕГО ЗА последним while (first < last) { size_t mid = first + (last - first) / 2; if (xyz.x <= coords[mid].x) last = mid; else first = mid + 1; } p = last; first = 1, last = sizeY; while (first < last) { size_t mid = first + (last - first) / 2; if (xyz.y <= coords[mid * sizeX].y) last = mid; else first = mid + 1; } s = last * sizeX; first = 1, last = sizeZ; while (first < last) { size_t mid = first + (last - first) / 2; if (xyz.z <= coords[mid * sizeXY].z) last = mid; else first = mid + 1; } l = last * sizeXY; // for (p = 1; p < sizeX && xyz.x > coords[p].x; p++); // for (s = sizeX, i = 0; i < sizeY && xyz.y > coords[s].y; s += sizeX, i++); // for (l = sizeXY, i = 0; i < sizeZ && xyz.z > coords[l].z; l += sizeXY, i++); // Получаем глобальные номера базисных функций size_t k[8]; k[1] = (l - sizeXY) + (s - sizeX) + p; k[0] = k[1] - 1; k[3] = k[1] + sizeX; k[2] = k[3] - 1; k[4] = k[0] + sizeXY; k[5] = k[1] + sizeXY; k[6] = k[2] + sizeXY; k[7] = k[3] + sizeXY; // Считаем значения базисных функций на КЭ double h = coords[p].x - coords[p - 1].x; double X1 = (coords[p].x - xyz.x) / h; double X2 = (xyz.x - coords[p - 1].x) / h; h = coords[s].y - coords[s - 1].y; double Y1 = (coords[s].y - xyz.y) / h; double Y2 = (xyz.y - coords[s - 1].y) / h; h = coords[l].z - coords[l - 1].z; double Z1 = (coords[l].z - xyz.z) / h; double Z2 = (xyz.z - coords[l - 1].z) / h; return v[k[0]] * X1*Y1*Z1 + v[k[1]] * X2*Y1*Z1 + v[k[2]] * X1*Y2*Z1 + v[k[3]] * X2*Y2*Z1 + v[k[4]] * X1*Y1*Z2 + v[k[5]] * X2*Y1*Z2 + v[k[6]] * X1*Y2*Z2 + v[k[7]] * X2*Y2*Z2; } void AnomalousField::createLocalG(const Coord3D p[8], double *G[8][8]) { double hX = p[1].x - p[0].x; double hY = p[2].y - p[0].y; double hZ = p[4].z - p[0].z; double hyhz_hx = hY * hZ / (36.0 * hX); double hxhz_hy = hX * hZ / (36.0 * hY); double hxhy_hz = hX * hY / (36.0 * hZ); double hx_24 = hX / 24.0; double hy_24 = hY / 24.0; double hz_24 = hZ / 24.0; double K1[8][9] = {{ 4, 2, 2, 2, 4, 2, 2, 2, 4}, {-4, 2, 2, -2, 2, 1, -2, 1, 2}, { 2,-2, 1, 2,-4, 2, 1,-2, 2}, {-2,-2, 1, -2,-2, 1, -1,-1, 1}, { 2, 1,-2, 1, 2,-2, 2, 2,-4}, {-2, 1,-2, -1, 1,-1, -2, 1,-2}, { 1,-1,-1, 1,-2,-2, 1,-2,-2}, {-1,-1,-1, -1,-1,-1, -1,-1,-1}}; double K2[7][9] = {{ 4,-2,-2, -2, 4, 2, -2, 2, 4}, {-2, 2,-1, 2,-2, 1, 1,-1, 1}, { 2, 2,-1, -2,-4, 2, -1,-2, 2}, {-2,-1, 2, 1, 1,-1, 2, 1,-2}, { 2,-1, 2, -1, 2,-2, -2, 2,-4}, {-1, 1, 1, 1,-1,-1, 1,-1,-1}, { 1, 1, 1, -1,-2,-2, -1,-2,-2}}; double K3[6][9] = {{ 4,-2, 2, -2, 4,-2, 2,-2, 4}, {-4,-2, 2, 2, 2,-1, -2,-1, 2}, { 1, 1,-1, -1,-2, 2, 1, 2,-2}, {-1, 1,-1, 1,-1, 1, -1, 1,-1}, { 2,-1,-2, -1, 2, 2, 2,-2,-4}, {-2,-1,-2, 1, 1, 1, -2,-1,-2}}; double K4[5][9] = {{ 4, 2,-2, 2, 4,-2, -2,-2, 4}, {-1,-1, 1, -1,-1, 1, 1, 1,-1}, { 1,-1, 1, 1,-2, 2, -1, 2,-2}, {-2, 1, 2, -1, 1, 1, 2,-1,-2}, { 2, 1, 2, 1, 2, 2, -2,-2,-4}}; double K5[4][9] = {{ 4, 2,-2, 2, 4,-2, -2,-2, 4}, {-4, 2,-2, -2, 2,-1, 2,-1, 2}, { 2,-2,-1, 2,-4,-2, -1, 2, 2}, {-2,-2,-1, -2,-2,-1, 1, 1, 1}}; double K6[3][9] = {{ 4,-2, 2, -2, 4,-2, 2,-2, 4}, {-2, 2, 1, 2,-2,-1, -1, 1, 1}, { 2, 2, 1, -2,-4,-2, 1, 2, 2}}; double K7[2][9] = {{ 4,-2,-2, -2, 4, 2, -2, 2, 4}, {-4,-2,-2, 2, 2, 1, 2, 1, 2}}; double K8[9] = { 4, 2, 2, 2, 4, 2, 2, 2, 4}; double P[9]; P[0] = hyhz_hx; P[1] = hz_24; P[2] = hy_24; P[3] = hz_24; P[4] = hxhz_hy; P[5] = hx_24; P[6] = hy_24; P[7] = hx_24; P[8] = hxhy_hz; for (size_t i = 0; i < 8; i++) for (size_t j = 0; j < 9; j++) G[0][i][j] = K1[i][j] * P[j]; for (size_t i = 0; i < 7; i++) for (size_t j = 0; j < 9; j++) G[1][i+1][j] = K2[i][j] * P[j]; for (size_t i = 0; i < 6; i++) for (size_t j = 0; j < 9; j++) G[2][i+2][j] = K3[i][j] * P[j]; for (size_t i = 0; i < 5; i++) for (size_t j = 0; j < 9; j++) G[3][i+3][j] = K4[i][j] * P[j]; for (size_t i = 0; i < 4; i++) for (size_t j = 0; j < 9; j++) G[4][i+4][j] = K5[i][j] * P[j]; for (size_t i = 0; i < 3; i++) for (size_t j = 0; j < 9; j++) G[5][i+5][j] = K6[i][j] * P[j]; for (size_t i = 0; i < 2; i++) for (size_t j = 0; j < 9; j++) G[6][i+6][j] = K7[i][j] * P[j]; for (size_t j = 0; j < 9; j++) G[7][7][j] = K8[j] * P[j]; } void AnomalousField::createLocalF(const Coord3D p[8], int nvk, double *G[8][8], double F[]) { double *sigma = sigmas[nvk]; double sigma0 = v0->getSigma((p[4].z + p[0].z) / 2.0); double dSigma[9]; for (size_t i = 0; i < 9; i++) dSigma[i] = -sigma[i]; for (size_t i = 0; i < 9; i++) dSigma[i] += rotations[nvk][i] * sigma0; double Gd[8][8]; for (size_t i = 0; i < 8; i++) for (size_t j = i; j < 8; j++) { Gd[i][j] = 0.0; for (size_t l = 0; l < 9; l++) Gd[i][j] += G[i][j][l] * dSigma[l]; Gd[j][i] = Gd[i][j]; } // f double q0[8]; for (size_t i = 0; i < 8; i++) q0[i] = getV0(p[i]); // F=G*q0 for (size_t i = 0; i < 8; i++) { double s = 0.0; for (size_t j = 0; j < 8; j++) s += Gd[i][j] * q0[j]; F[i] = s; } } int AnomalousField::readSigma(string fileWithSigma) { int n; ifstream file(fileWithSigma); if (!file.is_open()) return -1; file >> n; sigmas = new double*[n]; rotations = new double*[n]; int num; double val; for (int i = 0; i < n; i++) { file >> num; sigmas[i] = new double[9]; for (int j = 0; j < 9; j++) { file >> val; sigmas[num - 1][j] = val; } rotations[i] = new double[9]; for (int j = 0; j < 9; j++) { file >> val; rotations[num - 1][j] = val; } } file.close(); for (int i = 0; i < n; i++) { double tmp[9]; //MT σ // σ = MT σ М for (size_t k = 0; k < 3; k++) { tmp[3 * k] = rotations[i][k] * sigmas[i][0]; tmp[3 * k + 1] = rotations[i][3 + k] * sigmas[i][4]; tmp[3 * k + 2] = rotations[i][6 + k] * sigmas[i][8]; } for (size_t k = 0; k < 3; k++) for (size_t j = 0; j < 3; j++) { double sum = 0.0; for (size_t l = 0; l < 3; l++) sum += tmp[3 * k + l] * rotations[i][j + 3 * l]; sigmas[i][3 * k + j] = sum; } // M = MT M for (size_t k = 0; k < 3; k++) for (size_t j = 0; j < 3; j++) { double sum = 0.0; for (size_t l = 0; l < 3; l++) sum += rotations[i][k + 3 * l] * rotations[i][j + 3 * l]; tmp[3 * k + j] = sum; } for (size_t k = 0; k < 9; k++) rotations[i][k] = tmp[k]; } return 0; } void AnomalousField::createGlobalSLAE() { double *G0[8][8]; // Локальная матрица жесткости (без сигм) double G[8][8]; // Локальная матрица жесткости double F[8]; // Локальный вектор правой части for (size_t i = 0; i < 8; i++) for (size_t j = i; j < 8; j++) G0[i][j] = new double[9]; // Сетка Coord3D *xyz = grid->xyz; unsigned **nvtr = grid->nvtr; unsigned *nvkat = grid->nvkat; // Выделяем память для элементов матрицы (Там же они и обнуляются) matrix->createArrays(); // Матрица Matrix a = matrix->matrix(); // Память для вектора правой части f = new double[a.n]; for (size_t i = 0; i < a.n; i++) f[i] = 0.0; // Количество узлов К.Э. unsigned countFE = grid->getCountFE(); Coord3D p[8]; // Узлы К.Э. // Цикл по конечным элементам for (size_t k = 0; k < countFE; k++) { // Узлы конечного элемента for (size_t i = 0; i < 8; i++) p[i] = xyz[nvtr[k][i]]; double *sigma = sigmas[nvkat[k]]; // Создаем локальную матрицу жесткости createLocalG(p, G0); for (size_t i = 0; i < 8; i++) for (size_t j = i; j < 8; j++) { G[i][j] = 0.0; for (size_t l = 0; l < 9; l++) G[i][j] += G0[i][j][l] * sigma[l]; } // for (size_t i = 0; i < 8; i++) // { // cout << i << ": " << endl; // for (size_t j = i; j < 8; j++) // { // cout << " " << j << ": " << endl; // for (size_t l = 0; l < 9; l++) // cout << " " << G0[i][j][l] << " "; // cout << endl; // } // } // Создаем локальный вектор правой части createLocalF(p, nvkat[k], G0, F); // Заносим матрицу жесткости в глобальную СЛАУ for(int i = 0; i < 8; i++) // Цикл по строкам локальной матрицы { a.di[nvtr[k][i]] += G[i][i]; // Диагональные элементы uint column = nvtr[k][i]; // Искомый номер столбца for(int j = i + 1; j < 8; j++) // Цикл по столбцам (верхнего треугольника) { uint left = a.ig[nvtr[k][j]]; // Начальное значение левой границы поиска uint right = a.ig[nvtr[k][j]+1] - 1; // Начальное значение правой границы поиска while(a.jg[left] != column) // Бинарный поиск нужного столбца { int mid = (left + right) / 2; if(a.jg[mid] < column) left = mid + 1; else right = mid; } a.ggl[left] += G[i][j]; } } // Заносим локальный вектор правой части в глобальный for (size_t i = 0; i < 8; i++) f[nvtr[k][i]] += F[i]; } /* f[a.n - (grid->getSizeX() * grid->getSizeY()) / 2 - 1] = 1.0; cout << "Координаты источника: " << grid->xyz[a.n - (grid->getSizeX() * grid->getSizeY()) / 2 - 1].x << " " << grid->xyz[a.n - (grid->getSizeX() * grid->getSizeY()) / 2 - 1].y << " " << grid->xyz[a.n - (grid->getSizeX() * grid->getSizeY()) / 2 - 1].z << endl; */ for (size_t i = 0; i < 8; i++) for (size_t j = i; j < 8; j++) delete[] G0[i][j]; } void AnomalousField::firstBoundaryCondition() { Matrix a = matrix->matrix(); size_t sizeX = grid->getSizeX(); size_t sizeY = grid->getSizeY(); size_t sizeXY = sizeX * sizeY; // Создание списка смежности для каждой вершины set<unsigned> *list = new set<unsigned>[a.n]; // Список смежных узлов для каждого узла в порядке возрастания size_t countFE = grid->getCountFE(); uint **nvtr = grid->getNvtr(); for (size_t i = 0; i < countFE; i++) { uint *tmp = nvtr[i]; // Для каждого узла текущего элемента... for (size_t j = 0; j < 8; j++) { // ...добавляем в список смежные с ним узлы for (size_t k = 0; k < 8; k++) { // Добавляем только те узлы, глобальный номер которых больше текущего if (tmp[k] > tmp[j]) list[tmp[j]].insert(tmp[k]); } } } // Ближняя грань firstBoundaryConditionOnFace(list, 0, sizeXY, sizeX); // Дальняя грань firstBoundaryConditionOnFace(list, sizeXY - sizeX, sizeXY, sizeX); // Левая грань firstBoundaryConditionOnFace(list, sizeX, sizeXY, sizeXY - 2 * sizeX, a.n, sizeX); // Правая грань firstBoundaryConditionOnFace(list, 2 * sizeX - 1, sizeXY, sizeXY - 2 * sizeX, a.n, sizeX); // Нижняя грань firstBoundaryConditionOnFace(list, sizeX + 1, sizeX, sizeX - 2, sizeXY - sizeX - 1); delete[] list; /* // Ближняя грань firstBoundaryConditionOnFace(0, 0, sizeXY, sizeX); // Дальняя грань firstBoundaryConditionOnFace(0, sizeXY - sizeX, sizeXY, sizeX); // Левая грань firstBoundaryConditionOnFace(0, sizeX, sizeXY, sizeXY - 2 * sizeX, a.n, sizeX); // Правая грань firstBoundaryConditionOnFace(0, 2 * sizeX - 1, sizeXY, sizeXY - 2 * sizeX, a.n, sizeX); // Нижняя грань firstBoundaryConditionOnFace(0, sizeX + 1, sizeX, sizeX - 2, sizeXY - sizeX - 1); */ // matrix->saveElements(); /* ofstream fff("fff.txt"); for (size_t i = 0; i < a.n; i++) fff << f[i] << endl; fff.close(); */ // exit(0); } void AnomalousField::solve(string method, size_t maxIter, double x0) { // Выделяем память под результат if (v) delete[] v; v = new double[matrix->matrix().n]; // Начальное приближение for (size_t i = 0; i < matrix->matrix().n; i++) v[i] = x0; // Решаем СЛАУ if (method == "MSG_LLT") SLAE::solveMSG_LLT(matrix->matrix(), f, v, eps, maxIter); else if (method == "LOS_LU") SLAE::solveLOS_LU(matrix->matrix(), f, v, eps, maxIter); }
[ "kirill.puzanov@gmail.com" ]
kirill.puzanov@gmail.com
6f1ab3fa7fb8d16021dd062dc58ca73e4f2ebe7a
fd221efb1165d56ff7007a3b82aa84b1019883e0
/C/s1/c-pract7/14.cpp
82e1fed7da6b5955f92e3556214559110199f82f
[]
no_license
CyanoFresh/KPI-Labs
822a8057a1db8f4df04e0b71b498f80dc42fd281
894332df2cc5a6eb32ce08938f7ebecf21e0dc02
refs/heads/master
2023-01-09T06:50:03.303627
2021-12-06T18:14:40
2021-12-06T18:14:40
253,018,181
0
1
null
2023-01-07T05:54:00
2020-04-04T14:28:25
JavaScript
UTF-8
C++
false
false
673
cpp
#include <iostream> #include <cstring> using namespace std; class coord { public: int x, y; // coordinate values coord() { x = 0; y = 0; } coord(int i, int j) { x = i; y = j; } void show() { cout << "x=" << x << " y=" << y << "\n"; } coord operator>>(int n) { coord tmp; tmp.x = x >> n; tmp.y = y >> n; return tmp; } coord operator<<(int n) { coord tmp; tmp.x = x << n; tmp.y = y << n; return tmp; } }; int main() { coord a(10, 10), b(2, 2), c; a.show(); a =a<<1; a.show(); a=a>>1; c.show(); }
[ "cyanofresh@gmail.com" ]
cyanofresh@gmail.com
acff755389d2b9095880d040fccd6dd3330efcd1
a9ce2d47a598119dfec8faf937e04ef5b336d6b3
/aoj/2440.cpp
a5fa57bbf3bc440d5827750c7cc665aec8efca63
[]
no_license
acomagu/competitive-programming
2f20a84d974d536fbd309d94abe12575983891fc
91e84fa2628f66a4ffaf6322fd4429246cfe3307
refs/heads/master
2021-01-17T05:49:11.952640
2017-04-25T09:55:26
2017-04-25T09:55:26
60,955,837
0
0
null
null
null
null
UTF-8
C++
false
false
868
cpp
#include <iostream> #include <unordered_set> using namespace std; class Door { public: bool isOpened; void openedBy(string id) { isOpened = true; cout << "Opened by " << id << endl; } void closedBy(string id) { isOpened = false; cout << "Closed by " << id << endl; } void toggledBy(string id) { (isOpened) ? closedBy(id) : openedBy(id); } }; int main() { unordered_set<string> registedIds; int nRegistedIds; cin >> nRegistedIds; for(int i = 0; i < nRegistedIds; ++i) { string id; cin >> id; registedIds.insert(id); } Door door; int nTryIds; cin >> nTryIds; for(int i = 0; i < nTryIds; ++i) { string id; cin >> id; if(registedIds.find(id) != registedIds.end()) { door.toggledBy(id); } else { cout << "Unknown " << id << endl; } } return 0; }
[ "acomagu@gmail.com" ]
acomagu@gmail.com
52801b7d3c2bd2d5186665f0f9cb65cc7dad4f6a
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Numerics/Statistics/test/itkSampleTest4.cxx
18ad010acc421c0a99020877f09993659560e597
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "...
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
5,983
cxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #include <iostream> #include "itkSample.h" #include "itkObjectFactory.h" #include "itkMath.h" namespace itk { namespace Statistics { namespace SampleTest { template <typename TMeasurementVector> class MySample : public Sample< TMeasurementVector > { public: /** Standard class typedef. */ typedef MySample Self; typedef Sample< TMeasurementVector > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(MySample, Sample); /** Method for creation through the object factory. */ itkNewMacro(Self); typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; typedef typename Superclass::AbsoluteFrequencyType AbsoluteFrequencyType; typedef typename Superclass::InstanceIdentifier InstanceIdentifier; /** Get the size of the sample (number of measurements) */ virtual InstanceIdentifier Size() const ITK_OVERRIDE { return static_cast<InstanceIdentifier>( m_Values.size() ); } /** Remove all measurement vectors */ virtual void Clear() { m_Values.clear(); } /** Get the measurement associated with a particular * InstanceIdentifier. */ virtual const MeasurementVectorType & GetMeasurementVector(InstanceIdentifier id) const ITK_OVERRIDE { return m_Values[id]; } /** Get the frequency of a measurement specified by instance * identifier. */ virtual AbsoluteFrequencyType GetFrequency(InstanceIdentifier id) const ITK_OVERRIDE { return m_Frequencies[id]; } /** Get the total frequency of the sample. */ virtual TotalAbsoluteFrequencyType GetTotalFrequency() const ITK_OVERRIDE { TotalAbsoluteFrequencyType sum = NumericTraits< TotalAbsoluteFrequencyType >::ZeroValue(); typedef typename std::vector< AbsoluteFrequencyType >::const_iterator Iterator; Iterator itr = m_Frequencies.begin(); while( itr != m_Frequencies.end() ) { sum += *itr; ++itr; } return sum; } void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os,indent); os << indent << m_Values.size() << std::endl; os << indent << m_Frequencies.size() << std::endl; } void AddMeasurementVector( const MeasurementVectorType & measure, AbsoluteFrequencyType frequency ) { m_Values.push_back( measure ); m_Frequencies.push_back( frequency ); } private: std::vector< TMeasurementVector > m_Values; std::vector< AbsoluteFrequencyType > m_Frequencies; }; } } } int itkSampleTest4(int, char* [] ) { const unsigned int MeasurementVectorSize = 17; typedef std::vector< float > MeasurementVectorType; typedef itk::Statistics::SampleTest::MySample< MeasurementVectorType > SampleType; SampleType::Pointer sample = SampleType::New(); std::cout << sample->GetNameOfClass() << std::endl; std::cout << sample->SampleType::Superclass::GetNameOfClass() << std::endl; sample->Print(std::cout); sample->SetMeasurementVectorSize( MeasurementVectorSize ); // for code coverage if( sample->GetMeasurementVectorSize() != MeasurementVectorSize ) { std::cerr << "GetMeasurementVectorSize() Failed !" << std::endl; return EXIT_FAILURE; } std::cout << sample->Size() << std::endl; MeasurementVectorType measure( MeasurementVectorSize ); for( unsigned int i=0; i<MeasurementVectorSize; i++) { measure[i] = 29 * i * i; } typedef SampleType::AbsoluteFrequencyType AbsoluteFrequencyType; AbsoluteFrequencyType frequency = 17; sample->AddMeasurementVector( measure, frequency ); MeasurementVectorType measureBack = sample->GetMeasurementVector( 0 ); AbsoluteFrequencyType frequencyBack = sample->GetFrequency( 0 ); if( frequencyBack != frequency ) { std::cerr << "Error in GetFrequency()" << std::endl; return EXIT_FAILURE; } for( unsigned int j=0; j<MeasurementVectorSize; j++) { if( itk::Math::NotExactlyEquals(measureBack[j], measure[j]) ) { std::cerr << "Error in Set/Get MeasurementVector()" << std::endl; return EXIT_FAILURE; } } std::cout << sample->GetTotalFrequency() << std::endl; try { sample->SetMeasurementVectorSize( MeasurementVectorSize + 5 ); std::cerr << "Sample failed to throw an exception when calling SetMeasurementVectorSize()" << std::endl; return EXIT_FAILURE; } catch( itk::ExceptionObject & excp ) { std::cout << "Expected exception caught: " << excp << std::endl; } // If we call Clear(), now we should be able to change the // MeasurementVectorSize of the Sample: sample->Clear(); try { sample->SetMeasurementVectorSize( MeasurementVectorSize + 5 ); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
0f8b2033dbe52227af8b93d0cd3d731cf8016c22
2e05ee5264a0a02149c00469db3675d07c97f439
/esp32/libraries/sensors_actors/KY_037/test/Start/src/main.cpp
0f2007dadfd7fb7b90b3a21b655fbaabb784b8b4
[]
no_license
gkoe/iotsamstag2
c41e181094f1a1d38aae93c98036f6f2bfe613e7
359f6e16578720c0124a2811737d0fb1854d7f49
refs/heads/master
2020-04-21T18:23:19.861915
2019-02-09T10:52:12
2019-02-09T10:52:12
169,767,561
5
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <Arduino.h> #include <math.h> #include <KY_037.h> KY_037 *ky_037; void setup () { Serial.begin (115200); ky_037 = new KY_037(4, 2, 30, "test", "test", "db", 5.0); } // Das Programm liest die aktuellen Werte der Eingang-Pins // und gibt diese auf der seriellen Ausgabe aus void loop () { ky_037->getMeasure(); delay(10); }
[ "gkoe@gmx.at" ]
gkoe@gmx.at
f1047f35ef722df9cca7c433a8a42e1e690a9391
67a46851a67f0a93d7312c5a9a89c942e37b73eb
/algorithm/HDU-ACM/ambition0109/1264.cpp
b10cd37ce2eb0ee1e83d6fe624115be826e148ad
[]
no_license
zhangwj0101/codestudy
e8c0a0c55b0ee556c217dc58273711a18e4194c9
06ce3bb9f9d9f977e0e4dc7687c561ab74f1980b
refs/heads/master
2021-01-15T09:28:32.054331
2016-09-17T11:11:06
2016-09-17T11:11:06
44,471,951
0
0
null
null
null
null
UTF-8
C++
false
false
2,603
cpp
////////////////////System Comment//////////////////// ////Welcome to Hangzhou Dianzi University Online Judge ////http://acm.hdu.edu.cn ////////////////////////////////////////////////////// ////Username: ambition0109 ////Nickname: Ambition ////Run ID: ////Submit time: 2010-09-14 17:54:16 ////Compiler: Visual C++ ////////////////////////////////////////////////////// ////Problem ID: 1264 ////Problem Title: ////Run result: Accept ////Run time:15MS ////Run memory:236KB //////////////////System Comment End////////////////// #include<iostream> #include<algorithm> using namespace std; struct Seg_Tree{ int left,right; int len,cvr; }STree[600]; struct Seg{ int left,right; int hight,side; }seg[20000]; bool cmp(const Seg& a,const Seg& b){ return a.hight<b.hight; } void Build(int left,int right,int idx){ STree[idx].left=left; STree[idx].right=right; STree[idx].cvr=0; STree[idx].len=0; if(left==right) return; int mid=(left+right)>>1; Build(left,mid,idx<<1); Build(mid+1,right,idx<<1|1); } void Update(int idx){ if(STree[idx].cvr){ STree[idx].len=STree[idx].right-STree[idx].left+1; }else{ if(STree[idx].left==STree[idx].right){ STree[idx].len=0; }else{ STree[idx].len=STree[idx<<1].len+STree[idx<<1|1].len; } } } void Modify(int left,int right,int idx,int val){ if(STree[idx].left==left&&STree[idx].right==right){ STree[idx].cvr+=val; Update(idx); return; } //if(STree[idx].cvr){ // STree[idx<<1].cvr=STree[idx<<1|1].cvr=STree[idx].cvr; // STree[idx<<1].len=STree[idx<<1].right-STree[idx<<1].left; // STree[idx<<1|1].len=STree[idx<<1|1].right-STree[idx<<1|1].left; // STree[idx].cvr=0; //} int mid=(STree[idx].left+STree[idx].right)>>1; if(right<=mid){ Modify(left,right,idx<<1,val); }else if(left>mid){ Modify(left,right,idx<<1|1,val); }else{ Modify(left,mid,idx<<1,val); Modify(mid+1,right,idx<<1|1,val); } Update(idx); } int main(){ int x1,x2,y1,y2,t=0; while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)!=EOF){ if(x1<0){ Build(0,100,1); sort(seg,seg+t*2,cmp); int Sum=0; for(int i=0;i<t*2-1;i++){ Modify(seg[i].left,seg[i].right-1,1,seg[i].side); Sum+=STree[1].len*(seg[i+1].hight-seg[i].hight); } printf("%d\n",Sum); t=0; if(x1==-2) break; }else{ if(x2<x1) x1^=x2^=x1^=x2; if(y2<y1) y1^=y2^=y1^=y2; seg[t<<1].left=seg[t<<1|1].left=x1; seg[t<<1].right=seg[t<<1|1].right=x2; seg[t<<1].hight=y1; seg[t<<1|1].hight=y2; seg[t<<1].side=1; seg[t<<1|1].side=-1; t++; } } }
[ "zhangwj@zhangwj-MacBook-Pro.local" ]
zhangwj@zhangwj-MacBook-Pro.local
61b36376c1c998edf52a823c65f13f06f62e2ef9
4aece520981c3a37c37bdf3f18f20e760f2e530b
/ExamPart2.cpp
12ee1e15f9c34ca06bf86dff2afa15ed21749115
[]
no_license
timegnome/Basic-C---Projects
9fd4d151c804893c3642934f9be342a00c8d2937
d1c90e76ef702eb27dadf7195995bd60e2345ae7
refs/heads/master
2020-04-21T20:02:31.965585
2019-02-09T03:38:54
2019-02-09T03:38:54
169,828,728
0
0
null
null
null
null
UTF-8
C++
false
false
6,394
cpp
// // File.cpp // Final // // Created by MMaxwell on 12/15/15. Like a Boss // Copyright (c) 2015 MMaxwell. All rights reserved. // #include <iostream> #include <string> #include <fstream> #include "Job.h" #include "Queue.h" using namespace std; void printMenu(); int main() { Job temp; Queue<Job> standardJob; Queue<Job> priorityJob; char userSelection; string description, contactName; int Phone; int Id; ifstream inFile; inFile.open("Save.txt"); if(inFile.is_open()) { while(!inFile.eof()) { inFile>>Id; //cin.ignore(); getline(inFile,description); inFile>>Phone; getline(inFile, contactName); temp.setJobID(Id); temp.setJobDescription(description); temp.setPhoneExt(Phone); temp.setContact(contactName); if(temp.getJobID() != 0 && temp.getPhoneExt() != 0) { if(standardJob.enqueue(temp)) { } else { cout<<"Failed"<<endl; } } } } else { cout<<"No Text file"<<endl; } if(standardJob.isEmpty()) { cout<<"No saved data"<<endl; } inFile.close(); while(true) { printMenu(); cin>>userSelection; userSelection = toupper(userSelection); switch (userSelection) { case 'J': { cout<<"Select standard of priority job: \nS/P?"<<endl; cin>>userSelection; if(userSelection == 'P') { cout<<"\nEnter Job Id: "; cin>>Id; cout<<"\nEnter Job description: "; cin.ignore(); getline(cin,description); cout<<"\nEnter Phone extentension: "; cin>>Phone; cout<<"\nEnter Contact name: "; cin.ignore(); getline(cin, contactName); temp.setJobID(Id); temp.setJobDescription(description); temp.setPhoneExt(Phone); temp.setContact(contactName); if(priorityJob.enqueue(temp)) { cout<<"Added to priority"<<endl; } else { cout<<"Failed to add"<<endl; } } else { cout<<"\nEnter Job Id: "; cin>>Id; cout<<"\nEnter Job description: "; cin.ignore(); getline(cin,description); cout<<"\nEnter Phone extentension: "; cin>>Phone; cout<<"\nEnter Contact name: "; cin.ignore(); getline(cin, contactName); temp.setJobID(Id); temp.setJobDescription(description); temp.setPhoneExt(Phone); temp.setContact(contactName); if(standardJob.enqueue(temp)) { cout<<"Added to standard"<<endl; } else { cout<<"Failed to add"<<endl; } } break; } case 'N': { if(priorityJob.isEmpty()) { if(standardJob.dequeue(temp)) { cout<<"Standard job"<<temp<<endl; } else { cout<<"Failed to remove/isEmpty"<<endl; } } else { if(priorityJob.dequeue(temp)) { cout<<"Priority Job"<<temp<<endl; } else { cout<<"Failed to remove/isEmpty"<<endl; } } break; } case 'Q': { ofstream outFile; outFile.open("Save.txt"); if(priorityJob.isEmpty()) { while(!standardJob.isEmpty()) { if(standardJob.dequeue(temp)) { outFile<<temp.getJobID()<<" "<<temp.getJobDescription()<<"\n"<<temp.getPhoneExt()<<" "<<temp.getContact()<<endl; } else { cout<<"Failed to remove/isEmpty"<<endl; } } } else { while(!priorityJob.isEmpty()) { if(priorityJob.dequeue(temp)) { cout<<"Priority Job"<<temp<<endl; } else { cout<<"Failed to remove/isEmpty"<<endl; } } while(!standardJob.isEmpty()) { if(standardJob.dequeue(temp)) { outFile<<temp.getJobID()<<" "<<temp.getJobDescription()<<"\n"<<temp.getPhoneExt()<<" "<<temp.getContact()<<endl; } else { cout<<"Failed to remove/isEmpty"<<endl; } } } outFile.close(); return 0; break; } default: cout<<"In valid Selection"<<endl; break; } } } void printMenu() { cout<<"J: Add a new job"<<endl; cout<<"N: Remove a job"<<endl; cout<<"Q: Quit program and Save data"<<endl; }
[ "timegnome7@gmail.com" ]
timegnome7@gmail.com
de2f1e3e4f2e672402c1da9bc6f191d5eb73d952
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/chrome/service/cloud_print/printer_job_handler.cc
4f4c3364f52e96d96c65ac23c360e716785082b4
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
32,340
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/service/cloud_print/printer_job_handler.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/location.h" #include "base/md5.h" #include "base/metrics/histogram.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/common/cloud_print/cloud_print_constants.h" #include "chrome/common/cloud_print/cloud_print_helpers.h" #include "chrome/grit/generated_resources.h" #include "chrome/service/cloud_print/cloud_print_service_helpers.h" #include "chrome/service/cloud_print/job_status_updater.h" #include "net/base/mime_util.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "printing/printing_utils.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" namespace cloud_print { namespace { base::subtle::Atomic32 g_total_jobs_started = 0; base::subtle::Atomic32 g_total_jobs_done = 0; enum PrinterJobHandlerEvent { JOB_HANDLER_CHECK_FOR_JOBS, JOB_HANDLER_START, JOB_HANDLER_PENDING_TASK, JOB_HANDLER_PRINTER_UPDATE, JOB_HANDLER_JOB_CHECK, JOB_HANDLER_JOB_STARTED, JOB_HANDLER_VALID_TICKET, JOB_HANDLER_DATA, JOB_HANDLER_SET_IN_PROGRESS, JOB_HANDLER_SET_START_PRINTING, JOB_HANDLER_START_SPOOLING, JOB_HANDLER_SPOOLED, JOB_HANDLER_JOB_COMPLETED, JOB_HANDLER_INVALID_TICKET, JOB_HANDLER_INVALID_DATA, JOB_HANDLER_MAX, }; } // namespace PrinterJobHandler::PrinterInfoFromCloud::PrinterInfoFromCloud() : current_xmpp_timeout(0), pending_xmpp_timeout(0) { } PrinterJobHandler::PrinterInfoFromCloud::PrinterInfoFromCloud( const PrinterInfoFromCloud& other) = default; PrinterJobHandler::PrinterJobHandler( const printing::PrinterBasicInfo& printer_info, const PrinterInfoFromCloud& printer_info_cloud, const GURL& cloud_print_server_url, PrintSystem* print_system, Delegate* delegate) : print_system_(print_system), printer_info_(printer_info), printer_info_cloud_(printer_info_cloud), cloud_print_server_url_(cloud_print_server_url), delegate_(delegate), local_job_id_(-1), next_json_data_handler_(NULL), next_data_handler_(NULL), print_thread_("Chrome_CloudPrintJobPrintThread"), job_handler_task_runner_(base::ThreadTaskRunnerHandle::Get()), shutting_down_(false), job_check_pending_(false), printer_update_pending_(true), task_in_progress_(false), weak_ptr_factory_(this) { } bool PrinterJobHandler::Initialize() { if (!print_system_->IsValidPrinter(printer_info_.printer_name)) return false; printer_watcher_ = print_system_->CreatePrinterWatcher( printer_info_.printer_name); printer_watcher_->StartWatching(this); CheckForJobs(kJobFetchReasonStartup); return true; } std::string PrinterJobHandler::GetPrinterName() const { return printer_info_.printer_name; } void PrinterJobHandler::CheckForJobs(const std::string& reason) { VLOG(1) << "CP_CONNECTOR: Checking for jobs" << ", printer id: " << printer_info_cloud_.printer_id << ", reason: " << reason << ", task in progress: " << task_in_progress_; UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_CHECK_FOR_JOBS, JOB_HANDLER_MAX); job_fetch_reason_ = reason; job_check_pending_ = true; if (!task_in_progress_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Start, this)); } } void PrinterJobHandler::Shutdown() { VLOG(1) << "CP_CONNECTOR: Shutting down printer job handler" << ", printer id: " << printer_info_cloud_.printer_id; Reset(); shutting_down_ = true; while (!job_status_updater_list_.empty()) { // Calling Stop() will cause the OnJobCompleted to be called which will // remove the updater object from the list. job_status_updater_list_.front()->Stop(); } } // CloudPrintURLFetcher::Delegate implementation. CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleRawResponse( const net::URLFetcher* source, const GURL& url, const net::URLRequestStatus& status, int response_code, const net::ResponseCookies& cookies, const std::string& data) { // 415 (Unsupported media type) error while fetching data from the server // means data conversion error. Stop fetching process and mark job as error. if (next_data_handler_ == (&PrinterJobHandler::HandlePrintDataResponse) && response_code == net::HTTP_UNSUPPORTED_MEDIA_TYPE) { VLOG(1) << "CP_CONNECTOR: Job failed (unsupported media type)"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::JobFailed, this, JOB_DOWNLOAD_FAILED)); return CloudPrintURLFetcher::STOP_PROCESSING; } return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleRawData( const net::URLFetcher* source, const GURL& url, const std::string& data) { if (!next_data_handler_) return CloudPrintURLFetcher::CONTINUE_PROCESSING; return (this->*next_data_handler_)(source, url, data); } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleJSONData( const net::URLFetcher* source, const GURL& url, base::DictionaryValue* json_data, bool succeeded) { DCHECK(next_json_data_handler_); return (this->*next_json_data_handler_)(source, url, json_data, succeeded); } // Mark the job fetch as failed and check if other jobs can be printed void PrinterJobHandler::OnRequestGiveUp() { if (job_queue_handler_.JobFetchFailed(job_details_.job_id_)) { VLOG(1) << "CP_CONNECTOR: Job failed to load (scheduling retry)"; CheckForJobs(kJobFetchReasonFailure); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); } else { VLOG(1) << "CP_CONNECTOR: Job failed (giving up after " << kNumRetriesBeforeAbandonJob << " retries)"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::JobFailed, this, JOB_DOWNLOAD_FAILED)); } } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::OnRequestAuthError() { // We got an Auth error and have no idea how long it will take to refresh // auth information (may take forever). We'll drop current request and // propagate this error to the upper level. After auth issues will be // resolved, GCP connector will restart. OnAuthError(); return CloudPrintURLFetcher::STOP_PROCESSING; } std::string PrinterJobHandler::GetAuthHeader() { return GetCloudPrintAuthHeaderFromStore(); } // JobStatusUpdater::Delegate implementation bool PrinterJobHandler::OnJobCompleted(JobStatusUpdater* updater) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_JOB_COMPLETED, JOB_HANDLER_MAX); UMA_HISTOGRAM_LONG_TIMES("CloudPrint.PrintingTime", base::Time::Now() - updater->start_time()); bool ret = false; base::subtle::NoBarrier_AtomicIncrement(&g_total_jobs_done, 1); job_queue_handler_.JobDone(job_details_.job_id_); for (JobStatusUpdaterList::iterator index = job_status_updater_list_.begin(); index != job_status_updater_list_.end(); index++) { if (index->get() == updater) { job_status_updater_list_.erase(index); ret = true; break; } } return ret; } void PrinterJobHandler::OnAuthError() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); if (delegate_) delegate_->OnAuthError(); } void PrinterJobHandler::OnPrinterDeleted() { if (delegate_) delegate_->OnPrinterDeleted(printer_info_cloud_.printer_id); } void PrinterJobHandler::OnPrinterChanged() { printer_update_pending_ = true; if (!task_in_progress_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Start, this)); } } void PrinterJobHandler::OnJobChanged() { // Some job on the printer changed. Loop through all our JobStatusUpdaters // and have them check for updates. for (JobStatusUpdaterList::iterator index = job_status_updater_list_.begin(); index != job_status_updater_list_.end(); index++) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&JobStatusUpdater::UpdateStatus, index->get())); } } void PrinterJobHandler::OnJobSpoolSucceeded(const PlatformJobId& job_id) { DCHECK(CurrentlyOnPrintThread()); job_spooler_->AddRef(); print_thread_.message_loop()->ReleaseSoon(FROM_HERE, job_spooler_.get()); job_spooler_ = NULL; job_handler_task_runner_->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::JobSpooled, this, job_id)); } void PrinterJobHandler::OnJobSpoolFailed() { DCHECK(CurrentlyOnPrintThread()); job_spooler_->AddRef(); print_thread_.message_loop()->ReleaseSoon(FROM_HERE, job_spooler_.get()); job_spooler_ = NULL; VLOG(1) << "CP_CONNECTOR: Job failed (spool failed)"; job_handler_task_runner_->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::JobFailed, this, JOB_FAILED)); } // static void PrinterJobHandler::ReportsStats() { base::subtle::Atomic32 started = base::subtle::NoBarrier_AtomicExchange(&g_total_jobs_started, 0); base::subtle::Atomic32 done = base::subtle::NoBarrier_AtomicExchange(&g_total_jobs_done, 0); UMA_HISTOGRAM_COUNTS_100("CloudPrint.JobsStartedPerInterval", started); UMA_HISTOGRAM_COUNTS_100("CloudPrint.JobsDonePerInterval", done); } PrinterJobHandler::~PrinterJobHandler() { if (printer_watcher_.get()) printer_watcher_->StopWatching(); } // Begin Response handlers CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandlePrinterUpdateResponse( const net::URLFetcher* source, const GURL& url, base::DictionaryValue* json_data, bool succeeded) { VLOG(1) << "CP_CONNECTOR: Handling printer update response" << ", printer id: " << printer_info_cloud_.printer_id; // We are done here. Go to the Stop state VLOG(1) << "CP_CONNECTOR: Stopping printer job handler" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleJobMetadataResponse( const net::URLFetcher* source, const GURL& url, base::DictionaryValue* json_data, bool succeeded) { VLOG(1) << "CP_CONNECTOR: Handling job metadata response" << ", printer id: " << printer_info_cloud_.printer_id; bool job_available = false; if (succeeded) { std::vector<JobDetails> jobs; job_queue_handler_.GetJobsFromQueue(json_data, &jobs); if (!jobs.empty()) { if (jobs[0].time_remaining_ == base::TimeDelta()) { job_available = true; job_details_ = jobs[0]; job_start_time_ = base::Time::Now(); base::subtle::NoBarrier_AtomicIncrement(&g_total_jobs_started, 1); UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_JOB_STARTED, JOB_HANDLER_MAX); SetNextDataHandler(&PrinterJobHandler::HandlePrintTicketResponse); request_ = CloudPrintURLFetcher::Create(); if (print_system_->UseCddAndCjt()) { request_->StartGetRequest( CloudPrintURLFetcher::REQUEST_TICKET, GetUrlForJobCjt(cloud_print_server_url_, job_details_.job_id_, job_fetch_reason_), this, kJobDataMaxRetryCount, std::string()); } else { request_->StartGetRequest( CloudPrintURLFetcher::REQUEST_TICKET, GURL(job_details_.print_ticket_url_), this, kJobDataMaxRetryCount, std::string()); } } else { job_available = false; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&PrinterJobHandler::RunScheduledJobCheck, this), jobs[0].time_remaining_); } } } if (!job_available) { // If no jobs are available, go to the Stop state. VLOG(1) << "CP_CONNECTOR: Stopping printer job handler" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); } return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandlePrintTicketResponse(const net::URLFetcher* source, const GURL& url, const std::string& data) { VLOG(1) << "CP_CONNECTOR: Handling print ticket response" << ", printer id: " << printer_info_cloud_.printer_id; std::string mime_type; source->GetResponseHeaders()->GetMimeType(&mime_type); if (print_system_->ValidatePrintTicket(printer_info_.printer_name, data, mime_type)) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_VALID_TICKET, JOB_HANDLER_MAX); job_details_.print_ticket_ = data; job_details_.print_ticket_mime_type_ = mime_type; SetNextDataHandler(&PrinterJobHandler::HandlePrintDataResponse); request_ = CloudPrintURLFetcher::Create(); std::string accept_headers = "Accept: "; accept_headers += print_system_->GetSupportedMimeTypes(); request_->StartGetRequest(CloudPrintURLFetcher::REQUEST_DATA, GURL(job_details_.print_data_url_), this, kJobDataMaxRetryCount, accept_headers); } else { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_INVALID_TICKET, JOB_HANDLER_MAX); // The print ticket was not valid. We are done here. ValidatePrintTicketFailed(); } return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandlePrintDataResponse(const net::URLFetcher* source, const GURL& url, const std::string& data) { VLOG(1) << "CP_CONNECTOR: Handling print data response" << ", printer id: " << printer_info_cloud_.printer_id; if (base::CreateTemporaryFile(&job_details_.print_data_file_path_)) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_DATA, JOB_HANDLER_MAX); int ret = base::WriteFile(job_details_.print_data_file_path_, data.c_str(), data.length()); source->GetResponseHeaders()->GetMimeType( &job_details_.print_data_mime_type_); DCHECK(ret == static_cast<int>(data.length())); if (ret == static_cast<int>(data.length())) { UpdateJobStatus(PRINT_JOB_STATUS_IN_PROGRESS, JOB_SUCCESS); return CloudPrintURLFetcher::STOP_PROCESSING; } } UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_INVALID_DATA, JOB_HANDLER_MAX); // If we are here, then there was an error in saving the print data, bail out // here. VLOG(1) << "CP_CONNECTOR: Error saving print data" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::JobFailed, this, JOB_DOWNLOAD_FAILED)); return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleInProgressStatusUpdateResponse( const net::URLFetcher* source, const GURL& url, base::DictionaryValue* json_data, bool succeeded) { VLOG(1) << "CP_CONNECTOR: Handling success status update response" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::StartPrinting, this)); return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction PrinterJobHandler::HandleFailureStatusUpdateResponse( const net::URLFetcher* source, const GURL& url, base::DictionaryValue* json_data, bool succeeded) { VLOG(1) << "CP_CONNECTOR: Handling failure status update response" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); return CloudPrintURLFetcher::STOP_PROCESSING; } void PrinterJobHandler::Start() { VLOG(1) << "CP_CONNECTOR: Starting printer job handler" << ", printer id: " << printer_info_cloud_.printer_id << ", task in progress: " << task_in_progress_; UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_START, JOB_HANDLER_MAX); if (task_in_progress_) { // Multiple Starts can get posted because of multiple notifications // We want to ignore the other ones that happen when a task is in progress. return; } Reset(); if (!shutting_down_) { // Check if we have work to do. if (HavePendingTasks()) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_PENDING_TASK, JOB_HANDLER_MAX); if (!task_in_progress_ && printer_update_pending_) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_PRINTER_UPDATE, JOB_HANDLER_MAX); printer_update_pending_ = false; task_in_progress_ = UpdatePrinterInfo(); VLOG(1) << "CP_CONNECTOR: Changed task in progress" << ", printer id: " << printer_info_cloud_.printer_id << ", task in progress: " << task_in_progress_; } if (!task_in_progress_ && job_check_pending_) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_JOB_CHECK, JOB_HANDLER_MAX); task_in_progress_ = true; VLOG(1) << "CP_CONNECTOR: Changed task in progress" ", printer id: " << printer_info_cloud_.printer_id << ", task in progress: " << task_in_progress_; job_check_pending_ = false; // We need to fetch any pending jobs for this printer SetNextJSONHandler(&PrinterJobHandler::HandleJobMetadataResponse); request_ = CloudPrintURLFetcher::Create(); request_->StartGetRequest( CloudPrintURLFetcher::REQUEST_JOB_FETCH, GetUrlForJobFetch( cloud_print_server_url_, printer_info_cloud_.printer_id, job_fetch_reason_), this, kCloudPrintAPIMaxRetryCount, std::string()); last_job_fetch_time_ = base::TimeTicks::Now(); VLOG(1) << "CP_CONNECTOR: Last job fetch time" << ", printer name: " << printer_info_.printer_name.c_str() << ", timestamp: " << last_job_fetch_time_.ToInternalValue(); job_fetch_reason_.clear(); } } } } void PrinterJobHandler::Stop() { VLOG(1) << "CP_CONNECTOR: Stopping printer job handler" << ", printer id: " << printer_info_cloud_.printer_id; task_in_progress_ = false; VLOG(1) << "CP_CONNECTOR: Changed task in progress" << ", printer id: " << printer_info_cloud_.printer_id << ", task in progress: " << task_in_progress_; Reset(); if (HavePendingTasks()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Start, this)); } } void PrinterJobHandler::StartPrinting() { VLOG(1) << "CP_CONNECTOR: Starting printing" << ", printer id: " << printer_info_cloud_.printer_id; UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_SET_START_PRINTING, JOB_HANDLER_MAX); // We are done with the request object for now. request_ = NULL; if (!shutting_down_) { #if defined(OS_WIN) print_thread_.init_com_with_mta(true); #endif if (!print_thread_.Start()) { VLOG(1) << "CP_CONNECTOR: Failed to start print thread" << ", printer id: " << printer_info_cloud_.printer_id; JobFailed(JOB_FAILED); } else { print_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::DoPrint, this, job_details_, printer_info_.printer_name)); } } } void PrinterJobHandler::Reset() { job_details_.Clear(); request_ = NULL; print_thread_.Stop(); } void PrinterJobHandler::UpdateJobStatus(PrintJobStatus status, PrintJobError error) { VLOG(1) << "CP_CONNECTOR: Updating job status" << ", printer id: " << printer_info_cloud_.printer_id << ", job id: " << job_details_.job_id_ << ", job status: " << status; if (shutting_down_) { VLOG(1) << "CP_CONNECTOR: Job status update aborted (shutting down)" << ", printer id: " << printer_info_cloud_.printer_id << ", job id: " << job_details_.job_id_; return; } if (job_details_.job_id_.empty()) { VLOG(1) << "CP_CONNECTOR: Job status update aborted (empty job id)" << ", printer id: " << printer_info_cloud_.printer_id; return; } UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobStatus", error, JOB_MAX); if (error == JOB_SUCCESS) { DCHECK_EQ(status, PRINT_JOB_STATUS_IN_PROGRESS); UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_SET_IN_PROGRESS, JOB_HANDLER_MAX); SetNextJSONHandler( &PrinterJobHandler::HandleInProgressStatusUpdateResponse); } else { SetNextJSONHandler( &PrinterJobHandler::HandleFailureStatusUpdateResponse); } request_ = CloudPrintURLFetcher::Create(); request_->StartGetRequest( CloudPrintURLFetcher::REQUEST_UPDATE_JOB, GetUrlForJobStatusUpdate(cloud_print_server_url_, job_details_.job_id_, status, error), this, kCloudPrintAPIMaxRetryCount, std::string()); } void PrinterJobHandler::RunScheduledJobCheck() { CheckForJobs(kJobFetchReasonRetry); } void PrinterJobHandler::SetNextJSONHandler(JSONDataHandler handler) { next_json_data_handler_ = handler; next_data_handler_ = NULL; } void PrinterJobHandler::SetNextDataHandler(DataHandler handler) { next_data_handler_ = handler; next_json_data_handler_ = NULL; } void PrinterJobHandler::JobFailed(PrintJobError error) { VLOG(1) << "CP_CONNECTOR: Job failed" << ", printer id: " << printer_info_cloud_.printer_id << ", job id: " << job_details_.job_id_ << ", error: " << error; if (!shutting_down_) { UpdateJobStatus(PRINT_JOB_STATUS_ERROR, error); // This job failed, but others may be pending. Schedule a check. job_check_pending_ = true; job_fetch_reason_ = kJobFetchReasonFailure; } } void PrinterJobHandler::JobSpooled(PlatformJobId local_job_id) { VLOG(1) << "CP_CONNECTOR: Job spooled" << ", printer id: " << printer_info_cloud_.printer_id << ", job id: " << local_job_id; UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_SPOOLED, JOB_HANDLER_MAX); UMA_HISTOGRAM_LONG_TIMES("CloudPrint.SpoolingTime", base::Time::Now() - spooling_start_time_); if (shutting_down_) return; local_job_id_ = local_job_id; print_thread_.Stop(); // The print job has been spooled locally. We now need to create an object // that monitors the status of the job and updates the server. scoped_refptr<JobStatusUpdater> job_status_updater( new JobStatusUpdater(printer_info_.printer_name, job_details_.job_id_, local_job_id_, cloud_print_server_url_, print_system_.get(), this)); job_status_updater_list_.push_back(job_status_updater); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&JobStatusUpdater::UpdateStatus, job_status_updater.get())); CheckForJobs(kJobFetchReasonQueryMore); VLOG(1) << "CP_CONNECTOR: Stopping printer job handler" << ", printer id: " << printer_info_cloud_.printer_id; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); } bool PrinterJobHandler::UpdatePrinterInfo() { if (!printer_watcher_.get()) { LOG(ERROR) << "CP_CONNECTOR: Printer watcher is missing." << " Check printer server url for printer id: " << printer_info_cloud_.printer_id; return false; } VLOG(1) << "CP_CONNECTOR: Updating printer info" << ", printer id: " << printer_info_cloud_.printer_id; // We need to update the parts of the printer info that have changed // (could be printer name, description, status or capabilities). // First asynchronously fetch the capabilities. printing::PrinterBasicInfo printer_info; printer_watcher_->GetCurrentPrinterInfo(&printer_info); // Asynchronously fetch the printer caps and defaults. The story will // continue in OnReceivePrinterCaps. print_system_->GetPrinterCapsAndDefaults( printer_info.printer_name.c_str(), base::Bind(&PrinterJobHandler::OnReceivePrinterCaps, weak_ptr_factory_.GetWeakPtr())); // While we are waiting for the data, pretend we have work to do and return // true. return true; } bool PrinterJobHandler::HavePendingTasks() { return (job_check_pending_ || printer_update_pending_); } void PrinterJobHandler::ValidatePrintTicketFailed() { if (!shutting_down_) { LOG(ERROR) << "CP_CONNECTOR: Failed validating print ticket" << ", printer name: " << printer_info_.printer_name << ", job id: " << job_details_.job_id_; JobFailed(JOB_VALIDATE_TICKET_FAILED); } } void PrinterJobHandler::OnReceivePrinterCaps( bool succeeded, const std::string& printer_name, const printing::PrinterCapsAndDefaults& caps_and_defaults) { printing::PrinterBasicInfo printer_info; if (printer_watcher_.get()) printer_watcher_->GetCurrentPrinterInfo(&printer_info); std::string post_data; std::string mime_boundary = net::GenerateMimeMultipartBoundary(); if (succeeded) { std::string caps_hash = base::MD5String(caps_and_defaults.printer_capabilities); if (caps_hash != printer_info_cloud_.caps_hash) { // Hashes don't match, we need to upload new capabilities (the defaults // go for free along with the capabilities) printer_info_cloud_.caps_hash = caps_hash; if (caps_and_defaults.caps_mime_type == kContentTypeJSON) { DCHECK(print_system_->UseCddAndCjt()); net::AddMultipartValueForUpload(kUseCDD, "true", mime_boundary, std::string(), &post_data); } net::AddMultipartValueForUpload(kPrinterCapsValue, caps_and_defaults.printer_capabilities, mime_boundary, caps_and_defaults.caps_mime_type, &post_data); net::AddMultipartValueForUpload(kPrinterDefaultsValue, caps_and_defaults.printer_defaults, mime_boundary, caps_and_defaults.defaults_mime_type, &post_data); net::AddMultipartValueForUpload(kPrinterCapsHashValue, caps_hash, mime_boundary, std::string(), &post_data); } } else { LOG(ERROR) << "Failed to get printer caps and defaults" << ", printer name: " << printer_name; } std::string tags_hash = GetHashOfPrinterInfo(printer_info); if (tags_hash != printer_info_cloud_.tags_hash) { printer_info_cloud_.tags_hash = tags_hash; post_data += GetPostDataForPrinterInfo(printer_info, mime_boundary); // Remove all the existing proxy tags. std::string cp_tag_wildcard(kCloudPrintServiceProxyTagPrefix); cp_tag_wildcard += ".*"; net::AddMultipartValueForUpload(kPrinterRemoveTagValue, cp_tag_wildcard, mime_boundary, std::string(), &post_data); if (!last_caps_update_time_.is_null()) { UMA_HISTOGRAM_CUSTOM_TIMES( "CloudPrint.CapsUpdateInterval", base::Time::Now() - last_caps_update_time_, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromDays(7), 50); } last_caps_update_time_ = base::Time::Now(); } if (printer_info.printer_name != printer_info_.printer_name) { net::AddMultipartValueForUpload(kPrinterNameValue, printer_info.printer_name, mime_boundary, std::string(), &post_data); } if (printer_info.printer_description != printer_info_.printer_description) { net::AddMultipartValueForUpload(kPrinterDescValue, printer_info.printer_description, mime_boundary, std::string(), &post_data); } if (printer_info.printer_status != printer_info_.printer_status) { net::AddMultipartValueForUpload(kPrinterStatusValue, base::IntToString(printer_info.printer_status), mime_boundary, std::string(), &post_data); } // Add local_settings with a current XMPP ping interval. if (printer_info_cloud_.pending_xmpp_timeout != 0) { DCHECK(kMinXmppPingTimeoutSecs <= printer_info_cloud_.pending_xmpp_timeout); net::AddMultipartValueForUpload(kPrinterLocalSettingsValue, base::StringPrintf(kUpdateLocalSettingsXmppPingFormat, printer_info_cloud_.current_xmpp_timeout), mime_boundary, std::string(), &post_data); } printer_info_ = printer_info; if (!post_data.empty()) { net::AddMultipartFinalDelimiterForUpload(mime_boundary, &post_data); std::string mime_type("multipart/form-data; boundary="); mime_type += mime_boundary; SetNextJSONHandler(&PrinterJobHandler::HandlePrinterUpdateResponse); request_ = CloudPrintURLFetcher::Create(); request_->StartPostRequest( CloudPrintURLFetcher::REQUEST_UPDATE_PRINTER, GetUrlForPrinterUpdate( cloud_print_server_url_, printer_info_cloud_.printer_id), this, kCloudPrintAPIMaxRetryCount, mime_type, post_data, std::string()); } else { // We are done here. Go to the Stop state VLOG(1) << "CP_CONNECTOR: Stopping printer job handler" << ", printer name: " << printer_name; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrinterJobHandler::Stop, this)); } } void PrinterJobHandler::DoPrint(const JobDetails& job_details, const std::string& printer_name) { DCHECK(CurrentlyOnPrintThread()); job_spooler_ = print_system_->CreateJobSpooler(); UMA_HISTOGRAM_LONG_TIMES("CloudPrint.PrepareTime", base::Time::Now() - job_start_time_); DCHECK(job_spooler_.get()); base::string16 document_name = job_details.job_title_.empty() ? l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE) : base::UTF8ToUTF16(job_details.job_title_); document_name = printing::FormatDocumentTitleWithOwner( base::UTF8ToUTF16(job_details.job_owner_), document_name); UMA_HISTOGRAM_ENUMERATION("CloudPrint.JobHandlerEvent", JOB_HANDLER_START_SPOOLING, JOB_HANDLER_MAX); spooling_start_time_ = base::Time::Now(); if (!job_spooler_->Spool(job_details.print_ticket_, job_details.print_ticket_mime_type_, job_details.print_data_file_path_, job_details.print_data_mime_type_, printer_name, base::UTF16ToUTF8(document_name), job_details.tags_, this)) { OnJobSpoolFailed(); } } bool PrinterJobHandler::CurrentlyOnPrintThread() const { return base::MessageLoop::current() == print_thread_.message_loop(); } } // namespace cloud_print
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
3dfee271e328912877e3f33f54ab051693120b02
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/std/algorithms/alg.modifying.operations/alg.partitions/partition_point.pass.cpp
9301e48463a050294c1452e8e2f2ca617ee192f9
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
3,217
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <algorithm> // template<class ForwardIterator, class Predicate> // ForwardIterator // partition_point(ForwardIterator first, ForwardIterator last, Predicate pred); #include <algorithm> #include <cassert> #include "test_iterators.h" struct is_odd { bool operator()(const int& i) const {return i & 1;} }; int main() { { const int ia[] = {2, 4, 6, 8, 10}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia)); } { const int ia[] = {1, 2, 4, 6, 8}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 1)); } { const int ia[] = {1, 3, 2, 4, 6}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 2)); } { const int ia[] = {1, 3, 5, 2, 4, 6}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 3)); } { const int ia[] = {1, 3, 5, 7, 2, 4}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 4)); } { const int ia[] = {1, 3, 5, 7, 9, 2}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 5)); } { const int ia[] = {1, 3, 5, 7, 9, 11}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::end(ia)), is_odd()) == forward_iterator<const int*>(ia + 6)); } { const int ia[] = {1, 3, 5, 2, 4, 6, 7}; assert(std::partition_point(forward_iterator<const int*>(std::begin(ia)), forward_iterator<const int*>(std::begin(ia)), is_odd()) == forward_iterator<const int*>(ia)); } }
[ "1848@shanchain.com" ]
1848@shanchain.com
43d04e01b2d512c322c87b32e62f543eec969164
ae3f1ceb0a297bf213694791c60f39d5a2071f54
/RAAHN/stdafx.cpp
bb688b74a2d5face5e3c1ae274435d894053ddc4
[]
no_license
kinggra1/cppRAAHN
b9451cb07210d633d2792de4cdbe82f36a7b8e13
6809408bd6bf27923c740a69382185735bcce7cc
refs/heads/master
2021-01-11T00:50:25.286674
2016-10-26T02:57:52
2016-10-26T02:57:52
70,458,251
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
// stdafx.cpp : source file that includes just the standard includes // RAAHN.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "kinggra1@msu.edu" ]
kinggra1@msu.edu
901132a1bc57d3178c9107dc32175cd34552963e
1f85ddee76eb1883d61ba2b12d78c3fe89a1940c
/bonds.cpp
36c8a772dc185131bfc94cb6ef8e4f46ca1c5d02
[]
no_license
mrchessmaster/tools-for-academics
4dda14d93a018654b3201b02500209911d97bf6f
4134bb9b76f52a5a77420d0fc9949635242fe44e
refs/heads/master
2021-01-10T06:14:45.623301
2017-03-26T23:28:37
2017-03-26T23:28:37
48,836,230
1
1
null
null
null
null
UTF-8
C++
false
false
1,127
cpp
#include <iostream> #include <string> using namespace std; string toComma(int n) { string ret = ""; int temp; int i=0; while (n > 0) { temp = n % 10; n /= 10; if (i%3 == 0) ret = to_string(temp) + "," + ret; else ret = to_string(temp) + ret; i++; } ret.pop_back(); return ret; } int main() { cout << "Welcome to bond calculator" << endl; cout << "Enter b to begin." << endl; string in; cin >> in; if (in == "b") { cout << "Face value: "; double fv; cin >> fv; cout << "At: "; double at; cin >> at; at /= 100; cout << "Coupon rate: "; double cp; cin >> cp; cp /= 100; cout << "Yield: "; double y; cin >> y; y /= 100; cout << "Period: "; double t; cin >> t; cout.precision(15); double np = fv*at; for (int i=0; i<t*2; i++) { double payment = fv*cp/2; double expense = np*y/2; np += expense - payment; cout << "-----------------------------------" << endl; cout << "Time: " << i+1 << endl; cout << "Payment: " << toComma(payment) << endl; cout << "Interest Expense: " << toComma(expense) << endl; cout << "Current N/P: " << toComma(np) << endl; } } return 0; }
[ "yin.dydx@gmail.com" ]
yin.dydx@gmail.com
84c3ff4eb43b4460da36b40c2d71d750f793284e
5fccc7ec58bf1207df4baa35f87c1bea539c0ef9
/lab4/Modules/Calibration/PinHole.cc
c0eea659eb8f59ef056f0fcf36673e3112d93a8e
[]
no_license
rokzal/SLAM_LABS
134ef9adda1d0a5b39986c7bb4580c8fb5eed019
1b8b8a66b9b6263abb2537289817372c5e9b48fd
refs/heads/main
2023-04-13T18:47:57.192276
2021-04-29T14:45:36
2021-04-29T14:45:36
339,060,684
0
1
null
null
null
null
UTF-8
C++
false
false
1,845
cc
/** * This file is part of Mini-SLAM * * Copyright (C) 2021 Juan J. Gómez Rodríguez and Juan D. Tardós, University of Zaragoza. * * Mini-SLAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Mini-SLAM 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 Mini-SLAM. * If not, see <http://www.gnu.org/licenses/>. */ #include "PinHole.h" #define fx vParameters_[0] #define fy vParameters_[1] #define cx vParameters_[2] #define cy vParameters_[3] void PinHole::project(const Eigen::Vector3f& p3D, Eigen::Vector2f& p2D){ /* * Your code for task2 here! */ p2D[0] = fx * p3D[0]/p3D[2] + cx; p2D[1] = fy * p3D[1]/p3D[2] + cy; } void PinHole::unproject(const Eigen::Vector2f& p2D, Eigen::Vector3f& p3D) { /* * Your code for task2 here! */ p3D[0] = (p2D[0]-cx)/fx; p3D[1] = (p2D[1]-cy)/fy; p3D[2] = 1; } void PinHole::projectJac(const Eigen::Vector3f& p3D, Eigen::Matrix<float,2,3>& Jac) { /* * Your code for task2 here! */ //First row. Jac(0,0) = fx /p3D[2]; Jac(0,1) = 0.f; Jac(0,2) = -fx * p3D[0]/(p3D[2]*p3D[2]); Jac(1,0) = 0.f; Jac(1,1) = fy /p3D[2]; Jac(1,2) = -fy * p3D[1]/(p3D[2]*p3D[2]); } void PinHole::unprojectJac(const Eigen::Vector2f& p2D, Eigen::Matrix<float,3,2>& Jac) { Jac(0,0) = 1 / fx; Jac(0,1) = 0.f; Jac(1,0) = 0.f; Jac(1,1) = 1 / fy; Jac(2,0) = 0.f; Jac(2,1) = 0.f; }
[ "ubi1616@gmail.com" ]
ubi1616@gmail.com
0aa3fa3d57f54e59ed482bccd49aef3695039c4c
0b93b15b49f2b3eccb7e2af71a84ec762171134a
/MyHttpWeb1.2/ProtocolUtil.hpp
c0feb01600c14ab4bfc44badea7cf5f3162afc16
[]
no_license
sunjiyuansjy/MyProject_httpweb
97b954d6a8bb32f6e982b5f42bf354b62514cfcb
6c9407950e02113a117ce2088652bab4c05dc888
refs/heads/master
2020-04-23T09:40:23.610810
2019-02-27T23:56:04
2019-02-27T23:56:04
171,076,672
1
0
null
null
null
null
UTF-8
C++
false
false
10,373
hpp
#ifndef __PROTOCOLUTIL_HPP__ #define __PROTOCOLUTIL_HPP__ #include <iostream> #include <stdlib.h> #include <string> #include <strings.h> #include <unistd.h> #include <vector> #include <unordered_map> #include <sstream> #include <algorithm> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/stat.h> #include <sys/sendfile.h> #include <fcntl.h> #define BACKLOG 5 #define BUFF_NUM 1024 #define NORMAL 0 #define WARNING 1 #define ERROR 2 #define WEBROOT "wwwroot" #define HOMEPAGE "index.html" const char *ErrLevel[]={ "Normal", "Warning", "Error" }; //__FILE__ ___LINE__ void log(std::string msg,int level,std::string file,int line) { std::cout << " [ "<< file << ":" << line <<"]" << msg <<" [ "<< ErrLevel[level] <<" ] "<< std::endl; } #define LOG(msg,level) log(msg,level,__FILE__, __LINE__); class Util{ public: static void MakeKV(std::string s,std::string &k,std::string &v) { std::size_t pos = s.find(":"); k = s.substr(0,pos); v = s.substr(pos+2); } static std::string IntToString(int &x) { std::stringstream ss; ss << x; return ss.str(); } static std::string CodeToDosc(int code) { switch(code) { case 200: return "OK"; case 404: return "Not Found"; default: break; } return "Unknow error"; } }; class SocketApi{ public: static int Socket() { int sock = socket(AF_INET,SOCK_STREAM,0); if(sock < 0){ LOG("socket error!",ERROR); exit(2); } int opt = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); return sock; } static void Bind(int sock,int port) { struct sockaddr_in local; bzero(&local,sizeof(local)); local.sin_family = AF_INET; local.sin_port = htons(port); local.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0){ LOG("bind error!",ERROR); exit(3); } } static void Listen(int sock) { if(listen(sock,BACKLOG) < 0) { LOG("listen error!",ERROR); exit(4); } } static int Accept(int listen_sock,std::string &ip,int &port) { struct sockaddr_in peer; socklen_t len = sizeof(peer); int sock = accept(listen_sock, (struct sockaddr*)&peer, &len); if(sock<0){ LOG("accept error",WARNING); return -1; } port = ntohs(peer.sin_port); ip = inet_ntoa(peer.sin_addr); return sock; } }; class Http_Response{ public: //基本协议字段 std::string status_line; std::vector<std::string> response_header; std::string blank; std::string response_text; private: int code; std::string path; int recource_size; public: Http_Response() :blank("\r\n"),code(200),recource_size(0) {} int &Code() { return code; } void SetPath(std::string &path_) { path = path_; } std::string &Path() { return path; } void SetRecourceSize(int rs) { recource_size = rs; } int RecourceSize() { return recource_size; } void MakeStatusLine() { status_line = "HTTP/1.0"; status_line = " "; status_line = Util::IntToString(code); status_line = " "; status_line = Util::CodeToDosc(code); status_line = "\r\n"; LOG("Make Status Line Done!",NORMAL); } void MakeResponseHeader() { std::string line; line = "Content-Length:"; line += Util::IntToString(recource_size); line +="\r\n"; response_header.push_back(line); line += "\r\n"; response_header.push_back(line); LOG("Make Response Header Done!",NORMAL); } ~Http_Response() {} }; class Http_Request{ public: //基本协议字段 std::string request_line; std::vector<std::string> request_header; std::string blank; std::string request_text; private: //解析协议字段 std::string method; std::string uri;//path?arg std::string version; std::string path; //int recource_size; std::string query_string; std::unordered_map<std::string,std::string> header_kv; bool cgi; public: Http_Request():path(WEBROOT),cgi(false),blank("\r\n") {} void RequestLineParse() { //将一个字符串变成3个 //GET /x/y/z /HTTP /1.1\n std::stringstream ss(request_line); ss >> method >> uri >> version; transform(method.begin(),method.end(),method.begin(),::toupper); } void UriParse() { if(method == "GET") { std::size_t pos = uri.find('?'); if(pos!=std::string::npos){ cgi = true; path += uri.substr(0,pos); query_string = uri.substr(pos+1); }else{ //不带参数 path += uri;//wwwroot/a/b/c/d.html } }else{ //POST path += uri; } if(path[path.size()-1]=='/') { path += HOMEPAGE; // wwwroot/index.html } } void HeaderParse() { std::string k,v; for(auto it=request_header.begin();it!=request_header.end();it++) { Util::MakeKV(*it,k,v); header_kv.insert({k,v}); } } bool IsMethodLegal() { if(method != "GET"&& method != "POST") { return false; } return true; } int IsPathLegal(Http_Response *rsp)// wwwroot/a/b/c/d.html { int rs = 0; struct stat st; if(stat(path.c_str(),&st)<0) { LOG("file is not exist!",WARNING); return 404; } else{ rs = st.st_size; if(S_ISDIR(st.st_mode)){ path += "/"; path += HOMEPAGE; stat(path.c_str(),&st); rs = st.st_size; }else if((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH)){ cgi = true; }else{ //TODO } } rsp->SetPath(path); rsp->SetRecourceSize(rs); LOG("PATH is ok!",NORMAL); return 0; } bool IsNeedRecv() { return method == "POST" ? true:false; } bool IsCgi() { return cgi; } int ContentLength() { int content_length= -1; std::string cl = header_kv["Content-Line"]; std:: stringstream ss(cl); ss >> content_length; return content_length; } ~Http_Request() {} }; class Connect{ private: int sock; public: Connect(int sock_):sock(sock_) {} int RecvOneLine(std::string line_) { char buff[BUFF_NUM]; int i = 0; char c = 'X'; while(c!='\n' && i < BUFF_NUM - 1){ ssize_t s = recv(sock,&c,1,0); if(s > 0){ if(c=='\r') { recv(sock,&c,1,MSG_PEEK); if(c == '\n'){ recv(sock,&c,1,0); }else{ c = '\n'; } } // \r \n \r\n ->\n buff[i++] = c; } else{ break; } } buff[i] = 0; line_ = buff; return i; } void RecvRequestHeader(std::vector<std::string> &v) { std::string line = "X"; while(line != "\n"){ RecvOneLine(line); if(line != "\n") { v.push_back(line); } } LOG("Header Recv OK!",NORMAL); } void RecvText(std::string &Text,int content_length) { char c; for(auto i=0;i<content_length;i++) { recv(sock,&c,1,0); Text.push_back(c); } } void SendStatusLine(Http_Response *rsp) { std::string &sl = rsp->status_line; send(sock,sl.c_str(),sl.size(),0); } void SendHeader(Http_Response *rsp) { std::vector<std::string> &v = rsp->response_header; for(auto it = v.begin();it != v.end();it++) { send(sock,it->c_str(),it->size(),0); } } void SendText(Http_Response *rsp) { std::string &path = rsp -> Path(); int fd = open(path.c_str(),O_RDONLY); if(fd<0){ LOG("open file error!",WARNING); return; } sendfile(sock,fd,NULL,rsp->RecourceSize()); close(fd); } ~Connect() { close(sock); } }; class Entry{ public: static void ProcessNonCgi(Connect *conn,Http_Request *rq,Http_Response *rsp) { rsp->MakeStatusLine(); rsp->MakeResponseHeader(); // rsp->MakeResponseText(rq); conn->SendStatusLine(rsp); conn->SendHeader(rsp);//add \n conn->SendText(rsp); LOG("Send Response Done!",NORMAL); } static void ProcessResponse(Connect *conn,Http_Request *rq,Http_Response *rsp) { if(rq->IsCgi()){ //ProcesCgi(); }else{ LOG("MakeResponse Use Non Cgi!",NORMAL); ProcessNonCgi(conn,rq,rsp); } } static void *HandlerRequest(void *arg) { pthread_detach(pthread_self()); int *sock = (int*)arg; delete arg; #ifdef _DEBUG_ //for test char buf[10240]; read(*sock, buf, sizeof(buf)); std::cout << "#####################" << std::endl; std::cout << buf << std::endl; std::cout << "#####################" << std::endl; #else Connect *conn = new Connect(*sock); Http_Request *rq = new Http_Request; Http_Response *rsp = new Http_Response; int &code=rsp->Code(); conn->RecvOneLine(rq->request_line); rq->RequestLineParse(); if(rq->IsMethodLegal()) { LOG("Request Method Is not Legal",WARNING); goto end; } rq->UriParse(); if(rq->IsPathLegal(rsp)!=0) { code=404; LOG("file is not exist!",WARNING); goto end; } conn ->RecvRequestHeader(rq->request_header); rq->HeaderParse(); if(rq->IsNeedRecv()) { conn->RecvText(rq->request_text,rq->ContentLength()); LOG("POST Method,Need Rev Begin!",NORMAL); } LOG("Http Request Recv Done,OK!",NORMAL); ProcessResponse(conn,rq,rsp); end: delete conn; delete rq; delete rsp; delete sock; #endif return (void *)0; } }; #endif
[ "sunjiyuansjy@163.com" ]
sunjiyuansjy@163.com
b13b65b8b5770d9a70322fec65d1e92c3ca382f6
19af2e1dfe389afc71e26bebaadf7008251e04e2
/android_test/tensorflow-master/tensorflow/compiler/xla/service/gpu/custom_call_thunk.h
9011fa26ffa521c764cb4cb82e8e81142be7dc11
[ "Apache-2.0" ]
permissive
simi48/Ef-If_Jassen
6c4975216bb4ae4514fe94a8395a5da5c8e8fb2d
6076839492bff591cf9b457e949999e9167903e6
refs/heads/master
2022-10-15T15:36:35.023506
2020-12-02T10:38:13
2020-12-02T10:38:13
173,759,247
4
0
Apache-2.0
2022-10-04T23:51:35
2019-03-04T14:22:28
PureBasic
UTF-8
C++
false
false
2,468
h
/* Copyright 2019 The TensorFlow Authors. 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 TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ #include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h" #include "tensorflow/compiler/xla/service/gpu/hlo_execution_profiler.h" #include "tensorflow/compiler/xla/service/gpu/thunk.h" namespace xla { namespace gpu { // Thunk to run a GPU custom call. // // This thunk's `ExecuteOnStream` implementation executes a host function // `call_target` which is expected to enqueue operations onto the GPU. // // For information about the calling convention, see xla/g3doc/custom_call.md // // Note that not all kCustomCall HLOs in XLA:GPU end up being run by this thunk. // XLA itself creates kCustomCall instructions when lowering kConvolution HLOs // into calls to cudnn. These internally-created custom-calls are run using // ConvolutionThunk, not CustomCallThunk. There's no ambiguity because they // have special call target names (e.g. "__cudnn$convForward") that only the // compiler is allowed to create. class CustomCallThunk : public Thunk { public: CustomCallThunk( void* call_target, std::vector<ShapeTree<BufferAllocation::Slice>> operand_slices, ShapeTree<BufferAllocation::Slice> result_slices, std::string opaque, const HloInstruction* instr); Status ExecuteOnStream(const BufferAllocations& buffer_allocations, se::Stream* stream, HloExecutionProfiler* profiler) override; private: void* call_target_; std::vector<ShapeTree<BufferAllocation::Slice>> operand_slices_; ShapeTree<BufferAllocation::Slice> result_slices_; std::string opaque_; }; } // namespace gpu } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_
[ "TheSiebi@users.noreply.github.com" ]
TheSiebi@users.noreply.github.com
1872b8f6998e42a665481089f5a0b380ef33fe70
49c6cf776addc6fbac50c887edfa168d81aa7729
/Atcoder/Atcoder Beginner 197/a.cpp
e2140323adcb562121a3191f997d396bf5deb165
[]
no_license
Ryednap/Coding-Competition
b43e38b4e8d3bfc7eee21750cd1014fb4ce49c54
a4fd7b97f3898e60800689fe27b8c00ac8a456fa
refs/heads/main
2023-08-19T06:55:04.344956
2021-10-08T05:59:24
2021-10-08T05:59:24
398,359,907
0
0
null
2021-08-28T12:33:09
2021-08-20T17:55:14
C++
UTF-8
C++
false
false
164
cpp
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "uj.h" #endif int main() { string s; cin >> s; cout << s[1] << s[2] << s[0]; return 0; }
[ "ujjwalpandey408@gmail.com" ]
ujjwalpandey408@gmail.com
9b278595007f7170481e5d0bf25858449d569cdf
5dcb6b2a922e35db077d50b8c842ca5e6593db1a
/simpleml/graph_util.cc
3c5a58b7c191244b6ff510876d55feded199433a
[]
no_license
RamiHg/SimpleML
ec26e12a9acf3664bc0b2cdd60eb926bc098607b
5620e9ca36c89885d40a289f2271cf165141b927
refs/heads/master
2021-01-24T20:13:10.676500
2018-03-24T14:32:30
2018-03-24T14:32:30
123,245,511
0
0
null
null
null
null
UTF-8
C++
false
false
993
cc
#include "simpleml/graph_util.h" #include <sstream> #include "simpleml/graph.h" #include "simpleml/operations/internal/operation.h" namespace SimpleML { AdjacencyMap GetNodeDescendants(const Graph& graph) { AdjacencyMap map; for (const auto& pair : graph.GetNodes()) { const auto& node = pair.second; const auto& operation = node->GetOperation(); for (const auto* input : operation.GetInputs()) { map[input].push_back(node.get()); } } return map; } static std::string NameOpVariable(std::string_view op_name, const Graph& graph) { std::stringstream name_stream; name_stream << op_name << "_" << graph.GetNumNodes(); return name_stream.str(); } std::string GetUniqueNodeName(const Graph& graph, std::string_view overriden, std::string_view prefix) { return overriden.empty() ? NameOpVariable(prefix, graph) : std::string(overriden); } } // namespace SimpleML
[ "elgarawany@elgarawany-macbookpro.roam.corp.google.com" ]
elgarawany@elgarawany-macbookpro.roam.corp.google.com
3238cd86e255f9c66f131ec64845763f40770b51
69edc451cdb4bf23de322c9d8335af39d583cc82
/UVa/001112.cpp
03bffb40848cd07ebfd1c23c17d3f1c71d002b46
[]
no_license
jesusmoraleda/competitive-programming
cbd90384641565b651ac2694f98f5d10870b83a9
97511d4fd00e90fe6676bfd134c0eb56be3c7580
refs/heads/master
2020-09-04T17:09:37.607768
2017-08-13T10:06:04
2017-08-13T10:06:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
#include <iostream> using namespace std; #define INF 1000000000 // 10^9 int N, adjMat[100][100]; void floyd() { for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) adjMat[i][j] = min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]); } int main() { int nc; cin >> nc; while (nc--) { int E, T, M; cin >> N >> E >> T >> M; for (int u = 0; u < N; u++) for (int v = 0; v < N; v++) adjMat[u][v] = u == v ? 0 : INF; while (M--) { int a, b, e; cin >> a >> b >> e; a--, b--; adjMat[a][b] = e; } floyd(); E--; int cnt = 0; for (int u = 0; u < N; u++) if (adjMat[u][E] <= T) cnt++; cout << cnt << endl; if (nc > 0) cout << endl; } }
[ "hallaplay835@gmail.com" ]
hallaplay835@gmail.com
67fb3d94331327046cf7b1a6dacaa9ffd61c586b
f40c349fba25ba456ac7f3c041ed516039af773e
/src/visualization.h
29a48462cd5f7da83f49dfa0bf539317c8ee1bca
[]
no_license
axruff/cuda-flow3d
5b14a65e68914096d03e10175d1e84cf23aef2bb
916fe6cb51ebfa5afabf637af6c3e7ae7dcc3d8d
refs/heads/master
2020-03-29T15:56:54.868122
2019-11-29T16:03:13
2019-11-29T16:03:13
150,089,112
2
2
null
null
null
null
UTF-8
C++
false
false
4,752
h
/** * @file 3D Optical flow using NVIDIA CUDA * @author Institute for Photon Science and Synchrotron Radiation, Karlsruhe Institute of Technology * * @date 2015-2018 * @version 0.5.0 * * * @section LICENSE * * This program is copyrighted by the author and Institute for Photon Science and Synchrotron Radiation, * Karlsruhe Institute of Technology, Karlsruhe, Germany; * * */ #ifndef VIEWFLOW3D_VISUALIZATION_H_ #define VIEWFLOW3D_VISUALIZATION_H_ #include <thread> #include <mutex> #include <condition_variable> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/quaternion.hpp> #include <AntTweakBar.h> #include "src/data_types/data3d.h" #include "src/utils/gl/gl_program.h" class Visualization { private: enum VisualizationMethod { VM_LINES, VM_GLYPHS, VM_CONES }; bool initialized_ = false; bool has_texture_ = false; bool do_next_step_ = true; /* Dataset variables */ size_t ds_width_; size_t ds_height_; size_t ds_depth_; size_t ds_sample_x_ = 10; size_t ds_sample_y_ = 10; size_t ds_sample_z_ = 10; float ds_min_; float ds_max_; float ds_avg_; float ds_scale_ = 1.f; float ds_threshold_ = 1.f; /* GLFW variables */ size_t window_width_ = 1024; size_t window_height_ = 768; GLFWwindow* glfw_window_; GLFWwindow* glfw_thread_window_; /* OpenGL variables */ VisualizationMethod gl_vis_method_ = VM_GLYPHS; glm::mat4 gl_m_projection_p_; glm::mat4 gl_m_projection_o_; glm::mat4 gl_m_view_; glm::quat gl_q_rotation_; glm::vec4 gl_clear_color_; GLProgram gl_prog_bbox_; GLProgram gl_prog_lines_; GLProgram gl_prog_r_lines_; GLProgram gl_prog_glyphs_; GLProgram gl_prog_r_glyphs_; GLProgram gl_prog_sprite_; GLuint gl_vao_bbox_; GLuint gl_vao_lines_; GLuint gl_vao_glyphs_; GLuint gl_vao_sprite_; GLuint gl_vao_cones_; GLuint gl_tex_flow_field_; GLuint gl_tex_colormap_; float gl_f_r_scale_ = 1.f; float gl_f_r_seed_ = 1.f; bool gl_b_jittered_ = false; float gl_f_zoom_ = 0.f; int gl_i_mag_dir_ = 0; bool gl_b_show_grid_ = false; int gl_i_cone_indices_ = 0; /* AntTweakBar variables */ TwBar* ant_bar_; /* Thread variables */ std::thread thr_thread_; std::condition_variable thr_cv_initialized_; std::mutex thr_m_lock_; /* Singletone */ Visualization() {}; Visualization(Visualization const&) = delete; void operator=(Visualization const&) = delete; /* Initialization routines */ bool InitializeGLWindow(); bool InitializeGLResources(); bool InitializeGLGUI(); void Render(GLFWwindow* window); /* Auxiliaru funciton */ void UpdateFPSCounter(GLFWwindow* window); void UpdateDatasetSize(size_t width, size_t height, size_t depth); void GenerateCone(size_t face_count, GLuint gl_vao_cones, int* cone_vertices); /* Callback functions */ #ifdef _DEBUG static void GLFWErrorCallback(int error, const char* message); static void APIENTRY OpenGLDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam); #endif static void GLFWWindowSizeCallback(GLFWwindow* window, int width, int height); static void GLFWCursorPositionCallback(GLFWwindow* window, double xpos, double ypos); static void GLFWMouseButtonCallback(GLFWwindow* window, int button, int action, int mods); static void GLFWScrollCallback(GLFWwindow* window, double xoffset, double yoffset); static void GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); static void GLFWCharCallback(GLFWwindow* window, unsigned int codepoint); /* Threading */ void ThreadBody(); public: /* The Singletone is used to allow access from static callbacks to private member variables */ static Visualization& GetInstance() { static Visualization instance; return instance; } bool Initialize(); void Show(); void Destroy(); inline bool IsInitialized() const { return initialized_; }; /* Reads 3D flow field from 3 different raw files with U, V and W values; each file has width x height x depth dimensionality */ bool Load3DFlowTextureFromRAWFileUVW(const char* filename_u, const char* filename_v, const char* filename_w, size_t width, size_t height, size_t depth); /* Reads 3D flow field from a raw file containing width, height and depth values at the beginning */ bool Load3DFlowTextureFromRAWFileWHD(const char* filename); bool Load3DFlowTextureFromData3DUVW(Data3D& flow_u, Data3D& flow_v, Data3D&flow_w); /* Threading */ void RunInSeparateThread(); void WaitForInitialization(); void WaitForFinalization(); void DoNextStep(); void SaveToFile(); }; #endif // !VIEWFLOW3D_VISUALIZATION_H_
[ "ershov.alexey@gmail.com" ]
ershov.alexey@gmail.com
f5ca55fa35dca9eb038f8b3d983ff897e5bc1f2c
23a3c3e00dd680d29b2dd1c3a3aa36f633f52e4e
/unittests/test-contracts/deferred_test/deferred_test.hpp
dd814050d1194015a43e169456785d9f64ce34e3
[ "MIT", "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mycloudmyworld2019/DA-DAPPS
5afdcc7c825da22709c08fb4b5a4ede4bd4221ee
534ace858fb5d852d69a578151929e64e2932f8b
refs/heads/master
2020-06-05T17:15:50.605991
2019-06-18T08:03:25
2019-06-18T08:03:25
192,272,966
0
0
null
null
null
null
UTF-8
C++
false
false
826
hpp
/** * @file * @copyright defined in DA-DAPPS/LICENSE */ #pragma once #include <DA-DAPPSio/DA-DAPPSio.hpp> #include <vector> class [[DA-DAPPSio::contract]] deferred_test : public DA-DAPPSio::contract { public: using DA-DAPPSio::contract::contract; [[DA-DAPPSio::action]] void defercall( DA-DAPPSio::name payer, uint64_t sender_id, DA-DAPPSio::name contract, uint64_t payload ); [[DA-DAPPSio::action]] void deferfunc( uint64_t payload ); using deferfunc_action = DA-DAPPSio::action_wrapper<"deferfunc"_n, &deferred_test::deferfunc>; [[DA-DAPPSio::action]] void inlinecall( DA-DAPPSio::name contract, DA-DAPPSio::name authorizer, uint64_t payload ); [[DA-DAPPSio::on_notify("DA-DAPPSio::onerror")]] void on_error( uint128_t sender_id, DA-DAPPSio::ignore<std::vector<char>> sent_trx ); };
[ "Nan.Ai@outlook.com" ]
Nan.Ai@outlook.com
562a1419b2594859335ae100dbf258780fe8fd47
91e798b61594535024bead37c44828a507d97e4f
/图/最短路径.cpp
a31a33f7f1fcdafbdb9dad7dd276fec3ac8eadfc
[]
no_license
whram/data-structure
91d8001facb8b4e21bbc293cd8281694cc745ef9
a0b16dd84c9d34b4f76f8354f35d99ddaed02124
refs/heads/master
2022-07-05T20:48:44.220817
2020-05-22T09:17:24
2020-05-22T09:17:24
266,063,136
0
0
null
null
null
null
GB18030
C++
false
false
3,830
cpp
#include <stdio.h> #include <stdlib.h> #define INT_MAX 32676 /** Dijkstra 算法是用来计算图中一个 顶点到 其余的所有顶点的 最短距离的算法 */ /*** -1 表示两点之间距离是无限大 path[v] 表示的这个数组代表了Vx到 v 的最短路径 路径 = path[v][0],v,path[v][1],path[v][2] 直到一个path[v][x] == -1 Length[v] 代表了Vx到 v 的最短长度:权之和 代码注释: **/ typedef struct graph{ int **p; int vertNum; int arcNum; }*Graph,g; typedef struct l{ int* le; bool* isIn; }*Le; int VETNUM=6; void init(Le &L,int **&P,Graph &G); void Dijikstra(Le &L,int **&P,Graph &G,int &V); int lastInsert(int *&p,int &x); void myprint(Le &L,int**&p); int main(){ Le Length; // 某个顶点到其余所有顶点的最短距离 int **Path; // 路径 int Vx; // 某个顶点 Graph G; // 图 init(Length,Path,G); printf("Enter the begin vertex:\n"); scanf("%d",&Vx); Dijikstra(Length,Path,G,Vx); myprint(Length,Path); } void myprint(Le &L,int**&p){ int i,j; for(i=0;i<6;i++){ printf("%d:\t",L->le[i]); for(j=0;j<6;j++) printf("%d\t",p[i][j]); printf("\n"); } } int lastInsert(int *&p,int &x){ int i; for(i=0;i<VETNUM;i++){ if(p[i]==-1){ p[i] = x; return 1; } } } void init(Le &L,int **&P,Graph &G){ int data[6][6] = {{-1 ,-1 ,10 ,-1 ,30 ,100} ,{ -1 ,-1 ,5 ,-1 ,-1 ,-1 }, {-1 ,2 ,-1 ,50 ,-1 ,-1 } ,{ -1 ,-1 ,-1 ,-1 ,-1 ,10 }, {-1 ,-1 ,-1 ,20 ,-1 ,60 } ,{ -1 ,-1 ,-1 ,-1 ,-1 ,-1 }}; int data1[6][6] = {{-1 ,1 ,20 ,80 ,-1 ,400} ,{ 2 ,-1 ,-1 ,-1 ,-1 ,700}, {40 ,6 ,-1 ,4 ,-1 ,100} ,{ -1 ,-1 ,-1 ,-1 ,4 ,-1 }, {-1 ,-1 ,-1 ,-1 ,-1 ,3 } ,{ -1 ,-1 ,-1 ,-1 ,-1 ,-1 }}; int vextnum = 6; int i,j; G = (Graph)calloc(sizeof(g),1); G->p = (int**)malloc(sizeof(int*)*6); P = (int**)malloc(sizeof(int*)*6); L = (Le)calloc(sizeof(struct l),1); L->le = (int*)calloc(sizeof(int),6); L->isIn = (bool*)calloc(sizeof(bool),6); for(i=0;i<6;i++){ G->p[i] = (int*)malloc(sizeof(int)*6); P[i] = (int *)calloc(sizeof(int),6); } G->vertNum = 6; for(i=0;i<vextnum;i++) for(j=0;j<vextnum;j++) G->p[i][j] = data[i][j],P[i][j]= -1; /*** for(i=0;i<6;i++) printf("%d\n",L->isIn[i]); printf("xsaxas"); */ } void Dijikstra(Le &L,int **&P,Graph &G,int &V){ int Vk; int i,j; int Min; int check=0; /** 首先将L初始化 在这里面必有一条 V 到其他顶点的最小值 **/ for(i=0;i<G->vertNum;i++){ L->le[i] = G->p[V][i]; //printf("%d\t",L->le[i]); if(L->le[i] > -1) check =1; } if(check==0) printf("Error!!"),exit(0); for(i=1;i<G->vertNum;i++){ Min = INT_MAX; for(j=0;j<G->vertNum;j++) if(!L->isIn[j]) { if(L->le[j]!=-1&&L->le[j]<Min) { Vk = j, Min= L->le[j]; } } L->isIn[Vk] = true; // 将距离Vx最近的点加入到另外一个集合中 // 也就是说下一次不要比较 lastInsert(P[V],Vk); for(j=0;j<G->vertNum;j++){ if((G->p[Vk][j]!=-1)&&!L->isIn[j] &&(Min+G->p[Vk][j]<L->le[j])) { L->le[j] = Min+G->p[Vk][j]; lastInsert(P[j],Vk); lastInsert(P[j],j); } if(L->le[j]==-1&&(G->p[Vk][j]!=-1)) { L->le[j] = Min+G->p[Vk][j]; lastInsert(P[j],Vk); lastInsert(P[j],j); } } } }
[ "793663370@qq.com" ]
793663370@qq.com
c920188a681790c9053ae2ee4d580ce994232230
46af33c40c0913d0069b4a484369b148653f403d
/Homework/HW2/train-develope-test/Dynamic Perceptron/perceptron.h
eae369a782c173d504a24b1195c01920dc6f7815
[]
no_license
haibara502/Machine-Learning
d154ad669efb5117dead08229fd767c1227afdcc
dafa46c4b4555bcbf0f448832b20091b232171e9
refs/heads/master
2021-08-23T07:36:43.057558
2017-12-04T05:18:02
2017-12-04T05:18:02
103,791,446
0
0
null
null
null
null
UTF-8
C++
false
false
496
h
#ifndef PERCEPTRON #define PERCEPTRON #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <vector> #include "url.h" using namespace std; class Perceptron { vector<double> w; double b; double learningRate; static const int dimension; double getRandom(); int totalUpdate; public: void init(); void setLearningRate(double); void train(Urls); double cv(Urls); double test(Urls); void divideLearningRate(double); }; #endif
[ "haibara502@gmail.com" ]
haibara502@gmail.com
7b32871ea78cdde15809e505c21ec3a4839adb93
f225cb2dd06228408f033a07c6635f5047cf655c
/src/ShrubTundra.cpp
f6d126a9c4934e2d77e05208f90986fa020a448d
[ "MIT" ]
permissive
ua-snap/alfresco
722723ea60550a63125e9d4e4cc18ff14cfba3e5
0e60370eb5e20475f187fe4c5b716c662e187f33
refs/heads/main
2022-11-15T00:58:08.883181
2022-11-07T21:35:25
2022-11-07T21:35:25
3,391,389
3
2
MIT
2022-11-07T21:35:26
2012-02-08T21:10:07
C++
UTF-8
C++
false
false
14,911
cpp
//ShrubTundra.cpp #include "ShrubTundra.h" #include "CustomLandscape.h" //Declare static private members bool ShrubTundra::_isStaticSetupAlready = false; bool ShrubTundra::_isFireProbAgeDependent; bool ShrubTundra::_isInoculumEnabled = false; double* ShrubTundra::_pAgeDependentFireParams; float ShrubTundra::_fireProb; float ShrubTundra::_ignitionDepressor; double ShrubTundra::_seedRange; double* ShrubTundra::_pSeedSource; double ShrubTundra::_seedBasalArea; double ShrubTundra::_seedlingBasalArea; int ShrubTundra::_history; double* ShrubTundra::_pSeedEstParams; double ShrubTundra::_meanGrowth; double* ShrubTundra::_pClimateGrowth; double* ShrubTundra::_pCalibrationFactor; double ShrubTundra::_seedling; double ShrubTundra::_ratioAK = 0.; double ShrubTundra::_tundraSpruceBasalArea; double* ShrubTundra::_pStartAgeParms; double* ShrubTundra::_pIntegral; int ShrubTundra::_spruceTransitionYear; int ShrubTundra::_tundraTransitionYear; std::vector<double> ShrubTundra::_rollingTempMean; std::vector<double> ShrubTundra::_rollingSWIMean; EStartAgeType ShrubTundra::_startAgeType; ShrubTundra::ShrubTundra( const int& rAge, const bool& rIsTopoComplex, const float& rSite, const int& rYearOfLastBurn, const int& rLastBurnSeverity, const double& rFireIgnitionFactor, const double& rFireSensitivity, const Species& rSpecSubCanopy, const int treeDensity) : Frame (rAge, rIsTopoComplex, rSite, rYearOfLastBurn, rLastBurnSeverity, rFireIgnitionFactor, rFireSensitivity, rSpecSubCanopy) { _ShrubTundra(treeDensity); } ShrubTundra:: ShrubTundra(const Frame& rFrame, const int treeDensity) : Frame(rFrame) { _yearEstablished = gYear; _yearFrameEstablished = gYear; _ShrubTundra(treeDensity); _basalArea = rFrame.basalArea(); _inoculumScore = rFrame.inoculumScore(); } void ShrubTundra:: _ShrubTundra(const int treeDensity) //Local constructor - Initialize the local member variables and give the frame an initial age. //Default values are specified for all the arguments. However, it is desired to pull the //default tree density from the initialization file so the user can specify this on the fly. As a result, //a default argument for TreeDensity is provided, but it is overwritten if possible. { if (!_isStaticSetupAlready) throw SimpleException(SimpleException::UNKNOWN, "Static data members must be set before initializing species."); //Calc a starting age if not yet assigned. if (gFirstYear-1==_yearEstablished) { if (_startAgeType==CONSTANT) { _yearEstablished = _yearFrameEstablished = gFirstYear - (int)(GetNextRandom() * _pStartAgeParms[0]); } else { const double random = GetNextRandom(); int age = 0; while (random > _pIntegral[age++]); _yearEstablished = _yearFrameEstablished = gFirstYear + 1 - age; } } //Do other initializations if (treeDensity <= 0) _basalArea = 0.; else _basalArea = getInitialBasalArea(); _yearOfEstablishment = 0; //OLD TODO: _yearOfEstablishment = -_history; _degrees = -1; if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["enableInoculum"])){ _isInoculumEnabled = FRESCO->fif().root["Vegetation"]["enableInoculum"].asBool(); } if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Inoculum"])){ _inoculumMax = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Inoculum"].asDouble(); } else { _inoculumMax = 1.0; } if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["InoculumReturn"])){ _inoculumReturn= FRESCO->fif().root["Vegetation"]["ShrubTundra"]["InoculumReturn"].asDouble(); } else { _inoculumReturn = 1.0; } if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["InoculumBA"])){ _inoculumBA = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["InoculumBA"].asDouble(); } else { _inoculumBA = 1.0; } _inoculumScore = _inoculumMax; } ShrubTundra:: ~ShrubTundra() { } void ShrubTundra:: setStaticData() { if (!_isStaticSetupAlready) { _humanIgnitionsProb = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["HumanFireProb"].asDouble(); _isFireProbAgeDependent = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["FireProb.IsAgeDependent"].asBool(); if (_isFireProbAgeDependent) { if (3 != FRESCO->fif().pdGet(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["FireProb"], _pAgeDependentFireParams)) throw SimpleException(SimpleException::BADARRAYSIZE, "Expected array size of 3 for key: ShrubTundra.FireProb (because Tundra.FireProb.IsAgeDependent is set to TRUE)"); } else _fireProb = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["FireProb"].asDouble(); if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["IgnitionDepressor"])) _ignitionDepressor = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["IgnitionDepressor"].asDouble(); else _ignitionDepressor = 1; _history = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["History"].asInt(); _seedRange = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SeedRange"].asDouble(); _seedBasalArea = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Seed.BasalArea"].asDouble(); _seedling = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Seedling"].asDouble(); _seedlingBasalArea = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SeedlingBA"].asDouble(); _tundraSpruceBasalArea = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Spruce.BasalArea"].asDouble(); _pStartAgeParms = FRESCO->getStartAgeParms(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["StartAge"], &_startAgeType); _meanGrowth = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["MeanGrowth"].asDouble(); if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SpruceTransitionYear"])){ _spruceTransitionYear = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SpruceTransitionYear"].asInt(); } else { _spruceTransitionYear = 0; } if (FRESCO->fif().CheckKey(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["TundraTransitionYear"])){ _tundraTransitionYear = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["TundraTransitionYear"].asInt(); } else { _tundraTransitionYear = 0; } if (2 != FRESCO->fif().pdGet(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SeedEstParms"], _pSeedEstParams)) { throw SimpleException(SimpleException::BADARRAYSIZE, "Expected array size of 2 for key: ShrubTundra.SeedEstParms"); } if (3 != FRESCO->fif().pdGet(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["ClimGrowth"], _pClimateGrowth)) { throw SimpleException(SimpleException::BADARRAYSIZE, "Expected array size of 3 for key: ShrubTundra.ClimGrowth"); } if (2 != FRESCO->fif().pdGet(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["CalFactor"], _pCalibrationFactor)) { throw SimpleException(SimpleException::BADARRAYSIZE, "Expected array size of 2 for key: ShrubTundra.CalFactor"); } if (2 != FRESCO->fif().pdGet(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["SeedSource"], _pSeedSource)) { throw SimpleException(SimpleException::BADARRAYSIZE, "Expected array size of 2 for key: ShrubTundra.SeedSource"); } //Calculate _ratioAK for use in getInitialBasalAreaI() double spruceEstBasalAarea = FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Spruce.EstBA"].asDouble(); const double pSeedSourceFatTailParams[3] = {gCellSize, _pSeedSource[0], _pSeedSource[1]}; //Parameters for calling FatTail() const double alpha = _pCalibrationFactor[1] * spruceEstBasalAarea * _seedBasalArea * FatTail(pSeedSourceFatTailParams) / _seedling * _seedlingBasalArea; double k = _pCalibrationFactor[0] * _meanGrowth; _ratioAK = (k != 0) ? alpha/k : 0; if (_startAgeType==WEIBULL) { int length = (int)(5*_pStartAgeParms[0]); _pIntegral = new double[length]; Integrate (WeibullReliability, _pStartAgeParms, _pIntegral, 0, length-1, 1.); //Normalize so the integral is 1. for (int i=0; i<length; i++) _pIntegral[i] /= _pIntegral[length-1]; } _isStaticSetupAlready = true; } } void ShrubTundra:: clear() //Clear existing run if any and return to before a run is specified. { _isStaticSetupAlready = false; _fireProb = 0; _ignitionDepressor = 1; _seedRange = 0; _seedBasalArea = 0; _seedlingBasalArea = 0; _history = 0; _meanGrowth = 0; _seedling = 0; _tundraSpruceBasalArea = 0; delete[] _pIntegral; _pIntegral = 0; _startAgeType = CONSTANT; } float ShrubTundra::getAsFloat(RasterIO::ALFMapType mapType) { switch(mapType) { case RasterIO::TUNDRA_BASAL_AREA: return (float)_basalArea; break; default: throw Poco::Exception("This frame type ("+ToS((int)type())+") does not support the map type ("+ RasterIO::getMapTypeAsString(mapType) + ")"); } } Frame *ShrubTundra:: success(Landscape* pParent) //This function provides the successional information for the tundra frame. It is expected to return NULL //if the frame type does not change, and a pointer to a new frame if a transition occurs. The general //model used is to check immediate post burn stuff first, then time dependant state changes, and then //general (long term) state changes. Specific algorithms are documented in the code { if(FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Transitions"].asBool()){ //Check immediately after burn const int yearsSinceLastBurn = gYear - yearOfLastBurn; if (yearsSinceLastBurn == 1) { if (burnSeverity == HIGH_HSS){ //Reduce basal area to 0 _basalArea = 0.; //Reduce incoculum to 20% if (_isInoculumEnabled){ _inoculumScore *= 0.2; } if (gYear >= _tundraTransitionYear && _tundraTransitionYear > 0){ return new GraminoidTundra(*this); } } else if (burnSeverity == HIGH_LSS){ //Reduce basal area by 50% _basalArea *= 0.5; //Reduce incoculum to 50% if (_isInoculumEnabled){ _inoculumScore *= 0.5; } } else if (burnSeverity == MODERATE){ //Reduce basal area by 50% _basalArea *= 0.5; } else if (burnSeverity == LOW){ //Unchanged _basalArea = _basalArea; } //if (burnSeverity == HIGH_LSS || burnSeverity == HIGH_HSS ){ } if (_isInoculumEnabled){ if (_inoculumScore < _inoculumMax){ _inoculumScore += _inoculumReturn; if (_inoculumScore > _inoculumMax){ _inoculumScore = _inoculumMax; } } } float movingTempAverage = 0; float movingSWIAverage = 0; //Check to see if _rollingTempMean has been setup, or if this is the first pass if (_rollingTempMean.size() < 10){ _rollingTempMean.push_back(pParent->cellTempByMonth(7)); } else { _rollingTempMean.erase (_rollingTempMean.begin()); _rollingTempMean.push_back(pParent->cellTempByMonth(7)); } for (int i = 0; i < _rollingTempMean.size(); i++){ movingTempAverage += _rollingTempMean[i]; } movingTempAverage /= 10.0; float summerWarmthIndex = 0; if (pParent->cellTempByMonth(3) > 0){ summerWarmthIndex += pParent->cellTempByMonth(3); } if (pParent->cellTempByMonth(4) > 0){ summerWarmthIndex += pParent->cellTempByMonth(4); } if (pParent->cellTempByMonth(5) > 0){ summerWarmthIndex += pParent->cellTempByMonth(5); } if (pParent->cellTempByMonth(6) > 0){ summerWarmthIndex += pParent->cellTempByMonth(6); } if (pParent->cellTempByMonth(7) > 0){ summerWarmthIndex += pParent->cellTempByMonth(7); } if (_rollingSWIMean.size() < 10){ _rollingSWIMean.push_back(summerWarmthIndex); } else { _rollingSWIMean.erase (_rollingSWIMean.begin()); _rollingSWIMean.push_back(summerWarmthIndex); } for (int i = 0; i < _rollingSWIMean.size(); i++){ movingSWIAverage += _rollingSWIMean[i]; } movingSWIAverage /= 10.0; if (gYear >= _spruceTransitionYear && _spruceTransitionYear > 0){ if (movingTempAverage >= 10.0 && movingTempAverage <= 20.0){ double params[3] = {0., _pSeedSource[0], _pSeedSource[1]}; //The first location will get set to the actual distance double seeds; params[0] = 0; if (_isInoculumEnabled){ seeds = pParent->neighborsSuccess(&Frame::queryReply, &FatTail, _seedRange, params); //Find the neighborhood seed source - returns the weighted basal area seeds -= queryReply(pParent, FatTail (params)); seeds *= _seedBasalArea; } else { seeds = pParent->neighborsSuccess(&Frame::queryReply, &FatTail, _seedRange, params); //Find the neighborhood seed source - returns the weighted basal area seeds -= queryReply(pParent, FatTail (params)); seeds *= _seedBasalArea; } double modSeedling = 1; // Modified seedling ratio based on Burn Severity if (yearsSinceLastBurn <= 5){ if (burnSeverity == MODERATE || burnSeverity == HIGH_HSS){ modSeedling = 0.5; } else if (burnSeverity == HIGH_LSS){ modSeedling = 0.1; } } seeds /= (_seedling * modSeedling); if (_basalArea == 0 && seeds > 0) { _yearOfEstablishment = gYear; } double gparams[3] = {movingTempAverage, 15., 2.}; //The first location will get set to the actual distance double modGrowth = NormDist(gparams); modGrowth *= 5; double baFromGrowth = 0; if (_basalArea > 0){ baFromGrowth = -(_basalArea *_basalArea) * (0.00025) + (modGrowth * 0.2); if (_isInoculumEnabled && _basalArea < _inoculumBA){ baFromGrowth *= _inoculumScore; } } double baFromSeed = 0; if (seeds > 0.00001){ baFromSeed = seeds * _seedlingBasalArea; } _basalArea += baFromGrowth + baFromSeed; } //Transition if necessary if (_basalArea >= FRESCO->fif().root["Vegetation"]["ShrubTundra"]["Spruce.EstBA"].asDouble()) { return new WSpruce(*this); } } } return NULL; } double ShrubTundra:: getInitialBasalArea() //Returns an initial basal area for the cell based on the distribution derived in ShrubTundra.doc //and BasalArea.xls!PDFTest. Basically selects a basal area from a distribution which matches the //expected growth curve generated by the Excel model. Hence the inital basal area distribution //matches what one would expect at any given time. This reduces initial condition purturbations. { if (_ratioAK) return _ratioAK * ( pow(_tundraSpruceBasalArea/_ratioAK + 1.,(double) GetNextRandom()) - 1 ); else return 0.; }
[ "alec@alecbennett.com" ]
alec@alecbennett.com
1b2ba8cfad9416a4319bf3e5f69b11b6b2890514
5a77b5092acf817ac37a5fafd006feea434dd0d6
/Doxygen_Graphviz/DesignPatternExample/大話/cpp/command/Waiter.h
069ce813edff2fdb9a3f0dcfb74671040487e74d
[]
no_license
shihyu/MyTool
dfc94f507b848fb112483a635ef95e6a196c1969
3bfd1667ad86b3db63d82424cb4fa447cbe515af
refs/heads/master
2023-05-27T19:09:10.538570
2023-05-17T15:58:18
2023-05-17T15:58:18
14,722,815
33
21
null
null
null
null
UTF-8
C++
false
false
588
h
#pragma once #include "Command.h" #include <vector> namespace command { class Waiter { public: std::vector<Command*> orders; virtual void setOrder(Command* com); virtual void cancelOrder(Command* com); virtual void excute(); private: bool initialized; void InitializeInstanceFields() { if (! initialized) { orders = std::vector<Command*>(); initialized = true; } } public: Waiter() { InitializeInstanceFields(); } }; }
[ "jason_yao@htc.com" ]
jason_yao@htc.com
b6313cd5127afc12cf28e777b1e020718dd57873
c56e4f8cefae38364203457a60e5ff34a183ef0d
/src/main.cpp
93e17e9a4dd67abb17bd512c2bc1446f87d647be
[]
no_license
kosievdmerwe/YOTD
d03b0e6f6969cdb67a6d36d584f1c2ae8a205643
d6197331c54d922b93982e9f34d50f0212af70cf
refs/heads/master
2016-09-16T13:37:44.133834
2010-06-30T22:55:03
2010-06-30T22:55:03
745,112
1
0
null
null
null
null
UTF-8
C++
false
false
124
cpp
#include <iostream> using namespace std; int main(int argc, char** argv) { cout << "Hello World" << endl; return 0; }
[ "kosie.vandermerwe@gmail.com" ]
kosie.vandermerwe@gmail.com
8a18e9878c3f2f9e70947b04cb3444f7c3a479de
9f29a51abaef36255aae164864d5cac59de07291
/Source/Samples/20_HugeObjectCount/HugeObjectCount.cpp
9e8d649bb6e48e8d8c172da470e7bdce780ce06c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
taohuadao/Urho3D
50213e52ba3f7490435de5fe9379695539d75630
b094fe3d1273b1136b918d5c81b225182de74d8f
refs/heads/master
2023-08-18T05:08:19.121954
2023-08-10T03:49:54
2023-08-10T03:49:54
324,118,542
0
0
MIT
2020-12-24T09:30:45
2020-12-24T09:30:45
null
UTF-8
C++
false
false
8,552
cpp
// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/Profiler.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Material.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/StaticModelGroup.h> #include <Urho3D/Graphics/Zone.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/UI.h> #include "HugeObjectCount.h" #include <Urho3D/DebugNew.h> URHO3D_DEFINE_APPLICATION_MAIN(HugeObjectCount) HugeObjectCount::HugeObjectCount(Context* context) : Sample(context), animate_(false), useGroups_(false) { } void HugeObjectCount::Start() { // Execute base class startup Sample::Start(); // Create the scene content CreateScene(); // Create the UI content CreateInstructions(); // Setup the viewport for displaying the scene SetupViewport(); // Hook up to the frame update events SubscribeToEvents(); // Set the mouse mode to use in the sample Sample::InitMouseMode(MM_RELATIVE); } void HugeObjectCount::CreateScene() { auto* cache = GetSubsystem<ResourceCache>(); if (!scene_) scene_ = new Scene(context_); else { scene_->Clear(); boxNodes_.Clear(); } // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume // (-1000, -1000, -1000) to (1000, 1000, 1000) scene_->CreateComponent<Octree>(); // Create a Zone for ambient light & fog control Node* zoneNode = scene_->CreateChild("Zone"); auto* zone = zoneNode->CreateComponent<Zone>(); zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f)); zone->SetFogColor(Color(0.2f, 0.2f, 0.2f)); zone->SetFogStart(200.0f); zone->SetFogEnd(300.0f); // Create a directional light Node* lightNode = scene_->CreateChild("DirectionalLight"); lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized auto* light = lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_DIRECTIONAL); if (!useGroups_) { light->SetColor(Color(0.7f, 0.35f, 0.0f)); // Create individual box StaticModels in the scene for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { Node* boxNode = scene_->CreateChild("Box"); boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f)); boxNode->SetScale(0.25f); auto* boxObject = boxNode->CreateComponent<StaticModel>(); boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl")); boxNodes_.Push(SharedPtr<Node>(boxNode)); } } } else { light->SetColor(Color(0.6f, 0.6f, 0.6f)); light->SetSpecularIntensity(1.5f); // Create StaticModelGroups in the scene StaticModelGroup* lastGroup = nullptr; for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { // Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling // accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform // does not matter, and it does not render anything if instance nodes are not added to it if (!lastGroup || lastGroup->GetNumInstanceNodes() >= 25 * 25) { Node* boxGroupNode = scene_->CreateChild("BoxGroup"); lastGroup = boxGroupNode->CreateComponent<StaticModelGroup>(); lastGroup->SetModel(cache->GetResource<Model>("Models/Box.mdl")); } Node* boxNode = scene_->CreateChild("Box"); boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f)); boxNode->SetScale(0.25f); boxNodes_.Push(SharedPtr<Node>(boxNode)); lastGroup->AddInstanceNode(boxNode); } } } // Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it if (!cameraNode_) { cameraNode_ = new Node(context_); cameraNode_->SetPosition(Vector3(0.0f, 10.0f, -100.0f)); auto* camera = cameraNode_->CreateComponent<Camera>(); camera->SetFarClip(300.0f); } } void HugeObjectCount::CreateInstructions() { auto* cache = GetSubsystem<ResourceCache>(); auto* ui = GetSubsystem<UI>(); // Construct new Text object, set string to display and font to use auto* instructionText = ui->GetRoot()->CreateChild<Text>(); instructionText->SetText( "Use WASD keys and mouse/touch to move\n" "Space to toggle animation\n" "G to toggle object group optimization" ); instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15); // The text has multiple rows. Center them in relation to each other instructionText->SetTextAlignment(HA_CENTER); // Position the text relative to the screen center instructionText->SetHorizontalAlignment(HA_CENTER); instructionText->SetVerticalAlignment(VA_CENTER); instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4); } void HugeObjectCount::SetupViewport() { auto* renderer = GetSubsystem<Renderer>(); // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>())); renderer->SetViewport(0, viewport); } void HugeObjectCount::SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HugeObjectCount, HandleUpdate)); } void HugeObjectCount::MoveCamera(float timeStep) { // Do not move if the UI has a focused element (the console) if (GetSubsystem<UI>()->GetFocusElement()) return; auto* input = GetSubsystem<Input>(); // Movement speed as world units per second const float MOVE_SPEED = 20.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY = 0.1f; // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees IntVector2 mouseMove = input->GetMouseMove(); yaw_ += MOUSE_SENSITIVITY * mouseMove.x_; pitch_ += MOUSE_SENSITIVITY * mouseMove.y_; pitch_ = Clamp(pitch_, -90.0f, 90.0f); // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f)); // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (input->GetKeyDown(KEY_W)) cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_S)) cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_A)) cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_D)) cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep); } void HugeObjectCount::AnimateObjects(float timeStep) { URHO3D_PROFILE(AnimateObjects); const float ROTATE_SPEED = 15.0f; // Rotate about the Z axis (roll) Quaternion rotateQuat(ROTATE_SPEED * timeStep, Vector3::FORWARD); for (const SharedPtr<Node>& boxNode : boxNodes_) boxNode->Rotate(rotateQuat); } void HugeObjectCount::HandleUpdate(StringHash eventType, VariantMap& eventData) { using namespace Update; // Take the frame time step, which is stored as a float float timeStep = eventData[P_TIMESTEP].GetFloat(); // Toggle animation with space auto* input = GetSubsystem<Input>(); if (input->GetKeyPress(KEY_SPACE)) animate_ = !animate_; // Toggle grouped / ungrouped mode if (input->GetKeyPress(KEY_G)) { useGroups_ = !useGroups_; CreateScene(); } // Move the camera, scale movement with time step MoveCamera(timeStep); // Animate scene if enabled if (animate_) AnimateObjects(timeStep); }
[ "dao.taohua@gmail.com" ]
dao.taohua@gmail.com
94789cc33bedd9a555a38938234b12068a7dd671
b11b7c6cd7f62ae05f53e9e0681919d510e74404
/simplerainbowshift/simplerainbowshift.ino
e20980ad36d20967079857c9c5e0241487e611f0
[]
no_license
Sm0k3scr33n/fun_with_neopixels
7c78b614b463f9b149c8697b2cfb13abbb9ecea8
0fe4c9834ddf57c87dbf9901d9915fcea3f08300
refs/heads/master
2021-01-13T10:26:59.296463
2020-03-01T07:34:03
2020-03-01T07:34:03
72,259,598
0
0
null
null
null
null
UTF-8
C++
false
false
7,818
ino
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson // released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif // Which pin on the Arduino is connected to the NeoPixels? #define PIN 4 // How many NeoPixels are attached to the Arduino? #define NUMPIXELS 7 // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest // example for more information on possible values. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); #define DELAYVAL 500 // Time (in milliseconds) to pause between pixels int rgbLights = 7; int red[7]; int green[7]; int blue[7]; void setup() { pixels.begin(); // This initializes the NeoPixel library. } void hsi_to_rgb(int startChannel, float H, float S, float I) { int r, g, b; // if (H > 360) { // H = H - 360; // } // Serial.println("H: "+String(H)); H = fmod(H, 360); // cycle H around to 0-360 degrees H = 3.14159 * H / (float)180; // Convert to radians. S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1] I = I > 0 ? (I < 1 ? I : 1) : 0; if (H < 2.09439) { r = 255 * I / 3 * (1 + S * cos(H) / cos(1.0471967 - H)); g = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.0471967 - H))); b = 255 * I / 3 * (1 - S); } else if (H < 4.188787) { H = H - 2.09439; g = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667 - H)); b = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.0471967 - H))); r = 255 * I / 3 * (1 - S); } else { H = H - 4.188787; b = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667 - H)); r = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.0471967 - H))); g = 255 * I / 3 * (1 - S); } red[startChannel] = r; green[startChannel] = g; blue[startChannel] = b; } void rainbowShift(float brightness, float saturation, int delayint, int interval) { for (int n = 0; n <= 360; n++) { for (int i = 0, j = 0; i < NUMPIXELS; i++) { //We initialize each value of each pixel with the hsi to rgb function hsi_to_rgb(i, (n + i)*interval, saturation, brightness) ; //Serial.println("rgb" +String(i)+": "+String(rgb[j])+","+String(rgb[j+1])+","+String(rgb[j+2])); pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); j++; } // This sends the updated pixel color to the hardware. pixels.show(); delay(delayint); } } void rainbowShiftRv(float brightness, float saturation, int delayint, int interval) { for (int n = 360; n >= 0; n--) { for (int i = 0, j = 0; i < NUMPIXELS; i++) { hsi_to_rgb(i, (n + i)*interval, saturation, brightness) ; pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); j++; } pixels.show(); // This sends the updated pixel color to the hardware. delay(delayint); } } void rainbowShiftEveryOther(float brightness, float saturation, int delayint) { for (int n = 0; n <= 360; n++) { for (int i = 0; i < NUMPIXELS; i = i + 2) { hsi_to_rgb(i, n, saturation, brightness) ; } for (int i = 1; i < NUMPIXELS; i = i + 2) { hsi_to_rgb(i, n + 180, saturation, brightness) ; } for (int i = 0; i < NUMPIXELS; i++) { pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); } pixels.show(); // This sends the updated pixel color to the hardware. delay(delayint); } } void rainbowShiftSegments(float brightness, float saturation, int delayint) { for (int n = 0; n <= 360; n++) { for (int i = 0; i < NUMPIXELS; i = i + 4) { hsi_to_rgb(i, n, saturation, brightness) ; } for (int i = 1; i < NUMPIXELS; i = i + 4) { hsi_to_rgb(i, n + 60, saturation, brightness) ; } for (int i = 2; i < NUMPIXELS; i = i + 4) { hsi_to_rgb(i, n + 120, saturation, brightness) ; } for (int i = 3; i < NUMPIXELS; i = i + 4) { hsi_to_rgb(i, n + 180, saturation, brightness) ; } for (int i = 0; i < NUMPIXELS; i++) { pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); } pixels.show(); // This sends the updated pixel color to the hardware. delay(delayint); } } void rainbowShiftHalves() { float brightness = .5; float saturation = 1; for (int n = 0; n <= 360; n++) { for (int i = 6, j = 0; i < NUMPIXELS; i++, j++) { //We initialize each value of each pixel with the hsi to rgb function hsi_to_rgb(i, n, saturation, brightness) ; hsi_to_rgb(j, n + 180, saturation, brightness) ; //Serial.println("rgb" +String(i)+": "+String(rgb[j])+","+String(rgb[j+1])+","+String(rgb[j+2])); pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); pixels.setPixelColor(j, pixels.Color(red[j], green[j], blue[j])); } // This sends the updated pixel color to the hardware. pixels.show(); delay(25); } } void theaterChaseRainbow(uint8_t wait) { float brightness = .5; float saturation = 1; for (int j = 0; j < 360; j++) { // cycle all 360 colors in the hsi color space for (int q = 0; q < 3; q++) { for (uint16_t i = 0; i < NUMPIXELS; i = i + 3) { hsi_to_rgb(i, j, saturation, brightness) ; pixels.setPixelColor(i + q, red[i], green[i], blue[i]); //turn every third pixel on } pixels.show(); delay(wait); for (uint16_t i = 0; i < NUMPIXELS; i = i + 3) { pixels.setPixelColor(i + q, 0); //turn every third pixel off } } } } void colorShift(float brightness, float saturation, int delayint) { // float brightness = .5; // float saturation = 1; for (int n = 0; n <= 360; n++) { for (int i = 0, j = 0; i < NUMPIXELS; i++) { //We initialize each value of each pixel with the hsi to rgb function hsi_to_rgb(i, n, saturation, brightness) ; //Serial.println("rgb" +String(i)+": "+String(rgb[j])+","+String(rgb[j+1])+","+String(rgb[j+2])); pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); j++; } // This sends the updated pixel color to the hardware. pixels.show(); delay(delayint); } } // // void colorshift(int delyValue, int pixel, int startColor, int endColor){ // // // for(){} void rainbowShiftHalves(float brightness, float saturation, int delayint, int interval) { for (int n = 0; n <= 360; n++) { for (int i = 0, j = 0; i < NUMPIXELS; i++) { //We initialize each value of each pixel with the hsi to rgb function hsi_to_rgb(i, (n + i)*interval, saturation, brightness) ; //Serial.println("rgb" +String(i)+": "+String(rgb[j])+","+String(rgb[j+1])+","+String(rgb[j+2])); pixels.setPixelColor(i, pixels.Color(red[i], green[i], blue[i])); j++; } // This sends the updated pixel color to the hardware. pixels.show(); delay(delayint); } } void loop() { //function does not work well // rainbowShiftHalves(); // //theaterChaseRainbow(50); // rainbowShiftHalves(.7,1,25,30); // rainbowShiftEveryOther(.7,1,25); // rainbowShiftHalves(.7,1,random(10, 200),random(1,50)); colorShift(.7,1,random(10, 200)); colorShift(.7,1,random(10, 200)); rainbowShiftSegments(.7,1,random(10, 200)); rainbowShiftEveryOther(.7,1,random(10, 200)); rainbowShift(.7,1,random(10, 200),random(1,50)); rainbowShiftHalves(.7,1,random(10, 200),random(1,50)); colorShift(.7,1,random(100, 500)); /* rainbowShift(.7,2,25,30); colorShift(.7,1,75); rainbowShiftRv(.7,1,25,30); rainbowShiftRv(.7,1,150,6); colorShift(.7,1,random(10, 1000)); rainbowShiftHalves(.7,1,25,2); rainbowShiftEveryOther(.7,1,25); colorShift(.7,1,25); */ }
[ "ben.gabbard@live.com" ]
ben.gabbard@live.com
d5fe9c4d78291002205a36a72fe3707a88db16d1
667672d0f110eb8947fba0d012e4ebb56fe26012
/week-09/day-1/ex03/Fibonacci-test.cpp
0368a6b1f1cf7f682c816d17294bd4a285ecb4c7
[]
no_license
greenfox-zerda-sparta/javorszkymazsi
81190253fb1b66f5c6957587751b5849cbaa5345
8a1a8145d01961a217a5dd78b0f158947f01093f
refs/heads/master
2021-01-11T05:46:05.594604
2017-02-03T11:17:31
2017-02-03T11:17:31
71,350,495
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include "catch.h" #include "Fibonacci.h" TEST_CASE("Zeroth element in fibonacci") { Fibonacci fib(0); REQUIRE(fib.find_fibonacci(0) == 0); } TEST_CASE("First element in fibonacci") { Fibonacci fib(1); REQUIRE(fib.find_fibonacci(1) == 1); } TEST_CASE("Several elements in fibonacci") { Fibonacci fib(4); REQUIRE(fib.find_fibonacci(4) == 3); }
[ "javorszky.mariann@gmail.com" ]
javorszky.mariann@gmail.com
f0d459e747f3e1e7fce6a4add7097978ce257545
b5f525109f445945007761fe44ef0cca8220a3ef
/MFCtest2/MFCtest2/MFCtest2Doc.h
9ae3f521624341728863ad4926a36b70c7c555b9
[]
no_license
GXNUWHY/Test
9b584f22dc051586293406012d062ee66329dc59
fdb093f448430506c7ec572cb65e8de0f266e6fe
refs/heads/master
2021-02-13T02:22:57.503836
2020-06-02T11:10:20
2020-06-02T11:10:20
244,652,320
1
0
null
null
null
null
UTF-8
C++
false
false
880
h
 // MFCtest2Doc.h: CMFCtest2Doc 类的接口 // #pragma once class CMFCtest2Doc : public CDocument { protected: // 仅从序列化创建 CMFCtest2Doc() noexcept; DECLARE_DYNCREATE(CMFCtest2Doc) // 特性 public: // 操作 public: CRect rect; // 重写 public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // 实现 public: virtual ~CMFCtest2Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // 用于为搜索处理程序设置搜索内容的 Helper 函数 void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
[ "1183448845@qq.com" ]
1183448845@qq.com
816fc41abca5352cef48005885747ad013cd9e05
b6a92b2cd173131cd3280fe08198bfff4bb207fa
/Source/ProiectPoo_BalanTheodor_DamianStefan/Haine.h
f2ef61b112a741dd9cc11ccedabaecbd93caeebb
[]
no_license
Cioger/Proiect-POO-2021
58fb607cda011cf34fe3cc4adb3c3fd6f81ed5bd
e41fdc5a56cbe965be06903c090df1fd201f2f6f
refs/heads/main
2023-04-13T17:14:50.445751
2021-04-18T18:32:31
2021-04-18T18:32:31
328,492,042
0
0
null
null
null
null
UTF-8
C++
false
false
824
h
#pragma once #include <iostream> #include <string> using namespace std; enum class Marime { XS, S, M, L, XL }; class Haine { protected: int id; string descriere; float pret; string firma; bool inStoc; Marime marime; public: Haine(); Haine(int id, string descriere, float pret, string firma, bool inStoc, Marime marime); Haine(const Haine& p); int getId(); string getDescriere(); float getPret(); string getFirma(); bool getStoc(); Marime getMarime(); void setId(int id); void setDescriere(string descriere); void setPret(float pret); void setFirma(string firma); void setStoc(bool inStoc); void setMarime(Marime marime); virtual void updateTot(); virtual string Afisare(); //operatori void operator=(Haine p); Haine operator+=(int bt); virtual Haine operator-=(int ds); ~Haine(); };
[ "blntheodor@gmail.com" ]
blntheodor@gmail.com
b37aa780b53726717b09f937ff0146e96df760cc
071c74384fb6e929ef37b5ff712d21e6f147d10c
/NyxWebSvr/Source/Header_Impl.cpp
50069e7ed6528d5a06670c3a5d673694d17d065d
[]
no_license
cobreti/Nyx
410597bd763ed2c6583f212f63ba26f1ea3f8c36
0c62ba53a2999ad80d7f20f6bbebb00f1247f673
refs/heads/master
2016-09-05T11:54:24.773722
2014-08-10T13:21:46
2014-08-10T13:21:46
5,074,458
0
0
null
null
null
null
UTF-8
C++
false
false
398
cpp
// // Header_Impl.cpp // NyxWebSvr // // Created by Danny Thibaudeau on 2013-05-13. // Copyright (c) 2013 Danny Thibaudeau. All rights reserved. // #include <stdio.h> #include "Header_Impl.hpp" namespace NyxWebSvr { /** * */ CHeader_Impl::CHeader_Impl() { } /** * */ CHeader_Impl::~CHeader_Impl() { } }
[ "cobreti_@hotmail.com" ]
cobreti_@hotmail.com
41c680d94cb8d37ff44cd0cab09108a796f616fd
b0cc49d489bf2163829848881ef1ba3c9cf720ee
/qtconnectivity/src/nfc/qllcpsocket_maemo6_p.h
bd4d5cf2187e4fe86026e592619eeccfe5a29842
[]
no_license
mer-packages/qtconnectivity
8724ed57206c35883145af8e47774ab9dff25e49
c49489493e344b1dabedc5c687dab8cb349e3cb9
refs/heads/master
2021-01-25T08:28:56.284744
2013-07-26T11:23:41
2013-07-26T11:23:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,026
h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNfc module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QLLCPSOCKET_MAEMO6_P_H #define QLLCPSOCKET_MAEMO6_P_H #include <qconnectivityglobal.h> #include "qllcpsocket.h" #include <QtDBus/QDBusConnection> QT_FORWARD_DECLARE_CLASS(QDBusObjectPath) QT_FORWARD_DECLARE_CLASS(QDBusVariant) QT_FORWARD_DECLARE_CLASS(QSocketNotifier) class AccessRequestorAdaptor; class LLCPRequestorAdaptor; QT_BEGIN_NAMESPACE_NFC class SocketRequestor; class QLlcpSocketPrivate : public QObject { Q_OBJECT Q_DECLARE_PUBLIC(QLlcpSocket) public: QLlcpSocketPrivate(QLlcpSocket *q); QLlcpSocketPrivate(const QDBusConnection &connection, int fd, const QVariantMap &properties); ~QLlcpSocketPrivate(); void connectToService(QNearFieldTarget *target, const QString &serviceUri); void disconnectFromService(); bool bind(quint8 port); bool hasPendingDatagrams() const; qint64 pendingDatagramSize() const; qint64 writeDatagram(const char *data, qint64 size); qint64 writeDatagram(const QByteArray &datagram); qint64 readDatagram(char *data, qint64 maxSize, QNearFieldTarget **target = 0, quint8 *port = 0); qint64 writeDatagram(const char *data, qint64 size, QNearFieldTarget *target, quint8 port); qint64 writeDatagram(const QByteArray &datagram, QNearFieldTarget *target, quint8 port); QLlcpSocket::SocketError error() const; QLlcpSocket::SocketState state() const; qint64 readData(char *data, qint64 maxlex, quint8 *port = 0); qint64 writeData(const char *data, qint64 len); qint64 bytesAvailable() const; bool canReadLine() const; bool waitForReadyRead(int msecs); bool waitForBytesWritten(int msecs); bool waitForConnected(int msecs); bool waitForDisconnected(int msecs); bool waitForBound(int msecs); private slots: // com.nokia.nfc.AccessRequestor void AccessFailed(const QDBusObjectPath &targetPath, const QString &kind, const QString &error); void AccessGranted(const QDBusObjectPath &targetPath, const QString &accessKind); // com.nokia.nfc.LLCPRequestor void Accept(const QDBusVariant &lsap, const QDBusVariant &rsap, int fd, const QVariantMap &properties); void Connect(const QDBusVariant &lsap, const QDBusVariant &rsap, int fd, const QVariantMap &properties); void Socket(const QDBusVariant &lsap, int fd, const QVariantMap &properties); void _q_readNotify(); void _q_bytesWritten(); private: void setSocketError(QLlcpSocket::SocketError socketError); void initializeRequestor(); QLlcpSocket *q_ptr; QVariantMap m_properties; QList<QByteArray> m_receivedDatagrams; QDBusConnection m_connection; QString m_serviceUri; quint8 m_port; QString m_requestorPath; SocketRequestor *m_socketRequestor; int m_fd; QSocketNotifier *m_readNotifier; QSocketNotifier *m_writeNotifier; qint64 m_pendingBytes; QLlcpSocket::SocketState m_state; QLlcpSocket::SocketError m_error; }; QT_END_NAMESPACE_NFC #endif // QLLCPSOCKET_MAEMO6_P_H
[ "carsten.munk@jollamobile.com" ]
carsten.munk@jollamobile.com
99b3a1d8c13d072cbd3a2dee486fe06b36c62f49
0dab02d9be3666b41dca3ce6a6180134d5a6a8eb
/liveMedia/FramedSource.hh
772c41a43c7c0e8e2dd94f6d49b8dc70bdc808e1
[ "Apache-2.0" ]
permissive
lwg82/live555
3908f55decd84d0926d1f0d9e32526806a04dd46
091f56fe7cf3123e11cdbb68ac83357e50a413c4
refs/heads/master
2020-03-18T11:49:19.011443
2018-06-01T09:19:33
2018-06-01T09:19:33
134,693,035
0
0
null
null
null
null
UTF-8
C++
false
false
3,079
hh
/********** 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 3 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2017 Live Networks, Inc. All rights reserved. // Framed Sources // C++ header #ifndef _FRAMED_SOURCE_HH #define _FRAMED_SOURCE_HH #ifndef _NET_COMMON_H #include "NetCommon.h" #endif #ifndef _MEDIA_SOURCE_HH #include "MediaSource.hh" #endif class FramedSource: public MediaSource { public: static Boolean lookupByName(UsageEnvironment& env, char const* sourceName, FramedSource*& resultSource); typedef void (afterGettingFunc)(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); typedef void (onCloseFunc)(void* clientData); void getNextFrame(unsigned char* to, unsigned maxSize, afterGettingFunc* afterGettingFunc, void* afterGettingClientData, onCloseFunc* onCloseFunc, void* onCloseClientData); static void handleClosure(void* clientData); void handleClosure(); // This should be called (on ourself) if the source is discovered // to be closed (i.e., no longer readable) void stopGettingFrames(); virtual unsigned maxFrameSize() const; // size of the largest possible frame that we may serve, or 0 // if no such maximum is known (default) virtual void doGetNextFrame() = 0; // called by getNextFrame() Boolean isCurrentlyAwaitingData() const {return fIsCurrentlyAwaitingData;} static void afterGetting(FramedSource* source); // doGetNextFrame() should arrange for this to be called after the // frame has been read (*iff* it is read successfully) protected: FramedSource(UsageEnvironment& env); // abstract base class virtual ~FramedSource(); virtual void doStopGettingFrames(); protected: // The following variables are typically accessed/set by doGetNextFrame() unsigned char* fTo; // in unsigned fMaxSize; // in unsigned fFrameSize; // out unsigned fNumTruncatedBytes; // out struct timeval fPresentationTime; // out unsigned fDurationInMicroseconds; // out private: // redefined virtual functions: virtual Boolean isFramedSource() const; private: afterGettingFunc* fAfterGettingFunc; void* fAfterGettingClientData; onCloseFunc* fOnCloseFunc; void* fOnCloseClientData; Boolean fIsCurrentlyAwaitingData; }; #endif
[ "liweiguang82@163.com" ]
liweiguang82@163.com
f21a492df9497ee547137bbbf1d8beed149b8b70
36184239a2d964ed5f587ad8e83f66355edb17aa
/.history/hw3/ElectoralMap_20211021114920.cpp
8bc4c9ebb096c4e90fd116b2cf3eb0434562628c
[]
no_license
xich4932/csci3010
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
refs/heads/master
2023-08-24T04:03:12.748713
2021-10-22T08:22:58
2021-10-22T08:22:58
415,140,207
0
0
null
null
null
null
UTF-8
C++
false
false
17,582
cpp
#include<iostream> #include<map> #include<set> #include<random> #include<time.h> #include<cmath> #include<stdlib.h> #include"ElectoralMap.h" #define num_district 3 #define num_enum 4 #define one_person 1 //int Candidate::id = 0; int ElectoralMap::count_district = 0; int Election::ids = 0; std::vector<int> Election::party_one_active = {}; std::vector<int> Election::party_two_active = {}; std::vector<int> Election::party_three_active = {}; //std::vector<int> Election::stored_idx_each; int Candidate::party_one_candidate = 0; int Candidate::party_two_candidate = 0; int Candidate::party_three_candidate = 0; int Election::active_party[3] = {0}; Candidate::Candidate(){ ; } void Candidate::plus_vote(District dis, int count){ votes[dis] += count; } Candidate::Candidate(int given_id, party party_name, std::string candidate_name){ id_candidate = given_id; party_affiliation = party_name; name = candidate_name; std::map<int, District> temp_map = ElectoralMap::getInstance().get_map(); for(auto i = temp_map.begin(); i != temp_map.end(); i++){ votes.insert(std::pair<District, int>(i->second, 0)); } } int Candidate::get_ids(){ return id_candidate; } District::District(){ for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){ map_party.insert(std::pair<party,int>(temp, 0)); //map_party.insert(std::pair<party,int>(temp, range_random(engine))); } //std::uniform_int_distribution<unsigned> range_random1(5,29); square_mile = 99; id = 99; } District::District(int given_id){ // std::default_random_engine engine; // std::uniform_int_distribution<unsigned> range_random(0,9); for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){ map_party.insert(std::pair<party,int>(temp, rand()%9)); //map_party.insert(std::pair<party,int>(temp, range_random(engine))); } // std::uniform_int_distribution<unsigned> range_random1(5,29); square_mile = rand()%25+5; id = given_id; } party District::get_max(){ enum party ret; int max = 0; int old_ = max; for(auto i = map_party.begin(); i != map_party.end(); i++){ max = std::max(max, i->second); if(old_ != max){ old_ = max; ret = i->first; } } return ret; } int District::get_sum_constitutent(){ int sum = 0; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp + 1)){ sum += map_party[temp]; } return sum; } int District::get_sum_constitutent_exclude_none(party exclude_one){ int sum = 0; for(enum party temp = party::one; temp < party::none; temp = (party)(temp + 1)){ if(map_party[temp] == exclude_one) continue; // std::cout << temp <<" "; sum += map_party[temp]; } std::cout << "sum:" << sum << std::endl; return sum; } void District::change_party(party increase_party, party decrease_party, int num){ //debug: assume changing number is always smaller than the actual number if(num > map_party[decrease_party]){ map_party[increase_party] += map_party[decrease_party]; map_party[decrease_party] = 0; }else{ map_party[increase_party] += num; map_party[decrease_party] -= num; } }; ElectoralMap::ElectoralMap(){ for(int i = 0; i < num_district; i++){ District *temp = new District(count_district+1); map.insert(std::pair<int, District>(count_district+1, *temp)); count_district ++; } } std::string stringifyEnum(party one){ const std::string str[4] = {"party one", "party two", "party three", "party none"}; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){ if(temp == one) return str[(int)temp]; } return ""; } std::ostream & operator<<(std::ostream& os, District print_district){ std::cout << "district: "<< print_district.id <<":"<< std::endl; std::cout << "area: "<< print_district.square_mile << std::endl; for(enum party print_enum = party::one; print_enum <= party::none; print_enum = (party)(print_enum+1)){ std::cout << stringifyEnum(print_enum) <<": "<< print_district.map_party[print_enum] <<" "; } std::cout << std::endl; return os; } std::ostream & operator<<(std::ostream& os, ElectoralMap print_map){ for(auto i = print_map.map.begin(); i != print_map.map.end(); i++){ std::cout << i->second << std::endl; } return os; } void ask_name(std::string &name){ std::cout << "What is their name?"<<std::endl; getline(std::cin, name); } Election::Election(){ std::string choice; for(enum party party_name = party::one; party_name < party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.insert(std::pair<int, Candidate>(ids + 1, temp)); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } } /* void Election::register_candidate(){ std::string choice; for(enum party party_name; party_name <= party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.push_back(temp); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } } */ Candidate* Election::who_campaigning(){ std::string choice; while ((1)) { std::cout << "Which candidate is campaigning (id) (0 to stop) ?" <<std::endl; getline(std::cin, choice); if(choice == "0") return NULL; if(std::stoi(choice) >= ids){ std::cout << "index out of range"<< std::endl; continue; } break; //jump out of loop if id is availble } return &candidate_[std::stoi(choice)]; //int campaign_id = stoi(choice); //std::cout << ElectoralMap::getInstance << std::endl; // //int campaign_district = stoi(choice); //std::cout << candidate_[campaign_id].get_name() << " is campaigning in district "<< campaign_district << std::endl; } //return -1, select to quie int Election::where_campaigning(){ std::string choice; while ((1)) { std::cout << "Where is this candidate campaigning (id) (0 to stop) ?" <<std::endl; getline(std::cin, choice); if(choice == "0") return -1; if(std::stoi(choice) >= num_district){ std::cout << "index out of range"<< std::endl; continue; } break; //jump out of loop if id is availble } return std::stoi(choice); } Candidate Election::get_candidate(int id){ return candidate_[id]; } void Election::voting(){ std::map<party, int> sum_each_party; sum_each_party.insert(std::pair<party, int> (party::one, 0)); sum_each_party.insert(std::pair<party, int> (party::two, 0)); sum_each_party.insert(std::pair<party, int> (party::three,0)); std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active}; ElectoralMap vote_map = ElectoralMap::getInstance(); std::map<int, District> vote_district = ElectoralMap::getInstance().get_map(); int turn_candidate = 0; for(int d = 1; d <= num_district; d++){ for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ if(active_party[party_name]){ int get_voted = rand()%store_id_each[party_name].size(); candidate_[party_one_active[get_voted]].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); //sum_each_party[party_name] += vote_district[d].get_constituent(party_name); }else if(party_name == party::none){ party none_cantitutent = vote_district[d+1].get_max(); //if none constitutent is 9, should i count them as one or do random choice for each person if(party_name == party::none){ //the majority constituent is still none ; }else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); } }else{ int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); } } } } void District::convert_constituent(party increase_party, party decrease_party, int num){ //if no people in the party, do nothing if(!map_party[decrease_party]) return; map_party[increase_party] += num; map_party[decrease_party] -= num; } party randomlyPickEnum(){ int i = rand() % 3; if(i == 0) return party::one; if(i == 1) return party::two; if(i == 2) return party::three; } void Election::converting(District * campaign_district, Candidate * this_candidate){ double sum_constituent = campaign_district->get_constituent(this_candidate->get_party()); double sum_residents = campaign_district->get_sum_constitutent_exclude_none(this_candidate->get_party()); double possibility = ((sum_constituent+1)*2/sum_residents)*((sum_constituent+1)*2/campaign_district->get_square_mile()); std::cout <<"area: "<< campaign_district->get_square_mile() << std::endl; std::cout <<"sum_constituent: "<< sum_constituent << std::endl; std::cout <<"poss:"<< possibility << std::endl; double p_success = std::min(100.00,possibility ); double p_extra_success = 0.1 * p_success; int this_rand = rand()%100; std::cout << "Chances to convert: " << p_success << std::endl; std::cout << "Chances to convert from another party: "<< p_extra_success << std::endl; //convert only people in party none int convert_one = 0; if(campaign_district->get_constituent(party::none) > 0){ if(p_success > this_rand){ convert_one ++; campaign_district->convert_constituent(this_candidate->get_party(), party::none, one_person); } } if(p_extra_success > this_rand){ enum party converted = randomlyPickEnum(); while(converted == this_candidate->get_party()){ converted = randomlyPickEnum(); } campaign_district->convert_constituent(this_candidate->get_party(), converted, one_person); convert_one++; } std::cout << "Congrats, you have converted someone from none to one!" << std::endl; } void RepresentativeELection::calculate_vote(){ std::map<int ,District> this_district = ElectoralMap::getInstance().get_map(); int sum_all_constituent = 0; for(auto i = this_district.begin(); i != this_district.end(); i++){ sum_all_constituent += i->second.get_sum_constitutent(); } int total_district = this_district.size(); for(auto i = this_district.begin(); i != this_district.end(); i++){ vote_per_district.push_back(std::floor(i->second.get_sum_constitutent() * 1.0 / sum_all_constituent * total_district)); } } RepresentativeELection::RepresentativeELection(){ std::string choice; for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.insert(std::pair<int, Candidate>(ids + 1, temp)); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } //register_candidate(); } bool Election::check_end(){ return false; /* if(!condition) return true; return false; */ } void Election::report_win(){ //int sum_votes[num_enum - 1] = { 0, 0, 0}; std::map<int, District> print_map = ElectoralMap::getInstance().get_map(); for(auto i = print_map.begin(); i != print_map.end(); i++){ std::cout << "Distrcit"<< i->second.get_id() << std::endl; for(int c = 1; c <= ids; c++){ // std::cout << candidate_[c+1].get_vote().get_party(*i) << std::endl; } } /* std::map<int, Candidate> find_max; for(auto i = candidate_.begin(); i != candidate_.end(); i++){ find_max.insert(std::pair<int, Candidate>(i->get_vote(), *i)); } */ std::cout << "Congratulations, "<< candidate_.rbegin()->second.get_name() <<", you've won!"<<std::endl; } int party_to_int(enum party temp){ if(temp == party::one) return 0; if(temp == party::two) return 1; if(temp == party::three) return 2; return 3; //not gonna happen } party District::get_max_party(){ enum party max = party::one; int max_num = map_party[max]; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){ if(map_party[temp] > max_num){ max_num = map_party[temp]; max = temp; } } return max; } void RepresentativeELection::voting(){ std::map<party, int> sum_each_party; sum_each_party.insert(std::pair<party, int> (party::one, 0)); sum_each_party.insert(std::pair<party, int> (party::two, 0)); sum_each_party.insert(std::pair<party, int> (party::three,0)); std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active}; // ElectoralMap vote_map = ElectoralMap::getInstance(); std::map<int, District> vote_district = ElectoralMap::getInstance().get_map(); calculate_vote(); for(int d = 1; d <= num_district; d++){ for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ if(active_party[party_name]){ int get_voted = rand()%store_id_each[party_name].size(); candidate_[party_one_active[get_voted]].plus_vote(vote_district[d], vote_per_district[d]); //sum_each_party[party_name] += vote_district[d].get_constituent(party_name); }else if(party_name == party::none){ party none_cantitutent = vote_district[d+1].get_max(); //if none constitutent is 9, should i count them as one or do random choice for each person if(party_name == party::none){ //the majority constituent is still none ; }else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]); } }else{ int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]); } } } }
[ "70279863+xich4932@users.noreply.github.com" ]
70279863+xich4932@users.noreply.github.com
23f35e41593b5c27c135378d98ab2a067dea2c99
602a3dcb137d03476e9e127ae9ec6d09508be0f4
/Tools/WebGPUAPIStructure/WebGPU-Vulkan/BlitPassImpl.cpp
9fcfde4786750582f69c578cef8216a6ef7fc1eb
[]
no_license
dinfuehr/WebKit
daf6d8ed754f69f87e755fb12a4b80ce2b78f3c7
b179006c34d71af4c788719a7c67809e817e17c0
refs/heads/master
2023-01-14T05:55:29.410095
2018-11-12T15:12:35
2018-11-12T15:12:35
122,606,341
3
3
null
2022-10-11T17:39:17
2018-02-23T10:21:16
null
UTF-8
C++
false
false
2,712
cpp
/* * Copyright (C) 2017 Apple Inc. All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #include "BlitPassImpl.h" namespace WebGPU { BlitPassImpl::BlitPassImpl(vk::Device device, vk::UniqueCommandBuffer&& commandBuffer) : PassImpl(device, std::move(commandBuffer)) { } void BlitPassImpl::copyTexture(Texture& source, Texture& destination, unsigned int sourceX, unsigned int sourceY, unsigned int destinationX, unsigned int destinationY, unsigned int width, unsigned int height) { auto* downcast = dynamic_cast<TextureImpl*>(&source); assert(downcast != nullptr); auto& src = *downcast; downcast = dynamic_cast<TextureImpl*>(&destination); assert(downcast != nullptr); auto& dst = *downcast; const auto subresource = vk::ImageSubresourceLayers() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setMipLevel(0) .setBaseArrayLayer(0) .setLayerCount(1); const auto imageCopy = vk::ImageCopy() .setSrcSubresource(subresource) .setSrcOffset(vk::Offset3D(sourceX, sourceY, 0)) .setDstSubresource(subresource) .setDstOffset(vk::Offset3D(destinationX, destinationY, 0)) .setExtent(vk::Extent3D(width, height, 1)); commandBuffer->copyImage(src.getImage(), vk::ImageLayout::eGeneral, dst.getImage(), vk::ImageLayout::eGeneral, { imageCopy }); insertTexture(src); insertTexture(dst); } }
[ "mmaxfield@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
mmaxfield@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc
0289ad1994cbb21682c9efdc7b550dc45f9aaf2c
d2dd615dc6c041382b2ddf48b2fe2899b9f5b990
/CBStudy/main.cpp
aea431adb3990c24d51f53c2d76796d0679353c1
[]
no_license
zxlhhyccc/srgb
7b20a113b7a5dcc9323912f3bd39917f223bca57
9e3e0478191d6bb442f944a738be7efd5aa66325
refs/heads/master
2023-03-31T23:28:24.724933
2023-03-23T14:35:13
2023-03-23T14:35:13
162,991,434
0
0
null
2023-03-25T08:15:02
2018-12-24T13:04:52
C
UTF-8
C++
false
false
8,436
cpp
/* Code::Blocks 学习助手 V0.18 By 蘭公子 本工具切换VC2010中英文,或者开启命令行的编译器环境 Debug模式,命令行后台输出调试信息,但是不能显示图片 Release模式,可以显示图片和图标,不显示命令行后台 */ #include "cbstudy.h" //加载预编译头文件 INT_PTR CALLBACK DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void CBStudyInitdialog(HWND & hwnd); void CBStudyReadINI(); //读取配置模块 bool Clui_Language(int CodePage); // 设置VC编译器语言代码页 bool CBSfullPath(char* CBS_PATH, char* mypath); // 转换绝对路径 bool ConsoleCompiler(const char * ch); HBITMAP g_hBitmap1; // 第一个图片的句柄 HBITMAP g_hBitmap2; // 第二个图片的句柄 HICON g_hIcon; // 对话框图标句柄 HBRUSH g_hBgBrush; // 背景刷子 //定义路径全局变量存储 bool Change_PIC = false ; char CBS_vcbin[MAX_PATH], CBS_include[MAX_PATH], CBS_lib[MAX_PATH], CBS_gccbin[MAX_PATH], CBS_gccnls[MAX_PATH], CBS_PATH[MAX_PATH], CBS_MYAPP[MAX_PATH]; string strCBS_Cmdline ; // Windows系统的主函数 int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nCmd) { // 从资源中加载BMP文件和图标,这些工作也可以在WM_INITDIALOG消息中进行 g_hBitmap1 = ::LoadBitmap(hInst, (LPCTSTR)IDB_BITMAP1); g_hBitmap2 = ::LoadBitmap(hInst, (LPCTSTR)IDB_BITMAP2); g_hIcon = ::LoadIcon(hInst, (LPCTSTR)IDI_ICON); CBStudyReadINI(); // 读取 CBStudy.ini 的路径配置 // 用这个系统函数创建我们刚刚绘制好的窗体DLG_MAIN,设置回叫函数为DlgProc DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN ), 0, DlgProc); return 0; } INT_PTR CALLBACK DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // 对消息类别进行判断 switch(uMsg) { case WM_INITDIALOG: { CBStudyInitdialog(hwnd); // 设置标题栏图标,// 设置图片 } break; // 如果是命令事件(按钮等) case WM_COMMAND: // 对wParam低字节进行判断,其中是我们的ID(参见MSDN) switch(LOWORD(wParam)) { case IDC_Change_PIC: if (!Change_PIC) { SetDlgItemText(hwnd, IDC_INFO_TEXT, "美女都让你发现了,你真厉害!"); ::SendDlgItemMessage(hwnd, IDC_BABY_PIC, STM_SETIMAGE, IMAGE_BITMAP, (long)g_hBitmap2); printf("改图片\n"); Change_PIC = true; } else { CBStudyInitdialog(hwnd); Change_PIC = false; } break; case IDC_CLUI_CN: Clui_Language(2052); //设置中文代码页2052 SetDlgItemText(hwnd, IDC_INFO_TEXT, "您已经切换C/C++编译器构建信息为中文!"); break; case IDC_CLUI_EN: Clui_Language(1033); //设置中文代码页1033 SetDlgItemText(hwnd, IDC_INFO_TEXT, "C/C++ compiler build information for the English!"); break; case IDC_CLUI_VCCMD: printf("VC编译器路径 %s\n",CBS_vcbin); ConsoleCompiler("vc"); break; case IDC_CLUI_GCCMD: printf("GCC编译器路径 %s\n",CBS_gccbin); ConsoleCompiler("gcc"); break; // 如果是Cancel按钮被按下 case IDC_BTN_QUIT : // 这里读者可以充分发挥想象力,控制台函数可以调用 :) if (Change_PIC) { ::EndDialog (hwnd, IDC_BTN_QUIT); DeleteFile("CBStudy.cmd"); } // 分配空间作为临时存储 char buf[512]; // 获得Edit Control内容 GetDlgItemText(hwnd, IDC_INFO_TEXT, buf, 512); // 用printf打印我们获得的内容 printf("%s\n", buf); SetDlgItemText(hwnd, IDC_INFO_TEXT, "菜鸟,想退出了吗!程序中还有个彩蛋等你发现呢!"); Change_PIC = true; break; } break; // 如果窗口被关闭 case WM_CLOSE: // 要求系统关闭这个程序 PostQuitMessage(0); break; } // 默认返回0 return 0; } void CBStudyInitdialog(HWND & hwnd) { // 设置标题栏图标 ::SendMessage(hwnd, WM_SETICON, ICON_BIG, (long)g_hIcon); // 初始化显示图片的静态框架 HWND hWndBmp = ::GetDlgItem(hwnd, IDC_BABY_PIC ); // 设置SS_BITMAP风格 LONG nStyle = ::GetWindowLong(hWndBmp, GWL_STYLE); ::SetWindowLong(hWndBmp, GWL_STYLE, nStyle | SS_BITMAP); // 设置图片 ::SendDlgItemMessage(hwnd, IDC_BABY_PIC, STM_SETIMAGE, IMAGE_BITMAP, (long)g_hBitmap1); SetDlgItemText(hwnd, IDC_INFO_TEXT, "本工具切换C++编译器中英文,开启命令行的编译器环境"); } void CBStudyReadINI() { //读取配置文件路径 GetPrivateProfileString("VC2010_PATH", "VCBIN", "VCBIN", CBS_vcbin, MAX_PATH,".\\CBStudy.ini"); GetPrivateProfileString("VC2010_PATH", "INCLUDE", "INCLUDE", CBS_include, MAX_PATH,".\\CBStudy.ini"); GetPrivateProfileString("VC2010_PATH", "LIB", "LIB", CBS_lib, MAX_PATH,".\\CBStudy.ini"); GetPrivateProfileString("GCC_PATH", "GCCBIN", "GCCBIN", CBS_gccbin, MAX_PATH,".\\CBStudy.ini"); GetPrivateProfileString("GCC_PATH", "GCCNLS", "C:\\gcc\\share\\locale\\zh_CN", CBS_gccnls, MAX_PATH,".\\CBStudy.ini"); GetPrivateProfileString("MYAPP_PATH", "MYAPP", "E:\\myapp", CBS_MYAPP, MAX_PATH,".\\CBStudy.ini"); // 转为为绝对路径 GetCurrentDirectoryA(MAX_PATH, CBS_PATH); CBSfullPath(CBS_PATH, CBS_vcbin); CBSfullPath(CBS_PATH, CBS_include); CBSfullPath(CBS_PATH, CBS_lib); CBSfullPath(CBS_PATH, CBS_gccbin); CBSfullPath(CBS_PATH, CBS_gccnls); CBSfullPath(CBS_PATH, CBS_MYAPP); // printf("%s\n%s\n",CBS_gccnls,CBS_MYAPP); } bool CBSfullPath(char* CBS_PATH, char* mypath) { string strCBS(CBS_PATH); string absPath(mypath); string relativePath(mypath, 1, MAX_PATH - 3); if(mypath[0] == '.') { absPath = strCBS + relativePath; strcpy(mypath, absPath.c_str()); } return true; } bool Clui_Language(int CodePage) { string strCBS_CN2052(CBS_vcbin); string strCBS_EN2052(CBS_vcbin); strCBS_CN2052 += "\\2052"; strCBS_EN2052 += "\\EN2052"; char * cn2052 , * en2052 ; cn2052 =new char[MAX_PATH]; en2052 =new char[MAX_PATH]; strcpy(cn2052, strCBS_CN2052.c_str()); strcpy(en2052, strCBS_EN2052.c_str()); if (2052 == CodePage) //中文 MoveFile(en2052, cn2052); if (1033 == CodePage) //英文 MoveFile(cn2052, en2052); delete[] cn2052; delete[] en2052; printf("%i\n", CodePage); return true; } bool ConsoleCompiler(const char * ch) { // 建立批处理文件 std::ofstream fout( "CBStudy.cmd" ); if ('v'==ch[0]) { fout << "@echo off\nset PATH=" << CBS_vcbin << ";%PATH%\nset INCLUDE=" <<CBS_include <<"\nset LIB=" << CBS_lib <<"\ncolor a\n@echo 欢迎使用命令行VC2010编译器中文版 你可以使用TAB自动补全\ncl\n" ; } if ('g'==ch[0]) { fout << "@echo off\nset PATH=" << CBS_gccbin << ";%PATH%\ncolor a\n@echo 欢迎使用命令行 GCC 编译器中文版 你可以使用TAB自动补全\ng++ -v\n" ; } fout << "CD " << CBS_MYAPP << endl; fout.close(); // 执行批处理文件 char szCommandLine[] = "cmd /k CBStudy.cmd"; STARTUPINFO si = { sizeof(si) }; PROCESS_INFORMATION pi; si.dwFlags = STARTF_USESHOWWINDOW; // 指定wShowWindow成员有效 si.wShowWindow = TRUE; // 此成员设为TRUE的话则显示新建进程的主窗口, // 为FALSE的话则不显示 BOOL bRet = ::CreateProcess ( NULL, // 不在此指定可执行文件的文件名 szCommandLine, // 命令行参数 NULL, // 默认进程安全性 NULL, // 默认线程安全性 FALSE, // 指定当前进程内的句柄不可以被子进程继承 CREATE_NEW_CONSOLE, // 为新进程创建一个新的控制台窗口 NULL, // 使用本进程的环境变量 NULL, // 使用本进程的驱动器和目录 &si, &pi); return bRet; }
[ "landboy@amd3000.(none)" ]
landboy@amd3000.(none)
d47b879803974b8e6bba5890f699f14f2125d6bd
1d6dbe2ac145b9785b944855bfcce418f8327b16
/src/ROSPlan/devel/include/rosplan_knowledge_msgs/DomainFormula.h
22598f8e270e3c77df7223abd73aa071b89920ea
[]
no_license
giliamit/escorting_project
b0338e9652cf81e9435eb0fd5f0a57f09a3d6d84
2194e1385fcbb0be367af898576fc3bf8c94fde5
refs/heads/master
2021-05-06T18:54:54.232410
2017-11-25T15:53:55
2017-11-25T15:53:55
111,991,363
1
1
null
null
null
null
UTF-8
C++
false
false
6,735
h
// Generated by gencpp from file rosplan_knowledge_msgs/DomainFormula.msg // DO NOT EDIT! #ifndef ROSPLAN_KNOWLEDGE_MSGS_MESSAGE_DOMAINFORMULA_H #define ROSPLAN_KNOWLEDGE_MSGS_MESSAGE_DOMAINFORMULA_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <diagnostic_msgs/KeyValue.h> namespace rosplan_knowledge_msgs { template <class ContainerAllocator> struct DomainFormula_ { typedef DomainFormula_<ContainerAllocator> Type; DomainFormula_() : name() , typed_parameters() { } DomainFormula_(const ContainerAllocator& _alloc) : name(_alloc) , typed_parameters(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _name_type; _name_type name; typedef std::vector< ::diagnostic_msgs::KeyValue_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::diagnostic_msgs::KeyValue_<ContainerAllocator> >::other > _typed_parameters_type; _typed_parameters_type typed_parameters; typedef boost::shared_ptr< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> const> ConstPtr; }; // struct DomainFormula_ typedef ::rosplan_knowledge_msgs::DomainFormula_<std::allocator<void> > DomainFormula; typedef boost::shared_ptr< ::rosplan_knowledge_msgs::DomainFormula > DomainFormulaPtr; typedef boost::shared_ptr< ::rosplan_knowledge_msgs::DomainFormula const> DomainFormulaConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> & v) { ros::message_operations::Printer< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace rosplan_knowledge_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'diagnostic_msgs': ['/opt/ros/indigo/share/diagnostic_msgs/cmake/../msg'], 'rosplan_knowledge_msgs': ['/home/robot/catkin_ws_escorting/src/ROSPlan/src/rosplan/rosplan_knowledge_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > { static const char* value() { return "b9c7cfc3aa64764d3a82f96d3671bab1"; } static const char* value(const ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xb9c7cfc3aa64764dULL; static const uint64_t static_value2 = 0x3a82f96d3671bab1ULL; }; template<class ContainerAllocator> struct DataType< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > { static const char* value() { return "rosplan_knowledge_msgs/DomainFormula"; } static const char* value(const ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > { static const char* value() { return "# A knowledge item used to represent an atomic formula from the domain.\n\ # typed_parameters matches label -> type\n\ string name\n\ diagnostic_msgs/KeyValue[] typed_parameters\n\ \n\ ================================================================================\n\ MSG: diagnostic_msgs/KeyValue\n\ string key # what to label this value when viewing\n\ string value # a value to track over time\n\ "; } static const char* value(const ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.name); stream.next(m.typed_parameters); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct DomainFormula_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rosplan_knowledge_msgs::DomainFormula_<ContainerAllocator>& v) { s << indent << "name: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.name); s << indent << "typed_parameters[]" << std::endl; for (size_t i = 0; i < v.typed_parameters.size(); ++i) { s << indent << " typed_parameters[" << i << "]: "; s << std::endl; s << indent; Printer< ::diagnostic_msgs::KeyValue_<ContainerAllocator> >::stream(s, indent + " ", v.typed_parameters[i]); } } }; } // namespace message_operations } // namespace ros #endif // ROSPLAN_KNOWLEDGE_MSGS_MESSAGE_DOMAINFORMULA_H
[ "hadarydar@gmail.com" ]
hadarydar@gmail.com
7af073a2b89fd28905b10bd8af2faf4b00831d39
f21461d44f53d99faa038b274225b9c175360192
/zhang/search/B-Tree.cpp
e3b6bde2d81cd44817beabda09de78fa5deac106
[ "MIT" ]
permissive
costarzhang/C-Plus-Plus
5553e33ddf56b6069fec064d19345343dd00a20a
fa21e83f9c17adce4f8c46d53dcba4eacbbfa809
refs/heads/master
2023-03-28T18:33:09.994165
2021-03-30T09:32:09
2021-03-30T09:32:09
275,480,407
0
0
null
2020-06-28T01:04:12
2020-06-28T01:04:11
null
UTF-8
C++
false
false
18,262
cpp
/* 多路平衡查找树 */ /* 一棵m阶的B - Tree有如下特性: 1. 每个节点最多有m个孩子。 2. 除了根节点和叶子节点外,其它每个节点至少有Ceil(m / 2) 个孩子。 3. 若根节点不是叶子节点,则至少有2个孩子 4. 所有叶子节点都在同一层,且不包含其它关键字信息 5. 每个非终端节点包含n个关键字信息(P0,P1,…Pn, k1,…kn) 6. 关键字的个数n满足:ceil(m / 2) -1 <=n <= m - 1 7. ki(i = 1,…n) 为关键字,且关键字升序排序。 8. Pi(i = 1,…n) 为指向子树根节点的指针。P(i - 1) 指向的子树的所有节点关键字均小于ki,但都大于k(i - 1) */ #include <stdio.h> #include <iostream> #define MAXM 10 //定义B树的最大的阶数 const int m = 4; //设定B树的阶数 const int Max = m - 1; //结点的最大关键字数量 const int Min = (m - 1) / 2; //结点的最小关键字数量 typedef int KeyType; //KeyType为关键字类型 typedef struct node { //B树和B树结点类型 int keynum; //结点关键字个数 KeyType key[MAXM]; //关键字数组,key[0]不使用 struct node *parent; //双亲结点指针 struct node *ptr[MAXM]; //孩子结点指针数组 } BTNode, *BTree; typedef struct { //B树查找结果类型 BTNode *pt; //指向找到的结点 int i; //在结点中的关键字位置;从1开始 int tag; //查找成功与否标志 } Result; typedef struct LNode { //链表和链表结点类型 BTree data; //数据域 struct LNode *next; //指针域 } LNode, *LinkList; typedef enum status { //枚举类型(依次递增) TRUE, FALSE, OK, ERROR, OVERFLOW, EMPTY } Status; //初始化B树 Status InitBTree(BTree &t); //在结点p中查找关键字k的插入位置i int SearchBTNode(BTNode *p, KeyType k); /*在树t上查找关键字k,返回结果(pt,i,tag)。若查找成功,则特征值 tag=1,关键字k是指针pt所指结点中第i个关键字;否则特征值tag=0, 关键字k的插入位置为pt结点的第i个*/ Result SearchBTree(BTree t, KeyType k); //将关键字k和结点q分别插入到p->key[i+1]和p->ptr[i+1]中 void InsertBTNode(BTNode *&p, int i, KeyType k, BTNode *q); //将结点p分裂成两个结点,前一半保留,后一半移入结点q void SplitBTNode(BTNode *&p, BTNode *&q); //生成新的根结点t,原结点p和结点q为子树指针 void NewRoot(BTNode *&t, KeyType k, BTNode *p, BTNode *q); /*在树t上结点q的key[i]与key[i+1]之间插入关键字k。若引起 结点过大,则沿双亲链进行必要的结点分裂调整,使t仍是B树*/ void InsertBTree(BTree &t, int i, KeyType k, BTNode *p); //从p结点删除key[i]和它的孩子指针ptr[i] void Remove(BTNode *p, int i); //查找被删关键字p->key[i](在非叶子结点中)的替代叶子结点(右子树中值最小的关键字) void Substitution(BTNode *p, int i); /*将双亲结点p中的最后一个关键字移入右结点q中 将左结点aq中的最后一个关键字移入双亲结点p中*/ void MoveRight(BTNode *p, int i); /*将双亲结点p中的第一个关键字移入结点aq中, 将结点q中的第一个关键字移入双亲结点p中*/ void MoveLeft(BTNode *p, int i); /*将双亲结点p、右结点q合并入左结点aq, 并调整双亲结点p中的剩余关键字的位置*/ void Combine(BTNode *p, int i); //删除结点p中的第i个关键字后,调整B树 void AdjustBTree(BTNode *p, int i); //反映是否在结点p中是否查找到关键字k int FindBTNode(BTNode *p, KeyType k, int &i); //在结点p中查找并删除关键字k int BTNodeDelete(BTNode *p, KeyType k); //构建删除框架,执行删除操作 void BTreeDelete(BTree &t, KeyType k); //递归释放B树 void DestroyBTree(BTree &t); //初始化队列 Status InitQueue(LinkList &L); //新建一个结点 LNode *CreateNode(BTree t); //元素q入队列 Status Enqueue(LNode *p, BTree t); //出队列,并以q返回值 Status Dequeue(LNode *p, BTNode *&q); //队列判空 Status IfEmpty(LinkList L); //销毁队列 void DestroyQueue(LinkList L); //用队列遍历输出B树 Status Traverse(BTree t, LinkList L, int newline, int sum); //输出B树 Status PrintBTree(BTree t); //测试B树功能函数 void Test(); // 初始化 Status InitBTree(BTree &t) { t = NULL; return OK; } // 在结点p中查找关键字k的插入位置 int SearchBTNode(BTNode *p, KeyType k) { int i = 0; for (i = 0; i < p->keynum && p->key[i + 1] <= k; i++) ; return i; } /*在树t上查找关键字k,返回结果(pt,i,tag)。若查找成功,则特征值 tag=1,关键字k是指针pt所指结点中第i个关键字;否则特征值tag=0, 关键字k的插入位置为pt结点的第i个*/ Result SearchBTree(BTree t, KeyType k) { BTNode *p = t, *q = nullptr; //初始化结点p和结点q,p指向待查结点,q指向p的双亲 int found_tag = 0; //设定查找成功与否标志 int i = 0; Result r; //设定返回的查找结果 while (p != nullptr && found_tag == 0) { i = SearchBTNode(p, k); //在结点p中查找关键字k if (i > 0 && p->key[i] == k) //找到待查关键字 found_tag = 1; //查找成功 else { //查找失败 q = p; p = p->ptr[i]; //依次查找结点p的所有分支结点 } } if (found_tag == 1) { //查找成功,生成查找结果 r.pt = p; //关键字所在结点 r.i = i; //关键字在结点中的位置 r.tag = 1; } else { //查找失败,生成查找结果,查找失败的位置 r.pt = q; r.i = i; r.tag = 0; } return r; //返回关键字k的位置(或插入位置) } //将关键字k和结点q分别插入到p->key[i+1]和p->ptr[i+1]中 void InsertBTNode(BTNode *&p, int i, KeyType k, BTNode *q) { int j; for (j = p->keynum; j > i; j--) { //整体后移空出一个位置 p->key[j + 1] = p->key[j]; p->ptr[j + 1] = p->ptr[j]; } p->key[i + 1] = k; p->ptr[i + 1] = q; if (q != NULL) q->parent = p; p->keynum++; } void SplitBTNode(BTNode *&p, BTNode *&q) { int i; int s = (m + 1) / 2; q = (BTNode *)malloc(sizeof(BTNode)); //给结点q分配空间 q->ptr[0] = p->ptr[s]; //后一半移入结点q for (i = s + 1; i <= m; i++) { q->key[i - s] = p->key[i]; q->ptr[i - s] = p->ptr[i]; } q->keynum = p->keynum - s; q->parent = p->parent; for (i = 0; i <= p->keynum - s; i++) //修改双亲指针 if (q->ptr[i] != NULL) q->ptr[i]->parent = q; p->keynum = s - 1; //结点p的前一半保留,修改结点p的keynum } void NewRoot(BTNode *&t, KeyType k, BTNode *p, BTNode *q) { t = (BTNode *)malloc(sizeof(BTNode)); //分配空间 t->keynum = 1; t->ptr[0] = p; t->ptr[1] = q; t->key[1] = k; if (p != NULL) //调整结点p和q的双亲指针 p->parent = t; if (q != NULL) q->parent = t; t->parent = NULL; } void InsertBTree(BTree &t, int i, KeyType k, BTNode *p) { BTNode *q; int finish_tag, newroot_tag, s; //设定需要新结点标志和插入完成标志 KeyType x; if (p == NULL) //t是空树 NewRoot(t, k, NULL, NULL); //生成仅含关键字k的根结点t else { x = k; q = NULL; finish_tag = 0; newroot_tag = 0; while (finish_tag == 0 && newroot_tag == 0) { InsertBTNode(p, i, x, q); //将关键字x和结点q分别插入到p->key[i+1]和p->ptr[i+1] if (p->keynum <= Max) finish_tag = 1; //插入完成 else { s = (m + 1) / 2; SplitBTNode(p, q); //分裂结点 x = p->key[s]; if (p->parent) { //查找x的插入位置 p = p->parent; i = SearchBTNode(p, x); } else //没找到x,需要新结点 newroot_tag = 1; } } if (newroot_tag == 1) //根结点已分裂为结点p和q NewRoot(t, x, p, q); //生成新根结点t,p和q为子树指针 } } void Remove(BTNode *p, int i) { int j; for (j = i + 1; j <= p->keynum; j++) { //前移删除key[i]和ptr[i] p->key[j - 1] = p->key[j]; p->ptr[j - 1] = p->ptr[j]; } p->keynum--; } void Substitution(BTNode *p, int i) { BTNode *q; for (q = p->ptr[i]; q->ptr[0] != NULL; q = q->ptr[0]) ; p->key[i] = q->key[1]; //复制关键字值 } void MoveRight(BTNode *p, int i) { int j; BTNode *q = p->ptr[i]; BTNode *aq = p->ptr[i - 1]; for (j = q->keynum; j > 0; j--) { //将右兄弟q中所有关键字向后移动一位 q->key[j + 1] = q->key[j]; q->ptr[j + 1] = q->ptr[j]; } q->ptr[1] = q->ptr[0]; //从双亲结点p移动关键字到右兄弟q中 q->key[1] = p->key[i]; q->keynum++; p->key[i] = aq->key[aq->keynum]; //将左兄弟aq中最后一个关键字移动到双亲结点p中 p->ptr[i]->ptr[0] = aq->ptr[aq->keynum]; aq->keynum--; } void MoveLeft(BTNode *p, int i) { int j; BTNode *aq = p->ptr[i - 1]; BTNode *q = p->ptr[i]; aq->keynum++; //把双亲结点p中的关键字移动到左兄弟aq中 aq->key[aq->keynum] = p->key[i]; aq->ptr[aq->keynum] = p->ptr[i]->ptr[0]; p->key[i] = q->key[1]; //把右兄弟q中的关键字移动到双亲节点p中 q->ptr[0] = q->ptr[1]; q->keynum--; for (j = 1; j <= aq->keynum; j++) { //将右兄弟q中所有关键字向前移动一位 aq->key[j] = aq->key[j + 1]; aq->ptr[j] = aq->ptr[j + 1]; } } void Combine(BTNode *p, int i) { int j; BTNode *q = p->ptr[i]; BTNode *aq = p->ptr[i - 1]; aq->keynum++; //将双亲结点的关键字p->key[i]插入到左结点aq aq->key[aq->keynum] = p->key[i]; aq->ptr[aq->keynum] = q->ptr[0]; for (j = 1; j <= q->keynum; j++) { //将右结点q中的所有关键字插入到左结点aq aq->keynum++; aq->key[aq->keynum] = q->key[j]; aq->ptr[aq->keynum] = q->ptr[j]; } for (j = i; j < p->keynum; j++) { //将双亲结点p中的p->key[i]后的所有关键字向前移动一位 p->key[j] = p->key[j + 1]; p->ptr[j] = p->ptr[j + 1]; } p->keynum--; //修改双亲结点p的keynum值 free(q); //释放空右结点q的空间 } int FindBTNode(BTNode *p, KeyType k, int &i) { //反映是否在结点p中是否查找到关键字k if (k < p->key[1]) { //结点p中查找关键字k失败 i = 0; return 0; } else { //在p结点中查找 i = p->keynum; while (k < p->key[i] && i > 1) i--; if (k == p->key[i]) //结点p中查找关键字k成功 return 1; } return 1; } void AdjustBTree(BTNode *p, int i) { if (i == 0) //删除的是最左边关键字 if (p->ptr[1]->keynum > Min) //右结点可以借 MoveLeft(p, 1); else //右兄弟不够借 Combine(p, 1); else if (i == p->keynum) //删除的是最右边关键字 if (p->ptr[i - 1]->keynum > Min) //左结点可以借 MoveRight(p, i); else //左结点不够借 Combine(p, i); else if (p->ptr[i - 1]->keynum > Min) //删除关键字在中部且左结点够借 MoveRight(p, i); else if (p->ptr[i + 1]->keynum > Min) //删除关键字在中部且右结点够借 MoveLeft(p, i + 1); else //删除关键字在中部且左右结点都不够借 Combine(p, i); } int BTNodeDelete(BTNode *p, KeyType k) { int i; int found_tag; //查找标志 if (p == NULL) return 0; else { found_tag = FindBTNode(p, k, i); //返回查找结果 if (found_tag == 1) { //查找成功 if (p->ptr[i - 1] != NULL) { //删除的是非叶子结点 Substitution(p, i); //寻找相邻关键字(右子树中最小的关键字) BTNodeDelete(p->ptr[i], p->key[i]); //执行删除操作 } else Remove(p, i); //从结点p中位置i处删除关键字 } else found_tag = BTNodeDelete(p->ptr[i], k); //沿孩子结点递归查找并删除关键字k if (p->ptr[i] != NULL) if (p->ptr[i]->keynum < Min) //删除后关键字个数小于MIN AdjustBTree(p, i); //调整B树 return found_tag; } } void BTreeDelete(BTree &t, KeyType k) { BTNode *p; int a = BTNodeDelete(t, k); //删除关键字k if (a == 0) //查找失败 printf(" 关键字%d不在B树中\n", k); else if (t->keynum == 0) { //调整 p = t; t = t->ptr[0]; free(p); } } void DestroyBTree(BTree &t) { int i; BTNode *p = t; if (p != NULL) { //B树不为空 for (i = 0; i <= p->keynum; i++) { //递归释放每一个结点 DestroyBTree(*&p->ptr[i]); } free(p); } t = NULL; } Status InitQueue(LinkList &L) { L = (LNode *)malloc(sizeof(LNode)); //分配结点空间 if (L == NULL) //分配失败 return OVERFLOW; L->next = NULL; return OK; } LNode *CreateNode(BTNode *p) { LNode *q; q = (LNode *)malloc(sizeof(LNode)); //分配结点空间 if (q != NULL) { //分配成功 q->data = p; q->next = NULL; } return q; } Status Enqueue(LNode *p, BTNode *q) { if (p == NULL) return ERROR; while (p->next != NULL) //调至队列最后 p = p->next; p->next = CreateNode(q); //生成结点让q进入队列 return OK; } Status Dequeue(LNode *p, BTNode *&q) { LNode *aq; if (p == NULL || p->next == NULL) //删除位置不合理 return ERROR; aq = p->next; //修改被删结点aq的指针域 p->next = aq->next; q = aq->data; free(aq); //释放结点aq return OK; } Status IfEmpty(LinkList L) { if (L == NULL) //队列不存在 return ERROR; if (L->next == NULL) //队列为空 return TRUE; return FALSE; //队列非空 } void DestroyQueue(LinkList L) { LinkList p; if (L != NULL) { p = L; L = L->next; free(p); //逐一释放 DestroyQueue(L); } } Status Traverse(BTree t, LinkList L, int newline, int sum) { int i; BTree p; if (t != NULL) { printf(" [ "); Enqueue(L, t->ptr[0]); //入队 for (i = 1; i <= t->keynum; i++) { printf(" %d ", t->key[i]); Enqueue(L, t->ptr[i]); //子结点入队 } sum += t->keynum + 1; printf("]"); if (newline == 0) { //需要另起一行 printf("\n"); newline = sum - 1; sum = 0; } else newline--; } if (IfEmpty(L) == FALSE) { //l不为空 Dequeue(L, p); //出队,以p返回 Traverse(p, L, newline, sum); //遍历出队结点 } return OK; } Status PrintBTree(BTree t) { LinkList L; if (t == NULL) { printf(" B树为空树"); return OK; } InitQueue(L); //初始化队列 Traverse(t, L, 0, 0); //利用队列输出 DestroyQueue(L); //销毁队列 return OK; } void Test1() { BTNode *t = NULL; Result s; //设定查找结果 int j, n = 15; KeyType k; KeyType a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; printf("创建一棵%d阶B树:\n", m); for (j = 0; j < n; j++) { //逐一插入元素 s = SearchBTree(t, a[j]); if (s.tag == 0) InsertBTree(t, s.i, a[j], s.pt); printf(" 第%d步,插入元素%d:\n ", j + 1, a[j]); PrintBTree(t); } printf("\n"); printf("删除操作:\n"); //删除操作 k = 9; BTreeDelete(t, k); printf(" 删除%d:\n ", k); printf(" 删除后的B树: \n"); PrintBTree(t); printf("\n"); k = 1; BTreeDelete(t, k); printf(" 删除%d:\n ", k); printf(" 删除后的B树: \n"); PrintBTree(t); printf("\n"); printf(" 递归释放B树\n"); //递归释放B树 DestroyBTree(t); PrintBTree(t); } void Test2() { int i, k; BTree t = NULL; Result s; //设定查找结果 while (1) { printf("此时的B树:\n"); PrintBTree(t); printf("\n"); printf("=============Operation Table=============\n"); printf(" 1.Init 2.Insert 3.Delete \n"); printf(" 4.Destroy 5.Exit \n"); printf("=========================================\n"); printf("Enter number to choose operation:_____\b\b\b"); scanf("%d", &i); switch (i) { case 1: { InitBTree(t); printf("InitBTree successfully.\n"); break; } case 2: { printf("Enter number to InsertBTree:_____\b\b\b"); scanf("%d", &k); s = SearchBTree(t, k); InsertBTree(t, s.i, k, s.pt); printf("InsertBTree successfully.\n"); break; } case 3: { printf("Enter number to DeleteBTree:_____\b\b\b"); scanf("%d", &k); BTreeDelete(t, k); printf("\n"); printf("DeleteBTree successfully.\n"); break; } case 4: { DestroyBTree(t); break; printf("DestroyBTree successfully.\n"); } case 5: { exit(-1); break; } } } } int main() { Test1(); return 0; }
[ "costarzhang@foxmail.com" ]
costarzhang@foxmail.com
e7bb0ddca696450f4ab72b37c174f18bedf846c4
3f713aed2756c7b6dc090dc0a69b9d1fd592da12
/src/qt/transactionrecord.h
90d788d3601a918b7b0e61bc8b53f41f00fea94a
[ "MIT" ]
permissive
anyagixx/xorx
ba1a64fdf799c2b74a4b35aefa57ab630e8a0e6b
974709b63c6233a37d08f914b723e513e0ef5e44
refs/heads/master
2020-03-27T00:55:44.889288
2019-05-15T09:51:43
2019-05-15T09:51:43
145,667,570
0
0
null
null
null
null
UTF-8
C++
false
false
4,919
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_TRANSACTIONRECORD_H #define BITCOIN_QT_TRANSACTIONRECORD_H #include "amount.h" #include "uint256.h" #include <QList> #include <QString> class CWallet; class CWalletTx; /** UI model for transaction status. The transaction status is the part of a transaction that will change over time. */ class TransactionStatus { public: TransactionStatus() : countsForBalance(false), sortKey(""), matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1) { } enum Status { Confirmed, /**< Have 6 or more confirmations (normal tx) or fully mature (mined tx) **/ /// Normal (sent/received) transactions OpenUntilDate, /**< Transaction not yet final, waiting for date */ OpenUntilBlock, /**< Transaction not yet final, waiting for block */ Offline, /**< Not sent to any other nodes **/ Unconfirmed, /**< Not yet mined into a block **/ Confirming, /**< Confirmed, but waiting for the recommended number of confirmations **/ Conflicted, /**< Conflicts with other transaction or mempool **/ /// Generated (mined) transactions Immature, /**< Mined but waiting for maturity */ MaturesWarning, /**< Transaction will likely not mature because no nodes have confirmed */ NotAccepted /**< Mined but not accepted */ }; /// Transaction counts towards available balance bool countsForBalance; /// Sorting key based on status std::string sortKey; /** @name Generated (mined) transactions @{*/ int matures_in; /**@}*/ /** @name Reported status @{*/ Status status; qint64 depth; qint64 open_for; /**< Timestamp if status==OpenUntilDate, otherwise number of additional blocks that need to be mined before finalization */ /**@}*/ /** Current number of blocks (to know whether cached status is still valid) */ int cur_num_blocks; //** Know when to update transaction for ix locks **/ int cur_num_ix_locks; }; /** UI model for a transaction. A core transaction can be represented by multiple UI transactions if it has multiple outputs. */ class TransactionRecord { public: enum Type { Other, Generated, StakeMint, SendToAddress, SendToOther, RecvWithAddress, MNReward, RecvFromOther, SendToSelf, ZerocoinMint, ZerocoinSpend, RecvFromZerocoinSpend, ZerocoinSpend_Change_zXORX, ZerocoinSpend_FromMe, RecvWithObfuscation, ObfuscationDenominate, ObfuscationCollateralPayment, ObfuscationMakeCollaterals, ObfuscationCreateDenominations, Obfuscated }; /** Number of confirmation recommended for accepting a transaction */ static const int RecommendedNumConfirmations = 6; TransactionRecord() : hash(), time(0), type(Other), address(""), debit(0), credit(0), idx(0) { } TransactionRecord(uint256 hash, qint64 time) : hash(hash), time(time), type(Other), address(""), debit(0), credit(0), idx(0) { } TransactionRecord(uint256 hash, qint64 time, Type type, const std::string& address, const CAmount& debit, const CAmount& credit) : hash(hash), time(time), type(type), address(address), debit(debit), credit(credit), idx(0) { } /** Decompose CWallet transaction to model transaction records. */ static bool showTransaction(const CWalletTx& wtx); static QList<TransactionRecord> decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx); /** @name Immutable transaction attributes @{*/ uint256 hash; qint64 time; Type type; std::string address; CAmount debit; CAmount credit; /**@}*/ /** Subtransaction index, for sort key */ int idx; /** Status: can change with block chain update */ TransactionStatus status; /** Whether the transaction was sent/received with a watch-only address */ bool involvesWatchAddress; /** Return the unique identifier for this transaction (part) */ QString getTxID() const; /** Return the output index of the subtransaction */ int getOutputIndex() const; /** Update status from core wallet tx. */ void updateStatus(const CWalletTx& wtx); /** Return whether a status update is needed. */ bool statusUpdateNeeded(); }; #endif // BITCOIN_QT_TRANSACTIONRECORD_H
[ "anyagixx@yandex.ru" ]
anyagixx@yandex.ru
38bb2aedee87c06b41e68a839154f47a01110e27
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code/gui/guiresource.h
ae1e2d558775255d6200c3f5c8d58dd71dc05a6a
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
h
/*************************************************************************************************** * * DESCRIPTION A very simple resource manager to stop mulitple loads of files * * NOTES * ***************************************************************************************************/ #ifndef _GUIRESOURCE_H #define _GUIRESOURCE_H /*************************************************************************************************** * * CLASS CGuiResource * * DESCRIPTION A simple resource system based on file names. This means everything gets * cleared up properly and that when a proper resource system is in place it will * be easy to update the code. * * We can assume that all the GUI stuff is happily sat in a single GUI directory. * Filenames will be specified relative to this. * ***************************************************************************************************/ class CGuiResource : public Singleton< CGuiResource > { public: // Construction Destruction CGuiResource( void ); ~CGuiResource( void ); // Resource getting stuff uint8_t* GetResource( const char* pcFileName, int* iByteFileSize, bool bBinaryFile = false ); // Resource releasing stuff bool ReleaseResource( const char* pcFileName ); bool ReleaseResource( uint8_t* pData ); protected: // Our resource information struct GUI_RESOURCE { char* pcFileName; uint8_t* pData; int iFileSize; int iRefs; }; // Things that help void DropResource( GUI_RESOURCE& strResource ); // What we keep our resource information in ntstd::List< GUI_RESOURCE* > m_obResources; }; #endif // _GUIRESOURCE_H
[ "hopefullyidontgetbanned735@gmail.com" ]
hopefullyidontgetbanned735@gmail.com
9056d2c94866156e800448c6c76eaaa2947e7356
4014e8a0e9b0c18d37fca762b890c10a21591421
/XZZ2l2nu/tools/metCorr/macros/gjets/preskim_gjets.cc
4b17544ec065fc871f8ac1b097818438b0bf8aa0
[]
no_license
VirginiaCMS/cmgtools-lite
03801ebd074c0c617f75c19abffea60e4e79358c
fc43746a91ca3a2bb857858d3c78e15d20f54074
refs/heads/xzz2l2nu_8026p1
2021-01-24T05:41:59.334426
2017-10-26T00:42:54
2017-10-26T00:42:54
67,161,086
0
2
null
2017-10-26T00:42:55
2016-09-01T19:43:37
Fortran
UTF-8
C++
false
false
15,301
cc
#include "TFile.h" #include "TTree.h" #include "TBranch.h" #include "TH2D.h" #include "TH2F.h" #include "TH1F.h" #include "TMath.h" #include "TVector2.h" #include "TGraphErrors.h" #include <iostream> #include <fstream> #include <sstream> #include <stdlib.h> #include <string> #include <vector> #include <ctime> #include "TROOT.h" bool biggerTree=false; bool haloTree=true; int main(int argc, char** argv) { if( argc<3 ) { std::cout << argv[0] << ": " << std::endl ; std::cout << " Functionality: skimming... " << std::endl; std::cout << " " << std::endl; std::cout << " usage: " << argv[0] << " inputfile.root outputfile.root" << std::endl ; exit(1) ; } time_t now = time(0); char* dt = ctime(&now); std::cout << "Start time is: " << dt << std::endl; // input file name std::string inputfile((const char*)argv[1]); // output file name std::string outputfile((const char*)argv[2]); // initialize // root files TFile* finput = TFile::Open(inputfile.c_str()); TFile* foutput = TFile::Open(outputfile.c_str(), "recreate"); // tree TTree* tree = (TTree*)finput->Get("tree"); Int_t isData; tree->SetBranchAddress("isData",&isData); // check if tree has events if (tree->GetEntries()<=0) return 0; // get isData info tree->GetEntry(0); // select branches // tree->SetBranchStatus("photon_*",0); // tree->SetBranchStatus("jet_*",0); tree->SetBranchStatus("lep_*",0); // tree->SetBranchStatus("gjet_l*_px",0); // tree->SetBranchStatus("gjet_l*_py",0); // tree->SetBranchStatus("gjet_l*_pz",0); tree->SetBranchStatus("gjet_l2_eta",0); tree->SetBranchStatus("gjet_l2_rapidity",0); tree->SetBranchStatus("gjet_l2_mass",0); tree->SetBranchStatus("gjet_dPT*",0); tree->SetBranchStatus("gjet_deltaPhi",0); tree->SetBranchStatus("gjet_CosDeltaPhi",0); tree->SetBranchStatus("gjet_metOvSqSET",0); tree->SetBranchStatus("gjet_l1_mass",0); /////// // tree->SetBranchStatus("gjet_l1_chHadIso",0); // tree->SetBranchStatus("gjet_l1_phIso",0); // tree->SetBranchStatus("gjet_l1_neuHadIso",0); // tree->SetBranchStatus("gjet_l1_e5x5",0); // tree->SetBranchStatus("gjet_l1_e3x3",0); // tree->SetBranchStatus("gjet_l1_e2x5",0); // tree->SetBranchStatus("gjet_l1_e1x5",0); // tree->SetBranchStatus("gjet_l1_eTop",0); // tree->SetBranchStatus("gjet_l1_eBottom",0); // tree->SetBranchStatus("gjet_l1_eLeft",0); // tree->SetBranchStatus("gjet_l1_eRight",0); // tree->SetBranchStatus("gjet_l1_eMax",0); //// //tree->SetBranchStatus("gjet_l2_metSig",0); tree->SetBranchStatus("gjet_l2_t1*",0); tree->SetBranchStatus("gjet_l2_t1P*",0); // tree->SetBranchStatus("gjet_l2_*smear*", 0); // tree->SetBranchStatus("gjet_l2_*JER*",0); // tree->SetBranchStatus("gjet_l2_*Smear*",0); if (!isData) { //tree->SetBranchStatus("HLT_*",0); tree->SetBranchStatus("gjet_l1_mcMatchId",0); tree->SetBranchStatus("gjet_l1_mcPt",0); tree->SetBranchStatus("gjet_l1_mcEta",0); tree->SetBranchStatus("gjet_l1_mcPhi",0); tree->SetBranchStatus("gjet_l2_genPt",0); tree->SetBranchStatus("gjet_l2_t1Pt_*",1); tree->SetBranchStatus("gjet_l2_t1Phi_*",1); } tree->SetBranchStatus("nlep", 1); tree->SetBranchStatus("njet", 1); tree->SetBranchStatus("nbadmuon", 1); tree->SetAlias("absDeltaPhi", "fabs(TVector2::Phi_mpi_pi(gjet_l2_phi-gjet_l1_phi))"); tree->SetAlias("metPara", "gjet_l2_pt*cos(gjet_l2_phi-gjet_l1_phi)"); tree->SetAlias("metPerp", "gjet_l2_pt*sin(gjet_l2_phi-gjet_l1_phi)"); tree->SetAlias("uPara", "-gjet_l2_pt*cos(gjet_l2_phi-gjet_l1_phi)-gjet_l1_pt"); tree->SetAlias("uPerp", "-gjet_l2_pt*sin(gjet_l2_phi-gjet_l1_phi)"); tree->SetAlias("ut", "sqrt(uPara*uPara+uPerp*uPerp)"); tree->SetAlias("eta", "gjet_l1_eta"); tree->SetAlias("phi", "gjet_l1_phi"); tree->SetAlias("pt", "gjet_l1_pt"); if (isData) { //tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_globalTightHalo2016Filter&&Flag_eeBadScFilter&&Flag_BadPFMuonFilter&&Flag_BadChargedCandidateFilter&&Flag_noBadMuons)"); // for reminiaod tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_eeBadScFilter&&Flag_BadPFMuonFilter&&Flag_BadChargedCandidateFilter&&Flag_noBadMuons)"); // for select only beam halo //tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_globalTightHalo2016Filter&&Flag_eeBadScFilter&&Flag_BadPFMuonFilter&&Flag_BadChargedCandidateFilter)"); // for rereco } else { tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_globalTightHalo2016Filter&&Flag_eeBadScFilter&&Flag_BadPFMuonFilter&&Flag_BadChargedCandidateFilter)"); } //tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_globalTightHalo2016Filter&&Flag_eeBadScFilter&&Flag_BadPFMuonFilter&&Flag_BadChargedCandidateFilter&&Flag_CSCTightHalo2015Filter)"); //else tree->SetAlias("metfilter", "(Flag_EcalDeadCellTriggerPrimitiveFilter&&Flag_HBHENoiseIsoFilter&&Flag_goodVertices&&Flag_HBHENoiseFilter&&Flag_CSCTightHalo2015Filter)"); tree->SetAlias("ieta", "gjet_l1_ieta"); tree->SetAlias("iphi", "gjet_l1_iphi"); // tree->SetAlias("flag3", "((pt>=60&&!(eta>-2.5&&eta<-1.4&&phi>2.4&&phi<3.2)&&!(eta>-2.5&&eta<-1.4&&phi>-0.9&&phi<0.9)&&!(eta>-2.5&&eta<-1.4&&phi>-3.2&&phi<-2.4)&&!(eta>1.4&&eta<2.5&&phi>2.4&&phi<3.2)&&!(eta>1.4&&eta<2.5&&phi>-0.9&&phi<0.9)&&!(eta>1.4&&eta<2.5&&phi>-3.2&&phi<-2.0)&&!(eta>-2.1&&eta<-1.8&&phi>1.2&&phi<1.6)&&!(eta>-2.0&&eta<-1.6&&phi>-2.1&&phi<-1.8)&&!(eta>-0.3&&eta<0.0&&phi>2.5&&phi<3.0)&&!(eta>0.0&&eta<0.3&&phi>2.8&&phi<3.2)&&!(eta>-0.2&&eta<0.3&&phi>0.2&&phi<0.8)&&!(eta>-0.5&&eta<-0.2&&phi>-2.4&&phi<2.0)&&!(eta>2.3&&eta<2.5&&phi>-1.5&&phi<-1.0))||(pt<60&&!(eta>-2.5&&eta<-2.2&&phi>-3.0&&phi<-2.6)&&!(eta>0&&eta<0.3&&phi>-2.4&&phi<-1.4)&&!(eta>-0.2&&eta<0.2&&phi>-3.2&&phi<-2.6)&&!(eta>2.3&&eta<2.5&&phi>-2.6&&phi<-2.0)))"); tree->SetAlias("flag3", "(((gjet_l1_iphi>75||gjet_l1_iphi<25)&&fabs(gjet_l1_eta)>1.5)||(fabs(gjet_l1_eta)<1.5))"); // EB flag //tree->SetAlias("flg1eb", "(fabs(eta)<1.47&&!((ieta==5&&iphi==41)||(ieta==-51&&iphi==196)||(ieta==56&&iphi==67)||(ieta==-45&&iphi==340)||(ieta==58&&iphi==74)||(ieta==79&&iphi==67)||(ieta==72&&iphi==67)||(ieta==4&&iphi==70)||(ieta==17&&iphi==290)||(ieta==-44&&iphi==133)||(ieta==13&&iphi==67)||(ieta==-24&&iphi==119)||(ieta==-84&&iphi==168)||(ieta==73&&iphi==299)||(ieta==49&&iphi==6)||(ieta==-21&&iphi==308)||(ieta==59&&iphi==180)||(ieta==2&&iphi==81)||(ieta==22&&iphi==138)))"); //tree->SetAlias("flg1eb", "(fabs(eta)<1.47&&!((ieta==56&&iphi==67)||(ieta==-24&&iphi==119)||(ieta==72&&iphi==67)||(ieta==79&&iphi==67)||(ieta==-51&&iphi==196)||(ieta==-21&&iphi==308)||(ieta==1&&iphi==81)||(ieta==49&&iphi==6)||(ieta==58&&iphi==74)||(ieta==-31&&iphi==163)))"; //tree->SetAlias("flg1eb", "(fabs(eta)<1.47&&!((ieta==56&&iphi==67)||(ieta==79&&iphi==67)||(ieta==-51&&iphi==196)||(ieta==72&&iphi==67)||(ieta==58&&iphi==74)||(ieta==-24&&iphi==119)||(ieta==-21&&iphi==308)||(ieta==49&&iphi==6)||(ieta==1&&iphi==81)||(ieta==5&&iphi==180)||(ieta==-31&&iphi==163)||(ieta==5&&iphi==305)||(ieta==14&&iphi==321)||(ieta==-2&&iphi==244)||(ieta==-7&&iphi==39)||(ieta==-18&&iphi==189)||(ieta==-12&&iphi==196)||(ieta==6&&iphi==140)||(ieta==-27&&iphi==41)||(ieta==-5&&iphi==183)||(ieta==13&&iphi==218)||(ieta==-4&&iphi==125)||(ieta==-10&&iphi==163)||(ieta==-4&&iphi==229)||(ieta==-11&&iphi==163)||(ieta==-16&&iphi==170)||(ieta==-84&&iphi==168)||(ieta==5&&iphi==307)||(ieta==-10&&iphi==245)||(ieta==8&&iphi==329)||(ieta==-25&&iphi==109)||(ieta==-4&&iphi==183)||(ieta==-11&&iphi==28)||(ieta==26&&iphi==262)||(ieta==4&&iphi==245)||(ieta==3&&iphi==69)||(ieta==3&&iphi==186)||(ieta==-3&&iphi==187)||(ieta==6&&iphi==228)||(ieta==-24&&iphi==176)||(ieta==-3&&iphi==229)||(ieta==2&&iphi==246)||(ieta==-32&&iphi==146)||(ieta==-11&&iphi==182)||(ieta==2&&iphi==237)||(ieta==-4&&iphi==144)||(ieta==-11&&iphi==183)||(ieta==7&&iphi==214)||(ieta==1&&iphi==93)||(ieta==23&&iphi==147)))"); tree->SetAlias("flg1eb", "(fabs(eta)<1.47&&!((ieta==56&&iphi==67)||(ieta==-51&&iphi==196)||(ieta==79&&iphi==67)||(ieta==72&&iphi==67)||(ieta==58&&iphi==74)||(ieta==-24&&iphi==119)||(ieta==49&&iphi==6)||(ieta==-21&&iphi==308)||(ieta==1&&iphi==81)||(ieta==-31&&iphi==163)||(ieta==5&&iphi==180)||(ieta==14&&iphi==321)||(ieta==5&&iphi==305)||(ieta==6&&iphi==140)||(ieta==-18&&iphi==189)||(ieta==-2&&iphi==244)||(ieta==-12&&iphi==196)||(ieta==-7&&iphi==39)||(ieta==-10&&iphi==163)||(ieta==-4&&iphi==229)||(ieta==-27&&iphi==41)||(ieta==-11&&iphi==163)||(ieta==-16&&iphi==170)||(ieta==-5&&iphi==183)||(ieta==13&&iphi==218)||(ieta==-4&&iphi==125)||(ieta==-4&&iphi==183)||(ieta==-84&&iphi==168)||(ieta==5&&iphi==307)||(ieta==-10&&iphi==245)||(ieta==26&&iphi==262)||(ieta==8&&iphi==329)||(ieta==4&&iphi==245)||(ieta==-25&&iphi==109)||(ieta==-11&&iphi==28)||(ieta==2&&iphi==237)||(ieta==-3&&iphi==187)||(ieta==-4&&iphi==144)||(ieta==3&&iphi==186)||(ieta==-3&&iphi==229)||(ieta==2&&iphi==246)||(ieta==-4&&iphi==57)||(ieta==-32&&iphi==146)||(ieta==-11&&iphi==182)||(ieta==5&&iphi==24)||(ieta==-19&&iphi==185)||(ieta==7&&iphi==214)||(ieta==-4&&iphi==53)||(ieta==2&&iphi==66)||(ieta==23&&iphi==147)))"); // EE+ flag //tree->SetAlias("flg1eep", "(eta>1.566&&!((ieta==55&&iphi==27)||(ieta==62&&iphi==30)||(ieta==36&&iphi==64)||(ieta==43&&iphi==31)||(ieta==46&&iphi==31)||(ieta==42&&iphi==68)||(ieta==63&&iphi==31)||(ieta==48&&iphi==33)||(ieta==61&&iphi==35)||(ieta==61&&iphi==31)||(ieta==43&&iphi==32)||(ieta==46&&iphi==33)||(ieta==62&&iphi==35)||(ieta==38&&iphi==65)||(ieta==41&&iphi==68)||(ieta==40&&iphi==69)||(ieta==43&&iphi==70)||(ieta==44&&iphi==70)||(ieta==55&&iphi==70)||(ieta==52&&iphi==17)||(ieta==48&&iphi==21)||(ieta==48&&iphi==27)||(ieta==56&&iphi==29)||(ieta==65&&iphi==29)||(ieta==61&&iphi==30)||(ieta==37&&iphi==68)||(ieta==43&&iphi==69)||(ieta==49&&iphi==71)||(ieta==48&&iphi==74)))"); tree->SetAlias("flg1eep", "(eta>1.566)"); //tree->SetAlias("flg1eep", "((eta>1.566)&&!((ieta==48&&iphi==76)||(ieta==52&&iphi==76)||(ieta==52&&iphi==79)||(ieta==52&&iphi==80)||(ieta==53&&iphi==76)||(ieta==59&&iphi==24)||(ieta==47&&iphi==76)||(ieta==49&&iphi==76)||(ieta==48&&iphi==77)||(ieta==52&&iphi==21)||(ieta==53&&iphi==22)||(ieta==45&&iphi==76)))"); // EE- flag //tree->SetAlias("flg1eem", "(eta<-1.566&&!((ieta==44&&iphi==31)||(ieta==46&&iphi==31)||(ieta==47&&iphi==32)||(ieta==50&&iphi==31)||(ieta==61&&iphi==32)||(ieta==43&&iphi==33)||(ieta==37&&iphi==34)||(ieta==61&&iphi==34)||(ieta==37&&iphi==65)||(ieta==23&&iphi==21)||(ieta==59&&iphi==29)||(ieta==58&&iphi==30)||(ieta==46&&iphi==32)||(ieta==41&&iphi==33)||(ieta==46&&iphi==33)||(ieta==61&&iphi==35)||(ieta==38&&iphi==36)||(ieta==38&&iphi==64)||(ieta==68&&iphi==28)||(ieta==59&&iphi==30)||(ieta==36&&iphi==31)||(ieta==43&&iphi==32)||(ieta==42&&iphi==33)||(ieta==41&&iphi==34)||(ieta==59&&iphi==34)||(ieta==36&&iphi==35)||(ieta==37&&iphi==37)||(ieta==43&&iphi==69)||(ieta==58&&iphi==69)||(ieta==52&&iphi==74)||(ieta==36&&iphi==26)||(ieta==46&&iphi==27)||(ieta==49&&iphi==30)||(ieta==36&&iphi==32)||(ieta==37&&iphi==32)||(ieta==42&&iphi==32)||(ieta==38&&iphi==33)||(ieta==58&&iphi==33)||(ieta==63&&iphi==34)||(ieta==39&&iphi==65)||(ieta==37&&iphi==66)||(ieta==41&&iphi==68)||(ieta==59&&iphi==68)||(ieta==62&&iphi==70)||(ieta==49&&iphi==71)||(ieta==55&&iphi==71)||(ieta==51&&iphi==72)))"); tree->SetAlias("flg1eem", "(eta<-1.566)"); //tree->SetAlias("filter1", "(gjet_l1_sigmaIetaIeta>0.001&&gjet_l1_sigmaIphiIphi>0.001&&gjet_l1_SwissCross<0.95&&gjet_l1_mipTotE<4.9&&gjet_l1_time>-2.08&&gjet_l1_time<0.92)"); tree->SetAlias("filter1", "(gjet_l1_sigmaIetaIeta>0.001&&gjet_l1_sigmaIphiIphi>0.001&&gjet_l1_SwissCross<0.95&&gjet_l1_mipTotE<4.9&&gjet_l1_time>-2.58&&gjet_l1_time<1.42)"); if (haloTree) tree->SetAlias("filter1", "(gjet_l1_sigmaIetaIeta>0.001&&gjet_l1_sigmaIphiIphi>0.001&&gjet_l1_SwissCross<0.95&&gjet_l1_mipTotE>4.9)"); // select halo //TTree* tree_out = tree->CloneTree(-1); char ftmp1_name[1000]; sprintf(ftmp1_name, "%s_tmp1.root", outputfile.c_str() ); TFile* ftmp1 = TFile::Open(ftmp1_name, "recreate"); TTree* tree_tmp1; TTree* tree_tmp2; TTree* tree_tmp3; std::string selec; if (biggerTree) { selec = "HLT_PHOTONIDISO&&ngjet==1&&Max$(jet_pt[]*jet_chargedEmEnergyFraction[])<10&&Max$(jet_pt[]*jet_muonEnergyFraction[])<10&&flag3&&nlep==0"; } else { selec = "HLT_PHOTONIDISO&&metfilter&&ngjet==1&&Max$(jet_pt[]*jet_chargedEmEnergyFraction[])<10&&Max$(jet_pt[]*jet_muonEnergyFraction[])<10&&flag3&&filter1&&nlep==0"; if (haloTree) selec = "HLT_PHOTONIDISO&&metfilter&&ngjet==1&&filter1&&flag3"; // select halo } std::cout << "tree: " << tree->GetEntries() << " Entries" << std::endl; tree_tmp1 = tree->CopyTree(selec.c_str()); std::cout << "tree_tmp1: " << tree_tmp1->GetEntries() << " Entries" << std::endl; if (!biggerTree){ if (!haloTree) tree_tmp1->SetBranchStatus("Flag_*",0); // tree_tmp1->SetBranchStatus("Flag_hasBadMuon", 1); // for reminiaod tree_tmp1->SetBranchStatus("Flag_CSCTightHalo2015Filter", 1); tree_tmp1->SetBranchStatus("Flag_CSCTightHaloFilter", 1); } tree_tmp1->SetBranchStatus("HLT_*",0); tree_tmp1->SetBranchStatus("HLT_PHOTONIDISO", 1); tree_tmp1->SetBranchStatus("jet_*",0); tree_tmp1->SetBranchStatus("photon_*",0); tree_tmp1->SetBranchStatus("nphoton",1); tree_tmp1->SetBranchStatus("vtx_x",0); tree_tmp1->SetBranchStatus("vtx_y",0); //tree_tmp1->SetBranchStatus("jet_rawPt",1); //tree_tmp1->SetBranchStatus("jet_eta",1); //tree_tmp1->SetBranchStatus("jet_phi",1); //tree_tmp1->SetBranchStatus("jet_area",1); if (biggerTree){ tree_tmp3 = tree_tmp1; } else { tree_tmp2 = tree_tmp1->CopyTree("((eta<-1.566)||flg1eb||flg1eep)"); std::cout << "tree_tmp2: " << tree_tmp2->GetEntries() << " Entries" << std::endl; tree_tmp3 = tree_tmp2->CopyTree("((eta>-1.566)||flg1eem)"); std::cout << "tree_tmp3: " << tree_tmp3->GetEntries() << " Entries" << std::endl; } foutput->cd(); TTree* tree_out; if (isData) tree_out = tree_tmp3->CopyTree("(gjet_l1_trigerob_HLTbit>>0&1&&gjet_l1_trigerob_pt<=30)||(gjet_l1_trigerob_HLTbit>>1&1&&gjet_l1_trigerob_pt<=36)||(gjet_l1_trigerob_HLTbit>>2&1&&gjet_l1_trigerob_pt<=50)||(gjet_l1_trigerob_HLTbit>>3&1&&gjet_l1_trigerob_pt<=75)||(gjet_l1_trigerob_HLTbit>>4&1&&gjet_l1_trigerob_pt<=90)||(gjet_l1_trigerob_HLTbit>>5&1&&gjet_l1_trigerob_pt<=120)||(gjet_l1_trigerob_HLTbit>>6&1&&gjet_l1_trigerob_pt<=165)||(gjet_l1_trigerob_HLTbit>>7&1&&gjet_l1_trigerob_pt<=10000000)"); else tree_out = tree_tmp3->CloneTree(-1); std::cout << "tree_out: " << tree_out->GetEntries() << " Entries" << std::endl; foutput->cd(); tree_out->Write(); foutput->Close(); finput->Close(); char line[1000]; sprintf(line, ".! rm %s", ftmp1_name); gROOT->ProcessLine(line); now = time(0); dt = ctime(&now); std::cout << "End time is: " << dt << std::endl; return 0; }
[ "Hengne.Li@CERN.CH" ]
Hengne.Li@CERN.CH
e7b8b83d7eb96a67ba129e1e34aaa653eab8dbc5
5369b0f0a9950297dee7f2c8dc0d59433fc08854
/horrorGame01/horrorGame01/Common/Vector2.h
aeb67e00d6de2dbf48be2816b5bf7c6bb8af6f63
[]
no_license
terataichi/horrorGame
683bc50445ccadb3e7a30f51408488b47148f179
2ce36dd3d27ca16ae6bcaa374c968df0c8698f75
refs/heads/master
2023-08-21T05:05:10.353466
2021-10-12T15:05:16
2021-10-12T15:05:16
405,837,804
0
0
null
null
null
null
ISO-8859-7
C++
false
false
3,311
h
#pragma once #define GRAVITY 10.0f // ΓέΜίΪ°Δ‰»‚΅‚ά template<class T> class Vector2Template { public: Vector2Template(); Vector2Template(T x, T y); ~Vector2Template(); T x_; T y_; operator Vector2Template<int>() { return Vector2Template<int>{ static_cast<int>(x_), static_cast<int>(y_) }; }; operator Vector2Template<float>() { return Vector2Template<float>{ static_cast<float>(x_), static_cast<float>(y_) }; }; Vector2Template operator + ()const; Vector2Template operator - ()const; // ‘γ“ό‰‰ŽZŽq Vector2Template& operator = (const Vector2Template& vec); // ”δŠr‰‰ŽZŽq bool operator == (const Vector2Template& vec)const; bool operator != (const Vector2Template& vec)const; bool operator > (const Vector2Template& vec)const; bool operator >= (const Vector2Template& vec)const; bool operator < (const Vector2Template& vec)const; bool operator <= (const Vector2Template& vec)const; // “Y‚¦Žš‰‰ŽZŽq int& operator [] (int i); // ’P€‰‰ŽZŽq Vector2Template& operator += (const Vector2Template& vec); Vector2Template& operator -= (const Vector2Template& vec); Vector2Template& operator *= (const Vector2Template& vec); Vector2Template& operator /= (const Vector2Template& vec); Vector2Template& operator %= (const Vector2Template& vec); Vector2Template& operator *= (T k); Vector2Template& operator /= (T k); float Magnitude()const; static Vector2Template ZERO; Vector2Template<float> Normalized(void); }; // ’P€‰‰ŽZŽq@Vector2 E int template<class T> Vector2Template<T> operator +(const Vector2Template<T>& u, const T& k); template<class T> Vector2Template<T> operator -(const Vector2Template<T>& u, const T& k); template<class T> Vector2Template<T> operator *(const Vector2Template<T>& u, const T& k); template<class T> Vector2Template<T> operator /(const Vector2Template<T>& u, const T& k); template<class T> Vector2Template<T> operator %(const Vector2Template<T>& u, const T& k); // ’P€‰‰ŽZŽq@Vector2 E Vector2 template<class T> Vector2Template<T> operator +(const Vector2Template<T>& u, const Vector2Template<T>& v); template<class T> Vector2Template<T> operator -(const Vector2Template<T>& u, const Vector2Template<T>& v); template<class T> Vector2Template<T> operator *(const Vector2Template<T>& u, const Vector2Template<T>& v); template<class T> Vector2Template<T> operator /(const Vector2Template<T>& u, const Vector2Template<T>& v); template<class T> Vector2Template<T> operator %(const Vector2Template<T>& u, const Vector2Template<T>& v); // int * Vector2 template<class T> Vector2Template<T> operator *(const T& k, const Vector2Template<T>& u); // “ΰΟ template<class T> float Dot(const Vector2Template<T>& u, const Vector2Template<T>& v); // ŠOΟ template<class T> float Cross(const Vector2Template<T>& u, const Vector2Template<T>& v); // –@όƒxƒNƒgƒ‹ template<class T> Vector2Template<T> Normal(const Vector2Template<T>& u); // β‘Ξ’l template<class T> Vector2Template<T> abs(const Vector2Template<T>& u); using Vector2 = Vector2Template<int>; using Vector2d = Vector2Template<double>; using Vector2f = Vector2Template<float>; using Potision2 = Vector2; using Potision2f = Vector2f; using Size = Vector2; using Sizef = Vector2f; #include "details/Vector2.h"
[ "taichiz519@gmail.com" ]
taichiz519@gmail.com
3e6539a3d9f27878180beb9f609f643092b8f84e
e6769524d7a8776f19df0c78e62c7357609695e8
/branches/v0.5-new_cache_system/retroshare-gui/src/gui/TransfersDialog.h
31376769faf851a4f12178e2b3c539dce8c4a5ca
[]
no_license
autoscatto/retroshare
025020d92084f9bc1ca24da97379242886277779
e0d85c7aac0a590d5839512af8a1e3abce97ca6f
refs/heads/master
2020-04-09T11:14:01.836308
2013-06-30T13:58:17
2013-06-30T13:58:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,286
h
/**************************************************************** * RetroShare is distributed under the following license: * * Copyright (C) 2006,2007 crypton * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ****************************************************************/ #ifndef _TRANSFERSDIALOG_H #define _TRANSFERSDIALOG_H #include <set> #include <retroshare/rstypes.h> #include "RsAutoUpdatePage.h" #include "ui_TransfersDialog.h" class DLListDelegate; class ULListDelegate; class QStandardItemModel; class QStandardItem; class DetailsDialog; class FileProgressInfo; class TransfersDialog : public RsAutoUpdatePage { Q_OBJECT public: /** Default Constructor */ TransfersDialog(QWidget *parent = 0); ~TransfersDialog(); // replaced by shortcut // virtual void keyPressEvent(QKeyEvent *) ; virtual void updateDisplay() ; // derived from RsAutoUpdateWidget static DetailsDialog *detailsdlg; public slots: void insertTransfers(); // void handleDownloadRequest(const QString& url); private slots: /** Create the context popup menu and it's submenus */ void downloadListCostumPopupMenu( QPoint point ); void cancel(); void forceCheck(); /** removes finished Downloads**/ void clearcompleted(); void copyLink(); void pasteLink(); // void rootdecorated(); // void rootisnotdecorated(); void pauseFileTransfer(); void resumeFileTransfer(); void openFolderTransfer(); void openTransfer(); void previewTransfer(); /** clear download or all queue - for pending dwls */ // void clearQueue(); /** modify download priority actions */ void priorityQueueUp(); void priorityQueueDown(); void priorityQueueTop(); void priorityQueueBottom(); void speedSlow(); void speedAverage(); void speedFast(); void changeSpeed(int) ; void changeQueuePosition(QueueMove) ; void chunkRandom(); void chunkStreaming(); void showDetailsDialog(); void updateDetailsDialog(); void openCollection(); signals: void playFiles(QStringList files); private: QString getPeerName(const std::string& peer_id) const ; QStandardItemModel *DLListModel; QStandardItemModel *ULListModel; QItemSelectionModel *selection; QItemSelectionModel *selectionup; DLListDelegate *DLDelegate; ULListDelegate *ULDelegate; /** Create the actions on the tray menu or menubar */ void createActions(); /** Defines the actions for the context menu */ QAction* showdowninfoAct; QAction* playAct; QAction* cancelAct; QAction* forceCheckAct; QAction* clearcompletedAct; QAction* copylinkAct; QAction* pastelinkAct; QAction* rootisnotdecoratedAct; QAction* rootisdecoratedAct; QAction *pauseAct; QAction *resumeAct; QAction *openfolderAct; QAction *openfileAct; QAction *previewfileAct; // QAction *clearQueuedDwlAct; // QAction *clearQueueAct; QAction *changePriorityAct; QAction *prioritySlowAct; QAction *priorityMediumAct; QAction *priorityFastAct; QAction *queueDownAct; QAction *queueUpAct; QAction *queueTopAct; QAction *queueBottomAct; QAction *chunkRandomAct; QAction *chunkStreamingAct; QAction *detailsfileAct; bool m_bProcessSettings; void processSettings(bool bLoad); void getSelectedItems(std::set<std::string> *ids, std::set<int> *rows); bool controlTransferFile(uint32_t flags); void changePriority(int priority); void setChunkStrategy(FileChunksInfo::ChunkStrategy s) ; QTreeView *downloadList; /** Adds a new action to the toolbar. */ void addAction(QAction *action, const char *slot = 0); /** Qt Designer generated object */ Ui::TransfersDialog ui; public slots: // these two functions add entries to the transfers dialog, and return the row id of the entry modified/added // int addItem(const QString& symbol, const QString& name, const QString& coreID, qlonglong size, const FileProgressInfo& pinfo, double dlspeed, const QString& sources, const QString& status, const QString& priority, qlonglong completed, qlonglong remaining, qlonglong downloadtime); int addPeerToItem(int row, const QString& name, const QString& coreID, double dlspeed, uint32_t status, const FileProgressInfo& peerInfo); // void delItem(int row); int addUploadItem(const QString& symbol, const QString& name, const QString& coreID, qlonglong size, const FileProgressInfo& pinfo, double dlspeed, const QString& sources,const QString& source_id, const QString& status, qlonglong completed, qlonglong remaining); // void delUploadItem(int row); void showFileDetails() ; double getProgress(int row, QStandardItemModel *model); double getSpeed(int row, QStandardItemModel *model); QString getFileName(int row, QStandardItemModel *model); QString getStatus(int row, QStandardItemModel *model); QString getID(int row, QStandardItemModel *model); QString getPriority(int row, QStandardItemModel *model); qlonglong getFileSize(int row, QStandardItemModel *model); qlonglong getTransfered(int row, QStandardItemModel *model); qlonglong getRemainingTime(int row, QStandardItemModel *model); qlonglong getDownloadTime(int row, QStandardItemModel *model); QString getSources(int row, QStandardItemModel *model); }; #endif
[ "chrisparker126@b45a01b8-16f6-495d-af2f-9b41ad6348cc" ]
chrisparker126@b45a01b8-16f6-495d-af2f-9b41ad6348cc
142aecf8e27136cda26aef6926186d03550e81e7
d7f98c207a9953af80eaf9b885bdeff44cb4282d
/timer1-ctc-ocr-polling/timer1-ctc-ocr-polling.ino
361d8c37e62884df5a8a979de98cab8a869257a4
[]
no_license
yohanes-erwin/arduino
7e2db3240cdf70eb213b888e970a12a044b2c9c4
2bf61eecbbfe9d9ab7763745694258cf9526cd58
refs/heads/master
2021-06-03T22:40:33.293051
2016-07-01T02:55:21
2016-07-01T02:55:21
51,231,970
0
0
null
null
null
null
UTF-8
C++
false
false
818
ino
/******************************************************************************* * Make delay 1s with timer 1, CTC mode(top = OCR1A), prescaler 256, pooling * OCR1A = (1s*16000000Hz)/256 = 62500 = 0xF424 ******************************************************************************* */ void setup() { // PB5 (Arduino digital pin 13) as output bitSet(DDRB, 5); } void loop() { // Toggle LED on pin 13 bitSet(PINB, 5); // Delay 1s T1Delay(); } // Delay 1s void T1Delay() { // Load initial count value TCNT1 = 0; // Load compare match value OCR1A = 0xF424; // CTC mode, prescaler 256 TCCR1A = 0; TCCR1B = (1 << WGM12) | (1 << CS12); // Wait until timer 1 compare match while (!(TIFR1 & (1 << OCF1A))); // Stop timer 1 TCCR1B = 0; // Clear OCF1A flag TIFR1 = (1 << OCF1A); }
[ "erwin.setiawan789@gmail.com" ]
erwin.setiawan789@gmail.com
9f81c25f925a91b7213404fb18e7590945c0e6c1
8d263f87a0c89ee59c9f8134a1dadd07e3929cd4
/800/domino_pilling.cpp
f6f3efd3a2fe8548f768f247865f9804693d2e8b
[]
no_license
JustSmashUp/Codeforces
acb8388968425290f73d9fed9205e48b5ab6e4e6
419f4165bd024da6966733a5da53c5808d2aa39f
refs/heads/main
2023-01-24T21:10:23.410705
2020-12-06T11:21:53
2020-12-06T11:21:53
317,134,191
0
0
null
null
null
null
UTF-8
C++
false
false
119
cpp
#include <iostream> using namespace std; int main() { int m,n; cin >> m >> n; cout<< ((m*n)/2) <<endl; }
[ "rifatsarker71@gmail.com" ]
rifatsarker71@gmail.com
623e55a6fc4d85437c60ff01e24a29781e4d20d0
c1ed724117e99f42a5b2a8f74a92e697e1ae6b5c
/bts_study/14593.cpp
4643016f36e606efb26ccf26080c87b0da574673
[]
no_license
Hee-Jae/Algorithm
73d45913494541d4f38baa2e32259c4e9f50ab0b
a159380ff2a4f7ead2fb625618169b9b32335a17
refs/heads/master
2023-08-15T14:29:55.414276
2021-10-02T08:27:16
2021-10-02T08:27:16
401,086,191
0
0
null
null
null
null
UTF-8
C++
false
false
565
cpp
#include <iostream> #include <vector> #include <algorithm> #define mp make_pair #define pb push_back #define pii pair<int, int> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); vector<pair<pii, pii> > v; int N,S,C,L; cin >> N; for(int i=0; i<N; i++){ cin >> S >> C >> L; v.pb(mp(mp(S,-C), mp(-L,i))); } sort(v.begin(), v.end(), greater<pair<pii, pii> >()); // for(int i=0; i<N; i++) // cout << v[i].first.first << " " << v[i].first.second << " " << v[i].second.first << "\n"; cout << (v[0].second.second + 1); }
[ "jhj967878@naver.com" ]
jhj967878@naver.com
d26dded91a9f39f7d2ecff0df7b37d47f0fae64a
e1fe38f9207053ffa1c68c050ed6dc5e63975cd4
/array/car_pool.cpp
d0e414bc847bcda85781edda7b107e7e31ca01dd
[]
no_license
dhruv2600/leet
3199c568d7296219336ede0da8238ecd094ac402
71e73e999fa689285e7a9bc2414e7536c72cdab7
refs/heads/master
2023-09-03T06:24:41.885912
2021-10-22T17:15:06
2021-10-22T17:15:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
class Solution { public: bool carPooling(vector<vector<int>>& trips, int capacity) { int car=0; unordered_map<int,int>pick; unordered_map<int,int>drop; int maxdrop=INT_MIN; for(auto it:trips) { pick[it[1]]=it[0]; drop[it[2]]=it[0]; maxdrop=max(maxdrop,it[2]); } for(int i=1;i<=maxdrop;i++) { if(pick[i]!=0) { car+=pick[i]; } if(drop[i]!=0) { car-=drop[i]; } if(car>capacity|| car<0) return false; } cout<<car; return true; } };
[ "dhruvsharma2600@gmail.com" ]
dhruvsharma2600@gmail.com
3acae2c3452c149b026e9e702c693600a4623fb3
70828283ca189ff2dbd979adaeb03ebdacdd0da3
/vulkansdk-macos-1.2.162.0/macOS/include/spirv_cross/spirv_msl.hpp
5d34ca615fa05ce8b0430863789479af97834e3c
[]
no_license
mterekhov/doom
8c4703b91bed4b71b6dd4d2949e412d2d5142daf
e67dea1d95604c899d0254869e0aa9ee186591a2
refs/heads/master
2023-06-24T09:35:33.833068
2021-03-12T09:04:24
2021-03-12T09:04:24
331,362,925
0
0
null
null
null
null
UTF-8
C++
false
false
130
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:3b37bc65fadaa9b3d85dacf9b92f8acfa310d419f63aeaf904dd2ff06deaf09f size 48635
[ "" ]
c9e68c1150f0439dabcb2c9c99d818785956dadc
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5769900270288896_0/C++/naagi/b.cpp
af98a9bf0fe60dcaacdd46c926d87801072c6e6c
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
880
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; int main (void) { int test, tests; scanf ("%d", &tests); for (test = 0; test < tests; test++) { int i, j, k, n, r, c, res = 1000, tres; scanf ("%d %d %d", &r, &c, &n); for (i = 0; i < 1 << (r * c); i++) { tres = 0; if (__builtin_popcount(i) == n) { for (j = 1; j < r; j++) for (k = 0; k < c; k++) tres += (i & (1 << (j * c + k))) && (i & (1 << ((j-1) * c + k ))); for (j = 0; j < r; j++) for (k = 1; k < c; k++) tres += (i & (1 << (j * c + k))) && (i & (1 << (j * c + k - 1))); if (res > tres) res = tres; } } printf ("Case #%d: %d\n", test + 1, res); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
1146bc0dd4544622d47c72564121f021c3922679
b32dc9c68715276f36ec455b90a602348d39522a
/src/source/class/display/model/obj/Obj.h
b4e93543ca595cc3a4d3c05cfff381ec52a1b47b
[]
no_license
wicanr2/GameTest
3287432f7cb60323e0a61489aa515f660dac7d44
2ca9ac9401c75305bc86750e16d6bc56400f8814
refs/heads/master
2021-01-15T08:31:55.280976
2015-12-14T09:07:17
2015-12-14T09:07:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
#ifndef OBJ_H_ #define OBJ_H_ #include <GL/glew.h> #include <glm/glm.hpp> #include <vector> #include <class/display/model/obj/Face.h> class Model; class Obj{ public: Obj(); virtual ~Obj(); static Obj* load_obj(const char* path); std::vector<glm::vec3>v; std::vector<glm::vec2>uv; std::vector<glm::vec3>vn; std::vector<Face>fs; protected: }; #endif /* OBJ_H_ */
[ "tim11251994@gmail.com" ]
tim11251994@gmail.com
b142c07e0e3718c90762c38979ea32d2adbcd887
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5658571765186560_0/C++/nike0good/D_3.cpp
275aa510fc3a023cf5b95eb50916a0a85eca6e33
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,541
cpp
#include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<functional> #include<iostream> #include<cmath> #include<cctype> #include<ctime> using namespace std; #define For(i,n) for(int i=1;i<=n;i++) #define Fork(i,k,n) for(int i=k;i<=n;i++) #define Rep(i,n) for(int i=0;i<n;i++) #define ForD(i,n) for(int i=n;i;i--) #define RepD(i,n) for(int i=n;i>=0;i--) #define Forp(x) for(int p=pre[x];p;p=next[p]) #define Forpiter(x) for(int &p=iter[x];p;p=next[p]) #define Lson (x<<1) #define Rson ((x<<1)+1) #define MEM(a) memset(a,0,sizeof(a)); #define MEMI(a) memset(a,127,sizeof(a)); #define MEMi(a) memset(a,128,sizeof(a)); #define INF (2139062143) #define F (100000007) #define MAXT (100+10) #define MAXN (20+10) typedef long long ll; ll mul(ll a,ll b){return (a*b)%F;} ll add(ll a,ll b){return (a+b)%F;} ll sub(ll a,ll b){return (a-b+(a-b)/F*F+F)%F;} void upd(ll &a,ll b){a=(a%F+b%F)%F;} int T,x,n,m; int main() { freopen("D-small-attempt2.in","r",stdin); freopen("D-small-attempt2.out","w",stdout); cin>>T; For(kcase,T) { printf("Case #%d: ",kcase); scanf("%d%d%d",&x,&n,&m); if (n>m) swap(n,m); //n<=m if (x>=7 || n*m%x!=0 || max(n,m)<x ) { printf("RICHARD\n"); } else { if (n>x&&m>x) printf("GABRIEL\n"); else if (n==x&&m>=x) printf("GABRIEL\n"); else if (n==x-1&&m==x) printf("GABRIEL\n"); else if (n<=x&&m<=x) printf("RICHARD\n"); else printf("GABRIEL\n"); } } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
d48f444ecd6a5be9270bc82e03257618eb81020c
bb6ebff7a7f6140903d37905c350954ff6599091
/net/socket/ssl_server_socket_nss.h
bc5b65d53687fb58e51c4ac6bbd70764cb53ebd3
[ "BSD-3-Clause" ]
permissive
PDi-Communication-Systems-Inc/lollipop_external_chromium_org
faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f
ccadf4e63dd34be157281f53fe213d09a8c66d2c
refs/heads/master
2022-12-23T18:07:04.568931
2016-04-11T16:03:36
2016-04-11T16:03:36
53,677,925
0
1
BSD-3-Clause
2022-12-09T23:46:46
2016-03-11T15:49:07
C++
UTF-8
C++
false
false
4,765
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_SOCKET_SSL_SERVER_SOCKET_NSS_H_ #define NET_SOCKET_SSL_SERVER_SOCKET_NSS_H_ #include <certt.h> #include <keyt.h> #include <nspr.h> #include <nss.h> #include "base/memory/scoped_ptr.h" #include "net/base/completion_callback.h" #include "net/base/host_port_pair.h" #include "net/base/net_log.h" #include "net/base/nss_memio.h" #include "net/socket/ssl_server_socket.h" #include "net/ssl/ssl_config_service.h" namespace net { class SSLServerSocketNSS : public SSLServerSocket { public: // See comments on CreateSSLServerSocket for details of how these // parameters are used. SSLServerSocketNSS(scoped_ptr<StreamSocket> socket, scoped_refptr<X509Certificate> certificate, crypto::RSAPrivateKey* key, const SSLConfig& ssl_config); virtual ~SSLServerSocketNSS(); // SSLServerSocket interface. virtual int Handshake(const CompletionCallback& callback) OVERRIDE; // SSLSocket interface. virtual int ExportKeyingMaterial(const base::StringPiece& label, bool has_context, const base::StringPiece& context, unsigned char* out, unsigned int outlen) OVERRIDE; virtual int GetTLSUniqueChannelBinding(std::string* out) OVERRIDE; // Socket interface (via StreamSocket). virtual int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) OVERRIDE; virtual int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback) OVERRIDE; virtual int SetReceiveBufferSize(int32 size) OVERRIDE; virtual int SetSendBufferSize(int32 size) OVERRIDE; // StreamSocket implementation. virtual int Connect(const CompletionCallback& callback) OVERRIDE; virtual void Disconnect() OVERRIDE; virtual bool IsConnected() const OVERRIDE; virtual bool IsConnectedAndIdle() const OVERRIDE; virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE; virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE; virtual const BoundNetLog& NetLog() const OVERRIDE; virtual void SetSubresourceSpeculation() OVERRIDE; virtual void SetOmniboxSpeculation() OVERRIDE; virtual bool WasEverUsed() const OVERRIDE; virtual bool UsingTCPFastOpen() const OVERRIDE; virtual bool WasNpnNegotiated() const OVERRIDE; virtual NextProto GetNegotiatedProtocol() const OVERRIDE; virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE; private: enum State { STATE_NONE, STATE_HANDSHAKE, }; int InitializeSSLOptions(); void OnSendComplete(int result); void OnRecvComplete(int result); void OnHandshakeIOComplete(int result); int BufferSend(); void BufferSendComplete(int result); int BufferRecv(); void BufferRecvComplete(int result); bool DoTransportIO(); int DoPayloadRead(); int DoPayloadWrite(); int DoHandshakeLoop(int last_io_result); int DoReadLoop(int result); int DoWriteLoop(int result); int DoHandshake(); void DoHandshakeCallback(int result); void DoReadCallback(int result); void DoWriteCallback(int result); static SECStatus OwnAuthCertHandler(void* arg, PRFileDesc* socket, PRBool checksig, PRBool is_server); static void HandshakeCallback(PRFileDesc* socket, void* arg); int Init(); // Members used to send and receive buffer. bool transport_send_busy_; bool transport_recv_busy_; scoped_refptr<IOBuffer> recv_buffer_; BoundNetLog net_log_; CompletionCallback user_handshake_callback_; CompletionCallback user_read_callback_; CompletionCallback user_write_callback_; // Used by Read function. scoped_refptr<IOBuffer> user_read_buf_; int user_read_buf_len_; // Used by Write function. scoped_refptr<IOBuffer> user_write_buf_; int user_write_buf_len_; // The NSS SSL state machine PRFileDesc* nss_fd_; // Buffers for the network end of the SSL state machine memio_Private* nss_bufs_; // StreamSocket for sending and receiving data. scoped_ptr<StreamSocket> transport_socket_; // Options for the SSL socket. SSLConfig ssl_config_; // Certificate for the server. scoped_refptr<X509Certificate> cert_; // Private key used by the server. scoped_ptr<crypto::RSAPrivateKey> key_; State next_handshake_state_; bool completed_handshake_; DISALLOW_COPY_AND_ASSIGN(SSLServerSocketNSS); }; } // namespace net #endif // NET_SOCKET_SSL_SERVER_SOCKET_NSS_H_
[ "mrobbeloth@pdiarm.com" ]
mrobbeloth@pdiarm.com
71bc115dd8a4d46898ddf592b7475258076f5355
8647e338d2885d036908fdce8abd4f96fa6f1cd7
/keymaster/v0.2/keymaster_linaro.cpp
0e71cf2b0e0fbff2f167b8f153e22cb274cf288c
[]
no_license
vchong/device-linaro-sks
32c1a2687933bce0a404346dff4598588c60ccaf
00c807a2048d0309207fe7830f5fb3ef102344f4
refs/heads/master
2018-09-09T22:45:10.893017
2018-05-26T14:40:43
2018-05-26T14:40:43
127,885,106
0
0
null
null
null
null
UTF-8
C++
false
false
26,007
cpp
/* * Copyright (C) 2018 The Android Open Source Project * * 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. */ #include <errno.h> #include <string.h> #include <stdint.h> #include <keystore/keystore.h> #include <keymaster_linaro.h> #include <hardware/hardware.h> #include <hardware/keymaster0.h> #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/err.h> #include <openssl/x509.h> #include <memory> // For debugging #define LOG_NDEBUG 1 #define LOG_TAG "LinaroKeyMaster" #include <cutils/log.h> struct BIGNUM_Delete { void operator()(BIGNUM* p) const { BN_free(p); } }; typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM; struct EVP_PKEY_Delete { void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } }; typedef std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; struct PKCS8_PRIV_KEY_INFO_Delete { void operator()(PKCS8_PRIV_KEY_INFO* p) const { PKCS8_PRIV_KEY_INFO_free(p); } }; typedef std::unique_ptr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO; struct DSA_Delete { void operator()(DSA* p) const { DSA_free(p); } }; typedef std::unique_ptr<DSA, DSA_Delete> Unique_DSA; struct EC_KEY_Delete { void operator()(EC_KEY* p) const { EC_KEY_free(p); } }; typedef std::unique_ptr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY; struct EC_GROUP_Delete { void operator()(EC_GROUP* p) const { EC_GROUP_free(p); } }; typedef std::unique_ptr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP; struct RSA_Delete { void operator()(RSA* p) const { RSA_free(p); } }; typedef std::unique_ptr<RSA, RSA_Delete> Unique_RSA; struct Malloc_Free { void operator()(void* p) const { free(p); } }; typedef std::unique_ptr<keymaster0_device_t> Unique_keymaster_device_t; /** * Many OpenSSL APIs take ownership of an argument on success but * don't free the argument on failure. This means we need to tell our * scoped pointers when we've transferred ownership, without * triggering a warning by not using the result of release(). */ template <typename T, typename Delete_T> inline void release_because_ownership_transferred(std::unique_ptr<T, Delete_T>& p) { T* val __attribute__((unused)) = p.release(); } /* * Checks this thread's OpenSSL error queue and logs if * necessary. */ static void logOpenSSLError(const char* location) { int error = ERR_get_error(); if (error != 0) { char message[256]; ERR_error_string_n(error, message, sizeof(message)); ALOGE("OpenSSL error in %s %d: %s", location, error, message); } ERR_clear_error(); ERR_remove_thread_state(NULL); } static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlobLength) { /* * Find the length of each size. Public key is not needed anymore * but must be kept for alignment purposes. */ int publicLen = 0; int privateLen = i2d_PrivateKey(pkey, NULL); if (privateLen <= 0) { ALOGE("private key size was too big"); return -1; } /* int type + int size + private key data + int size + public key data */ *keyBlobLength = get_softkey_header_size() + sizeof(type) + sizeof(publicLen) + privateLen + sizeof(privateLen) + publicLen; // derData will be returned to the caller, so allocate it with malloc. std::unique_ptr<unsigned char, Malloc_Free> derData( static_cast<unsigned char*>(malloc(*keyBlobLength))); if (derData.get() == NULL) { ALOGE("could not allocate memory for key blob"); return -1; } unsigned char* p = derData.get(); /* Write the magic value for software keys. */ p = add_softkey_header(p, *keyBlobLength); /* Write key type to allocated buffer */ for (int i = sizeof(type) - 1; i >= 0; i--) { *p++ = (type >> (8 * i)) & 0xFF; } /* Write public key to allocated buffer */ for (int i = sizeof(publicLen) - 1; i >= 0; i--) { *p++ = (publicLen >> (8 * i)) & 0xFF; } /* Write private key to allocated buffer */ for (int i = sizeof(privateLen) - 1; i >= 0; i--) { *p++ = (privateLen >> (8 * i)) & 0xFF; } if (i2d_PrivateKey(pkey, &p) != privateLen) { logOpenSSLError("wrap_key"); return -1; } *keyBlob = derData.release(); return 0; } static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) { long publicLen = 0; long privateLen = 0; const uint8_t* p = keyBlob; const uint8_t* const end = keyBlob + keyBlobLength; if (keyBlob == NULL) { ALOGE("supplied key blob was NULL"); return NULL; } int type = 0; if (keyBlobLength < (get_softkey_header_size() + sizeof(type) + sizeof(publicLen) + 1 + sizeof(privateLen) + 1)) { ALOGE("key blob appears to be truncated"); return NULL; } if (!is_softkey(p, keyBlobLength)) { ALOGE("cannot read key; it was not made by this keymaster"); return NULL; } p += get_softkey_header_size(); for (size_t i = 0; i < sizeof(type); i++) { type = (type << 8) | *p++; } for (size_t i = 0; i < sizeof(type); i++) { publicLen = (publicLen << 8) | *p++; } if (p + publicLen > end) { ALOGE("public key length encoding error: size=%ld, end=%td", publicLen, end - p); return NULL; } p += publicLen; if (end - p < 2) { ALOGE("private key truncated"); return NULL; } for (size_t i = 0; i < sizeof(type); i++) { privateLen = (privateLen << 8) | *p++; } if (p + privateLen > end) { ALOGE("private key length encoding error: size=%ld, end=%td", privateLen, end - p); return NULL; } Unique_EVP_PKEY pkey(d2i_PrivateKey(type, nullptr, &p, privateLen)); if (pkey.get() == NULL) { logOpenSSLError("unwrap_key"); return NULL; } return pkey.release(); } static int generate_dsa_keypair(EVP_PKEY* pkey, const keymaster_dsa_keygen_params_t* dsa_params) { if (dsa_params->key_size < 512) { ALOGI("Requested DSA key size is too small (<512)"); return -1; } Unique_DSA dsa(DSA_new()); if (dsa_params->generator_len == 0 || dsa_params->prime_p_len == 0 || dsa_params->prime_q_len == 0 || dsa_params->generator == NULL || dsa_params->prime_p == NULL || dsa_params->prime_q == NULL) { if (DSA_generate_parameters_ex(dsa.get(), dsa_params->key_size, NULL, 0, NULL, NULL, NULL) != 1) { logOpenSSLError("generate_dsa_keypair"); return -1; } } else { dsa->g = BN_bin2bn(dsa_params->generator, dsa_params->generator_len, NULL); if (dsa->g == NULL) { logOpenSSLError("generate_dsa_keypair"); return -1; } dsa->p = BN_bin2bn(dsa_params->prime_p, dsa_params->prime_p_len, NULL); if (dsa->p == NULL) { logOpenSSLError("generate_dsa_keypair"); return -1; } dsa->q = BN_bin2bn(dsa_params->prime_q, dsa_params->prime_q_len, NULL); if (dsa->q == NULL) { logOpenSSLError("generate_dsa_keypair"); return -1; } } if (DSA_generate_key(dsa.get()) != 1) { logOpenSSLError("generate_dsa_keypair"); return -1; } if (EVP_PKEY_assign_DSA(pkey, dsa.get()) == 0) { logOpenSSLError("generate_dsa_keypair"); return -1; } release_because_ownership_transferred(dsa); return 0; } static int generate_ec_keypair(EVP_PKEY* pkey, const keymaster_ec_keygen_params_t* ec_params) { Unique_EC_GROUP group; switch (ec_params->field_size) { case 224: group.reset(EC_GROUP_new_by_curve_name(NID_secp224r1)); break; case 256: group.reset(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); break; case 384: group.reset(EC_GROUP_new_by_curve_name(NID_secp384r1)); break; case 521: group.reset(EC_GROUP_new_by_curve_name(NID_secp521r1)); break; default: break; } if (group.get() == NULL) { logOpenSSLError("generate_ec_keypair"); return -1; } #if !defined(OPENSSL_IS_BORINGSSL) EC_GROUP_set_point_conversion_form(group.get(), POINT_CONVERSION_UNCOMPRESSED); EC_GROUP_set_asn1_flag(group.get(), OPENSSL_EC_NAMED_CURVE); #endif /* initialize EC key */ Unique_EC_KEY eckey(EC_KEY_new()); if (eckey.get() == NULL) { logOpenSSLError("generate_ec_keypair"); return -1; } if (EC_KEY_set_group(eckey.get(), group.get()) != 1) { logOpenSSLError("generate_ec_keypair"); return -1; } if (EC_KEY_generate_key(eckey.get()) != 1 || EC_KEY_check_key(eckey.get()) < 0) { logOpenSSLError("generate_ec_keypair"); return -1; } if (EVP_PKEY_assign_EC_KEY(pkey, eckey.get()) == 0) { logOpenSSLError("generate_ec_keypair"); return -1; } release_because_ownership_transferred(eckey); return 0; } static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) { Unique_BIGNUM bn(BN_new()); if (bn.get() == NULL) { logOpenSSLError("generate_rsa_keypair"); return -1; } if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) { logOpenSSLError("generate_rsa_keypair"); return -1; } /* initialize RSA */ Unique_RSA rsa(RSA_new()); if (rsa.get() == NULL) { logOpenSSLError("generate_rsa_keypair"); return -1; } if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) || RSA_check_key(rsa.get()) < 0) { logOpenSSLError("generate_rsa_keypair"); return -1; } if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) { logOpenSSLError("generate_rsa_keypair"); return -1; } release_because_ownership_transferred(rsa); return 0; } __attribute__((visibility("default"))) int linaro_km_generate_keypair( const keymaster0_device_t*, const keymaster_keypair_t key_type, const void* key_params, uint8_t** keyBlob, size_t* keyBlobLength) { Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { logOpenSSLError("linaro_km_generate_keypair"); return -1; } if (key_params == NULL) { ALOGW("key_params == null"); return -1; } else if (key_type == TYPE_DSA) { const keymaster_dsa_keygen_params_t* dsa_params = (const keymaster_dsa_keygen_params_t*)key_params; generate_dsa_keypair(pkey.get(), dsa_params); } else if (key_type == TYPE_EC) { const keymaster_ec_keygen_params_t* ec_params = (const keymaster_ec_keygen_params_t*)key_params; generate_ec_keypair(pkey.get(), ec_params); } else if (key_type == TYPE_RSA) { const keymaster_rsa_keygen_params_t* rsa_params = (const keymaster_rsa_keygen_params_t*)key_params; generate_rsa_keypair(pkey.get(), rsa_params); } else { ALOGW("Unsupported key type %d", key_type); return -1; } if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), keyBlob, keyBlobLength)) { return -1; } return 0; } __attribute__((visibility("default"))) int linaro_km_import_keypair(const keymaster0_device_t*, const uint8_t* key, const size_t key_length, uint8_t** key_blob, size_t* key_blob_length) { if (key == NULL) { ALOGW("input key == NULL"); return -1; } else if (key_blob == NULL || key_blob_length == NULL) { ALOGW("output key blob or length == NULL"); return -1; } Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length)); if (pkcs8.get() == NULL) { logOpenSSLError("linaro_km_import_keypair"); return -1; } /* assign to EVP */ Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get())); if (pkey.get() == NULL) { logOpenSSLError("linaro_km_import_keypair"); return -1; } if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), key_blob, key_blob_length)) { return -1; } return 0; } __attribute__((visibility("default"))) int linaro_km_get_keypair_public(const keymaster0_device_t*, const uint8_t* key_blob, const size_t key_blob_length, uint8_t** x509_data, size_t* x509_data_length) { if (x509_data == NULL || x509_data_length == NULL) { ALOGW("output public key buffer == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(key_blob, key_blob_length)); if (pkey.get() == NULL) { return -1; } int len = i2d_PUBKEY(pkey.get(), NULL); if (len <= 0) { logOpenSSLError("linaro_km_get_keypair_public"); return -1; } std::unique_ptr<uint8_t, Malloc_Free> key(static_cast<uint8_t*>(malloc(len))); if (key.get() == NULL) { ALOGE("Could not allocate memory for public key data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get()); if (i2d_PUBKEY(pkey.get(), &tmp) != len) { logOpenSSLError("linaro_km_get_keypair_public"); return -1; } ALOGV("Length of x509 data is %d", len); *x509_data_length = len; *x509_data = key.release(); return 0; } static int sign_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey)); if (dsa.get() == NULL) { logOpenSSLError("linaro_km_sign_dsa"); return -1; } unsigned int dsaSize = DSA_size(dsa.get()); std::unique_ptr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dsaSize))); if (signedDataPtr.get() == NULL) { logOpenSSLError("linaro_km_sign_dsa"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); if (DSA_sign(0, data, dataLength, tmp, &dsaSize, dsa.get()) <= 0) { logOpenSSLError("linaro_km_sign_dsa"); return -1; } *signedDataLength = dsaSize; *signedData = signedDataPtr.release(); return 0; } static int sign_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey)); if (eckey.get() == NULL) { logOpenSSLError("linaro_km_sign_ec"); return -1; } unsigned int ecdsaSize = ECDSA_size(eckey.get()); std::unique_ptr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(ecdsaSize))); if (signedDataPtr.get() == NULL) { logOpenSSLError("linaro_km_sign_ec"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); if (ECDSA_sign(0, data, dataLength, tmp, &ecdsaSize, eckey.get()) <= 0) { logOpenSSLError("linaro_km_sign_ec"); return -1; } *signedDataLength = ecdsaSize; *signedData = signedDataPtr.release(); return 0; } static int sign_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGW("Cannot handle padding type %d", sign_params->padding_type); return -1; } Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (rsa.get() == NULL) { logOpenSSLError("linaro_km_sign_rsa"); return -1; } std::unique_ptr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength))); if (signedDataPtr.get() == NULL) { logOpenSSLError("linaro_km_sign_rsa"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) { logOpenSSLError("linaro_km_sign_rsa"); return -1; } *signedDataLength = dataLength; *signedData = signedDataPtr.release(); return 0; } __attribute__((visibility("default"))) int linaro_km_sign_data( const keymaster0_device_t*, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (data == NULL) { ALOGW("input data to sign == NULL"); return -1; } else if (signedData == NULL || signedDataLength == NULL) { ALOGW("output signature buffer == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); if (pkey.get() == NULL) { return -1; } int type = EVP_PKEY_type(pkey->type); if (type == EVP_PKEY_DSA) { const keymaster_dsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_dsa_sign_params_t*>(params); return sign_dsa(pkey.get(), const_cast<keymaster_dsa_sign_params_t*>(sign_params), data, dataLength, signedData, signedDataLength); } else if (type == EVP_PKEY_EC) { const keymaster_ec_sign_params_t* sign_params = reinterpret_cast<const keymaster_ec_sign_params_t*>(params); return sign_ec(pkey.get(), const_cast<keymaster_ec_sign_params_t*>(sign_params), data, dataLength, signedData, signedDataLength); } else if (type == EVP_PKEY_RSA) { const keymaster_rsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_rsa_sign_params_t*>(params); return sign_rsa(pkey.get(), const_cast<keymaster_rsa_sign_params_t*>(sign_params), data, dataLength, signedData, signedDataLength); } else { ALOGW("Unsupported key type"); return -1; } } static int verify_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey)); if (dsa.get() == NULL) { logOpenSSLError("linaro_km_verify_dsa"); return -1; } if (DSA_verify(0, signedData, signedDataLength, signature, signatureLength, dsa.get()) <= 0) { logOpenSSLError("linaro_km_verify_dsa"); return -1; } return 0; } static int verify_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey)); if (eckey.get() == NULL) { logOpenSSLError("linaro_km_verify_ec"); return -1; } if (ECDSA_verify(0, signedData, signedDataLength, signature, signatureLength, eckey.get()) <= 0) { logOpenSSLError("linaro_km_verify_ec"); return -1; } return 0; } static int verify_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGW("Cannot handle padding type %d", sign_params->padding_type); return -1; } else if (signatureLength != signedDataLength) { ALOGW("signed data length must be signature length"); return -1; } Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (rsa.get() == NULL) { logOpenSSLError("linaro_km_verify_data"); return -1; } std::unique_ptr<uint8_t[]> dataPtr(new uint8_t[signedDataLength]); if (dataPtr.get() == NULL) { logOpenSSLError("linaro_km_verify_data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get()); if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) { logOpenSSLError("linaro_km_verify_data"); return -1; } int result = 0; for (size_t i = 0; i < signedDataLength; i++) { result |= tmp[i] ^ signedData[i]; } return result == 0 ? 0 : -1; } __attribute__((visibility("default"))) int linaro_km_verify_data( const keymaster0_device_t*, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (signedData == NULL || signature == NULL) { ALOGW("data or signature buffers == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); if (pkey.get() == NULL) { return -1; } int type = EVP_PKEY_type(pkey->type); if (type == EVP_PKEY_DSA) { const keymaster_dsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_dsa_sign_params_t*>(params); return verify_dsa(pkey.get(), const_cast<keymaster_dsa_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else if (type == EVP_PKEY_RSA) { const keymaster_rsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_rsa_sign_params_t*>(params); return verify_rsa(pkey.get(), const_cast<keymaster_rsa_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else if (type == EVP_PKEY_EC) { const keymaster_ec_sign_params_t* sign_params = reinterpret_cast<const keymaster_ec_sign_params_t*>(params); return verify_ec(pkey.get(), const_cast<keymaster_ec_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else { ALOGW("Unsupported key type %d", type); return -1; } } /* Close an opened OpenSSL instance */ static int linaro_km_close(hw_device_t* dev) { delete dev; return 0; } /* * Generic device handling */ __attribute__((visibility("default"))) int linaro_km_open(const hw_module_t* module, const char* name, hw_device_t** device) { if (strcmp(name, KEYSTORE_KEYMASTER) != 0) return -EINVAL; Unique_keymaster_device_t dev(new keymaster0_device_t); if (dev.get() == NULL) return -ENOMEM; dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 1; dev->common.module = (struct hw_module_t*)module; dev->common.close = linaro_km_close; dev->flags = KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_DSA | KEYMASTER_SUPPORTS_EC; dev->generate_keypair = linaro_km_generate_keypair; dev->import_keypair = linaro_km_import_keypair; dev->get_keypair_public = linaro_km_get_keypair_public; dev->delete_keypair = NULL; dev->delete_all = NULL; dev->sign_data = linaro_km_sign_data; dev->verify_data = linaro_km_verify_data; ERR_load_crypto_strings(); ERR_load_BIO_strings(); *device = reinterpret_cast<hw_device_t*>(dev.release()); return 0; } static struct hw_module_methods_t keystore_module_methods = { .open = linaro_km_open, }; struct keystore_module linaro_keymaster_module __attribute__((visibility("default"))) = { .common = { .tag = HARDWARE_MODULE_TAG, .module_api_version = KEYMASTER_MODULE_API_VERSION_0_2, .hal_api_version = HARDWARE_HAL_API_VERSION, .id = KEYSTORE_HARDWARE_MODULE_ID, .name = "Keymaster 0.2 Linaro HAL", .author = "The Android Open Source Project", .methods = &keystore_module_methods, .dso = 0, .reserved = {}, }, };
[ "victor.chong@linaro.org" ]
victor.chong@linaro.org
ef43e3e5a2aafb019a658fc6b8272d7ba4e5115f
6161b649af64dd01c041ef47e809eb0ea2c6e6fd
/libs/ardour/control_protocol_manager.cc
1e793bb71b8fd1e223989cb3a9c473d37d8cf72d
[]
no_license
taybin/Gusto
a6df309075f2ed5fffa5404ce756c8282cc6aa87
567554470a8de13a9984c895b83f3ac045f587ab
refs/heads/master
2016-08-05T13:52:42.667291
2010-07-06T03:11:34
2010-07-06T03:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,967
cc
/* Copyright (C) 2000-2007 Paul Davis This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <dlfcn.h> #include "pbd/compose.h" #include "pbd/file_utils.h" #include "pbd/error.h" #include "control_protocol/control_protocol.h" #include "ardour/session.h" #include "ardour/control_protocol_manager.h" #include "ardour/control_protocol_search_path.h" using namespace ARDOUR; using namespace std; using namespace PBD; #include "i18n.h" ControlProtocolManager* ControlProtocolManager::_instance = 0; const string ControlProtocolManager::state_node_name = X_("ControlProtocols"); ControlProtocolManager::ControlProtocolManager () { } ControlProtocolManager::~ControlProtocolManager() { Glib::Mutex::Lock lm (protocols_lock); for (list<ControlProtocol*>::iterator i = control_protocols.begin(); i != control_protocols.end(); ++i) { delete (*i); } control_protocols.clear (); for (list<ControlProtocolInfo*>::iterator p = control_protocol_info.begin(); p != control_protocol_info.end(); ++p) { delete (*p); } control_protocol_info.clear(); } void ControlProtocolManager::set_session (Session* s) { SessionHandlePtr::set_session (s); if (_session) { Glib::Mutex::Lock lm (protocols_lock); for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) { if ((*i)->requested || (*i)->mandatory) { instantiate (**i); (*i)->requested = false; if ((*i)->protocol && (*i)->state) { (*i)->protocol->set_state (*(*i)->state, Stateful::loading_state_version); } } } } } void ControlProtocolManager::session_going_away() { SessionHandlePtr::session_going_away (); { Glib::Mutex::Lock lm (protocols_lock); for (list<ControlProtocol*>::iterator p = control_protocols.begin(); p != control_protocols.end(); ++p) { delete *p; } control_protocols.clear (); for (list<ControlProtocolInfo*>::iterator p = control_protocol_info.begin(); p != control_protocol_info.end(); ++p) { // mark existing protocols as requested // otherwise the ControlProtocol instances are not recreated in set_session if ((*p)->protocol) { (*p)->requested = true; (*p)->protocol = 0; } } } } ControlProtocol* ControlProtocolManager::instantiate (ControlProtocolInfo& cpi) { /* CALLER MUST HOLD LOCK */ if (_session == 0) { return 0; } cpi.descriptor = get_descriptor (cpi.path); if (cpi.descriptor == 0) { error << string_compose (_("control protocol name \"%1\" has no descriptor"), cpi.name) << endmsg; return 0; } if ((cpi.protocol = cpi.descriptor->initialize (cpi.descriptor, _session)) == 0) { error << string_compose (_("control protocol name \"%1\" could not be initialized"), cpi.name) << endmsg; return 0; } control_protocols.push_back (cpi.protocol); return cpi.protocol; } int ControlProtocolManager::teardown (ControlProtocolInfo& cpi) { if (!cpi.protocol) { return 0; } if (!cpi.descriptor) { return 0; } if (cpi.mandatory) { return 0; } cpi.descriptor->destroy (cpi.descriptor, cpi.protocol); { Glib::Mutex::Lock lm (protocols_lock); list<ControlProtocol*>::iterator p = find (control_protocols.begin(), control_protocols.end(), cpi.protocol); if (p != control_protocols.end()) { control_protocols.erase (p); } else { cerr << "Programming error: ControlProtocolManager::teardown() called for " << cpi.name << ", but it was not found in control_protocols" << endl; } } cpi.protocol = 0; dlclose (cpi.descriptor->module); return 0; } void ControlProtocolManager::load_mandatory_protocols () { if (_session == 0) { return; } Glib::Mutex::Lock lm (protocols_lock); for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) { if ((*i)->mandatory && ((*i)->protocol == 0)) { info << string_compose (_("Instantiating mandatory control protocol %1"), (*i)->name) << endmsg; instantiate (**i); } } } void ControlProtocolManager::discover_control_protocols () { vector<sys::path> cp_modules; Glib::PatternSpec so_extension_pattern("*.so"); Glib::PatternSpec dylib_extension_pattern("*.dylib"); find_matching_files_in_search_path (control_protocol_search_path (), so_extension_pattern, cp_modules); find_matching_files_in_search_path (control_protocol_search_path (), dylib_extension_pattern, cp_modules); info << string_compose (_("looking for control protocols in %1"), control_protocol_search_path().to_string()) << endmsg; for (vector<sys::path>::iterator i = cp_modules.begin(); i != cp_modules.end(); ++i) { control_protocol_discover ((*i).to_string()); } } int ControlProtocolManager::control_protocol_discover (string path) { ControlProtocolDescriptor* descriptor; if ((descriptor = get_descriptor (path)) != 0) { ControlProtocolInfo* cpi = new ControlProtocolInfo (); if (!descriptor->probe (descriptor)) { info << string_compose (_("Control protocol %1 not usable"), descriptor->name) << endmsg; } else { cpi->descriptor = descriptor; cpi->name = descriptor->name; cpi->path = path; cpi->protocol = 0; cpi->requested = false; cpi->mandatory = descriptor->mandatory; cpi->supports_feedback = descriptor->supports_feedback; cpi->state = 0; control_protocol_info.push_back (cpi); info << string_compose(_("Control surface protocol discovered: \"%1\""), cpi->name) << endmsg; } dlclose (descriptor->module); } return 0; } ControlProtocolDescriptor* ControlProtocolManager::get_descriptor (string path) { void *module; ControlProtocolDescriptor *descriptor = 0; ControlProtocolDescriptor* (*dfunc)(void); const char *errstr; if ((module = dlopen (path.c_str(), RTLD_NOW)) == 0) { error << string_compose(_("ControlProtocolManager: cannot load module \"%1\" (%2)"), path, dlerror()) << endmsg; return 0; } dfunc = (ControlProtocolDescriptor* (*)(void)) dlsym (module, "protocol_descriptor"); if ((errstr = dlerror()) != 0) { error << string_compose(_("ControlProtocolManager: module \"%1\" has no descriptor function."), path) << endmsg; error << errstr << endmsg; dlclose (module); return 0; } descriptor = dfunc(); if (descriptor) { descriptor->module = module; } else { dlclose (module); } return descriptor; } void ControlProtocolManager::foreach_known_protocol (boost::function<void(const ControlProtocolInfo*)> method) { for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) { method (*i); } } ControlProtocolInfo* ControlProtocolManager::cpi_by_name (string name) { for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) { if (name == (*i)->name) { return *i; } } return 0; } int ControlProtocolManager::set_state (const XMLNode& node, int /*version*/) { XMLNodeList clist; XMLNodeConstIterator citer; XMLProperty* prop; Glib::Mutex::Lock lm (protocols_lock); clist = node.children(); for (citer = clist.begin(); citer != clist.end(); ++citer) { if ((*citer)->name() == X_("Protocol")) { prop = (*citer)->property (X_("active")); if (prop && string_is_affirmative (prop->value())) { if ((prop = (*citer)->property (X_("name"))) != 0) { ControlProtocolInfo* cpi = cpi_by_name (prop->value()); if (cpi) { if (!(*citer)->children().empty()) { cpi->state = (*citer)->children().front (); } else { cpi->state = 0; } if (_session) { instantiate (*cpi); } else { cpi->requested = true; } } } } } } return 0; } XMLNode& ControlProtocolManager::get_state (void) { XMLNode* root = new XMLNode (state_node_name); Glib::Mutex::Lock lm (protocols_lock); for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) { XMLNode * child; if ((*i)->protocol) { child = &((*i)->protocol->get_state()); child->add_property (X_("active"), "yes"); // should we update (*i)->state here? probably. root->add_child_nocopy (*child); } else if ((*i)->state) { // keep ownership clear root->add_child_copy (*(*i)->state); } else { child = new XMLNode (X_("Protocol")); child->add_property (X_("name"), (*i)->name); child->add_property (X_("active"), "no"); root->add_child_nocopy (*child); } } return *root; } void ControlProtocolManager::set_protocol_states (const XMLNode& node) { XMLNodeList nlist; XMLNodeConstIterator niter; XMLProperty* prop; nlist = node.children(); for (niter = nlist.begin(); niter != nlist.end(); ++niter) { XMLNode* child = (*niter); if ((prop = child->property ("name")) == 0) { error << _("control protocol XML node has no name property. Ignored.") << endmsg; continue; } ControlProtocolInfo* cpi = cpi_by_name (prop->value()); if (!cpi) { warning << string_compose (_("control protocol \"%1\" is not known. Ignored"), prop->value()) << endmsg; continue; } /* copy the node so that ownership is clear */ cpi->state = new XMLNode (*child); } } ControlProtocolManager& ControlProtocolManager::instance () { if (_instance == 0) { _instance = new ControlProtocolManager (); } return *_instance; }
[ "taybin@penguinsounds.org" ]
taybin@penguinsounds.org
61327862cd4ef192f2b9a094f95416d18552c65e
ae15f4bd822bd5a3bd854acda2e4641bdcd26cc9
/Lab 2/example-quad/src/testApp.cpp
8978259a98ca584805ce86e5d05b8420674d5520
[]
no_license
eltaiguer/tdi_grupo3
6889767db31f6128ccba84578cd0a041c1529ea2
789940751e66e00056b3a37eb674478b01325294
refs/heads/master
2021-01-25T07:34:02.695720
2014-11-12T21:25:08
2014-11-12T21:25:08
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
10,308
cpp
#include "testApp.h" using namespace ofxCv; using namespace cv; //-------------------------------------------------------------- void testApp::setup(){ // listen on the given port cout << "listening for osc messages on port " << PORT << "\n"; receiver.setup(PORT); ofSetVerticalSync(true); // this uses depth information for occlusion // rather than always drawing things on top of each other glEnable(GL_DEPTH_TEST); // ofBox uses texture coordinates from 0-1, so you can load whatever // sized images you want and still use them to texture your box // but we have to explicitly normalize our tex coords here ofEnableNormalizedTexCoords(); light1.enable(); light2.enable(); light3.enable(); light4.enable(); light5.enable(); light6.enable(); //Quad de la cara de frente, front.addVertex(ofVec3f(-100,200,100));//4 front.addVertex(ofVec3f(100,200,100));//5 front.addVertex(ofVec3f(100,200,-100));//6 front.addVertex(ofVec3f(-100,200,-100));//7 //Agrego la textura front.addTexCoord(ofVec2f(0,0)); front.addTexCoord(ofVec2f(0,1)); front.addTexCoord(ofVec2f(1,1)); front.addTexCoord(ofVec2f(1,0)); derecha.addVertex( ofPoint(-100,200,-100)); //7 derecha.addVertex( ofPoint(100,200,-100)); //6 derecha.addVertex( ofPoint(100,0,-100)); //2 derecha.addVertex( ofPoint(-100,0,-100)); //3 derecha.addTexCoord(ofVec2f(0,0)); derecha.addTexCoord(ofVec2f(0,1)); derecha.addTexCoord(ofVec2f(1,1)); derecha.addTexCoord(ofVec2f(1,0)); izquierda.addVertex( ofPoint(-100,0,100)); //0 izquierda.addVertex( ofPoint(100,0,100)); //1 izquierda.addVertex( ofPoint(100,200,100)); //5 izquierda.addVertex( ofPoint(-100,200,100)); //4 izquierda.addTexCoord(ofVec2f(0,0)); izquierda.addTexCoord(ofVec2f(0,1)); izquierda.addTexCoord(ofVec2f(1,1)); izquierda.addTexCoord(ofVec2f(1,0)); top.addVertex( ofPoint(-100,200,100)); //4 top.addVertex( ofPoint(-100,200,-100)); //7 top.addVertex( ofPoint(-100,0,-100)); //3 top.addVertex( ofPoint(-100,0,100)); //0 top.addTexCoord(ofVec2f(0,0)); top.addTexCoord(ofVec2f(0,1)); top.addTexCoord(ofVec2f(1,1)); top.addTexCoord(ofVec2f(1,0)); bottom.addVertex( ofPoint(-100,0,100)); //0 bottom.addVertex( ofPoint(100,0,100)); //1 bottom.addVertex( ofPoint(100,0,-100)); //2 bottom.addVertex( ofPoint(-100,0,-100)); //3 bottom.addTexCoord(ofVec2f(0,0)); bottom.addTexCoord(ofVec2f(0,1)); bottom.addTexCoord(ofVec2f(1,1)); bottom.addTexCoord(ofVec2f(1,0)); back.addVertex( ofPoint(100,200,100)); //5 back.addVertex( ofPoint(100,200,-100)); //6 back.addVertex( ofPoint(100,0,-100)); //2 back.addVertex( ofPoint(100,0,100)); //1 back.addTexCoord(ofVec2f(0,0)); back.addTexCoord(ofVec2f(0,1)); back.addTexCoord(ofVec2f(1,1)); back.addTexCoord(ofVec2f(1,0)); //------------------------------------------ //Dibujo la cara de frente en el quad front front.addTriangle( 0, 1, 2 ); front.addTriangle( 2, 3 ,0 ); izquierda.addTriangle(0, 1, 2); izquierda.addTriangle(2, 3, 0); derecha.addTriangle( 0, 1, 2 ); derecha.addTriangle( 2, 3, 0 ); top.addTriangle( 0, 1, 2 ); top.addTriangle( 2, 3, 0 ); bottom.addTriangle( 0, 1, 2 ); bottom.addTriangle( 2, 3, 0 ); back.addTriangle( 0, 1, 2 ); back.addTriangle( 2, 3, 0 ); // Masculino img_front_comun_mas.loadImage("mas_comun.png"); img_front_boca_abierta_mas.loadImage("mas_boca_abierta.png"); img_front_boca_abierta_cejas_mas.loadImage("mas_boca_abierta_cejas.png"); img_front_boca_fruncida_mas.loadImage("mas_boca_fruncida.png"); img_front_cejas_arriba_mas.loadImage("mas_cejas_arriba.png"); img_front_sonrisa_mas.loadImage("mas_sonrisa.png"); img_izquierda_mas.loadImage("mas_izquierda.png"); img_derecha_mas.loadImage("mas_derecha.png"); img_background_mas.loadImage("mas_superior.png"); // Femenino img_front_comun_fem.loadImage("fem_comun.png"); img_front_boca_abierta_fem.loadImage("fem_boca_abierta.png"); img_front_boca_abierta_cejas_fem.loadImage("fem_boca_abierta_cejas.png"); img_front_boca_fruncida_fem.loadImage("fem_boca_fruncida.png"); img_front_cejas_arriba_fem.loadImage("fem_cejas_arriba.png"); img_front_sonrisa_fem.loadImage("fem_sonrisa.png"); img_izquierda_fem.loadImage("fem_izquierda.png"); img_derecha_fem.loadImage("fem_derecha.png"); img_background_fem.loadImage("fem_superior.png"); //EXPRESIONS cam.initGrabber(640, 480); tracker.setup(); tracker.setRescale(.1); classifier.load("expressions"); genero = true; exp = 4; // cara comun currentPitchAngle=0; currentYawAngle=0; currentRollAngle=0; } //-------------------------------------------------------------- void testApp::update(){ cam.update(); if(cam.isFrameNew()) { if(tracker.update(toCv(cam))) { exp = classifier.classify(tracker); printf("exp: %d\n",exp); } } light1.setPosition(200, 0, 0); light2.setPosition(-200, 0, 0); light3.setPosition(0, 200, 0); light4.setPosition(0, -200, 0); light5.setPosition(0, 0, 200); light6.setPosition(0, 0, -200); // hide old messages for(int i = 0; i < NUM_MSG_STRINGS; i++){ if(timers[i] < ofGetElapsedTimef()){ msg_strings[i] = ""; } } // check for waiting messages while(receiver.hasWaitingMessages()){ // get the next message ofxOscMessage m; receiver.getNextMessage(&m); if (m.getAddress()=="/head/orientationAngles/"){ printf("PITCH %f\n",m.getArgAsFloat(0)); printf("YAW %f\n",m.getArgAsFloat(1)); printf("ROLL %f\n",m.getArgAsFloat(2)); pitchAngle=m.getArgAsFloat(0); yawAngle=m.getArgAsFloat(1); rollAngle=m.getArgAsFloat(2); /*if (abs(abs(currentYawAngle) - abs(yawAngle)) > DIFF){ */currentYawAngle=yawAngle; /* }*/ /*if ((abs(currentRollAngle - rollAngle)) > DIFF){ */currentRollAngle=rollAngle;/* } */ //if (abs(abs(currentPitchAngle) - abs(pitchAngle)) > DIFF){ currentPitchAngle=-pitchAngle; //} } } } //-------------------------------------------------------------- void testApp::draw(){ ofPushMatrix(); tracker.draw(); ofTranslate( ofGetWidth()/2, ofGetHeight()/2, 0 ); ofRotateX(90); ofRotateY(90); float time = ofGetElapsedTimef(); ofRotate(currentPitchAngle, 0 , 0, 1.5 ); ofRotate(currentRollAngle, 0 , 1, 0 ); ofRotate(currentYawAngle, 1.5, 0, 0 ); ofSetColor( 255, 255 ,255 ); //Dibujo la cara de frente dependiendo del género seleccionado y la expresión detectada if (exp == 0){ if (genero){ img_front_boca_abierta_mas.getTextureReference().bind(); front.draw(); img_front_boca_abierta_mas.unbind(); } else { img_front_boca_abierta_fem.getTextureReference().bind(); front.draw(); img_front_boca_abierta_fem.unbind(); } } else if (exp == 1){ if (genero){ img_front_boca_abierta_cejas_mas.getTextureReference().bind(); front.draw(); img_front_boca_abierta_cejas_mas.unbind(); } else { img_front_boca_abierta_cejas_fem.getTextureReference().bind(); front.draw(); img_front_boca_abierta_cejas_fem.unbind(); } } else if (exp == 2){ if (genero){ img_front_boca_fruncida_mas.getTextureReference().bind(); front.draw(); img_front_boca_fruncida_mas.unbind(); } else { img_front_boca_fruncida_fem.getTextureReference().bind(); front.draw(); img_front_boca_fruncida_fem.unbind(); } } else if (exp == 3){ if (genero){ img_front_cejas_arriba_mas.getTextureReference().bind(); front.draw(); img_front_cejas_arriba_mas.unbind(); } else { img_front_cejas_arriba_fem.getTextureReference().bind(); front.draw(); img_front_cejas_arriba_fem.unbind(); } } else if (exp == 4){ if (genero){ img_front_comun_mas.getTextureReference().bind(); front.draw(); img_front_comun_mas.unbind(); } else { img_front_comun_fem.getTextureReference().bind(); front.draw(); img_front_comun_fem.unbind(); } } else if (exp == 5){ if (genero){ img_front_sonrisa_mas.getTextureReference().bind(); front.draw(); img_front_sonrisa_mas.unbind(); } else { img_front_sonrisa_fem.getTextureReference().bind(); front.draw(); img_front_sonrisa_fem.unbind(); } } // Dibujo el resto de la cabeza dependiendo del genero if (genero){ //Dibujo la cara izquierda img_izquierda_mas.getTextureReference().bind(); izquierda.draw(); img_izquierda_mas.unbind(); //Dibujo la cara derecha img_derecha_mas.getTextureReference().bind(); derecha.draw(); img_derecha_mas.unbind(); img_background_mas.getTextureReference().bind(); //Dibujo top top.draw(); //Dibujo bottom bottom.draw(); //Dibujo Back back.draw(); img_background_mas.unbind(); } else { //Dibujo la cara izquierda img_izquierda_fem.getTextureReference().bind(); izquierda.draw(); img_izquierda_fem.unbind(); //Dibujo la cara derecha img_derecha_fem.getTextureReference().bind(); derecha.draw(); img_derecha_fem.unbind(); img_background_fem.getTextureReference().bind(); //Dibujo top top.draw(); //Dibujo bottom bottom.draw(); //Dibujo Back back.draw(); img_background_fem.unbind(); } ofPopMatrix(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == 'c'){ genero = !genero; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
[ "jose.lvp@gmail.com" ]
jose.lvp@gmail.com
21511893d50359191a56c32832bcdac9ca4ee6bc
cee83e8f6585c20d4444ddc12492e42a6b3412d5
/dep/libopenmpt/soundlib/Load_med.cpp
f12b68f52dc6cd2b76d5c7bf99f2a114bccf1b4f
[ "BSD-3-Clause" ]
permissive
fgenesis/tyrsound
95b93afb71fa80a6d95b8c6771f29aea6333afd2
a032eaf8a3a8212a764bf6c801325e67ab02473e
refs/heads/master
2021-01-22T10:08:35.576908
2014-08-31T01:54:17
2014-08-31T01:54:17
10,146,874
4
0
null
2014-02-02T02:42:25
2013-05-18T20:40:23
C
UTF-8
C++
false
false
30,143
cpp
/* * Load_med.cpp * ------------ * Purpose: OctaMed MED module loader * Notes : (currently none) * Authors: Olivier Lapicque * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "Loaders.h" #include "../common/StringFixer.h" OPENMPT_NAMESPACE_BEGIN //#define MED_LOG #define MED_MAX_COMMENT_LENGTH 5*1024 //: Is 5 kB enough? // flags #define MMD_FLAG_FILTERON 0x1 #define MMD_FLAG_JUMPINGON 0x2 #define MMD_FLAG_JUMP8TH 0x4 #define MMD_FLAG_INSTRSATT 0x8 // instruments are attached (this is a module) #define MMD_FLAG_VOLHEX 0x10 #define MMD_FLAG_STSLIDE 0x20 // SoundTracker mode for slides #define MMD_FLAG_8CHANNEL 0x40 // OctaMED 8 channel song #define MMD_FLAG_SLOWHQ 0x80 // HQ slows playing speed (V2-V4 compatibility) // flags2 #define MMD_FLAG2_BMASK 0x1F #define MMD_FLAG2_BPM 0x20 #define MMD_FLAG2_MIX 0x80 // uses Mixing (V7+) // flags3: #define MMD_FLAG3_STEREO 0x1 // mixing in Stereo mode #define MMD_FLAG3_FREEPAN 0x2 // free panning #define MMD_FLAG3_GM 0x4 // module designed for GM/XG compatibility // generic MMD tags #define MMDTAG_END 0 #define MMDTAG_PTR 0x80000000 // data needs relocation #define MMDTAG_MUSTKNOW 0x40000000 // loader must fail if this isn't recognized #define MMDTAG_MUSTWARN 0x20000000 // loader must warn if this isn't recognized // ExpData tags // # of effect groups, including the global group (will // override settings in MMDSong struct), default = 1 #define MMDTAG_EXP_NUMFXGROUPS 1 #define MMDTAG_TRK_NAME (MMDTAG_PTR|1) // trackinfo tags #define MMDTAG_TRK_NAMELEN 2 // namelen includes zero term. #define MMDTAG_TRK_FXGROUP 3 // effectinfo tags #define MMDTAG_FX_ECHOTYPE 1 #define MMDTAG_FX_ECHOLEN 2 #define MMDTAG_FX_ECHODEPTH 3 #define MMDTAG_FX_STEREOSEP 4 #define MMDTAG_FX_GROUPNAME (MMDTAG_PTR|5) // the Global Effects group shouldn't have name saved! #define MMDTAG_FX_GRPNAMELEN 6 // namelen includes zero term. #ifdef NEEDS_PRAGMA_PACK #pragma pack(push, 1) #endif typedef struct PACKED tagMEDMODULEHEADER { DWORD id; // MMD1-MMD3 DWORD modlen; // Size of file DWORD song; // Position in file for this song WORD psecnum; WORD pseq; DWORD blockarr; // Position in file for blocks DWORD mmdflags; DWORD smplarr; // Position in file for samples DWORD reserved; DWORD expdata; // Absolute offset in file for ExpData (0 if not present) DWORD reserved2; WORD pstate; WORD pblock; WORD pline; WORD pseqnum; WORD actplayline; BYTE counter; BYTE extra_songs; // # of songs - 1 } MEDMODULEHEADER; STATIC_ASSERT(sizeof(MEDMODULEHEADER) == 52); typedef struct PACKED tagMMD0SAMPLE { WORD rep, replen; BYTE midich; BYTE midipreset; BYTE svol; signed char strans; } MMD0SAMPLE; STATIC_ASSERT(sizeof(MMD0SAMPLE) == 8); // Sample header is immediately followed by sample data... typedef struct PACKED tagMMDSAMPLEHEADER { DWORD length; // length of *one* *unpacked* channel in *bytes* WORD type; // if non-negative // bits 0-3 reserved for multi-octave instruments, not supported on the PC // 0x10: 16 bit (otherwise 8 bit) // 0x20: Stereo (otherwise mono) // 0x40: Uses DeltaCode // 0x80: Packed data // -1: Synth // -2: Hybrid // if type indicates packed data, these fields follow, otherwise we go right to the data WORD packtype; // Only 1 = ADPCM is supported WORD subtype; // Packing subtype // ADPCM subtype // 1: g723_40 // 2: g721 // 3: g723_24 BYTE commonflags; // flags common to all packtypes (none defined so far) BYTE packerflags; // flags for the specific packtype uint32 leftchlen; // packed length of left channel in bytes uint32 rightchlen; // packed length of right channel in bytes (ONLY PRESENT IN STEREO SAMPLES) BYTE SampleData[1]; // Sample Data } MMDSAMPLEHEADER; STATIC_ASSERT(sizeof(MMDSAMPLEHEADER) == 21); // MMD0/MMD1 song header typedef struct PACKED tagMMD0SONGHEADER { MMD0SAMPLE sample[63]; WORD numblocks; // # of blocks WORD songlen; // # of entries used in playseq BYTE playseq[256]; // Play sequence WORD deftempo; // BPM tempo signed char playtransp; // Play transpose BYTE flags; // 0x10: Hex Volumes | 0x20: ST/NT/PT Slides | 0x40: 8 Channels song BYTE flags2; // [b4-b0]+1: Tempo LPB, 0x20: tempo mode, 0x80: mix_conv=on BYTE tempo2; // tempo TPL BYTE trkvol[16]; // track volumes BYTE mastervol; // master volume BYTE numsamples; // # of samples (max=63) } MMD0SONGHEADER; STATIC_ASSERT(sizeof(MMD0SONGHEADER) == 788); // MMD2/MMD3 song header typedef struct PACKED tagMMD2SONGHEADER { MMD0SAMPLE sample[63]; WORD numblocks; // # of blocks WORD numsections; // # of sections DWORD playseqtable; // filepos of play sequence DWORD sectiontable; // filepos of sections table (WORD array) DWORD trackvols; // filepos of tracks volume (BYTE array) WORD numtracks; // # of tracks (max 64) WORD numpseqs; // # of play sequences DWORD trackpans; // filepos of tracks pan values (BYTE array) LONG flags3; // 0x1:stereo_mix, 0x2:free_panning, 0x4:GM/XG compatibility WORD voladj; // vol_adjust (set to 100 if 0) WORD channels; // # of channels (4 if =0) BYTE mix_echotype; // 1:normal,2:xecho BYTE mix_echodepth; // 1..6 WORD mix_echolen; // > 0 signed char mix_stereosep; // -4..4 BYTE pad0[223]; WORD deftempo; // BPM tempo signed char playtransp; // play transpose BYTE flags; // 0x1:filteron, 0x2:jumpingon, 0x4:jump8th, 0x8:instr_attached, 0x10:hex_vol, 0x20:PT_slides, 0x40:8ch_conv,0x80:hq slows playing speed BYTE flags2; // 0x80:mix_conv=on, [b4-b0]+1:tempo LPB, 0x20:tempo_mode BYTE tempo2; // tempo TPL BYTE pad1[16]; BYTE mastervol; // master volume BYTE numsamples; // # of samples (max 63) } MMD2SONGHEADER; STATIC_ASSERT(sizeof(MMD2SONGHEADER) == 788); // For MMD0 the note information is held in 3 bytes, byte0, byte1, byte2. For reference we // number the bits in each byte 0..7, where 0 is the low bit. // The note is held as bits 5..0 of byte0 // The instrument is encoded in 6 bits, bits 7 and 6 of byte0 and bits 7,6,5,4 of byte1 // The command number is bits 3,2,1,0 of byte1, command data is in byte2: // For command 0, byte2 represents the second data byte, otherwise byte2 // represents the first data byte. typedef struct PACKED tagMMD0BLOCK { BYTE numtracks; BYTE lines; // File value is 1 less than actual, so 0 -> 1 line } MMD0BLOCK; // BYTE data[lines+1][tracks][3]; STATIC_ASSERT(sizeof(MMD0BLOCK) == 2); // For MMD1,MMD2,MMD3 the note information is carried in 4 bytes, byte0, byte1, // byte2 and byte3 // The note is held as byte0 (values above 0x84 are ignored) // The instrument is held as byte1 // The command number is held as byte2, command data is in byte3 // For commands 0 and 0x19 byte3 represents the second data byte, // otherwise byte2 represents the first data byte. typedef struct PACKED tagMMD1BLOCK { WORD numtracks; // Number of tracks, may be > 64, but then that data is skipped. WORD lines; // Stored value is 1 less than actual, so 0 -> 1 line DWORD info; // Offset of BlockInfo (if 0, no block_info is present) } MMD1BLOCK; STATIC_ASSERT(sizeof(MMD1BLOCK) == 8); typedef struct PACKED tagMMD1BLOCKINFO { DWORD hlmask; // Unimplemented - ignore DWORD blockname; // file offset of block name DWORD blocknamelen; // length of block name (including term. 0) DWORD pagetable; // file offset of command page table DWORD cmdexttable; // file offset of command extension table DWORD reserved[4]; // future expansion } MMD1BLOCKINFO; STATIC_ASSERT(sizeof(MMD1BLOCKINFO) == 36); // A set of play sequences is stored as an array of uint32 files offsets // Each offset points to the play sequence itself. typedef struct PACKED tagMMD2PLAYSEQ { char name[32]; DWORD command_offs; // filepos of command table DWORD reserved; WORD length; WORD seq[512]; // skip if > 0x8000 } MMD2PLAYSEQ; STATIC_ASSERT(sizeof(MMD2PLAYSEQ) == 1066); // A command table contains commands that effect a particular play sequence // entry. The only commands read in are STOP or POSJUMP, all others are ignored // POSJUMP is presumed to have extra bytes containing a WORD for the position typedef struct PACKED tagMMDCOMMAND { WORD offset; // Offset within current sequence entry BYTE cmdnumber; // STOP (537) or POSJUMP (538) (others skipped) BYTE extra_count; BYTE extra_bytes[4];// [extra_count]; } MMDCOMMAND; // Last entry has offset == 0xFFFF, cmd_number == 0 and 0 extrabytes STATIC_ASSERT(sizeof(MMDCOMMAND) == 8); typedef struct PACKED tagMMD0EXP { DWORD nextmod; // File offset of next Hdr DWORD exp_smp; // Pointer to extra instrument data WORD s_ext_entries; // Number of extra instrument entries WORD s_ext_entrsz; // Size of extra instrument data DWORD annotxt; DWORD annolen; DWORD iinfo; // Instrument names WORD i_ext_entries; WORD i_ext_entrsz; DWORD jumpmask; DWORD rgbtable; BYTE channelsplit[4]; // Only used if 8ch_conv (extra channel for every nonzero entry) DWORD n_info; DWORD songname; // Song name DWORD songnamelen; DWORD dumps; DWORD mmdinfo; DWORD mmdrexx; DWORD mmdcmd3x; DWORD trackinfo_ofs; // ptr to song->numtracks ptrs to tag lists DWORD effectinfo_ofs; // ptr to group ptrs DWORD tag_end; } MMD0EXP; STATIC_ASSERT(sizeof(MMD0EXP) == 80); #ifdef NEEDS_PRAGMA_PACK #pragma pack(pop) #endif static void MedConvert(ModCommand *p, const MMD0SONGHEADER *pmsh) //--------------------------------------------------------------- { const BYTE bpmvals[9] = { 179,164,152,141,131,123,116,110,104}; ModCommand::COMMAND command = p->command; UINT param = p->param; switch(command) { case 0x00: if (param) command = CMD_ARPEGGIO; else command = 0; break; case 0x01: command = CMD_PORTAMENTOUP; break; case 0x02: command = CMD_PORTAMENTODOWN; break; case 0x03: command = CMD_TONEPORTAMENTO; break; case 0x04: command = CMD_VIBRATO; break; case 0x05: command = CMD_TONEPORTAVOL; break; case 0x06: command = CMD_VIBRATOVOL; break; case 0x07: command = CMD_TREMOLO; break; case 0x0A: if (param & 0xF0) param &= 0xF0; command = CMD_VOLUMESLIDE; if (!param) command = 0; break; case 0x0B: command = CMD_POSITIONJUMP; break; case 0x0C: command = CMD_VOLUME; if (pmsh->flags & MMD_FLAG_VOLHEX) { if (param < 0x80) { param = (param+1) / 2; } else command = 0; } else { if (param <= 0x99) { param = (param >> 4)*10+((param & 0x0F) % 10); if (param > 64) param = 64; } else command = 0; } break; case 0x09: command = static_cast<ModCommand::COMMAND>((param <= 0x20) ? CMD_SPEED : CMD_TEMPO); break; case 0x0D: if (param & 0xF0) param &= 0xF0; command = CMD_VOLUMESLIDE; if (!param) command = 0; break; case 0x0F: // Set Tempo / Special // F.00 = Pattern Break if (!param) command = CMD_PATTERNBREAK; else // F.01 - F.F0: Set tempo/speed if (param <= 0xF0) { if (pmsh->flags & MMD_FLAG_8CHANNEL) { param = (param > 10) ? 99 : bpmvals[param-1]; } else // F.01 - F.0A: Set Speed if (param <= 0x0A) { command = CMD_SPEED; } else // Old tempo if (!(pmsh->flags2 & MMD_FLAG2_BPM)) { param = Util::muldiv(param, 5*715909, 2*474326); } // F.0B - F.F0: Set Tempo (assumes LPB=4) if (param > 0x0A) { command = CMD_TEMPO; if (param < 0x21) param = 0x21; if (param > 240) param = 240; } } else switch(param) { // F.F1: Retrig 2x case 0xF1: command = CMD_MODCMDEX; param = 0x93; break; // F.F2: Note Delay 2x case 0xF2: command = CMD_MODCMDEX; param = 0xD3; break; // F.F3: Retrig 3x case 0xF3: command = CMD_MODCMDEX; param = 0x92; break; // F.F4: Note Delay 1/3 case 0xF4: command = CMD_MODCMDEX; param = 0xD2; break; // F.F5: Note Delay 2/3 case 0xF5: command = CMD_MODCMDEX; param = 0xD4; break; // F.F8: Filter Off case 0xF8: command = CMD_MODCMDEX; param = 0x00; break; // F.F9: Filter On case 0xF9: command = CMD_MODCMDEX; param = 0x01; break; // F.FD: Very fast tone-portamento case 0xFD: command = CMD_TONEPORTAMENTO; param = 0xFF; break; // F.FE: End Song case 0xFE: command = CMD_SPEED; param = 0; break; // F.FF: Note Cut case 0xFF: command = CMD_MODCMDEX; param = 0xC0; break; default: #ifdef MED_LOG Log("Unknown Fxx command: cmd=0x%02X param=0x%02X\n", command, param); #endif param = command = 0; } break; // 11.0x: Fine Slide Up case 0x11: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x10; break; // 12.0x: Fine Slide Down case 0x12: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x20; break; // 14.xx: Vibrato case 0x14: command = CMD_VIBRATO; break; // 15.xx: FineTune case 0x15: command = CMD_MODCMDEX; param &= 0x0F; param |= 0x50; break; // 16.xx: Pattern Loop case 0x16: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x60; break; // 18.xx: Note Cut case 0x18: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xC0; break; // 19.xx: Sample Offset case 0x19: command = CMD_OFFSET; break; // 1A.0x: Fine Volume Up case 0x1A: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xA0; break; // 1B.0x: Fine Volume Down case 0x1B: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xB0; break; // 1D.xx: Pattern Break case 0x1D: command = CMD_PATTERNBREAK; break; // 1E.0x: Pattern Delay case 0x1E: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xE0; break; // 1F.xy: Retrig case 0x1F: command = CMD_RETRIG; param &= 0x0F; break; // 2E.xx: set panning case 0x2E: command = CMD_MODCMDEX; param = ((param + 0x10) & 0xFF) >> 1; if (param > 0x0F) param = 0x0F; param |= 0x80; break; default: #ifdef MED_LOG // 0x2E ? Log("Unknown command: cmd=0x%02X param=0x%02X\n", command, param); #endif command = 0; param = 0; } p->command = command; p->param = static_cast<ModCommand::PARAM>(param); } bool CSoundFile::ReadMed(const uint8 *lpStream, const DWORD dwMemLength, ModLoadingFlags loadFlags) //------------------------------------------------------------------------------------------------- { const MEDMODULEHEADER *pmmh; const MMD0SONGHEADER *pmsh; const MMD2SONGHEADER *pmsh2; const MMD0EXP *pmex; DWORD dwBlockArr, dwSmplArr, dwExpData, wNumBlocks; DWORD *pdwTable; int8 version; UINT deftempo; int playtransp = 0; if ((!lpStream) || (dwMemLength < 0x200)) return false; pmmh = (MEDMODULEHEADER *)lpStream; if (((pmmh->id & 0x00FFFFFF) != 0x444D4D) || (!pmmh->song)) return false; // Check for 'MMDx' DWORD dwSong = BigEndian(pmmh->song); if ((dwSong >= dwMemLength) || (dwSong + sizeof(MMD0SONGHEADER) >= dwMemLength)) return false; version = (signed char)((pmmh->id >> 24) & 0xFF); if ((version < '0') || (version > '3')) return false; else if(loadFlags == onlyVerifyHeader) return true; #ifdef MED_LOG Log("\nLoading MMD%c module (flags=0x%02X)...\n", version, BigEndian(pmmh->mmdflags)); Log(" modlen = %d\n", BigEndian(pmmh->modlen)); Log(" song = 0x%08X\n", BigEndian(pmmh->song)); Log(" psecnum = %d\n", BigEndianW(pmmh->psecnum)); Log(" pseq = %d\n", BigEndianW(pmmh->pseq)); Log(" blockarr = 0x%08X\n", BigEndian(pmmh->blockarr)); Log(" mmdflags = 0x%08X\n", BigEndian(pmmh->mmdflags)); Log(" smplarr = 0x%08X\n", BigEndian(pmmh->smplarr)); Log(" reserved = 0x%08X\n", BigEndian(pmmh->reserved)); Log(" expdata = 0x%08X\n", BigEndian(pmmh->expdata)); Log(" reserved2= 0x%08X\n", BigEndian(pmmh->reserved2)); Log(" pstate = %d\n", BigEndianW(pmmh->pstate)); Log(" pblock = %d\n", BigEndianW(pmmh->pblock)); Log(" pline = %d\n", BigEndianW(pmmh->pline)); Log(" pseqnum = %d\n", BigEndianW(pmmh->pseqnum)); Log(" actplayline=%d\n", BigEndianW(pmmh->actplayline)); Log(" counter = %d\n", pmmh->counter); Log(" extra_songs = %d\n", pmmh->extra_songs); Log("\n"); #endif InitializeGlobals(); InitializeChannels(); // Setup channel pan positions and volume SetupMODPanning(true); madeWithTracker = mpt::String::Print("OctaMED (MMD%1)", std::string(1, version)); m_nType = MOD_TYPE_MED; m_nSamplePreAmp = 32; dwBlockArr = BigEndian(pmmh->blockarr); dwSmplArr = BigEndian(pmmh->smplarr); dwExpData = BigEndian(pmmh->expdata); if ((dwExpData) && (dwExpData < dwMemLength - sizeof(MMD0EXP))) pmex = (MMD0EXP *)(lpStream+dwExpData); else pmex = NULL; pmsh = (MMD0SONGHEADER *)(lpStream + dwSong); pmsh2 = (MMD2SONGHEADER *)pmsh; #ifdef MED_LOG if (version < '2') { Log("MMD0 Header:\n"); Log(" numblocks = %d\n", BigEndianW(pmsh->numblocks)); Log(" songlen = %d\n", BigEndianW(pmsh->songlen)); Log(" playseq = "); for (UINT idbg1=0; idbg1<16; idbg1++) Log("%2d, ", pmsh->playseq[idbg1]); Log("...\n"); Log(" deftempo = 0x%04X\n", BigEndianW(pmsh->deftempo)); Log(" playtransp = %d\n", (signed char)pmsh->playtransp); Log(" flags(1,2) = 0x%02X, 0x%02X\n", pmsh->flags, pmsh->flags2); Log(" tempo2 = %d\n", pmsh->tempo2); Log(" trkvol = "); for (UINT idbg2=0; idbg2<16; idbg2++) Log("0x%02X, ", pmsh->trkvol[idbg2]); Log("...\n"); Log(" mastervol = 0x%02X\n", pmsh->mastervol); Log(" numsamples = %d\n", pmsh->numsamples); } else { Log("MMD2 Header:\n"); Log(" numblocks = %d\n", BigEndianW(pmsh2->numblocks)); Log(" numsections= %d\n", BigEndianW(pmsh2->numsections)); Log(" playseqptr = 0x%04X\n", BigEndian(pmsh2->playseqtable)); Log(" sectionptr = 0x%04X\n", BigEndian(pmsh2->sectiontable)); Log(" trackvols = 0x%04X\n", BigEndian(pmsh2->trackvols)); Log(" numtracks = %d\n", BigEndianW(pmsh2->numtracks)); Log(" numpseqs = %d\n", BigEndianW(pmsh2->numpseqs)); Log(" trackpans = 0x%04X\n", BigEndian(pmsh2->trackpans)); Log(" flags3 = 0x%08X\n", BigEndian(pmsh2->flags3)); Log(" voladj = %d\n", BigEndianW(pmsh2->voladj)); Log(" channels = %d\n", BigEndianW(pmsh2->channels)); Log(" echotype = %d\n", pmsh2->mix_echotype); Log(" echodepth = %d\n", pmsh2->mix_echodepth); Log(" echolen = %d\n", BigEndianW(pmsh2->mix_echolen)); Log(" stereosep = %d\n", (signed char)pmsh2->mix_stereosep); Log(" deftempo = 0x%04X\n", BigEndianW(pmsh2->deftempo)); Log(" playtransp = %d\n", (signed char)pmsh2->playtransp); Log(" flags(1,2) = 0x%02X, 0x%02X\n", pmsh2->flags, pmsh2->flags2); Log(" tempo2 = %d\n", pmsh2->tempo2); Log(" mastervol = 0x%02X\n", pmsh2->mastervol); Log(" numsamples = %d\n", pmsh->numsamples); } Log("\n"); #endif wNumBlocks = BigEndianW(pmsh->numblocks); m_nChannels = 4; m_nSamples = pmsh->numsamples; if (m_nSamples > 63) m_nSamples = 63; // Tempo m_nDefaultTempo = 125; deftempo = BigEndianW(pmsh->deftempo); if (!deftempo) deftempo = 125; if (pmsh->flags2 & MMD_FLAG2_BPM) { UINT tempo_tpl = (pmsh->flags2 & MMD_FLAG2_BMASK) + 1; if (!tempo_tpl) tempo_tpl = 4; deftempo *= tempo_tpl; deftempo /= 4; #ifdef MED_LOG Log("newtempo: %3d bpm (bpm=%3d lpb=%2d)\n", deftempo, BigEndianW(pmsh->deftempo), (pmsh->flags2 & MMD_FLAG2_BMASK)+1); #endif } else { deftempo = Util::muldiv(deftempo, 5*715909, 2*474326); #ifdef MED_LOG Log("oldtempo: %3d bpm (bpm=%3d)\n", deftempo, BigEndianW(pmsh->deftempo)); #endif } // Speed m_nDefaultSpeed = pmsh->tempo2; if (!m_nDefaultSpeed) m_nDefaultSpeed = 6; if (deftempo < 0x21) deftempo = 0x21; if (deftempo > 255) { while ((m_nDefaultSpeed > 3) && (deftempo > 260)) { deftempo = (deftempo * (m_nDefaultSpeed - 1)) / m_nDefaultSpeed; m_nDefaultSpeed--; } if (deftempo > 255) deftempo = 255; } m_nDefaultTempo = deftempo; // Reading Samples for (UINT iSHdr=0; iSHdr<m_nSamples; iSHdr++) { ModSample &sample = Samples[iSHdr + 1]; sample.nLoopStart = BigEndianW(pmsh->sample[iSHdr].rep) << 1; sample.nLoopEnd = sample.nLoopStart + (BigEndianW(pmsh->sample[iSHdr].replen) << 1); sample.nVolume = (pmsh->sample[iSHdr].svol << 2); sample.nGlobalVol = 64; if (sample.nVolume > 256) sample.nVolume = 256; // Was: sample.RelativeTone = -12 * pmsh->sample[iSHdr].strans; // But that breaks MMD1 modules (e.g. "94' summer.mmd1" from Modland) - "automatic terminated to.mmd0" still sounds broken, probably "play transpose" is broken there. sample.RelativeTone = pmsh->sample[iSHdr].strans; sample.nPan = 128; if (sample.nLoopEnd <= 2) sample.nLoopEnd = 0; if (sample.nLoopEnd) sample.uFlags.set(CHN_LOOP); } // Common Flags m_SongFlags.set(SONG_FASTVOLSLIDES, !(pmsh->flags & 0x20)); // Reading play sequence if (version < '2') { UINT nbo = BigEndianW(pmsh->songlen); if (nbo >= MAX_ORDERS) nbo = MAX_ORDERS-1; if (!nbo) nbo = 1; Order.ReadFromArray(pmsh->playseq, nbo); playtransp = pmsh->playtransp; } else { UINT nSections; ORDERINDEX nOrders = 0; WORD nTrks = BigEndianW(pmsh2->numtracks); if ((nTrks >= 4) && (nTrks <= 32)) m_nChannels = nTrks; DWORD playseqtable = BigEndian(pmsh2->playseqtable); UINT numplayseqs = BigEndianW(pmsh2->numpseqs); if (!numplayseqs) numplayseqs = 1; nSections = BigEndianW(pmsh2->numsections); DWORD sectiontable = BigEndian(pmsh2->sectiontable); if ((!nSections) || (!sectiontable) || (sectiontable >= dwMemLength-2)) nSections = 1; nOrders = 0; Order.resize(0); for (UINT iSection=0; iSection<nSections; iSection++) { UINT nplayseq = 0; if ((sectiontable) && (sectiontable < dwMemLength-2)) { nplayseq = lpStream[sectiontable+1]; sectiontable += 2; // WORDs } else { nSections = 0; } UINT pseq = 0; if ((playseqtable) && (playseqtable < dwMemLength) && (nplayseq*4 < dwMemLength - playseqtable)) { pseq = BigEndian(((DWORD*)(lpStream+playseqtable))[nplayseq]); } if ((pseq) && (pseq < dwMemLength - sizeof(MMD2PLAYSEQ))) { MMD2PLAYSEQ *pmps = (MMD2PLAYSEQ *)(lpStream + pseq); if(songName.empty()) mpt::String::Read<mpt::String::maybeNullTerminated>(songName, pmps->name); uint16 n = BigEndianW(pmps->length); if (pseq+n <= dwMemLength) { Order.resize(nOrders + n); for (UINT i=0; i<n; i++) { WORD seqval = BigEndianW(pmps->seq[i]); if ((seqval < wNumBlocks) && (nOrders < MAX_ORDERS-1)) { Order[nOrders++] = (ORDERINDEX)seqval; } } } } } playtransp = pmsh2->playtransp; } // Reading Expansion structure if (pmex) { // Channel Split if ((m_nChannels == 4) && (pmsh->flags & 0x40)) { for (UINT i8ch=0; i8ch<4; i8ch++) { if (pmex->channelsplit[i8ch]) m_nChannels++; } } // Song Comments (null-terminated) UINT annotxt = BigEndian(pmex->annotxt); UINT annolen = BigEndian(pmex->annolen); annolen = MIN(annolen, MED_MAX_COMMENT_LENGTH); //Thanks to Luigi Auriemma for pointing out an overflow risk if ((annotxt) && (annolen) && (annolen <= dwMemLength) && (annotxt <= dwMemLength - annolen) ) { songMessage.Read(lpStream + annotxt, annolen - 1, SongMessage::leAutodetect); } // Song Name UINT songname = BigEndian(pmex->songname); UINT songnamelen = BigEndian(pmex->songnamelen); if ((songname) && (songnamelen) && (songname <= dwMemLength) && (songnamelen <= dwMemLength-songname)) { mpt::String::Read<mpt::String::maybeNullTerminated>(songName, reinterpret_cast<const char *>(lpStream + songname), songnamelen); } // Sample Names DWORD smpinfoex = BigEndian(pmex->iinfo); if (smpinfoex) { DWORD iinfoptr = BigEndian(pmex->iinfo); UINT ientries = BigEndianW(pmex->i_ext_entries); UINT ientrysz = BigEndianW(pmex->i_ext_entrsz); if ((iinfoptr) && (ientrysz < 256) && (ientries*ientrysz < dwMemLength) && (iinfoptr < dwMemLength - ientries*ientrysz)) { const char *psznames = (const char *)(lpStream + iinfoptr); for (UINT i=0; i<ientries; i++) if (i < m_nSamples) { mpt::String::Read<mpt::String::maybeNullTerminated>(m_szNames[i + 1], reinterpret_cast<const char *>(psznames + i * ientrysz), ientrysz); } } } // Track Names DWORD trackinfo_ofs = BigEndian(pmex->trackinfo_ofs); if ((trackinfo_ofs) && (trackinfo_ofs < dwMemLength) && (m_nChannels * 4u < dwMemLength - trackinfo_ofs)) { DWORD *ptrktags = (DWORD *)(lpStream + trackinfo_ofs); for (UINT i=0; i<m_nChannels; i++) { DWORD trknameofs = 0, trknamelen = 0; DWORD trktagofs = BigEndian(ptrktags[i]); if (trktagofs && (trktagofs <= dwMemLength - 8) ) { while (trktagofs+8 < dwMemLength) { DWORD ntag = BigEndian(*(DWORD *)(lpStream + trktagofs)); if (ntag == MMDTAG_END) break; DWORD tagdata = BigEndian(*(DWORD *)(lpStream + trktagofs + 4)); switch(ntag) { case MMDTAG_TRK_NAMELEN: trknamelen = tagdata; break; case MMDTAG_TRK_NAME: trknameofs = tagdata; break; } trktagofs += 8; } if ((trknameofs) && (trknameofs < dwMemLength - trknamelen)) { mpt::String::Read<mpt::String::maybeNullTerminated>(ChnSettings[i].szName, reinterpret_cast<const char *>(lpStream + trknameofs), trknamelen); } } } } } // Reading samples if (dwSmplArr > dwMemLength - 4*m_nSamples) return true; pdwTable = (DWORD*)(lpStream + dwSmplArr); for (UINT iSmp=0; iSmp<m_nSamples; iSmp++) if (pdwTable[iSmp]) { UINT dwPos = BigEndian(pdwTable[iSmp]); if ((dwPos >= dwMemLength) || (dwPos + sizeof(MMDSAMPLEHEADER) >= dwMemLength)) continue; MMDSAMPLEHEADER *psdh = (MMDSAMPLEHEADER *)(lpStream + dwPos); UINT len = BigEndian(psdh->length); #ifdef MED_LOG Log("SampleData %d: stype=0x%02X len=%d\n", iSmp, BigEndianW(psdh->type), len); #endif if(dwPos + len + 6 > dwMemLength) len = 0; UINT stype = BigEndianW(psdh->type); char *psdata = (char *)(lpStream + dwPos + 6); SampleIO sampleIO( SampleIO::_8bit, SampleIO::mono, SampleIO::bigEndian, SampleIO::signedPCM); if (stype & 0x80) { psdata += (stype & 0x20) ? 14 : 6; } else { if(stype & 0x10) { sampleIO |= SampleIO::_16bit; len /= 2; } if(stype & 0x20) { sampleIO |= SampleIO::stereoSplit; len /= 2; } } Samples[iSmp + 1].nLength = len; if(loadFlags & loadSampleData) { FileReader chunk(psdata, dwMemLength - dwPos - 6); sampleIO.ReadSample(Samples[iSmp + 1], chunk); } } // Reading patterns (blocks) if(!(loadFlags & loadPatternData)) { return true; } if (wNumBlocks > MAX_PATTERNS) wNumBlocks = MAX_PATTERNS; if ((!dwBlockArr) || (dwBlockArr > dwMemLength - 4*wNumBlocks)) return true; pdwTable = (DWORD*)(lpStream + dwBlockArr); playtransp += (version == '3') ? 24 : 48; for (PATTERNINDEX iBlk=0; iBlk<wNumBlocks; iBlk++) { UINT dwPos = BigEndian(pdwTable[iBlk]); if ((!dwPos) || (dwPos >= dwMemLength) || (dwPos >= dwMemLength - 8)) continue; UINT lines = 64, tracks = 4; if (version == '0') { const MMD0BLOCK *pmb = (const MMD0BLOCK *)(lpStream + dwPos); lines = pmb->lines + 1; tracks = pmb->numtracks; if (!tracks) tracks = m_nChannels; if(Patterns.Insert(iBlk, lines)) continue; ModCommand *p = Patterns[iBlk]; const uint8 * s = (const uint8 *)(lpStream + dwPos + 2); UINT maxlen = tracks*lines*3; if (maxlen + dwPos > dwMemLength - 2) break; for (UINT y=0; y<lines; y++) { for (UINT x=0; x<tracks; x++, s+=3) if (x < m_nChannels) { BYTE note = s[0] & 0x3F; BYTE instr = s[1] >> 4; if (s[0] & 0x80) instr |= 0x10; if (s[0] & 0x40) instr |= 0x20; if ((note) && (note <= 132)) p->note = static_cast<BYTE>(note + playtransp); p->instr = instr; p->command = s[1] & 0x0F; p->param = s[2]; // if (!iBlk) Log("%02X.%02X.%02X | ", s[0], s[1], s[2]); MedConvert(p, pmsh); p++; } //if (!iBlk) Log("\n"); } } else { MMD1BLOCK *pmb = (MMD1BLOCK *)(lpStream + dwPos); #ifdef MED_LOG Log("MMD1BLOCK: lines=%2d, tracks=%2d, offset=0x%04X\n", BigEndianW(pmb->lines), BigEndianW(pmb->numtracks), BigEndian(pmb->info)); #endif MMD1BLOCKINFO *pbi = NULL; BYTE *pcmdext = NULL; lines = (pmb->lines >> 8) + 1; tracks = pmb->numtracks >> 8; if (!tracks) tracks = m_nChannels; Patterns.Insert(iBlk, lines); DWORD dwBlockInfo = BigEndian(pmb->info); if ((dwBlockInfo) && (dwBlockInfo < dwMemLength - sizeof(MMD1BLOCKINFO))) { pbi = (MMD1BLOCKINFO *)(lpStream + dwBlockInfo); #ifdef MED_LOG Log(" BLOCKINFO: blockname=0x%04X namelen=%d pagetable=0x%04X &cmdexttable=0x%04X\n", BigEndian(pbi->blockname), BigEndian(pbi->blocknamelen), BigEndian(pbi->pagetable), BigEndian(pbi->cmdexttable)); #endif if ((pbi->blockname) && (pbi->blocknamelen)) { DWORD nameofs = BigEndian(pbi->blockname); UINT namelen = BigEndian(pbi->blocknamelen); if ((nameofs < dwMemLength) && (namelen < dwMemLength - nameofs)) { Patterns[iBlk].SetName((char *)(lpStream + nameofs), namelen); } } if (pbi->cmdexttable) { DWORD cmdexttable = BigEndian(pbi->cmdexttable); if (cmdexttable < dwMemLength - 4) { cmdexttable = BigEndian(*(DWORD *)(lpStream + cmdexttable)); if ((cmdexttable) && (cmdexttable <= dwMemLength - lines*tracks)) { pcmdext = (BYTE *)(lpStream + cmdexttable); } } } } ModCommand *p = Patterns[iBlk]; const uint8 * s = (const uint8 *)(lpStream + dwPos + 8); UINT maxlen = tracks*lines*4; if (maxlen + dwPos > dwMemLength - 8) break; for (UINT y=0; y<lines; y++) { for (UINT x=0; x<tracks; x++, s+=4) if (x < m_nChannels) { BYTE note = s[0]; if ((note) && (note <= 132)) { int rnote = note + playtransp; if (rnote < 1) rnote = 1; if (rnote > NOTE_MAX) rnote = NOTE_MAX; p->note = (BYTE)rnote; } p->instr = s[1]; p->command = s[2]; p->param = s[3]; if (pcmdext) p->vol = pcmdext[x]; MedConvert(p, pmsh); p++; } if (pcmdext) pcmdext += tracks; } } } return true; } OPENMPT_NAMESPACE_END
[ "false.genesis@googlemail.com" ]
false.genesis@googlemail.com
f4441bc5f6353eacbf146d400aac57820753381f
ec543e13a8f328c3aa73d0579669bab32d4220c4
/mapnikvt/src/mapnikvt/TextSymbolizer.cpp
bfeaff27c1e7d4ab7807ff5c05b460c98b6d84d9
[ "BSD-3-Clause" ]
permissive
yangkf1985/mobile-carto-libs
64568fea7d10e24bc42ebf92d0fdf78d0a3d08cc
e446eea9bdd05c59188834de230cea378132e1d1
refs/heads/master
2023-04-18T13:51:29.915699
2021-04-20T08:38:43
2021-04-20T08:38:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,869
cpp
#include "TextSymbolizer.h" #include "ParserUtils.h" #include "FontSet.h" #include "Expression.h" #include "ExpressionOperator.h" #include "vt/FontManager.h" #include <memory> #include <vector> #include <limits> #include <boost/algorithm/string.hpp> namespace carto { namespace mvt { void TextSymbolizer::build(const FeatureCollection& featureCollection, const FeatureExpressionContext& exprContext, const SymbolizerContext& symbolizerContext, vt::TileLayerBuilder& layerBuilder) { std::lock_guard<std::mutex> lock(_mutex); updateBindings(exprContext); if (_sizeFunc == vt::FloatFunction(0)) { return; } std::shared_ptr<vt::Font> font = getFont(symbolizerContext); if (!font) { _logger->write(Logger::Severity::ERROR, "Failed to load text font " + (!_faceName.empty() ? _faceName : _fontSetName)); return; } vt::CompOp compOp = convertCompOp(_compOp); bool clip = _clipDefined ? _clip : _allowOverlap; vt::TextFormatter formatter(font, _sizeStatic, getFormatterOptions(symbolizerContext)); float fontScale = symbolizerContext.getSettings().getFontScale(); vt::LabelOrientation placement = convertTextPlacement(_placement); float minimumDistance = _minimumDistance * std::pow(2.0f, -exprContext.getAdjustedZoom()); vt::ColorFunction fillFunc = _functionBuilder.createColorOpacityFunction(_fillFunc, _opacityFunc); vt::FloatFunction sizeFunc = _functionBuilder.createChainedFloatFunction("multiply" + boost::lexical_cast<std::string>(fontScale), [fontScale](float size) { return size * fontScale; }, _sizeFunc); vt::ColorFunction haloFillFunc = _functionBuilder.createColorOpacityFunction(_haloFillFunc, _haloOpacityFunc); vt::FloatFunction haloRadiusFunc = _functionBuilder.createChainedFloatFunction("multiply" + boost::lexical_cast<std::string>(fontScale), [fontScale](float size) { return size * fontScale; }, _haloRadiusFunc); std::vector<std::pair<long long, std::tuple<vt::TileLayerBuilder::Vertex, std::string>>> textInfos; std::vector<std::pair<long long, vt::TileLayerBuilder::TextLabelInfo>> labelInfos; auto addText = [&](long long localId, long long globalId, const std::string& text, const boost::optional<vt::TileLayerBuilder::Vertex>& vertex, const vt::TileLayerBuilder::Vertices& vertices) { long long groupId = (_allowOverlap ? -1 : (minimumDistance > 0 ? (std::hash<std::string>()(text) & 0x7fffffff) : 0)); if (clip) { if (vertex) { textInfos.emplace_back(localId, std::make_tuple(*vertex, text)); } else if (!vertices.empty()) { textInfos.emplace_back(localId, std::make_tuple(vertices.front(), text)); } } else { labelInfos.emplace_back(localId, vt::TileLayerBuilder::TextLabelInfo(globalId * 3 + 1, groupId, text, vertex, vertices, _placementPriority, minimumDistance)); } }; auto flushTexts = [&](const cglib::mat3x3<float>& transform) { if (clip) { vt::TextStyle style(compOp, fillFunc, sizeFunc, haloFillFunc, haloRadiusFunc, _orientationAngle, fontScale, cglib::vec2<float>(0, 0), std::shared_ptr<vt::BitmapImage>(), transform); std::size_t textInfoIndex = 0; layerBuilder.addTexts([&](long long& id, vt::TileLayerBuilder::Vertex& vertex, std::string& text) { if (textInfoIndex >= textInfos.size()) { return false; } id = textInfos[textInfoIndex].first; vertex = std::get<0>(textInfos[textInfoIndex].second); text = std::get<1>(textInfos[textInfoIndex].second); textInfoIndex++; return true; }, style, formatter); textInfos.clear(); } else { vt::TextLabelStyle style(placement, fillFunc, sizeFunc, haloFillFunc, haloRadiusFunc, true, _orientationAngle, fontScale, cglib::vec2<float>(0, 0), std::shared_ptr<vt::BitmapImage>()); std::size_t labelInfoIndex = 0; layerBuilder.addTextLabels([&](long long& id, vt::TileLayerBuilder::TextLabelInfo& labelInfo) { if (labelInfoIndex >= labelInfos.size()) { return false; } id = labelInfos[labelInfoIndex].first; labelInfo = labelInfos[labelInfoIndex].second; labelInfoIndex++; return true; }, style, formatter); labelInfos.clear(); } }; buildFeatureCollection(featureCollection, exprContext, symbolizerContext, formatter, placement, -1, addText); flushTexts(cglib::mat3x3<float>::identity()); } void TextSymbolizer::bindParameter(const std::string& name, const std::string& value) { if (name == "name") { _textExpression = std::make_shared<VariableExpression>(value); } else if (name == "feature-id") { bind(&_featureId, parseExpression(value), &TextSymbolizer::convertId); _featureIdDefined = true; } else if (name == "face-name") { bind(&_faceName, parseStringExpression(value)); } else if (name == "fontset-name") { bind(&_fontSetName, parseStringExpression(value)); } else if (name == "placement") { bind(&_placement, parseStringExpression(value)); } else if (name == "size") { bind(&_sizeFunc, parseExpression(value)); bind(&_sizeStatic, parseExpression(value)); } else if (name == "spacing") { bind(&_spacing, parseExpression(value)); } else if (name == "fill") { bind(&_fillFunc, parseStringExpression(value), &TextSymbolizer::convertColor); } else if (name == "opacity") { bind(&_opacityFunc, parseExpression(value)); } else if (name == "halo-fill") { bind(&_haloFillFunc, parseStringExpression(value), &TextSymbolizer::convertColor); } else if (name == "halo-opacity") { bind(&_haloOpacityFunc, parseExpression(value)); } else if (name == "halo-radius") { bind(&_haloRadiusFunc, parseExpression(value)); } else if (name == "halo-rasterizer") { // just ignore this } else if (name == "allow-overlap") { bind(&_allowOverlap, parseExpression(value)); } else if (name == "clip") { bind(&_clip, parseExpression(value)); _clipDefined = true; } else if (name == "placement-priority") { bind(&_placementPriority, parseExpression(value)); } else if (name == "minimum-distance") { bind(&_minimumDistance, parseExpression(value)); } else if (name == "text-transform") { bind(&_textTransform, parseStringExpression(value)); } else if (name == "orientation") { bind(&_orientationAngle, parseExpression(value)); _orientationDefined = true; } else if (name == "dx") { bind(&_dx, parseExpression(value)); } else if (name == "dy") { bind(&_dy, parseExpression(value)); } else if (name == "avoid-edges") { // can ignore this, we are not clipping texts at tile boundaries } else if (name == "wrap-width") { bind(&_wrapWidth, parseExpression(value)); } else if (name == "wrap-before") { bind(&_wrapBefore, parseExpression(value)); } else if (name == "character-spacing") { bind(&_characterSpacing, parseExpression(value)); } else if (name == "line-spacing") { bind(&_lineSpacing, parseExpression(value)); } else if (name == "horizontal-alignment") { bind(&_horizontalAlignment, parseStringExpression(value)); } else if (name == "vertical-alignment") { bind(&_verticalAlignment, parseStringExpression(value)); } else if (name == "comp-op") { bind(&_compOp, parseStringExpression(value)); } else { Symbolizer::bindParameter(name, value); } } std::string TextSymbolizer::getTransformedText(const std::string& text) const { if (_textTransform.empty()) { return text; } else if (_textTransform == "uppercase") { return toUpper(text); } else if (_textTransform == "lowercase") { return toLower(text); } else if (_textTransform == "capitalize") { return capitalize(text); } return text; } std::shared_ptr<vt::Font> TextSymbolizer::getFont(const SymbolizerContext& symbolizerContext) const { std::shared_ptr<vt::Font> font = symbolizerContext.getSettings().getFallbackFont(); if (!_faceName.empty()) { font = symbolizerContext.getFontManager()->getFont(_faceName, font); } else if (!_fontSetName.empty()) { for (const std::shared_ptr<FontSet>& fontSet : _fontSets) { if (fontSet->getName() == _fontSetName) { const std::vector<std::string>& faceNames = fontSet->getFaceNames(); for (auto it = faceNames.rbegin(); it != faceNames.rend(); it++) { const std::string& faceName = *it; std::shared_ptr<vt::Font> mainFont = symbolizerContext.getFontManager()->getFont(faceName, font); if (mainFont) { font = mainFont; } } break; } } } return font; } cglib::bbox2<float> TextSymbolizer::calculateTextSize(const std::shared_ptr<vt::Font>& font, const std::string& text, const vt::TextFormatter& formatter) const { std::vector<vt::Font::Glyph> glyphs = formatter.format(text, formatter.getFontSize()); cglib::bbox2<float> bbox = cglib::bbox2<float>::smallest(); cglib::vec2<float> pen = cglib::vec2<float>(0, 0); for (const vt::Font::Glyph& glyph : glyphs) { if (glyph.codePoint == vt::Font::CR_CODEPOINT) { pen = cglib::vec2<float>(0, 0); } else { bbox.add(pen + glyph.offset); bbox.add(pen + glyph.offset + glyph.size); } pen += glyph.advance; } return bbox; } vt::TextFormatter::Options TextSymbolizer::getFormatterOptions(const SymbolizerContext& symbolizerContext) const { float fontScale = symbolizerContext.getSettings().getFontScale(); cglib::vec2<float> offset(_dx * fontScale, -_dy * fontScale); cglib::vec2<float> alignment(_dx < 0 ? 1.0f : (_dx > 0 ? -1.0f : 0.0f), _dy < 0 ? 1.0f : (_dy > 0 ? -1.0f : 0.0f)); if (_horizontalAlignment == "left") { alignment(0) = -1.0f; } else if (_horizontalAlignment == "middle") { alignment(0) = 0.0f; } else if (_horizontalAlignment == "right") { alignment(0) = 1.0f; } if (_verticalAlignment == "top") { alignment(1) = -1.0f; } else if (_verticalAlignment == "middle") { alignment(1) = 0.0f; } else if (_verticalAlignment == "bottom") { alignment(1) = 1.0f; } return vt::TextFormatter::Options(alignment, offset, _wrapBefore, _wrapWidth * fontScale, _characterSpacing, _lineSpacing); } vt::LabelOrientation TextSymbolizer::convertTextPlacement(const std::string& orientation) const { vt::LabelOrientation placement = convertLabelPlacement(orientation); if (placement != vt::LabelOrientation::LINE) { if (_orientationDefined) { // if orientation is explictly defined, use POINT placement return vt::LabelOrientation::POINT; } } return placement; } void TextSymbolizer::buildFeatureCollection(const FeatureCollection& featureCollection, const FeatureExpressionContext& exprContext, const SymbolizerContext& symbolizerContext, const vt::TextFormatter& formatter, vt::LabelOrientation placement, float bitmapSize, const std::function<void(long long localId, long long globalId, const std::string& text, const boost::optional<vt::TileLayerBuilder::Vertex>& vertex, const vt::TileLayerBuilder::Vertices& vertices)>& addText) { FeatureExpressionContext textExprContext(exprContext); for (std::size_t index = 0; index < featureCollection.size(); index++) { textExprContext.setFeatureData(featureCollection.getFeatureData(index)); std::string text = getTransformedText(ValueConverter<std::string>::convert(_textExpression->evaluate(textExprContext))); std::size_t hash = std::hash<std::string>()(text); float textSize = bitmapSize < 0 ? (placement == vt::LabelOrientation::LINE ? calculateTextSize(formatter.getFont(), text, formatter).size()(0) : 0) : bitmapSize; long long localId = featureCollection.getLocalId(index); long long globalId = _featureIdDefined ? (_featureId ? _featureId : generateId()) : combineId(featureCollection.getGlobalId(index), hash); const std::shared_ptr<const Geometry>& geometry = featureCollection.getGeometry(index); auto addLineTexts = [&](const std::vector<cglib::vec2<float>>& vertices) { if (_spacing <= 0) { addText(localId, globalId, text, boost::optional<vt::TileLayerBuilder::Vertex>(), vertices); return; } float linePos = 0; for (std::size_t i = 1; i < vertices.size(); i++) { const cglib::vec2<float>& v0 = vertices[i - 1]; const cglib::vec2<float>& v1 = vertices[i]; float lineLen = cglib::length(v1 - v0) * symbolizerContext.getSettings().getTileSize(); if (i == 1) { linePos = std::min(lineLen, _spacing) * 0.5f; } while (linePos < lineLen) { cglib::vec2<float> pos = v0 + (v1 - v0) * (linePos / lineLen); if (std::min(pos(0), pos(1)) > 0.0f && std::max(pos(0), pos(1)) < 1.0f) { addText(localId, generateId(), text, pos, vertices); } linePos += _spacing + textSize; } linePos -= lineLen; } }; if (auto pointGeometry = std::dynamic_pointer_cast<const PointGeometry>(geometry)) { for (const auto& vertex : pointGeometry->getVertices()) { addText(localId, globalId, text, vertex, vt::TileLayerBuilder::Vertices()); } } else if (auto lineGeometry = std::dynamic_pointer_cast<const LineGeometry>(geometry)) { if (placement == vt::LabelOrientation::LINE) { for (const auto& vertices : lineGeometry->getVerticesList()) { addLineTexts(vertices); } } else { for (const auto& vertices : lineGeometry->getVerticesList()) { addText(localId, globalId, text, boost::optional<vt::TileLayerBuilder::Vertex>(), vertices); } } } else if (auto polygonGeometry = std::dynamic_pointer_cast<const PolygonGeometry>(geometry)) { if (placement == vt::LabelOrientation::LINE) { for (const auto& vertices : polygonGeometry->getClosedOuterRings(true)) { addLineTexts(vertices); } } else { for (const auto& vertex : polygonGeometry->getSurfacePoints()) { addText(localId, globalId, text, vertex, vt::TileLayerBuilder::Vertices()); } } } else { _logger->write(Logger::Severity::WARNING, "Unsupported geometry for TextSymbolizer/ShieldSymbolizer"); } } } } }
[ "mark.tehver@gmail.com" ]
mark.tehver@gmail.com
7573c44498782b1446eb0e775c0130dfac63b3b0
a55cec32c0191f3f99752749f8323a517be46638
/ProfessionalC++/SingletonLogger/Logger.h
40551eee1bce237110e3dfc29fd8cae13a1c0f96
[ "Apache-2.0" ]
permissive
zzragida/CppExamples
e0b0d1609b2e485cbac22e0878e00cc8ebce6a94
d627b097efc04209aa4012f7b7f9d82858da3f2d
refs/heads/master
2021-01-18T15:06:57.286097
2016-03-08T00:23:31
2016-03-08T00:23:31
49,173,497
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
#include <iostream> #include <fstream> #include <vector> #include <string> class Logger { public: static const std::string kLogLevelDebug; static const std::string kLogLevelInfo; static const std::string kLogLevelError; static Logger& instance(); void log(const std::string& msg, const std::string& level); void log(const std::vector<std::string>& msgs, const std::string& level); protected: static Logger sInstance; static const char* const kLogFileName; std::ofstream mOutputStream; private: Logger(); virtual ~Logger(); };
[ "zzragida@gmail.com" ]
zzragida@gmail.com
2dc1b9395cf931aec189b17659172208111bb9c4
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/PColgp_FieldOfHArray1OfCirc2d.hxx
31001cd5320b5654288941d63388bbb97800756b
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
2,388
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _PColgp_FieldOfHArray1OfCirc2d_HeaderFile #define _PColgp_FieldOfHArray1OfCirc2d_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineAlloc_HeaderFile #include <Standard_DefineAlloc.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _DBC_BaseArray_HeaderFile #include <DBC_BaseArray.hxx> #endif #ifndef _Handle_PColgp_VArrayNodeOfFieldOfHArray1OfCirc2d_HeaderFile #include <Handle_PColgp_VArrayNodeOfFieldOfHArray1OfCirc2d.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Standard_PrimitiveTypes_HeaderFile #include <Standard_PrimitiveTypes.hxx> #endif class Standard_NegativeValue; class Standard_OutOfRange; class Standard_DimensionMismatch; class Standard_NullObject; class gp_Circ2d; class PColgp_VArrayNodeOfFieldOfHArray1OfCirc2d; class PColgp_VArrayTNodeOfFieldOfHArray1OfCirc2d; Standard_EXPORT const Handle(Standard_Type)& STANDARD_TYPE(PColgp_FieldOfHArray1OfCirc2d); class PColgp_FieldOfHArray1OfCirc2d : public DBC_BaseArray { public: DEFINE_STANDARD_ALLOC Standard_EXPORT PColgp_FieldOfHArray1OfCirc2d(); Standard_EXPORT PColgp_FieldOfHArray1OfCirc2d(const Standard_Integer Size); Standard_EXPORT PColgp_FieldOfHArray1OfCirc2d(const PColgp_FieldOfHArray1OfCirc2d& Varray); Standard_EXPORT void Resize(const Standard_Integer Size) ; Standard_EXPORT void Assign(const PColgp_FieldOfHArray1OfCirc2d& Other) ; void operator =(const PColgp_FieldOfHArray1OfCirc2d& Other) { Assign(Other); } Standard_EXPORT void SetValue(const Standard_Integer Index,const gp_Circ2d& Value) ; Standard_EXPORT gp_Circ2d& Value(const Standard_Integer Index) const; gp_Circ2d& operator ()(const Standard_Integer Index) const { return Value(Index); } Standard_EXPORT void Destroy() ; ~PColgp_FieldOfHArray1OfCirc2d() { Destroy(); } protected: private: #ifdef CSFDB // DBC_VArray : field // #endif }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
f800f06d2b8062cc31f69dadf89ee1e4fffe4f0f
51adec2540ecbc95373c27e2b899b1645a08fff1
/Lab 1 DLL's in C++/lab1.1/lab1.3DDLdynamisk/stdafx.cpp
d3c3ee12f5901f02a120a146b5228f8475473e2b
[]
no_license
entvex/ITKPU1-01
684220e0169faf8f0b18bf98a4e095feb8929eb2
da17087f423ba2c65e00908a890c18a613b1f176
refs/heads/master
2021-01-23T02:06:02.951906
2017-03-23T15:23:39
2017-03-23T15:23:39
85,962,153
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
// stdafx.cpp : source file that includes just the standard includes // lab1.3DDLdynamisk.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "entvex@gmail.com" ]
entvex@gmail.com
7834db57e53f551a9a0d442c21d3175be6218083
8e097cd73a96cbd55db11189856f4f914d0bca14
/include/kaballoc/std/tuple.h
cac5eeed3e369fe227289718391280f38ccf9ee4
[ "Unlicense" ]
permissive
KABoissonneault/allocator
fe3e6dcae2afddca553e2334b61302c3873a5b87
93736e25657dddad4d458e7c11de5dc169af43cb
refs/heads/master
2021-02-25T22:22:41.467444
2020-11-16T03:10:56
2020-11-16T03:10:56
245,471,768
1
0
null
null
null
null
UTF-8
C++
false
false
444
h
#pragma once // Add std types as relocatable based on the table found on this site: https://quuxplusone.github.io/blog/2019/02/20/p1144-what-types-are-relocatable/ #include "kaballoc/trait/relocatable.h" #include <tuple> namespace kab { template<typename... Args> using tuple = std::tuple<Args...>; template<typename... Args> struct is_trivially_relocatable<tuple<Args...>> : std::conjunction<is_trivially_relocatable<Args>...> { }; }
[ "kaboissonneault@bhvr.com" ]
kaboissonneault@bhvr.com
2180e5586b0fbd92c2b2b8c88a93b3fd0aaff3e0
2406608bbae69096bc6e92157111c999e3d33f2f
/Лаба 8/E.cpp
68f27629ef542c291b8711d72bf27e4e4646266b
[]
no_license
TerixSK/Algorithms-2020-2021
a19eea7c28d831da40deb30c0e32347b46b30b7a
715ba0c54f42b4f39b04b6a7eaae1b391967e0d3
refs/heads/master
2023-04-17T01:53:26.387030
2021-04-26T14:23:14
2021-04-26T14:23:14
361,481,443
3
3
null
null
null
null
UTF-8
C++
false
false
1,771
cpp
#include <fstream> #include <iostream> #include <vector> #include <queue> using namespace std; vector<int> graph[100000]; vector<bool> used; vector<int> dist; void bfs(int v) // обход в ширину { used[v] = true; // помечаем первую вершину dist[v] = 0; queue<int> q; q.push(v); // добовляем её в очередь while (!q.empty()) // пока очередь не пуста { int E = q.front(); // достаём из очереди первый элемент for (int i = 0; i < graph[E].size(); i++) { if (used[graph[E][i]] == false) // если вершина ещё непомечена { used[graph[E][i]] = true; // помечаем её dist[graph[E][i]] = dist[E] + 1; // добовляем 1 за пройденную вершину q.push(graph[E][i]); // добвляем вершину в очередь } } q.pop(); } } int main() { ifstream fin("pathbge1.in"); ofstream fout("pathbge1.out"); int n, m, top1, top2; fin >> n >> m; for (int i = 0; i < m; i++) // считываем входные данные { fin >> top1 >> top2; top1--; top2--; graph[top1].push_back(top2); graph[top2].push_back(top1); } for (int i = 0; i < n; i++) // заполняем векторы меток и расстояния { used.push_back(false); dist.push_back(0); } for (int i = 0; i < n; i++) // запускаем обход в ширину if (used[i] == false) bfs(i); for (int i = 0; i < n; i++) fout << dist[i] << " "; return 0; }
[ "tarasov2964@mail.ru" ]
tarasov2964@mail.ru
c4b0d75aaa9ebc8b319047491cbbc13db1c1e280
3438e8c139a5833836a91140af412311aebf9e86
/components/sync/model_impl/processor_entity_tracker_unittest.cc
98037971fdeb900c69b9690eba27b256792a382e
[ "BSD-3-Clause" ]
permissive
Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786370
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
2022-12-18T12:14:22
2016-10-18T04:58:13
null
UTF-8
C++
false
false
19,754
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/model_impl/processor_entity_tracker.h" #include <utility> #include "base/memory/ptr_util.h" #include "components/sync/base/model_type.h" #include "components/sync/base/time.h" #include "components/sync/engine/non_blocking_sync_common.h" #include "components/sync/protocol/sync.pb.h" #include "components/sync/syncable/syncable_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace { const char kKey[] = "key"; const char kHash[] = "hash"; const char kId[] = "id"; const char kName[] = "name"; const char kValue1[] = "value1"; const char kValue2[] = "value2"; const char kValue3[] = "value3"; sync_pb::EntitySpecifics GenerateSpecifics(const std::string& name, const std::string& value) { sync_pb::EntitySpecifics specifics; specifics.mutable_preference()->set_name(name); specifics.mutable_preference()->set_value(value); return specifics; } std::unique_ptr<EntityData> GenerateEntityData(const std::string& hash, const std::string& name, const std::string& value) { std::unique_ptr<EntityData> entity_data(new EntityData()); entity_data->client_tag_hash = hash; entity_data->specifics = GenerateSpecifics(name, value); entity_data->non_unique_name = name; return entity_data; } UpdateResponseData GenerateUpdate(const ProcessorEntityTracker& entity, const std::string& hash, const std::string& id, const std::string& name, const std::string& value, const base::Time& mtime, int64_t version) { std::unique_ptr<EntityData> data = GenerateEntityData(hash, name, value); data->id = id; data->modification_time = mtime; UpdateResponseData update; update.entity = data->PassToPtr(); update.response_version = version; return update; } UpdateResponseData GenerateTombstone(const ProcessorEntityTracker& entity, const std::string& hash, const std::string& id, const std::string& name, const base::Time& mtime, int64_t version) { std::unique_ptr<EntityData> data = base::MakeUnique<EntityData>(); data->client_tag_hash = hash; data->non_unique_name = name; data->id = id; data->modification_time = mtime; UpdateResponseData update; update.entity = data->PassToPtr(); update.response_version = version; return update; } CommitResponseData GenerateAckData(const CommitRequestData& request, const std::string id, int64_t version) { CommitResponseData response; response.id = id; response.client_tag_hash = request.entity->client_tag_hash; response.sequence_number = request.sequence_number; response.response_version = version; response.specifics_hash = request.specifics_hash; return response; } } // namespace // Some simple sanity tests for the ProcessorEntityTracker. // // A lot of the more complicated sync logic is implemented in the // SharedModelTypeProcessor that owns the ProcessorEntityTracker. We can't unit // test it here. // // Instead, we focus on simple tests to make sure that variables are getting // properly intialized and flags properly set. Anything more complicated would // be a redundant and incomplete version of the SharedModelTypeProcessor tests. class ProcessorEntityTrackerTest : public ::testing::Test { public: ProcessorEntityTrackerTest() : ctime_(base::Time::Now() - base::TimeDelta::FromSeconds(1)) {} std::unique_ptr<ProcessorEntityTracker> CreateNew() { return ProcessorEntityTracker::CreateNew(kKey, kHash, "", ctime_); } std::unique_ptr<ProcessorEntityTracker> CreateSynced() { std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); entity->RecordAcceptedUpdate( GenerateUpdate(*entity, kHash, kId, kName, kValue1, ctime_, 1)); DCHECK(!entity->IsUnsynced()); return entity; } const base::Time ctime_; }; // Test the state of the default new tracker. TEST_F(ProcessorEntityTrackerTest, DefaultTracker) { std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); EXPECT_EQ(kKey, entity->storage_key()); EXPECT_EQ(kHash, entity->metadata().client_tag_hash()); EXPECT_EQ("", entity->metadata().server_id()); EXPECT_FALSE(entity->metadata().is_deleted()); EXPECT_EQ(0, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(kUncommittedVersion, entity->metadata().server_version()); EXPECT_EQ(TimeToProtoTime(ctime_), entity->metadata().creation_time()); EXPECT_EQ(0, entity->metadata().modification_time()); EXPECT_TRUE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->UpdateIsReflection(1)); EXPECT_FALSE(entity->HasCommitData()); } // Test creating and commiting a new local item. TEST_F(ProcessorEntityTrackerTest, NewLocalItem) { std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); entity->MakeLocalChange(GenerateEntityData(kHash, kName, kValue1)); EXPECT_EQ("", entity->metadata().server_id()); EXPECT_FALSE(entity->metadata().is_deleted()); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(kUncommittedVersion, entity->metadata().server_version()); EXPECT_NE(0, entity->metadata().modification_time()); EXPECT_FALSE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_TRUE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->UpdateIsReflection(1)); EXPECT_TRUE(entity->HasCommitData()); EXPECT_EQ(kValue1, entity->commit_data()->specifics.preference().value()); // Generate a commit request. The metadata should not change. const sync_pb::EntityMetadata metadata_v1 = entity->metadata(); CommitRequestData request; entity->InitializeCommitRequestData(&request); EXPECT_EQ(metadata_v1.SerializeAsString(), entity->metadata().SerializeAsString()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->UpdateIsReflection(1)); EXPECT_TRUE(entity->HasCommitData()); const EntityData& data = request.entity.value(); EXPECT_EQ("", data.id); EXPECT_EQ(kHash, data.client_tag_hash); EXPECT_EQ(kName, data.non_unique_name); EXPECT_EQ(kValue1, data.specifics.preference().value()); EXPECT_EQ(TimeToProtoTime(ctime_), TimeToProtoTime(data.creation_time)); EXPECT_EQ(entity->metadata().modification_time(), TimeToProtoTime(data.modification_time)); EXPECT_FALSE(data.is_deleted()); EXPECT_EQ(1, request.sequence_number); EXPECT_EQ(kUncommittedVersion, request.base_version); EXPECT_EQ(entity->metadata().specifics_hash(), request.specifics_hash); // Ack the commit. entity->ReceiveCommitResponse(GenerateAckData(request, kId, 1)); EXPECT_EQ(kId, entity->metadata().server_id()); EXPECT_FALSE(entity->metadata().is_deleted()); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(1, entity->metadata().acked_sequence_number()); EXPECT_EQ(1, entity->metadata().server_version()); EXPECT_EQ(metadata_v1.creation_time(), entity->metadata().creation_time()); EXPECT_EQ(metadata_v1.modification_time(), entity->metadata().modification_time()); EXPECT_FALSE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_TRUE(entity->UpdateIsReflection(1)); EXPECT_FALSE(entity->HasCommitData()); } // Test state for a newly synced server item. TEST_F(ProcessorEntityTrackerTest, NewServerItem) { std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); const base::Time mtime = base::Time::Now(); entity->RecordAcceptedUpdate( GenerateUpdate(*entity, kHash, kId, kName, kValue1, mtime, 10)); EXPECT_EQ(kId, entity->metadata().server_id()); EXPECT_FALSE(entity->metadata().is_deleted()); EXPECT_EQ(0, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(10, entity->metadata().server_version()); EXPECT_EQ(TimeToProtoTime(mtime), entity->metadata().modification_time()); EXPECT_FALSE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_TRUE(entity->UpdateIsReflection(9)); EXPECT_TRUE(entity->UpdateIsReflection(10)); EXPECT_FALSE(entity->UpdateIsReflection(11)); EXPECT_FALSE(entity->HasCommitData()); } // Test state for a tombstone received for a previously unknown item. TEST_F(ProcessorEntityTrackerTest, NewServerTombstone) { std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); const base::Time mtime = base::Time::Now(); entity->RecordAcceptedUpdate( GenerateTombstone(*entity, kHash, kId, kName, mtime, 1)); EXPECT_EQ(kId, entity->metadata().server_id()); EXPECT_TRUE(entity->metadata().is_deleted()); EXPECT_EQ(0, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(1, entity->metadata().server_version()); EXPECT_EQ(TimeToProtoTime(mtime), entity->metadata().modification_time()); EXPECT_TRUE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_TRUE(entity->CanClearMetadata()); EXPECT_TRUE(entity->UpdateIsReflection(1)); EXPECT_FALSE(entity->UpdateIsReflection(2)); EXPECT_FALSE(entity->HasCommitData()); } // Apply a deletion update to a synced item. TEST_F(ProcessorEntityTrackerTest, ServerTombstone) { // Start with a non-deleted state with version 1. std::unique_ptr<ProcessorEntityTracker> entity = CreateSynced(); // A deletion update one version later. const base::Time mtime = base::Time::Now(); entity->RecordAcceptedUpdate( GenerateTombstone(*entity, kHash, kId, kName, mtime, 2)); EXPECT_TRUE(entity->metadata().is_deleted()); EXPECT_EQ(0, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(2, entity->metadata().server_version()); EXPECT_EQ(TimeToProtoTime(mtime), entity->metadata().modification_time()); EXPECT_TRUE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_TRUE(entity->CanClearMetadata()); EXPECT_TRUE(entity->UpdateIsReflection(2)); EXPECT_FALSE(entity->UpdateIsReflection(3)); EXPECT_FALSE(entity->HasCommitData()); } // Test a local change of a synced item. TEST_F(ProcessorEntityTrackerTest, LocalChange) { std::unique_ptr<ProcessorEntityTracker> entity = CreateSynced(); const int64_t mtime_v0 = entity->metadata().modification_time(); const std::string specifics_hash_v0 = entity->metadata().specifics_hash(); // Make a local change with different specifics. entity->MakeLocalChange(GenerateEntityData(kHash, kName, kValue2)); const int64_t mtime_v1 = entity->metadata().modification_time(); const std::string specifics_hash_v1 = entity->metadata().specifics_hash(); EXPECT_FALSE(entity->metadata().is_deleted()); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(1, entity->metadata().server_version()); EXPECT_LT(mtime_v0, mtime_v1); EXPECT_NE(specifics_hash_v0, specifics_hash_v1); EXPECT_EQ(specifics_hash_v0, entity->metadata().base_specifics_hash()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_TRUE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_TRUE(entity->HasCommitData()); // Make a commit. CommitRequestData request; entity->InitializeCommitRequestData(&request); EXPECT_EQ(kId, request.entity->id); EXPECT_FALSE(entity->RequiresCommitRequest()); // Ack the commit. entity->ReceiveCommitResponse(GenerateAckData(request, kId, 2)); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(1, entity->metadata().acked_sequence_number()); EXPECT_EQ(2, entity->metadata().server_version()); EXPECT_EQ(mtime_v1, entity->metadata().modification_time()); EXPECT_EQ(specifics_hash_v1, entity->metadata().specifics_hash()); EXPECT_EQ("", entity->metadata().base_specifics_hash()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->HasCommitData()); } // Test a local deletion of a synced item. TEST_F(ProcessorEntityTrackerTest, LocalDeletion) { std::unique_ptr<ProcessorEntityTracker> entity = CreateSynced(); const int64_t mtime = entity->metadata().modification_time(); const std::string specifics_hash = entity->metadata().specifics_hash(); // Make a local delete. entity->Delete(); EXPECT_TRUE(entity->metadata().is_deleted()); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_EQ(1, entity->metadata().server_version()); EXPECT_LT(mtime, entity->metadata().modification_time()); EXPECT_TRUE(entity->metadata().specifics_hash().empty()); EXPECT_EQ(specifics_hash, entity->metadata().base_specifics_hash()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_TRUE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->HasCommitData()); // Generate a commit request. The metadata should not change. const sync_pb::EntityMetadata metadata_v1 = entity->metadata(); CommitRequestData request; entity->InitializeCommitRequestData(&request); EXPECT_EQ(metadata_v1.SerializeAsString(), entity->metadata().SerializeAsString()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->HasCommitData()); const EntityData& data = request.entity.value(); EXPECT_EQ(kId, data.id); EXPECT_EQ(kHash, data.client_tag_hash); EXPECT_EQ("", data.non_unique_name); EXPECT_EQ(TimeToProtoTime(ctime_), TimeToProtoTime(data.creation_time)); EXPECT_EQ(entity->metadata().modification_time(), TimeToProtoTime(data.modification_time)); EXPECT_TRUE(data.is_deleted()); EXPECT_EQ(1, request.sequence_number); EXPECT_EQ(1, request.base_version); EXPECT_EQ(entity->metadata().specifics_hash(), request.specifics_hash); // Ack the deletion. entity->ReceiveCommitResponse(GenerateAckData(request, kId, 2)); EXPECT_TRUE(entity->metadata().is_deleted()); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(1, entity->metadata().acked_sequence_number()); EXPECT_EQ(2, entity->metadata().server_version()); EXPECT_EQ(metadata_v1.modification_time(), entity->metadata().modification_time()); EXPECT_TRUE(entity->metadata().specifics_hash().empty()); EXPECT_TRUE(entity->metadata().base_specifics_hash().empty()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_TRUE(entity->CanClearMetadata()); EXPECT_FALSE(entity->HasCommitData()); } // Test that hashes and sequence numbers are handled correctly for the "commit // commit, ack ack" case. TEST_F(ProcessorEntityTrackerTest, LocalChangesInterleaved) { std::unique_ptr<ProcessorEntityTracker> entity = CreateSynced(); const std::string specifics_hash_v0 = entity->metadata().specifics_hash(); // Make the first change. entity->MakeLocalChange(GenerateEntityData(kHash, kName, kValue2)); const std::string specifics_hash_v1 = entity->metadata().specifics_hash(); EXPECT_EQ(1, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_NE(specifics_hash_v0, specifics_hash_v1); EXPECT_EQ(specifics_hash_v0, entity->metadata().base_specifics_hash()); // Request the first commit. CommitRequestData request_v1; entity->InitializeCommitRequestData(&request_v1); // Make the second change. entity->MakeLocalChange(GenerateEntityData(kHash, kName, kValue3)); const std::string specifics_hash_v2 = entity->metadata().specifics_hash(); EXPECT_EQ(2, entity->metadata().sequence_number()); EXPECT_EQ(0, entity->metadata().acked_sequence_number()); EXPECT_NE(specifics_hash_v1, specifics_hash_v2); EXPECT_EQ(specifics_hash_v0, entity->metadata().base_specifics_hash()); // Request the second commit. CommitRequestData request_v2; entity->InitializeCommitRequestData(&request_v2); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_TRUE(entity->HasCommitData()); // Ack the first commit. entity->ReceiveCommitResponse(GenerateAckData(request_v1, kId, 2)); EXPECT_EQ(2, entity->metadata().sequence_number()); EXPECT_EQ(1, entity->metadata().acked_sequence_number()); EXPECT_EQ(2, entity->metadata().server_version()); EXPECT_EQ(specifics_hash_v2, entity->metadata().specifics_hash()); EXPECT_EQ(specifics_hash_v1, entity->metadata().base_specifics_hash()); EXPECT_TRUE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_TRUE(entity->HasCommitData()); // Ack the second commit. entity->ReceiveCommitResponse(GenerateAckData(request_v2, kId, 3)); EXPECT_EQ(2, entity->metadata().sequence_number()); EXPECT_EQ(2, entity->metadata().acked_sequence_number()); EXPECT_EQ(3, entity->metadata().server_version()); EXPECT_EQ(specifics_hash_v2, entity->metadata().specifics_hash()); EXPECT_EQ("", entity->metadata().base_specifics_hash()); EXPECT_FALSE(entity->IsUnsynced()); EXPECT_FALSE(entity->RequiresCommitRequest()); EXPECT_FALSE(entity->RequiresCommitData()); EXPECT_FALSE(entity->CanClearMetadata()); EXPECT_FALSE(entity->HasCommitData()); } } // namespace syncer
[ "support@opentext.com" ]
support@opentext.com
a468f75b79c5bbb8ae13ec9a2f869013b77b1cea
f8c69330231784fa08cf70b04a9c6e9211813582
/ProblemSolving/easy/ElectronicsShop/electronicsShop.cpp
b190956fbc5b2e1244ef20abdc22d2af58c50d07
[]
no_license
paul-nema/hackerrank
71c1f2b5340741dab354b830c57e3cd1db38bc39
3660fce336277034dc94d27feed72bbf412276b5
refs/heads/master
2020-03-30T05:49:50.467010
2019-03-02T13:09:16
2019-03-02T13:09:16
150,822,037
0
0
null
null
null
null
UTF-8
C++
false
false
2,608
cpp
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); /* * Complete the getMoneySpent function below. */ // b: budget int getMoneySpent(vector<int> keyboards, vector<int> drives, int b) { int bestDeal{ -1 }; int prev{ b }; int remaining; for( auto const keyboard: keyboards ) { for( auto const drive: drives ) { remaining = b - ( keyboard + drive ); if( remaining >= 0 && remaining < prev ) { if( remaining == 0 ) { return( b ); // return first deal that uses the whole budget } bestDeal = remaining; prev = remaining; } } } return( bestDeal == -1 ? -1 : b - bestDeal ); } int main() { string bnm_temp; getline(cin, bnm_temp); vector<string> bnm = split_string(bnm_temp); int b = stoi(bnm[0]); int n = stoi(bnm[1]); int m = stoi(bnm[2]); string keyboards_temp_temp; getline(cin, keyboards_temp_temp); vector<string> keyboards_temp = split_string(keyboards_temp_temp); vector<int> keyboards(n); for (int keyboards_itr = 0; keyboards_itr < n; keyboards_itr++) { int keyboards_item = stoi(keyboards_temp[keyboards_itr]); keyboards[keyboards_itr] = keyboards_item; } string drives_temp_temp; getline(cin, drives_temp_temp); vector<string> drives_temp = split_string(drives_temp_temp); vector<int> drives(m); for (int drives_itr = 0; drives_itr < m; drives_itr++) { int drives_item = stoi(drives_temp[drives_itr]); drives[drives_itr] = drives_item; } /* * * The maximum amount of money she can spend on a keyboard and USB * drive, or -1 if she can't purchase both items * */ int moneySpent = getMoneySpent(keyboards, drives, b); cout << moneySpent << "\n"; return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [](const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back( input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
[ "paul.nema@gmail.com" ]
paul.nema@gmail.com
26b67488e84e3bd8943f2b2b3565af5d8458f2e7
da3c59e9e54b5974648828ec76f0333728fa4f0c
/mobilemessaging/smilui/playersrc/SmilPlayerLinkParser.cpp
efec80a2272d0f3b3b70ff4d9999bdcd954e6383
[]
no_license
finding-out/oss.FCL.sf.app.messaging
552a95b08cbff735d7f347a1e6af69fc427f91e8
7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c
refs/heads/master
2022-01-29T12:14:56.118254
2010-11-03T20:32:03
2010-11-03T20:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
cpp
/* * Copyright (c) 2003-2005 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * Parses wanted string: * Phone numbers * E-mail addresses * URL addresses * */ // INCLUDE FILES #include "SmilPlayerLinkParser.h" // Url Address' beginnings _LIT( KHttpUrlAddress, "http://"); _LIT( KRtspUrlAddress, "rtsp://"); _LIT( KHttpsUrlAddress, "https://"); _LIT( KWwwUrlAddress, "www."); _LIT( KWapUrlAddress, "wap."); // ============================ MEMBER FUNCTIONS =============================== // ---------------------------------------------------------------------------- // CSmilPlayerLinkParser::LinkType // Returns given link type. // ---------------------------------------------------------------------------- // SmilPlayerLinkParser::TSmilPlayerLinkType SmilPlayerLinkParser::LinkType( const TDesC& aText ) { TSmilPlayerLinkType result( ESmilPlayerNotSupported ); if ( SearchMailAddress( aText ) ) { result = ESmilPlayerMailAddress; } if ( SearchUrl( aText ) ) { result = ESmilPlayerUrlAddress; } if ( SearchPhoneNumber( aText ) ) { result = ESmilPlayerPhoneNumber; } return result; } // ---------------------------------------------------------------------------- // CSmilPlayerLinkParser::ParseUrl // Parses URL from given text string. // ---------------------------------------------------------------------------- // TBool SmilPlayerLinkParser::ParseUrl( const TDesC& aType, const TDesC& aText ) { if( aText.Length() >= aType.Length() ) { if( aText.Left( aType.Length() ).MatchF( aType ) != KErrNotFound ) { return ETrue; } } return EFalse; } // ---------------------------------------------------------------------------- // SmilPlayerLinkParser::SearchMailAddress // Returns whether given string contains mail address. // ---------------------------------------------------------------------------- // TBool SmilPlayerLinkParser::SearchMailAddress( const TDesC& aText ) { if( aText.Length() >= KMailToString().Length() ) { if( aText.Left( KMailToString().Length() ).MatchF( KMailToString ) != KErrNotFound ) { return ETrue; } } return EFalse; } // ---------------------------------------------------------------------------- // SmilPlayerLinkParser::SearchPhoneNumber // Returns whether given string contains phone number. // ---------------------------------------------------------------------------- // TBool SmilPlayerLinkParser::SearchPhoneNumber( const TDesC& aText ) { if( aText.Length() >= KPhoneToString().Length() ) { if( aText.Left( KPhoneToString().Length() ).MatchF( KPhoneToString ) != KErrNotFound ) { return ETrue; } } return EFalse; } // ---------------------------------------------------------------------------- // SmilPlayerLinkParser::SearchUrl // Returns whether given string contains URL address. // ---------------------------------------------------------------------------- // TBool SmilPlayerLinkParser::SearchUrl( const TDesC& aText ) { TBool wasValidUrl = EFalse; // Search for http:// wasValidUrl = ParseUrl( KHttpUrlAddress, aText ); if ( !wasValidUrl ) { // Search for https:// wasValidUrl = ParseUrl( KHttpsUrlAddress, aText ); } if ( !wasValidUrl ) { // Search for rtsp:// wasValidUrl = ParseUrl( KRtspUrlAddress, aText ); } if ( !wasValidUrl ) { // Search for www. wasValidUrl = ParseUrl( KWwwUrlAddress, aText ); } if ( !wasValidUrl ) { // Search for wap. wasValidUrl = ParseUrl( KWapUrlAddress, aText ); } return wasValidUrl; } // End of File
[ "none@none" ]
none@none
d520f43cd8566e87bce501dd6088cedb5ee33392
b5e1da7261a18adde3dbf041e6fd20d846d57ef5
/src/dynamic_load_balance.cpp
d6a5b92e22e0c670fb86daac5c8b406d3ec8e7a0
[]
no_license
mlunacek/load_balance
0b35844c7b48a2a2be853c292ff1cdd9751a8f4e
cd44a7b329b1a237b6a7f96b238550e124bebf24
refs/heads/master
2021-01-02T23:13:07.547419
2012-08-31T20:20:32
2012-08-31T20:20:32
4,788,080
1
0
null
2012-08-31T20:20:34
2012-06-25T22:06:38
null
UTF-8
C++
false
false
1,732
cpp
#include "dynamic_load_balance.hpp" dynamic_load_balance::dynamic_load_balance(const std::string &filename, mpi::communicator &comm): load_balance(filename, comm) { } dynamic_load_balance::~dynamic_load_balance() { } void dynamic_load_balance::execute() { if( m_comm.rank() == 0 ) { if( m_comm.size() == 1) serial(); else master(); } else worker(); } void dynamic_load_balance::master() { // Give them another when ready... bool ready; int recv_count = 0; for(int index=0; index < m_jobs.size(); ++index) { mpi::status msg = m_comm.probe(); if (msg.tag() == msg_rank_ready) { recv_count++; m_comm.recv(msg.source(), msg.tag(), ready); m_comm.send(msg.source(), msg_data_packet, m_jobs[index]); } } //if the number of jobs is less than processor counts.. for( recv_count; recv_count< m_comm.size(); ++recv_count) { mpi::status msg = m_comm.probe(); if (msg.tag() == msg_rank_ready) m_comm.recv(msg.source(), msg.tag(), ready); } // Tell the workers we are finished bool done = true; for(int r=1; r<m_comm.size(); ++r) m_comm.send(r, msg_finished, done); } void dynamic_load_balance::worker() { // Ready for work... bool ready = true; m_comm.send(0, msg_rank_ready, ready); bool done = false; while( !done) { mpi::status msg = m_comm.probe(); if (msg.tag() == msg_data_packet) { // Receive the packet of data std::string cmd; m_comm.recv(msg.source(), msg.tag(), cmd); //std::cout << cmd << std::endl; system(cmd.c_str()); // Ready m_comm.send(0, msg_rank_ready, ready); } else if( msg.tag() == msg_finished ) { m_comm.recv(msg.source(), msg.tag(), done); } } }
[ "monte.lunacek@gmail.com" ]
monte.lunacek@gmail.com
1eeef5a65fcb4e109f6f9a40377b2e1eb55b419b
1fdd0647dea9328042757624884b0d4284d4b327
/Client/CPlayerState.h
8f2cf4185eec73173ff4361b2e95161cb9bafc03
[]
no_license
moonseokchoi-kr/CupheadCloneGame
4800858b1c1363ca5e69d3d0328c028a34a2bdef
da2318cc82182abe44adee7cd180902ae44b2d99
refs/heads/master
2023-08-21T08:05:44.398782
2021-10-10T10:47:37
2021-10-10T10:47:37
394,128,076
0
0
null
null
null
null
UTF-8
C++
false
false
728
h
#pragma once class CPlayer; class CPlayerStateMachine; class CSound; class CPlayerState { public: CPlayerState(PLAYER_STATE _state); virtual ~CPlayerState(); public: CPlayerStateMachine* GetAI() { return m_ai; } PLAYER_STATE GetState() { return m_state; } CPlayer* GetPlayer(); PLAYER_STATE GetSubState() { return m_subState; } public: virtual void Enter() = 0; virtual void Exit() = 0; virtual void Update() = 0; public: void SetSFX(const wstring& _name); CSound* GetSFX() { return m_sfx; } protected: virtual void updateSubState(){} virtual void updateAnimation() {} PLAYER_STATE m_subState; private: CPlayerStateMachine* m_ai; PLAYER_STATE m_state; CSound* m_sfx; friend class CPlayerStateMachine; };
[ "moonseoktech@gmail.com" ]
moonseoktech@gmail.com