blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
8227c81c7e6bcde73c4716e35537a6d0aea08382
f2e4ed7d954feea8fc93076fd7bc3a79f6dd4995
/purenessscopeserver/purenessscopeserver/PurenessScopeServer/Common/ServerMessageTask.h
18075d03824f924c33619114d8c676b2034613eb
[]
no_license
ZGH1204/PSS
b0c3abe1f9064cc17f3b143bb8a7f451c54981b3
3ff406f9b9ba3afed6bfdaefdeb91b7f108d2109
refs/heads/master
2021-09-08T07:55:20.716549
2016-06-27T09:04:50
2016-06-27T09:04:50
null
0
0
null
null
null
null
GB18030
C++
false
false
2,796
h
#ifndef _SERVERMESSAGETASK_H #define _SERVERMESSAGETASK_H #include "define.h" #include "ace/Task.h" #include "ace/Synch.h" #include "ace/Malloc_T.h" #include "ace/Singleton.h" #include "ace/Thread_Mutex.h" #include "ace/Date_Time.h" #include "IClientManager.h" #include "MessageBlockManager.h" //处理服务器间接收数据包过程代码 //如果服务器间线程处理挂起了,会尝试重启服务 //add by freeeyes #define MAX_SERVER_MESSAGE_QUEUE 1000 //允许最大队列长度 #define MAX_DISPOSE_TIMEOUT 30 //允许最大等待处理时间 //服务器间通讯的数据结构(接收包) struct _Server_Message_Info { IClientMessage* m_pClientMessage; uint16 m_u2CommandID; ACE_Message_Block* m_pRecvFinish; _ClientIPInfo m_objServerIPInfo; _Server_Message_Info() { m_u2CommandID = 0; m_pClientMessage = NULL; m_pRecvFinish = NULL; } }; //服务器间数据包消息队列处理过程 class CServerMessageTask : public ACE_Task<ACE_MT_SYNCH> { public: CServerMessageTask(); ~CServerMessageTask(); virtual int open(void* args = 0); virtual int svc (void); virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); bool Start(); int Close(); bool IsRun(); uint32 GetThreadID(); bool PutMessage(_Server_Message_Info* pMessage); bool CheckServerMessageThread(ACE_Time_Value tvNow); void AddClientMessage(IClientMessage* pClientMessage); void DelClientMessage(IClientMessage* pClientMessage); private: bool CheckValidClientMessage(IClientMessage* pClientMessage); bool ProcessMessage(_Server_Message_Info* pMessage, uint32 u4ThreadID); private: uint32 m_u4ThreadID; //当前线程ID bool m_blRun; //当前线程是否运行 uint32 m_u4MaxQueue; //在队列中的数据最多个数 EM_Server_Recv_State m_emState; //处理状态 ACE_Time_Value m_tvDispose; //接收数据包处理时间 //记录当前有效的IClientMessage,因为是异步的关系。 //这里必须保证回调的时候IClientMessage是合法的。 typedef vector<IClientMessage*> vecValidIClientMessage; vecValidIClientMessage m_vecValidIClientMessage; }; class CServerMessageManager { public: CServerMessageManager(); ~CServerMessageManager(); void Init(); bool Start(); int Close(); bool PutMessage(_Server_Message_Info* pMessage); bool CheckServerMessageThread(ACE_Time_Value tvNow); void AddClientMessage(IClientMessage* pClientMessage); void DelClientMessage(IClientMessage* pClientMessage); private: CServerMessageTask* m_pServerMessageTask; ACE_Recursive_Thread_Mutex m_ThreadWritrLock; }; typedef ACE_Singleton<CServerMessageManager, ACE_Recursive_Thread_Mutex> App_ServerMessageTask; #endif
a18c01f915c0d808fb9ef811823a151539918897
bd9e44aaf5f569725310d72c19a4638b3bb8c9d5
/day01/ex08/Human.cpp
fa3932b3ba272c2c136b57b4e17cd2055c03ef04
[]
no_license
nvd-ros/CPP_Piscine
5580bce13275212246ce01135350c0f5c8d34cd5
a1194b9cce521b306096ea34cd51df1c05e82928
refs/heads/master
2022-01-09T02:45:35.227517
2019-07-05T10:43:14
2019-07-05T10:43:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Human.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rnovodra <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/03 16:26:37 by rnovodra #+# #+# */ /* Updated: 2018/10/03 16:26:37 by rnovodra ### ########.fr */ /* */ /* ************************************************************************** */ #include "Human.hpp" #include <map> typedef void (Human::*ptr_fun)(std::string const &); void Human::meleeAttack(std::string const & target) { std::cout << "Kgh!!! to " << target << std::endl; return ; } void Human::rangedAttack(std::string const & target) { std::cout << "AVADA KEDAVRA to " << target << std::endl; return ; } void Human::intimidatingShout(std::string const & target) { std::cout << "FUS RO DAH!!! to " << target << std::endl; return ; } void Human::action(std::string const & action_name, std::string const & target) { std::map<std::string, ptr_fun> m; m.insert(std::make_pair("melee", &Human::meleeAttack)); m.insert(std::make_pair("ranged", &Human::rangedAttack)); m.insert(std::make_pair("shout", &Human::intimidatingShout)); ptr_fun ptr = m[action_name]; (this->*ptr)(target); return ; }
dde622b6938d1a56b571044eb331492a7599040b
60d0b32a4b5c121d73287d1f84357d1ea7f812b8
/DAQlml/DAQcomedi.h
7480d33176f8ac7961957733798a603e772d60e4
[]
no_license
carobraud/DAQlml
b70179b9b1388cb5fd5989bfff835f1ffe036f60
8a085ecf00c1923a1c00224e2fb08b47a94f3ca3
refs/heads/master
2016-09-05T18:04:47.920781
2013-04-12T17:40:50
2013-04-12T17:40:50
9,399,955
0
1
null
null
null
null
UTF-8
C++
false
false
16,889
h
#ifndef DAQ_COMEDI #define DAQ_COMEDI //!acquisition device /** * acquisition device to record multiple 1D channels through comedi library * \note member names were initially based on \c option structure from comedi demo examples **/ class DAQdevice { public://! \todo [YN] use setter and getter ! int verbose; ///< verbose option std::string filename;///< device file name comedi_t *dev; ///< pointer to device comedi_range *comedirange; ///< pointer to comedirange; comedi_cmd c,*cmd; ///< comedi command int subdevice; ///< subdevice id int aref; ///< reference, GROUND or DIFFERENCE int bufsize; ///< board buffer size int maxdata; ///< max value of voltage unsigned int chanlist[256]; ///< channellist corresponding to the channel index int sample_number; ///< sample number int sampling_rate; ///< sampling rate int range_id; ///< range id; std::vector<std::string> channel_name; ///< channel name std::vector<int> channel_index; ///< channel index //! constructor //! \todo subdevice and aref should be configurable somewhere? DAQdevice() { initDAQdevice(); } DAQdevice(std::string dev_filename,bool buffer=true) { filename=dev_filename; initDAQdevice(); } // !/todo add variable subdevice: 0 for read and 1 for write void initDAQdevice() { subdevice=0; aref=AREF_GROUND; cmd = &c; } //! set unsigned int chanlist from channel_index, range and aref void setchannellist() { for(unsigned int i = 0; i < channel_index.size(); i++){ chanlist[i] = CR_PACK(channel_index[i], range_id, aref); } } //! print on \c given stream all member values void print(std::ostream &stream) { stream<<"comedi version code: "<<comedi_get_version_code(dev)<<std::endl; stream<<"device file: "<<filename<<std::endl; stream<<"driver name: "<<comedi_get_driver_name(dev)<<std::endl; stream<<"board name: "<<comedi_get_board_name(dev)<<std::endl; stream<<"subdevice id: " << subdevice << "\n"; int type = comedi_get_subdevice_type(dev, subdevice); stream<<"subdevice type: "; switch(type) { case 0: stream<<"unused"<<std::endl; break; case 1: stream<<"analog input"<<std::endl; break; case 2: stream<<"analog output"<<std::endl; break; } stream<<"number of channels: "<<channel_index.size()<<std::endl; stream<<"channels: "; for(unsigned int i=0; i<channel_index.size(); i++){ stream<<chanlist[i]<<" "; } stream<<std::endl; stream<<"analog reference id: "<<aref<<std::endl; std::cerr<<"analog reference: "; switch(aref) { case AREF_GROUND: std::cerr<<"AREF_GROUND"<<std::endl;break; case AREF_COMMON: std::cerr<<"AREF_COMMON"<<std::endl;break; case AREF_DIFF: std::cerr<<"AREF_DIFF"<<std::endl;break; case AREF_OTHER: std::cerr<<"AREF_OTHER"<<std::endl;break; } show_range(stream); //stream<<"convert binary to voltage: "<<physical<<std::endl; stream<<"number of samples: "<<sample_number<<std::endl; stream<<"sampling rate: "<<sampling_rate<<" Hz"<<std::endl; // dump command if(verbose) { std::cout<<"start_arg: "<< cmd->start_arg <<std::endl; std::cout<<"scan_begin_arg: "<< cmd->scan_begin_arg <<std::endl; std::cout<<"convert_arg: "<< cmd->convert_arg <<std::endl; std::cout<<"scan_end_arg: "<< cmd->scan_end_arg <<std::endl; std::cout<<"stop_arg: "<< cmd->stop_arg <<std::endl; } } //! print on standard output void print() { print(std::cout); } //! print voltage range information int show_range(std::ostream &stream) { ///- show minimum and maximum of the range stream<<"range=["<<comedirange->min<<".."<<comedirange->max<<"] ("; ///- show unit of the range std::string unit_name; switch(comedirange->unit) { case UNIT_volt: unit_name="volts"; break; case UNIT_mA: unit_name="milliamps"; break; case UNIT_none: default: unit_name="none"; break; }//switch unit stream<<unit_name<<")\n"; return 0; } //! load acquisition parameter from file /** * load acquisition parameters from NetCDF file (i.e. .CDL; ncgen -o parameters.nc parameters.cdl): such as sampling conditions. * The program user should specify all program parameters within this .CDL file. * \param [in] file_name NetCDF/CDL parameter file name (e.g. file named "~/acquisition/parameters.nc") * \see show_range **/ int load_parameter(const std::string file_name) { //NetCDF/CDL parameter file object (i.e. parameter class) CParameterNetCDF fp; ///open file from its name int error=fp.loadFile((char *)file_name.c_str()); if(error){std::cerr<<"loadFile return "<< error <<std::endl;return error;} ///open acquisition variable (i.e. process variable) //prepare to load parameters as the attribute of "acquisition" //! \bug \c process should be \c int or \c byte instead of \c float float process; std::string process_name="acquisition"; if((error=fp.loadVar(process,&process_name))){std::cerr<<"Error: process variable \""<<process_name<<"\" can not be loaded (return value is "<<error<<")\n";return error;} ///load attributes (i.e. process parameters) // load parameters as process attributes //! \todo [low] add error messages for all attributes fp.loadAttribute("channels",channel_index); fp.loadAttribute("channel_name",channel_name); fp.loadAttribute("sampling_rate",sampling_rate); fp.loadAttribute("number_of_samples",sample_number); fp.loadAttribute("range_id",range_id); setchannellist(); return 0; } //! prepare commands to the board /** * prepare command for the board **/ int prepare_cmd() { unsigned period_nanosec=(unsigned)(1e9/sampling_rate); memset(cmd,0,sizeof(*cmd)); cmd->subdev = subdevice; cmd->flags = 0; //! start the measurement immediately //! one can specify TRIG_EXT for external trigerring //! \todo cmd->start_src should be configurable by parameter.nc cmd->start_src = TRIG_NOW; cmd->start_arg = 0; // set the board sampling rate (see comedi website) cmd->scan_begin_src = TRIG_TIMER; cmd->scan_begin_arg = period_nanosec; // set waiting time for A/D convertion to be minimum // this should be corrected in command test cmd->convert_src = TRIG_TIMER; cmd->convert_arg = 1; // set number of channels cmd->scan_end_src = TRIG_COUNT; cmd->scan_end_arg = channel_index.size(); // set number of scans cmd->stop_src = TRIG_COUNT; cmd->stop_arg = sample_number; // set channel list cmd->chanlist = chanlist; cmd->chanlist_len = channel_index.size(); return 0; } //! configure device (A/D board) and prepare to start the operation /** * * @param map pointer to mapped memory region * * @return **/ int config_device_common() { int sdflag; /// subdevice flag // load thee device file dev = comedi_open(filename.c_str()); if(!(dev)){ comedi_perror(filename.c_str()); exit(1); } // check subdevice flag before using it sdflag = comedi_get_subdevice_flags(dev, subdevice); std::cout<<std::showbase; if (verbose) std::cout<<"subdevice flag: "<<std::hex<<sdflag<<std::dec<<std::endl; // get max data and range. these will be used to convert 16bit integer binary to physical voltage maxdata = comedi_get_maxdata(dev, subdevice,channel_index.front()); comedirange = comedi_get_range(dev, subdevice,channel_index.front(),range_id); if(verbose) std::cout<<"maxdata:"<<maxdata<<", min:"<<(comedirange)->min<<", max:"<<(comedirange)->max<<", unit:"<<(comedirange)->unit<<std::endl; return 0; }//config_device_common int config_device_point() { return config_device_common(); }//config_device_point int config_device_specific_buffer(void *&map) { int ret; // get the buffer size of the subdevice bufsize = comedi_get_buffer_size(dev, subdevice); if(verbose) std::cout<<"buffer size is "<<bufsize<<std::endl; // map device buffer to main memory through device file /dev/comedi0 // option MAP_SHARED means updating memory contents when the file (/dev/comedi0) is updated. // (this means buffer and memory are linked??) // mmap(*addr, size, prot, flags, fd, offset) is the system function. map = mmap(NULL, bufsize, PROT_READ, MAP_SHARED, comedi_fileno(dev), 0); if( verbose ) std::cout<<"pointer to mapped region: "<<std::hex<<map<<std::dec<<std::endl; if( map == MAP_FAILED ){ perror( "mmap" ); exit(1); } // this function should be called twice. ret = comedi_command_test(dev, cmd); ret = comedi_command_test(dev, cmd); if(ret != 0){ fprintf(stderr,"command_test failed\n"); exit(1); } // check actual sampling frequency is the same as the user specified int actual_freq=1e9/cmd->scan_begin_arg; if(sampling_rate != actual_freq) { std::cerr<<"please check the sampling rate."<<std::endl; std::cerr<<"user specified sampling freq: "<<sampling_rate<<" Hz"<<std::endl; std::cerr<<" actual sampling freq: "<<actual_freq<<" Hz"<<std::endl; exit(1); } // send the command to the board ret = comedi_command(dev, cmd); if(ret < 0) { comedi_perror("comedi_command"); exit(1); } return 0; }//config_device_specific_buffer int config_device_buffer(void *&map) { int ret; prepare_cmd(); // prepare command to the board; if((ret=config_device_common())!=0) return ret; return config_device_specific_buffer(map); }//config_device_buffer };//DAQdevice class //! display help options /** * * * \code * print_help(std::cout); * \endcode * @return */ //! \todo [low] should be in DAQdevice class int print_help(std::ostream &stream) { stream<<""; return 0; } //! convert integer 16bit binary data into float physical voltage /** * * * @param [in] data integer binary * @param [inout] data_phys physical voltage * @param [in] DAQdev DAQdevice object * * @return */ template <typename Tacquisition, typename Tphysical> int convert_to_phys(cimg_library::CImgList<Tacquisition>& data, cimg_library::CImgList<Tphysical>& data_phys, DAQdevice DAQdev) { data_phys.assign(data); cimglist_for(data,c) { cimg_forX(data[c],s) { data_phys[c](s)=comedi_to_phys(data[c](s), DAQdev.comedirange, DAQdev.maxdata); } } return 0; } //! convert float physical voltage into integer 16bit binary data /** * * * @param data integer binary * @param data_phys physical voltage * @param [inout] DAQdev DAQdevice object * * @return */ template <typename Tacquisition, typename Tphysical> int convert_from_phys(cimg_library::CImgList<Tphysical>& data_phys, cimg_library::CImgList<Tacquisition>& data, DAQdevice DAQdev, const bool assign=true) { if(assign) data.assign(data_phys); cimglist_for(data_phys,c) { cimg_forX(data_phys[c],s) { data[c](s)=comedi_from_phys(data_phys[c](s), DAQdev.comedirange, DAQdev.maxdata); } } return 0; } //! create time corresponding to each sample /** * create time corresponding to each sample * the delay between channels is also taken into account * * @param[in] data * @param[out] time * @param[in,out] DAQdev * @param sampling_rate * * @return */ template <typename Tdata, typename Ttime> int create_time(cimg_library::CImgList<Tdata>& data, cimg_library::CImgList<Ttime>& time, DAQdevice DAQdev) { //get minimum convert time of the board int min_convert_time=DAQdev.cmd->convert_arg; // in nano second //std::cerr<<__FILE__<<"/"<<__func__<<"(...)\n"<<std::flush; //data.print("data"); //PR(board_frequency); //PR(sampling_rate); //allocate time structure time.assign(data); //time.print("time"); double cdelay=1e-9*(double)min_convert_time;//delay between channels double present_time=0.0; cimg_forX(time[0],s) { cimglist_for(time,c) { time[c](s)=present_time+cdelay*c; // time of a channel is delayed depending on c } present_time+=1/(double)DAQdev.sampling_rate; } return 0; } //! subfunction of char *cmd_src(int src,char *buf) { buf[0]=0; if(src&TRIG_NONE)strcat(buf,"none|"); if(src&TRIG_NOW)strcat(buf,"now|"); if(src&TRIG_FOLLOW)strcat(buf, "follow|"); if(src&TRIG_TIME)strcat(buf, "time|"); if(src&TRIG_TIMER)strcat(buf, "timer|"); if(src&TRIG_COUNT)strcat(buf, "count|"); if(src&TRIG_EXT)strcat(buf, "ext|"); if(src&TRIG_INT)strcat(buf, "int|"); #ifdef TRIG_OTHER if(src&TRIG_OTHER)strcat(buf, "other|"); #endif if(strlen(buf)==0){ sprintf(buf,"unknown(0x%08x)",src); }else{ buf[strlen(buf)-1]=0; } return buf; } char *tobinary(char *s,int bits,int n) { int bit=1<<n; char *t=s; for(;bit;bit>>=1) *t++=(bits&bit)?'1':'0'; *t=0; return s; } void probe_max_1chan(comedi_t *it,int s) { comedi_cmd cmd; char buf[100]; printf(" command fast 1chan:\n"); if(comedi_get_cmd_generic_timed(it, s, &cmd, 1, 1)<0){ printf(" not supported\n"); }else{ printf(" start: %s %d\n", cmd_src(cmd.start_src,buf),cmd.start_arg); printf(" scan_begin: %s %d\n", cmd_src(cmd.scan_begin_src,buf),cmd.scan_begin_arg); printf(" convert: %s %d\n", cmd_src(cmd.convert_src,buf),cmd.convert_arg); printf(" scan_end: %s %d\n", cmd_src(cmd.scan_end_src,buf),cmd.scan_end_arg); printf(" stop: %s %d\n", cmd_src(cmd.stop_src,buf),cmd.stop_arg); } } void get_command_stuff(comedi_t *it,int s) { comedi_cmd cmd; char buf[100]; if(comedi_get_cmd_src_mask(it,s,&cmd)<0){ printf(" not supported\n"); }else{ printf(" start: %s\n",cmd_src(cmd.start_src,buf)); printf(" scan_begin: %s\n",cmd_src(cmd.scan_begin_src,buf)); printf(" convert: %s\n",cmd_src(cmd.convert_src,buf)); printf(" scan_end: %s\n",cmd_src(cmd.scan_end_src,buf)); printf(" stop: %s\n",cmd_src(cmd.stop_src,buf)); probe_max_1chan(it,s); } } int get_board_info(std::string fd, bool verbose) { std::vector<std::string> subdevice_types; subdevice_types.push_back("unused"); subdevice_types.push_back("analog input"); subdevice_types.push_back("analog output"); subdevice_types.push_back("digital input"); subdevice_types.push_back("digital output"); subdevice_types.push_back("digital I/O"); subdevice_types.push_back("counter"); subdevice_types.push_back("timer"); subdevice_types.push_back("memory"); subdevice_types.push_back("calibration"); subdevice_types.push_back("processor"); subdevice_types.push_back("serial digital I/O"); comedi_t *it; int i,j; int n_subdevices, type; int chan, n_chans; int n_ranges; int subdev_flags; comedi_range *rng; comedi_cmd cmd; it=comedi_open((char*)fd.c_str()); std::cout<<"version code: "<<comedi_get_version_code(it)<<std::endl; std::cout<<"device file: "<<fd<<std::endl; std::cout<<"driver name: "<<comedi_get_driver_name(it)<<std::endl; std::cout<<"board name: "<<comedi_get_board_name(it)<<std::endl; comedi_get_cmd_generic_timed(it, 0, &cmd, 1, 1); // assuming analog input is channel 0 int min_convert_time=cmd.convert_arg; if(verbose) { n_subdevices=comedi_get_n_subdevices(it); std::cout<<"number of subdevices: "<<n_subdevices<<std::endl; for(i = 0; i < n_subdevices; i++){ printf("subdevice %d:\n",i); type = comedi_get_subdevice_type(it, i); std::cout<<" type:"<<type<<subdevice_types[type]<<std::endl; if(type==COMEDI_SUBD_UNUSED) return 0; subdev_flags = comedi_get_subdevice_flags(it, i); printf(" flags: 0x%08x\n",subdev_flags); n_chans=comedi_get_n_channels(it,i); printf(" number of channels: %d\n",n_chans); if(!comedi_maxdata_is_chan_specific(it,i)){ printf(" max data value: %lu\n", (unsigned long)comedi_get_maxdata(it,i,0)); }else{ printf(" max data value: (channel specific)\n"); for(chan=0;chan<n_chans;chan++){ printf(" chan%d: %lu\n",chan, (unsigned long)comedi_get_maxdata(it,i,chan)); } } printf(" ranges:\n"); if(!comedi_range_is_chan_specific(it,i)){ n_ranges=comedi_get_n_ranges(it,i,0); printf(" all chans:"); for(j=0;j<n_ranges;j++){ rng=comedi_get_range(it,i,0,j); printf(" [%g,%g]",rng->min,rng->max); } printf("\n"); }else{ for(chan=0;chan<n_chans;chan++){ n_ranges=comedi_get_n_ranges(it,i,chan); printf(" chan%d:",chan); for(j=0;j<n_ranges;j++){ rng=comedi_get_range(it,i,chan,j); printf(" [%g,%g]",rng->min,rng->max); } printf("\n"); } } printf(" command:\n"); get_command_stuff(it,i); } }//verbose return min_convert_time; } #endif// DAQ_COMEDI
9572f5fe85db74e2fac20b36487f672d59d8039b
b4ef2a339222c756d1649d21c63543f7f7ed7cef
/src/qt/test/test_main.cpp
9795873fec838332fc27161fd54b29ce118c5fa1
[ "MIT" ]
permissive
caliburcoin/Crypto-Calibur
0a7fbca3709c2f387bf32495b8c086ce06b125a2
89d6eb7ec506455888b577ebe5dedb39d921881b
refs/heads/master
2020-05-23T09:50:06.914800
2019-05-31T16:36:31
2019-05-31T16:36:31
186,713,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/calibur-config.h" #endif #include "util.h" #include "uritests.h" #ifdef ENABLE_WALLET #include "paymentservertests.h" #endif #include <QCoreApplication> #include <QObject> #include <QTest> #include <openssl/ssl.h> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if defined(QT_QPA_PLATFORM_MINIMAL) Q_IMPORT_PLUGIN(QMinimalIntegrationPlugin); #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif extern void noui_connect(); // This is all you need to run all the tests int main(int argc, char *argv[]) { SetupEnvironment(); bool fInvalid = false; // Don't remove this, it's needed to access // QCoreApplication:: in the tests QCoreApplication app(argc, argv); app.setApplicationName("Calibur-Qt-test"); SSL_library_init(); URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; #ifdef ENABLE_WALLET PaymentServerTests test2; if (QTest::qExec(&test2) != 0) fInvalid = true; #endif return fInvalid; }
af5577bd2d626d42992592d1302c31237f0c7983
d6e7f725b5c813307cbeab5013e8606b664a7b0b
/src/ocg14/mips_cpu.cpp
a41637cd138008a30d200b0754dae5dff0d63351
[]
no_license
trueivorian/MIPS-Simulator
0bfe372f7916da12221b9212ee37382a58cbe083
e0fd67d3f7bd9e6463a1677ed089359c3b6fb055
refs/heads/master
2022-09-26T06:25:54.135551
2020-06-04T01:18:47
2020-06-04T01:18:47
269,168,367
0
0
null
null
null
null
UTF-8
C++
false
false
16,928
cpp
#include "mips.h" #include "mips_cpu_decoder.h" #include "mips_cpu_alu.h" #include <iostream> using namespace std; struct mips_cpu_impl { uint32_t pc; uint32_t npc; uint32_t regs[32]; uint32_t hi; uint32_t lo; unsigned logLevel; FILE* logDst; mips_mem_h ram; }; mips_error fetch(mips_cpu_h state, uint32_t &instr); mips_error fetch_next(mips_cpu_h state, uint32_t &instr); mips_error execute(mips_cpu_h state, const uint32_t instr); mips_error mips_cpu_get_npc(mips_cpu_h state, uint32_t *npc); mips_error mips_cpu_set_npc(mips_cpu_h state, uint32_t npc); mips_cpu_h mips_cpu_create(mips_mem_h mem) { mips_cpu_impl *cpu = new mips_cpu_impl; cpu->ram = mem; cpu->pc = 0; cpu->npc = cpu->pc + 4; cpu->hi = 0; cpu->lo = 0; for(int i=0; i<=31; i++) { cpu->regs[i] = 0; } return cpu; } mips_error mips_cpu_reset(mips_cpu_h state) { if(!state) { return mips_ErrorInvalidHandle; } state->pc = 0; state->npc = 0; for(int i=0; i<=31; i++) { state->regs[i] = 0; } return mips_Success; } /*! Returns the current value of one of the 32 general purpose MIPS registers */ mips_error mips_cpu_get_register( // If we refer to this function we can access the register mips_cpu_h state, //!< Valid (non-empty) handle to a CPU unsigned index, //!< Index from 0 to 31 uint32_t *value //!< Where to write the value to ){ if(!state) { return mips_ErrorInvalidHandle; } *value = state->regs[index]; return mips_Success; } mips_error mips_cpu_set_register( mips_cpu_h state, //!< Valid (non-empty) handle to a CPU unsigned index, //!< Index from 0 to 31 uint32_t value //!< New value to write into register file ) { if(!state) { return mips_ErrorInvalidHandle; } state->regs[index] = value; return mips_Success; } mips_error mips_cpu_set_pc( mips_cpu_h state, //!< Valid (non-empty) handle to a CPU uint32_t pc //!< Address of the next instruction to exectute. ) { if(!state) { return mips_ErrorInvalidHandle; } state->pc = pc; state->npc = pc +4; return mips_Success; } mips_error mips_cpu_get_pc( mips_cpu_h state, //!< Valid (non-empty) handle to a CPU uint32_t *pc //!< Where to write the byte address too ) { if(!state) { return mips_ErrorInvalidHandle; } *pc = state->pc; return mips_Success; } mips_error mips_cpu_get_npc( mips_cpu_h state, //!< Valid (non-empty) handle to a CPU uint32_t *npc //!< Where to write the byte address too ) { if(!state) { return mips_ErrorInvalidHandle; } *npc = state->npc; return mips_Success; } mips_error mips_cpu_set_npc( mips_cpu_h state, //!< Valid (non-empty) handle to a CPU uint32_t npc //!< Valid (non-empty) handle to a CPU ) { if(!state) { return mips_ErrorInvalidHandle; } state->npc = npc; return mips_Success; } mips_error mips_cpu_set_accum(mips_cpu_h state, uint32_t hi, uint32_t lo) { mips_error err = mips_Success; err = mips_cpu_set_hi(state, hi); err = mips_cpu_set_lo(state, lo); return err; } mips_error mips_cpu_set_hi(mips_cpu_h state, uint32_t hi) { if(!state) { return mips_ErrorInvalidHandle; } state->hi = hi; return mips_Success; } mips_error mips_cpu_set_lo(mips_cpu_h state, uint32_t lo) { if(!state) { return mips_ErrorInvalidHandle; } state->lo = lo; return mips_Success; } mips_error mips_cpu_get_hi(mips_cpu_h state, uint32_t* hi) { if(!state) { return mips_ErrorInvalidHandle; } *hi = state->hi; return mips_Success; } mips_error mips_cpu_get_lo(mips_cpu_h state, uint32_t* lo) { if(!state) { return mips_ErrorInvalidHandle; } *lo = state->lo; return mips_Success; } mips_error mips_cpu_step( // this forwards the CPU by one instruction mips_cpu_h state //! Valid (non-empty) handle to a CPU ) { mips_error err = mips_Success; uint32_t instr = 0; // fetch err = fetch(state, instr); // execute err = execute(state, instr); err = mips_cpu_set_register(state, 0, 0); err = mips_cpu_set_pc(state, state->npc); return err; } mips_error fetch(mips_cpu_h state, uint32_t &instr) { mips_error err = mips_Success; uint8_t mem_buffer[4]; uint32_t pc = 0; err = mips_cpu_get_pc(state, &pc); err = mips_mem_read(state->ram, pc, 4, mem_buffer); instr = to_big(mem_buffer); return err; } mips_error fetch_next(mips_cpu_h state, uint32_t &instr) { mips_error err = mips_Success; uint8_t mem_buffer[4]; uint32_t npc = 0; err = mips_cpu_get_npc(state, &npc); err = mips_mem_read(state->ram, npc, 4, mem_buffer); return err; } mips_error mips_cpu_set_debug_level(mips_cpu_h state, unsigned level, FILE *dest) { state->logLevel = level; state->logDst = dest; return mips_Success; } void mips_cpu_free(mips_cpu_h state) { delete state; } mips_error execute(mips_cpu_h state, const uint32_t instr) { mips_error err = mips_Success; // Initialise variables uint32_t opcode = decode_opcode(instr); uint32_t rs = 0; uint32_t rt = 0; uint32_t rd = 0; uint32_t shift = 0; uint32_t func = 0; uint32_t addr = 0; uint32_t data = 0; if(opcode==0) { // r type shift = decode_shift(instr); func = decode_func(instr); err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); switch(func) { case 0x20: cout << "ADD $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; if(shift != 0x0) { return mips_ExceptionInvalidInstruction; } err = ADD(rd, rs, rt); break; case 0x21: cout << "ADDU $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; if(shift != 0x0) { return mips_ExceptionInvalidInstruction; } err = ADDU(rd, rs, rt); break; case 0x24: cout << "AND $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; if(shift != 0x0) { return mips_ExceptionInvalidInstruction; } err = AND(rd, rs, rt); break; case 0x1A: cout << "DIV $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; if(!rt) { return mips_ExceptionInvalidInstruction; } err = DIV(state, rs, rt); break; case 0x1B: cout << "DIVU $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = DIVU(state, rs, rt); break; case 0x05: cout << "JALR $" << decode_rd(instr) << ", $" << decode_rs(instr) << endl; err = JALR(state, rd, rs); break; case 0x08: cout << "JR $" << decode_rs(instr) << endl; err = JR(state, rs); break; case 0x10: cout << "MFHI $" << decode_rd(instr) << endl; err = MFHI(state, rd); break; case 0x12: cout << "MFLO $" << decode_rd(instr) << endl; err = MFLO(state, rd); break; case 0x11: cout << "MTHI $" << decode_rs(instr) << endl; err = MTHI(state, rd); break; case 0x13: cout << "MTLO $" << decode_rs(instr) << endl; err = MFLO(state, rs); break; case 0x18: cout << "MULT $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = MULT(state, rs, rt); break; case 0x19: cout << "MULTU $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = MULTU(state, rs, rt); break; case 0x25: cout << "OR $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = OR(rd, rs, rt); break; case 0x00: cout << "SLL $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", " << shift << endl; err = SLL(rd, rt, shift); break; case 0x04: cout << "SLLV $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", $" << decode_rs(instr) << endl; err = SLLV(rd, rt, rs); break; case 0x2A: cout << "SLT $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", $" << decode_rs(instr) << endl; err = SLT(rd, rs, rt); break; case 0x2B: cout << "SLTU $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", $" << decode_rs(instr) << endl; err = SLTU(rd, rs, rt); case 0x03: cout << "SRA $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", " << shift << endl; err = SRA(rd, rt, shift); break; case 0x07: cout << "SRAV $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", $" << decode_rs(instr) << endl; err = SRAV(rd, rt, rs); break; case 0x02: cout << "SRL $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", " << shift << endl; err = SRL(rd, rt, shift); break; case 0x06: cout << "SRLV $" << decode_rd(instr) << ", $" << decode_rt(instr) << ", $" << decode_rs(instr) << endl; err = SRLV(rd, rt, rs); break; case 0x22: cout << "SUB $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = SUB(rd, rs, rt); break; case 0x23: cout << "SUBU $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = SUBU(rd, rs, rt); break; case 0x26: cout << "XOR $" << decode_rd(instr) << ", $" << decode_rs(instr) << ", $" << decode_rt(instr) << endl; err = XOR(rd, rs, rt); break; } err = mips_cpu_set_register(state, decode_rd(instr), rd); } else if(opcode==1) { // j type uint32_t branch_func = decode_branch_func(instr); data = decode_data(instr); switch(branch_func) { case 0x01: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = BGEZ(state, rs, data); cout << "BGEZ $" << decode_rs(instr) << ", " << data << endl; break; case 0x11: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = BGEZAL(state, rs, data); cout << "BGEZAL $" << decode_rs(instr) << ", " << data << endl; break; case 0x00: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = BLTZ(state, rs, data); cout << "BLTZ $" << decode_rs(instr) << ", " << data << endl; break; case 0x10: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = BLTZAL(state, rs, data); cout << "BLTZAL $" << decode_rs(instr) << ", " << data << endl; break; } } else { // i type data = decode_data(instr); uint32_t instr_next = 0; err = fetch_next(state, instr_next); uint32_t opcode_next = decode_opcode(instr_next); uint32_t nrt = 0; switch(opcode) { case 0x08: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = ADDI(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "ADDI $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x09: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = ADDIU(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "ADDIU $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x0C: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = ANDI(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "ANDI $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x04: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); err = BEQ(state, rs, rt, data); cout << "BEQ $" << decode_rs(instr) << ", $" << decode_rt(instr) << ", " << data << endl; break; case 0x07: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); err = BGTZ(state, rs, data); cout << "BGTZ $" << decode_rs(instr) << ", " << data << endl; break; case 0x06: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = BLEZ(state, rs, data); cout << "BLEZ $" << decode_rs(instr) << ", " << data << endl; break; case 0x05: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); err = BNE(state, rs, rt, data); cout << "BNE $" << decode_rs(instr) << ", $" << decode_rt(instr) << ", " << data << endl; break; case 0x02: err = J(state, decode_addr(instr)); cout << "J " << decode_addr(instr) << endl; break; case 0x03: err = JAL(state, decode_addr(instr)); cout << "JAL " << decode_addr(instr) << endl; break; case 0x20: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = LB(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LB $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x24: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = LBU(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LBU $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x21: err = mips_cpu_get_register(state, decode_rs(instr), &rs); if(!data%2) { return mips_ExceptionInvalidInstruction; } err = LH(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LH $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x25: err = mips_cpu_get_register(state, decode_rs(instr), &rs); if(!data%2) { return mips_ExceptionInvalidInstruction; } err = LHU(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LHU $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x23: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = LW(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LW $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x22: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = LWL(state->ram, rs + data, rt); err = mips_cpu_get_register(state, decode_rt(instr_next), &nrt); if((opcode_next != 0x22) || (opcode_next != 0x26)) { if(rt==nrt) { return mips_ExceptionInvalidInstruction; } } err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "LWL $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x26: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = LWR(state->ram, rs + data, rt); err = mips_cpu_set_register(state, decode_rs(instr), rt); cout << "LWR $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x0D: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = ORI(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "ORI $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x28: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); err = SB(state->ram, rs + data, rt); cout << "SB $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x29: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); if(!data%2) { return mips_ExceptionInvalidInstruction; } err = SH(state->ram, rs + data, rt); cout << "SH $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x0A: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = SLTI(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "SLTI $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x0B: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = SLTIU(rt, rs, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "SLTIU $" << decode_rt(instr) << ", $" << decode_rs(instr) << ", " << data << endl; break; case 0x2B: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = mips_cpu_get_register(state, decode_rt(instr), &rt); err = SW(state->ram, rs + data, rt); cout << "SW $" << decode_rt(instr) << ", " << data << "($" << decode_rs(instr) << ")" << endl; break; case 0x0E: err = mips_cpu_get_register(state, decode_rs(instr), &rs); err = XORI(rs, rt, data); err = mips_cpu_set_register(state, decode_rt(instr), rt); cout << "XORI $" << decode_rt(instr) << ", $" << decode_rs << ", " << data << endl; break; default: return mips_ExceptionInvalidInstruction; } } return err; }
9730b34eddae81708bc649483e4c1cfa1ebc5f00
e40acae655c826239c165a9398475ae65940b137
/Analyzer/analyzer.cpp
0e66516b240c53d07aad2693d685101389df8fb2
[]
no_license
ruigulala/coin
de7cc454ca4983245d21f04d20aa0e1781f44401
196e275b7068bf0045b80a5b8e6742c7bfeea60c
refs/heads/master
2020-04-06T06:50:32.253154
2015-05-12T13:34:43
2015-05-12T13:34:43
35,488,034
0
0
null
null
null
null
UTF-8
C++
false
false
17,947
cpp
#include "stdio.h" #include "string.h" #include <unistd.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include "general_types.H" #include <iostream> #include <climits> #include <vector> #include <map> #include <algorithm> /* ----------------Global Variables--------------- */ /* Store all the "dynamic" query ins */ std::map<uint32_t, std::vector<uint64_t> > queryIns; /* Store all the trace start index for each thread */ std::vector<uint64_t> threadStartIndex; /* Store the lockset for each LOCK and UNLOCK ins */ std::map<uint64_t, std::vector<uint64_t> > lockset; std::vector<uint64_t> dummyLockset; /* Barrier index per each thread */ std::map<uint64_t, std::vector<uint64_t> > barrIndex; /* Lock and unlock index per each thread */ std::map<uint64_t, std::vector<uint64_t> > lockIndex; /* The number of entries */ uint64_t size; extern void dumpTimestamp(uint16_t * ts); // Find the dynamic matching entry for the static ins void find_ins(const recentry_t * buffer, std::map<uint32_t, uint32_t> * staticIns) { uint64_t i = 0; std::map<uint32_t, uint32_t>::iterator it; for(i = 0; i < size; i++) { it = staticIns->find(buffer[i].info.access.ip); if(it != staticIns->end()) { assert(buffer[i].op == READ_OP); queryIns[it->first].push_back(i); it->second++; } } for(it = staticIns->begin(); it != staticIns->end(); it++) { if(it->second == 0) std::cerr << "Can't find dynamic mapping for ins:0x" <<std::hex<< it->first << std::endl; } } // Compute the start index for each thread and compute the lockset void pre_compute(const recentry_t * buffer) { uint8_t curThread = 0; std::vector<uint64_t> curLock; uint64_t i = 0; threadStartIndex.push_back(0); for( i = 0; i < size; i++) { if(buffer[i].thread != curThread) { // Make sure the log is in ascending order assert(buffer[i].thread == curThread + 1); threadStartIndex.push_back(i); curThread++; } if(buffer[i].op == LOCK_OP) { curLock.push_back(i); lockset[i] = curLock; lockIndex[buffer[i].thread].push_back(i); } else if(buffer[i].op == UNLOCK_OP) { std::vector<uint64_t>::iterator it; for(it = curLock.begin(); it != curLock.end(); it++) { if(buffer[*it].info.lock.lock == buffer[i].info.lock.lock) { curLock.erase(it); break; } } // An unlock must follows a lock //assert(it == curLock.end()); lockset[i] = curLock; lockIndex[buffer[i].thread].push_back(i); } else if(buffer[i].op == BARRIER_OP) { barrIndex[buffer[i].thread].push_back(i); } } } void test_pre_compute() { std::cout << "First dump threadStartIndex" << std::endl; std::vector<uint64_t>::iterator it; uint8_t i = 0; for(it = threadStartIndex.begin(); it != threadStartIndex.end(); it++) { std::cout << "Thread " << i << " starts at " << *it << std::endl; std::cout << "Barrier Index for Thread " << i << std::endl; std::vector<uint64_t>::iterator it1; for(it1 = barrIndex[i].begin(); it1 != barrIndex[i].end(); it1++) { std::cout << *it1 << " "; } std::cout << std::endl; std::cout << "Lock and Unlock Index for Thread " << i << std::endl; for(it1 = lockIndex[i].begin(); it1 != lockIndex[i].end(); it1++) { std::cout << *it1 << std::endl;; std::cout << "Lockset is:" << std::endl; std::vector<uint64_t>::iterator it2; for(it2 = lockset[*it1].begin(); it2 != lockset[*it1].end(); it2++) { std::cout << *it2 << " "; } std::cout << std::endl; } i++; } } /* Return the ins's timestamp */ uint16_t * getTimestamp(const recentry_t * buffer, const uint64_t start_ins) { assert(buffer[start_ins].op == WRITE_OP || buffer[start_ins].op == READ_OP); assert(start_ins <= size); uint64_t end_index; // Find the trace start of the thread std::vector<uint64_t>::iterator it; //std::cout << "Dump threadStartIndex:" << std::endl; //for(it = threadStartIndex.begin(); it != threadStartIndex.end(); it++) //std::cout << *it << " "; //std::cout << std::endl; for(it = threadStartIndex.begin(); it != threadStartIndex.end(); it++) { // If we reach the last thread start if((it + 1) == threadStartIndex.end()) { end_index = *it; } else if(*it <= start_ins && *(it + 1) > start_ins) { end_index = *it; break; } } uint64_t i; uint16_t * ts = (uint16_t*)calloc(BARRNUMS + 1, sizeof(uint16_t)); for(i=start_ins - 1; i != static_cast<uint64_t>(end_index-1); i--) { if(buffer[i].op == BARRIER_OP) { int skew = 8; int ts_i = 0; while(skew >= 0) { ts[ts_i++] = buffer[i - skew].info.barrier.ts0; ts[ts_i++] = buffer[i - skew].info.barrier.ts1; ts[ts_i++] = buffer[i - skew].info.barrier.ts2; ts[ts_i++] = buffer[i - skew].info.barrier.ts3; skew--; } break; } } if(i == static_cast<uint64_t>(end_index - 1)) { //std::cerr << "Error: Missing Timestamp for Thread " // << buffer[start_ins].thread << std::endl; //abort(); } return ts; } /* Return the ins's lockset */ std::vector<uint64_t> * getLockset(const recentry_t * buffer, const uint64_t start_ins) { uint64_t end_index; // Find the trace start of the thread assert(start_ins <= size); std::vector<uint64_t>::iterator it; for(it = threadStartIndex.begin(); it != threadStartIndex.end(); it++) { // If it's the last thread if((it + 1) == threadStartIndex.end()) { end_index = *it; } else if(*it <= start_ins && *(it + 1) > start_ins) { end_index = *it; break; } } uint64_t i; for(i = start_ins - 1; i != static_cast<uint64_t>(end_index-1); i--) { if(buffer[i].op == LOCK_OP || buffer[i].op == UNLOCK_OP) { return &lockset[i]; } } if(i == static_cast<uint64_t>(end_index - 1)) { //std::cerr << "Warning: No Lock or Unlock operations being performed ahead" //<< " " << start_ins<< std::endl; } return &dummyLockset; } // Given a shared variable read ins, find the W ins backwards uint64_t findW(const recentry_t * buffer, const uint64_t start_ins) { assert(buffer[start_ins].op == READ_OP); // 1.1 Need to be a write op // 1.2 Need to access the same mem location as read op // 1.3 The value of the write need to be the same as read op // 2. Put all to a vector and compare those timestamp to r // 3. Compare all to the last, pop_back ... // 4. Pick one from what's left uint64_t i = size - 1; std::vector<uint64_t> candidateW; uint16_t * r_ts; r_ts = getTimestamp(buffer, start_ins); for(; i != static_cast<uint64_t>(-1); i--) { if(buffer[i].op != WRITE_OP) continue; if(buffer[i].info.access.addr != buffer[start_ins].info.access.addr) continue; if(buffer[i].info.access.val != buffer[start_ins].info.access.val) continue; // r.ts < w.ts -> false uint16_t * w_ts; w_ts = getTimestamp(buffer, i); if(r_ts[buffer[start_ins].thread] < w_ts[buffer[start_ins].thread]) { free(w_ts); continue; } // Prune out the ins after start_ins within the same thread if(buffer[i].thread == buffer[start_ins].thread) if(i > start_ins) { free(w_ts); continue; } free(w_ts); candidateW.push_back(i); } if(candidateW.size() == 0) { std::cerr << "Can't find the corresponding W ins"; std::cerr << "for Ins:" << start_ins << " Op:" << buffer[start_ins].op << std::endl; free(r_ts); abort(); return 0; } free(r_ts); // Dump the vector //std::vector<int>::iterator it; //for(it = candidateW.begin(); it != candidateW.end(); it++) //std::cout << *it << " "; //std::cout << std::endl; if(candidateW.size() == 1) return candidateW[0]; // Find the lastest w ins // Get the timestamp of all the w candidates uint16_t ** w_ts = (uint16_t**)calloc(candidateW.size(), sizeof(uint16_t *)); int w_vec_i = 0; for(w_vec_i = 0; w_vec_i < candidateW.size(); w_vec_i++) { w_ts[w_vec_i] = (uint16_t*)calloc(BARRNUMS + 1, sizeof(uint16_t)); w_ts[w_vec_i] = getTimestamp(buffer, candidateW[w_vec_i]); } for(w_vec_i = 0; w_vec_i < candidateW.size() - 1; w_vec_i++) { int i_tmp = 0; for(i_tmp = w_vec_i + 1; i_tmp < candidateW.size(); i_tmp++) { // if w_vec_i.ts < i_tmp.ts if(w_ts[w_vec_i][buffer[candidateW[w_vec_i]].thread] < w_ts[i_tmp][buffer[candidateW[w_vec_i]].thread]) { break; } } if(i_tmp == candidateW.size()) { // Free the memory for(i_tmp = 0; i_tmp < candidateW.size(); i_tmp++) { free(w_ts[i_tmp]); } free(w_ts); return candidateW[w_vec_i]; } } std::cerr << "ERROR: candidates disappeared." << std::endl; abort(); return 0; } bool isWPrime(const recentry_t * buffer, const uint64_t r_ins, const uint64_t w_ins, const uint64_t w_p_ins) { assert(w_ins != w_p_ins); // 0 w and w' need to access the same mem location if(buffer[w_ins].info.access.addr != buffer[w_p_ins].info.access.addr) return false; // Obtain the timestamp uint16_t * r_ts = getTimestamp(buffer, r_ins); uint16_t * w_ts = getTimestamp(buffer, w_ins); uint16_t * w_p_ts = getTimestamp(buffer, w_p_ins); // 1.1 r.time_stamp < w'.time_stamp, r and w' not same thread if(buffer[r_ins].thread != buffer[w_p_ins].thread) { if(r_ts[buffer[r_ins].thread] < w_p_ts[buffer[r_ins].thread]) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } // 1.2 r and w' in same thread else { if(r_ins < w_p_ins) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } // 2.1 w′.time-stamp < w.time-stamp < r.time-stamp then (different thread) if(buffer[w_p_ins].thread != buffer[w_ins].thread) { if(w_p_ts[buffer[w_p_ins].thread] < w_ts[buffer[w_p_ins].thread] && w_ts[buffer[w_ins].thread] < r_ts[buffer[w_ins].thread]) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } // 2.2 w′.time-stamp < w.time-stamp then (same thread) // w < r is enforced by findW else { if(w_p_ins < w_ins) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } // 3. if w is executed before r in a critical section CS1, // w′ is in critical section CS2, CS1 and CS2 are from different threads, // and CS1 is mutually exclusive from CS2 then std::vector<uint64_t> * w_lockset, * r_lockset, * w_p_lockset; w_lockset = getLockset(buffer, w_ins); r_lockset = getLockset(buffer, r_ins); w_p_lockset = getLockset(buffer, w_p_ins); if(buffer[r_ins].thread == buffer[w_ins].thread) { if(buffer[r_ins].thread != buffer[w_p_ins].thread) { std::vector<uint64_t> cs1(20); std::vector<uint64_t> result(20); std::vector<uint64_t>::iterator it; it=std::set_intersection (w_lockset->begin(), w_lockset->end(), r_lockset->begin(), r_lockset->end(), cs1.begin()); cs1.resize(it - cs1.begin()); it=std::set_intersection (w_p_lockset->begin(), w_p_lockset->end(), cs1.begin(), cs1.end(), result.begin()); result.resize(it - result.begin()); if(result.size() != 0) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } } // 4.if w′ is executed before w in a critical section CS1, // r is in critical section CS2, CS1 and CS2 are from different threads, // and CS1 is mutually exclusive from CS2 then if(buffer[w_ins].thread == buffer[w_p_ins].thread) { if(buffer[r_ins].thread != buffer[w_ins].thread) { std::vector<uint64_t> cs1(20); std::vector<uint64_t> result(20); std::vector<uint64_t>::iterator it; //for(it = w_lockset->begin(); it != w_lockset->end(); it++) //std::cout << "L: "<< *it << std::endl; it=std::set_intersection (w_lockset->begin(), w_lockset->end(), w_p_lockset->begin(), w_p_lockset->end(), cs1.begin()); cs1.resize(it - cs1.begin()); it=std::set_intersection (r_lockset->begin(), r_lockset->end(), cs1.begin(), cs1.end(), result.begin()); result.resize(it - result.begin()); if(result.size() != 0) { free(r_ts); free(w_ts); free(w_p_ts); return false; } } } free(r_ts); free(w_ts); free(w_p_ts); return true; } void dumpTimestamp(uint16_t * ts) { int i = 0; std::cout << "Timestamp dump:" << std::endl; for(i = 0; i < BARRNUMS + 1; i++) std::cout << ts[i] << " "; std::cout << std::endl; } void dumpToVec(const recentry_t* rec) { int i=0; printf("%d\t",(int)rec->thread); switch(rec->op){ case READ_OP: printf("R\t"); printf("0x%x\t0x%x",rec->info.access.ip,rec->info.access.addr); printf("\t%d",rec->info.access.reg); printf("\t%d",rec->mid); printf("\n"); break; case WRITE_OP: printf("W\t"); printf("0x%x\t0x%x",rec->info.access.ip,rec->info.access.addr); printf("\t%d",rec->info.access.reg); printf("\t%d", rec->mid); printf("\n"); break; case BARRIER_OP: printf("B\t"); printf("%d\t%d\t%d\t%d\n",(int)rec->info.barrier.ts0,(int)rec->info.barrier.ts1, (int)rec->info.barrier.ts2, (int)rec->info.barrier.ts3); break; case LOCK_OP: printf("L\t"); printf("0x%x\t%d\n",rec->info.lock.lock,rec->info.lock.instance); break; case UNLOCK_OP: printf("U\t"); printf("0x%x\t%d\n",rec->info.lock.lock,rec->info.lock.instance); break; default: ; } } bool parseTraceLine(recentry_t * buf, long iadr, long dadr, long count) { if((buf->op == READ_OP) || (buf->op == WRITE_OP)) { if((iadr!=0) && ((long)buf->info.access.ip!=iadr)) return false; if((dadr!=0) && ((long)buf->info.access.addr!=dadr)) return false; } return true; } void readIns(char * ilistFile, std::map<uint32_t, uint32_t> * staticIns) { FILE *ifp; uint32_t ins; ifp = fopen(ilistFile, "r"); if (ifp == NULL) { fprintf(stderr, "Can't open input file in.list!\n"); exit(1); } while (fscanf(ifp, "%x", &ins) != EOF) { (*staticIns)[ins] = 0; } return; } int main(int argc, char * argv[]) { //set default value: if(argc < 2){ printf("Please type -h for help\n"); return 0; } extern char * optarg; char ch; char tracefilename[100]; char ilistFile[100]; //long iaddr=0; long daddr=0; long count=0; strcpy(tracefilename,"temp"); while ((ch = getopt(argc,argv,"i:d:f:c:h")) != -1){ switch(ch){ case 'f': strcpy(tracefilename,optarg);break; case 'd': daddr=strtoul(optarg,NULL,0);break; //atoi(optarg);break; case 'c': count=strtoul(optarg,NULL,0);break; case 'i': strcpy(ilistFile, optarg);break; case 'h': default: printf("-f tracefile name\n"); printf("-d interesting data memory address\n"); printf("-i interesting instruction address\n"); printf("-c entry index [invalid in this version]\n"); printf("-h help\n"); return 0; } } int tracefile; struct stat st; recentry_t* buffer; printf("Display parameters:\n"); printf("Trace file: %s\n", tracefilename); printf("Instruction file: %s\n", ilistFile); printf("Begin to analyze:\n"); tracefile = open(tracefilename, O_RDWR); if(tracefile < 0){ perror("Error opening file:"); fprintf(stderr,"./ctdbg_s -f <filename> -i <instruction filter> -d <access-address filter>\n"); return 0; } if(fstat(tracefile, &st) < 0){ perror("Error stating file:"); return 0; } buffer = (recentry_t *)mmap(0, (1 + st.st_size / 4096) * 4096, PROT_READ | PROT_WRITE, MAP_SHARED, tracefile, 0); size = st.st_size / sizeof(recentry_t); assert(size < ULLONG_MAX); if(buffer == (void *)-1){ perror("Error with mmap:"); return 0; } pre_compute(buffer); //test_pre_compute(); std::map<uint32_t, uint32_t> staticIns; // Read instructions from a file readIns(ilistFile, &staticIns); find_ins(buffer, &staticIns); printf("Size of the file is %llu\n", size); /* Test findW() */ std::map<uint32_t, std::vector<uint64_t> >::iterator it; std::vector<uint64_t>::iterator it2; for(it = queryIns.begin(); it != queryIns.end(); it++) { for(it2 = it->second.begin(); it2 != it->second.end(); it2++) { uint64_t tmp_w = findW(buffer, *it2); printf("T%u R:%llu[0x%x] T%u W:%llu[0x%x]\n", buffer[*it2].thread, *it2, buffer[*it2].info.access.ip, buffer[tmp_w].thread, tmp_w, buffer[tmp_w].info.access.ip); uint64_t i = 0; //int progress = 0; for(i = 0; i < size; i++) { //if(i % (uint64_t)(size * 0.1) == 0) { //printf("%d%% is done.\n", 10 * progress); //progress++; //} if(buffer[i].op == WRITE_OP && i != tmp_w) if(isWPrime(buffer, *it2, tmp_w, i)) printf("[RESULT]T%u R: %llu[0x%x] \tT%u W: %llu[0x%x] \tT%u W': %llu[0x%x]\n", buffer[*it2].thread, *it2, buffer[*it2].info.access.ip, buffer[tmp_w].thread, tmp_w, buffer[tmp_w].info.access.ip, buffer[i].thread, i, buffer[i].info.access.ip); } } } //uint64_t index = 0; //for(index = 0;index < size; index++){ //std::cout << "Index:" << std::dec << index << std::endl; //dumpToVec(&buffer[index]); //} /* Test for getTimeStamp */ //uint16_t * tmp = getTimestamp(buffer, 16); //dumpTimestamp(tmp); //free(tmp); //finish msync(buffer, st.st_size, MS_SYNC); printf("done\n"); }
6a6f4c36fa35c545985d5bb33fbfc3eac91061f7
877f4db43b49b908579c8112af7c2a4ded4d4f3e
/Assignment_1/average.cpp
eb3891e641ec3040f0d396e17edfdd837232034c
[]
no_license
mfaramarzi/CSC211_Programming_CPP
f3d31905f62c3003fd30c82d889e07f99b96ad94
3e09f31fed37c7740da783bf5541a939b2b7086b
refs/heads/main
2023-08-28T13:53:17.322678
2021-10-31T00:59:55
2021-10-31T00:59:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
564
cpp
/* Prompt the user for three decimal values and print the average of the three in the format: The average of <num1>, <num2>, and <num3> is <average>. */ #include<iostream> #include <iomanip> int main(){ // defining parameters double num1, num2, num3, average; // reading a number std::cin >> num1 >> num2 >> num3; average = (num1 + num2 + num3)/3; std::cout << std::fixed; std::cout << std::setprecision(4); std::cout <<"The average of " << num1 << ", " << num2 << ", and " << num3 << " is "; std::cout <<average; }
dda541b77e034502c5c570fb7014d940ee17aca5
80c585608b7bb36ef5653aec866819e0eb919cfa
/src/client/src/EnInteropNote.h
770c6aa3fe7a5ae0024c2fe9c97c4c1f35ee6cbe
[]
no_license
ARLM-Attic/peoples-note
109bb9539c612054d6ff2a4db3bdce84bad189c4
1e7354c66a9e2b6ccb8b9ee9c31314bfa4af482d
refs/heads/master
2020-12-30T16:14:51.727240
2013-07-07T09:56:03
2013-07-07T09:56:03
90,967,267
0
0
null
null
null
null
UTF-8
C++
false
false
378
h
#pragma once #include "Guid.h" #include "Note.h" class EnInteropNote { public: Note note; GuidList resources; GuidList tags; Guid notebook; std::wstring name; Guid guid; int usn; bool isDirty; EnInteropNote(const Note & note, const Guid & notebook); }; typedef std::vector<EnInteropNote> EnInteropNoteList;
[ "SND\\DonReba_cp@aadf2aa7-86a3-4242-a263-039aa7a476c3" ]
SND\DonReba_cp@aadf2aa7-86a3-4242-a263-039aa7a476c3
7a20233e3c0e834dc94a72d6f697510fa1f740ee
175d783916d1c08e8eb05a964e85dc9f1ee689f7
/PointCloud/evaluateImages.h
29288ab2af79dc72cb06b875656658aff0ba9a48
[]
no_license
Armida220/pointCloud
cfc146530690076591f7ea8bc615a4da56ffd7d1
9a6d4c277f7631ba75f4ae25f60ef2726f430312
refs/heads/master
2020-05-03T02:02:21.389697
2019-03-29T03:44:35
2019-03-29T03:44:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
898
h
#pragma once #include <vector> #include <map> #include <opencv2/opencv.hpp> namespace calibration { /** * @brief This function compute the cell index of each image * * */ void computeCellIndexs( const std::vector<std::vector<cv::Point2f>>& imagePoints, const cv::Size& imageSize, const std::size_t& calibGridSize, std::vector<std::vector<std::size_t>>& cellIndexsPerImage); /** * @brief This function compute each cell's weight from all images * * */ void computeCellsWeight( const std::vector<std::vector<std::size_t>>& cellIndexsPerImage, const std::size_t& calibGridSize, std::vector<std::size_t>& cellsWeight); /** * @brief This function compute each image's score */ void computeImageScores( const std::vector<std::vector<std::size_t>>& cellIndexsPerImage, const std::vector<std::size_t>& cellsWeight, std::vector<float>& imageScores); }
9fc21e9abe86aee3f3912576af22e1ee85fc2f71
e6b96681b393ae335f2f7aa8db84acc65a3e6c8d
/atcoder.jp/abc146/abc146_a/Main.cpp
d5d0aa64d88aaa50aa85b9b5ee9177f70b2a6789
[]
no_license
okuraofvegetable/AtCoder
a2e92f5126d5593d01c2c4d471b1a2c08b5d3a0d
dd535c3c1139ce311503e69938611f1d7311046d
refs/heads/master
2022-02-21T15:19:26.172528
2021-03-27T04:04:55
2021-03-27T04:04:55
249,614,943
0
0
null
null
null
null
UTF-8
C++
false
false
3,668
cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll; // #define int long long #define pb push_back #define mp make_pair #define eps 1e-9 #define INF 2000000000 #define LLINF 1000000000000000ll #define sz(x) ((int)(x).size()) #define fi first #define sec second #define all(x) (x).begin(),(x).end() #define sq(x) ((x)*(x)) #define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++) #define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++) #define EQ(a,b) (abs((a)-(b))<eps) #define dmp(x) cerr << __LINE__ << " " << #x << " " << x << endl; template<class T> void chmin(T& a,const T& b){if(a>b)a=b;} template<class T> void chmax(T& a,const T& b){if(a<b)a=b;} template<class T> using MaxHeap = priority_queue<T>; template<class T> using MinHeap = priority_queue<T,vector<T>,greater<T> >; template<class T,class U> ostream& operator << (ostream& os,pair<T,U>& p){ os << p.fi << ',' << p.sec; return os; } template<class T,class U> istream& operator >> (istream& is,pair<T,U>& p){ is >> p.fi >> p.sec; return is; } template<class T> ostream& operator << (ostream &os,const vector<T> &vec){ for(int i=0;i<vec.size();i++){ os << vec[i]; if(i+1<vec.size())os << ' '; } return os; } template<class T> istream& operator >> (istream &is,vector<T>& vec){ for(int i=0;i<vec.size();i++)is >> vec[i]; return is; } void fastio(){ cin.tie(0); ios::sync_with_stdio(0); cout<<fixed<<setprecision(20); } const ll MOD = 1000000007ll; // if inv is needed, this shold be prime. struct ModInt{ ll val; ModInt():val(0ll){} ModInt(const ll& v):val(((v%MOD)+MOD)%MOD){} ModInt exp(ll y)const{ if(!y)return ModInt(1ll); ModInt a = exp(y/2ll); a *= a; if(y&1)a*=(*this); return a; } bool operator==(const ModInt& x)const{return val==x.val;} inline bool operator!=(const ModInt& x)const{return !(*this==x);} bool operator<(const ModInt& x)const{return val<x.val;} bool operator>(const ModInt& x)const{return val>x.val;} inline bool operator>=(const ModInt& x)const{return !(*this<x);} inline bool operator<=(const ModInt& x)const{return !(*this>x);} ModInt& operator+=(const ModInt& x){if((val+=x.val)>=MOD)val-=MOD;return *this;} ModInt& operator-=(const ModInt& x){if((val+=MOD-x.val)>=MOD)val-=MOD;return *this;} ModInt& operator*=(const ModInt& x){(val*=x.val)%=MOD;return *this;} ModInt operator+(const ModInt& x)const{return ModInt(*this)+=x;} ModInt operator-(const ModInt& x)const{return ModInt(*this)-=x;} ModInt operator*(const ModInt& x)const{return ModInt(*this)*=x;} friend istream& operator>>(istream&i,ModInt& x){ll v;i>>v;x=v;return i;} friend ostream& operator<<(ostream&o,const ModInt& x){o<<x.val;return o;} }; ModInt pow(ModInt a,ll x){ ModInt res = ModInt(1ll); while(x){ if(x&1)res *= a; x >>= 1; a = a*a; } return res; } vector<ModInt> inv,fac,facinv; // notice: 0C0 = 1 ModInt nCr(int n,int r){ assert(!(n<r)); assert(!(n<0||r<0)); return fac[n]*facinv[r]*facinv[n-r]; } void init(int SIZE){ fac.resize(SIZE+10); inv.resize(SIZE+10); facinv.resize(SIZE+10); fac[0]=ModInt(1ll); for(int i=1;i<=SIZE;i++)fac[i]=fac[i-1]*ModInt(i); inv[1]=ModInt(1ll); for(int i=2;i<=SIZE;i++)inv[i]=ModInt(0ll)-ModInt(MOD/i)*inv[MOD%i]; facinv[0]=ModInt(1ll); for(int i=1;i<=SIZE;i++)facinv[i]=facinv[i-1]*inv[i]; return; } string s; signed main(){ fastio(); cin >> s; if(s=="SUN")cout << 7 << endl; if(s=="SAT")cout << 1 << endl; if(s=="FRI")cout << 2 << endl; if(s=="THU")cout << 3 << endl; if(s=="WED")cout << 4 << endl; if(s=="TUE")cout << 5 << endl; if(s=="MON")cout << 6 << endl; return 0; }
43f1680ccea9f5de7c8863975b470a74455ce2e4
39040af0ff84935d083209731dd7343f93fa2874
/inc/dp/uobjectpool.h
678c8d1e07da8c2c5155f6ba11697cd96d77adcb
[ "Apache-2.0" ]
permissive
alanzw/ulib-win
02f8b7bcd8220b6a057fd3b33e733500294f9b56
b67f644ed11c849e3c93b909f90d443df7be4e4c
refs/heads/master
2020-04-06T05:26:54.849486
2011-07-23T05:47:17
2011-07-23T05:47:17
34,505,292
5
3
null
null
null
null
UTF-8
C++
false
false
936
h
/* * ===================================================================================== * * Filename: uobjectpool.h * * Description: Object Pool * * Version: 1.0 * Created: 2009-7-22 20:13:02 * Revision: none * Compiler: gcc * * Author: huys (hys), [email protected] * Company: hu * * ===================================================================================== */ namespace huys { namespace dp { namespace creational { #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName &); \ void operator=(const TypeName &) #define DISALLOW_EVIL_CONSTRUCTOR(TypeName) \ DISALLOW_COPY_AND_ASSIGN(TypeName template <typename T> class UObjectPool { public: UObjectPool(); ~UObjectPool(); private: DISALLOW_EVIL_CONSTRUCTOR(UObjectPool); }; }; // namespace creational }; // namespace dp }; // namespace huys
[ "fox000002@48c0247c-a797-11de-8c46-7bd654735883" ]
fox000002@48c0247c-a797-11de-8c46-7bd654735883
eb51544fc5fc58eee30dfe7d667d4bcba3844046
3e27864309375d72adaf3d31c678f8066b536484
/wingwidget.h
ca63dabcd21d04952c327c48dc6d6392be33461a
[]
no_license
Uking33/180622-QT-OilManageSystem
c83ca4a9a8f6865d6329dc3a8a70fcb0bb14a42a
979c9fd5fbd849c3baaea5ccf2d0ec3b9aa41ef1
refs/heads/main
2023-04-13T21:44:56.319947
2021-04-23T05:55:05
2021-04-23T05:55:05
360,778,133
0
0
null
null
null
null
UTF-8
C++
false
false
2,307
h
#ifndef WINGWIDGET_H #define WINGWIDGET_H //窗口 #include <QWidget> class OutPut; //布局 class QVBoxLayout; class QHBoxLayout; //控件 class QTableWidget; class QLabel; class QComboBox; class QLineEdit; class UButton; class UDateBox; class UTimeBox; class ULine; class URectBox; class UMulRadio; //辅助 class QTableWidgetSelectionRange; class QTableWidgetItem; class QresizeEvent; class ULoading; class WingWidget: public QWidget { Q_OBJECT public://公有函数 WingWidget(OutPut *m_output, WingWidget *m_parent); ~WingWidget(); void ChangeType(int tpye = -1); protected://保护数据 OutPut *m_output; WingWidget *m_parent; QList<int> m_indexList; ULoading *m_uloading; protected://保护控件 QVBoxLayout *m_layout; QHBoxLayout *m_layout1; QHBoxLayout *m_layout2; QHBoxLayout *m_layout3; QHBoxLayout *m_dateSLayout; QLabel *m_dateSLabel; UDateBox *m_dateSBox; UButton *m_dateSBtn1; UButton *m_dateSBtn2; QHBoxLayout *m_findLayout; QLabel *m_findLabel; QComboBox *m_findBox; QLineEdit *m_findEdit; QHBoxLayout *m_dateELayout; QLabel *m_dateELabel; UDateBox *m_dateEBox; UButton *m_dateEBtn1; UButton *m_dateEBtn2; bool m_isCheck; UMulRadio *m_radio1; UMulRadio *m_radio2; UMulRadio *m_radio3; QHBoxLayout *m_btnLayout; UButton *m_btn1; UButton *m_btn2; UButton *m_btn3; UButton *m_btn4; UButton *m_btn5; UButton *m_btn6; QTableWidget *m_table_up; QTableWidget *m_table; QStringList m_findLabels; QStringList m_headerLabels1; QStringList m_headerLabels2; QStringList m_tableType1; QStringList m_tableType2; int m_type; //table choose type bool m_isDetails; protected://保护函数 void ClearWidget(); void Create(); protected slots://保护槽函数 void FindChange(int index); void TableSort(int index); public: int BtnFind(QList<QList<QVariant> > &oList, QTableWidget *tableWidget, QStringList strList, int maxRow=10); QList<int> *BtnDel(int maxCount); //outside delete * void DelSum(QList<int>* indexList, int m_index, QList<QList<QVariant>>*m_var1, QList<QList<QList<QVariant> > > *m_var2, QStringList m_tableAuto, QStringList m_tableType); }; #endif // WINGWIDGET_H
91ba51ac90e25e65724e457f053ecd5fb59cf3f0
d1b3e118bad21fbd77476b8ff9bdb83742d67f3b
/XMEngine/src/Engine/Shaders/SpriteShader.h
7284052d5d82bf18f8de7b9be63e9398bd7a8a32
[]
no_license
thezzk/XMEngine
13517353902bee0e01aa80adfbb1471834b7eb56
c1df1ae9706edb75e1cb80cf3337ab4cd1bff8d5
refs/heads/master
2021-01-11T18:54:35.818378
2017-04-23T05:18:03
2017-04-23T05:18:03
79,653,297
1
0
null
null
null
null
UTF-8
C++
false
false
775
h
// // SpriteShader.hpp // XMEngine // // Created by thezzk on 17/4/6. // Copyright © 2017年 thezzk. All rights reserved. // #ifndef SpriteShader_hpp #define SpriteShader_hpp #include "iostream" #include "TextureShader.h" namespace gEngine { class SpriteShader: public TextureShader { public: SpriteShader(std::string vertexShaderpath, std::string fragmentShaderPath); virtual ~SpriteShader(); void setTextureCoordinate(const std::vector<GLfloat>& texCoord); virtual void activateShader(std::vector<GLfloat> pixelColor, std::shared_ptr<const Camera> aCamera); private: GLuint mTexCoordBuffer; const static GLfloat initTexCoord[]; }; }// namespace gEngine #endif /* SpriteShader_hpp */
68eac0f034b1c6849e6cdcfea254271df0d69bc4
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/比赛/清北学堂/入学测试0715/2018715/2018715/src/铜陵一中 孙乐旋/cover.cpp
f95ec9c9c11793465fe8e940aaa765d6172a7592
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; int f[100002],n,k,len=0,b[100002]; struct node{ int s,e,l; }a[100002]; int cmp1(node a,node b){ return a.e<b.e; } int main(){ freopen("cover.in","r",stdin); freopen("cover.out","w",stdout); cin>>n>>k; for(int i=1;i<=n;++i){ cin>>a[i].s>>a[i].e; a[i].l=a[i].e-a[i].s; } sort(a+1,a+1+n,cmp1); for(int i=1;i<=n;++i) for(int i=1;i<=n;++i){ if(a[i-1].e>a[i].s) b[i]=a[i].l-a[i-1].e+a[i].s; if(a[i+1].s<a[i].e) b[i]=b[i]-a[i].e+a[i+1].s; if(b[i]<0) b[i]=0; } sort(b+1,b+1+n); for(int i=1;i<=n-k;++i) f[i]=1; for(int i=1;i<=n;++i){ if(f[i]==1) continue; if(len==0){ len=a[i].l;continue; } len+=a[i].e-a[i-1].e; } cout<<a[n].e-a[1].s; return 0; }
8dbd0822ede2df5ba3898dcf6dfea31e019a9f96
e13128e573ffb52df3094954bd16e9551277321c
/mex-wholebodymodel/library/include/modelgravitybiasforces.h
141d99fd5f30ebbbb2f53b3f8073413be7e9cecc
[]
no_license
Anesh20/mex-wholebodymodel
e42c3cbb815f29b3e9fdd1ece7ddd3adae7d8342
1d73b87920392cd1b1706731f5e0af75506662d2
refs/heads/master
2022-12-22T20:41:49.066396
2020-09-29T10:29:42
2020-09-29T10:29:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,862
h
/* * Copyright (C) 2016 Robotics, Brain and Cognitive Sciences - Istituto Italiano di Tecnologia * Authors: Martin Neururer * email: [email protected], [email protected] * * The development of this software was supported by the FP7 EU projects * CoDyCo (No. 600716 ICT 2011.2.1 Cognitive Systems and Robotics (b)) * http://www.codyco.eu * * Permission is granted to copy, distribute, and/or modify this program * under the terms of the GNU General Public License, version 2 or any * later version published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details */ #ifndef MODELGRAVITYBIASFORCES_H #define MODELGRAVITYBIASFORCES_H // global includes // library includes // local includes #include "modelcomponent.h" namespace mexWBIComponent { class ModelGravityBiasForces : public ModelComponent { public: static ModelGravityBiasForces *getInstance(); /** * Delete the (static) instance of this component, * and set the instance pointer to 0. */ static void deleteInstance(); virtual bool allocateReturnSpace(int nlhs, mxArray **plhs); virtual bool compute(int nrhs, const mxArray **prhs); virtual bool computeFast(int nrhs, const mxArray **prhs); virtual ~ModelGravityBiasForces(); private: ModelGravityBiasForces(); bool processArguments(int nrhs, const mxArray **prhs); static ModelGravityBiasForces *modelGravityBiasForces; // inputs: static double *qj; static double *g; // output: static double *g_q; // gravity bias forces G(q) }; } #endif // MODELGRAVITYBIASFORCES_H
9b2ae329d8697111642f48435b8c9821319ee2d6
55c0a372b99775811f782434b409ace8554f28f4
/DFS.cpp
bc374a9d7c9cd036875c817c98712073c3447156
[]
no_license
cantbesure/DataStruct
8fbc5822022571fa9ed0ea3f061cf9eda97ec338
b58791b4695799db789b62fdda5caa57f69d2d89
refs/heads/master
2016-09-06T08:20:53.010382
2014-06-17T05:01:49
2014-06-17T05:01:49
17,535,554
2
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #include <stack> #include <vector> #include <cstdlib> #include <string> #include <cstring> #include <map> #include <ctime> #define eps 1e-9 #define init 30 #define increse 10 #define LmT 4 using namespace std; typedef long long LL; const int maxx= 100; bool vis[maxx]; int weight[maxx][maxx]; int link[maxx][maxx]; void dfs(int index) { cout<<index<<endl; vis[index]=true; for (int i=1;i<link[index][0];i++) { if (!vis[link[index][i]]) dfs(link[index][i]); } } int main() { int n,m; cin>>n>>m; int p,q; memset(vis,0,sizeof vis); for (int i=0;i<n;i++) link[i][0]=1; for (int i=0;i<m;i++) { cin>>p>>q; link[p][link[p][0]++]=q; link[q][link[q][0]++]=p; } dfs(0); return 0; } /*test data 8 9 0 2 0 1 1 2 1 3 1 5 2 4 4 7 5 7 6 7 */ /*output 0 2 1 3 5 7 4 6 */
cacf18b3298fa7cb47fc990b22770328de2b0f8d
888b8f657b27712fcbd2d6df295c1d4aed4e4307
/PAT/A1018 Public Bike Management.cpp
cfb84a42ecf87a36e3be7feeab4169df9978ef10
[]
no_license
zzwblog/AlgorithmCode
9a0b1fb0b459dad1c6d127cf1f1d996a97c2bac2
0e9c2f0b096298eaedf442674416d01afceac7a3
refs/heads/master
2022-12-15T16:09:04.009443
2020-09-03T10:48:53
2020-09-03T10:48:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,732
cpp
//#include <iostream> //#include <algorithm> //#include <vector> ////using namespace std; ////const int inf = 99999999; ////int cmax, n, sp, m; ////int minneed = inf, minback = inf; ////int e[510][510], dis[510], weight[510]; ////bool visit[510]; ////vector<int> pre[510], path, temppath; ////void dfs(int v) { //// temppath.push_back(v); //// if (v == 0) { //// int need = 0, back = 0; //// for (int i = temppath.size() - 1; i >= 0; i--) { //// int id = temppath[i]; //// if (weight[id] > 0) { //// back += weight[id]; //// } //// else { //// if (back > (0 - weight[id])) { //// back += weight[id]; //// } //// else { //// need += ((0 - weight[id]) - back); //// back = 0; //// } //// } //// } //// if (need < minneed) { //// minneed = need; //// minback = back; //// path = temppath; //// } //// else if (need == minneed && back < minback) { //// minback = back; //// path = temppath; //// } //// temppath.pop_back(); //// return; //// } //// for (int i = 0; i < pre[v].size(); i++) //// dfs(pre[v][i]); //// temppath.pop_back(); ////} ////int main() { //// fill(e[0], e[0] + 510 * 510, inf); //// fill(dis, dis + 510, inf); //// scanf("%d%d%d%d", &cmax, &n, &sp, &m); //// for (int i = 1; i <= n; i++) { //// scanf("%d", &weight[i]); //// weight[i] = weight[i] - cmax / 2; //// } //// for (int i = 0; i < m; i++) { //// int a, b; //// scanf("%d%d", &a, &b); //// scanf("%d", &e[a][b]); //// e[b][a] = e[a][b]; //// } //// dis[0] = 0; //// for (int i = 0; i <= n; i++) { //// int u = -1, minn = inf; //// for (int j = 0; j <= n; j++) { //// if (visit[j] == false && dis[j] < minn) { //// u = j; //// minn = dis[j]; //// } //// } //// if (u == -1) break; //// visit[u] = true; //// for (int v = 0; v <= n; v++) { //// if (visit[v] == false && e[u][v] != inf) { //// if (dis[v] > dis[u] + e[u][v]) { //// dis[v] = dis[u] + e[u][v]; //// pre[v].clear(); //// pre[v].push_back(u); //// } //// else if (dis[v] == dis[u] + e[u][v]) { //// pre[v].push_back(u); //// } //// } //// } //// } //// dfs(sp); //// printf("%d 0", minneed); //// for (int i = path.size() - 2; i >= 0; i--) //// printf("->%d", path[i]); //// printf(" %d", minback); //// return 0; ////} //// // // //#include <iostream> //#include <vector> //using namespace std; //int C, N, Sp, M, c1, c2, w; //int bikes[505] = { 0 }, graph[505][505], dis[505]; //vector<int>father[505], path, tempPath;//因为每个节点的父节点可能有多个 //bool visit[505] = { false }; //int minNeed = INT32_MAX, minBack = INT32_MAX; //void Dijkstra(int st) //{ // dis[st] = 0; // for (int i = 0; i <= N; ++i) // { // int u = -1, minDis = INT32_MAX; // for (int j = 0; j <= N; ++j) // { // if (visit[j] == false && minDis > dis[j]) // { // u = j; // minDis = dis[j]; // } // } // if (u == -1)break; // visit[u] = true; // for (int v = 0; v <= N; ++v) // { // if (visit[v] == false && graph[u][v] <INT32_MAX) // { // if (dis[v] > dis[u] + graph[u][v]) // { // dis[v] = dis[u] + graph[u][v]; // father[v].clear(); // father[v].push_back(u); // } // else if (dis[v] == dis[u] + graph[u][v]) // father[v].push_back(u); // } // } // } //} //void DFS(int v) //{ // tempPath.push_back(v); // if (v == 0)//回到了起点,我们计算需要的自行车数量 // { // int need = 0, back = 0; // for (int i = tempPath.size() - 1; i >= 0; --i) // { // int id = tempPath[i]; // if (bikes[id] > 0)//车的数量过多,需要拿回去 // back += bikes[id]; // else // {//车的数量不够 // if (back > (0 - bikes[id]))//拿回去的比要的多,那就还得拿回去 // back += bikes[id]; // else //需要的比拿回去的多,还得拿过来 // { // need += ((0 - bikes[id]) - back); // back = 0; // } // } // } // if (minNeed > need) // { // minNeed = need; // minBack = back; // path = tempPath; // } // else if (minNeed == need && back< minBack) // { // minBack = back; // path = tempPath; // } // tempPath.pop_back(); // return; // } // for (int i = 0; i < father[v].size(); ++i) // DFS(father[v][i]); // tempPath.pop_back(); //} //int main() //{ // fill(graph[0], graph[0] + 505 * 505, INT32_MAX); // fill(dis, dis + 505, INT32_MAX); // cin >> C >> N >> Sp >> M; // for (int i = 1; i <= N; ++i) // { // cin >> bikes[i]; // bikes[i] = bikes[i] - C / 2; // } // while (M--) // { // cin >> c1 >> c2 >> w; // graph[c1][c2] = graph[c2][c1] = w; // } // Dijkstra(0); // DFS(Sp); // cout << minNeed << " " << 0; // for (int i = path.size() - 2; i >= 0; --i) // cout << "->" << path[i]; // cout << " " << minBack; // return 0; //} // //#include <iostream> //#include <vector> //using namespace std; //int theC, n, m, den, cap[505], v[505][505] = { 0 }; //vector<int>father[505]; //void Dijstra( ) //{ // vector<int>path(n + 1, INT32_MAX); // vector<bool>visit(n + 1, false); // path[0] = 0; // for (int i = 0; i <= n; ++i) // { // int index = -1, minD = INT32_MAX; // for (int j = 0; j <= n; ++j) // { // if (visit[j] == false && minD > path[j]) // { // index = j; // minD = path[j]; // } // } // if (index == -1)break; // visit[index] = true; // for (int u = 0; u <= n; ++u) // { // if (visit[u] == false && v[index][u] > 0) // { // if (path[u] > path[index] + v[index][u]) // { // path[u] = path[index] + v[index][u]; // father[u].clear(); // father[u].push_back(index); // } // else if (path[u] == path[index] + v[index][u]) // father[u].push_back(index); // } // } // } //} //int minNeed = INT32_MAX, minBack = INT32_MAX; //vector<int>temp, res; //void DFS(int x) //{ // temp.push_back(x); // if (x == 0) // { // int need = 0, back = 0; // for (int i = temp.size()-2; i >= 0; --i) // { // int dis = cap[temp[i]] - theC / 2; // if (dis >= 0) // back += dis; // else // { // if (back + dis >= 0)//带回去的可以补充缺少的 // back += dis; // else//缺太多 // { // need -= (back + dis); // back = 0; // } // } // } // if (need < minNeed) // { // res = temp; // minNeed = need; // minBack = back; // } // else if (need ==minNeed && back < minBack) // { // minBack = back; // res = temp; // } // } // for (auto a : father[x]) // DFS(a); // temp.pop_back(); //} //int main() //{ // cin >> theC >> n >> den >> m; // for (int i = 1; i <= n; ++i) // cin >> cap[i]; // while (m--) // { // int a, b, c; // cin >> a >> b >> c; // v[a][b] = v[b][a] = c; // } // Dijstra( ); // DFS(den); // cout << minNeed << " " << 0; // for (int i = res.size() - 2; i >= 0; --i) // cout << "->" << res[i]; // cout << " " << minBack; // return 0; //}
85b70207399e14e95cfd2ca4ecd90908c751e7ee
34216a295b2a1b2ea98d726f5bf5368eb8919bc3
/RequestTestTool/QNetWorkThread.cpp
7a19af815795ded6c82ba9fe85195ddbc00e58ed
[]
no_license
julian-zhuang/RequestTestTool
833f22211cb488678ffd98567e4bdeb05c905c49
76d3daae0a6266ba22f33553837ce78b465f8afe
refs/heads/master
2020-03-21T00:03:01.745124
2018-07-09T08:03:12
2018-07-09T08:03:12
137,875,025
0
0
null
null
null
null
GB18030
C++
false
false
5,814
cpp
#include "QNetWorkThread.h" QNetWorkThread::~QNetWorkThread() { if (SSL_Enadble == false) { m_socket.disconnect(); } if (SSL_Enadble == true) { m_SSLsocket.disconnect(); } } void QNetWorkThread::SetTimeOut(unsigned int UtimeOut) { TimeOut = UtimeOut * 100; } void QNetWorkThread::SetKeepAlive(bool Ubool) { IsKeepAlive = Ubool; } void QNetWorkThread::SetThreadControlSignal(unsigned int UCOntorl) { m_ControlSignal = UCOntorl; } void QNetWorkThread::run() { //发出线程开始的信号 emit ThreadStatusSignals(THREAD_START, 0); //建立连接 if (EstablishConnection() < 0 ) { emit ThreadStatusSignals(THREAD_END, 0); return; } //循环发送和读取 bool flag = true; while (flag) { if (SendRequestData() < 0 ) { emit ThreadStatusSignals(THREAD_END, 0); return; } if (RecvResponseData() < 0) { emit ThreadStatusSignals(THREAD_END, 0); return; } //一次发送接收完成,阻塞等待 switch (WaitControlSignal()) { case THREAD_CONTROL_CONTINUE: break; case THREAD_CONTROL_STOP: flag = false; break; default: flag = false; break; } } emit ThreadStatusSignals(THREAD_END, 0); return; } void QNetWorkThread::NW_Disconnect() { emit ThreadStatusSignals(THREAD_CONNECTED, 0); //连接超时 } void QNetWorkThread::NW_Error(QAbstractSocket::SocketError socketError) { int a = socketError; int b = 0; } void QNetWorkThread::NW_SSLError() { m_ControlSignal = THREAD_CONTROL_STOP; } void QNetWorkThread::NW_Encrypted() { isEncryption = true; } unsigned int QNetWorkThread::WaitControlSignal() { if (IsKeepAlive == false) { return THREAD_CONTROL_STOP; } while (1) { if (m_ControlSignal == THREAD_CONTROL_STOP) { m_ControlSignal = 0; return THREAD_CONTROL_STOP; } if (m_ControlSignal == THREAD_CONTROL_CONTINUE) { m_ControlSignal = 0; return THREAD_CONTROL_CONTINUE; } usleep(1);//切换CPU时间片 } return 0; } int QNetWorkThread::EstablishConnection() { if (SSL_Enadble == true) { connect(&m_SSLsocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(NW_Error(QAbstractSocket::SocketError)), Qt::DirectConnection); connect(&m_SSLsocket, SIGNAL(disconnected()), this, SLOT(NW_Disconnect()), Qt::DirectConnection); connect(&m_SSLsocket, SIGNAL(sslErrors()), this, SLOT(NW_SSLError()), Qt::DirectConnection); connect(&m_SSLsocket, SIGNAL(encrypted()), this, SLOT(NW_Encrypted()), Qt::DirectConnection); m_SSLsocket.modeChanged(QSslSocket::SslClientMode); m_SSLsocket.connectToHost(QString::fromStdString(Host), Port); if (!m_SSLsocket.waitForConnected(TimeOut)) { emit ThreadStatusSignals(THREAD_CONNECT_TIMEOUT, 0); //连接超时 return -1; } emit ThreadStatusSignals(THREAD_CONNECT_SUCCESS, 0); m_SSLsocket.startClientEncryption(); if (!m_SSLsocket.waitForEncrypted(TimeOut)) { emit ThreadStatusSignals(THREAD_SSL_FALLED, 0); m_SSLsocket.disconnect(); return -2; } emit ThreadStatusSignals(THREAD_SSL_SUCCESSFUL, 0); } if (SSL_Enadble == false) { connect(&m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(NW_Error(QAbstractSocket::SocketError)), Qt::DirectConnection); connect(&m_socket, SIGNAL(disconnected()), this, SLOT(NW_Disconnect()), Qt::DirectConnection); m_socket.connectToHost(Host.c_str(), Port); if (!m_socket.waitForConnected(TimeOut)) { emit ThreadStatusSignals(THREAD_CONNECT_TIMEOUT, 0); //连接超时 return -1; } emit ThreadStatusSignals(THREAD_CONNECT_SUCCESS, 0); } return 0; } int QNetWorkThread::SendRequestData() { int RequestDataLenth = RequestData.str().length(); int SentSuccessfully = 0; const char *m_RequestData = RequestData.str().c_str(); if (SSL_Enadble == true) { while (RequestDataLenth - SentSuccessfully > 0) { SentSuccessfully = m_SSLsocket.write(m_RequestData + SentSuccessfully, RequestDataLenth - SentSuccessfully); if (SentSuccessfully < 0) { emit ThreadStatusSignals(THREAD_SEND_FALLED, -1); return -1; } emit ThreadStatusSignals(THREAD_SEND_SUCCESS_COUNT, SentSuccessfully); //发送计数 } } if (SSL_Enadble == false) { while (RequestDataLenth - SentSuccessfully > 0) { SentSuccessfully = m_socket.write(m_RequestData + SentSuccessfully, RequestDataLenth - SentSuccessfully); if (SentSuccessfully < 0) { emit ThreadStatusSignals(THREAD_SEND_FALLED, -1); return -1; } emit ThreadStatusSignals(THREAD_SEND_SUCCESS_COUNT, SentSuccessfully); //发送计数 } } emit ThreadStatusSignals(THREAD_SEND_SUCCESS, SentSuccessfully); //发送完成 return 0; } int QNetWorkThread::RecvResponseData() { QByteArray m_Response; QByteArray m_Response_Tmp; ResponseData.clear(); ResponseData.str(""); m_Response.clear(); m_Response_Tmp.clear(); int RecvDataCount = 1; if (SSL_Enadble == true) { if (!m_SSLsocket.waitForReadyRead(TimeOut)) { emit ThreadStatusSignals(THREAD_RECV_TIMEOUT, 0); //接收超时 return -1; } while (RecvDataCount) { m_Response_Tmp.clear(); m_Response_Tmp = m_SSLsocket.readAll(); RecvDataCount = m_Response_Tmp.size(); m_Response.append(m_Response_Tmp); emit ThreadStatusSignals(THREAD_RECV_SUCCESS_COUNT, m_Response.size()); //接收计数 } ResponseData << m_Response.toStdString(); } if (SSL_Enadble == false) { if (!m_socket.waitForReadyRead(TimeOut)) { emit ThreadStatusSignals(THREAD_RECV_TIMEOUT, 0); //接收超时 return -1; } while (RecvDataCount) { m_Response_Tmp.clear(); m_Response_Tmp = m_socket.readAll(); RecvDataCount = m_Response_Tmp.size(); m_Response.append(m_Response_Tmp); emit ThreadStatusSignals(THREAD_RECV_SUCCESS_COUNT, m_Response.size()); //接收计数 } ResponseData << m_Response.toStdString(); } emit ThreadStatusSignals(THREAD_RECV_SUCCESS, 0); return 0; }
9056044aeafd9ad85583f47dca6c61dcf07da7ab
8db59eac65c01e4b6ec5b4ac5488564da8e7968e
/source/challenge.h
094a71f6facd46baa0e5d529f90d21fc9c835c43
[]
no_license
fjunqueira/world-builder
8b24b926d8eef163155aa0f5f2b1d53463a6a1aa
764a1cc232d1cc938bd5ab29daeacbe545a94957
refs/heads/master
2020-05-22T01:10:52.806494
2017-03-17T00:31:49
2017-03-17T00:31:49
62,979,959
3
0
null
null
null
null
UTF-8
C++
false
false
821
h
#ifndef WORLD_BUILDER_CHALLENGE_H #define WORLD_BUILDER_CHALLENGE_H #include <string> struct Challenge { Challenge() {} Challenge(const std::string& description, const float& grass_percentage, const float& water_percentage, const float& sand_percentage, const float& vegetation_percentage, const float& tolerable_error) : description_(description), grass_percentage_(grass_percentage), water_percentage_(water_percentage), sand_percentage_(sand_percentage), vegetation_percentage_(vegetation_percentage), tolerable_error_(tolerable_error) { } std::string description_; float grass_percentage_; float water_percentage_; float sand_percentage_; float vegetation_percentage_; float tolerable_error_; }; #endif // WORLD_BUILDER_CHALLENGE_H
ed096170d78a101bab09b4965bd3840451de1a19
9184e230f8b212e8f686a466c84ecc89abe375d1
/arcseventdata/module/bindings.cc
cde951c962ed67a54919d7ac8ecbe2cfc9a2542f
[]
no_license
danse-inelastic/DrChops
75b793d806e6351dde847f1d92ab6eebb1ef24d2
7ba4ce07a5a4645942192b4b81f7afcae505db90
refs/heads/master
2022-04-26T17:37:41.666851
2015-05-02T23:21:13
2015-05-02T23:21:13
34,094,584
0
1
null
2020-09-10T01:50:10
2015-04-17T03:30:52
Python
UTF-8
C++
false
false
4,745
cc
// -*- C++ -*- // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Michael A.G. Aivazis // California Institute of Technology // (C) 1998-2005 All Rights Reserved // // <LicenseText> // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #include <portinfo> #include <Python.h> #include "bindings.h" #include "misc.h" // miscellaneous methods #include "wrap_events2EvenlySpacedIx.h" #include "wrap_events2EvenlySpacedIxy.h" #include "wrap_events2EvenlySpacedIxxxx.h" #include "wrap_readevents.h" #include "wrap_readpixelpositions.h" #include "wrap_mslice_formating.h" #include "wrap_normalize_iqe.h" #include "wrap_normalize_iqqqe.h" #include "wrap_normalize_ihkle.h" // the method table struct PyMethodDef pyarcseventdata_methods[] = { // dummy entry for testing {pyarcseventdata_hello__name__, pyarcseventdata_hello, METH_VARARGS, pyarcseventdata_hello__doc__}, {pyarcseventdata_copyright__name__, pyarcseventdata_copyright, METH_VARARGS, pyarcseventdata_copyright__doc__}, // events2Ipix {wrap_arcseventdata::events2Ipix_numpyarray__name__, wrap_arcseventdata::events2Ipix_numpyarray, METH_VARARGS, wrap_arcseventdata::events2Ipix_numpyarray__doc__}, // events2Itof {wrap_arcseventdata::events2Itof_numpyarray__name__, wrap_arcseventdata::events2Itof_numpyarray, METH_VARARGS, wrap_arcseventdata::events2Itof_numpyarray__doc__}, // events2Idspacing {wrap_arcseventdata::events2Idspacing_numpyarray__name__, wrap_arcseventdata::events2Idspacing_numpyarray, METH_VARARGS, wrap_arcseventdata::events2Idspacing_numpyarray__doc__}, // events2IpixE {wrap_arcseventdata::events2IpixE_numpyarray__name__, wrap_arcseventdata::events2IpixE_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IpixE_numpyarray__doc__}, // events2IQE {wrap_arcseventdata::events2IQE_numpyarray__name__, wrap_arcseventdata::events2IQE_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IQE_numpyarray__doc__}, // events2Ipixtof {wrap_arcseventdata::events2Ipixtof_numpyarray__name__, wrap_arcseventdata::events2Ipixtof_numpyarray, METH_VARARGS, wrap_arcseventdata::events2Ipixtof_numpyarray__doc__}, // events2Ipixd {wrap_arcseventdata::events2Ipixd_numpyarray__name__, wrap_arcseventdata::events2Ipixd_numpyarray, METH_VARARGS, wrap_arcseventdata::events2Ipixd_numpyarray__doc__}, // events2IpixEi {wrap_arcseventdata::events2IpixEi_numpyarray__name__, wrap_arcseventdata::events2IpixEi_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IpixEi_numpyarray__doc__}, // events2IpixL {wrap_arcseventdata::events2IpixL_numpyarray__name__, wrap_arcseventdata::events2IpixL_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IpixL_numpyarray__doc__}, // events2IQQQE {wrap_arcseventdata::events2IQQQE_numpyarray__name__, wrap_arcseventdata::events2IQQQE_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IQQQE_numpyarray__doc__}, // events2IhklE {wrap_arcseventdata::events2IhklE_numpyarray__name__, wrap_arcseventdata::events2IhklE_numpyarray, METH_VARARGS, wrap_arcseventdata::events2IhklE_numpyarray__doc__}, // readevents {wrap_arcseventdata::readevents__name__, wrap_arcseventdata::readevents, METH_VARARGS, wrap_arcseventdata::readevents__doc__}, // readpixelpositions {wrap_arcseventdata::readpixelpositions__name__, wrap_arcseventdata::readpixelpositions, METH_VARARGS, wrap_arcseventdata::readpixelpositions__doc__}, // SGrid_str {wrap_arcseventdata::SGrid_str_numpyarray__name__, wrap_arcseventdata::SGrid_str_numpyarray, METH_VARARGS, wrap_arcseventdata::SGrid_str_numpyarray__doc__}, // calcSolidAngleQE {wrap_arcseventdata::calcSolidAngleQE_numpyarray__name__, wrap_arcseventdata::calcSolidAngleQE_numpyarray, METH_VARARGS, wrap_arcseventdata::calcSolidAngleQE_numpyarray__doc__}, // calcSolidAngleQQQE {wrap_arcseventdata::calcSolidAngleQQQE_numpyarray__name__, wrap_arcseventdata::calcSolidAngleQQQE_numpyarray, METH_VARARGS, wrap_arcseventdata::calcSolidAngleQQQE_numpyarray__doc__}, // calcSolidAngleHKLE {wrap_arcseventdata::calcSolidAngleHKLE_numpyarray__name__, wrap_arcseventdata::calcSolidAngleHKLE_numpyarray, METH_VARARGS, wrap_arcseventdata::calcSolidAngleHKLE_numpyarray__doc__}, // Sentinel {0, 0} }; // version // $Id$ // End of file
2670932e047edbd3b211eb09341bb2ff2206ed76
309e9e43f6c105f686a5991d355f201423b6f20e
/old study/c++/iotek_cpp_course/data/object1.cpp
efcfee118d2c379a0c3cba855b9034056df013c9
[]
no_license
jikal/mystudy
d1e106725154730de0567fe4d7a7efa857b09682
ff51292c3fcb93d354c279e2c5222bc17b874966
refs/heads/master
2020-05-30T09:36:55.439089
2015-06-30T02:58:22
2015-06-30T02:58:22
35,258,479
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
#include <stdio.h> #include <stdlib.h> class A{ public: A() { printf("A created\n"); } ~A() { printf("A destroyed\n"); } }; class B{ public: B() { printf("B created\n"); } ~B() { printf("B destroyed\n"); } }; A globalA; B globalB; int foo(void) { printf("\nfoo()------------------------->\n"); A localA; static B localB; printf("foo()<----------------------------\n"); return 0; } int main(int argc, char *argv[]) { printf("main()------------------------>\n"); foo(); foo(); printf("main()<---------------------------\n"); return 0; }
[ "zhk@ubuntu.(none)" ]
zhk@ubuntu.(none)
774f5ae43dc7d3177557608fb6cfd8e9b48277f1
8c19c9b454c02f897142bcb6f4d39d46da82e344
/praktikum09/Excercise2Main.cpp
577eb5a0df8895cd5b3f8e29ecf7940ea6e4c023
[]
no_license
mkotzjan/CppInternship
1a93b9d04845eae3d13eb97c247281ae6c400075
a2a2e14f4e61eef6f9a141179e5f19598dfd4aeb
refs/heads/master
2021-01-15T11:38:56.312035
2015-05-13T16:34:39
2015-05-13T16:34:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
// Aufgabe 2 #include <iostream> #include <stdlib.h> using namespace std; // Rekursive Berechnung von Fibonacci int fibo(int n) { if (n < 2) { return n; } else { return fibo(n - 1) + fibo(n - 2); } } int main(int argc, char *argv[]) { // prüfen ob anzahl der Parameter stimmt if (argc != 2) { cout << "Calculates the n fibonacci number." << endl; cout << "Using:" << endl; cout << "./Excercise2Main <n>" << endl; } else { cout << "n. fibonacci:" << endl; cout << fibo(atoi(argv[1])) << endl; } } // Getestet: // Parameteranzahl != 1 // 0 // 1 // 3 // 10
8ff10ed8a184a0398102fb7d772594b080fa7136
8d502c627473aa9aaf44672b296df9d8dc3030e9
/include/zg/messagetree/server/MessageTreeDatabaseObject.h
bedec8fe60b2947cec7b424918d5dc4ac2405ffb
[ "BSD-3-Clause" ]
permissive
ruurdadema/zg_choir
901c5c288f5627fb331c46adbb34191aaf1f017b
86a4e41d9dae2bb32dc1d20d95a66c0173a9292d
refs/heads/master
2023-03-06T18:16:44.149214
2023-02-01T16:00:10
2023-02-01T16:00:10
131,770,423
0
0
BSD-3-Clause
2018-05-17T07:44:05
2018-05-01T22:39:03
C++
UTF-8
C++
false
false
28,611
h
#ifndef MessageTreeDatabaseObject_h #define MessageTreeDatabaseObject_h #include "zg/IDatabaseObject.h" #include "zg/messagetree/gateway/ITreeGatewaySubscriber.h" // for TreeGatewayFlags #include "reflector/StorageReflectSession.h" // for SetDataNodeFlags #include "util/NestCount.h" namespace zg { class MessageTreeDatabasePeerSession; /** This is a concrete implementation of IDatabaseObject that uses a subtree of the MUSCLE * Message-tree database as the data structure it synchronizes across peers. */ class MessageTreeDatabaseObject : public IDatabaseObject { public: /** Constructor * @param session pointer to the MessageTreeDatabasePeerSession object that created us * @param dbIndex our index within the databases-list. * @param rootNodePath a sub-path indicating where the root of our managed Message sub-tree * should be located (relative to the MessageTreeDatabasePeerSession's session-node) * May be empty if you want the session's session-node itself of be the * root of the managed sub-tree. */ MessageTreeDatabaseObject(MessageTreeDatabasePeerSession * session, int32 dbIndex, const String & rootNodePath); /** Destructor */ virtual ~MessageTreeDatabaseObject() {/* empty */} // IDatabaseObject implementation virtual void SetToDefaultState(); virtual status_t SetFromArchive(const ConstMessageRef & archive); virtual status_t SaveToArchive(const MessageRef & archive) const; virtual uint32 GetCurrentChecksum() const {return _checksum;} virtual uint32 CalculateChecksum() const; virtual String ToString() const; /** Returns a pointer to the MessageTreeDatabasePeerSession object that created us, or NULL * if this object was not created by a MessageTreeDatabasePeerSession. */ MessageTreeDatabasePeerSession * GetMessageTreeDatabasePeerSession() const; /** Checks if the given path belongs to this database. * @param path a session-relative node-path (eg "dbs/db_0/foo/bar"), or an absolute node-path (eg "/zg/0/dbs/db_0/foo/bar"). * @param optRetRelativePath if non-NULL, and this method returns true, then the String this points to will * be written to with the path to the node that is relative to our root-node (eg "foo/bar"). * @returns The distance between path and our root-node, in "hops", on success (eg 0 means the path matches our database's * root-node exactly; 1 means it matches at the level of our database's children, and so on). * Returns -1 if the path doesn't match anything in our database. */ int32 GetDatabaseSubpath(const String & path, String * optRetRelativePath = NULL) const; /** Returns the session-relative path of the root of this database's subtree (without any trailing slash) */ const String & GetRootPathWithoutSlash() const {return _rootNodePathWithoutSlash;} /** Returns the session-relative path of the root of this database's subtree (with a trailing slash) */ const String & GetRootPathWithSlash() const {return _rootNodePathWithSlash;} /** Sends a request to the senior peer that the specified node-value be uploaded to the message-tree database. * @param path session-relative path of the database node to upload (may be wildcarded, but only if (optPayload) is a NULL reference) * @param optPayload reference to the Message payload you want added/updated at the given path, or a NULL reference if you want * node(s) matching the given path to be deleted. * @param flags optional TREE_GATEWAY_* flags to modify the behavior of the upload. * @param optBefore if non-mpety, the name of the sibling node that this node should be placed before, or empty if you want the * uploaded node to be placed at the end of the index. Only used if TREE_GATEWAY_FLAG_INDEXED was specified. * @param optOpTag if non-empty, a String provided by the client-side ITreeGatewaySubscriber to be associated with this operation. * Subscribers will receive this tag as part of their TreeNodeUpdated() callbacks. This string can be whatever the caller likes. * @returns B_NO_ERROR on success, or another error code on failure. */ virtual status_t UploadNodeValue(const String & path, const ConstMessageRef & optPayload, TreeGatewayFlags flags, const String & optBefore, const String & optOpTag); /** Sends a request to the senior peer that the specified node sub-tree be uploaded. * @param path session-relative path indicating where in the message-tree to place the root of the uploaded sub-tree. * @param valuesMsg should contain the subtree to upload. * @param flags optional TREE_GATEWAY_* flags to modify the behavior of the upload. * @param optOpTag if non-empty, a String provided by the client-side ITreeGatewaySubscriber to be associated with this operation. * Subscribers will receive this tag as part of their TreeNodeUpdated() callbacks. This string can be whatever the caller likes. * @returns B_NO_ERROR on success, or another error code on failure. */ virtual status_t UploadNodeSubtree(const String & path, const ConstMessageRef & valuesMsg, TreeGatewayFlags flags, const String & optOpTag); /** Sends a request to remove matching nodes from the database. * @param path session-relative path indicating which node(s) to delete. May be wildcarded. * @param optFilter if non-NULL, only nodes whose Message-payloaded are matched by this query-filter will be deletes. * @param flags optional TREE_GATEWAY_* flags to modify the behavior of the operation. * @param optOpTag if non-empty, a String provided by the client-side ITreeGatewaySubscriber to be associated with this operation. * Subscribers will receive this tag as part of their TreeNodeUpdated() callbacks. This string can be whatever the caller likes. * @returns B_NO_ERROR on success, or another error code on failure. */ virtual status_t RequestDeleteNodes(const String & path, const ConstQueryFilterRef & optFilter, TreeGatewayFlags flags, const String & optOpTag); /** Sends a request to modify the ordering of the indices of matching nodes in the database. * @param path session-relative path indicating which node(s) to modify the indices of. May be wildcarded. * @param optBefore if non-empty, the name of the sibling node that this node should be placed before, or empty if you want the * uploaded node to be placed at the end of the index. Only used if TREE_GATEWAY_FLAG_INDEXED was specified. * @param optFilter if non-NULL, only nodes whose Message-payloaded are matched by this query-filter will have their indices modified. * @param flags optional TREE_GATEWAY_* flags to modify the behavior of the operation. * @param optOpTag if non-empty, a String provided by the client-side ITreeGatewaySubscriber to be associated with this operation. * Subscribers will receive this tag as part of their TreeNodeUpdated() callbacks. This string can be whatever the caller likes. * @returns B_NO_ERROR on success, or another error code on failure. */ virtual status_t RequestMoveIndexEntry(const String & path, const String & optBefore, const ConstQueryFilterRef & optFilter, TreeGatewayFlags flags, const String & optOpTag); /** This callback method is called when a node in this database-object's subtree is created, updated, or destroyed. * @param relativePath the path to this node (relative to this database-object's root-node) * @param node a reference to the node's current state -- see node.GetData() for the node's current (post-change) payload. * @param oldDataRef a reference to the node's payload as it was before this change (or a NULL reference if this node is being created now) * @param isBeingRemoved true iff this node is being deleted by this change * @note be sure to call up to the parent implementation of this method if you override it! */ virtual void MessageTreeNodeUpdated(const String & relativePath, DataNode & node, const ConstMessageRef & oldDataRef, bool isBeingRemoved); /** This callback method is called when the index of node in this database-object's subtree is being modified. * @param relativePath the path to this node (relative to this database-object's root-node) * @param node a reference to the node's current state * @param op An INDEX_OP_* value indicating what type of index-update is being applied to the index. * @param index the location within the index at which the new entry is to be inserted (if op is INDEX_OP_ENTRY_INSERTED) * or removed (if op is INDEX_OP_ENTRYREMOVED). Not used if op is INDEX_OP_ENTRYCLEARED. * @param key Name of the node that is being inserted (if op is INDEX_OP_ENTRYINSERTED) or removed (if op is INDEX_OP_ENTRYREMOVED) * Not used if op is INDEX_OP_ENTRYCLEARED. * @note be sure to call up to the parent implementation of this method if you override it! */ virtual void MessageTreeNodeIndexChanged(const String & relativePath, DataNode & node, char op, uint32 index, const String & key); /** Called after an ITreeGatewaySubscriber somewhere has called SendMessageToTreeSeniorPeer(). * @param fromPeerID the ID of the ZGPeer that the subscriber is directly connected to * @param payload the Message that the subscriber sent to us * @param tag a tag-string that can be used to route replies back to the originating subscriber, if desired. * @note Default implementation just prints an error to the log saying that the Message wasn't handled. */ virtual void MessageReceivedFromTreeGatewaySubscriber(const ZGPeerID & fromPeerID, const MessageRef & payload, const String & tag); /** Call this to send a Message back to an ITreeGatewaySubscriber (eg in response to a MessageReceivedFromTreeGatewaySubscriber() callback) * @param toPeerID the ID of the ZGPeer that the subscriber is directly connected to * @param tag the tag-String to use to direct the Message to the correct subscriber (as was previously passed in to MessageReceivedFromTreeGatewaySubscriber()) * @param payload the Message to send to the subscriber * @returns B_NO_ERROR on success, or an error code on failure. */ virtual status_t SendMessageToTreeGatewaySubscriber(const ZGPeerID & toPeerID, const String & tag, const ConstMessageRef & payload); /** Returns a reference to our currently-active operation-tag, or a reference to an empty string if there isn't one. */ const String & GetCurrentOpTag() const {return *_opTagStack.TailWithDefault(&GetEmptyString());} protected: // IDatabaseObject API virtual ConstMessageRef SeniorUpdate(const ConstMessageRef & seniorDoMsg); virtual status_t JuniorUpdate(const ConstMessageRef & juniorDoMsg); /** Called by SeniorUpdate() when it wants to add a set/remove-node action to the Junior-Message it is assembling for junior peers to act on when they update their databases. * Default implementation just adds the appropriate update-Message to (assemblingMessage), but subclasses can * override this to do more (eg to also record undo-stack information, in the UndoStackMessageTreeDatabaseObject subclass). * @param relativePath path to the node in question, relative to our subtree's root. * @param oldPayload the payload that our node had before we made this change (NULL if the node is being created) * @param newPayload the payload that our node has after we make this change (NULL if the node is being destroyed) * @param assemblingMessage the Message we are gathering records into. * @param prepend True iff the filed Message should be prepended to the beginning of (assemblingMessage), or false if it should be appended to the end. * @param optOpTag Client-provided descriptive tag for this operation. * @returns a valid MessageRef on success, or a NULL MessageRef on failure. */ virtual status_t SeniorRecordNodeUpdateMessage(const String & relativePath, const ConstMessageRef & oldPayload, const ConstMessageRef & newPayload, MessageRef & assemblingMessage, bool prepend, const String & optOpTag); /** Called by SeniorUpdate() when it wants to add an update-node-index action to the Junior-Message it is assembling for junior peers to act on when they update their databases. * Default implementation just adds the appropriate update-Message to (assemblingMessage), but subclasses can * override this to do more (eg to also record undo-stack information, in the UndoStackMessageTreeDatabaseObject subclass). * @param relativePath path to the node in question, relative to our subtree's root. * @param op the index-update opcode of the change * @param index the position within the index of the change * @param key the name of the child node in the index * @param assemblingMessage the Message we are gathering records into. * @param prepend True iff the filed Message should be prepended to the beginning of (assemblingMessage), or false if it should be appended to the end. * @param optOpTag Client-provided descriptive tag for this operation. * @returns a valid MessageRef on success, or a NULL MessageRef on failure. */ virtual status_t SeniorRecordNodeIndexUpdateMessage(const String & relativePath, char op, uint32 index, const String & key, MessageRef & assemblingMessage, bool prepend, const String & optOpTag); /** Called by SeniorUpdate() when it needs to handle an individual sub-Message in the senior-update context * @param msg the sub-Message to handle * @returns B_NO_ERROR on success, or another error-code on failure. * @note the default implementation handles the standard Message-Tree functionality, but subclasses can override this to provide more handling if they want to. */ virtual status_t SeniorMessageTreeUpdate(const ConstMessageRef & msg); /** Called by SeniorUpdate() when it needs to handle an individual sub-Message in the junior-update context * @param msg the sub-Message to handle * @returns B_NO_ERROR on success, or another error-code on failure. * @note the default implementation handles the standard Message-Tree functionality, but subclasses can override this to provide more handling if they want to. */ virtual status_t JuniorMessageTreeUpdate(const ConstMessageRef & msg); /** Used to decide whether or not to handle a given MTD_COMMAND_* update Message. * Used as a hook by the UndoStackMessageTreeDatabaseObject subclass to filter out undesirable meta-data updates * when executing an "undo" or a "redo" operation. Default implementation just always returns true. * @param path the node-path specified by the update-message * @param flags the TreeGatewayFlags specified by the update-message */ virtual bool IsOkayToHandleUpdateMessage(const String & path, TreeGatewayFlags flags) const {(void) path; (void) flags; return true;} /** When called from within a SeniorUpdate() or JuniorUpdate() context, returns true iff the update we're currently * handling was tagged with the TREE_GATEWAY_FLAG_INTERIM (and can therefore be skipped when performing an undo or redo) */ bool IsHandlingInterimUpdate() const {return _interimUpdateNestCount.IsInBatch();} /** * Returns a pointer to the first DataNode object that mactches the given node-path. * @param nodePath The node's path, relative to this database object's root-path. Wildcarding is okay. * @return A pointer to the specified DataNode, or NULL if no node matching that path was found. */ DataNode * GetDataNode(const String & nodePath) const; /** Pass-through to StorageReflectSession::SetDataNode() on our MessageTreeDatabasePeerSession object * @param nodePath The node's path, relative to this database object's root-path. * @param dataMsgRef The value to set the node to * @param flags list of SETDATANODE_FLAG_* values to affect our behavior. Defaults to no-bits-set. * @param optInsertBefore If (addToIndex) is true, this may be the name of the node to insert this new node before in the index. * If empty, the new node will be appended to the end of the index. If (addToIndex) is false, this argument is ignored. * @param optOpTag an optional arbitrary tag-string to present to subscribers to describe this operation. * @return B_NO_ERROR on success, or an error code on failure. */ status_t SetDataNode(const String & nodePath, const ConstMessageRef & dataMsgRef, SetDataNodeFlags flags=SetDataNodeFlags(), const String &optInsertBefore=GetEmptyString(), const String & optOpTag=GetEmptyString()); /** Convenience method: Adds nodes that match the specified path to the passed-in Queue. * @param nodePath the node path to match against. May be absolute (eg "/0/1234/frc*") or relative (eg "blah"). * If it's a relative path, only nodes in the current session's subtree will be searched. * @param filter If non-NULL, only nodes whose data Messages match this filter will be added to the (retMatchingNodes) table. * @param retMatchingNodes A Queue that will on return contain the list of matching nodes. * @param maxResults Maximum number of matching nodes to return. Defaults to MUSCLE_NO_LIMIT. * @return B_NO_ERROR on success, or an error code on failure. Note that failing to find any matching nodes is NOT considered an error. */ status_t FindMatchingNodes(const String & nodePath, const ConstQueryFilterRef & filter, Queue<DataNodeRef> & retMatchingNodes, uint32 maxResults = MUSCLE_NO_LIMIT) const; /** Convenience method: Same as FindMatchingNodes(), but finds only the first matching node. * @param nodePath the node path to match against. May be absolute (eg "/0/1234/frc*") or relative (eg "blah"). * If it's a relative path, only nodes in the current session's subtree will be searched. * @param filter If non-NULL, only nodes whose data Messages match this filter will be added to the (retMatchingNodes) table. * @returns a reference to the first matching node on success, or a NULL reference on failure. */ DataNodeRef FindMatchingNode(const String & nodePath, const ConstQueryFilterRef & filter) const; /** Convenience method (used by some customized daemons) -- Given a source node and a destination path, * Make (path) a deep, recursive clone of (node). * @param sourceNode Reference to a DataNode to clone. * @param destPath Path of where the newly created node subtree will appear. Should be relative to our home node. * @param flags optional bit-chord of SETDATANODE_FLAG_* flags to modify our behavior. Defaults to no-flags-set. * @param optInsertBefore If (addToTargetIndex) is true, this argument will be passed on to InsertOrderedChild(). * Otherwise, this argument is ignored. * @param optPruner If non-NULL, this object can be used as a callback to prune the traversal or filter * the MessageRefs cloned. * @param optOpTag an optional arbitrary tag-string to present to subscribers to describe this operation. * @return B_NO_ERROR on success, or an error code on failure (may leave a partially cloned subtree on failure) */ status_t CloneDataNodeSubtree(const DataNode & sourceNode, const String & destPath, SetDataNodeFlags flags = SetDataNodeFlags(), const String * optInsertBefore = NULL, const ITraversalPruner * optPruner = NULL, const String & optOpTag = GetEmptyString()); /** Pass-through to StorageReflectSession::RemoveDataNodes() on our MessageTreeDatabasePeerSession object * @param nodePath The node's path, relative to this database object's root-path. Wildcarding is okay. * @param filterRef optional ConstQueryFilter to restrict which nodes that match (nodePath) actually get removed * @param quiet If set to true, subscribers won't be updated regarding this change to the database. * @param optOpTag an optional arbitrary tag-string to present to subscribers to describe this operation. * @return B_NO_ERROR on success, or an error code on failure. */ status_t RemoveDataNodes(const String & nodePath, const ConstQueryFilterRef & filterRef = ConstQueryFilterRef(), bool quiet = false, const String & optOpTag = GetEmptyString()); /** Pass-through to StorageReflectSession::MoveIndexEntries() on our MessageTreeDatabasePeerSession object * @param nodePath The node's path, relative to this database object's root-path. Wildcarding is okay. * @param optBefore if non-empty, the moved nodes in the index will be moved to just before the node with this name. If empty, they'll be moved to the end of the index. * @param filterRef If non-NULL, we'll use the given QueryFilter object to filter out our result set. * Only nodes whose Messages match the QueryFilter will have their parent-nodes' index modified. Default is a NULL reference. * @param optOpTag an optional arbitrary tag-string to present to subscribers to describe this operation. * @return B_NO_ERROR on success, or an error code on failure. */ status_t MoveIndexEntries(const String & nodePath, const String & optBefore, const ConstQueryFilterRef & filterRef, const String & optOpTag = GetEmptyString()); /** Pass-through to StorageReflectSession::SaveNodeTreeToMessage() on our MessageTreeDatabasePeerSession object * Recursively saves a given subtree of the node database into the given Message object, for safe-keeping. * (It's a bit more efficient than it looks, since all data Messages are reference counted rather than copied) * @param msg the Message to save the subtree into. This object can later be provided to RestoreNodeTreeFromMessage() to restore the subtree. * @param node The node to begin recursion from (ie the root of the subtree) * @param path The path to prepend to the paths of children of the node. Used in the recursion; you typically want to pass in "" here. * @param saveData Whether or not the payload Message of (node) should be saved. The payload Messages of (node)'s children will always be saved no matter what, as long as (maxDepth) is greater than zero. * @param maxDepth How many levels of children should be saved to the Message. If left as MUSCLE_NO_LIMIT (the default), * the entire subtree will be saved; otherwise the tree will be clipped to at most (maxDepth) levels. * If (maxDepth) is zero, only (node) will be saved. * @param optPruner If set non-NULL, this object will be used as a callback to prune the traversal, and optionally * to filter the data that gets saved into (msg). * @returns B_NO_ERROR on success, or an error code on failure. */ status_t SaveNodeTreeToMessage(Message & msg, const DataNode & node, const String & path, bool saveData, uint32 maxDepth = MUSCLE_NO_LIMIT, const ITraversalPruner * optPruner = NULL) const; /** Pass-through to StorageReflectSession::RestoreNodeTreeFromMessage() on our MessageTreeDatabasePeerSession object * Recursively creates or updates a subtree of the node database from the given Message object. * (It's a bit more efficient than it looks, since all data Messages are reference counted rather than copied) * @param msg the Message to restore the subtree from. This Message is typically one that was created earlier by SaveNodeTreeToMessage(). * @param path The relative path of the root node to add restored nodes into, eg "" is your MessageTreeDatabaseObject's rootNodePath-node. * @param loadData Whether or not the payload Message of (node) should be restored. The payload Messages of (node)'s children will always be restored no matter what. * @param flags Optional bit-chord of SETDATANODE_FLAG_* bits to affect our behavior. Defaults to no-flags-set. * @param maxDepth How many levels of children should be restored from the Message. If left as MUSCLE_NO_LIMIT (the default), * the entire subtree will be restored; otherwise the tree will be clipped to at most (maxDepth) levels. * If (maxDepth) is zero, only (node) will be restored. * @param optPruner If set non-NULL, this object will be used as a callback to prune the traversal, and optionally * to filter the data that gets loaded from (msg). * @param optOpTag an optional arbitrary tag-string to present to subscribers to describe this operation. * @returns B_NO_ERROR on success, or an error code on failure. */ status_t RestoreNodeTreeFromMessage(const Message & msg, const String & path, bool loadData, SetDataNodeFlags flags = SetDataNodeFlags(), uint32 maxDepth = MUSCLE_NO_LIMIT, const ITraversalPruner * optPruner = NULL, const String & optOpTag = GetEmptyString()); // A little RIAA class to manage pushing/popping the _opTagStack for us automagically class OpTagGuard { public: OpTagGuard(const String & optOpTag, MessageTreeDatabaseObject * dbObj) : _dbObj(dbObj), _optOpTag(optOpTag) { _pushed = ((_optOpTag.HasChars())&&(_dbObj->_opTagStack.AddTail(&_optOpTag).IsOK())); } ~OpTagGuard() {if (_pushed) _dbObj->_opTagStack.RemoveTail();} private: MessageTreeDatabaseObject * _dbObj; const String & _optOpTag; bool _pushed; }; #define DECLARE_OP_TAG_GUARD const OpTagGuard tagGuard(optOpTag, this) /** Convenience method for when we want to call SetDataNode(); returns the set of SETDATANODE_FLAGS_* bits * that corresponds to the passed-in set of TREE_GATEWAY_FLAG_* bits that pertain to uploading a data-node. * @param tgf a set of TREE_GATEWAY_FLAG_* bits * @returns the corresponding set of SETDATANODE_FLAG_* bits. */ SetDataNodeFlags ConvertTreeGatewayFlagsToSetDataNodeFlags(TreeGatewayFlags tgf) const; private: class SafeQueryFilter : public QueryFilter { public: SafeQueryFilter(const MessageTreeDatabaseObject * dbObj) : _dbObj(dbObj) {/* empty */} virtual bool Matches(ConstMessageRef & /*msg*/, const DataNode * optNode) const {return optNode ? _dbObj->IsNodeInThisDatabase(*optNode) : false;} virtual uint32 TypeCode() const {return 0;} // okay because we never save/restore this type anyway virtual status_t SaveToArchive(Message &) const {MCRASH("SafeQueryFilter shouldn't be saved to an archive"); return B_UNIMPLEMENTED;} virtual status_t SetFromArchive(const Message &) {MCRASH("SafeQueryFilter shouldn't be set from an archive"); return B_UNIMPLEMENTED;} private: const MessageTreeDatabaseObject * _dbObj; }; bool IsInSetupOrTeardown() const; bool IsNodeInThisDatabase(const DataNode & node) const; String DatabaseSubpathToSessionRelativePath(const String & subPath, TreeGatewayFlags flags) const; void DumpDescriptionToString(const DataNode & node, String & s, uint32 indentLevel) const; MessageRef CreateNodeUpdateMessage(const String & path, const ConstMessageRef & optPayload, TreeGatewayFlags flags, const String & optBefore, const String & optOpTag) const; MessageRef CreateNodeIndexUpdateMessage(const String & relativePath, char op, uint32 index, const String & key, const String & optOpTag); MessageRef CreateSubtreeUpdateMessage(const String & path, const ConstMessageRef & payload, TreeGatewayFlags flags, const String & optOpTag) const; status_t HandleNodeUpdateMessage(const Message & msg); status_t HandleNodeUpdateMessageAux(const Message & msg, TreeGatewayFlags flags); status_t HandleNodeIndexUpdateMessage(const Message & msg); status_t HandleSubtreeUpdateMessage(const Message & msg); status_t UploadUndoRedoRequestToSeniorPeer(uint32 whatCode, const String & optSequenceLabel, uint32 whichDB); MessageRef _assembledJuniorMessage; NestCount _interimUpdateNestCount; const String _rootNodePathWithoutSlash; const String _rootNodePathWithSlash; const uint32 _rootNodeDepth; uint32 _checksum; // running checksum Queue<const String *> _opTagStack; friend class OpTagGuard; }; DECLARE_REFTYPES(MessageTreeDatabaseObject); }; // end namespace zg #endif
f3eda0a0cda47e033fd86951df149c79e7ff9d16
de908a3dadbbf372eb44e588b07cb6ae798510ac
/examples/example/001/src/001.cpp
542aa4aa546fb41b0fbfede07e01078de2bbd15f
[ "MIT" ]
permissive
ImgMagic-Tech-Team/ImageStone
0678c144c40f6076447148191545a4390cda1c9e
d9e6ce00379ba0c78278fa4bacc07c8f0f547feb
refs/heads/main
2023-09-06T00:04:00.047309
2021-11-25T05:09:29
2021-11-25T05:09:29
431,712,512
0
1
null
null
null
null
UTF-8
C++
false
false
5,551
cpp
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include "../../../ImageStone.h" // operation menu const char * szOpMenu = "please enter a number(1 to 25) to choice a effect.\n\n\ 1) invert image color\n\ 2) gray scale\n\ 3) threshold\n\ 4) flip\n\ 5) emboss\n\ 6) splash\n\ 7) mosaic\n\ 8) oil paint\n\ 9) add 3D grid\n\ 10) whirl & pinch\n\ 11) gradient fill radial\n\ 12) adjust gamma\n\ 13) rotate 90'\n\ 14) ribbon\n\ 15) halftone\n\ 16) lens flare\n\ 17) adjust saturation\n\ 18) box blur\n\ 19) zoom blur\n\ 20) radial blur\n\ 21) motion blur\n\ 22) add shadow\n\ 23) color tone\n\ 24) soft glow\n\ 25) tile reflection\n\ " ; //================================================================================ class FCShowProgress : public FCObjProgress { public : virtual void ResetProgress() { m_nLast = 0 ; } virtual void SetProgress (int nNew) { if (nNew - m_nLast >= 2) { printf ("#") ; m_nLast = nNew ; } } protected : int m_nLast ; } ; //================================================================================ int main (int argc, char* argv[]) { const char* szTestFile = "test.bmp" ; // image to load const char* szSaveFile = "save.bmp" ; // image to save // not found FILE * pf = fopen (szTestFile, "rb") ; if (pf) fclose(pf) ; if (!pf) { printf ("can't load %s, please put a bmp file named %s in same folder to binary file.\n", szTestFile, szTestFile) ; return 0 ; } // load test image FCObjImage img ; if (!img.Load (szTestFile)) { printf ("load %s failed, the image must BMP format.\n", szTestFile) ; return 0 ; } printf ("now, the %s image has been loaded successfully!\n\n", szTestFile) ; printf ("image's infomation:\n") ; printf ("width : %d\n", img.Width()) ; printf ("height : %d\n", img.Height()) ; printf ("color : %d\n\n", img.ColorBits()) ; img.ConvertTo32Bit() ; // print menu && choice a effect char szInput[255] = {0} ; printf ("%s", szOpMenu) ; scanf ("%s", szInput) ; FCSinglePixelProcessBase * pEffect = NULL ; switch (atoi(szInput)) { case 1 : pEffect = new FCPixelInvert() ; break ; case 2 : pEffect = new FCPixelGrayscale() ; break ; case 3 : pEffect = new FCPixelThreshold(100) ; break ; case 4 : pEffect = new FCPixelFlip() ; break ; case 5 : pEffect = new FCPixelEmboss(2) ; break ; case 6 : pEffect = new FCPixelSplash(15) ; break ; case 7 : pEffect = new FCPixelMosaic(10) ; break ; case 8 : pEffect = new FCPixelOilPaint(7) ; break ; case 9 : pEffect = new FCPixel3DGrid(16,100) ; break ; case 10 : pEffect = new FCPixelWhirlPinch(LIB_PI/2.0,10) ; break ; case 11 : { RECT rcEllipse = {0,0,img.Width(),img.Height()} ; RGBQUAD crStart = {255,255,255}, crEnd = {255,0,0} ; pEffect = new FCPixelGradientRadial(rcEllipse,crStart,crEnd) ; } break ; case 12 : pEffect = new FCPixelGamma(2) ; break ; case 13 : pEffect = new FCPixelRotate90() ; break ; case 14 : pEffect = new FCPixelRibbon(35,25) ; break ; case 15 : pEffect = new FCPixelHalftoneM3() ; break ; case 16 : { POINT pt = {100, 100} ; pEffect = new FCPixelLensFlare(pt) ; } break ; case 17 : pEffect = new FCPixelHueSaturation(100,150) ; break ; case 18 : pEffect = new FCPixelBlur_Box(5,true) ; break ; case 19 : pEffect = new FCPixelBlur_Zoom(5) ; break ; case 20 : pEffect = new FCPixelBlur_Radial(5) ; break ; case 21 : pEffect = new FCPixelBlur_Motion(30, DIRECT_LEFT) ; break ; case 22 : { SHADOWDATA ShData ; ShData.crShadow = PCL_RGBA(0,0,0) ; ShData.nAlpha = 75 ; ShData.nSmooth = 10 ; ShData.nOffsetX = 5 ; ShData.nOffsetY = 5 ; pEffect = new FCPixelAddShadow(ShData) ; } break ; case 23 : pEffect = new FCPixelColorTone(PCL_RGBA(254,168,33)) ; break ; case 24 : pEffect = new FCPixelSoftGlow(10, 60, 110) ; break ; case 25 : pEffect = new FCPixelTileReflection(45, 20, 8) ; break ; default : printf ("choice invalid. quit do nothing.\n") ; return 0 ; } // to show progress, it's obvious in large image and slower algorithm (such as : OilPaint) FCShowProgress showPro ; printf ("\ncurrent progress : ") ; img.SinglePixelProcessProc (*pEffect, &showPro) ; printf ("\n\n") ; delete pEffect ; // save image FCObjImage imgWhite ; imgWhite.Create (img.Width(), img.Height(), 24) ; FCPixelFillColor cmdFillWhite(FCColor::crWhite()) ; imgWhite.SinglePixelProcessProc (cmdFillWhite) ; RECT rcImg = {0, 0, img.Width(), img.Height()} ; imgWhite.AlphaBlend (img, rcImg, rcImg, 100) ; imgWhite.Save (szSaveFile) ; printf ("the effected image has been saved into %s !\n\n", szSaveFile) ; return 0 ; }
4ab6f0c07fc5e9296d21edef73622e9f1e762a5d
d314485dfaf21a3516023381f3d223424cbde471
/seccondlevel.cpp
8c80aae080d95977601ee53b64ed1c80c92aba4f
[]
no_license
derikos/daily
64825c46dab91bea057368cfbb8403fa7b42ddcb
772c9f783ed3c1ddcd4dcc1e086ca9fda83402e6
refs/heads/master
2021-01-20T00:06:07.851925
2018-09-03T13:05:13
2018-09-03T13:27:24
89,079,007
0
0
null
2017-04-27T07:19:55
2017-04-22T15:17:37
C++
UTF-8
C++
false
false
194
cpp
#include "seccondlevel.h" #include "derived.h" SeccondLevel::SeccondLevel(int rows, int columns) : Derived(rows,columns) { std::cout<<"This is SeccondLevel's constructor"<<std::endl; }
4f17091f70e337cf26dd56560b20a472554abee5
cfbe33213b6146535c784d3d4f8e4265d931ecb4
/mainwindow.cpp
10f6d97b3ec119594786b15564b2c884516f33d7
[]
no_license
mengyouxu/qt_network_utils
fb9258c72718a923260b17b0645942ed3f2cbe63
40b1518b44f657d3ea45780de4e25850ca91b645
refs/heads/master
2021-01-10T07:33:20.486314
2016-02-05T13:36:46
2016-02-05T13:36:46
48,647,747
0
0
null
null
null
null
UTF-8
C++
false
false
1,782
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QHostInfo> #include <QNetworkInterface> #include <QMessageBox> #include "network_utils.h" #include <iostream> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //init network_utils here nu = new network_utils(); string *target_host = new string("www.baidu.com"); list<string> host_addr = nu->getHostByName(target_host); nu->pingHost(target_host); for(list<string>::iterator i=host_addr.begin();i!=host_addr.end();i++){ std::cout<<"addr : "<<(*i).c_str()<<std::endl; } std::flush(std::cout); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QString detail = ""; QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); for(int i=0;i<list.count();i++){ QNetworkInterface interface=list.at(i); detail = detail + tr("设备:") + interface.name() + "\n"; detail = detail + tr("硬件地址: ") + interface.hardwareAddress()+ "\n"; QList<QNetworkAddressEntry> entryList = interface.addressEntries(); for(int j=0;j<entryList.count();j++){ QNetworkAddressEntry entry = entryList.at(j); detail = detail + "\t" + tr("IP 地址: ") + entry.ip().toString() + "\n"; detail = detail + "\t" + tr("子网掩码: ") + entry.netmask().toString()+"\n"; detail = detail + "\t" + tr("广播地址: ") + entry.broadcast().toString() +"\n"; } } QMessageBox::information(this,tr("Detail"),detail); } void MainWindow::on_pushButtonGetHostname_clicked() { string *hostname = nu->getHostName(); ui->labelHostname->setText(hostname->c_str()); }
c560a18cb1687bd357fd4fcb84833445ddfd6ab4
e30874b3aa20804833dd11788176f839fcd08690
/cpp/benchmarks/groupby/group_struct_values.cpp
024fd3708fd4004ef663a851ab2c87ab782076f4
[ "Apache-2.0" ]
permissive
rapidsai/cudf
eaba8948cddde8161c3b02b1b972dab3df8d95b3
c51633627ee7087542ad4c315c0e139dea58e408
refs/heads/branch-23.10
2023-09-04T07:18:27.194295
2023-09-03T06:20:33
2023-09-03T06:20:33
90,506,918
5,386
751
Apache-2.0
2023-09-14T00:27:03
2017-05-07T03:43:37
C++
UTF-8
C++
false
false
3,881
cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * 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 <benchmarks/common/generate_input.hpp> #include <benchmarks/fixture/benchmark_fixture.hpp> #include <benchmarks/synchronization/synchronization.hpp> #include <cudf/aggregation.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/groupby.hpp> #include <cudf/structs/structs_column_view.hpp> static constexpr cudf::size_type num_struct_members = 8; static constexpr cudf::size_type max_int = 100; static constexpr cudf::size_type max_str_length = 32; static auto create_data_table(cudf::size_type n_rows) { data_profile const table_profile = data_profile_builder() .distribution(cudf::type_id::INT32, distribution_id::UNIFORM, 0, max_int) .distribution(cudf::type_id::STRING, distribution_id::NORMAL, 0, max_str_length); // The first two struct members are int32 and string. // The first column is also used as keys in groupby. // The subsequent struct members are int32 and string again. return create_random_table( cycle_dtypes({cudf::type_id::INT32, cudf::type_id::STRING}, num_struct_members), row_count{n_rows}, table_profile); } // Max aggregation/scan technically has the same performance as min. template <typename OpType> void BM_groupby_min_struct(benchmark::State& state) { auto const n_rows = static_cast<cudf::size_type>(state.range(0)); auto data_cols = create_data_table(n_rows)->release(); auto const keys_view = data_cols.front()->view(); auto const values = cudf::make_structs_column(keys_view.size(), std::move(data_cols), 0, rmm::device_buffer()); using RequestType = std::conditional_t<std::is_same_v<OpType, cudf::groupby_aggregation>, cudf::groupby::aggregation_request, cudf::groupby::scan_request>; auto gb_obj = cudf::groupby::groupby(cudf::table_view({keys_view})); auto requests = std::vector<RequestType>(); requests.emplace_back(RequestType()); requests.front().values = values->view(); requests.front().aggregations.push_back(cudf::make_min_aggregation<OpType>()); for (auto _ : state) { [[maybe_unused]] auto const timer = cuda_event_timer(state, true); if constexpr (std::is_same_v<OpType, cudf::groupby_aggregation>) { [[maybe_unused]] auto const result = gb_obj.aggregate(requests); } else { [[maybe_unused]] auto const result = gb_obj.scan(requests); } } } class Groupby : public cudf::benchmark {}; #define MIN_RANGE 10'000 #define MAX_RANGE 10'000'000 #define REGISTER_BENCHMARK(name, op_type) \ BENCHMARK_DEFINE_F(Groupby, name)(::benchmark::State & state) \ { \ BM_groupby_min_struct<op_type>(state); \ } \ BENCHMARK_REGISTER_F(Groupby, name) \ ->UseManualTime() \ ->Unit(benchmark::kMillisecond) \ ->RangeMultiplier(4) \ ->Ranges({{MIN_RANGE, MAX_RANGE}}); REGISTER_BENCHMARK(Aggregation, cudf::groupby_aggregation) REGISTER_BENCHMARK(Scan, cudf::groupby_scan_aggregation)
1cbf724751f16d513455a6b6a7cc2ace6bc6634e
18f66cb9a08030afab48494b96536e6a80277435
/acm.timus.ru_33735/1031.cpp
632bbd330c1778eb98ebbc1e2936ae78b039fbf1
[]
no_license
Rassska/acm
aa741075a825080637bebab128d763b64c7f73ae
18aaa37e96b6676334c24476e47cd17d22ca9541
refs/heads/master
2023-03-15T16:57:59.274305
2015-02-24T21:36:34
2015-02-24T21:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
#include <cstdio> #include <cmath> #include <algorithm> #define INF 1000000000 using namespace std; int Ls[3],Cs[3]; int n; struct Station { int Distance; int PathLength; }; Station Stations[10002]; void main() { //freopen("input.txt","r",stdin); for(int i = 0; i < 3; i++) scanf("%d",&Ls[i]); for(int i = 0; i < 3; i++) scanf("%d",&Cs[i]); int source, sink; scanf("%d%d%d",&n,&source,&sink); Stations[0].PathLength = INF; for(int i = 1; i < n; i++) { scanf("%d",&Stations[i].Distance); Stations[i].PathLength = INF; } if(sink < source) swap(sink, source); source--; sink--; Stations[source].PathLength = 0; for(int v = source; v <= sink; v++) { for(int w = v+1; w <= sink; w++) { int cost = -1; for(int i = 0; i < 3; i++) { if(abs(Stations[v].Distance-Stations[w].Distance) <= Ls[i]) { cost = Cs[i]; break; } } if(cost != -1) { int newcost = Stations[v].PathLength + cost; if(newcost < Stations[w].PathLength) Stations[w].PathLength = newcost; } } } printf("%d",Stations[sink].PathLength); }
2f705c3011d7c3decf0a59bd0b6ac8e4e79f247f
db5bba94cf3eae6f1a16b1e780aa36f4b8c3c2da
/green/src/model/DescribeOssResultItemsRequest.cc
f8f4f6d4b36f3f38a63c6ea68e051cad6d79efb1
[ "Apache-2.0" ]
permissive
chaomengnan/aliyun-openapi-cpp-sdk
42eb87a6119c25fd2d2d070a757b614a5526357e
bb7d12ae9db27f2d1b3ba7736549924ec8d9ef85
refs/heads/master
2020-07-25T00:15:29.526225
2019-09-12T15:34:29
2019-09-12T15:34:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,795
cc
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/green/model/DescribeOssResultItemsRequest.h> using AlibabaCloud::Green::Model::DescribeOssResultItemsRequest; DescribeOssResultItemsRequest::DescribeOssResultItemsRequest() : RpcServiceRequest("green", "2017-08-23", "DescribeOssResultItems") {} DescribeOssResultItemsRequest::~DescribeOssResultItemsRequest() {} int DescribeOssResultItemsRequest::getTotalCount()const { return totalCount_; } void DescribeOssResultItemsRequest::setTotalCount(int totalCount) { totalCount_ = totalCount; setCoreParameter("TotalCount", std::to_string(totalCount)); } float DescribeOssResultItemsRequest::getMinScore()const { return minScore_; } void DescribeOssResultItemsRequest::setMinScore(float minScore) { minScore_ = minScore; setCoreParameter("MinScore", std::to_string(minScore)); } std::string DescribeOssResultItemsRequest::getSuggestion()const { return suggestion_; } void DescribeOssResultItemsRequest::setSuggestion(const std::string& suggestion) { suggestion_ = suggestion; setCoreParameter("Suggestion", suggestion); } int DescribeOssResultItemsRequest::getCurrentPage()const { return currentPage_; } void DescribeOssResultItemsRequest::setCurrentPage(int currentPage) { currentPage_ = currentPage; setCoreParameter("CurrentPage", std::to_string(currentPage)); } float DescribeOssResultItemsRequest::getMaxScore()const { return maxScore_; } void DescribeOssResultItemsRequest::setMaxScore(float maxScore) { maxScore_ = maxScore; setCoreParameter("MaxScore", std::to_string(maxScore)); } std::string DescribeOssResultItemsRequest::getStartDate()const { return startDate_; } void DescribeOssResultItemsRequest::setStartDate(const std::string& startDate) { startDate_ = startDate; setCoreParameter("StartDate", startDate); } std::string DescribeOssResultItemsRequest::getResourceType()const { return resourceType_; } void DescribeOssResultItemsRequest::setResourceType(const std::string& resourceType) { resourceType_ = resourceType; setCoreParameter("ResourceType", resourceType); } std::string DescribeOssResultItemsRequest::getScene()const { return scene_; } void DescribeOssResultItemsRequest::setScene(const std::string& scene) { scene_ = scene; setCoreParameter("Scene", scene); } std::string DescribeOssResultItemsRequest::getQueryId()const { return queryId_; } void DescribeOssResultItemsRequest::setQueryId(const std::string& queryId) { queryId_ = queryId; setCoreParameter("QueryId", queryId); } std::string DescribeOssResultItemsRequest::getBucket()const { return bucket_; } void DescribeOssResultItemsRequest::setBucket(const std::string& bucket) { bucket_ = bucket; setCoreParameter("Bucket", bucket); } std::string DescribeOssResultItemsRequest::getEndDate()const { return endDate_; } void DescribeOssResultItemsRequest::setEndDate(const std::string& endDate) { endDate_ = endDate; setCoreParameter("EndDate", endDate); } std::string DescribeOssResultItemsRequest::getSourceIp()const { return sourceIp_; } void DescribeOssResultItemsRequest::setSourceIp(const std::string& sourceIp) { sourceIp_ = sourceIp; setCoreParameter("SourceIp", sourceIp); } int DescribeOssResultItemsRequest::getPageSize()const { return pageSize_; } void DescribeOssResultItemsRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setCoreParameter("PageSize", std::to_string(pageSize)); } std::string DescribeOssResultItemsRequest::getLang()const { return lang_; } void DescribeOssResultItemsRequest::setLang(const std::string& lang) { lang_ = lang; setCoreParameter("Lang", lang); } bool DescribeOssResultItemsRequest::getStock()const { return stock_; } void DescribeOssResultItemsRequest::setStock(bool stock) { stock_ = stock; setCoreParameter("Stock", stock ? "true" : "false"); } std::string DescribeOssResultItemsRequest::getObject()const { return object_; } void DescribeOssResultItemsRequest::setObject(const std::string& object) { object_ = object; setCoreParameter("Object", object); }
bd80a4bc1a49c8613a68a9e0bbd6f5ec29fc2172
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/test/multimedia/dmusic/dmtest1/Help_Buffer3d.cpp
3d505b90bd97ac47c7cee8bb1ac2d2a380c71edd
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,369
cpp
/******************************************************************************** FILE: BUFFER3D.cpp PURPOSE: This wraps both a DSound and a DSoundBuffer object, so that it can abstract the positioning calls. BY: DANHAFF ********************************************************************************/ #include "globals.h" #include "Help_Buffer3D.h" /******************************************************************************** Initializes variables in the function like normal code does. ********************************************************************************/ DMBUFFER::BUFFER3D::BUFFER3D(void) { HRESULT hr = S_OK; m_pDS = NULL; m_pDSB = NULL; //Set up as if you had called DSB_TestMode(TESTAPPLY_IMMEDIATE) m_dwActualApplyValue = DS3D_IMMEDIATE; m_eApply = TESTAPPLY_IMMEDIATE; m_bCommit = FALSE; //Set up the positioning stuff. m_vLisPos = make_D3DVECTOR(0, 0, 0); m_vBufPos = make_D3DVECTOR(0, 0, 0); //Relative offset positioning stuff. m_vRelPos = make_D3DVECTOR(0, 0, 0); m_bUsingRelPos = FALSE; }; /******************************************************************************** ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::Init(D3DVECTOR vRelative, IDirectSoundBuffer *pDSB) { HRESULT hr = S_OK; static char szFullPath[1000]; WIN32_FIND_DATA Data = {0}; DWORD dwCurrentFile = 0; DWORD dwChosenFile = 0; BOOL bRes = FALSE; //Create the DSound object (our "listener") CHECK(DMHelp_DirectSoundCreate( 0, &m_pDS, NULL ) ); if ( SUCCEEDED( hr ) ) { m_pDSB = pDSB; } //Are we relativizing our listener and source? m_vRelPos = vRelative; if (vRelative == make_D3DVECTOR(0, 0, 0)) m_bUsingRelPos = FALSE; else m_bUsingRelPos = TRUE; return hr; }; /******************************************************************************** DESTRUCTOR ********************************************************************************/ DMBUFFER::BUFFER3D::~BUFFER3D(void) { //Release buffers RELEASE(m_pDSB); RELEASE(m_pDS); } /******************************************************************************** Takes debug output and appends stuff to it based on whether we're de or not. ********************************************************************************/ /* void BUFFER3D::ConsoleOut(CHAR *szFormat, ...) { va_list va; static char szBuffer[1000]; if (NULL == this) Log(ABORTLOGLEVEL, "BUFFER3D ptr is NULL!!!!"); CHAR *pszWarningDeferred= "(may not apply: Using DEFERRED w/o CommittDeferredSettings)"; va_start(va, szFormat); vsprintf(szBuffer, szFormat, va); Log(FYILOGLEVEL, szBuffer); va_end(va); }; */ /******************************************************************************** PURPOSE: This tells the wrapper class how to proxy position changes, etc. ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_Test_SetTestingApply(TestApplies dwApply) { HRESULT hr = S_OK; //Store our apply methodology. m_eApply = dwApply; //Calculate our actual apply value. m_dwActualApplyValue = 0; switch (dwApply) { case TESTAPPLY_DEFERRED_NOUPDATE: m_dwActualApplyValue = DS3D_DEFERRED; break; case TESTAPPLY_DEFERRED_UPDATE: m_dwActualApplyValue = DS3D_DEFERRED; break; case TESTAPPLY_IMMEDIATE: m_dwActualApplyValue = DS3D_IMMEDIATE; break; case DS3D_IMMEDIATE: case DS3D_DEFERRED: m_dwActualApplyValue = dwApply; default: Log(ABORTLOGLEVEL, "ERROR: Invalid parameter dwApply=%d passed to GetActualApplyValue", dwApply); m_dwActualApplyValue = 0xFFFFFFFF; break; } //Store our commit methodology (do we call CommitDeferredSettings?) if (TESTAPPLY_DEFERRED_UPDATE == dwApply) m_bCommit = TRUE; else m_bCommit = FALSE; return hr; }; /******************************************************************************** This intercepts the position call and relativizes the vectors based on the relative position if any. ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetPosition(FLOAT x, FLOAT y, FLOAT z) { HRESULT hr = S_OK; m_vLisPos = make_D3DVECTOR(x, y, z); CHECKRUN(DS_SetActualPositions()); return hr; }; /******************************************************************************** PURPOSE: Given our object's apparent positions, this function will adjust them as follows: 1) The relative position (m_vRelPos) is subtracted from both the listener and the buffer position. ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetActualPositions(void) { HRESULT hr = S_OK; D3DVECTOR vActualLisPos = m_vLisPos; D3DVECTOR vActualBufPos = m_vBufPos; //1) The relative position (m_vRelPos) is subtracted from both the listener //and the buffer position. if (m_bUsingRelPos) { vActualLisPos -= m_vRelPos; vActualBufPos -= m_vRelPos; } //Set the positions and apply if necessasry. CHECKRUN(m_pDS-> SetPosition(vActualLisPos.x, vActualLisPos.y, vActualLisPos.z, m_dwActualApplyValue)); CHECKRUN(m_pDSB->SetPosition(vActualBufPos.x, vActualBufPos.y, vActualBufPos.z, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetAllParameters(LPCDS3DLISTENER pds3dl) { HRESULT hr = S_OK; D3DVECTOR vActualLisPos = {0, 0, 0}; D3DVECTOR vActualBufPos = {0, 0, 0}; DS3DLISTENER ds3dl; ZeroMemory(&ds3dl, sizeof(ds3dl)); //Save the listener data. ds3dl = *pds3dl; //Save the current listener position to our class. m_vLisPos = ds3dl.vPosition; //1) The relative position (m_vRelPos) is subtracted from both the listener //and the buffer position. if (m_bUsingRelPos) { vActualLisPos = m_vLisPos - m_vRelPos; vActualBufPos = m_vBufPos - m_vRelPos; } else { vActualLisPos = m_vLisPos; vActualBufPos = m_vBufPos; } //Stick the new values into the struct. ds3dl.vPosition = vActualLisPos; //Set the listener parameters like we're supposed to. CHECKRUN(m_pDS->SetAllParameters(pds3dl, m_dwActualApplyValue)); //If we're doing some automatic adjustments than set the buffer position too, otherwise leave it alone. if (m_bUsingRelPos/* || DS3DMODE_HEADRELATIVE == m_dwActualTestMode*/) { CHECKRUN(m_pDSB->SetPosition(vActualBufPos.x, vActualBufPos.y, vActualBufPos.z, m_dwActualApplyValue)); } //Commit if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; }; /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetDistanceFactor(FLOAT flDistanceFactor) { HRESULT hr = S_OK; CHECKRUN(m_pDS->SetDistanceFactor(flDistanceFactor, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetDopplerFactor(FLOAT flDopplerFactor) { HRESULT hr = S_OK; CHECKRUN(m_pDS->SetDopplerFactor(flDopplerFactor, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetOrientation(FLOAT xFront, FLOAT yFront, FLOAT zFront, FLOAT xTop, FLOAT yTop, FLOAT zTop) { HRESULT hr = S_OK; CHECKRUN(m_pDS->SetOrientation(xFront, yFront, zFront, xTop, yTop, zTop, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetRolloffFactor(FLOAT flRolloffFactor) { HRESULT hr = S_OK; CHECKRUN(m_pDS->SetRolloffFactor(flRolloffFactor, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DS_SetVelocity(FLOAT x, FLOAT y, FLOAT z) { HRESULT hr = S_OK; CHECKRUN(m_pDS->SetVelocity(x, y, z, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Just like DS_SetAllParameters ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetAllParameters(LPCDS3DBUFFER pds3db) { HRESULT hr = S_OK; D3DVECTOR vActualLisPos = {0, 0, 0}; D3DVECTOR vActualBufPos = {0, 0, 0}; DS3DBUFFER ds3db; ZeroMemory(&ds3db, sizeof(ds3db)); //Save the buffer data. ds3db = *pds3db; //Save the current buffer position to our class. m_vBufPos = ds3db.vPosition; //1) The relative position (m_vRelPos) is subtracted from both the listener //and the buffer position. if (m_bUsingRelPos) { vActualLisPos = m_vLisPos - m_vRelPos; vActualBufPos = m_vBufPos - m_vRelPos; } else { vActualLisPos = m_vLisPos; vActualBufPos = m_vBufPos; } //Stick the new values into the struct. ds3db.vPosition = vActualBufPos; //If we're doing some automatic adjustments than set the listener position too, otherwise leave it alone. if (m_bUsingRelPos) { CHECKRUN(m_pDS->SetPosition(vActualLisPos.x, vActualLisPos.y, vActualLisPos.z, m_dwActualApplyValue)); } //Set the structure. CHECKRUN(m_pDSB->SetAllParameters(&ds3db, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetConeAngles(DWORD dwInsideConeAngle, DWORD dwOutsideConeAngle) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetConeAngles(dwInsideConeAngle, dwOutsideConeAngle, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). *********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetConeOrientation(FLOAT x, FLOAT y, FLOAT z) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetConeOrientation(x, y, z, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetConeOutsideVolume(LONG lConeOutsideVolume) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetConeOutsideVolume(lConeOutsideVolume, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetMaxDistance(FLOAT flMaxDistance) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetMaxDistance(flMaxDistance, m_dwActualApplyValue)) if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetMinDistance(FLOAT flMinDistance) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetMinDistance(flMinDistance, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetPosition(FLOAT x, FLOAT y, FLOAT z) { HRESULT hr = S_OK; //Set the internal variable. m_vBufPos = make_D3DVECTOR(x, y, z); //Finally, set the position. CHECKRUN(DS_SetActualPositions()); return hr; } /******************************************************************************** Simple wrapper function; performs call based on m_eApply (which translates into m_dwActualApplyValue and m_bCommit). ********************************************************************************/ HRESULT DMBUFFER::BUFFER3D::DSB_SetVelocity(FLOAT x, FLOAT y, FLOAT z) { HRESULT hr = S_OK; CHECKRUN(m_pDSB->SetVelocity(x, y, z, m_dwActualApplyValue)); if (m_bCommit) CHECKRUN(m_pDS->CommitDeferredSettings()); return hr; } /******************************************************************************** Note: These are crap functions cuz the D3DOVERLOADS don't work. BUG 2371 Overloaded functions unusable on D3DVECTOR due to inclusion of less functional D3DVECTOR class in D3D8TYPES.H ********************************************************************************/ D3DVECTOR DMBUFFER::operator - (const D3DVECTOR& v, const D3DVECTOR& w) { D3DVECTOR a; a.x = v.x - w.x; a.y = v.y - w.y; a.z = v.z - w.z; return a; }; D3DVECTOR DMBUFFER::operator -= (D3DVECTOR& v, const D3DVECTOR& w) { v.x -= w.x; v.y -= w.y; v.z -= w.z; return v; }; BOOL DMBUFFER::operator == (D3DVECTOR& v, const D3DVECTOR& w) { return ( v.x == w.x && v.y == w.y && v.z == w.z ); }; //constructor D3DVECTOR DMBUFFER::make_D3DVECTOR(FLOAT _x, FLOAT _y, FLOAT _z) { D3DVECTOR v; v.x = _x; v.y = _y; v.z = _z; return v; } /******************************************************************************** ********************************************************************************/ HRESULT DMBUFFER::DMHelp_DirectSoundCreate(DWORD dwDeviceId, LPDIRECTSOUND *ppDirectSound, LPUNKNOWN pUnkOuter) { HRESULT hr = S_OK; CHECK(DirectSoundCreate(0, ppDirectSound, pUnkOuter)); return hr; }; /******************************************************************************** Makes it easy to print out which mode you're in. ********************************************************************************/ static char *pszApplyStrings[] = {"TESTAPPLY_DEFERRED_NOUPDATE", "TESTAPPLY_DEFERRED_UPDATE", "TESTAPPLY_IMMEDIATE"}; char *DMBUFFER::String(TestApplies eTestApply) { return pszApplyStrings[eTestApply - TESTAPPLY_DEFERRED_NOUPDATE]; } /******************************************************************************** PURPOSE: Sets the x, y, or z component of a vector where x, y, z are indexed by dwComponent values 0-2. Is nice for loops that test all 3 axes. ********************************************************************************/ void DMBUFFER::DMSetComponent(D3DVECTOR *pVector, DWORD dwComponent, FLOAT fValue) { switch (dwComponent) { case 0: pVector->x = fValue; break; case 1: pVector->y = fValue; break; case 2: pVector->z = fValue; break; default: Log(ABORTLOGLEVEL, "Test Error in DMSetComponent, see danhaff!!!!"); break; } }
ba3d9e194b7cafff3f8dabe39fe4a4b64fe9c8ba
d405119b88872aa46c6a3a28ea1cca478741e88b
/external_libs/Car.h
73040d05d042eff790fc269a92b666aa68f39502
[ "MIT" ]
permissive
Pippo98/TPA_Homework1
b032d0d299093604e101aca2e8eac2ebcdc747e5
b88781558b26e2bd0bce9756d1d2772e81155f8b
refs/heads/main
2023-04-15T06:30:40.186925
2021-04-27T13:12:23
2021-04-27T13:12:23
356,637,410
0
2
MIT
2021-04-27T13:12:24
2021-04-10T16:30:27
C++
UTF-8
C++
false
false
2,371
h
#ifndef CAR_H #define CAR_H #include <iostream> #include <string> #include <fstream> #include <streambuf> #include <sstream> #define SFONDOX 800 #define SFONDOY 600 using namespace std; // parametri da passare alla funzione per inizializzarla struct parametri { float inheight; // altezza del veicolo float inwidth; // larghezza del veicolo float inpx; // posizione x del veicolo float inpy; // posizione y del veicolo int indiam; // diametro dei cerchioni (16, 17, 18) int inass; // assetto della macchina (1, 2, 3) }; // parametri carrozzeria struct coca_carrozzeria { float cx, cy; float width, height; }; // parametri ruota struct coca_ruota { float ruota, cerchione; float centrox, centroy; }; // parametri tetto struct coca_tetto { float x1, y1; float x2, y2; float x3, y3; float x4, y4; float x5, y5; }; // parametri finestrini struct coca_finestrini { float p1x, p1y; float p2x, p2y; float p3x, p3y; }; // parametri spoiler struct coca_spoiler { float px, py; float widths, heights; }; // parametri dell'intero device struct coca_device { coca_carrozzeria car; coca_ruota sx; coca_ruota dx; coca_finestrini fin; coca_spoiler spoil; coca_tetto cap; }; // intestazione + fine std::string coca_intestazione(); std::string coca_sfondo(); std::string coca_fine(); // funzioni carrozzeria void coca_try_carrozzeria(coca_device* macch); std::string coca_strg_carrozzeria(coca_device* macch); // funzioni ruote void coca_try_ruote(coca_device* macch); void coca_try_assetto(coca_device* macch); std::string coca_strg_ruote(coca_device* macch); // funzioni finestrini void coca_try_finestrini(coca_device* macch); std::string coca_strg_finestrini(coca_device* macch); // funzioni spoiler void coca_try_spoiler(coca_device* macch); std::string coca_strg_spoiler(coca_device* macch); // funzioni tetto void coca_try_tetto(coca_device* macch); std::string coca_strg_tetto(coca_device* macch); // funzioni del device void coca_try_device(coca_device* macch); std::string coca_strg_device(coca_device* macch, int scelta); // funzione scrive su file void coca_write(string svg); // funzione legge un file string coca_read(); // funzione che inizzializza il device passando dei parametri coca_device* coca_init_device(parametri par); #endif //CAR_H
fdf0c129f2a8107c523676d8281c61e7dd45f396
acd92f081599799a46f88201747ee29fab305801
/engine/rendering/backend/FrameResources.h
4892f9836a2ae87fd43324a344e8c033a3eafba4
[]
no_license
shadow-lr/VulkanRenderer
7d538cf07b8e1dd126cbe6b9c29838656b2b626e
63ab42b0f48b768271472f4ce05371fe566144de
refs/heads/master
2022-10-12T06:54:09.773120
2020-06-15T05:34:08
2020-06-15T05:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#pragma once #include <memory> #include <vulkan/vulkan.h> #include "Wrappers.h" class VulkanDevice; class VulkanSwapChain; class FrameObject { public: FrameObject (VulkanDevice& device, VulkanSwapChain& swapChain); ~FrameObject (); FrameObject (FrameObject const& fb) = delete; FrameObject& operator= (FrameObject const& fb) = delete; FrameObject (FrameObject&& fb) noexcept; FrameObject& operator= (FrameObject&& fb) noexcept; VkResult AcquireNextSwapchainImage (); void PrepareFrame (); void submit (); VkResult Present (); VkCommandBuffer GetPrimaryCmdBuf (); private: VulkanDevice* device; VulkanSwapChain* swapchain; uint32_t swapChainIndex; // which frame to render to VulkanSemaphore imageAvailSem; VulkanSemaphore renderFinishSem; CommandPool commandPool; CommandBuffer primary_command_buffer; VkPipelineStageFlags stageMasks = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; };
4a4ee0b0a5c31e7796470b2cbad833b29f74ff82
fbd8c56e8e449f7ac80b5156e80c15c14cb34b12
/AtCoder/abc163/C.cpp
7a7a2ce2be2f97194b9d32e406dc6f09bb185b7c
[ "MIT" ]
permissive
Saikat-S/acm-problems-solutions
558374a534f4f4aa2bf3bea889c1d5c5a536cf59
921c0f3e508e1ee8cd14be867587952d5f67bbb9
refs/heads/master
2021-08-03T02:27:21.019914
2021-07-27T06:18:28
2021-07-27T06:18:28
132,938,151
4
0
null
null
null
null
UTF-8
C++
false
false
3,015
cpp
/*************************************************** * Problem Name : C.cpp * Problem Link : * OJ : * Verdict : AC * Date : 2020-04-19 * Problem Type : * Author Name : Saikat Sharma * University : CSE, MBSTU ***************************************************/ #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <climits> #include <cstring> #include <string> #include <sstream> #include <vector> #include <queue> #include <list> #include <unordered_map> #include <unordered_set> #include <cstdlib> #include <deque> #include <stack> #include <bitset> #include <cassert> #include <map> #include <set> #include <cassert> #include <iomanip> #include <random> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef unsigned long long ull; #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define __FileRead freopen ("input.txt", "r", stdin) #define __FileWrite freopen ("output.txt", "w", stdout) #define SET(a,v) memset(a,v,sizeof(a)) #define SZ(v) (int)v.size() #define pii pair<int,int> #define pil pair <int, ll> #define pli pair <ll, int> #define pll pair <ll, ll> #define debug cout <<"######\n" #define debug1(x) cout <<"### " << x << " ###\n" #define debug2(x,y) cout <<"# " << x <<" : "<< y <<" #\n" #define nl cout << "\n"; #define sp cout << " "; #define sl(n) scanf("%lld", &n) #define sf(n) scanf("%lf", &n) #define si(n) scanf("%d", &n) #define ss(n) scanf("%s", n) #define pf(n) scanf("%d", n) #define pfl(n) scanf("%lld", n) #define all(v) v.begin(), v.end() #define rall(v) v.begin(), v.end() #define srt(v) sort(v.begin(), v.end()) #define r_srt(v) sort(v.rbegin(), v.rend()) #define rev(v) reverse(v.rbegin(), v.rend()) #define Sqr(x) ((x)*(x)) #define Mod(x, m) ((((x) % (m)) + (m)) % (m)) #define max3(a, b, c) max(a, max(b, c)) #define min3(a, b, c) min(a, min(b, c)) #define pb push_back #define mk make_pair #define MAX 200005 #define INF 1000000009 #define MOD 1000000007 template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>; template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> string toString ( T Number ) { stringstream ss; ss << Number; return ss.str(); } template<typename T> int toInt (T str) { stringstream ss; ss << str; int num; ss >> num; return num; } ll lcm ( ll a, ll b ) { return ( a / __gcd ( a, b ) ) * b; } /************************************ Code Start Here ******************************************************/ vector<int>adj[MAX]; int nod[MAX]; int main () { __FastIO; //~ cout << setprecision (10) << fixed; int n; cin >> n; for (int i = 2; i <= n; i++) { int u; cin >> u; nod[u]++; } for(int i = 1; i<=n; i++){ cout << nod[i] << "\n"; } return 0; }
b6fe0a7765027e9bc80f605bd8c69a6ce2f2352d
12676cc44aeaf7ae604fdd7d3319052af7d0fbf2
/uva00957.cpp
7cc8c6d0bb71b0c08e08c65708155670a7a42f99
[]
no_license
BIT-zhaoyang/competitive_programming
e42a50ae88fdd37b085cfaf64285bfd50ef0fbbc
a037dd40fd5665f3248dc9c6ff3254c7ab2addb2
refs/heads/master
2021-04-19T00:02:12.570233
2018-09-01T11:59:44
2018-09-01T11:59:44
51,271,209
1
0
null
null
null
null
UTF-8
C++
false
false
2,780
cpp
#include <bits/stdc++.h> #define _ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout.precision(15); using namespace std; /* UB <- upper_bound a1 a2 a3 ... t t t t t t b1 b2 b3 lower_bound-> LB t: target value */ /* Intuitive explanation on the following two functions: The only difference lies at if(vi[M] < targetYear) and if(vi[M] <= targetYear). Why this difference gives different performance? Let's consider the previous one step before the 'while' loop terminates. Before the while loop terminates, the relatino of L, R, M must be: 1 <= R - L <= 2; // plot this you will get it L <= M < R; -> vi[L] <= vi[M] < vi[R] In each iteration, either L increase or R decrease(R implicitly decrease due to the downwards of integer division). In case 1: R - L = 2, M = L + 1. if(vi[M] < targetYear), L = M + 1 = R. Then at this time, vi[L] >= targetYear. The reason is that, last time we get to R = M, it's due to vi[M] >= targetYear. In case 2: L = M = R-1. Smiliar argument applies. In short, in lower_bound, L keeps increasing when vi[M] < targetYear thus finally gives us lower_bound. In upper_bound, L keeps increasing when vi[M] <= targetYear and once it reach a point that vi[L] > targetYear, since L <= M < R, L will never increase. */ int low_bound(int targetYear, vector<int> &vi){ if(vi.back() < targetYear) return -1; int L = 0, R = vi.size()-1, M; while(L < R){ M = (L+R)/2; // when use vi[m] < targetYear, it's lower_bound // lower_bound gives the index of first element no less than the target value if(vi[M] < targetYear) L = M+1; else R = M; } return L; } int up_bound(int targetYear, vector<int> &vi){ if(vi.back() < targetYear) return -1; int L = 0, R = vi.size()-1, M; while(L < R){ M = (L+R)/2; // when use vi[m] <= targetYear, it's upper_bound // upper_bound gives the index of the first element larger than target value if(vi[M] <= targetYear) L = M+1; else R = M; } return L; } int main(){ _ int Y, N; while(cin >> Y){ cin >> N; vector<int> vi(N, 0); for(int i = 0; i < N; ++i) cin >> vi[i]; int targetYear = 0, j = -1, length = -1, start, end; // j: index to the last Pope within in the constraint years for(int i = 0; i < N; ++i){ targetYear = vi[i] + Y - 1; j = up_bound(targetYear, vi); if(j-i > length){ length = j-i; start = i; end = j; } } cout << length << " " << vi[start] << " " << vi[end-1] << endl; } return 0; }
a3f78c08d25cb0cbaeb95f387ee24015797028cf
4589750807f18f71f49a6fb5e366154015f4ebfc
/operatorexpression/11.cpp
048210d5217c0245ab73e72350e2d7f97bb88095
[]
no_license
mohsin0176/HandNotes-onCPlusCPlus
afe7920dfc981a3cb2f1586c11981944451311e5
fd03ed40cfe8496ba141f16af7f9fc069d10fbc2
refs/heads/master
2023-03-19T11:41:52.487673
2021-03-07T11:31:01
2021-03-07T11:31:01
342,002,120
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include<iostream> #include<bits/stdc++.h> #include<math.h> #include<cstdlib.h> #include<limits.h> #include<iomanip.h> #include<fstream.h> #include<process.h> #define PI 3.1416 using namespace std; int main() { int a,b,c; c=(a=10,b=20,a+b); cout<<a; cout<<b; cout<<c; return 0; }
27e984d92d55bb01ba02ddb3837740b3344e227e
16548f3ed92d122f0639db2f4e866b0d797a98f8
/src/qt/bitcoin.cpp
a49000b2f5102d5644c79d4a895397a3c061bab2
[ "MIT" ]
permissive
bitcoinrapid4/bitcoinrapid
bdc214ec10b6a46cd454a825ed98920d5e691705
f295086273d0044bf96384687526d25066f3693c
refs/heads/master
2021-05-03T15:34:35.304123
2018-02-08T15:29:47
2018-02-08T15:29:47
120,479,764
0
0
null
null
null
null
UTF-8
C++
false
false
10,821
cpp
/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include "intro.h" #include <QApplication> #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #include <QSettings> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. BitcoinRapid can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /** Set up translations */ static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator) { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if(!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("BitcoinRapid"); QApplication::setOrganizationDomain("bitcoinrapid.org"); if (GetBoolArg("-testnet", false)) // Separate UI settings for testnet QApplication::setApplicationName("BitcoinRapid-Qt-testnet"); else QApplication::setApplicationName("BitcoinRapid-Qt"); // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); // User language is set up: pick a data directory Intro::pickDataDirectory(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("BitcoinRapid"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // ... then GUI settings: OptionsModel optionsModel; // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false)) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window(GetBoolArg("-testnet", false), 0); guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.addWallet("~Default", &walletModel); window.setCurrentWallet("~Default"); // If -min option passed, start window minimized. if(GetBoolArg("-min", false)) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; } // Shutdown the core and its threads, but don't exit BitcoinRapid-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
a6330ec389a8d7ec8b4a7da6decb1b4715081297
ef142ad790366ca1f65da6a0d82583ce8757dd1c
/blitzd/cache/UserCache.cpp
300f21872da9e55affd33109e5f7ff32f0020d42
[ "MIT" ]
permissive
shellohunter/blitzd
1242a8794346d67099769c9993ff4ba92dac2792
774a543b619d3332dd40e9cde32aa54948145cb4
refs/heads/master
2021-05-26T14:43:19.775032
2012-12-26T06:01:03
2012-12-26T06:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,687
cpp
#include "Config.h" #include "UserCache.h" #include "core/Cfg.h" #include "core/Message.h" #include "core/Client.h" #include "storage/StorageSqlite.h" namespace Cache { UserCache userCache; UserCacheItem::UserCacheItem( const char * username ): _dirty(false), _id(0), _username(username), _flag(0), _friend_dirty(false) { memset(_salt, 0, 32); memset(_verifier, 0, 32); } void UserCacheItem::SetSalt( const byte* s ) { if(memcmp(_salt, s, 32) == 0) return; _dirty = true; memcpy(_salt, s, 32); } void UserCacheItem::SetVerifier( const byte * s ) { if(memcmp(_verifier, s, 32) == 0) return; _dirty = true; memcpy(_verifier, s, 32); } void UserCacheItem::SetPasswd( const byte * p ) { if(memcmp(_passwd, p, 20) == 0) return; _dirty = true; memcpy(_passwd, p, 20); } void UserCacheItem::SetMail( std::string m ) { if(_mail == m) return; _mail = m; _dirty = true; } void UserCacheItem::SetFlag( uint f ) { if(_flag == f) return; _flag = f; _dirty = true; } void UserCacheItem::SetData( std::string k, std::string v ) { std::string& modstr = _data_map[k]; if(modstr == v) return; modstr = v; _dirty = true; } void UserCacheItem::SetDataMap( const byte * data, uint size ) { const char * d = (const char *)data; uint p = 0; while(p < size) { uint l = (uint)strnlen(d + p, size - p); uint e = p + l; for(uint i = p; i < e; i ++) { if(d[i] == '=') { _data_map[std::string(d + p, d + i)] = std::string(d + i + 1, d + e); break; } } p = e + 1; } } void UserCacheItem::BuildDataMap( Utils::Stream& st ) { data_map_t::iterator it; for(it = _data_map.begin(); it != _data_map.end(); ++ it) { if(it->second.empty()) continue; std::string single = it->first + '=' + it->second; st << single; } } void UserCacheItem::FriendSendInfo(std::string text, bool mutual) { std::set<Core::Client *> toset; for(uint i = 0; i < _friend_list.size(); i ++) { Friend_t& fr = _friend_list[i]; Core::Client * c; if((!mutual || fr.mutual) && fr.user.get() != NULL && (c = Core::clientPool[fr.user->GetUsername()]) != NULL) { toset.insert(c); } } if(!toset.empty()) Core::Message::Send(toset, NULL, Core::Message::Info, text, false); } void UserCacheItem::FriendWhisper(Core::Client* from, std::string text, bool mutual) { std::set<Core::Client *> toset; for(uint i = 0; i < _friend_list.size(); i ++) { Friend_t& fr = _friend_list[i]; Core::Client * c; if((!mutual || fr.mutual) && fr.user.get() != NULL && (c = Core::clientPool[fr.user->GetUsername()]) != NULL) { toset.insert(c); } } if(!toset.empty()) Core::Message::Send(toset, from, Core::Message::Whisper, text, false); } int UserCacheItem::AddFriend( UserCacheItem::Pointer user, int *mutIdx /*= NULL*/ ) { if(user.get() == NULL || user.get() == this) { return -1; } Friend_t fr; int idx1 = FindFriend(user.get()); if(idx1 >= 0) return idx1; if(_friend_list.size() > 20) return -1; int idx2 = user->FindFriend(this); if(idx2 >= 0) { if(mutIdx != NULL) { *mutIdx = idx2; } user->GetFriend(idx2)->mutual = true; } else { if(mutIdx != NULL) { *mutIdx = -1; } } fr.mutual = (idx2 >= 0); fr.user = user; _friend_list.push_back(fr); _friend_dirty = true; return _friend_list.size() - 1; } bool UserCacheItem::MoveFriend( uint idx1, uint idx2 ) { if(idx1 < 0 || idx1 >= _friend_list.size()) return false; if(idx2 < 0 || idx2 >= _friend_list.size()) return false; if(idx1 == idx2) return true; Friend_t& fr = _friend_list[idx1]; if(idx1 < idx2) { for(uint i = idx1; i < idx2; i ++) { _friend_list[i] = _friend_list[i + 1]; } } else { for(uint i = idx1; i > idx2; i --) { _friend_list[i] = _friend_list[i - 1]; } } _friend_list[idx2] = fr; _friend_dirty = true; return true; } bool UserCacheItem::RemoveFriend( uint idx ) { if(idx < 0 || idx >= _friend_list.size()) return false; if(_friend_list.size() > idx + 1) { for(size_t i = _friend_list.size() - 1; i > idx; i --) { _friend_list[i - 1] = _friend_list[i]; } } _friend_list.resize(_friend_list.size() - 1); _friend_dirty = true; return true; } bool UserCacheItem::RemoveFriend( UserCacheItem * user ) { int index = FindFriend(user); if(index < 0) return false; return RemoveFriend(index); } bool UserCacheItem::RemoveFriend( std::string name ) { int index = FindFriend(name); if(index < 0) return false; return RemoveFriend(index); } int UserCacheItem::FindFriend( UserCacheItem * user ) { for(size_t i = 0; i < _friend_list.size(); i ++) { if(_friend_list[i].user == user) return i; } return -1; } int UserCacheItem::FindFriend( std::string name ) { for(size_t i = 0; i < _friend_list.size(); i ++) { if(_STR.strcmpi(_friend_list[i].user->GetUsername().c_str(), name.c_str()) == 0) return i; } return -1; } uint UserCacheItem::GetFriendCount() { return _friend_list.size(); } UserCacheItem::Friend_t* UserCacheItem::GetFriend( uint index ) { if(index < 0 || index >= _friend_list.size()) return NULL; return &_friend_list[index]; } UserCache::UserCache(): _next_uid(1), _count(0) { _name_map.rehash(Core::cfg.GetHashtableSize()); _id_map.rehash(Core::cfg.GetHashtableSize()); } UserCacheItem::Pointer UserCache::Add( const char * name, uint uid ) { UserCacheItem * item_ = new UserCacheItem(name); if(item_ == NULL) return NULL; UserCacheItem::Pointer item(item_); if(uid == 0) { uid = _next_uid; ++ _next_uid; } else { if(uid >= _next_uid) _next_uid = uid + 1; } item->SetUserId(uid); if(uid > 0) { _count ++; _id_map[uid] = item; } _name_map[name] = item; return item; } UserCacheItem::Pointer UserCache::Take( uint id ) { if(id == 0) return UserCacheItem::Pointer(); UIntMap_t::iterator it = _id_map.find(id); if(it == _id_map.end()) return UserCacheItem::Pointer(); _count --; UserCacheItem::Pointer ptr = it->second; _name_map.erase(ptr->GetUsername()); _id_map.erase(it); return ptr; } UserCacheItem::Pointer UserCache::Take( const char * name ) { InCaseStringMap_t::iterator it = _name_map.find(name); if(it == _name_map.end()) return UserCacheItem::Pointer(); UserCacheItem::Pointer ptr = it->second; if(ptr->GetUserId() > 0) { _count --; _id_map.erase(ptr->GetUserId()); } _name_map.erase(it); return ptr; } void UserCache::Remove( uint id ) { if(id == 0) return; UIntMap_t::iterator it = _id_map.find(id); if(it == _id_map.end()) return; _count --; _name_map.erase(it->second->GetUsername()); _id_map.erase(it); } void UserCache::Remove( const char * name ) { InCaseStringMap_t::iterator it = _name_map.find(name); if(it == _name_map.end()) return; if(it->second->GetUserId() > 0) { _count --; _id_map.erase(it->second->GetUserId()); } _name_map.erase(it); } UserCacheItem::Pointer UserCache::operator[]( std::string name ) { InCaseStringMap_t::iterator it = _name_map.find(name); if(it == _name_map.end()) return LoadUser(name.c_str()); if(!it->second->IsExist()) return UserCacheItem::Pointer(); return it->second; } UserCacheItem::Pointer UserCache::operator[]( uint id ) { UIntMap_t::iterator it = _id_map.find(id); if(it == _id_map.end()) return LoadUser(NULL, id); if(!it->second->IsExist()) return UserCacheItem::Pointer(); return it->second; } UserCacheItem::Pointer UserCache::LoadUser( const char* name, uint id ) { std::vector<std::vector<Storage::Storage::DataDef> > result; const char * keys[] = {"userid", "username", "salt", "verifier", "passwd", "mail", "flag", "data", NULL}; char whereexpr[128]; if(name != NULL) { sprintf(whereexpr, "username=\"%s\"", name); } else { sprintf(whereexpr, "userid=%u", id); } Storage::storage->GetMatch("users", keys, whereexpr, result); size_t c = result.size(); if(c > 1) { Storage::storage->RemoveMatch("users", whereexpr); } else if(c == 1) { std::vector<Storage::Storage::DataDef>& row = result[0]; LOG_DEBUG(("Loaded %s", row[1].sVal)); uint user_id = (uint)row[0].lVal; UserCacheItem::Pointer ptr = Add(row[1].sVal, user_id); if(row[2].bSize >= 32) ptr->SetSalt(row[2].bVal); if(row[3].bSize >= 32) ptr->SetVerifier(row[3].bVal); if(row[4].bSize >= 20) ptr->SetPasswd(row[4].bVal); ptr->SetMail(row[5].sVal); ptr->SetFlag((uint)row[6].lVal); ptr->SetDataMap(row[7].bVal, row[7].bSize); ptr->SetDirty(false); const char * fkeys[] = {"friendlist", NULL}; result.clear(); sprintf(whereexpr, "userid=%u", user_id); Storage::storage->GetMatch("friends", fkeys, whereexpr, result); c = result.size(); if(c >= 1) { std::vector<Storage::Storage::DataDef>& row = result[0]; const uint * data = (const uint *)row[0].bVal; c = row[0].bSize / sizeof(uint); for(uint i = 0; i < c; ++ i) ptr->AddFriend((*this)[data[i]], NULL); } return ptr; } UserCacheItem * item_ = new UserCacheItem(name); if(item_ == NULL) return NULL; UserCacheItem::Pointer item(item_); _name_map[name] = item; return UserCacheItem::Pointer(); } void UserCache::LoadFromDB() { std::vector<std::vector<Storage::Storage::DataDef> > result; const char * keys[] = {"MAX(userid)", NULL}; Storage::storage->GetAll("users", keys, result); size_t c = result.size(); if(c >= 1) { std::vector<Storage::Storage::DataDef>& row = result[0]; LOG_DEBUG(("Maximum user id is: %u", (uint)row[0].lVal)); _next_uid = (uint)row[0].lVal + 1; } const char * keys2[] = {"COUNT(userid)", NULL}; Storage::storage->GetAll("users", keys2, result); c = result.size(); if(c >= 1) { std::vector<Storage::Storage::DataDef>& row = result[0]; LOG_DEBUG(("User count is: %u", (uint)row[0].lVal)); _count = (uint)row[0].lVal; } } void UserCache::SaveToDB() { UIntMap_t::iterator it; Storage::storage->Begin(); for(it = _id_map.begin(); it != _id_map.end(); ++ it) { if(it->second.get() == NULL) continue; UserCacheItem * item = it->second.get(); if(item->IsDirty()) { item->SetDirty(false); Storage::Storage::DataDef df[8]; df[0].SetInt(item->GetUserId()); df[1].SetString(item->GetUsername().c_str()); df[2].SetBinary(item->GetSalt(), 32); df[3].SetBinary(item->GetVerifier(), 32); df[4].SetBinary(item->GetPasswd(), 20); df[5].SetString(item->GetMail().c_str()); df[6].SetInt(item->GetFullFlag()); Utils::Stream buf; item->BuildDataMap(buf); df[7].SetBinary(buf, buf.size()); const char * keys[] = {"userid", "username", "salt", "verifier", "passwd", "mail", "flag", "data", NULL}; Storage::storage->Set("users", keys, df); } if(item->IsFriendDirty()) { item->SetFriendDirty(false); Storage::Storage::DataDef df[2]; df[0].SetInt(item->GetUserId()); std::vector<uint> fridlist; for(uint i = 0; i < item->GetFriendCount(); ++ i) { UserCacheItem::Friend_t * fr = item->GetFriend(i); if(fr == NULL || fr->user.get() == NULL) continue; fridlist.push_back(fr->user->GetUserId()); } if(fridlist.empty()) df[1].SetBinary(NULL, 0); else df[1].SetBinary((const byte *)&fridlist[0], sizeof(uint) * fridlist.size()); const char * keys[] = {"userid", "friendlist", NULL}; Storage::storage->Set("friends", keys, df); } } Storage::storage->Commit(); } }
6fe13a1ce894dfc5a56c0aae2aa7bd58057139c5
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/559.cpp
0ec6c6a3e7d82e8469a14c34e23cf6126d5511b9
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,037
cpp
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for(int i=0;i<(int)(n);++i) #define FOR(i, b, n) for(int i=b;i<(n);++i) #define ALL(c) (c).begin(),(c).end() #define PB(c) push_back(c) #define SS size() #define ST first #define ND second typedef long long ll; typedef vector<int> vi; typedef set<int> si; typedef vector<vi> vvi; typedef pair<int, int> pii; template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; } template<typename T, typename U> static void amax(T &x, U y) { if (x < y) x = y; } int di(int n){ int s = 0; while(n!=0) { s+= n%10; n/=10; } return s; } int main() { ios::sync_with_stdio(0); int k; cin >> k; int N=10000; vi f(N+1); FOR(i,1,N+1) f[i]= f[i/10]+i%10; FOR(i,2,100000000) { if (f[i/N] + f[i%N]==10) k--; // 11111|22222 count separately >1e5, <1e5 if (k==0) { cout << i << endl; return 0;} } }
0670f7745009ce2d9bc45b07ed9bc0b8bee996e1
3c280e0f3ba927a5456bfc12bec350ee45540f72
/hardware/libsensors/AccelSensor.cpp
a12c327a61ca8d3e16260a654b037ace3cf6b149
[]
no_license
spiesolo/device-softwinner-common
ff0e8a5818925a8885d767db7a7b3b47181302c9
f3f15428fd1af48f87dc391d571358f1d9fbef13
refs/heads/master
2021-01-01T17:51:54.816604
2017-07-24T07:41:54
2017-07-24T07:44:56
98,181,119
1
0
null
null
null
null
UTF-8
C++
false
false
11,424
cpp
/* * Copyright (C) 2012 Freescale Semiconductor Inc. * Copyright (C) 2008 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. */ #define LOG_TAG "AccelSensors" #include <string.h> #include <fcntl.h> #include <errno.h> #include <math.h> #include <stdlib.h> #include <poll.h> #include <unistd.h> #include <dirent.h> #include <sys/select.h> #include <dlfcn.h> #include <cutils/log.h> #include <cutils/properties.h> #include "AccelSensor.h" #define ACC_DATA_NAME gsensorInfo.sensorName #define ACC_SYSFS_PATH "/sys/class/input" #define ACC_SYSFS_DELAY "delay" #define ACC_SYSFS_ENABLE "enable" #define ACC_EVENT_X ABS_X #define ACC_EVENT_Y ABS_Y #define ACC_EVENT_Z ABS_Z AccelSensor::AccelSensor() : SensorBase(NULL, ACC_DATA_NAME), mEnabled(0), mPendingMask(0), convert(0.0), direct_x(0), direct_y(0), direct_z(0), direct_xy(-1), mInputReader(16), mDelay(0) { #ifdef DEBUG_SENSOR ALOGD("sensorName:%s,classPath:%s,lsg:%f\n", gsensorInfo.sensorName, gsensorInfo.classPath, gsensorInfo.priData); #endif if (strlen(gsensorInfo.sensorName)) { if(! gsensor_cfg()) ALOGE("gsensor config error!\n"); } memset(&mPendingEvent, 0, sizeof(mPendingEvent)); memset(&mAccData, 0, sizeof(mAccData)); mPendingEvent.version = sizeof(sensors_event_t); mPendingEvent.sensor = ID_A; mPendingEvent.type = SENSOR_TYPE_ACCELEROMETER; mPendingEvent.acceleration.status = SENSOR_STATUS_ACCURACY_HIGH; mUser = 0; #ifdef DEBUG_SENSOR ALOGD("%s:data_fd:%d\n", __func__, data_fd); #endif if(!strcmp(ACC_DATA_NAME, "lsm303d_acc")) { sprintf(gsensorInfo.classPath, "%s/%s/%s", gsensorInfo.classPath, "device", "accelerometer"); ALOGD("gsensorInfo.classPath:%s", gsensorInfo.classPath); } } AccelSensor::~AccelSensor() { } char* AccelSensor::get_cfg_value(char *buf) { int j = 0; int k = 0; char* val; val = strtok(buf, "="); if (val != NULL){ val = strtok(NULL, " \n\r\t"); } buf = val; return buf; } int AccelSensor::gsensor_cfg() { FILE *fp; int name_match = 0; char buf[128] = {0}; char * val; if((fp = fopen(GSENSOR_CONFIG_PATH, "rb")) == NULL) { ALOGD("can't not open file!\n"); return 0; } while(fgets(buf, LINE_LENGTH, fp)) { if (!strncmp(buf, GSENSOR_NAME, strlen(GSENSOR_NAME))) { val = get_cfg_value(buf); #ifdef DEBUG_SENSOR ALOGD("val:%s\n",val); #endif name_match = (strncmp(val, gsensorInfo.sensorName, strlen(gsensorInfo.sensorName))) ? 0 : 1; if (name_match) { convert = (GRAVITY_EARTH/gsensorInfo.priData); #ifdef DEBUG_SENSOR ALOGD("lsg: %f,convert:%f", gsensorInfo.priData, convert); #endif memset(&buf, 0, sizeof(buf)); continue; } } if(name_match ==0){ memset(&buf, 0, sizeof(buf)); continue; }else if(name_match < 5){ name_match++; val = get_cfg_value(buf); #ifdef DEBUG_SENSOR ALOGD("val:%s\n", val); #endif if (!strncmp(buf,GSENSOR_DIRECTX, strlen(GSENSOR_DIRECTX))){ direct_x = (strncmp(val, TRUE,strlen(val))) ? convert * (-1) : convert; } if (!strncmp(buf, GSENSOR_DIRECTY, strlen(GSENSOR_DIRECTY))){ direct_y =(strncmp(val, TRUE,strlen(val))) ? convert * (-1) : convert; } if (!strncmp(buf, GSENSOR_DIRECTZ, strlen(GSENSOR_DIRECTZ))){ direct_z =(strncmp(val, TRUE,strlen(val))) ? convert * (-1) : convert; } if (!strncmp(buf,GSENSOR_XY, strlen(GSENSOR_XY))){ direct_xy = (strncmp(val, TRUE,strlen(val))) ? 0 : 1; } }else{ name_match = 0; break; } memset(&buf, 0, sizeof(buf)); } #ifdef DEBUG_SENSOR ALOGD("direct_x: %f,direct_y: %f,direct_z: %f,direct_xy:%d,sensor_name:%s \n", direct_x, direct_y, direct_z, direct_xy, gsensorInfo.sensorName); #endif if((direct_x == 0) || (direct_y == 0) || (direct_z == 0) || (direct_xy == (-1)) || (convert == 0.0)) { return 0; } fclose(fp); return 1; } int AccelSensor::setEnable(int32_t handle, int en) { int err = 0; //ALOGD("enable: handle: %ld, en: %d", handle, en); if(handle != ID_A && handle != ID_O && handle != ID_M) return -1; if(en) mUser++; else{ mUser--; if(mUser < 0) mUser = 0; } if(mUser > 0) err = enable_sensor(); else err = disable_sensor(); if(handle == ID_A ) { if(en) mEnabled++; else mEnabled--; if(mEnabled < 0) mEnabled = 0; } //update_delay(); #ifdef DEBUG_SENSOR ALOGD("AccelSensor enable %d ,usercount %d, handle %d ,mEnabled %d, err %d", en, mUser, handle, mEnabled, err); #endif return 0; } int AccelSensor::setDelay(int32_t handle, int64_t ns) { // ALOGD("delay: handle: %ld, ns: %lld", handle, ns); if (ns < 0) return -EINVAL; #ifdef DEBUG_SENSOR ALOGD("%s: ns = %lld", __func__, ns); #endif mDelay = ns; return update_delay(); } int AccelSensor::update_delay() { return set_delay(mDelay); } int AccelSensor::readEvents(sensors_event_t* data, int count) { if (count < 1) return -EINVAL; ssize_t n = mInputReader.fill(data_fd); if (n < 0) return n; int numEventReceived = 0; input_event const* event; while (count && mInputReader.readEvent(&event)) { int type = event->type; if ((type == EV_ABS) || (type == EV_REL) || (type == EV_KEY)) { processEvent(event->code, event->value); mInputReader.next(); } else if (type == EV_SYN) { int64_t time = timevalToNano(event->time); if (mPendingMask) { mPendingMask = 0; mPendingEvent.timestamp = time; if (mEnabled) { *data++ = mPendingEvent; mAccData = mPendingEvent; count--; numEventReceived++; } } if (!mPendingMask) { mInputReader.next(); } } else { ALOGE("AccelSensor: unknown event (type=%d, code=%d)", type, event->code); mInputReader.next(); } } return numEventReceived; } void AccelSensor::processEvent(int code, int value) { switch (code) { case ACC_EVENT_X : mPendingMask = 1; if(direct_xy) { mPendingEvent.acceleration.y= value * direct_y; }else { mPendingEvent.acceleration.x = value * direct_x; } break; case ACC_EVENT_Y : mPendingMask = 1; if(direct_xy) { mPendingEvent.acceleration.x = value * direct_x; }else { mPendingEvent.acceleration.y = value * direct_y; } break; case ACC_EVENT_Z : mPendingMask = 1; mPendingEvent.acceleration.z = value * direct_z ; break; } #ifdef DEBUG_SENSOR ALOGD("Sensor data: x,y,z: %f, %f, %f\n", mPendingEvent.acceleration.x, mPendingEvent.acceleration.y, mPendingEvent.acceleration.z); #endif } int AccelSensor::writeEnable(int isEnable) { char buf[2]; int err = -1 ; if(gsensorInfo.classPath[0] == ICHAR) return -1; int bytes = sprintf(buf, "%d", isEnable); if(!strcmp(ACC_DATA_NAME, "lsm303d_acc")) { err = set_sysfs_input_attr(gsensorInfo.classPath,"enable_device",buf,bytes); }else { err = set_sysfs_input_attr(gsensorInfo.classPath,"enable",buf,bytes); } return err; } int AccelSensor::writeDelay(int64_t ns) { if(gsensorInfo.classPath[0] == ICHAR) return -1; if (ns > 10240000000LL) { ns = 10240000000LL; /* maximum delay in nano second. */ } if (ns < 312500LL) { ns = 312500LL; /* minimum delay in nano second. */ } char buf[80]; int bytes = sprintf(buf, "%lld", ns/1000 / 1000); if(!strcmp(ACC_DATA_NAME, "lsm303d_acc")) { int err = set_sysfs_input_attr(gsensorInfo.classPath,"pollrate_us",buf,bytes); } else { int err = set_sysfs_input_attr(gsensorInfo.classPath,"delay",buf,bytes); } return 0; } int AccelSensor::enable_sensor() { return writeEnable(1); } int AccelSensor::disable_sensor() { return writeEnable(0); } int AccelSensor::set_delay(int64_t ns) { return writeDelay(ns); } int AccelSensor::getEnable(int32_t handle) { return (handle == ID_A) ? mEnabled : 0; } /*****************************************************************************/
18b7f60bf895be64417d76d73d74b1fc632d5afb
5ee0eb940cfad30f7a3b41762eb4abd9cd052f38
/Case_save/case9/100/nut
8b63a8b82d888baf621763c9768bdaa1b19cde77
[]
no_license
mamitsu2/aircond5_play4
052d2ff593661912b53379e74af1f7cee20bf24d
c5800df67e4eba5415c0e877bdeff06154d51ba6
refs/heads/master
2020-05-25T02:11:13.406899
2019-05-20T04:56:10
2019-05-20T04:56:10
187,570,146
0
0
null
null
null
null
UTF-8
C++
false
false
9,982
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "100"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 0.000959748 0.00103077 0.001035 0.00108002 0.00112147 0.00115965 0.00119618 0.00123316 0.00126414 0.00128226 0.00128169 0.00125762 0.00120865 0.00114034 0.00106643 0.000475683 0.000567158 0.000619739 0.000612411 0.000596399 0.000576426 0.000549796 0.000522311 0.000496965 0.000474295 0.000454151 0.000436241 0.000420182 0.000405738 0.000392392 0.000379369 0.000365593 0.000356684 0.000331125 0.00136633 0.00288915 0.00263352 0.00306417 0.00343334 0.0038161 0.00417848 0.00446401 0.00471354 0.00493394 0.00508925 0.00513923 0.00502546 0.0046069 0.00342934 0.001065 0.000649557 0.000516043 0.000964135 0.00129439 0.00156359 0.00173179 0.00176598 0.00145558 0.00128627 0.00116132 0.00106197 0.000981166 0.000915188 0.000862358 0.000812368 0.000757912 0.000705735 0.000659383 0.000782632 0.000419442 0.00171407 0.00398563 0.00303808 0.00403261 0.00438697 0.00463136 0.00482013 0.00497653 0.00514687 0.00533465 0.00551314 0.00565976 0.00575288 0.00574343 0.00549763 0.00449744 0.00100583 0.000959019 0.0013262 0.00166769 0.00201989 0.00230674 0.0022951 0.00074611 0.000671221 0.000609419 0.000558326 0.00051569 0.000479771 0.000449383 0.000424154 0.000404483 0.000447232 0.000532208 0.000906222 0.000485461 0.00205767 0.0053893 0.00294078 0.00420862 0.0045566 0.00462035 0.00464161 0.00470518 0.00483557 0.00501094 0.00519493 0.00537581 0.00555621 0.00571437 0.00580007 0.00557398 0.00444122 0.00122358 0.00159012 0.00208375 0.00258553 0.00302593 0.00333273 0.00312792 0.000824926 0.000767115 0.000730764 0.000704935 0.000681534 0.000654772 0.000627959 0.000598 0.000561019 0.00053557 0.00056212 0.00108138 0.000538217 0.00240914 0.00724776 0.00335573 0.00391371 0.00448809 0.00448038 0.00439898 0.00442822 0.00458096 0.00477452 0.004958 0.0051345 0.00531921 0.0054774 0.00555363 0.00549586 0.00517542 0.00438586 0.00417578 0.00421809 0.00434912 0.00448893 0.00457403 0.00447389 0.00383509 0.00361034 0.00350636 0.00341651 0.00329549 0.00311473 0.00278852 0.00236883 0.00189245 0.00140913 0.00103377 0.00107211 0.000701553 0.000664195 0.00079324 0.000886882 0.00277776 0.00926294 0.00511804 0.00371461 0.00416082 0.00435719 0.00436582 0.00433183 0.00453532 0.00473351 0.00490157 0.00506007 0.00522567 0.00536716 0.00541063 0.00533741 0.00522495 0.00514348 0.00518643 0.00523802 0.00524886 0.00522733 0.00516739 0.00504997 0.00485524 0.00470842 0.00457699 0.00443031 0.00425756 0.00405543 0.00377669 0.00337635 0.00285732 0.00225077 0.00168771 0.00123422 0.000947709 0.000837176 0.00121715 0.000930728 0.00312974 0.0107943 0.0080299 0.00525133 0.00440145 0.00429986 0.00450485 0.00459513 0.00471393 0.00484032 0.00496318 0.00509744 0.00526299 0.00541816 0.00546182 0.00537673 0.0053144 0.00539642 0.00549764 0.00549006 0.00538983 0.00524725 0.00508832 0.00492928 0.00477945 0.00464264 0.00449867 0.00433846 0.00416804 0.00400212 0.00384905 0.00361297 0.00321647 0.00269051 0.00217169 0.00168244 0.00135304 0.00129326 0.00136553 0.00107917 0.00320575 0.0100566 0.00868373 0.00760551 0.00654774 0.00583755 0.00549377 0.00517507 0.00503404 0.00503812 0.00509311 0.00520144 0.00538763 0.00558493 0.00564706 0.00555857 0.005489 0.0054736 0.00534727 0.00516112 0.00495548 0.0047562 0.0045732 0.00440809 0.00425765 0.00411209 0.00396218 0.00381367 0.00368342 0.00359114 0.00355268 0.00354871 0.00336595 0.00299401 0.00266429 0.00251638 0.00269201 0.00334976 0.00428475 0.00165327 0.00312932 0.00374093 0.00425429 0.00448617 0.0046084 0.00461058 0.00461658 0.00473355 0.00495385 0.0051299 0.00520091 0.00532777 0.00558603 0.00585214 0.00590964 0.00577769 0.00546907 0.0050907 0.00475909 0.00449579 0.00428308 0.00410366 0.0039421 0.00378583 0.00362602 0.00345787 0.00328296 0.00310948 0.00294667 0.0027998 0.0026691 0.00255147 0.0024617 0.0024024 0.00239654 0.00243489 0.00244187 0.00234415 0.00217429 0.00151437 0.0020608 0.00400447 0.00473608 0.0051595 0.00554898 0.00587702 0.00593785 0.00569763 0.00538399 0.00548716 0.00584135 0.00615906 0.00611317 0.00563759 0.00502045 0.00451781 0.00418872 0.00397237 0.00381198 0.00367404 0.0035388 0.00339514 0.00323884 0.00307181 0.00290149 0.00273932 0.0025981 0.00249033 0.00242711 0.00240912 0.00241722 0.00244166 0.00246877 0.00246452 0.00237749 0.00218531 0.00190055 0.0012224 0.0023604 0.00494791 0.00588309 0.00596497 0.00607244 0.00616492 0.00559773 0.0047947 0.00427723 0.00482071 0.00508056 0.00512378 0.00491454 0.00449127 0.00405141 0.00373761 0.00353382 0.00339286 0.00328028 0.00317586 0.00306949 0.0029585 0.00284589 0.00273862 0.00264506 0.00257176 0.00252063 0.00248696 0.00248543 0.00251774 0.00257744 0.00265286 0.00272415 0.0027756 0.00276401 0.00275352 0.00239798 0.00123823 0.00203783 0.00215366 0.00224346 0.00236119 0.00222309 0.00207525 0.00188693 0.00160824 0.00129889 0.00113199 0.00105921 0.0010549 0.00104566 0.00100144 0.000950563 0.000908355 0.000880891 0.000862513 0.000850324 0.000841819 0.000835644 0.000831385 0.000829276 0.000829958 0.000834246 0.000842949 0.000856786 0.000876448 0.000902841 0.000937512 0.000979574 0.00102921 0.00108651 0.00115163 0.00122409 0.00131969 0.00135053 0.00131897 0.00122995 0.00113467 ) ; boundaryField { floor { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 29 ( 0.000128501 5.66116e-05 6.82439e-05 7.48231e-05 7.39096e-05 7.191e-05 6.94068e-05 6.60531e-05 6.25711e-05 5.93401e-05 5.64329e-05 5.38351e-05 5.15133e-05 4.94211e-05 4.75308e-05 4.57765e-05 4.40571e-05 4.223e-05 4.1043e-05 3.7617e-05 3.76169e-05 4.93212e-05 5.78625e-05 6.45834e-05 0.000128501 5.66116e-05 6.17753e-05 0.000115893 0.000146716 ) ; } ceiling { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 43 ( 0.000237314 0.00024985 0.000259521 0.00027226 0.000257489 0.000241544 0.000221048 0.000190272 0.000155308 0.000136084 0.000127613 0.000127115 0.000126056 0.000120878 0.000114881 0.000109877 0.000106606 0.000104411 0.000102952 0.000101932 0.000101191 0.000100679 0.000100426 0.000100508 0.000101023 0.000102067 0.000103726 0.000106077 0.000109224 0.000113342 0.000118314 0.000124149 0.000130847 0.00013841 0.000146768 0.000157712 0.000161223 0.00015763 0.000147441 0.000136444 0.000353537 0.000416541 0.000271916 ) ; } sWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 0.000237381; } nWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 6(0.000107322 0.000112538 0.000129996 0.000146586 0.000148404 0.000136454); } sideWalls { type empty; } glass1 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(0.000116039 0.00016322 0.000202299 0.00024006 0.000277986 0.000317138 0.000354018 0.000361936 0.000354004); } glass2 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 2(0.000195355 0.000179826); } sun { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 14 ( 0.000115972 0.000124329 0.000124824 0.000130086 0.000134907 0.000139332 0.000143549 0.000147805 0.000151358 0.000153432 0.000153367 0.000150611 0.000144987 0.000137097 ) ; } heatsource1 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 3(8.03252e-05 9.60781e-05 0.000107318); } heatsource2 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 4(0.000128332 7.85181e-05 7.85181e-05 0.000121398); } Table_master { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(9.03697e-05 8.11983e-05 7.35369e-05 6.71321e-05 6.17327e-05 5.71414e-05 5.32239e-05 4.99467e-05 4.7375e-05); } Table_slave { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(9.99045e-05 9.29207e-05 8.84975e-05 8.53388e-05 8.24651e-05 7.91648e-05 7.58418e-05 7.21087e-05 6.7469e-05); } inlet { type calculated; value uniform 0.000100623; } outlet { type calculated; value nonuniform List<scalar> 2(0.00203783 0.00215366); } } // ************************************************************************* //
b36ddc82c7640ec5beda0a3c7cec8aac14b09ec1
ffb8f7050f2287ae9a78f7a5a8011ce6638d9020
/DCMTK_New_Demo/DCMTKLib/dcmtk/dcmjpeg/djencbas.h
aa96e391f0d3ede148ebe1eacd2ef485b0b86a13
[]
no_license
alvinak/DCMTK_Demo
77023c549b802bbb3131d7ad21cd0e0941260120
7c598eadce19d02736680050bcf384610a0c9b1e
refs/heads/master
2020-07-28T15:38:16.164507
2019-01-28T03:19:21
2019-01-28T03:19:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,479
h
/* * * Copyright (C) 1997-2011, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmjpeg * * Author: Marco Eichelberg, Norbert Olges * * Purpose: Codec class for encoding JPEG Baseline (lossy, 8-bit) * */ #ifndef DJENCBAS_H #define DJENCBAS_H #include "../config/osconfig.h" #include "../dcmjpeg/djcodece.h" /* for class DJCodecEncoder */ /** Encoder class for JPEG Baseline (lossy, 8-bit) */ class DCMTK_DCMJPEG_EXPORT DJEncoderBaseline : public DJCodecEncoder { public: /// default constructor DJEncoderBaseline(); /// destructor virtual ~DJEncoderBaseline(); /** returns the transfer syntax that this particular codec * is able to encode and decode. * @return supported transfer syntax */ virtual E_TransferSyntax supportedTransferSyntax() const; private: /** returns true if the transfer syntax supported by this * codec is lossless. * @return lossless flag */ virtual OFBool isLosslessProcess() const; /** creates 'derivation description' string after encoding. * @param toRepParam representation parameter passed to encode() * @param cp codec parameter passed to encode() * @param bitsPerSample bits per sample of the original image data prior to compression * @param ratio image compression ratio. This is not the "quality factor" * but the real effective ratio between compressed and uncompressed image, * i. e. 30 means a 30:1 lossy compression. * @param imageComments image comments returned in this * parameter which is initially empty */ virtual void createDerivationDescription( const DcmRepresentationParameter * toRepParam, const DJCodecParameter *cp, Uint8 bitsPerSample, double ratio, OFString& derivationDescription) const; /** creates an instance of the compression library to be used * for encoding/decoding. * @param toRepParam representation parameter passed to encode() * @param cp codec parameter passed to encode() * @param bitsPerSample bits per sample for the image data * @return pointer to newly allocated codec object */ virtual DJEncoder *createEncoderInstance( const DcmRepresentationParameter * toRepParam, const DJCodecParameter *cp, Uint8 bitsPerSample) const; }; #endif
86ba1138ab9ffb708fdf0b60e1166790e24fdf91
76454d4e8c6731836d16dc63f7bfebd89927d2d3
/mydevice/code/Test_Move_Head/Test_Move_Head.ino
f44cf6b2d2a8622c82d46edc0ec58c9b9e932287
[]
no_license
andrewintw/fujiwara-marina-muda-device-workshop
70274c7ae070d7309298a5d25f6e29776cbdc826
83ca4b5402266f0abde4574a8e68409739dab1fb
refs/heads/main
2022-12-30T10:31:28.924848
2020-10-19T06:23:55
2020-10-19T06:23:55
304,695,340
0
0
null
null
null
null
UTF-8
C++
false
false
734
ino
#include <Servo.h> Servo ServoHead; // pin9 void setup() { ServoHead.attach(9); Serial.begin(9600); delay(1000); ServoHead.write(80); delay(1000); } void moveServo(Servo &servo, int startPos, int endPos, int delayTime) { int pos = 0; if (startPos < endPos) { for (pos = startPos; pos <= endPos; pos += 1) { servo.write(pos); delay(delayTime); } } else { for (pos = startPos; pos >= endPos; pos -= 1) { servo.write(pos); delay(delayTime); } } } void loop() { Serial.println("1: Turn head"); moveServo(ServoHead, 80, 150, 100); delay(3000); Serial.println("2: Turn head back"); moveServo(ServoHead, 150, 80, 100); }
d1e8f27f4ba2b9e10987a8f23ae1fe1711d2c709
2e03a084b065b8ccadcb08f1f95ff1bb408c0613
/CrapGL/CameraRayPoint.h
18d067d526c7939e0955bca97c26841be52164ec
[]
no_license
solitaryzero/myCrapGL
4c7042d4840ab2511e634048fe0bb595a6bdb30b
852ff0ca6a0848e6aab09a7a3281a935fca33b43
refs/heads/master
2021-01-16T19:14:20.926105
2017-08-13T05:58:08
2017-08-13T05:58:08
100,156,656
0
0
null
null
null
null
UTF-8
C++
false
false
292
h
#pragma once #include "Vector3.h" #include "IntersectInfo.h" #include "ray.h" class CameraRayPoint { public: int x, y; ray cameraRay; double modifier; IntersectInfo info; CameraRayPoint(); CameraRayPoint(int x_, int y_, double mo, ray c_, IntersectInfo info_); ~CameraRayPoint(); };
6d6d47eb24a8da88c98846e5f2b531ecc71c904d
64bcf0098acbf4c873b82920b1ff719850b0206e
/Week_16/Adaptable Functors and Fucntion Adapters/main.cpp
a143ae2c2ce468e881241c3cf82df03843c0378a
[]
no_license
luosch/13-cpp-hw
60d6a3a7fe6fc3efd50d5d96e00e3cf9204581bc
7d17253a99ae04103ddb9202fd305bd10612a499
refs/heads/master
2020-05-29T10:22:31.196385
2014-06-11T03:49:31
2014-06-11T03:49:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#include <cstdlib> #include <iostream> #include <vector> #include "Adapter.h" using std::cin; using std::cout; using std::endl; const int LIM = 6; void Show(double v) { std::cout.width(6); std::cout << v << ' '; } int main(int argc, char *argv[]) { freopen("in.txt", "r", stdin); double arr1[LIM]; double arr2[LIM]; for (int i = 0; i < LIM; i++) cin >> arr1[i]; for (int i = 0; i < LIM; i++) cin >> arr2[i]; vector<double> gr8(arr1, arr1 + LIM); vector<double> m8(arr2, arr2 + LIM); cout.setf(ios_base::fixed); cout.precision(1); cout << "gr8: \t"; Adapter::show(gr8.begin(), gr8.end(), Show); cout << endl; cout << "m8: \t"; Adapter::show(m8.begin(), m8.end(), Show); cout << endl; vector<double> sum(LIM); Adapter::add(gr8.begin(), gr8.end(), m8.begin(), sum.begin()); cout << "sum: \t"; Adapter::show(sum.begin(), sum.end(), Show); cout << endl; vector<double> prod(LIM); Adapter::multi(gr8.begin(), gr8.end(), prod.begin(), 2.5); cout << "prod: \t"; Adapter::show(prod.begin(), prod.end(), Show); cout << endl; return EXIT_SUCCESS; }
593209ad59efe41a44d4ae540e2bef4c6354d739
dd62d226dc68c87a5cd377785bf32b3b8531845b
/proj.android/Photon-AndroidNDK_SDK/Photon-cpp/inc/Enums/NetworkPort.h
6cd94ca3ed14b7183c3ecc732432306d0de6cc0b
[ "MIT" ]
permissive
h-iwata/MultiplayPaint
f3d1dd1d5cba2f304ed581f3ba9560df3c2d5466
b170ec60bdda93c041ef59625ac2d6eba54d0335
refs/heads/master
2016-09-05T15:00:27.678210
2015-07-09T09:52:18
2015-07-09T09:52:18
35,269,936
1
0
null
null
null
null
UTF-8
C++
false
false
364
h
/* Exit Games Photon - C++ Client Lib * Copyright (C) 2004-2015 by Exit Games GmbH. All rights reserved. * http://www.exitgames.com * mailto:[email protected] */ #pragma once namespace ExitGames { namespace Photon { namespace NetworkPort { static const int UDP = 5055; static const int TCP = 4530; } /** @file */ } }
37f5001f28ce68bc2afe3ecdbb0500b8b16f267b
f94aa5bd4d8814b57ae6713c1f69fa1e11bc6526
/TribesAscendSDK/HeaderDump/TribesGame__TrFamilyInfo_Medium_Warder_DS.h
a969ee4beeb29dbd925ed025a8c923ef4f839610
[]
no_license
pixel5/TASDK
71980b727b86034771ea91c67f6c02116f47c245
0dc5e4524efed291fe7d8cf936fa64e0e37e4e82
refs/heads/master
2020-05-23T15:12:55.162796
2013-07-13T00:27:32
2013-07-13T00:27:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
957
h
#pragma once #define ADD_VAR( x, y, z ) ( ##x ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( #x " TribesGame.TrFamilyInfo_Medium_Warder_DS." #y ) ); \ return ( ##x( this, script_property->offset, z ) ); \ } #define ADD_STRUCT( x, y, z ) ( ##x ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( "StructProperty TribesGame.TrFamilyInfo_Medium_Warder_DS." #y ) ); \ return ( ##x( this, script_property->offset, z ) ); \ } #define ADD_OBJECT( x, y ) ( class x* ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( "ObjectProperty TribesGame.TrFamilyInfo_Medium_Warder_DS." #y ) ); \ return *( x** )( this + script_property->offset ); \ } namespace UnrealScript { class TrFamilyInfo_Medium_Warder_DS : public TrFamilyInfo_Medium_Warder { public: }; } #undef ADD_VAR #undef ADD_STRUCT #undef ADD_OBJECT
73421d8cd0c0e5fb15abaa60515753fc0c00f62b
844a2bae50e141915a8ebbcf97920af73718d880
/Between Demo 4.1 and Demo 4.32/legacy_130_src/HARDWARE/HW_MAIN.H
0e61399d0c7c022e867703eeee64efbb84168a45
[]
no_license
KrazeeTobi/SRB2-OldSRC
0d5a79c9fe197141895a10acc65863c588da580f
a6be838f3f9668e20feb64ba224720805d25df47
refs/heads/main
2023-03-24T15:30:06.921308
2021-03-21T06:41:06
2021-03-21T06:41:06
349,902,734
0
0
null
null
null
null
UTF-8
C++
false
false
3,471
h
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id: hw_main.h,v 1.9 2000/07/01 09:23:50 bpereira Exp $ // // Copyright (C) 1998-2000 by DooM Legacy Team. // // 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. // // // $Log: hw_main.h,v $ // Revision 1.9 2000/07/01 09:23:50 bpereira // no message // // Revision 1.8 2000/05/09 20:57:31 hurdler // use my own code for colormap (next time, join with Boris own code) // (necessary due to a small bug in Boris' code (not found) which shows strange effects under linux) // // Revision 1.7 2000/04/30 10:30:10 bpereira // no message // // Revision 1.6 2000/04/27 17:48:47 hurdler // colormap code in hardware mode is now the default // // Revision 1.5 2000/04/24 15:23:13 hurdler // Support colormap for text // // Revision 1.4 2000/04/22 21:08:23 hurdler // I like it better like that // // Revision 1.3 2000/04/12 16:03:51 hurdler // ready for T&L code and true static lighting // // Revision 1.2 2000/02/27 00:42:11 hurdler // fix CR+LF problem // // Revision 1.1.1.1 2000/02/22 20:32:33 hurdler // Initial import into CVS (v1.29 pr3) // // // DESCRIPTION: // 3D render mode functions // //----------------------------------------------------------------------------- #ifndef __HWR_MAIN_H__ #define __HWR_MAIN_H__ #include "hw_data.h" #include "../am_map.h" #include "../d_player.h" #include "../r_defs.h" // Startup & Shutdown the hardware mode renderer void HWR_Startup (void); void HWR_Shutdown (void); void HWR_clearAutomap (void); void HWR_drawAMline (fline_t* fl, int color); void HWR_FadeScreenMenuBack (unsigned long color, int height); void HWR_RenderPlayerView (int viewnumber, player_t* player); void HWR_DrawViewBorder (int clearlines); void HWR_DrawFlatFill (int x, int y, int w, int h, int flatlumpnum); void HWR_Screenshot (void); void HWR_InitTextureMapping (void); void HWR_SetViewSize (int blocks); void HWR_ScalePatch (BOOL bScalePatch); void HWR_DrawPatch (GlidePatch_t* gpatch, int x, int y); void HWR_DrawMappedPatch (GlidePatch_t* gpatch, int x, int y, byte *colormap); void HWR_Make3DfxPatch (patch_t* patch, GlidePatch_t* grPatch, GlideMipmap_t *grMipmap); void HWR_CreatePlanePolygons (int bspnum); #ifdef TANDL void HWR_CreateStaticLightmaps (int bspnum); #endif void HWR_PrepLevelCache (int numtextures); void HWR_DrawFill(int x, int y, int w, int h, int color); void HWR_DrawPic(int x,int y,int lumpnum); void HWR_AddCommands (void); extern consvar_t cv_grcrappymlook; extern consvar_t cv_grdynamiclighting; extern consvar_t cv_grstaticlighting; extern consvar_t cv_grmblighting; extern consvar_t cv_grcoronas; extern consvar_t cv_grfov; extern consvar_t cv_grpolygonsmooth; extern consvar_t cv_grmd2; extern consvar_t cv_grfog; extern consvar_t cv_grfogcolor; extern consvar_t cv_grfogdensity; extern consvar_t cv_grcontrast; extern consvar_t cv_grgammared; extern consvar_t cv_grgammagreen; extern consvar_t cv_grgammablue; #endif
95a69d65bae67459f84e0e8a9a613fdfa39f3bb4
8242d218808b8cc5734a27ec50dbf1a7a7a4987a
/Intermediate/Build/Win64/Netshoot/Inc/Engine/MaterialExpressionQualitySwitch.gen.cpp
cc0d95c4c0549a88fee08d6ccc70d80d653abb1b
[]
no_license
whyhhr/homework2
a2e75b494a962eab4fb0a740f83dc8dc27f8f6ee
9808107fcc983c998d8601920aba26f96762918c
refs/heads/main
2023-08-29T08:14:39.581638
2021-10-22T16:47:11
2021-10-22T16:47:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,755
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Engine/Classes/Materials/MaterialExpressionQualitySwitch.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeMaterialExpressionQualitySwitch() {} // Cross Module References ENGINE_API UClass* Z_Construct_UClass_UMaterialExpressionQualitySwitch_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpressionQualitySwitch(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpression(); UPackage* Z_Construct_UPackage__Script_Engine(); ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FExpressionInput(); // End Cross Module References void UMaterialExpressionQualitySwitch::StaticRegisterNativesUMaterialExpressionQualitySwitch() { } UClass* Z_Construct_UClass_UMaterialExpressionQualitySwitch_NoRegister() { return UMaterialExpressionQualitySwitch::StaticClass(); } struct Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Default_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_Default; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Inputs_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_Inputs; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UMaterialExpression, (UObject* (*)())Z_Construct_UPackage__Script_Engine, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::Class_MetaDataParams[] = { { "HideCategories", "Object Object" }, { "IncludePath", "Materials/MaterialExpressionQualitySwitch.h" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpressionQualitySwitch.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Default_MetaData[] = { { "Comment", "/** Default connection, used when a specific quality level input is missing. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpressionQualitySwitch.h" }, { "ToolTip", "Default connection, used when a specific quality level input is missing." }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Default = { "Default", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpressionQualitySwitch, Default), Z_Construct_UScriptStruct_FExpressionInput, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Default_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Default_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Inputs_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpressionQualitySwitch.h" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Inputs = { "Inputs", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, CPP_ARRAY_DIM(Inputs, UMaterialExpressionQualitySwitch), STRUCT_OFFSET(UMaterialExpressionQualitySwitch, Inputs), Z_Construct_UScriptStruct_FExpressionInput, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Inputs_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Inputs_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Default, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::NewProp_Inputs, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UMaterialExpressionQualitySwitch>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::ClassParams = { &UMaterialExpressionQualitySwitch::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::PropPointers), 0, 0x000820A0u, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UMaterialExpressionQualitySwitch() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialExpressionQualitySwitch_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UMaterialExpressionQualitySwitch, 2385931841); template<> ENGINE_API UClass* StaticClass<UMaterialExpressionQualitySwitch>() { return UMaterialExpressionQualitySwitch::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialExpressionQualitySwitch(Z_Construct_UClass_UMaterialExpressionQualitySwitch, &UMaterialExpressionQualitySwitch::StaticClass, TEXT("/Script/Engine"), TEXT("UMaterialExpressionQualitySwitch"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialExpressionQualitySwitch); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
389d78c70b9dfa8f06931a9a6641a9901000f432
4c95c5ca3ca75233f8049c4fbf3d839006bfb022
/src/parse.cpp
5fd9cb71e10a68e69db25ff39a64adce3fd73f7c
[]
no_license
ybgdgh/apriltag_pares_graph
eca280b2de4bacd229f91d014758b91c8ea4d9f9
c903b7e11af2bbfe1f08036fb40af301a402f3aa
refs/heads/master
2020-08-26T23:47:10.652759
2019-10-24T02:46:27
2019-10-24T02:46:27
217,185,320
0
0
null
null
null
null
UTF-8
C++
false
false
264
cpp
#include "ros/ros.h" #include "node.h" int main(int argc, char *argv[]) { ros::init(argc, argv, "parse"); ros::NodeHandle nh; ros::NodeHandle np("~"); PARSE parse_debug(nh,np); ros::spin(); cout << "finish!" << endl; return 0; }
148ab9a3a1331d0aaea02a7b590e0031e8bb632f
bcae6681107f3102d871318619aded222714d26d
/trunk/Ej_13/p_C2/eventoscliente.cpp
ca43df6d3c5b79ee439ce430cb6ad729d0b7bc22
[]
no_license
gruizFING/SED
04d7a471391031b81ed6db61f9e0a8e7821cf002
ccef0b24ede64e0ad56c3273c5f4dc2dcfe2555f
refs/heads/master
2020-06-16T22:32:09.469388
2019-07-08T02:33:00
2019-07-08T02:33:00
195,721,732
0
0
null
null
null
null
UTF-8
C++
false
false
4,456
cpp
#include "eventoscliente.hpp" #include "banco.hpp" #include "cliente.hpp" #include <iostream> #include <math.h> using namespace eosim::core; // en el constructor se utiliza el identificador definido en eventoscliente.hpp ClienteFeeder::ClienteFeeder(Model& model): BEvent(clienteF, model) {} ClienteFeeder::~ClienteFeeder() {} void ClienteFeeder::eventRoutine(Entity* who) { Cliente* c = dynamic_cast<Cliente*>(who); // se anuncia la llegada del cliente std::string tipo = c->retiraDinero ? "Retiro" : "Otro"; std::cout << "Llega el cliente numero " << c->nro << " de tipo '" << tipo << "'. Tiempo: " << who->getClock() << "\n"; // se castea owner a un Banco Banco& b = dynamic_cast<Banco&>(owner); //Elegir caja disponible o esperar en cola q0 Cliente* cliente = dynamic_cast<Cliente*>(who); int numeroCaja = -1; for (unsigned int i = 0; i < b.cantCajas; i++) { Caja* caja = b.cajas[i]; if (caja->disponible) { //Agarro la primer caja disponible numeroCaja = i; break; } } if (numeroCaja == -1) //No hay caja disponible, poner el cliente a esperar en qInicial { b.qInicial.push(who); std::cout << "El cliente numero " << cliente->nro << " pasa a esperar en la cola. Tiempo: " << b.getSimTime() << "\n\n"; //Registro largo de la cola b.lColaCajasTW.log(b.qInicial.size()); } else // Poner al cliente en la caja elegida para ser atendido { cliente->cajaElegida = numeroCaja; Caja* caja = b.cajas[numeroCaja]; caja->disponible = false; std::cout << "La caja " << numeroCaja + 1 << " atiende al cliente numero " << cliente->nro << ". Tiempo: " << b.getSimTime() << "\n\n"; //Se toma el tiempo de ir a la caja en 10 seg agregandolo al tiempo de servicio if (cliente->retiraDinero) b.schedule(b.distTiempoServicioR.sample() + 10, cliente, salidaC); else b.schedule(b.distTiempoServicioNR.sample() + 10, cliente, salidaC); //Registro tiempo de espera para este cliente igual a 0 b.tEsperaO.log(0); } // Regristro datos sobre la cantidad de clientes b.cantClientesActuales++; b.cantClientesTW.log(b.cantClientesActuales); // creo proximo cliente y se agenda el arribo del nuevo cliente // 1 de cada 3 son retiro double probRetiro = b.distProbRetiro.sample(); Cliente* nuevoCliente = new Cliente(probRetiro > ((double)1/3) ? false : true); nuevoCliente->nro = ++b.nroCliente; //b.schedule(b.distArribosClientes.sample(), nuevoCliente, clienteF); //Para el Analisis de sensibilidad //b.schedule(tiempoEntreArribosMin, nuevoCliente, clienteF); b.schedule(tiempoEntreArribosMax, nuevoCliente, clienteF); } // en el constructor se utiliza el identificador definido en eventoscliente.hpp SalidaCliente::SalidaCliente(Model& model): BEvent(salidaC, model) {} SalidaCliente::~SalidaCliente() {} void SalidaCliente::eventRoutine(Entity* who) { Banco& b = dynamic_cast<Banco&>(owner); Cliente* cliente = dynamic_cast<Cliente*>(who); std::cout << "El cliente numero " << cliente->nro << " de la caja " << cliente->cajaElegida + 1 << " sale del banco. Tiempo: " << b.getSimTime() << "\n"; if (!b.qInicial.empty()) { // Agarro al primero de la cola Cliente* nuevoClienteCaja = dynamic_cast<Cliente*>(b.qInicial.pop()); nuevoClienteCaja->cajaElegida = cliente->cajaElegida; std::cout << "La caja " << nuevoClienteCaja->cajaElegida + 1 << " pasa a atender el cliente numero " << nuevoClienteCaja->nro << ". Tiempo: " << b.getSimTime() << "\n\n"; //Registro tiempo de espera en la cola que tuvo el cliente b.tEsperaO.log(b.getSimTime() - nuevoClienteCaja->getClock()); if (nuevoClienteCaja->retiraDinero) b.schedule(b.distTiempoServicioR.sample() + 10, nuevoClienteCaja, salidaC); else b.schedule(b.distTiempoServicioNR.sample() + 10, nuevoClienteCaja, salidaC); } else { b.cajas[cliente->cajaElegida]->disponible = true; std::cout << "La caja " << cliente->cajaElegida + 1 << " queda disponible. Tiempo: " << b.getSimTime() << "\n\n"; } // Registro datos del largo de la cola b.lColaCajasTW.log(b.qInicial.size()); // Registro datos sobre la cantidad de clientes b.cantClientesActuales--; b.cantClientesTW.log(b.cantClientesActuales); delete who; }
90d4a59f43714dae7f4c481278e14ff22d82436e
7da54b0879af988c5c18f5bb1f6dd76d711bf93d
/GalaxyWar/h/GW_Collisionnable.hpp
1c137d4547ee12b478c395a6a86ddc23e2fc2586
[]
no_license
Spirou003/Old_Galaxywar
e8bc92e6e98db56c28962e4cac3ae162316dac86
d01d0d63f15a4a0517ef942b9a09e8f2cc14b7ac
refs/heads/master
2021-01-18T21:39:18.900712
2016-10-01T15:53:23
2016-10-01T15:53:23
69,746,816
0
0
null
null
null
null
UTF-8
C++
false
false
2,247
hpp
#ifndef GW_COLLISIONNABLE_H #define GW_COLLISIONNABLE_H #include "GW_Constantes.hpp" struct GW_JeuData; #include <cmath> #include "GW_Functions.hpp" #include "../t/GW_ArrayList.hpp" #include "GW_CollisionnableAdmin.hpp" class GW_Collisionnable { public: GW_Collisionnable(void); virtual ~GW_Collisionnable(void); virtual const Shape* GetPolygon(void) const = 0; static bool Collision(const GW_Collisionnable* obj1, const GW_Collisionnable* obj2); static int Type(GW_Collisionnable* obj); virtual void Draw(RenderWindow* App) = 0; virtual bool IsDead (void) const = 0; virtual bool IsCollisionnable (void) const; virtual bool IsOut (void) const; bool IsDeletable(void); //virtual float Effet(GW_Collisionnable* obj, float self, float other) = 0; //virtual float Prepare(const GW_Collisionnable* obj) const = 0; //virtual void Paralyze(cfloat dt) = 0; //virtual void Carbonyze(cfloat dt) = 0; virtual float GetX (void) const; virtual float GetY (void) const; virtual float GetAngle (void) const; virtual void Action (GW_JeuData* truc, cfloat dt, bool lim = true) = 0; virtual bool Dead (GW_JeuData* truc, RenderWindow* App) = 0; static void EffetCollision(GW_Collisionnable* obj1, GW_Collisionnable* obj2); static void ClassicDraw(RenderWindow* App, Drawable* spr, cfloat x, cfloat y, cfloat angle); static Shape Octogon, Carre; enum Type { TA, TB, TC, TKU, TW, TX, TY, TZ, NBTIR, EA, EB, EC, ED, EE, EF, EG, EH, EI, EJ, EK, EL, EM, EN, EO, EP, EQ, ER, ES, ET, EU, EV, EW, EX, EY, EZ, EJO, NBOBJ }; static CUInt32 NBENN = NBOBJ-NBTIR-1; protected: static void ClassicDraw(RenderWindow* App, Drawable* spr, GW_Collisionnable* obj); static void PolygonProjectionToDroiteCentered(const Shape* polygon, CSInt32 nb, cfloat a, cfloat b, float* min, float* max, const GW_Collisionnable* obj); float x, y, angle, scaleX, scaleY, dmax; int type; private: bool isdelete; }; #endif
d2315fc7afd448a2f6bc887a3dfee4917b889233
52d32fd2bed109869a928d072917f9bc6f6ebb9e
/src/nova/guest/redis/constants.h
823edf5cd9434f1da2225678cc5d40060bfb832c
[]
no_license
cp16net/sneaky-pete-1
b45650de7ee09aa5282b8fcadf4318dd75e6f0d9
40f778f966001e762a6d4bd7da972070c52cb6ea
refs/heads/master
2020-12-25T23:47:52.418739
2014-04-17T15:55:22
2014-04-17T15:55:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,205
h
#ifndef CONSTANTS_H #define CONSTANTS_H #include <string> namespace nova { namespace redis { //Redis responses. static const std::string STRING_RESPONSE = "+"; static const std::string STRING_DESCRIPTION = "String."; static const std::string ERROR_RESPONSE = "-"; static const std::string ERROR_DESCRIPTION = "Error."; static const std::string INTEGER_RESPONSE = ":"; static const std::string INTEGER_DESCRIPTION = "Integer."; static const std::string MULTIPART_RESPONSE = "*"; static const std::string MULTIPART_DESCRIPTION = "Multipart string response."; static const std::string CERROR_RESPONSE = "cerror"; static const std::string CERROR_DESCRIPTION = "Client error."; static const std::string UNSUPPORTED_RESPONSE = "unsupported"; static const std::string UNSUPPORTED_DESCRIPTION = "Unsupported response type."; static const std::string SERROR_RESPONSE = "serror"; static const std::string SERROR_DESCRIPTION = "Redis server error."; static const std::string STIMEOUT_RESPONSE = "stimeout"; static const std::string STIMEOUT_DESCRIPTION = "Redis server timeout."; static const std::string CTIMEOUT_RESPONSE = "ctimeout"; static const std::string CTIMEOUT_DESCRIPTION = "Redis client timed out."; static const std::string CCONNECTED_RESPONSE = "cconnected"; static const std::string CCONNECTED_DESCRIPTION = "Redis client connected."; static const std::string CCONNECTION_ERR_RESPONSE = "sconnection_err"; static const std::string CCONNECTION_ERR_DESCRIPTION = "Redis client unable " "to connect."; static const std::string CMESSAGE_SENT_RESPONSE = "cmessage_sent"; static const std::string CMESSAGE_SENT_DESCRIPTION = "Redis client" "sent message."; static const std::string CNOTHING_TO_DO_RESPONSE = "cnothing"; static const std::string CNOTHING_TO_DO_DESCRIPTION = "No command sent " "nothing to do."; //Client options. static const std::string DEFAULT_REDIS_CONFIG = "/etc/redis/redis.conf"; static const std::string REDIS_PORT = "6379"; static const std::string REDIS_AGENT_NAME = "trove-guestagent"; static const std::string SOCKET_NAME = "localhost"; static const int CRLF_LEN = 2; static const int SOCK_ERROR = -1; static const int MAX_RETRIES = 100; static const int FIRST_BYTE_READ = 1; static const int READ_LEN = 2048; static const std::string CRLF = "\r\n"; //This is bad but it is a value that is never used by redis. //So it means the item does not exist in the vector. static const int INT_NULL = -42; //Config keys. static const std::string DISABLE = "#"; static const std::string INCLUDE_FILE = "include"; static const std::string DAEMONIZE = "daemonize"; static const std::string PIDFILE = "pidfile"; static const std::string PORT = "port"; static const std::string TCP_BACKLOG = "tcp-backlog"; static const std::string BIND_ADDR = "bind"; static const std::string UNIX_SOCKET = "unixsocket"; static const std::string UNIX_SOCKET_PERMISSION = "unixsocketperm"; static const std::string TCP_KEEPALIVE = "tcp-keepalive"; static const std::string LOG_LEVEL = "loglevel"; static const std::string LOG_FILE = "logfile"; static const std::string SYSLOG = "syslog-enabled"; static const std::string SYSLOG_IDENT = "syslog-ident"; static const std::string SYSLOG_FACILITY = "syslog-facility"; static const std::string DATABASES = "databases"; static const std::string SAVE = "save"; static const std::string STOP_WRITES_ON_BGSAVE_ERROR = "stop-writes-on-bgsave" "-error"; static const std::string RDB_COMPRESSION = "rdbcompression"; static const std::string RDB_CHECKSUM = "rdbchecksum"; static const std::string DB_FILENAME = "dbfilename"; static const std::string DB_DIR = "dir"; static const std::string SLAVE_OF = "slaveof"; static const std::string MASTER_AUTH = "masterauth"; static const std::string SLAVE_SERVE_STALE_DATA = "slave-serve-stale-data"; static const std::string SLAVE_READ_ONLY = "slave-read-only"; static const std::string REPL_PING_SLAVE_PERIOD = "repl-ping-slave-period"; static const std::string REPL_TIMEOUT = "repl-timeout"; static const std::string REPL_DISABLE_TCP_NODELAY = "repl-disable-tcp-nodelay"; static const std::string REPL_BACKLOG_SIZE = "repl-backlog-size"; static const std::string REPL_BACKLOG_TTL = "repl-backlog-ttl"; static const std::string SLAVE_PRIORITY = "slave-priority"; static const std::string MIN_SLAVES_TO_WRITE = "min-slaves-to-write"; static const std::string MIN_SLAVES_MAX_LAG = "min-slaves-max-lag"; static const std::string REQUIRE_PASS = "requirepass"; static const std::string RENAME_COMMAND = "rename-command"; static const std::string MAX_CLIENTS = "maxclients"; static const std::string MAX_MEMORY = "maxmemory"; static const std::string MAX_MEMORY_POLICY = "maxmemory-policy"; static const std::string MAX_MEMORY_SAMPLES = "maxmemory-samples"; static const std::string APPEND_ONLY = "appendonly"; static const std::string APPEND_FILENAME = "appendfilename"; static const std::string APPEND_FSYNC = "appendfsync"; static const std::string NO_APPEND_FSYNC_ON_REWRITE = "no-appendfsync-on-" "rewrite"; static const std::string AUTO_AOF_REWRITE_PERCENTAGE = "auto-aof-rewrite-" "percentage"; static const std::string AUTO_AOF_REWRITE_MIN_SIZE = "auto-aof-rewrite-" "min-size"; static const std::string LUA_TIME_LIMIT = "lua-time-limit"; static const std::string SLOWLOG_LOG_SLOWER_THAN = "slowlog-log-slower-" "than"; static const std::string SLOWLOG_MAX_LEN = "slowlog-max-len"; static const std::string NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events"; static const std::string HASH_MAX_ZIP_LIST_ENTRIES = "hash-max-ziplist-" "entries"; static const std::string HASH_MAX_ZIP_LIST_VALUE = "hash-max-ziplist-" "value"; static const std::string LIST_MAX_ZIP_LIST_ENTRIES = "list-max-ziplist-" "entries"; static const std::string LIST_MAX_ZIP_LIST_VALUE = "list-max-ziplist-" "value"; static const std::string SET_MAX_INTSET_ENTRIES = "set-max-intset-entries"; static const std::string ZSET_MAX_ZIP_LIST_ENTRIES = "zset-max-ziplist-entries"; static const std::string ZSET_MAX_ZIP_LIST_VALUE = "zset-max-ziplist-value"; static const std::string ACTIVE_REHASHING = "activerehashing"; static const std::string CLIENT_OUTPUT_BUFFER_LIMIT = "client-output-" "buffer-limit"; static const std::string HZ = "hz"; static const std::string AOF_REWRITE_INCREMENTAL_FSYNC = "aof-rewrite-" "incremental-fsync"; //Config value types. static const std::string TYPE_STRING = "string"; static const std::string TYPE_INT = "int"; static const std::string TYPE_MEMORY = "memory"; static const std::string TYPE_BYTES = "bytes"; static const std::string TYPE_KILOBYTES = "kilobytes"; static const std::string TYPE_MEGABYTES = "megabytes"; static const std::string TYPE_GIGABYTES = "gigabytes"; static const std::string TYPE_BOOL = "bool"; static const std::string TYPE_TRUE = "yes"; static const std::string TYPE_FALSE = "no"; //Save keys. static const std::string SAVE_SECONDS = "seconds"; static const std::string SAVE_CHANGES = "changes"; //Loglevel. static const std::string LOG_LEVEL_DEBUG = "debug"; static const std::string LOG_LEVEL_VERBOSE = "verbose"; static const std::string LOG_LEVEL_NOTICE = "notice"; static const std::string LOG_LEVEL_WARNING = "warning"; //Slave of keys. static const std::string MASTER_IP = "master_ip"; static const std::string MASTER_PORT = "master_port"; //Rename command keys. static const std::string RENAMED_COMMAND = "renamed_command"; static const std::string NEW_COMMAND_NAME = "new_command_name"; //Max memory policy values. static const std::string VOLATILE_LRU = "volatile-lru"; static const std::string ALLKEYS_LRU = "allkeys-lru"; static const std::string VOLATILE_RANDOM = "volatile-random"; static const std::string ALLKEYS_RANDOM = "allkeys-random"; static const std::string VOLATILE_TTL = "volatile-ttl"; static const std::string NO_EVICTION = "noevection"; //Append sync values. static const std::string APPEND_FSYNC_ALWAYS = "always"; static const std::string APPEND_FSYNC_EVERYSEC = "everysec"; static const std::string APPEND_FSYNC_NO = "no"; //Client output buffer limit class values. static const std::string NORMAL_CLIENTS = "normal"; static const std::string SLAVE_CLIENTS = "slave"; static const std::string PUBSUB_CLIENTS = "pubsub"; //Client output buffer limit keys. static const std::string CLIENT_BUFFER_LIMIT_CLASS = "class"; static const std::string CLIENT_BUFFER_LIMIT_HARD_LIMIT = "hard_limit"; static const std::string CLIENT_BUFFER_LIMIT_SOFT_LIMIT = "soft_limit"; static const std::string CLIENT_BUFFER_LIMIT_SOFT_SECONDS = "soft_seconds"; //Memory units. static const std::string KILOBYTES = "kb"; static const std::string MEGABYTES = "mb"; static const std::string GIGABYTES = "gb"; //Redis key command names. static const std::string COMMAND_DEL = "DEL"; static const std::string COMMAND_DUMP = "DUMP"; static const std::string COMMAND_EXISTS = "EXISTS"; static const std::string COMMAND_EXPIRE = "EXPIRE"; static const std::string COMMAND_EXPIRE_AT = "EXPIREAT"; static const std::string COMMAND_KEYS = "KEYS"; static const std::string COMMAND_MIGRATE = "MIGRATE"; static const std::string COMMAND_MOVE = "MOVE"; static const std::string COMMAND_OBJECT = "OBJECT"; static const std::string COMMAND_PERSIST = "PERSIST"; static const std::string COMMAND_PEXIPRE = "PEXPIRE"; static const std::string COMMAND_PEXPIRE_AT = "PEXPIREAT"; static const std::string COMMAND_PTTL = "PTTL"; static const std::string COMMAND_RANDOMKEY = "RANDOMKEY"; static const std::string COMMAND_RENAME = "RENAME"; static const std::string COMMAND_RENAMENX = "RENAMENX"; static const std::string COMMAND_RESTORE = "RESTORE"; static const std::string COMMAND_SORT = "SORT"; static const std::string COMMAND_TTL = "TTL"; static const std::string COMMAND_TYPE = "TYPE"; static const std::string COMMAND_SCAN = "SCAN"; //Redis string command names. static const std::string COMMAND_APPEND = "APPEND"; static const std::string COMMAND_BITCOUNT = "BITCOUT"; static const std::string COMMAND_BITOP = "BITOP"; static const std::string COMMAND_DECR = "DECR"; static const std::string COMMAND_DECR_BY = "DECRBY"; static const std::string COMMAND_GET = "GET"; static const std::string COMMAND_GET_BIT = "GETGIT"; static const std::string COMMAND_GET_RANGE = "GETRANGE"; static const std::string COMMAND_GET_SET = "GETSET"; static const std::string COMMAND_INCR = "INCR"; static const std::string COMMAND_INCR_BY = "INCRBY"; static const std::string COMMAND_INCR_BY_FLOAT = "INCRBYFLOAT"; static const std::string COMMAND_MGET = "MGET"; static const std::string COMMAND_MSET = "MSET"; static const std::string COMMAND_MSETNX = "MSETNX"; static const std::string COMMAND_PSETEX = "PSETEX"; static const std::string COMMAND_SET = "SET"; static const std::string COMMAND_SET_BIT = "SETBIT"; static const std::string COMMAND_SETEX = "SETEX"; static const std::string COMMAND_SET_RANGE = "SETRANGE"; static const std::string COMMAND_STRLEN = "STRLEN"; //Redis hash command names. static const std::string COMMAND_HDEL = "HDEL"; static const std::string COMMAND_HEXISTS = "HEXISTS"; static const std::string COMMAND_HGET = "HGET"; static const std::string COMMAND_HGET_ALL = "HGETALL"; static const std::string COMMAND_HINCR_BY = "HINCRBY"; static const std::string COMMAND_HINCR_BY_FLOAT = "HINCRBYFLOAT"; static const std::string COMMAND_HKEYS = "HKEYS"; static const std::string COMMAND_HLEN = "HLEN"; static const std::string COMMAND_HMGET = "HMGET"; static const std::string COMMAND_HMSET = "HMSET"; static const std::string COMMAND_HSET = "HSET"; static const std::string COMMAND_HSETNX = "HSETNX"; static const std::string COMMAND_HVALS = "HVALS"; static const std::string COMMAND_HSCAN = "HSCAN"; //Redis list command names. static const std::string COMMAND_BLPOP = "BLPOP"; static const std::string COMMAND_BRPOP = "BRPOP"; static const std::string COMMAND_BRPOPLPUSH = "BRPOPLPUSH"; static const std::string COMMAND_LINDEX = "LINDEX"; static const std::string COMMAND_LINSTER = "LINSTER"; static const std::string COMMAND_LLEN = "LLEN"; static const std::string COMMAND_LPOP = "LPOP"; static const std::string COMMAND_LPUSH = "LPUSH"; static const std::string COMMAND_LPUSHX = "LPUSHX"; static const std::string COMMAND_LRANGE = "LRANGE"; static const std::string COMMAND_LREM = "LREM"; static const std::string COMMAND_LSET = "LSET"; static const std::string COMMAND_LTRIM = "LTRIM"; static const std::string COMMAND_RPOP = "RPOP"; static const std::string COMMAND_RPOPLPUSH = "RPOPLPUSH"; static const std::string COMMAND_RPUSH = "RPUSH"; static const std::string COMMAND_RPUSHX = "RPUSHX"; //Redis set command names. static const std::string COMMAND_SADD = "SADD"; static const std::string COMMAND_SCARD = "SCARD"; static const std::string COMMAND_SDIFF = "SDIFF"; static const std::string COMMAND_SDIFFSTORE = "SDIFFSTORE"; static const std::string COMMAND_SINTER = "SINTER"; static const std::string COMMAND_SINTERSORE = "SINTERSTORE"; static const std::string COMMAND_SISMEMEBER = "SISMEMBER"; static const std::string COMMAND_SMEMBERS = "SMEMBERS"; static const std::string COMMAND_SMOVE = "SMOVE"; static const std::string COMMAND_SPOP = "SPOP"; static const std::string COMMAND_SRANDMEMEBER = "SRANDMEMEBER"; static const std::string COMMAND_SREM = "SREM"; static const std::string COMMAND_SUNION = "SUNION"; static const std::string COMMAND_SUINIONSTORE = "SUNIONSTORE"; static const std::string COMMAND_SSCAN = "SSCAN"; //Redis sorted set command names. static const std::string COMMAND_ZADD = "ZADD"; static const std::string COMMAND_ZCARD = "ZCARD"; static const std::string COMMAND_ZCOUNT = "ZCOUNT"; static const std::string COMMAND_ZINCR_BY = "ZINCRBY"; static const std::string COMMAND_ZINTERSTORE = "ZINTERSTORE"; static const std::string COMMAND_ZRANGE = "ZRANGE"; static const std::string COMMAND_ZRANGEBYSCORE = "ZRANGEBYSCORE"; static const std::string COMMAND_ZRANK = "ZRANK"; static const std::string COMMAND_ZREM = "ZREM"; static const std::string COMMAND_ZREMRANGEBYRANK = "ZREMRANGEBYRANK"; static const std::string COMMAND_ZREMRANGEBYSCORE = "ZREMRANGEBYSCORE"; static const std::string COMMAND_ZREVRANK = "ZREVERANK"; static const std::string COMMAND_ZSCORE = "ZSCORE"; static const std::string COMMAND_ZUNIONSTORE = "ZUNIONSTORE"; static const std::string COMMAND_ZSCAN = "ZSCAN"; //Redis pub/sub command names. static const std::string COMMAND_PSUBSCRIBE = "PSUBSCRIBE"; static const std::string COMMAND_PUBSUB = "PUBSUB"; static const std::string COMMAND_PUBLISH = "PUBLISH"; static const std::string COMMAND_PUNSUBSCRIBE = "PUNSUBSCRIBE"; static const std::string COMMAND_SUBSCRIBE = "SUBSCRIBE"; static const std::string COMMAND_UNSUBSCRIBE = "UNSUBSCRIBE"; //Redis transaction command names. static const std::string COMMAND_DISCARD = "DISCARD"; static const std::string COMMAND_EXEC = "EXEC"; static const std::string COMMAND_MULTI = "MULTI"; static const std::string COMMAND_UNWATCH = "UNWATCH"; static const std::string COMMAND_WATCH = "WATCH"; //Redis scripting command namees. static const std::string COMMAND_EVAL = "EVAL"; static const std::string COMMAND_EVALSHA = "EVALSHA"; static const std::string COMMAND_SCRIPT_EXISTS = "SCRIPT EXISTS"; static const std::string COMMAND_SCRIPT_FLUSH = "SCRIPT FLUSH"; static const std::string COMMAND_SCRIPT_KILL = "SCRIPT KILL"; static const std::string COMMAND_SCRIPT_LOAD = "SCRIPT LOAD"; //Redis connection command names. static const std::string COMMAND_AUTH = "AUTH"; static const std::string COMMAND_ECHO = "ECHO"; static const std::string COMMAND_PING = "PING"; static const std::string COMMAND_QUIT = "QUIT"; static const std::string COMMAND_SELECT = "SELECT"; //Redis server command names. static const std::string COMMAND_BGREWRITEAOF = "BGREWRITEAOF"; static const std::string COMMAND_BGSAVE = "BGSAVE"; static const std::string COMMAND_CLIENT_KILL = "CLIENT KILL"; static const std::string COMMAND_CLIENT_LIST = "CLIENT LIST"; static const std::string COMMAND_CLIENT_GETNAME = "CLIENT GETNAME"; static const std::string COMMAND_CLIENT_SETNAME = "CLIENT SETNAME"; static const std::string COMMAND_CLIENT = "CLIENT"; static const std::string COMMAND_CONFIG_GET = "CONFIG GET"; static const std::string COMMAND_CONFIG_REWRITE = "CONFIG REWRITE"; static const std::string COMMAND_CONFIG_SET = "CONFIG SET"; static const std::string COMMAND_CONFIG_RESETSTAT = "CONFIG RESETSTAT"; static const std::string COMMAND_CONFIG = "CONFIG"; static const std::string COMMAND_DBSIZE = "DBSIZE"; static const std::string COMMAND_DEBUG_OBJECT = "DEBUG OBJECT"; static const std::string COMMAND_DEBUG_SEGFAULT = "DEBUG SEGFAULT"; static const std::string COMMAND_FLUSHALL = "FLUSHALL"; static const std::string COMMAND_FLUSHDB = "FLUSHDB"; static const std::string COMMAND_INFO = "INFO"; static const std::string COMMAND_LASTSAVE = "LASTSAVE"; static const std::string COMMAND_MONITOR = "MONITOR"; static const std::string COMMAND_SAVE = "SAVE"; static const std::string COMMAND_SHUTDOWN = "SHUTDOWN"; static const std::string COMMAND_SLAVEOF = "SLAVEOF"; static const std::string COMMAND_SLOWLOG = "SLOWLOG"; static const std::string COMMAND_SYNC = "SYNC"; static const std::string COMMAND_TIME = "TIME"; }}//end of nova::redis #endif /* CONSTANTS_H */
b3264ac96b2fe9e6a60a42c5f36321b844c35e41
40f9d141de64e2f0d89607a3cad6535d5af3c802
/src/helloworld/helloworld.cpp
552521ebdeff19e5a2ed477310162d9520882d26
[]
no_license
ejoebstl/cpp-cmake-example
a951efcfe7daa56f720f2e51a4f9fa323eb0c6a3
0ad09b3d184ecf3be80c20914b2a3ebbd74091d8
refs/heads/master
2020-03-22T05:36:40.744928
2018-07-03T12:12:11
2018-07-03T12:12:11
139,578,374
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#include<iostream> using namespace std; int main() { cout << "Hello c++ World!" << endl; return 0; }
b1d363cdbd4ecd3466c472e96eb4814b502d2958
f665cedcf56e09a0cf51aff97fc9856e2bd37e77
/QuestionAnswerService/QuestionAnswerService/FQAServer.cpp
1e21318ddee6e166a45359cd0351667d9e70f93e
[]
no_license
zhangqiaoli/robot
2e2f3fb0e38d08fa14a90e4341242f6a92e74f35
085b116d3cb0c5391a5175867315be0c7ebb5ebd
refs/heads/master
2021-01-10T01:45:46.041344
2015-11-16T01:35:46
2015-11-16T01:35:46
45,585,762
0
0
null
null
null
null
GB18030
C++
false
false
7,617
cpp
#include "stdafx.h" #include "FQAServer.h" #include <Poco/NamedMutex.h> #include <Poco/Util/Option.h> #include <Poco/Util/OptionSet.h> #include <Poco/Util/HelpFormatter.h> #include <SADatabase.h> #include "SALogChannel.h" #include "FQACommon.h" using namespace Poco; using namespace Poco::Util; Configure cfg; FQAService::FQAService(void) : _helpRequested(false) { } FQAService::~FQAService(void) { } // 定义选项 void FQAService::defineOptions(OptionSet& options) { ServerApplication::defineOptions(options); options.addOption( Option("help", "h", "display help information on command line arguments") .required(false) .repeatable(false) .callback(OptionCallback<FQAService>(this, &FQAService::handleHelp))); } // 处理帮助 void FQAService::handleHelp(const std::string& name, const std::string& value) { _helpRequested = true; displayHelp(); stopOptionsProcessing(); } // 显示帮助 void FQAService::displayHelp() { HelpFormatter helpFormatter(options()); helpFormatter.setCommand(commandName()); helpFormatter.setUsage("OPTIONS"); helpFormatter.setHeader("Robot Service application."); helpFormatter.format(std::cout); } // 初始化 void FQAService::initialize(Application& self) { if (!_helpRequested) { //loadConfiguration(); // load default configuration files, if present Path oPath; oPath.parseDirectory(SAAssistant::GetApplicationPath()); oPath = oPath.parent(); oPath.setFileName("faq.ini"); loadConfiguration(oPath.toString(Path::PATH_NATIVE)); // load default configuration files, if present ServerApplication::initialize(self); SALogChannel::GetInstance().EnableFileLog("$(ApplicationPath)../log/faq_$(Year4)$(Month2)$(Day2)_$(FileNumber2).log"); logger().information("FaqService starting..."); // 重复运行检查 NamedMutex nm("FaqService"); if (!nm.tryLock()) { throw ApplicationException("FaqService already running!"); } // 加载配置文件 if (!ReloadConfig()) { throw ApplicationException("Load Config Failed!"); } m_httpServer.m_Options.sListenAddress = F("%d", cfg.httpListenPort); m_httpServer.AddRouter("/question-answering/get_answer", boost::bind(&FQAService::OnReceiveHttpRequest, this, _1)); m_httpServer.Start(); } } int FQAService::OnReceiveHttpRequest(struct mg_connection* conn) { string sContent = ""; string sRemoteip = ""; if (conn) { if (conn->remote_ip) { sRemoteip = conn->remote_ip; } if (conn->content_len > 0) { char* content = (char *)malloc(conn->content_len + 1); memset(content, 0, conn->content_len + 1); strncpy(content, conn->content, conn->content_len); sContent = content; } else { SALOG.debug(format("OnReceiveHttpRequest start...remote=%s:%u,content is empty!", sRemoteip, conn->remote_port)); return 1; } } SALOG.debug(format("OnReceiveHttpRequest start...remote=%s:%u,RECV='%s'", sRemoteip, conn->remote_port, sContent)); bool ret = false; string sAnswer = ""; int nErrcode = 0; string sErrmsg = "ok"; if (!sContent.empty()) { rapidjson::Document oDocument; if (!oDocument.Parse<0>(sContent.c_str()).HasParseError() && oDocument.IsObject()) { if (oDocument.HasMember("source") && oDocument["source"].IsString()) { string sSource = oDocument["source"].GetString(); if (Poco::toLower(sSource) == "xfyun") { if (oDocument.HasMember("text") && oDocument["text"].IsObject()) { rapidjson::Value& text = oDocument["text"]; ret = xfyunSemanticProcess(text, sAnswer, nErrcode, sErrmsg); if (!ret) { nErrcode = 6; sErrmsg = "xfyunSemanticProcess failed!"; SALOG.debug(sErrmsg); } } else { nErrcode = 1; sErrmsg = "data format invalid,miss text node"; SALOG.debug(sErrmsg); } } } else { nErrcode = 1; sErrmsg = "data format invalid,miss source node"; SALOG.debug(sErrmsg); } } else { nErrcode = 2; sErrmsg = "invalid request data!"; SALOG.debug("invalid request data,not json format!"); } } rapidjson::Document response; response.SetObject(); rapidjson::Document::AllocatorType& allocator = response.GetAllocator(); response.AddMember("errcode", nErrcode, allocator); response.AddMember("errmsg", sErrmsg.c_str(), allocator); response.AddMember("answer", sAnswer.c_str(), allocator); string sResponse = JsonDocToString(response); m_httpServer.HTTP_SendResponse(conn, 200, "OK", sResponse); SALOG.debug(F("Send http response:%s", sResponse)); return 0; } bool FQAService::xfyunSemanticProcess(rapidjson::Value& text, string& answer, int& errcode, string& errmsg) { bool ret = false; if (text.HasMember("rc") && text["rc"].IsInt()) { int rc = text["rc"].GetInt(); if (rc == 0) { if (text.HasMember("service") && text["service"].IsString()) { string sReqid = text["service"].GetString(); bool result = GetAnswerByReqID(sReqid, answer); if (!result) { errcode = 5; errmsg = "GetAnswerByID failed!"; SALOG.debug(F("GetAnswerByID '%s' failed!", sReqid)); } else { ret = true; } } //if (text.HasMember("semantic") && text["semantic"].IsObject()) //{ // rapidjson::Value& semantic = text["semantic"]; // if (semantic.HasMember("slots") && semantic["slots"].IsObject()) // { // rapidjson::Value& slots = semantic["slots"]; // if (slots.HasMember("reqid") && slots["reqid"].IsString()) // { // string sReqid = slots["reqid"].GetString(); // bool result = GetAnswerByReqID(sReqid, answer); // if (!result) // { // errcode = 5; // errmsg = "GetAnswerByID failed!"; // SALOG.debug(F("GetAnswerByID '%s' failed!", sReqid)); // } // else // { // ret = true; // } // } // } //} } else { errcode = 4; errmsg = "xfyun Semantic parse failed!"; SALOG.debug(errmsg); } } else { errcode = 3; errmsg = "xfyun Semantic lack node rc,invalid data!"; SALOG.debug(errmsg); } return ret; } bool FQAService::GetAnswerByReqID(const string& sAnswerid, string& sAnswer) { SADBConnectorPtr db = SADBConnector::CreateConnector(); db->SetConnectString(cfg.databaseString); SASQLMaker sm(F("select answer.content from answer left join question on question.answerid =answer.id where question.id = '%s'", sAnswerid)); db->ExecuteSQL(sm); SADBRecordSet rs(db); if (rs.SelectSQL(sm)) { if (!rs.IsEmpty()) { rs.GetField("content", sAnswer); SALOG.debug(F("get answer:%s by id %s", sAnswer, sAnswerid)); return true; } } else { SALOG.error("GetAnswerByID, SelectSQL failed"); return false; } return false; } // 入口 int FQAService::main(const std::vector<std::string>& args) { if (!_helpRequested) { logger().information("FaqService Start Running..."); m_tmTimer.setStartInterval(10000); m_tmTimer.setPeriodicInterval(5000); m_tmTimer.start(TimerCallback<FQAService>(*this, &FQAService::OnTimer)); waitForTerminationRequest(); m_tmTimer.stop(); } return Application::EXIT_OK; } // 释放 void FQAService::uninitialize() { logger().information("FaqService Cleaning..."); ServerApplication::uninitialize(); } bool FQAService::ReloadConfig() { cfg.databaseString = config().getString("FAQ.Database", ""); cfg.logLevel = config().getString("FAQ.LogLevel", "debug"); cfg.httpListenPort = config().getInt("FAQ.HttpListenPort", 18030); SALOG.setLevel(cfg.logLevel); return true; } void FQAService::OnTimer(Timer& timer) { } FQAService& FQAService::instance() { return (FQAService&)Application::instance(); } POCO_SERVER_MAIN(FQAService)
69396c525c4a90cd8b2e16f4fe2f3fcedeea997b
2b50fd71f5a7bb0932c04688cdcf54a76ce101c8
/src/classes/gdaemon_tasks.h
ce4172fa5f77b1d61ff8a1819fd6c9cfe7385512
[ "MIT" ]
permissive
hixio-mh/daemon
0a545014c8af3d824c7eea9995ac0329735d1b6b
88671543524ea2c2bce444c5ed8996f98e4231da
refs/heads/master
2022-09-20T02:40:03.720484
2020-04-20T22:58:17
2020-04-20T22:58:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,824
h
#ifndef GDAEMON_GDAEMON_TASKS_H #define GDAEMON_GDAEMON_TASKS_H #include <queue> #include <unordered_set> #include <unordered_map> #include <memory> #include <boost/thread.hpp> #include "commands/game_server_cmd.h" #include "models/gdaemon_task.h" #define TASK_WAITING 1 #define TASK_WORKING 2 #define TASK_ERROR 3 #define TASK_SUCCESS 4 #define TASK_CANCELED 5 namespace GameAP { struct GdaemonTasksStats { unsigned int working_tasks_count; unsigned int waiting_tasks_count; }; class GdaemonTasks { public: static constexpr auto GAME_SERVER_START = "gsstart"; static constexpr auto GAME_SERVER_PAUSE = "gspause"; // NOT Implemented static constexpr auto GAME_SERVER_STOP = "gsstop"; static constexpr auto GAME_SERVER_KILL = "gskill"; // NOT Implemented static constexpr auto GAME_SERVER_RESTART = "gsrest"; static constexpr auto GAME_SERVER_INSTALL = "gsinst"; static constexpr auto GAME_SERVER_REINSTALL = "gsreinst"; // NOT Implemented static constexpr auto GAME_SERVER_UPDATE = "gsupd"; static constexpr auto GAME_SERVER_DELETE = "gsdel"; static constexpr auto GAME_SERVER_MOVE = "gsmove"; static constexpr auto GAME_SERVER_EXECUTE = "cmdexec"; static GdaemonTasks& getInstance() { static GdaemonTasks instance; return instance; } /** * Run next queue task */ void run_next(); /** * Return if queue empty * @return bool */ bool empty(); /** * Update tasks list from api */ void update(); /** * If GameAP Daemon has unexpectedly stopped * Get tasks with 'working' status and put them to queue */ void check_after_crash(); /** * Get scheduler stats */ GdaemonTasksStats stats(); private: /** * Main tasks queue */ std::queue<std::shared_ptr<GdaemonTask>> tasks; /** * Exists queue tasks */ std::unordered_set<unsigned int> exists_tasks; /** * Working tasks commands (starting, installation, ... servers) * first - task id * second - cmd ptr */ std::unordered_map<unsigned int, Cmd*> active_cmds; /** * CMD Child processes pids */ std::unordered_map<unsigned int, pid_t> cmd_processes; // TODO: Remove after replace to coroutines boost::thread_group cmds_threads; /** * Start new task */ void start(std::shared_ptr<GdaemonTask> &task); void before_cmd(std::shared_ptr<GdaemonTask> &task); void after_cmd(std::shared_ptr<GdaemonTask> &task); /** * Check tasks command. Update output */ void proceed(std::shared_ptr<GdaemonTask> &task); // API void api_update_status(std::shared_ptr<GdaemonTask> &task); void api_append_output(std::shared_ptr<GdaemonTask> &task, std::string &output); GdaemonTasks() { this->tasks = {}; this->exists_tasks = {}; this->active_cmds = {}; } GdaemonTasks( const GdaemonTasks&); GdaemonTasks& operator=( GdaemonTasks& ); }; } #endif //GDAEMON_GDAEMON_TASKS_H
c82f678cce0abbbec017b48d6d78114154ff4a51
3fa08a93a34d75ab8da1125fe8cc4c46dae52601
/src/CButtonBar.cpp
5449b36b9f24543bf7525634788539e198e72029
[]
no_license
Ashrak22/FTP-client
9e42dc49a996de059abdd5f7535ac977fc27de5a
f6d2e345183b110deeaea83d1cea1dc8c313b8c6
refs/heads/master
2016-09-01T10:08:03.123956
2015-11-19T17:05:06
2015-11-19T17:05:06
46,506,919
0
0
null
null
null
null
UTF-8
C++
false
false
2,220
cpp
/** * @file CButtonBar.cpp * @brief Implementation of CButtonBar Class * @author Jakub J Simon * */ #include "CButtonBar.h" /*! \brief The constructor sets the coordinates to last line of window. */ CButtonBar::CButtonBar() : CGUIItem(0, LINES-1, COLS, 1) { ///The constructor sets the coordinates fo the button bar, which are always all the same. It is the last Line of the window (the whole width). The it calls CButtonBar::redraw(). redraw(); } /*! \brief Draw the buttons. */ ///Redraw draws the buttons on the coordinates whch were previously set by constructor. Each button is roughly 1/6 of the width void CButtonBar::redraw() { wattron(mWindow, A_BOLD); mvwprintw(mWindow, 0, 0, " 1"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 2, "Help"); for(int i = 6; i < COLS/6; i++)mvwprintw(mWindow, 0, i, " "); wattroff(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, COLS/6, " 3"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 2+COLS/6, "ChangeWorkDir"); for(int i = COLS/6+16; i < COLS/3; i++)mvwprintw(mWindow, 0, i, " "); wattroff(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, COLS/6+15, " 5"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 17+COLS/6, "RecurDown"); for(int i = COLS/6+26; i < COLS/2; i++)mvwprintw(mWindow, 0, i, " "); wattroff(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, COLS/2, " 7"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, COLS/2+2, "Upload"); for(int i = COLS/2 + 8; i < 4*COLS/6; i++)mvwprintw(mWindow, 0, i, " "); wattroff(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 4*COLS/6, " 8"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 4*COLS/6+2, "MkDir"); for(int i = 4*COLS/6 + 7; i < 5*COLS/6; i++)mvwprintw(mWindow, 0, i, " "); wattroff(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 5*COLS/6, " 9"); wattron(mWindow, COLOR_PAIR(4)); mvwprintw(mWindow, 0, 5*COLS/6+2, "DelFile"); for(int i = 5*COLS/6 + 9; i <= COLS; i++)mvwprintw(mWindow, 0, i, " "); wrefresh(mWindow); } /*! \brief Empty destructor just to call the parent destructor. */ CButtonBar::~CButtonBar() { }
0ed6b709931201f93033373b3b8d50fc744fb51f
547a0e37998c836be10ee00f13b1cf201a381de5
/3.2小节——入门模拟->查找元素/ProblemD.cpp
1a2d7572dbc88a4effd05cedba5d7a96044a08b1
[]
no_license
hegongshan/algorithm-notes
7232c3b3868f1a6ca4603756adc92edb3facbf6d
59e1ab7146858e5a4b4b11c9b7459289e2a93f16
refs/heads/master
2020-04-29T11:41:02.881872
2019-08-06T15:35:39
2019-08-06T15:35:39
176,108,059
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
#include <cstdio> int main() { int n, m; while (scanf("%d", &n) != EOF) { int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } scanf("%d", &m); for (int i = 0; i < m; i++) { int x; scanf("%d", &x); bool flag = false; for (int j = 0; j < n; j++) { if (arr[j] == x) { printf("YES\n"); flag = true; break; } } if (!flag) { printf("NO\n"); } } } return 0; }
d76c4ac5d93dd6a6777305b6561339cf1c825517
bdf42290c1e3208c2b675bab0562054adbda63bd
/base/posix/unix_domain_socket_linux.cc
20a5944b4ee7d4ebe412ee3b34aa8b044a5f97b0
[ "BSD-3-Clause" ]
permissive
mockingbirdnest/chromium
245a60c0c99b8c2eb2b43c104d82981070ba459d
e5eff7e6629d0e80dcef392166651e863af2d2fb
refs/heads/master
2023-05-25T01:25:21.964034
2023-05-14T16:49:08
2023-05-14T16:49:08
372,263,533
0
0
BSD-3-Clause
2023-05-14T16:49:09
2021-05-30T16:28:29
C++
UTF-8
C++
false
false
8,254
cc
// Copyright (c) 2011 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 "base/posix/unix_domain_socket_linux.h" #include <errno.h> #include <sys/socket.h> #include <unistd.h> #include <vector> #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/memory/scoped_vector.h" #include "base/pickle.h" #include "base/posix/eintr_wrapper.h" #include "base/stl_util.h" #if !defined(__native_client_nonsfi__) #include <sys/uio.h> #endif const size_t UnixDomainSocket::kMaxFileDescriptors = 16; #if !defined(__native_client_nonsfi__) // Creates a connected pair of UNIX-domain SOCK_SEQPACKET sockets, and passes // ownership of the newly allocated file descriptors to |one| and |two|. // Returns true on success. static bool CreateSocketPair(base::ScopedFD* one, base::ScopedFD* two) { int raw_socks[2]; if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks) == -1) return false; one->reset(raw_socks[0]); two->reset(raw_socks[1]); return true; } // static bool UnixDomainSocket::EnableReceiveProcessId(int fd) { const int enable = 1; return setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable)) == 0; } #endif // !defined(__native_client_nonsfi__) // static bool UnixDomainSocket::SendMsg(int fd, const void* buf, size_t length, const std::vector<int>& fds) { struct msghdr msg = {}; struct iovec iov = { const_cast<void*>(buf), length }; msg.msg_iov = &iov; msg.msg_iovlen = 1; char* control_buffer = NULL; if (fds.size()) { const unsigned control_len = CMSG_SPACE(sizeof(int) * fds.size()); control_buffer = new char[control_len]; struct cmsghdr* cmsg; msg.msg_control = control_buffer; msg.msg_controllen = control_len; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fds.size()); memcpy(CMSG_DATA(cmsg), &fds[0], sizeof(int) * fds.size()); msg.msg_controllen = cmsg->cmsg_len; } // Avoid a SIGPIPE if the other end breaks the connection. // Due to a bug in the Linux kernel (net/unix/af_unix.c) MSG_NOSIGNAL isn't // regarded for SOCK_SEQPACKET in the AF_UNIX domain, but it is mandated by // POSIX. const int flags = MSG_NOSIGNAL; const ssize_t r = HANDLE_EINTR(sendmsg(fd, &msg, flags)); const bool ret = static_cast<ssize_t>(length) == r; delete[] control_buffer; return ret; } // static ssize_t UnixDomainSocket::RecvMsg(int fd, void* buf, size_t length, ScopedVector<base::ScopedFD>* fds) { return UnixDomainSocket::RecvMsgWithPid(fd, buf, length, fds, NULL); } // static ssize_t UnixDomainSocket::RecvMsgWithPid(int fd, void* buf, size_t length, ScopedVector<base::ScopedFD>* fds, base::ProcessId* pid) { return UnixDomainSocket::RecvMsgWithFlags(fd, buf, length, 0, fds, pid); } // static ssize_t UnixDomainSocket::RecvMsgWithFlags(int fd, void* buf, size_t length, int flags, ScopedVector<base::ScopedFD>* fds, base::ProcessId* out_pid) { fds->clear(); struct msghdr msg = {}; struct iovec iov = { buf, length }; msg.msg_iov = &iov; msg.msg_iovlen = 1; const size_t kControlBufferSize = CMSG_SPACE(sizeof(int) * kMaxFileDescriptors) #if !defined(__native_client_nonsfi__) // The PNaCl toolchain for Non-SFI binary build does not support ucred. + CMSG_SPACE(sizeof(struct ucred)) #endif ; char control_buffer[kControlBufferSize]; msg.msg_control = control_buffer; msg.msg_controllen = sizeof(control_buffer); const ssize_t r = HANDLE_EINTR(recvmsg(fd, &msg, flags)); if (r == -1) return -1; int* wire_fds = NULL; unsigned wire_fds_len = 0; base::ProcessId pid = -1; if (msg.msg_controllen > 0) { struct cmsghdr* cmsg; for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0); if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { DCHECK(payload_len % sizeof(int) == 0); DCHECK(wire_fds == NULL); wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg)); wire_fds_len = payload_len / sizeof(int); } #if !defined(__native_client_nonsfi__) // The PNaCl toolchain for Non-SFI binary build does not support // SCM_CREDENTIALS. if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) { DCHECK(payload_len == sizeof(struct ucred)); DCHECK(pid == -1); pid = reinterpret_cast<struct ucred*>(CMSG_DATA(cmsg))->pid; } #endif } } #if !defined(__native_client_nonsfi__) // The PNaCl toolchain for Non-SFI binary build does not support // MSG_TRUNC or MSG_CTRUNC. if (msg.msg_flags & MSG_TRUNC || msg.msg_flags & MSG_CTRUNC) { for (unsigned i = 0; i < wire_fds_len; ++i) close(wire_fds[i]); errno = EMSGSIZE; return -1; } #endif if (wire_fds) { for (unsigned i = 0; i < wire_fds_len; ++i) fds->push_back(new base::ScopedFD(wire_fds[i])); } if (out_pid) { // |pid| will legitimately be -1 if we read EOF, so only DCHECK if we // actually received a message. Unfortunately, Linux allows sending zero // length messages, which are indistinguishable from EOF, so this check // has false negatives. if (r > 0 || msg.msg_controllen > 0) DCHECK_GE(pid, 0); *out_pid = pid; } return r; } #if !defined(__native_client_nonsfi__) // static ssize_t UnixDomainSocket::SendRecvMsg(int fd, uint8_t* reply, unsigned max_reply_len, int* result_fd, const Pickle& request) { return UnixDomainSocket::SendRecvMsgWithFlags(fd, reply, max_reply_len, 0, /* recvmsg_flags */ result_fd, request); } // static ssize_t UnixDomainSocket::SendRecvMsgWithFlags(int fd, uint8_t* reply, unsigned max_reply_len, int recvmsg_flags, int* result_fd, const Pickle& request) { // This socketpair is only used for the IPC and is cleaned up before // returning. base::ScopedFD recv_sock, send_sock; if (!CreateSocketPair(&recv_sock, &send_sock)) return -1; { std::vector<int> send_fds; send_fds.push_back(send_sock.get()); if (!SendMsg(fd, request.data(), request.size(), send_fds)) return -1; } // Close the sending end of the socket right away so that if our peer closes // it before sending a response (e.g., from exiting), RecvMsgWithFlags() will // return EOF instead of hanging. send_sock.reset(); ScopedVector<base::ScopedFD> recv_fds; // When porting to OSX keep in mind it doesn't support MSG_NOSIGNAL, so the // sender might get a SIGPIPE. const ssize_t reply_len = RecvMsgWithFlags( recv_sock.get(), reply, max_reply_len, recvmsg_flags, &recv_fds, NULL); recv_sock.reset(); if (reply_len == -1) return -1; // If we received more file descriptors than caller expected, then we treat // that as an error. if (recv_fds.size() > (result_fd != NULL ? 1 : 0)) { NOTREACHED(); return -1; } if (result_fd) *result_fd = recv_fds.empty() ? -1 : recv_fds[0]->release(); return reply_len; } #endif // !defined(__native_client_nonsfi__)
bf3fddef101d0308ab10174a00612e7006a57fde
24e24e03dad406305e82b5900197f5624e0a3e20
/A/112A.cpp
6a4dc092a10d44706b5008711b1a462bee873f43
[]
no_license
Sohan021/ProblemSolve_CodeForces
9a7ec2b8cc671c478786afd6122d72b807c45d1d
c5a0870c6d79f11c11623526f2bb5f08cba0922f
refs/heads/main
2023-03-31T05:05:31.031347
2021-03-30T05:18:29
2021-03-30T05:18:29
352,877,044
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include<bits/stdc++.h> using namespace std; int main() { string s1, s2; cin>>s1>>s2; for(int i=0;i<s1.length();i++){ if(s1[i]<92){ s1[i]+=32; } if(s2[i]<92){ s2[i]+=32; } } if(s1>s2) cout<<1<<endl; else if(s1<s2) cout<<-1<<endl; else if(s1==s2) cout<<0<<endl; }
b400cd6219866dd4fea859d8766369ee1f10dc2b
e5694cdc45c5eb77f699bdccff936f341d0e87e2
/a/tz/ax/truegrid/evnthlpr.h
495b15daf0c816ffc1b4a5f52080637be9a0b99d
[]
no_license
arksoftgit/10d
2bee2f20d78dccf0b5401bb7129494499a3c547d
4940b9473beebfbc2f4d934fc013b86aa32f5887
refs/heads/master
2020-04-16T02:26:52.876019
2017-10-10T20:27:34
2017-10-10T20:27:34
49,138,607
0
3
null
2016-08-29T13:03:58
2016-01-06T14:02:53
C
UTF-8
C++
false
false
859
h
/********************************************************************************************/ // // File: trhlpr.h // Copyright: Ton Beller AG2000 // Autor: TMV // Datum: 5. September 2000 // description: helper classes for event handling // // // list of classes : // Name: description: // ------------------------------------------------------------------------------------ // CActiveXEvent holds single activex event with its name and its DISPID // // /* Change log most recent first order: */ /*********************************************************************************************/ #include <afx.h> class CActiveXEvent : public CObject { public: CActiveXEvent(){}; CActiveXEvent(CString strName, long lID); ~CActiveXEvent(){}; public: CString m_strName; long m_lID; };
240f8e4808bf2782cf857564869f3a709935020f
0ae93c468e035b54cac957f771cc924913cc8037
/BREC_1_2/Bbb/SdrSvr/AscpDisIf.h
4c262c1847177beb129516f386fdc17f546b04ae
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
kitspace-forks/BREC
87c5662f4d27c7755a2a5398d823b545b357ff57
f87c065da63cbc305be7e11d44f33677b1fa35a2
refs/heads/master
2021-05-31T19:08:28.416588
2016-05-28T21:38:44
2016-05-28T21:38:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,102
h
// // // This source code is available under the "Simplified BSD license". // // Copyright (c) 2013, J. Kleiner // 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. // // 3. Neither the name of the original author nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /// #ifndef __ASCP_DISIF_H__ #define __ASCP_DISIF_H__ #include "../Util/mcf.h" #include "../Util/net.h" class AscpDisIf : public McF { int mLog; int mThreadExit; int mIpPort; char *mIpStr; char *mRadioName; void SendResponse( UdpSvr *usv ); public: AscpDisIf(); void Main(); void RcvEvent( char *evtStr ); }; #endif
6daf378908f90cf778b91019aa54b5734ca93aab
0f0d07564b248595dff2b0ab8330c0dc2d50380b
/src/qt/coincontroldialog.cpp
1787c073ec6503558bdc6724c2915d03e3dcd3b7
[ "MIT" ]
permissive
BungeeStartup/Bungee
bea117905106c65d757ff056cb138f8f93a03d26
b91f65c0b59257552a1ffd1f487abdfe89bf8c19
refs/heads/master
2021-03-03T04:24:21.263474
2020-04-05T18:58:16
2020-04-05T18:58:16
245,931,390
0
1
null
null
null
null
UTF-8
C++
false
false
35,356
cpp
#include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "base58.h" #include "chain.h" #include "guiutil.h" #include "init.h" #include "optionsmodel.h" #include "walletmodel.h" #include "coincontrol.h" #include "wallet.h" #include <ctime> #include <QMessageBox> #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> using namespace std; QList<qint64> CoinControlDialog::payAmounts; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); CoinControlDialog::CoinControlDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // Toggle lock state connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 // ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190); ui->treeWidget->setColumnWidth(COLUMN_DATE, 60); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64_t in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64_t in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but dont show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); } CoinControlDialog::~CoinControlDialog() { delete ui; } void CoinControlDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(model, this); } } // helper function str_pad QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding) { while (s.length() < nPadLength) s = sPadding + s; return s; } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure clock_t begin = clock(); CoinControlDialog::updateLabels(model, this); clock_t end = clock(); double t = double(end - begin) / CLOCKS_PER_SEC; LogPrintf("CoinControlDialog::buttonSelectAllClicked(CoinControlDialog::updateLabels) - Time elapsed: %f \n", t); } // Toggle lock state void CoinControlDialog::buttonToggleLockClicked() { QTreeWidgetItem *item; // Works in list-mode only if(ui->radioListMode->isChecked()){ ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){ item = ui->treeWidget->topLevelItem(i); COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())){ model->unlockCoin(outpt); item->setDisabled(false); item->setIcon(COLUMN_CHECKBOX, QIcon()); } else{ model->lockCoin(outpt); item->setDisabled(true); item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); } updateLabelLocked(); } ui->treeWidget->setEnabled(true); CoinControlDialog::updateLabels(model, this); } else{ QMessageBox msgBox; msgBox.setObjectName("lockMessageBox"); //msgBox.setStyleSheet(GUIUtil::loadStyleSheet()); msgBox.setText(tr("Please switch to \"List mode\" to use this function.")); msgBox.exec(); } } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BungeeUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // copy label "Low output" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } else { logicalIndex = getMappedColumn(logicalIndex, false); if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // parent checkbox clicked by user void CoinControlDialog::parentViewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() != 64) { Qt::CheckState state = Qt::Checked; for (int i = 0; i < item->childCount(); i++) { if (item->child(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox for (int i = 0; i < item->childCount(); i++) { if (item->child(i)->checkState(COLUMN_CHECKBOX) != state){ item->child(i)->setCheckState(COLUMN_CHECKBOX, state); } } ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); } else if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) { CoinControlDialog::viewItemChanged(item, column); } } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else { coinControl->Select(outpt); } // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } // todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node // including all childs are partially selected. But the parent node should be fully selected // as well as the childs. Childs should never be partially selected in the first place. // Please remove this ugly fix, once the bug is solved upstream. #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // helper function, return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority) { if (dPriority > 576000ULL) // at least medium, this number is from AllowFree(), the other thresholds are kinda random { if (dPriority > 5760000000ULL) return tr("highest"); else if (dPriority > 576000000ULL) return tr("high"); else if (dPriority > 57600000ULL) return tr("medium-high"); else return tr("medium"); } else { if (dPriority > 5760ULL) return tr("low-medium"); else if (dPriority > 58ULL) return tr("low"); else return tr("lowest"); } } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount qint64 nPayAmount = 0; bool fLowOutput = false; bool fDust = false; CTransaction txDummy; const int listSize = CoinControlDialog::payAmounts.size(); clock_t begin = clock(); //for (int i = 0; i < listSize; ++i) foreach(const qint64 &amount, CoinControlDialog::payAmounts) { //qint64 amount = CoinControlDialog::payAmounts.at(i); nPayAmount += amount; if (amount > 0) { if (amount < CENT) fLowOutput = true; CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); } } QString sPriorityLabel = ""; CAmount nAmount = 0; int64_t nPayFee = 0; int64_t nAfterFee = 0; int64_t nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; std::vector<COutPoint> vCoinControl; std::vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput& out, vOutputs) { // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); // Bytes CTxDestination address; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get< CKeyID >(&address); if (keyid && model->getPubKey(*keyid, pubkey)){ nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here // Priority dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority); // Fee int64_t nFee = nTransactionFee * (1 + (int64_t)nBytes / 1000); // IX Fee if(coinControl->useInstantX) nFee = max(nFee, CENT); // Min Fee int64_t nMinFee = GetMinFee(txDummy, nBytes, AllowFree(dPriority), GMF_SEND); nPayFee = max(nFee, nMinFee); if (nPayAmount > 0) { nChange = nAmount - nPayFee - nPayAmount; // if sub-cent change is required, the fee must be raised to at least CTransaction::nMinTxFee if (nPayFee < MIN_TX_FEE && nChange > 0 && nChange < CENT) { if (nChange < MIN_TX_FEE) // change < 0.0001 => simply move all change to fees { nPayFee += nChange; nChange = 0; } else { nChange = nChange + nPayFee - MIN_TX_FEE; nPayFee = MIN_TX_FEE; } } // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < CENT) { CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0)); if (txout.IsDust(MIN_RELAY_TX_FEE)) { nPayFee += nChange; nChange = 0; } } if (nChange == 0) nBytes -= 34; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } // actually update labels int nDisplayUnit = BungeeUnits::XBNG; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); // enable/disable "low output" and "change" dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BungeeUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BungeeUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BungeeUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText((fLowOutput ? (fDust ? tr("DUST") : tr("yes")) : tr("no"))); // Low Output / Dust l8->setText(BungeeUnits::formatWithUnit(nDisplayUnit, nChange)); // Change // turn labels "red" l5->setStyleSheet((nBytes >= 10000) ? "color:red;" : ""); // Bytes >= 10000 l6->setStyleSheet((dPriority <= 576000) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); // Low Output = "yes" l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01 XBNG // tool tips l5->setToolTip(tr("This label turns red, if the transaction size is bigger than 10000 bytes.\n\n This means a fee of at least %1 per kb is required.\n\n Can vary +/- 1 Byte per input.").arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT))); l6->setToolTip(tr("Transactions with higher priority get more likely into a block.\n\nThis label turns red, if the priority is smaller than \"medium\".\n\n This means a fee of at least %1 per kb is required.").arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT))); l7->setToolTip(tr("This label turns red, if any recipient receives an amount smaller than %1.\n\n This means a fee of at least %2 is required. \n\n Amounts below 0.546 times the minimum relay fee are shown as DUST.").arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT))); l8->setToolTip(tr("This label turns red, if the change is smaller than %1.\n\n This means a fee of at least %2 is required.").arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BungeeUnits::formatWithUnit(nDisplayUnit, CENT))); dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); clock_t end = clock(); double t = double(end - begin) / CLOCKS_PER_SEC; LogPrintf("CoinControlDialog::updateLabels() - Time elapsed: %f \n", t); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; clock_t begin = clock(); bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } int64_t nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 148; // 180 if uncompressed public key nSum += out.tx->vout[out.i].nValue; nChildren++; QTreeWidgetItem *itemOutput; if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress); else itemOutput = new QTreeWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBungeeAddress(outputAddress).ToString()); // if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get< CKeyID >(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 180; } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BungeeUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " ")); // immature PoS reward if (out.tx->IsCoinStake() && out.tx->GetBlocksToMaturity() > 0 && out.tx->GetDepthInMainChain() > 0) { itemOutput->setBackground(COLUMN_CONFIRMATIONS, Qt::red); itemOutput->setDisabled(true); } // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " ")); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority)); itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " ")); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); } // set checkbox if (coinControl->IsSelected(txhash, out.i)) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BungeeUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " ")); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum)); itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " ")); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); clock_t end = clock(); double t = double(end - begin) / CLOCKS_PER_SEC; LogPrintf("CoinControlDialog::updateView - Time elapsed: %f \n", t); }
5e52ca1ba657c6b1bfd1d23d7bec5d48b72d0c06
9cd3188509c4e5845f47de0475eafc6de69cbd68
/comp sci 3/testest.cpp
067edd27ee5431eb6ebe658b89193b26bbfe9c5a
[ "Apache-2.0" ]
permissive
MattPhilpot/RandomHomework
9f52cc40a9922086ff8e0c8708229a956df3d6e3
efa61590689c0af862a52104bad89c35bc133a65
refs/heads/master
2021-11-08T06:07:20.423519
2021-11-02T02:55:26
2021-11-02T02:55:26
237,514,421
0
0
null
null
null
null
UTF-8
C++
false
false
270
cpp
/* * calculator_main.cpp * * * Created by Matthew Philpot on 1/28/10. * */ #include <iostream> #include "string" using namespace std; int main () { char * str1 = "hi "; char * str2 = "fren "; char * str3; str3 = *str1 + *str2; cout << str3; return 1; }
7a88888a984aedb34c1f07d77e4947fd347f175f
82a476e781cacf6b4501eb90f3ba67ab01e358f1
/ioprocess/xversion/ioprocess-1.cpp
7a37fa62aad94620c46028c541463bc4628bf327
[]
no_license
dennis-tmeinc/zeus6
5131017dd56ed3df3c5314d0006ea47d5e5eb82b
45f19c76b1322e16ac85432c2f3bdd75bd13c378
refs/heads/master
2020-04-10T07:26:11.962128
2020-03-20T20:46:44
2020-03-20T20:46:44
160,880,288
0
1
null
null
null
null
UTF-8
C++
false
false
31,999
cpp
#include <stdio.h> #include <sys/mman.h> #include <signal.h> #include <termios.h> #include <unistd.h> #include <sys/reboot.h> #include "../cfg.h" #include "../dvrsvr/eagle32/davinci_sdk.h" #include "../dvrsvr/genclass.h" #include "../dvrsvr/config.h" #include "diomap.h" // HARD DRIVE LED and STATUS #define HDLED (0x10) #define HDINSERTED (0x40) #define HDKEYLOCK (0x80) struct baud_table_t { speed_t baudv ; int baudrate ; } baud_table[7] = { { B2400, 2400}, { B4800, 4800}, { B9600, 9600}, { B19200, 19200}, { B38400, 38400}, { B57600, 57600}, { B115200, 115200} } ; struct dio_mmap * p_dio_mmap ; #define SERIAL_DELAY (500000) #define DEFSERIALBAUD (115200) char dvriomap[256] = "/var/dvr/dvriomap" ; char serial_dev[256] = "/dev/ttyS1" ; char * pidfile = "/var/dvr/ioprocess.pid" ; int serial_handle ; unsigned int mcu_poweroffdelaytimer ; // unsigned int outputmap ; // output pin map cache char dvrconfigfile[] = CFG_FILE ; int ledflashing=0; int watchdogenabled=0; int gpsvalid = 0 ; int app_mode = 0 ; // 0: quit!, 1: run, 2: shutdown delay 3: standby, 4: reboot (30s before hard reboot) unsigned int panelled=0 ; unsigned int devicepower=0xffff; void sig_handler(int signum) { if( signum == SIGUSR1 ) { ledflashing=1 ; } else if( signum == SIGUSR2 ) { if( p_dio_mmap ) { p_dio_mmap->outputmap=0; } ledflashing=0 ; } else { app_mode=0; } } void dio_lock() { int i; for( i=0; i<1000; i++ ) { if( p_dio_mmap->lock>0 ) { usleep(1); } else { break ; } } p_dio_mmap->lock=1; } void dio_unlock() { p_dio_mmap->lock=0; } // Check if data ready to read on serial port // return 0: no data // 1: yes int serial_dataready(int microsecondsdelay) { struct timeval timeout ; fd_set fds; if( serial_handle<=0 ) { return 0; } timeout.tv_sec = microsecondsdelay/1000000 ; timeout.tv_usec = microsecondsdelay%1000000 ; FD_ZERO(&fds); FD_SET(serial_handle, &fds); if (select(serial_handle + 1, &fds, NULL, NULL, &timeout) > 0) { return FD_ISSET(serial_handle, &fds); } else { return 0; } } int serial_read(void * buf, size_t bufsize) { if( serial_handle>0 ) { return read( serial_handle, buf, bufsize); } return 0; } int serial_write(void * buf, size_t bufsize) { if( serial_handle>0 ) { return write( serial_handle, buf, bufsize); } return 0; } #define MCU_INPUTNUM (6) #define MCU_OUTPUTNUM (4) unsigned int mcu_doutputmap ; // check data check sum // return 0: checksum correct int mcu_checksun( char * data ) { char ck; int i ; if( data[0]<5 || data[0]>40 ) { return -1 ; } ck=0; for( i=0; i<(int)data[0]; i++ ) { ck+=data[i] ; } return (int)ck; } // calculate check sum of data void mcu_calchecksun( char * data ) { char ck ; int i; if( data[0]<5 || data[0]>40 ) { // wrong data return ; } ck=0 ; for( i=0; i<(data[0]-1); i++ ) { ck-=data[i] ; } data[i] = ck ; } // send command to mcu // return 0 : failed // >0 : success int mcu_send( char * cmd ) { if( *cmd<5 || *cmd>40 ) { // wrong data return 0 ; } mcu_calchecksun( cmd ); return serial_write(cmd, (int)(*cmd)); } // receive one data package from mcu // return 0: failed // >0: bytes of data received int mcu_recv( char * recv, int size ) { int n; if( size<5 ) { // minimum packge size? return 0 ; } while( serial_dataready(SERIAL_DELAY) ) { if( serial_read(recv, 1) ) { n=(int) *recv ; if( n>=5 && n<=size ) { n=serial_read(recv+1, n-1) ; n++ ; if(n==recv[0] && recv[1]==0 && recv[2]==1 && mcu_checksun( recv ) == 0 ) { return n; } } } } return 0 ; } // receive dont cared data from mcu void mcu_recv_dontcare() { char rbuf[20] ; while( serial_dataready(SERIAL_DELAY) ) { serial_read(rbuf, 10); } } int mcu_bootupready() { static char cmd_bootupready[8]="\x07\x01\x00\x11\x02\x00\xcc" ; char responds[20] ; while( serial_dataready(100000) ) { serial_read(responds, 20); } cmd_bootupready[5]=(char)watchdogenabled; if(mcu_send(cmd_bootupready)) { if( mcu_recv( responds, 20 ) ) { if( responds[3]=='\x11' && responds[4]=='\x03' ) { p_dio_mmap->inputmap = responds[5] ; // get default input map panelled=0 ; devicepower=0xffff; return 1 ; } } } return 0 ; } int mcu_doutput() { static char cmd_doutput_on[8] ="\x07\x01\x00\x25\x02\x00\xcc" ; static char cmd_doutput_off[8]="\x07\x01\x00\x26\x02\x00\xcc" ; char responds[20] ; int resok; int x = mcu_doutputmap^(p_dio_mmap->outputmap) ; if( x==0 ) { return 0 ; } mcu_doutputmap=p_dio_mmap->outputmap ; resok=0; // set output channel cmd_doutput_off[5] = (char)( (~mcu_doutputmap)&x ) ; if( cmd_doutput_off[5] ) { // send output off command if(mcu_send(cmd_doutput_off)) { if( mcu_recv( responds, 20 ) ) { if( responds[3]=='\x26' && responds[4]=='\x3' ) { resok = 1 ; } } } } // set ouput on channel cmd_doutput_on[5] = (char)( mcu_doutputmap&x ) ; if( cmd_doutput_on[5] ) { // send output on command if(mcu_send(cmd_doutput_on)) { if( mcu_recv( responds, 20 ) ) { if( responds[3]=='\x25' && responds[4]=='\x3' ) { resok=1 ; } } } } return resok; } // check mcu input // parameter // usdelay - micro-seconds waiting // return // 1: got something, digital input or power off input? // 0: nothing int mcu_input(int usdelay) { int res = 0 ; int inum ; char ibuf[20] ; for(inum=0; inum<10; inum++ ) { if( serial_dataready(usdelay) ) { if( mcu_recv( ibuf, 20 )>0 ) { if( ibuf[3]=='\x1c' && ibuf[4]=='\x02' ) { // dinput event p_dio_mmap->inputmap = (int) (unsigned char) ibuf[5] ; static char rsp_dinput[7] = "\x06\x01\x00\x1c\x03\xcc" ; mcu_send(rsp_dinput); res = 1; } else if( ibuf[3]=='\x08' && ibuf[4]=='\x02' ) { // ignition off event static char rsp_poweroff[10] = "\x08\x01\x00\x08\x03\x00\x10\xcc" ; // rsp_poweroff[5] = ((p_dio_mmap->lockpower)>>8)&0xff ; // rsp_poweroff[6] = (p_dio_mmap->lockpower)&0xff ; mcu_send(rsp_poweroff); mcu_poweroffdelaytimer = ((unsigned)(ibuf[6]))*256+((unsigned)ibuf[7]) ; p_dio_mmap->poweroff = 1 ; // send power off message to DVR printf("Ignition off\n"); res = 1; } else if( ibuf[3]=='\x09' && ibuf[4]=='\x02' ) { // ignition on event static char rsp_poweron[10] = "\x07\x01\x00\x09\x03\x00\xcc" ; rsp_poweron[5]=(char)watchdogenabled; mcu_send( rsp_poweron ); p_dio_mmap->poweroff = 0 ; // send power on message to DVR printf("ignition on\n"); res = 1; } } } else { break; } } return res; } // get mcu digital input int mcu_dinput() { static char cmd_dinput[8]="\x06\x01\x00\x1d\x02\xcc" ; char responds[20] ; mcu_input(10000); if(mcu_send(cmd_dinput)) { if( mcu_recv( responds, 20 ) ) { if( responds[3]=='\x1d' && responds[4]=='\x03' ) { p_dio_mmap->inputmap =(int) (unsigned char) responds[5] ; // get digital input map return 1 ; } } } return 0 ; } // set more mcu power off delay // return remain delay time int mcu_poweroffdelay(int delay) { int delaytime = 0 ; static char cmd_poweroffdelaytime[10]="\x08\x01\x00\x08\x02\x00\x01\xcc" ; char responds[20] ; if( delay ) { cmd_poweroffdelaytime[6]=30 ; } else { cmd_poweroffdelaytime[6]=2 ; } if( mcu_send(cmd_poweroffdelaytime) ) { if( mcu_recv( responds, 20 ) ) { if( responds[3]=='\x08' && responds[4]=='\x03' ) { delaytime = ((unsigned)(responds[5]))*256+((unsigned)responds[6]) ; } } } return delaytime ; } void mcu_watchdogenable() { char responds[20] ; static char cmd_watchdogenable[10]="\x06\x01\x00\x1a\x02\xcc" ; if( mcu_send(cmd_watchdogenable) ) { // ignor the responds, if any. mcu_recv( responds, 20 ); } watchdogenabled = 1 ; } void mcu_watchdogdisable() { char responds[20] ; static char cmd_watchdogdisable[10]="\x06\x01\x00\x1b\x02\xcc" ; if( mcu_send(cmd_watchdogdisable) ) { // ignor the responds, if any. mcu_recv( responds, 20 ); } watchdogenabled = 0 ; } void mcu_watchdogkick() { char responds[20] ; static char cmd_kickwatchdog[10]="\x06\x01\x00\x18\x02\xcc" ; if( mcu_send(cmd_kickwatchdog) ) { // ignor the responds, if any. mcu_recv( responds, 20 ); } } void mcu_hdpoweron() { char responds[20] ; static char cmd_hdpoweron[10]="\x06\x01\x00\x28\x02\xcc" ; if( mcu_send(cmd_hdpoweron) ) { // ignor the responds, if any. mcu_recv( responds, 20 ); } } void mcu_hdpoweroff() { char responds[20] ; static char cmd_hdpoweroff[10]="\x06\x01\x00\x29\x02\xcc" ; if( mcu_send(cmd_hdpoweroff) ) { // ignor the responds, if any. mcu_recv( responds, 20 ); } } // return time_t: success // 0: failed time_t mcu_r_rtc() { struct tm t ; static char cmd_readrtc[8] = "\x06\x01\x00\x06\x02\xf1" ; char responds[20] ; if( mcu_send( cmd_readrtc ) ) { if( mcu_recv( responds, 20 ) ) { if( responds[3]==6 && responds[4]==3 ) { t.tm_year = responds[11]/16*10 + responds[11]%16 + 100; t.tm_mon = responds[10]/16*10 + responds[10]%16 - 1; t.tm_mday = responds[ 9]/16*10 + responds[ 9]%16 ; t.tm_hour = responds[ 7]/16*10 + responds[ 7]%16 ; t.tm_min = responds[ 6]/16*10 + responds[ 6]%16 ; t.tm_sec = responds[ 5]/16*10 + responds[ 5]%16 ; t.tm_isdst = -1 ; return timegm( & t ) ; } } } return (time_t)0; } void mcu_readrtc() { static char cmd_readrtc[8] = "\x06\x01\x00\x06\x02\xf1" ; char responds[20] ; if( mcu_send( cmd_readrtc ) ) { if( mcu_recv( responds, 20 ) ) { if( responds[3]==6 && responds[4]==3 ) { p_dio_mmap->rtc_year = 2000+responds[11]/16*10 + responds[11]%16 ; p_dio_mmap->rtc_month = responds[10]/16*10 + responds[10]%16 ; p_dio_mmap->rtc_day = responds[ 9]/16*10 + responds[ 9]%16 ; p_dio_mmap->rtc_hour = responds[ 7]/16*10 + responds[ 7]%16 ; p_dio_mmap->rtc_minute= responds[ 6]/16*10 + responds[ 6]%16 ; p_dio_mmap->rtc_second= responds[ 5]/16*10 + responds[ 5]%16 ; p_dio_mmap->rtc_millisecond = 0 ; p_dio_mmap->rtc_cmd = 0 ; // cmd finish return ; } } } p_dio_mmap->rtc_cmd = -1 ; // cmd error. } // 3 LEDs On Panel // parameters: // led: 0= USB flash LED, 1= Error LED, 2 = Video Lost LED // flash: 0=off, 1=flash void mcu_led(int led, int flash) { static char cmd_ledctrl[10] = "\x08\x01\x00\x2f\x02\x00\x00\xcc" ; cmd_ledctrl[5]=(char)led ; cmd_ledctrl[6]=(char)(flash!=0) ; if( mcu_send( cmd_ledctrl ) ) { mcu_recv_dontcare(); // don't care } } // Device Power // parameters: // device: 0= GPS, 1= Slave Eagle boards, 2=Network switch // poweron: 0=poweroff, 1=poweron void mcu_devicepower(int device, int poweron ) { static char cmd_devicepower[10] = "\x08\x01\x00\x2e\x02\x00\x00\xcc" ; cmd_devicepower[5]=(char)device ; cmd_devicepower[6]=(char)(poweron!=0) ; if( mcu_send( cmd_devicepower ) ) { mcu_recv_dontcare(); // don't care } } void mcu_reset() { static char cmd_reset[8]="\x06\x01\x00\x00\x02\xcc" ; if( mcu_send( cmd_reset ) ) { mcu_recv_dontcare(); // don't care } } // update mcu firmware // return 1: success, 0: failed int mcu_update_firmware( char * firmwarebuf, int size ) { int res = 0 ; int ts, s ; char responds[20] ; static char cmd_updatefirmware[8] = "\x06\x01\x00\x01\x02\xcc" ; // reset mcu mcu_reset(); // send update command if( mcu_send( cmd_updatefirmware ) ) { mcu_recv_dontcare(); // don't care } // send firmware ts=0 ; while( ts<size ) { s = serial_write ( &firmwarebuf[ts], size-ts ) ; if( s<0 ) { break; // error } ts+=s ; } // wait a bit if( serial_dataready(5000000) ) { if( mcu_recv( responds, 20 ) ) { if( responds[3]==0x03 && responds[4]==0x02 ) { res=1 ; } } } return res ; } static char bcd(int v) { return (char)(((v/10)%10)*0x10 + v%10) ; } // return 1: success // 0: failed int mcu_w_rtc(time_t tt) { char cmd_setrtc[16] ; char responds[20] ; struct tm t ; gmtime_r( &tt, &t); cmd_setrtc[0] = 0x0d ; cmd_setrtc[1] = 1 ; cmd_setrtc[2] = 0 ; cmd_setrtc[3] = 7 ; cmd_setrtc[4] = 2 ; cmd_setrtc[5] = bcd( t.tm_sec ) ; cmd_setrtc[6] = bcd( t.tm_min ) ; cmd_setrtc[7] = bcd( t.tm_hour ); cmd_setrtc[8] = 0 ; // day of week ? cmd_setrtc[9] = bcd( t.tm_mday ); cmd_setrtc[10] = bcd( t.tm_mon + 1 ); cmd_setrtc[11] = bcd( t.tm_year + 1900 - 2000 ) ; if( mcu_send(cmd_setrtc) ) { if( mcu_recv(responds, 20 ) ) { if( responds[3]==7 && responds[4]==3 ) { return 1; } } } return 0 ; } void mcu_setrtc() { char cmd_setrtc[16] ; char responds[20] ; cmd_setrtc[0] = 0x0d ; cmd_setrtc[1] = 1 ; cmd_setrtc[2] = 0 ; cmd_setrtc[3] = 7 ; cmd_setrtc[4] = 2 ; cmd_setrtc[5] = bcd( p_dio_mmap->rtc_second ) ; cmd_setrtc[6] = bcd( p_dio_mmap->rtc_minute ); cmd_setrtc[7] = bcd( p_dio_mmap->rtc_hour ); cmd_setrtc[8] = 0 ; // day of week ? cmd_setrtc[9] = bcd( p_dio_mmap->rtc_day ); cmd_setrtc[10] = bcd( p_dio_mmap->rtc_month) ; cmd_setrtc[11] = bcd( p_dio_mmap->rtc_year) ; if( mcu_send(cmd_setrtc) ) { if( mcu_recv(responds, 20 ) ) { if( responds[3]==7 && responds[4]==3 ) { p_dio_mmap->rtc_cmd = 0 ; // cmd finish return ; } } } p_dio_mmap->rtc_cmd = -1 ; // cmd error. } // sync system time to rtc void mcu_syncrtc() { time_t t ; struct timeval current_time; gettimeofday(&current_time, NULL); t = (time_t) current_time.tv_sec ; if( mcu_w_rtc(t) ) { p_dio_mmap->rtc_cmd = 0 ; // cmd finish } else { p_dio_mmap->rtc_cmd = -1 ; // cmd error } } void mcu_rtctosys() { struct timeval tv ; time_t rtc ; rtc=mcu_r_rtc(); if( rtc!=(time_t)0 ) { tv.tv_sec=rtc ; tv.tv_usec=0; settimeofday(&tv, NULL); } } void mcu_adjtime() { struct timeval tv ; time_t rtc ; rtc=mcu_r_rtc(); if( rtc!=(time_t)0 ) { gettimeofday(&tv, NULL); if( rtc!=tv.tv_sec ) { tv.tv_sec =(time_t)((int)rtc - (int)tv.tv_sec ) ; tv.tv_usec = 0 ; adjtime( &tv, NULL ); } } } void time_syncgps () { struct timeval tv ; int diff ; time_t gpstime ; dio_lock(); if( p_dio_mmap->gps_valid ) { gettimeofday(&tv, NULL); gpstime = (time_t) p_dio_mmap->gps_gpstime ; if( gpstime!=tv.tv_sec ) { diff = (int)gpstime - (int)tv.tv_sec ; if( diff>2 || diff<-2 ) { tv.tv_sec=gpstime ; tv.tv_usec= (int)((p_dio_mmap->gps_gpstime - gpstime)*1000.0); settimeofday( &tv, NULL ); mcu_w_rtc(gpstime) ; } else { tv.tv_sec =(time_t)diff ; tv.tv_usec = 0 ; adjtime( &tv, NULL ); } } } dio_unlock(); } void time_syncmcu() { int diff ; struct timeval tv ; time_t rtc ; rtc=mcu_r_rtc(); if( rtc!=(time_t)0 ) { gettimeofday(&tv, NULL); if( rtc!=tv.tv_sec ) { diff = (int)rtc - (int)tv.tv_sec ; if( diff>2 || diff<-2 ) { tv.tv_sec=rtc ; tv.tv_usec=0; settimeofday( &tv, NULL ); } else { tv.tv_sec =(time_t)diff ; tv.tv_usec = 0 ; adjtime( &tv, NULL ); } } } } void dvrsvr_down() { pid_t dvrpid = p_dio_mmap->dvrpid ; if( dvrpid > 0 ) { kill( dvrpid, SIGUSR1 ) ; // suspend DVRSVR while( p_dio_mmap->dvrpid ) { p_dio_mmap->outputmap ^= HDLED ; mcu_input(200000); mcu_doutput(); } sync(); } } void dvrsvr_up() { } int g_syncrtc=0 ; // return // 0 : failed // 1 : success int appinit() { FILE * pidf ; int fd ; int i; int port=0; char * p ; config dvrconfig(dvrconfigfile); string v ; v = dvrconfig.getvalue( "system", "iomapfile"); char * iomapfile = v.getstring(); if( iomapfile && strlen(iomapfile)>0 ) { strncpy( dvriomap, iomapfile, sizeof(dvriomap)); } fd = open(dvriomap, O_RDWR | O_CREAT, S_IRWXU); if( fd<=0 ) { printf("Can't create io map file!\n"); return 0 ; } ftruncate(fd, sizeof(struct dio_mmap)); p=(char *)mmap( NULL, sizeof(struct dio_mmap), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 ); close( fd ); // fd no more needed if( p==(char *)-1 || p==NULL ) { printf( "IO memory map failed!"); return 0; } p_dio_mmap = (struct dio_mmap *)p ; if( p_dio_mmap->usage <=0 ) { memset( p_dio_mmap, 0, sizeof( struct dio_mmap ) ); } p_dio_mmap->usage++; // add one usage // initialize shared memory p_dio_mmap->inputnum = MCU_INPUTNUM ; p_dio_mmap->outputnum = MCU_OUTPUTNUM ; p_dio_mmap->panel_led = 0; p_dio_mmap->devicepower = 0xffff; // assume all device is power on p_dio_mmap->iopid = getpid () ; // io process pid // check if sync rtc wanted g_syncrtc = dvrconfig.getvalueint("io", "syncrtc"); // initilize serial port v = dvrconfig.getvalue( "io", "serialport"); if( v.length()>0 ) { p = v.getstring() ; } else { p = serial_dev ; } if( strcmp( p, "/dev/ttyS1")==0 ) { port=1 ; } serial_handle = open( p, O_RDWR | O_NOCTTY | O_NDELAY ); if( serial_handle > 0 ) { int baud ; baud = dvrconfig.getvalueint("io", "serialbaudrate"); if( baud<2400 || baud>115200 ) { baud=DEFSERIALBAUD ; } fcntl(serial_handle, F_SETFL, 0); if( port==1 ) { // port 1 // Use Hikvision API to setup serial port (RS485) InitRS485(serial_handle, baud, DATAB8, STOPB1, NOPARITY, NOCTRL); } else { struct termios tios ; speed_t baud_t ; tcgetattr(serial_handle, &tios); // set serial port attributes tios.c_cflag = CS8|CLOCAL|CREAD; tios.c_iflag = IGNPAR; tios.c_oflag = 0; tios.c_lflag = 0; // ICANON; tios.c_cc[VMIN]=0; // minimum char 0 tios.c_cc[VTIME]=2; // 0.2 sec time out baud_t = B115200 ; for( i=0; i<7; i++ ) { if( baud == baud_table[i].baudrate ) { baud_t = baud_table[i].baudv ; break; } } cfsetispeed(&tios, baud_t); cfsetospeed(&tios, baud_t); tcflush(serial_handle, TCIFLUSH); tcsetattr(serial_handle, TCSANOW, &tios); } } else { // even no serail port, we still let process run printf("Serial port failed!\n"); } pidf = fopen( pidfile, "w" ); if( pidf ) { fprintf(pidf, "%d", (int)getpid() ); fclose(pidf); } return 1; } // app finish, clean up void appfinish() { int lastuser ; // close serial port if( serial_handle>0 ) { close( serial_handle ); serial_handle=0; } p_dio_mmap->iopid = 0 ; p_dio_mmap->usage-- ; if( p_dio_mmap->usage <= 0 ) { lastuser=1 ; } else { lastuser=0; } // clean up shared memory munmap( p_dio_mmap, sizeof( struct dio_mmap ) ); if( lastuser ) { unlink( dvriomap ); // remove map file. } // delete pid file unlink( pidfile ); } int main() { int i; unsigned int serialno=0; int oldhdlock = 0 ; // HD lock status, default 0 : open int hdlock ; // HD lock status int noinputwatchdog = 0 ; // noinput watchdog if( appinit()==0 ) { return 1; } watchdogenabled = 0 ; // watchdogenabled = 1 ; // initialize mcu (power processor) if( mcu_bootupready () ) { printf("MCU UP!\n"); } else { printf("MCU failed!\n"); } // initialize output mcu_doutputmap=~(p_dio_mmap->outputmap) ; // // initialize power // setup signal handler signal(SIGQUIT, sig_handler); signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGUSR1, sig_handler); signal(SIGUSR2, sig_handler); printf( "DVR IO process started!\n"); if( g_syncrtc ) { mcu_rtctosys(); } // get default digital input mcu_dinput(); if( watchdogenabled ) { mcu_watchdogenable(); } app_mode = 1 ; while( app_mode ) { // do input pin polling // if( mcu_input(50000) == 0 ) { // with 0.05 second delay. // no inputs noinputwatchdog++ ; if( noinputwatchdog>100000 ) { // ~~ 1.3 hour mcu_bootupready () ; // restart mcu ??? noinputwatchdog=0 ; } } else { noinputwatchdog=0 ; } // do ignition pin polling // ... did in mcu_input() /* Sorry , I have no control over here &-< if( p_dio_mmap->poweroff && p_dio_mmap->lockpower ) { // toggling lock power pin. if( serialno%149==0 ) { // every 3 seconds printf("Powerdelay timer = %d ,", mcu_poweroffdelaytimer ); if( mcu_poweroffdelaytimer<25 ) { mcu_poweroffdelay(15); printf("call powerdelay(15), timer = %d\n", mcu_poweroffdelaytimer ); } else { mcu_poweroffdelay(1); printf("call powerdelay(1), timer = %d\n", mcu_poweroffdelaytimer ); } } } */ // rtc command check if( p_dio_mmap->rtc_cmd != 0 ) { if( p_dio_mmap->rtc_cmd == 1 ) { mcu_readrtc(); } else if( p_dio_mmap->rtc_cmd == 2 ) { mcu_setrtc(); } else if( p_dio_mmap->rtc_cmd == 3 ) { mcu_syncrtc(); } else { p_dio_mmap->rtc_cmd=-1; // command error, (unknown cmd) } } // do digital output if( p_dio_mmap->outputmap!=mcu_doutputmap ) { // output map changed. // do real output pin here mcu_doutput(); } if( serialno%21==0 ) { // every one seconds // do power management mode switching if( app_mode==1 ) { // running mode p_dio_mmap->devicepower = 0xffff ; if( p_dio_mmap->poweroff && p_dio_mmap->lockpower==0 ) { // ignition off detected shutdowndelay_start ; app_mode=2 ; } else { } } else if( app_mode==2 ) { // shutdown delay if( p_dio_mmap->poweroff==0 ) { app_mode=1 ; // back to normal } else { mcu_poweroffdelay (); if( delay time out ? ) { // suspend dvrsvr_down p_dio_mmap->devicepower=0 ; // turn off all devices poweroff app_mode=3 ; } } } else if( app_mode==3 ) { // standby // resume dvrsvr ... if( p_dio_mmap->poweroff==0 ) { p_dio_mmap->devicepower=0xffff ; // turn all devices power app_mode=1 ; // back to normal } else { mcu_poweroffdelay (); if( standby time out ? ) { app_mode=4 ; } } } else if( app_mode==4 ) { // reboot } else { // other? must be error app_mode=1 ; } if( ledflashing ) { p_dio_mmap->outputmap ^= 0xff ; } // kick watchdog if( p_dio_mmap->dvrpid == 0 ) { mcu_watchdogkick(); } else { // DVRSVR running? if( (++(p_dio_mmap->dvrwatchdog)) < 30 ) { // 10 seconds dvr watchdog timer mcu_watchdogkick(); } else { // halt system ? or reboot ? sync(); // reboot(RB_AUTOBOOT); printf("IOPROCESS: DVR server halt!\n"); p_dio_mmap->dvrwatchdog=0 ; // break; } } // check HD plug-in state hdlock = (p_dio_mmap->inputmap & (HDINSERTED|HDKEYLOCK) )==0 ; // HD plugged in and locked p_dio_mmap->hdkey=hdlock ; if( hdlock != oldhdlock ) { oldhdlock = hdlock ; if( hdlock ) { // turn on HD power mcu_hdpoweron() ; // turn on HD led p_dio_mmap->outputmap |= HDLED ; } else { // suspend DVRSVR process pid_t dvrpid = p_dio_mmap->dvrpid ; if( dvrpid > 0 ) { kill(dvrpid, SIGUSR1); // request dvrsvr to turn down for( i=0; i<80; i++ ) { if( p_dio_mmap->dvrpid <= 0 ) break; mcu_input(200000); p_dio_mmap->outputmap ^= HDLED ; mcu_doutput(); } if( i>78 ) { printf("dvrsvr may dead!\n"); } } // umount disks system("/davinci/dvr/umountdisks") ; // flash HD led for few seconds for( i=0; i<6; i++ ) { mcu_input(200000); p_dio_mmap->outputmap ^= HDLED ; mcu_doutput(); } // turn off HD power mcu_input(20000); mcu_hdpoweroff(); // flash HD led for few seconds for( i=0; i<6; i++ ) { p_dio_mmap->outputmap ^= HDLED ; mcu_input(200000); mcu_doutput(); } if( dvrpid > 0 ) { kill(dvrpid, SIGUSR2); // resume dvrsvr // flash HD led for few more seconds, wait dvrsvr up for( i=0; i<30; i++ ) { p_dio_mmap->outputmap ^= HDLED ; mcu_input(200000); mcu_doutput(); if( p_dio_mmap->dvrpid > 0 ) { break; } } } // turn off HD LED p_dio_mmap->outputmap &= ~ HDLED ; mcu_input(20000); } } } // update panel LEDs if( panelled != p_dio_mmap->panel_led ) { for( i=0; i<16; i++ ) { if( (panelled ^ p_dio_mmap->panel_led) & (1<<i) ) { mcu_led(i, p_dio_mmap->panel_led & (1<<i) ); } } panelled = p_dio_mmap->panel_led ; } // update device power if( devicepower != p_dio_mmap->devicepower ) { for( i=0; i<16; i++ ) { if( (devicepower ^ p_dio_mmap->devicepower) & (1<<i) ) { mcu_devicepower(i, p_dio_mmap->devicepower & (1<<i) ); } } devicepower = p_dio_mmap->devicepower ; } if( gpsvalid != p_dio_mmap->gps_valid ) { gpsvalid = p_dio_mmap->gps_valid ; if( gpsvalid ) { time_syncgps () ; } } // adjust system time with RTC if( g_syncrtc && serialno%100000==0 ) { // call adjust time about every one hour if( gpsvalid ) { time_syncgps(); } else { time_syncmcu(); } } serialno++; } if( watchdogenabled ) { mcu_watchdogdisable(); } appfinish(); printf( "DVR IO process ended!\n"); return 0; }
f54b2b6dd22da05c0744a1353f9fd71560230aa6
395d1860e82bc75ccc04b91c4b9a8fa46276d9bb
/Source/Common/Compat/Deprecated/Compat/hkHavokAllClassUpdates.h
d66f2171a15d5fb0e89f1e9178e694b9db14a546
[]
no_license
Hakhyun-Kim/projectanarchy
28ba7370050000a12e4305faa11d5deb77c330a1
ccea719afcb03967a68a169730b59e8a8a6c45f8
refs/heads/master
2021-06-03T04:41:22.814866
2013-11-07T07:21:03
2013-11-07T07:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,786
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COMPAT_HAVOK_ALL_CLASS_UPDATES_H #define HK_COMPAT_HAVOK_ALL_CLASS_UPDATES_H #include <Common/Compat/Deprecated/Version/hkVersionRegistry.h> #include <Common/Compat/hkHavokVersions.h> #define HK_SERIALIZE_MIN_COMPATIBLE_VERSION_INTERNAL_VALUE HK_HAVOK_VERSION_300 #define HK_CLASS_UPDATE_INFO(FROM,TO) \ namespace hkCompat_hk##FROM##_hk##TO \ { \ extern hkVersionRegistry::UpdateDescription hkVersionUpdateDescription; \ } #include <Common/Compat/Deprecated/Compat/hkCompatVersions.h> #undef HK_CLASS_UPDATE_INFO #undef HK_SERIALIZE_MIN_COMPATIBLE_VERSION_INTERNAL_VALUE #endif // HK_COMPAT_HAVOK_ALL_CLASS_UPDATES_H /* * Havok SDK - Base file, BUILD(#20131019) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from [email protected]. * */
cc369b9f5b55a7a324a03badd0dc2001125d1b5d
81bfc13080c1cd85e987f27eeaf77236fb41e03e
/Source/ProvingGrounds/ProvingGroundsProjectile.cpp
ba0fc12cc9f40cee4315e3620bda6dbe3f6a75e6
[]
no_license
Yurimeitzen0/ProvingGrounds
39a2183a5f1f0f2db8f382a70855576a325b2232
74b5d88aa4f1f6d4b26f696731ea49c23cfbc000
refs/heads/master
2020-04-23T04:35:40.924637
2019-03-26T01:16:20
2019-03-26T01:16:20
170,912,441
0
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "ProvingGroundsProjectile.h" #include "GameFramework/ProjectileMovementComponent.h" #include "Components/SphereComponent.h" AProvingGroundsProjectile::AProvingGroundsProjectile() { // Use a sphere as a simple collision representation CollisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp")); CollisionComp->InitSphereRadius(5.0f); CollisionComp->BodyInstance.SetCollisionProfileName("Projectile"); CollisionComp->OnComponentHit.AddDynamic(this, &AProvingGroundsProjectile::OnHit); // set up a notification for when this component hits something blocking // Players can't walk on it CollisionComp->SetWalkableSlopeOverride(FWalkableSlopeOverride(WalkableSlope_Unwalkable, 0.f)); CollisionComp->CanCharacterStepUpOn = ECB_No; // Set as root component RootComponent = CollisionComp; // Use a ProjectileMovementComponent to govern this projectile's movement ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp")); ProjectileMovement->UpdatedComponent = CollisionComp; ProjectileMovement->InitialSpeed = 3000.f; ProjectileMovement->MaxSpeed = 3000.f; ProjectileMovement->bRotationFollowsVelocity = true; ProjectileMovement->bShouldBounce = true; // Die after 3 seconds by default InitialLifeSpan = 3.0f; } void AProvingGroundsProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { // Only add impulse and destroy projectile if we hit a physics if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL) && OtherComp->IsSimulatingPhysics()) { OtherComp->AddImpulseAtLocation(GetVelocity() * 100.0f, GetActorLocation()); Destroy(); } }
59de308c0b88d5b65945a1fe411dbc451e0b5bd4
54e1a786248dde2ac0143d261f69a0c0ad843b7f
/LhaForge/ConfigCode/Dialogs/Dlg_shortcut.h
0bc5dd13dd930a17cc26fa6c487db337d1c7e6cc
[]
no_license
killvxk/lhaforge
0cc741e8143df2205fa88869b6f42c59ff1fd0bd
3cf98291f08de1e5c0f492115f54f3e89f99ab0c
refs/heads/master
2020-04-25T04:11:10.360033
2013-05-31T16:17:20
2013-05-31T16:17:20
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,394
h
/* * Copyright (c) 2005-2012, Claybird * 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. * 3. Neither the name of the Claybird nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #pragma once #include "Dlg_Base.h" #include "../../resource.h" #include "../../Utilities/Utility.h" //==================================== // ショートカット作成 //==================================== class CConfigManager; class CConfigDlgShortcut : public CDialogImpl<CConfigDlgShortcut>,public CMessageFilter,public IConfigDlgBase { protected: virtual BOOL PreTranslateMessage(MSG* pMsg){ return IsDialogMessage(pMsg); } public: enum { IDD = IDD_PROPPAGE_SHORTCUT }; // メッセージマップ BEGIN_MSG_MAP_EX(CConfigDlgShortcut) MSG_WM_INITDIALOG(OnInitDialog) COMMAND_RANGE_HANDLER(IDC_BUTTON_CREATE_EXTRACT_SHORTCUT_DESKTOP,IDC_BUTTON_CREATE_EXTRACT_SHORTCUT_SENDTO, OnCreateShortcut) COMMAND_RANGE_HANDLER(IDC_BUTTON_CREATE_COMPRESS_SHORTCUT_DESKTOP,IDC_BUTTON_CREATE_COMPRESS_SHORTCUT_SENDTO, OnCreateShortcut) COMMAND_RANGE_HANDLER(IDC_BUTTON_CREATE_AUTOMATIC_SHORTCUT_DESKTOP,IDC_BUTTON_CREATE_AUTOMATIC_SHORTCUT_SENDTO, OnCreateShortcut) COMMAND_RANGE_HANDLER(IDC_BUTTON_CREATE_LIST_SHORTCUT_DESKTOP,IDC_BUTTON_CREATE_LIST_SHORTCUT_SENDTO, OnCreateShortcut) COMMAND_RANGE_HANDLER(IDC_BUTTON_CREATE_TESTARCHIVE_SHORTCUT_DESKTOP,IDC_BUTTON_CREATE_TESTARCHIVE_SHORTCUT_SENDTO, OnCreateShortcut) MSG_WM_DESTROY(OnDestroy) END_MSG_MAP() LRESULT OnInitDialog(HWND hWnd, LPARAM lParam); LRESULT OnCreateShortcut(WORD,WORD,HWND,BOOL&); bool GetCompressShortcutInfo(LPTSTR,CString&); LRESULT OnApply(){return TRUE;} CConfigDlgShortcut(){ TRACE(_T("CConfigDlgShortcut()\n")); } LRESULT OnDestroy(){ CMessageLoop* pLoop = _Module.GetMessageLoop(); pLoop->RemoveMessageFilter(this); return TRUE; } void LoadConfig(CConfigManager& Config){} void StoreConfig(CConfigManager& Config){} };
26b01336382624b7a2c2c23d210c24348cd9c9fd
8caa570ec32fa20d01e55acefd2b933f16964421
/interviewquestions/GoogleInterviews/RacerRank/main.cpp
f4acf99eb1a52843cb47e0061b66d15646712ff5
[]
no_license
zhenl010/zhenl010
50d37601e3f9a7f759d6563ef53e0df98ffca261
f70065b153a8eb3dc357899158fe8011e4d93121
refs/heads/master
2020-04-18T10:16:53.980484
2013-06-05T16:11:47
2013-06-05T16:11:47
3,318,566
0
1
null
null
null
null
UTF-8
C++
false
false
1,839
cpp
// 一堆racer,每个racer有出发时间和到达时间,计算每个racer的score,规则如下 // :score = 所有出发比自己晚但是到达比自己早的racer数量之和,(所有的出发时间 // 和到达时间没有重复的)要求时间复杂度o(nlgn). #include <iostream> #include <vector> #include <algorithm> #include "OrderStatisticTree.h" namespace { ////////////////////////////////////////////////////////////////////////// using namespace std; struct Racer { int beg; int end; }; template<typename DataType, int N> int ArraySize(DataType(&a)[N]) { return N; } struct IdValue { int idx; int val; }; bool LessIdValue(const IdValue& a, const IdValue& b) { return a.val < b.val; } class ScoreHelper { public: explicit ScoreHelper(const vector<Racer>& racers): racers_(racers) {} vector<int> GetScores() { int size = racers_.size(); vector<IdValue> ends(size); for (int i=0; i<size; ++i) { ends[i].idx = i; ends[i].val = racers_[i].end; } sort(ends.begin(), ends.end(), LessIdValue); vector<int> scs(size); OrderStatisticTree<IdValue, LessIdValue> begins; for (int i=0; i<size; ++i) { int idx = ends[i].idx; IdValue beg = { idx, racers_[idx].beg }; begins.Insert(beg); scs[idx] = ends[idx].val - begins.Rank(beg); } return scs; } private: const vector<Racer>& racers_; }; ////////////////////////////////////////////////////////////////////////// } int main() { int racer_num = 5; Racer rcs[] = { { 1, 100 }, { 2, 10 }, { 3, 4 }, { 5, 6 }, }; vector<Racer> racers(rcs, rcs+ArraySize(rcs)); // for (int i=0; i<racer_num; ++i) { // racers[i].beg = rand(); // racers[i].end = racers[i].beg + rand(); // } vector<int> scores = ScoreHelper(racers).GetScores(); return 0; }
4aae9a68e69c67280a069d6e9c3fe7e469f3bc7a
51f08e2fc0b3a24377737a33727def8a4da89b76
/src/ECS/Components/AnimationComponent.cpp
46c7bd90462a970fd61b99e70fcc5c9a112472ce
[ "MIT" ]
permissive
InversePalindrome/ProceduralX
bf820373247d4341732b57cf17f62a004a75e2d6
f53d734970be4300f06db295d25e1a012b1a8fd9
refs/heads/master
2020-12-29T11:36:06.410204
2020-05-11T21:38:12
2020-05-11T21:38:12
238,593,940
3
0
null
null
null
null
UTF-8
C++
false
false
1,691
cpp
/* Copyright (c) 2020 Inverse Palindrome ProceduralX - ECS/Components/AnimationComponent.cpp https://inversepalindrome.com/ */ #include "ECS/Components/AnimationComponent.hpp" void ECS::Components::AnimationComponent::update(const sf::Time& deltaTime) { animator.update(deltaTime); } void ECS::Components::AnimationComponent::animate(sf::Sprite& sprite) { animator.animate(sprite); } void ECS::Components::AnimationComponent::playAnimation(State state) { animator.playAnimation(state, animationMap[state].loop); } void ECS::Components::AnimationComponent::stopAnimation() { animator.stopAnimation(); } void ECS::Components::AnimationComponent::addAnimation(State state, const std::function<void(sf::Sprite&, float)>& animation, const AnimationData& animationData) { animationMap[state] = animationData; animator.addAnimation(state, animation, sf::seconds(animationData.duration.count())); } bool ECS::Components::AnimationComponent::isPlayingAnimation() const { return animator.isPlayingAnimation(); } bool ECS::Components::AnimationComponent::hasAnimation(State state) const { return animationMap.count(state); } ECS::Components::AnimationComponent::Iterator ECS::Components::AnimationComponent::begin() { return animationMap.begin(); } ECS::Components::AnimationComponent::Iterator ECS::Components::AnimationComponent::end() { return animationMap.end(); } ECS::Components::AnimationComponent::ConstIterator ECS::Components::AnimationComponent::begin() const { return animationMap.cbegin(); } ECS::Components::AnimationComponent::ConstIterator ECS::Components::AnimationComponent::end() const { return animationMap.cend(); }
6c5f85865dd89a7f1a692c81669f9a4279abf232
3437fb257545a0bf6d25a76ada6047f7c4686865
/LeetCode/598.cpp
3ca5f6eac60e78acbd30e7e7e383ac082262953b
[]
no_license
whing123/C-Coding
62d1db79d6e6c211c7032ca91f466ffda4048ad9
3edfbad82acd5667eb0134cb3de787555f9714d8
refs/heads/master
2021-01-23T01:26:17.228602
2019-10-03T16:21:43
2019-10-03T16:21:43
102,434,473
0
0
null
null
null
null
UTF-8
C++
false
false
552
cpp
/* *题目: * 598 * Range Addition II * *思路: * * *技法: * */ class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { if(ops.size() == 0){ return m * n; } int a, b; a = b = INT_MAX; for(int i = 0; i < ops.size(); ++i){ if(ops[i][0] < a){ a = ops[i][0]; } if(ops[i][1] < b){ b = ops[i][1]; } } return a * b; } };
e2369bcac8e3f8614e9c2556791f87bde23933fe
dae49b5b2c087df67ccdd706f89f8b553ad5ad1e
/kokkos/lulesh.cc
6577b9a62cdc3c6b5ce37b1b78004086113d412f
[]
no_license
joao-lima/lulesh
d9eb679bcbca115fe5a4b75c91e67f0af4efeca2
07ccaf1e16ebd282002792c677db5f7d59dc8a05
refs/heads/master
2021-01-21T13:53:27.259043
2016-05-20T02:23:34
2016-05-20T02:23:34
46,507,824
0
0
null
null
null
null
UTF-8
C++
false
false
96,739
cc
/* This is a Version 2.0 MPI + OpenMP implementation of LULESH Copyright (c) 2010-2013. Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. LLNL-CODE-461231 All rights reserved. This file is part of LULESH, Version 2.0. Please also read this link -- http://www.opensource.org/licenses/index.php ////////////// DIFFERENCES BETWEEN THIS VERSION (2.x) AND EARLIER VERSIONS: * Addition of regions to make work more representative of multi-material codes * Default size of each domain is 30^3 (27000 elem) instead of 45^3. This is more representative of our actual working set sizes * Single source distribution supports pure serial, pure OpenMP, MPI-only, and MPI+OpenMP * Addition of ability to visualize the mesh using VisIt https://wci.llnl.gov/codes/visit/download.html * Various command line options (see ./lulesh2.0 -h) -q : quiet mode - suppress stdout -i <iterations> : number of cycles to run -s <size> : length of cube mesh along side -r <numregions> : Number of distinct regions (def: 11) -b <balance> : Load balance between regions of a domain (def: 1) -c <cost> : Extra cost of more expensive regions (def: 1) -f <filepieces> : Number of file parts for viz output (def: np/9) -p : Print out progress -v : Output viz file (requires compiling with -DVIZ_MESH -h : This message printf("Usage: %s [opts]\n", execname); printf(" where [opts] is one or more of:\n"); printf(" -q : quiet mode - suppress all stdout\n"); printf(" -i <iterations> : number of cycles to run\n"); printf(" -s <size> : length of cube mesh along side\n"); printf(" -r <numregions> : Number of distinct regions (def: 11)\n"); printf(" -b <balance> : Load balance between regions of a domain (def: 1)\n"); printf(" -c <cost> : Extra cost of more expensive regions (def: 1)\n"); printf(" -f <numfiles> : Number of files to split viz dump into (def: (np+10)/9)\n"); printf(" -p : Print out progress\n"); printf(" -v : Output viz file (requires compiling with -DVIZ_MESH\n"); printf(" -h : This message\n"); printf("\n\n"); *Notable changes in LULESH 2.0 * Split functionality into different files lulesh.cc - where most (all?) of the timed functionality lies lulesh-comm.cc - MPI functionality lulesh-init.cc - Setup code lulesh-viz.cc - Support for visualization option lulesh-util.cc - Non-timed functions * * The concept of "regions" was added, although every region is the same ideal * gas material, and the same sedov blast wave problem is still the only * problem its hardcoded to solve. * Regions allow two things important to making this proxy app more representative: * Four of the LULESH routines are now performed on a region-by-region basis, * making the memory access patterns non-unit stride * Artificial load imbalances can be easily introduced that could impact * parallelization strategies. * The load balance flag changes region assignment. Region number is raised to * the power entered for assignment probability. Most likely regions changes * with MPI process id. * The cost flag raises the cost of ~45% of the regions to evaluate EOS by the * entered multiple. The cost of 5% is 10x the entered multiple. * MPI and OpenMP were added, and coalesced into a single version of the source * that can support serial builds, MPI-only, OpenMP-only, and MPI+OpenMP * Added support to write plot files using "poor mans parallel I/O" when linked * with the silo library, which in turn can be read by VisIt. * Enabled variable timestep calculation by default (courant condition), which * results in an additional reduction. * Default domain (mesh) size reduced from 45^3 to 30^3 * Command line options to allow numerous test cases without needing to recompile * Performance optimizations and code cleanup beyond LULESH 1.0 * Added a "Figure of Merit" calculation (elements solved per microsecond) and * output in support of using LULESH 2.0 for the 2017 CORAL procurement * * Possible Differences in Final Release (other changes possible) * * High Level mesh structure to allow data structure transformations * Different default parameters * Minor code performance changes and cleanup TODO in future versions * Add reader for (truly) unstructured meshes, probably serial only * CMake based build system ////////////// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. Additional BSD Notice 1. This notice is required to be provided under our contract with the U.S. Department of Energy (DOE). This work was produced at Lawrence Livermore National Laboratory under Contract No. DE-AC52-07NA27344 with the DOE. 2. Neither the United States Government nor Lawrence Livermore National Security, LLC nor any of their employees, makes any warranty, express or implied, or assumes any liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately-owned rights. 3. Also, reference herein to any specific commercial products, process, or services by trade name, trademark, manufacturer or otherwise does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or Lawrence Livermore National Security, LLC. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or Lawrence Livermore National Security, LLC, and shall not be used for advertising or product endorsement purposes. */ #include <climits> #include <vector> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <sys/time.h> #include <iostream> #include <unistd.h> #include <Kokkos_Core.hpp> #include "lulesh.h" /*********************************/ /* Data structure implementation */ /*********************************/ /* might want to add access methods so that memory can be */ /* better managed, as in luleshFT */ template <typename T> T *Allocate(size_t size) { return static_cast<T *>(malloc(sizeof(T)*size)) ; } template <typename T> void Release(T **ptr) { if (*ptr != NULL) { free(*ptr) ; *ptr = NULL ; } } /******************************************/ /* Work Routines */ static inline void TimeIncrement(Domain& domain) { Real_t targetdt = domain.stoptime() - domain.time() ; if ((domain.dtfixed() <= Real_t(0.0)) && (domain.cycle() != Int_t(0))) { Real_t ratio ; Real_t olddt = domain.deltatime() ; /* This will require a reduction in parallel */ Real_t gnewdt = Real_t(1.0e+20) ; Real_t newdt ; if (domain.dtcourant() < gnewdt) { gnewdt = domain.dtcourant() / Real_t(2.0) ; } if (domain.dthydro() < gnewdt) { gnewdt = domain.dthydro() * Real_t(2.0) / Real_t(3.0) ; } #if USE_MPI MPI_Allreduce(&gnewdt, &newdt, 1, ((sizeof(Real_t) == 4) ? MPI_FLOAT : MPI_DOUBLE), MPI_MIN, MPI_COMM_WORLD) ; #else newdt = gnewdt; #endif ratio = newdt / olddt ; if (ratio >= Real_t(1.0)) { if (ratio < domain.deltatimemultlb()) { newdt = olddt ; } else if (ratio > domain.deltatimemultub()) { newdt = olddt*domain.deltatimemultub() ; } } if (newdt > domain.dtmax()) { newdt = domain.dtmax() ; } domain.deltatime() = newdt ; } /* TRY TO PREVENT VERY SMALL SCALING ON THE NEXT CYCLE */ if ((targetdt > domain.deltatime()) && (targetdt < (Real_t(4.0) * domain.deltatime() / Real_t(3.0))) ) { targetdt = Real_t(2.0) * domain.deltatime() / Real_t(3.0) ; } if (targetdt < domain.deltatime()) { domain.deltatime() = targetdt ; } domain.time() += domain.deltatime() ; ++domain.cycle() ; } /******************************************/ KOKKOS_INLINE_FUNCTION void CollectDomainNodesToElemNodes(real_t_view_1d x, real_t_view_1d y, real_t_view_1d z, const Index_t* elemToNode, Real_t elemX[8], Real_t elemY[8], Real_t elemZ[8]) { Index_t nd0i = elemToNode[0] ; Index_t nd1i = elemToNode[1] ; Index_t nd2i = elemToNode[2] ; Index_t nd3i = elemToNode[3] ; Index_t nd4i = elemToNode[4] ; Index_t nd5i = elemToNode[5] ; Index_t nd6i = elemToNode[6] ; Index_t nd7i = elemToNode[7] ; elemX[0] = x(nd0i); elemX[1] = x(nd1i); elemX[2] = x(nd2i); elemX[3] = x(nd3i); elemX[4] = x(nd4i); elemX[5] = x(nd5i); elemX[6] = x(nd6i); elemX[7] = x(nd7i); elemY[0] = y(nd0i); elemY[1] = y(nd1i); elemY[2] = y(nd2i); elemY[3] = y(nd3i); elemY[4] = y(nd4i); elemY[5] = y(nd5i); elemY[6] = y(nd6i); elemY[7] = y(nd7i); elemZ[0] = z(nd0i); elemZ[1] = z(nd1i); elemZ[2] = z(nd2i); elemZ[3] = z(nd3i); elemZ[4] = z(nd4i); elemZ[5] = z(nd5i); elemZ[6] = z(nd6i); elemZ[7] = z(nd7i); } static inline void CollectDomainNodesToElemNodes(Domain &domain, const Index_t* elemToNode, Real_t elemX[8], Real_t elemY[8], Real_t elemZ[8]) { Index_t nd0i = elemToNode[0] ; Index_t nd1i = elemToNode[1] ; Index_t nd2i = elemToNode[2] ; Index_t nd3i = elemToNode[3] ; Index_t nd4i = elemToNode[4] ; Index_t nd5i = elemToNode[5] ; Index_t nd6i = elemToNode[6] ; Index_t nd7i = elemToNode[7] ; elemX[0] = domain.x(nd0i); elemX[1] = domain.x(nd1i); elemX[2] = domain.x(nd2i); elemX[3] = domain.x(nd3i); elemX[4] = domain.x(nd4i); elemX[5] = domain.x(nd5i); elemX[6] = domain.x(nd6i); elemX[7] = domain.x(nd7i); elemY[0] = domain.y(nd0i); elemY[1] = domain.y(nd1i); elemY[2] = domain.y(nd2i); elemY[3] = domain.y(nd3i); elemY[4] = domain.y(nd4i); elemY[5] = domain.y(nd5i); elemY[6] = domain.y(nd6i); elemY[7] = domain.y(nd7i); elemZ[0] = domain.z(nd0i); elemZ[1] = domain.z(nd1i); elemZ[2] = domain.z(nd2i); elemZ[3] = domain.z(nd3i); elemZ[4] = domain.z(nd4i); elemZ[5] = domain.z(nd5i); elemZ[6] = domain.z(nd6i); elemZ[7] = domain.z(nd7i); } /******************************************/ struct InitStressTermsForElems { real_t_view_1d p; real_t_view_1d q; real_t_view_1d sigxx; real_t_view_1d sigyy; real_t_view_1d sigzz; Index_t numElem; // // pull in the stresses appropriate to the hydro integration // InitStressTermsForElems(real_t_view_1d p_, real_t_view_1d q_, real_t_view_1d sigxx_, real_t_view_1d sigyy_, real_t_view_1d sigzz_, Index_t& numElem_): p(p_), q(q_), sigxx(sigxx_), sigyy(sigyy_), sigzz(sigzz_), numElem(numElem_) {} KOKKOS_INLINE_FUNCTION void operator() (const int& i) const { sigxx[i] = sigyy[i] = sigzz[i] = - p(i) - q(i) ; } }; /******************************************/ KOKKOS_INLINE_FUNCTION void CalcElemShapeFunctionDerivatives( Real_t const x[], Real_t const y[], Real_t const z[], Real_t b[][8], Real_t* const volume ) { const Real_t x0 = x[0] ; const Real_t x1 = x[1] ; const Real_t x2 = x[2] ; const Real_t x3 = x[3] ; const Real_t x4 = x[4] ; const Real_t x5 = x[5] ; const Real_t x6 = x[6] ; const Real_t x7 = x[7] ; const Real_t y0 = y[0] ; const Real_t y1 = y[1] ; const Real_t y2 = y[2] ; const Real_t y3 = y[3] ; const Real_t y4 = y[4] ; const Real_t y5 = y[5] ; const Real_t y6 = y[6] ; const Real_t y7 = y[7] ; const Real_t z0 = z[0] ; const Real_t z1 = z[1] ; const Real_t z2 = z[2] ; const Real_t z3 = z[3] ; const Real_t z4 = z[4] ; const Real_t z5 = z[5] ; const Real_t z6 = z[6] ; const Real_t z7 = z[7] ; Real_t fjxxi, fjxet, fjxze; Real_t fjyxi, fjyet, fjyze; Real_t fjzxi, fjzet, fjzze; Real_t cjxxi, cjxet, cjxze; Real_t cjyxi, cjyet, cjyze; Real_t cjzxi, cjzet, cjzze; fjxxi = Real_t(.125) * ( (x6-x0) + (x5-x3) - (x7-x1) - (x4-x2) ); fjxet = Real_t(.125) * ( (x6-x0) - (x5-x3) + (x7-x1) - (x4-x2) ); fjxze = Real_t(.125) * ( (x6-x0) + (x5-x3) + (x7-x1) + (x4-x2) ); fjyxi = Real_t(.125) * ( (y6-y0) + (y5-y3) - (y7-y1) - (y4-y2) ); fjyet = Real_t(.125) * ( (y6-y0) - (y5-y3) + (y7-y1) - (y4-y2) ); fjyze = Real_t(.125) * ( (y6-y0) + (y5-y3) + (y7-y1) + (y4-y2) ); fjzxi = Real_t(.125) * ( (z6-z0) + (z5-z3) - (z7-z1) - (z4-z2) ); fjzet = Real_t(.125) * ( (z6-z0) - (z5-z3) + (z7-z1) - (z4-z2) ); fjzze = Real_t(.125) * ( (z6-z0) + (z5-z3) + (z7-z1) + (z4-z2) ); /* compute cofactors */ cjxxi = (fjyet * fjzze) - (fjzet * fjyze); cjxet = - (fjyxi * fjzze) + (fjzxi * fjyze); cjxze = (fjyxi * fjzet) - (fjzxi * fjyet); cjyxi = - (fjxet * fjzze) + (fjzet * fjxze); cjyet = (fjxxi * fjzze) - (fjzxi * fjxze); cjyze = - (fjxxi * fjzet) + (fjzxi * fjxet); cjzxi = (fjxet * fjyze) - (fjyet * fjxze); cjzet = - (fjxxi * fjyze) + (fjyxi * fjxze); cjzze = (fjxxi * fjyet) - (fjyxi * fjxet); /* calculate partials : this need only be done for l = 0,1,2,3 since , by symmetry , (6,7,4,5) = - (0,1,2,3) . */ b[0][0] = - cjxxi - cjxet - cjxze; b[0][1] = cjxxi - cjxet - cjxze; b[0][2] = cjxxi + cjxet - cjxze; b[0][3] = - cjxxi + cjxet - cjxze; b[0][4] = -b[0][2]; b[0][5] = -b[0][3]; b[0][6] = -b[0][0]; b[0][7] = -b[0][1]; b[1][0] = - cjyxi - cjyet - cjyze; b[1][1] = cjyxi - cjyet - cjyze; b[1][2] = cjyxi + cjyet - cjyze; b[1][3] = - cjyxi + cjyet - cjyze; b[1][4] = -b[1][2]; b[1][5] = -b[1][3]; b[1][6] = -b[1][0]; b[1][7] = -b[1][1]; b[2][0] = - cjzxi - cjzet - cjzze; b[2][1] = cjzxi - cjzet - cjzze; b[2][2] = cjzxi + cjzet - cjzze; b[2][3] = - cjzxi + cjzet - cjzze; b[2][4] = -b[2][2]; b[2][5] = -b[2][3]; b[2][6] = -b[2][0]; b[2][7] = -b[2][1]; /* calculate jacobian determinant (volume) */ *volume = Real_t(8.) * ( fjxet * cjxet + fjyet * cjyet + fjzet * cjzet); } /******************************************/ static inline void SumElemFaceNormal(Real_t *normalX0, Real_t *normalY0, Real_t *normalZ0, Real_t *normalX1, Real_t *normalY1, Real_t *normalZ1, Real_t *normalX2, Real_t *normalY2, Real_t *normalZ2, Real_t *normalX3, Real_t *normalY3, Real_t *normalZ3, const Real_t x0, const Real_t y0, const Real_t z0, const Real_t x1, const Real_t y1, const Real_t z1, const Real_t x2, const Real_t y2, const Real_t z2, const Real_t x3, const Real_t y3, const Real_t z3) { Real_t bisectX0 = Real_t(0.5) * (x3 + x2 - x1 - x0); Real_t bisectY0 = Real_t(0.5) * (y3 + y2 - y1 - y0); Real_t bisectZ0 = Real_t(0.5) * (z3 + z2 - z1 - z0); Real_t bisectX1 = Real_t(0.5) * (x2 + x1 - x3 - x0); Real_t bisectY1 = Real_t(0.5) * (y2 + y1 - y3 - y0); Real_t bisectZ1 = Real_t(0.5) * (z2 + z1 - z3 - z0); Real_t areaX = Real_t(0.25) * (bisectY0 * bisectZ1 - bisectZ0 * bisectY1); Real_t areaY = Real_t(0.25) * (bisectZ0 * bisectX1 - bisectX0 * bisectZ1); Real_t areaZ = Real_t(0.25) * (bisectX0 * bisectY1 - bisectY0 * bisectX1); *normalX0 += areaX; *normalX1 += areaX; *normalX2 += areaX; *normalX3 += areaX; *normalY0 += areaY; *normalY1 += areaY; *normalY2 += areaY; *normalY3 += areaY; *normalZ0 += areaZ; *normalZ1 += areaZ; *normalZ2 += areaZ; *normalZ3 += areaZ; } /******************************************/ static inline void CalcElemNodeNormals(Real_t pfx[8], Real_t pfy[8], Real_t pfz[8], const Real_t x[8], const Real_t y[8], const Real_t z[8]) { for (Index_t i = 0 ; i < 8 ; ++i) { pfx[i] = Real_t(0.0); pfy[i] = Real_t(0.0); pfz[i] = Real_t(0.0); } /* evaluate face one: nodes 0, 1, 2, 3 */ SumElemFaceNormal(&pfx[0], &pfy[0], &pfz[0], &pfx[1], &pfy[1], &pfz[1], &pfx[2], &pfy[2], &pfz[2], &pfx[3], &pfy[3], &pfz[3], x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2], x[3], y[3], z[3]); /* evaluate face two: nodes 0, 4, 5, 1 */ SumElemFaceNormal(&pfx[0], &pfy[0], &pfz[0], &pfx[4], &pfy[4], &pfz[4], &pfx[5], &pfy[5], &pfz[5], &pfx[1], &pfy[1], &pfz[1], x[0], y[0], z[0], x[4], y[4], z[4], x[5], y[5], z[5], x[1], y[1], z[1]); /* evaluate face three: nodes 1, 5, 6, 2 */ SumElemFaceNormal(&pfx[1], &pfy[1], &pfz[1], &pfx[5], &pfy[5], &pfz[5], &pfx[6], &pfy[6], &pfz[6], &pfx[2], &pfy[2], &pfz[2], x[1], y[1], z[1], x[5], y[5], z[5], x[6], y[6], z[6], x[2], y[2], z[2]); /* evaluate face four: nodes 2, 6, 7, 3 */ SumElemFaceNormal(&pfx[2], &pfy[2], &pfz[2], &pfx[6], &pfy[6], &pfz[6], &pfx[7], &pfy[7], &pfz[7], &pfx[3], &pfy[3], &pfz[3], x[2], y[2], z[2], x[6], y[6], z[6], x[7], y[7], z[7], x[3], y[3], z[3]); /* evaluate face five: nodes 3, 7, 4, 0 */ SumElemFaceNormal(&pfx[3], &pfy[3], &pfz[3], &pfx[7], &pfy[7], &pfz[7], &pfx[4], &pfy[4], &pfz[4], &pfx[0], &pfy[0], &pfz[0], x[3], y[3], z[3], x[7], y[7], z[7], x[4], y[4], z[4], x[0], y[0], z[0]); /* evaluate face six: nodes 4, 7, 6, 5 */ SumElemFaceNormal(&pfx[4], &pfy[4], &pfz[4], &pfx[7], &pfy[7], &pfz[7], &pfx[6], &pfy[6], &pfz[6], &pfx[5], &pfy[5], &pfz[5], x[4], y[4], z[4], x[7], y[7], z[7], x[6], y[6], z[6], x[5], y[5], z[5]); } /******************************************/ static inline void SumElemStressesToNodeForces( const Real_t B[][8], const Real_t stress_xx, const Real_t stress_yy, const Real_t stress_zz, Real_t fx[], Real_t fy[], Real_t fz[] ) { for(Index_t i = 0; i < 8; i++) { fx[i] = -( stress_xx * B[0][i] ); fy[i] = -( stress_yy * B[1][i] ); fz[i] = -( stress_zz * B[2][i] ); } } /******************************************/ struct IntegrateStressForElemsByElem{ real_t_view_1d x; real_t_view_1d y; real_t_view_1d z; real_t_view_1d fx; real_t_view_1d fy; real_t_view_1d fz; index_t_view_1d nodelist; real_t_view_1d fx_elem; real_t_view_1d fy_elem; real_t_view_1d fz_elem; real_t_view_1d sigxx; real_t_view_1d sigyy; real_t_view_1d sigzz; real_t_view_1d determ; Index_t numElem; IntegrateStressForElemsByElem( real_t_view_1d x_, real_t_view_1d y_, real_t_view_1d z_, real_t_view_1d fx_, real_t_view_1d fy_, real_t_view_1d fz_, index_t_view_1d nodelist_, real_t_view_1d fx_elem_, real_t_view_1d fy_elem_, real_t_view_1d fz_elem_, real_t_view_1d sigxx_, real_t_view_1d sigyy_, real_t_view_1d sigzz_, real_t_view_1d determ_, Index_t& numElem_): x(x_), y(y_), z(z_), fx(fx_), fy(fy_), fz(fz_), nodelist(nodelist_), fx_elem(fx_elem_), fy_elem(fy_elem_), fz_elem(fz_elem_), sigxx(sigxx_), sigyy(sigyy_), sigzz(sigzz_), determ(determ_), numElem(numElem_) {} KOKKOS_INLINE_FUNCTION void operator() (const int& k) const { const Index_t* const elemToNode = &nodelist[Index_t(8)*k]; Real_t B[3][8] ;// shape function derivatives Real_t x_local[8] ; Real_t y_local[8] ; Real_t z_local[8] ; // get nodal coordinates from global arrays and copy into local arrays. CollectDomainNodesToElemNodes(x, y, z, elemToNode, x_local, y_local, z_local); // Volume calculation involves extra work for numerical consistency CalcElemShapeFunctionDerivatives(x_local, y_local, z_local, B, &determ[k]); CalcElemNodeNormals( B[0] , B[1], B[2], x_local, y_local, z_local ); // Eliminate thread writing conflicts at the nodes by giving // each element its own copy to write to SumElemStressesToNodeForces( B, sigxx[k], sigyy[k], sigzz[k], &fx_elem[k*8], &fy_elem[k*8], &fz_elem[k*8] ) ; } }; struct IntegrateStressForElemsByNode{ real_t_view_1d fx; real_t_view_1d fy; real_t_view_1d fz; real_t_view_1d fx_elem; real_t_view_1d fy_elem; real_t_view_1d fz_elem; index_t_view_1d nodeElemStart; index_t_view_1d nodeElemCornerList; Index_t numNode; IntegrateStressForElemsByNode( real_t_view_1d fx_, real_t_view_1d fy_, real_t_view_1d fz_, real_t_view_1d fx_elem_, real_t_view_1d fy_elem_, real_t_view_1d fz_elem_, index_t_view_1d nodeElemStart_, index_t_view_1d nodeElemCornerList_, Index_t& numNode_ ) : fx(fx_), fy(fy_), fz(fz_), fx_elem(fx_elem_), fy_elem(fy_elem_), fz_elem(fz_elem_), nodeElemStart(nodeElemStart_), nodeElemCornerList(nodeElemCornerList_), numNode(numNode_) {} KOKKOS_INLINE_FUNCTION void operator() (const int& i) const { Index_t count = nodeElemStart[i+1] - nodeElemStart[i]; Index_t *cornerList = &nodeElemCornerList[nodeElemStart[i]]; Real_t fx_tmp = Real_t(0.0) ; Real_t fy_tmp = Real_t(0.0) ; Real_t fz_tmp = Real_t(0.0) ; for (Index_t i=0 ; i < count ; ++i) { Index_t elem = cornerList[i] ; fx_tmp += fx_elem[elem] ; fy_tmp += fy_elem[elem] ; fz_tmp += fz_elem[elem] ; } fx(i) = fx_tmp ; fy(i) = fy_tmp ; fz(i) = fz_tmp ; } }; static inline void IntegrateStressForElems( Domain &domain, real_t_view_1d sigxx, real_t_view_1d sigyy, real_t_view_1d sigzz, real_t_view_1d determ, Index_t numElem, Index_t numNode) { Index_t numElem8 = numElem * 8 ; Real_t *fx_elem; Real_t *fy_elem; Real_t *fz_elem; fx_elem = Allocate<Real_t>(numElem8) ; fy_elem = Allocate<Real_t>(numElem8) ; fz_elem = Allocate<Real_t>(numElem8) ; // loop over all elements real_t_view_1d fx_elem_(fx_elem, numElem8); real_t_view_1d fy_elem_(fy_elem, numElem8); real_t_view_1d fz_elem_(fz_elem, numElem8); IntegrateStressForElemsByElem f0( domain.x_view(), domain.y_view(), domain.z_view(), domain.fx_view(), domain.fy_view(), domain.fz_view(), domain.nodelist_view(), fx_elem_, fy_elem_, fz_elem_, sigxx, sigyy, sigzz, determ, numElem ); Kokkos::parallel_for(f0.numElem, f0); // If threaded, then we need to copy the data out of the temporary // arrays used above into the final forces field IntegrateStressForElemsByNode f1( domain.fx_view(), domain.fy_view(), domain.fz_view(), fx_elem_, fy_elem_, fz_elem_, domain.nodeElemStart_view, domain.nodeElemCornerList_view, numNode ); Kokkos::parallel_for(f1.numNode, f1); Release(&fz_elem) ; Release(&fy_elem) ; Release(&fx_elem) ; } /******************************************/ static inline void VoluDer(const Real_t x0, const Real_t x1, const Real_t x2, const Real_t x3, const Real_t x4, const Real_t x5, const Real_t y0, const Real_t y1, const Real_t y2, const Real_t y3, const Real_t y4, const Real_t y5, const Real_t z0, const Real_t z1, const Real_t z2, const Real_t z3, const Real_t z4, const Real_t z5, Real_t* dvdx, Real_t* dvdy, Real_t* dvdz) { const Real_t twelfth = Real_t(1.0) / Real_t(12.0) ; *dvdx = (y1 + y2) * (z0 + z1) - (y0 + y1) * (z1 + z2) + (y0 + y4) * (z3 + z4) - (y3 + y4) * (z0 + z4) - (y2 + y5) * (z3 + z5) + (y3 + y5) * (z2 + z5); *dvdy = - (x1 + x2) * (z0 + z1) + (x0 + x1) * (z1 + z2) - (x0 + x4) * (z3 + z4) + (x3 + x4) * (z0 + z4) + (x2 + x5) * (z3 + z5) - (x3 + x5) * (z2 + z5); *dvdz = - (y1 + y2) * (x0 + x1) + (y0 + y1) * (x1 + x2) - (y0 + y4) * (x3 + x4) + (y3 + y4) * (x0 + x4) + (y2 + y5) * (x3 + x5) - (y3 + y5) * (x2 + x5); *dvdx *= twelfth; *dvdy *= twelfth; *dvdz *= twelfth; } /******************************************/ static inline void CalcElemVolumeDerivative(Real_t dvdx[8], Real_t dvdy[8], Real_t dvdz[8], const Real_t x[8], const Real_t y[8], const Real_t z[8]) { VoluDer(x[1], x[2], x[3], x[4], x[5], x[7], y[1], y[2], y[3], y[4], y[5], y[7], z[1], z[2], z[3], z[4], z[5], z[7], &dvdx[0], &dvdy[0], &dvdz[0]); VoluDer(x[0], x[1], x[2], x[7], x[4], x[6], y[0], y[1], y[2], y[7], y[4], y[6], z[0], z[1], z[2], z[7], z[4], z[6], &dvdx[3], &dvdy[3], &dvdz[3]); VoluDer(x[3], x[0], x[1], x[6], x[7], x[5], y[3], y[0], y[1], y[6], y[7], y[5], z[3], z[0], z[1], z[6], z[7], z[5], &dvdx[2], &dvdy[2], &dvdz[2]); VoluDer(x[2], x[3], x[0], x[5], x[6], x[4], y[2], y[3], y[0], y[5], y[6], y[4], z[2], z[3], z[0], z[5], z[6], z[4], &dvdx[1], &dvdy[1], &dvdz[1]); VoluDer(x[7], x[6], x[5], x[0], x[3], x[1], y[7], y[6], y[5], y[0], y[3], y[1], z[7], z[6], z[5], z[0], z[3], z[1], &dvdx[4], &dvdy[4], &dvdz[4]); VoluDer(x[4], x[7], x[6], x[1], x[0], x[2], y[4], y[7], y[6], y[1], y[0], y[2], z[4], z[7], z[6], z[1], z[0], z[2], &dvdx[5], &dvdy[5], &dvdz[5]); VoluDer(x[5], x[4], x[7], x[2], x[1], x[3], y[5], y[4], y[7], y[2], y[1], y[3], z[5], z[4], z[7], z[2], z[1], z[3], &dvdx[6], &dvdy[6], &dvdz[6]); VoluDer(x[6], x[5], x[4], x[3], x[2], x[0], y[6], y[5], y[4], y[3], y[2], y[0], z[6], z[5], z[4], z[3], z[2], z[0], &dvdx[7], &dvdy[7], &dvdz[7]); } /******************************************/ static inline void CalcElemFBHourglassForce(Real_t *xd, Real_t *yd, Real_t *zd, Real_t hourgam[][4], Real_t coefficient, Real_t *hgfx, Real_t *hgfy, Real_t *hgfz ) { Real_t hxx[4]; for(Index_t i = 0; i < 4; i++) { hxx[i] = hourgam[0][i] * xd[0] + hourgam[1][i] * xd[1] + hourgam[2][i] * xd[2] + hourgam[3][i] * xd[3] + hourgam[4][i] * xd[4] + hourgam[5][i] * xd[5] + hourgam[6][i] * xd[6] + hourgam[7][i] * xd[7]; } for(Index_t i = 0; i < 8; i++) { hgfx[i] = coefficient * (hourgam[i][0] * hxx[0] + hourgam[i][1] * hxx[1] + hourgam[i][2] * hxx[2] + hourgam[i][3] * hxx[3]); } for(Index_t i = 0; i < 4; i++) { hxx[i] = hourgam[0][i] * yd[0] + hourgam[1][i] * yd[1] + hourgam[2][i] * yd[2] + hourgam[3][i] * yd[3] + hourgam[4][i] * yd[4] + hourgam[5][i] * yd[5] + hourgam[6][i] * yd[6] + hourgam[7][i] * yd[7]; } for(Index_t i = 0; i < 8; i++) { hgfy[i] = coefficient * (hourgam[i][0] * hxx[0] + hourgam[i][1] * hxx[1] + hourgam[i][2] * hxx[2] + hourgam[i][3] * hxx[3]); } for(Index_t i = 0; i < 4; i++) { hxx[i] = hourgam[0][i] * zd[0] + hourgam[1][i] * zd[1] + hourgam[2][i] * zd[2] + hourgam[3][i] * zd[3] + hourgam[4][i] * zd[4] + hourgam[5][i] * zd[5] + hourgam[6][i] * zd[6] + hourgam[7][i] * zd[7]; } for(Index_t i = 0; i < 8; i++) { hgfz[i] = coefficient * (hourgam[i][0] * hxx[0] + hourgam[i][1] * hxx[1] + hourgam[i][2] * hxx[2] + hourgam[i][3] * hxx[3]); } } /******************************************/ static inline void CalcFBHourglassForceForElems( Domain &domain, real_t_view_1d determ, Real_t *x8n, Real_t *y8n, Real_t *z8n, Real_t *dvdx, Real_t *dvdy, Real_t *dvdz, Real_t hourg, Index_t numElem, Index_t numNode) { #if _OPENMP Index_t numthreads = omp_get_max_threads(); #else Index_t numthreads = 1; #endif /************************************************* * * FUNCTION: Calculates the Flanagan-Belytschko anti-hourglass * force. * *************************************************/ Index_t numElem8 = numElem * 8 ; Real_t *fx_elem; Real_t *fy_elem; Real_t *fz_elem; if(numthreads > 1) { fx_elem = Allocate<Real_t>(numElem8) ; fy_elem = Allocate<Real_t>(numElem8) ; fz_elem = Allocate<Real_t>(numElem8) ; } Real_t gamma[4][8]; gamma[0][0] = Real_t( 1.); gamma[0][1] = Real_t( 1.); gamma[0][2] = Real_t(-1.); gamma[0][3] = Real_t(-1.); gamma[0][4] = Real_t(-1.); gamma[0][5] = Real_t(-1.); gamma[0][6] = Real_t( 1.); gamma[0][7] = Real_t( 1.); gamma[1][0] = Real_t( 1.); gamma[1][1] = Real_t(-1.); gamma[1][2] = Real_t(-1.); gamma[1][3] = Real_t( 1.); gamma[1][4] = Real_t(-1.); gamma[1][5] = Real_t( 1.); gamma[1][6] = Real_t( 1.); gamma[1][7] = Real_t(-1.); gamma[2][0] = Real_t( 1.); gamma[2][1] = Real_t(-1.); gamma[2][2] = Real_t( 1.); gamma[2][3] = Real_t(-1.); gamma[2][4] = Real_t( 1.); gamma[2][5] = Real_t(-1.); gamma[2][6] = Real_t( 1.); gamma[2][7] = Real_t(-1.); gamma[3][0] = Real_t(-1.); gamma[3][1] = Real_t( 1.); gamma[3][2] = Real_t(-1.); gamma[3][3] = Real_t( 1.); gamma[3][4] = Real_t( 1.); gamma[3][5] = Real_t(-1.); gamma[3][6] = Real_t( 1.); gamma[3][7] = Real_t(-1.); /*************************************************/ /* compute the hourglass modes */ #pragma omp parallel for firstprivate(numElem, hourg) for(Index_t i2=0;i2<numElem;++i2){ Real_t *fx_local, *fy_local, *fz_local ; Real_t hgfx[8], hgfy[8], hgfz[8] ; Real_t coefficient; Real_t hourgam[8][4]; Real_t xd1[8], yd1[8], zd1[8] ; const Index_t *elemToNode = domain.nodelist(i2); Index_t i3=8*i2; Real_t volinv=Real_t(1.0)/determ[i2]; Real_t ss1, mass1, volume13 ; for(Index_t i1=0;i1<4;++i1){ Real_t hourmodx = x8n[i3] * gamma[i1][0] + x8n[i3+1] * gamma[i1][1] + x8n[i3+2] * gamma[i1][2] + x8n[i3+3] * gamma[i1][3] + x8n[i3+4] * gamma[i1][4] + x8n[i3+5] * gamma[i1][5] + x8n[i3+6] * gamma[i1][6] + x8n[i3+7] * gamma[i1][7]; Real_t hourmody = y8n[i3] * gamma[i1][0] + y8n[i3+1] * gamma[i1][1] + y8n[i3+2] * gamma[i1][2] + y8n[i3+3] * gamma[i1][3] + y8n[i3+4] * gamma[i1][4] + y8n[i3+5] * gamma[i1][5] + y8n[i3+6] * gamma[i1][6] + y8n[i3+7] * gamma[i1][7]; Real_t hourmodz = z8n[i3] * gamma[i1][0] + z8n[i3+1] * gamma[i1][1] + z8n[i3+2] * gamma[i1][2] + z8n[i3+3] * gamma[i1][3] + z8n[i3+4] * gamma[i1][4] + z8n[i3+5] * gamma[i1][5] + z8n[i3+6] * gamma[i1][6] + z8n[i3+7] * gamma[i1][7]; hourgam[0][i1] = gamma[i1][0] - volinv*(dvdx[i3 ] * hourmodx + dvdy[i3 ] * hourmody + dvdz[i3 ] * hourmodz ); hourgam[1][i1] = gamma[i1][1] - volinv*(dvdx[i3+1] * hourmodx + dvdy[i3+1] * hourmody + dvdz[i3+1] * hourmodz ); hourgam[2][i1] = gamma[i1][2] - volinv*(dvdx[i3+2] * hourmodx + dvdy[i3+2] * hourmody + dvdz[i3+2] * hourmodz ); hourgam[3][i1] = gamma[i1][3] - volinv*(dvdx[i3+3] * hourmodx + dvdy[i3+3] * hourmody + dvdz[i3+3] * hourmodz ); hourgam[4][i1] = gamma[i1][4] - volinv*(dvdx[i3+4] * hourmodx + dvdy[i3+4] * hourmody + dvdz[i3+4] * hourmodz ); hourgam[5][i1] = gamma[i1][5] - volinv*(dvdx[i3+5] * hourmodx + dvdy[i3+5] * hourmody + dvdz[i3+5] * hourmodz ); hourgam[6][i1] = gamma[i1][6] - volinv*(dvdx[i3+6] * hourmodx + dvdy[i3+6] * hourmody + dvdz[i3+6] * hourmodz ); hourgam[7][i1] = gamma[i1][7] - volinv*(dvdx[i3+7] * hourmodx + dvdy[i3+7] * hourmody + dvdz[i3+7] * hourmodz ); } /* compute forces */ /* store forces into h arrays (force arrays) */ ss1=domain.ss(i2); mass1=domain.elemMass(i2); volume13=CBRT(determ[i2]); Index_t n0si2 = elemToNode[0]; Index_t n1si2 = elemToNode[1]; Index_t n2si2 = elemToNode[2]; Index_t n3si2 = elemToNode[3]; Index_t n4si2 = elemToNode[4]; Index_t n5si2 = elemToNode[5]; Index_t n6si2 = elemToNode[6]; Index_t n7si2 = elemToNode[7]; xd1[0] = domain.xd(n0si2); xd1[1] = domain.xd(n1si2); xd1[2] = domain.xd(n2si2); xd1[3] = domain.xd(n3si2); xd1[4] = domain.xd(n4si2); xd1[5] = domain.xd(n5si2); xd1[6] = domain.xd(n6si2); xd1[7] = domain.xd(n7si2); yd1[0] = domain.yd(n0si2); yd1[1] = domain.yd(n1si2); yd1[2] = domain.yd(n2si2); yd1[3] = domain.yd(n3si2); yd1[4] = domain.yd(n4si2); yd1[5] = domain.yd(n5si2); yd1[6] = domain.yd(n6si2); yd1[7] = domain.yd(n7si2); zd1[0] = domain.zd(n0si2); zd1[1] = domain.zd(n1si2); zd1[2] = domain.zd(n2si2); zd1[3] = domain.zd(n3si2); zd1[4] = domain.zd(n4si2); zd1[5] = domain.zd(n5si2); zd1[6] = domain.zd(n6si2); zd1[7] = domain.zd(n7si2); coefficient = - hourg * Real_t(0.01) * ss1 * mass1 / volume13; CalcElemFBHourglassForce(xd1,yd1,zd1, hourgam, coefficient, hgfx, hgfy, hgfz); // With the threaded version, we write into local arrays per elem // so we don't have to worry about race conditions if (numthreads > 1) { fx_local = &fx_elem[i3] ; fx_local[0] = hgfx[0]; fx_local[1] = hgfx[1]; fx_local[2] = hgfx[2]; fx_local[3] = hgfx[3]; fx_local[4] = hgfx[4]; fx_local[5] = hgfx[5]; fx_local[6] = hgfx[6]; fx_local[7] = hgfx[7]; fy_local = &fy_elem[i3] ; fy_local[0] = hgfy[0]; fy_local[1] = hgfy[1]; fy_local[2] = hgfy[2]; fy_local[3] = hgfy[3]; fy_local[4] = hgfy[4]; fy_local[5] = hgfy[5]; fy_local[6] = hgfy[6]; fy_local[7] = hgfy[7]; fz_local = &fz_elem[i3] ; fz_local[0] = hgfz[0]; fz_local[1] = hgfz[1]; fz_local[2] = hgfz[2]; fz_local[3] = hgfz[3]; fz_local[4] = hgfz[4]; fz_local[5] = hgfz[5]; fz_local[6] = hgfz[6]; fz_local[7] = hgfz[7]; } else { domain.fx(n0si2) += hgfx[0]; domain.fy(n0si2) += hgfy[0]; domain.fz(n0si2) += hgfz[0]; domain.fx(n1si2) += hgfx[1]; domain.fy(n1si2) += hgfy[1]; domain.fz(n1si2) += hgfz[1]; domain.fx(n2si2) += hgfx[2]; domain.fy(n2si2) += hgfy[2]; domain.fz(n2si2) += hgfz[2]; domain.fx(n3si2) += hgfx[3]; domain.fy(n3si2) += hgfy[3]; domain.fz(n3si2) += hgfz[3]; domain.fx(n4si2) += hgfx[4]; domain.fy(n4si2) += hgfy[4]; domain.fz(n4si2) += hgfz[4]; domain.fx(n5si2) += hgfx[5]; domain.fy(n5si2) += hgfy[5]; domain.fz(n5si2) += hgfz[5]; domain.fx(n6si2) += hgfx[6]; domain.fy(n6si2) += hgfy[6]; domain.fz(n6si2) += hgfz[6]; domain.fx(n7si2) += hgfx[7]; domain.fy(n7si2) += hgfy[7]; domain.fz(n7si2) += hgfz[7]; } } if (numthreads > 1) { // Collect the data from the local arrays into the final force arrays #pragma omp parallel for firstprivate(numNode) for( Index_t gnode=0 ; gnode<numNode ; ++gnode ) { Index_t count = domain.nodeElemCount(gnode) ; Index_t *cornerList = domain.nodeElemCornerList(gnode) ; Real_t fx_tmp = Real_t(0.0) ; Real_t fy_tmp = Real_t(0.0) ; Real_t fz_tmp = Real_t(0.0) ; for (Index_t i=0 ; i < count ; ++i) { Index_t elem = cornerList[i] ; fx_tmp += fx_elem[elem] ; fy_tmp += fy_elem[elem] ; fz_tmp += fz_elem[elem] ; } domain.fx(gnode) += fx_tmp ; domain.fy(gnode) += fy_tmp ; domain.fz(gnode) += fz_tmp ; } Release(&fz_elem) ; Release(&fy_elem) ; Release(&fx_elem) ; } } /******************************************/ struct CalcHourglassControlForElemsKernel { real_t_view_1d x; real_t_view_1d y; real_t_view_1d z; index_t_view_1d nodelist; real_t_view_1d v; real_t_view_1d volo; real_t_view_1d determ; real_t_view_1d dvdx; real_t_view_1d dvdy; real_t_view_1d dvdz; real_t_view_1d x8n; real_t_view_1d y8n; real_t_view_1d z8n; Index_t numElem; CalcHourglassControlForElemsKernel( real_t_view_1d x_, real_t_view_1d y_, real_t_view_1d z_, index_t_view_1d nodelist_, real_t_view_1d v_, real_t_view_1d volo_, real_t_view_1d determ_, real_t_view_1d dvdx_, real_t_view_1d dvdy_, real_t_view_1d dvdz_, real_t_view_1d x8n_, real_t_view_1d y8n_, real_t_view_1d z8n_, Index_t& numElem_): x(x_), y(y_), z(z_), dvdx(dvdx_), dvdy(dvdy_), dvdz(dvdz_), x8n(x8n_), y8n(y8n_), z8n(z8n_), nodelist(nodelist_), v(v_), volo(volo_), determ(determ_), numElem(numElem_) {} KOKKOS_INLINE_FUNCTION void operator() (const int& i) const { Real_t x1[8], y1[8], z1[8] ; Real_t pfx[8], pfy[8], pfz[8] ; Index_t* elemToNode = &nodelist[Index_t(8)*i]; CollectDomainNodesToElemNodes(x, y, z, elemToNode, x1, y1, z1); CalcElemVolumeDerivative(pfx, pfy, pfz, x1, y1, z1); /* load into temporary storage for FB Hour Glass control */ for(Index_t ii=0;ii<8;++ii){ Index_t jj=8*i+ii; dvdx[jj] = pfx[ii]; dvdy[jj] = pfy[ii]; dvdz[jj] = pfz[ii]; x8n[jj] = x1[ii]; y8n[jj] = y1[ii]; z8n[jj] = z1[ii]; } determ[i] = volo(i) * v(i); /* Do a check for negative volumes */ if ( v(i) <= Real_t(0.0) ) { #if USE_MPI MPI_Abort(MPI_COMM_WORLD, VolumeError) ; #else exit(VolumeError); #endif } } }; static inline void CalcHourglassControlForElems(Domain& domain, real_t_view_1d determ, Real_t hgcoef) { Index_t numElem = domain.numElem() ; Index_t numElem8 = numElem * 8 ; Real_t *dvdx = Allocate<Real_t>(numElem8) ; Real_t *dvdy = Allocate<Real_t>(numElem8) ; Real_t *dvdz = Allocate<Real_t>(numElem8) ; Real_t *x8n = Allocate<Real_t>(numElem8) ; Real_t *y8n = Allocate<Real_t>(numElem8) ; Real_t *z8n = Allocate<Real_t>(numElem8) ; real_t_view_1d dvdx_(dvdx, numElem8); real_t_view_1d dvdy_(dvdy, numElem8); real_t_view_1d dvdz_(dvdz, numElem8); real_t_view_1d x8n_(x8n, numElem8); real_t_view_1d y8n_(y8n, numElem8); real_t_view_1d z8n_(z8n, numElem8); CalcHourglassControlForElemsKernel f0( domain.x_view(), domain.y_view(), domain.z_view(), domain.nodelist_view(), domain.v_view(), domain.volo_view(), determ, dvdx_, dvdy_, dvdz_, x8n_, y8n_, z8n_, numElem ); Kokkos::parallel_for(f0.numElem, f0); if ( hgcoef > Real_t(0.) ) { CalcFBHourglassForceForElems( domain, determ, x8n, y8n, z8n, dvdx, dvdy, dvdz, hgcoef, numElem, domain.numNode()) ; } Release(&z8n) ; Release(&y8n) ; Release(&x8n) ; Release(&dvdz) ; Release(&dvdy) ; Release(&dvdx) ; return ; } /******************************************/ struct CalcVolumeForceForElemsCheckError { Index_t numElem; real_t_view_1d determ; CalcVolumeForceForElemsCheckError(real_t_view_1d determ_, Index_t& numElem_): determ(determ_), numElem(numElem_) {} KOKKOS_INLINE_FUNCTION void operator() (const int& i) const { if (determ[i] <= Real_t(0.0)) { #if USE_MPI MPI_Abort(MPI_COMM_WORLD, VolumeError) ; #else exit(VolumeError); #endif } } }; static inline void CalcVolumeForceForElems(Domain& domain) { Index_t numElem = domain.numElem() ; if (numElem != 0) { Real_t hgcoef = domain.hgcoef() ; Real_t *sigxx = Allocate<Real_t>(numElem) ; Real_t *sigyy = Allocate<Real_t>(numElem) ; Real_t *sigzz = Allocate<Real_t>(numElem) ; Real_t *determ = Allocate<Real_t>(numElem) ; real_t_view_1d sigxx_(sigxx, numElem); real_t_view_1d sigyy_(sigyy, numElem); real_t_view_1d sigzz_(sigzz, numElem); /* Sum contributions to total stress tensor */ InitStressTermsForElems f0(domain.p_view(), domain.q_view(), sigxx_, sigyy_, sigzz_, numElem); Kokkos::parallel_for(f0.numElem, f0); real_t_view_1d determ_(determ, numElem); // call elemlib stress integration loop to produce nodal forces from // material stresses. IntegrateStressForElems( domain, sigxx_, sigyy_, sigzz_, determ_, numElem, domain.numNode()) ; CalcVolumeForceForElemsCheckError f1(determ_, numElem); Kokkos::parallel_for(f1.numElem, f1); CalcHourglassControlForElems(domain, determ_, hgcoef) ; Release(&determ) ; Release(&sigzz) ; Release(&sigyy) ; Release(&sigxx) ; } } /******************************************/ static inline void CalcForceForNodes(Domain& domain) { Index_t numNode = domain.numNode() ; #if USE_MPI CommRecv(domain, MSG_COMM_SBN, 3, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, true, false) ; #endif #pragma omp parallel for firstprivate(numNode) for (Index_t i=0; i<numNode; ++i) { domain.fx(i) = Real_t(0.0) ; domain.fy(i) = Real_t(0.0) ; domain.fz(i) = Real_t(0.0) ; } /* Calcforce calls partial, force, hourq */ CalcVolumeForceForElems(domain) ; #if USE_MPI Domain_member fieldData[3] ; fieldData[0] = &Domain::fx ; fieldData[1] = &Domain::fy ; fieldData[2] = &Domain::fz ; CommSend(domain, MSG_COMM_SBN, 3, fieldData, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, true, false) ; CommSBN(domain, 3, fieldData) ; #endif } /******************************************/ static inline void CalcAccelerationForNodes(Domain &domain, Index_t numNode) { #pragma omp parallel for firstprivate(numNode) for (Index_t i = 0; i < numNode; ++i) { domain.xdd(i) = domain.fx(i) / domain.nodalMass(i); domain.ydd(i) = domain.fy(i) / domain.nodalMass(i); domain.zdd(i) = domain.fz(i) / domain.nodalMass(i); } } /******************************************/ static inline void ApplyAccelerationBoundaryConditionsForNodes(Domain& domain) { Index_t size = domain.sizeX(); Index_t numNodeBC = (size+1)*(size+1) ; #pragma omp parallel { if (!domain.symmXempty() != 0) { #pragma omp for nowait firstprivate(numNodeBC) for(Index_t i=0 ; i<numNodeBC ; ++i) domain.xdd(domain.symmX(i)) = Real_t(0.0) ; } if (!domain.symmYempty() != 0) { #pragma omp for nowait firstprivate(numNodeBC) for(Index_t i=0 ; i<numNodeBC ; ++i) domain.ydd(domain.symmY(i)) = Real_t(0.0) ; } if (!domain.symmZempty() != 0) { #pragma omp for nowait firstprivate(numNodeBC) for(Index_t i=0 ; i<numNodeBC ; ++i) domain.zdd(domain.symmZ(i)) = Real_t(0.0) ; } } } /******************************************/ static inline void CalcVelocityForNodes(Domain &domain, const Real_t dt, const Real_t u_cut, Index_t numNode) { #pragma omp parallel for firstprivate(numNode) for ( Index_t i = 0 ; i < numNode ; ++i ) { Real_t xdtmp, ydtmp, zdtmp ; xdtmp = domain.xd(i) + domain.xdd(i) * dt ; if( FABS(xdtmp) < u_cut ) xdtmp = Real_t(0.0); domain.xd(i) = xdtmp ; ydtmp = domain.yd(i) + domain.ydd(i) * dt ; if( FABS(ydtmp) < u_cut ) ydtmp = Real_t(0.0); domain.yd(i) = ydtmp ; zdtmp = domain.zd(i) + domain.zdd(i) * dt ; if( FABS(zdtmp) < u_cut ) zdtmp = Real_t(0.0); domain.zd(i) = zdtmp ; } } /******************************************/ static inline void CalcPositionForNodes(Domain &domain, const Real_t dt, Index_t numNode) { #pragma omp parallel for firstprivate(numNode) for ( Index_t i = 0 ; i < numNode ; ++i ) { domain.x(i) += domain.xd(i) * dt ; domain.y(i) += domain.yd(i) * dt ; domain.z(i) += domain.zd(i) * dt ; } } /******************************************/ static inline void LagrangeNodal(Domain& domain) { #ifdef SEDOV_SYNC_POS_VEL_EARLY Domain_member fieldData[6] ; #endif const Real_t delt = domain.deltatime() ; Real_t u_cut = domain.u_cut() ; /* time of boundary condition evaluation is beginning of step for force and * acceleration boundary conditions. */ CalcForceForNodes(domain); #if USE_MPI #ifdef SEDOV_SYNC_POS_VEL_EARLY CommRecv(domain, MSG_SYNC_POS_VEL, 6, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, false, false) ; #endif #endif CalcAccelerationForNodes(domain, domain.numNode()); ApplyAccelerationBoundaryConditionsForNodes(domain); CalcVelocityForNodes( domain, delt, u_cut, domain.numNode()) ; CalcPositionForNodes( domain, delt, domain.numNode() ); #if USE_MPI #ifdef SEDOV_SYNC_POS_VEL_EARLY fieldData[0] = &Domain::x ; fieldData[1] = &Domain::y ; fieldData[2] = &Domain::z ; fieldData[3] = &Domain::xd ; fieldData[4] = &Domain::yd ; fieldData[5] = &Domain::zd ; CommSend(domain, MSG_SYNC_POS_VEL, 6, fieldData, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, false, false) ; CommSyncPosVel(domain) ; #endif #endif return; } /******************************************/ static inline Real_t CalcElemVolume( const Real_t x0, const Real_t x1, const Real_t x2, const Real_t x3, const Real_t x4, const Real_t x5, const Real_t x6, const Real_t x7, const Real_t y0, const Real_t y1, const Real_t y2, const Real_t y3, const Real_t y4, const Real_t y5, const Real_t y6, const Real_t y7, const Real_t z0, const Real_t z1, const Real_t z2, const Real_t z3, const Real_t z4, const Real_t z5, const Real_t z6, const Real_t z7 ) { Real_t twelveth = Real_t(1.0)/Real_t(12.0); Real_t dx61 = x6 - x1; Real_t dy61 = y6 - y1; Real_t dz61 = z6 - z1; Real_t dx70 = x7 - x0; Real_t dy70 = y7 - y0; Real_t dz70 = z7 - z0; Real_t dx63 = x6 - x3; Real_t dy63 = y6 - y3; Real_t dz63 = z6 - z3; Real_t dx20 = x2 - x0; Real_t dy20 = y2 - y0; Real_t dz20 = z2 - z0; Real_t dx50 = x5 - x0; Real_t dy50 = y5 - y0; Real_t dz50 = z5 - z0; Real_t dx64 = x6 - x4; Real_t dy64 = y6 - y4; Real_t dz64 = z6 - z4; Real_t dx31 = x3 - x1; Real_t dy31 = y3 - y1; Real_t dz31 = z3 - z1; Real_t dx72 = x7 - x2; Real_t dy72 = y7 - y2; Real_t dz72 = z7 - z2; Real_t dx43 = x4 - x3; Real_t dy43 = y4 - y3; Real_t dz43 = z4 - z3; Real_t dx57 = x5 - x7; Real_t dy57 = y5 - y7; Real_t dz57 = z5 - z7; Real_t dx14 = x1 - x4; Real_t dy14 = y1 - y4; Real_t dz14 = z1 - z4; Real_t dx25 = x2 - x5; Real_t dy25 = y2 - y5; Real_t dz25 = z2 - z5; #define TRIPLE_PRODUCT(x1, y1, z1, x2, y2, z2, x3, y3, z3) \ ((x1)*((y2)*(z3) - (z2)*(y3)) + (x2)*((z1)*(y3) - (y1)*(z3)) + (x3)*((y1)*(z2) - (z1)*(y2))) Real_t volume = TRIPLE_PRODUCT(dx31 + dx72, dx63, dx20, dy31 + dy72, dy63, dy20, dz31 + dz72, dz63, dz20) + TRIPLE_PRODUCT(dx43 + dx57, dx64, dx70, dy43 + dy57, dy64, dy70, dz43 + dz57, dz64, dz70) + TRIPLE_PRODUCT(dx14 + dx25, dx61, dx50, dy14 + dy25, dy61, dy50, dz14 + dz25, dz61, dz50); #undef TRIPLE_PRODUCT volume *= twelveth; return volume ; } /******************************************/ //inline Real_t CalcElemVolume( const Real_t x[8], const Real_t y[8], const Real_t z[8] ) { return CalcElemVolume( x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], z[0], z[1], z[2], z[3], z[4], z[5], z[6], z[7]); } /******************************************/ static inline Real_t AreaFace( const Real_t x0, const Real_t x1, const Real_t x2, const Real_t x3, const Real_t y0, const Real_t y1, const Real_t y2, const Real_t y3, const Real_t z0, const Real_t z1, const Real_t z2, const Real_t z3) { Real_t fx = (x2 - x0) - (x3 - x1); Real_t fy = (y2 - y0) - (y3 - y1); Real_t fz = (z2 - z0) - (z3 - z1); Real_t gx = (x2 - x0) + (x3 - x1); Real_t gy = (y2 - y0) + (y3 - y1); Real_t gz = (z2 - z0) + (z3 - z1); Real_t area = (fx * fx + fy * fy + fz * fz) * (gx * gx + gy * gy + gz * gz) - (fx * gx + fy * gy + fz * gz) * (fx * gx + fy * gy + fz * gz); return area ; } /******************************************/ static inline Real_t CalcElemCharacteristicLength( const Real_t x[8], const Real_t y[8], const Real_t z[8], const Real_t volume) { Real_t a, charLength = Real_t(0.0); a = AreaFace(x[0],x[1],x[2],x[3], y[0],y[1],y[2],y[3], z[0],z[1],z[2],z[3]) ; charLength = std::max(a,charLength) ; a = AreaFace(x[4],x[5],x[6],x[7], y[4],y[5],y[6],y[7], z[4],z[5],z[6],z[7]) ; charLength = std::max(a,charLength) ; a = AreaFace(x[0],x[1],x[5],x[4], y[0],y[1],y[5],y[4], z[0],z[1],z[5],z[4]) ; charLength = std::max(a,charLength) ; a = AreaFace(x[1],x[2],x[6],x[5], y[1],y[2],y[6],y[5], z[1],z[2],z[6],z[5]) ; charLength = std::max(a,charLength) ; a = AreaFace(x[2],x[3],x[7],x[6], y[2],y[3],y[7],y[6], z[2],z[3],z[7],z[6]) ; charLength = std::max(a,charLength) ; a = AreaFace(x[3],x[0],x[4],x[7], y[3],y[0],y[4],y[7], z[3],z[0],z[4],z[7]) ; charLength = std::max(a,charLength) ; charLength = Real_t(4.0) * volume / SQRT(charLength); return charLength; } /******************************************/ static inline void CalcElemVelocityGradient( const Real_t* const xvel, const Real_t* const yvel, const Real_t* const zvel, const Real_t b[][8], const Real_t detJ, Real_t* const d ) { const Real_t inv_detJ = Real_t(1.0) / detJ ; Real_t dyddx, dxddy, dzddx, dxddz, dzddy, dyddz; const Real_t* const pfx = b[0]; const Real_t* const pfy = b[1]; const Real_t* const pfz = b[2]; d[0] = inv_detJ * ( pfx[0] * (xvel[0]-xvel[6]) + pfx[1] * (xvel[1]-xvel[7]) + pfx[2] * (xvel[2]-xvel[4]) + pfx[3] * (xvel[3]-xvel[5]) ); d[1] = inv_detJ * ( pfy[0] * (yvel[0]-yvel[6]) + pfy[1] * (yvel[1]-yvel[7]) + pfy[2] * (yvel[2]-yvel[4]) + pfy[3] * (yvel[3]-yvel[5]) ); d[2] = inv_detJ * ( pfz[0] * (zvel[0]-zvel[6]) + pfz[1] * (zvel[1]-zvel[7]) + pfz[2] * (zvel[2]-zvel[4]) + pfz[3] * (zvel[3]-zvel[5]) ); dyddx = inv_detJ * ( pfx[0] * (yvel[0]-yvel[6]) + pfx[1] * (yvel[1]-yvel[7]) + pfx[2] * (yvel[2]-yvel[4]) + pfx[3] * (yvel[3]-yvel[5]) ); dxddy = inv_detJ * ( pfy[0] * (xvel[0]-xvel[6]) + pfy[1] * (xvel[1]-xvel[7]) + pfy[2] * (xvel[2]-xvel[4]) + pfy[3] * (xvel[3]-xvel[5]) ); dzddx = inv_detJ * ( pfx[0] * (zvel[0]-zvel[6]) + pfx[1] * (zvel[1]-zvel[7]) + pfx[2] * (zvel[2]-zvel[4]) + pfx[3] * (zvel[3]-zvel[5]) ); dxddz = inv_detJ * ( pfz[0] * (xvel[0]-xvel[6]) + pfz[1] * (xvel[1]-xvel[7]) + pfz[2] * (xvel[2]-xvel[4]) + pfz[3] * (xvel[3]-xvel[5]) ); dzddy = inv_detJ * ( pfy[0] * (zvel[0]-zvel[6]) + pfy[1] * (zvel[1]-zvel[7]) + pfy[2] * (zvel[2]-zvel[4]) + pfy[3] * (zvel[3]-zvel[5]) ); dyddz = inv_detJ * ( pfz[0] * (yvel[0]-yvel[6]) + pfz[1] * (yvel[1]-yvel[7]) + pfz[2] * (yvel[2]-yvel[4]) + pfz[3] * (yvel[3]-yvel[5]) ); d[5] = Real_t( .5) * ( dxddy + dyddx ); d[4] = Real_t( .5) * ( dxddz + dzddx ); d[3] = Real_t( .5) * ( dzddy + dyddz ); } /******************************************/ //static inline void CalcKinematicsForElems( Domain &domain, Real_t *vnew, Real_t deltaTime, Index_t numElem ) { // loop over all elements #pragma omp parallel for firstprivate(numElem, deltaTime) for( Index_t k=0 ; k<numElem ; ++k ) { Real_t B[3][8] ; /** shape function derivatives */ Real_t D[6] ; Real_t x_local[8] ; Real_t y_local[8] ; Real_t z_local[8] ; Real_t xd_local[8] ; Real_t yd_local[8] ; Real_t zd_local[8] ; Real_t detJ = Real_t(0.0) ; Real_t volume ; Real_t relativeVolume ; const Index_t* const elemToNode = domain.nodelist(k) ; // get nodal coordinates from global arrays and copy into local arrays. CollectDomainNodesToElemNodes(domain, elemToNode, x_local, y_local, z_local); // volume calculations volume = CalcElemVolume(x_local, y_local, z_local ); relativeVolume = volume / domain.volo(k) ; vnew[k] = relativeVolume ; domain.delv(k) = relativeVolume - domain.v(k) ; // set characteristic length domain.arealg(k) = CalcElemCharacteristicLength(x_local, y_local, z_local, volume); // get nodal velocities from global array and copy into local arrays. for( Index_t lnode=0 ; lnode<8 ; ++lnode ) { Index_t gnode = elemToNode[lnode]; xd_local[lnode] = domain.xd(gnode); yd_local[lnode] = domain.yd(gnode); zd_local[lnode] = domain.zd(gnode); } Real_t dt2 = Real_t(0.5) * deltaTime; for ( Index_t j=0 ; j<8 ; ++j ) { x_local[j] -= dt2 * xd_local[j]; y_local[j] -= dt2 * yd_local[j]; z_local[j] -= dt2 * zd_local[j]; } CalcElemShapeFunctionDerivatives( x_local, y_local, z_local, B, &detJ ); CalcElemVelocityGradient( xd_local, yd_local, zd_local, B, detJ, D ); // put velocity gradient quantities into their global arrays. domain.dxx(k) = D[0]; domain.dyy(k) = D[1]; domain.dzz(k) = D[2]; } } /******************************************/ static inline void CalcLagrangeElements(Domain& domain, Real_t* vnew) { Index_t numElem = domain.numElem() ; if (numElem > 0) { const Real_t deltatime = domain.deltatime() ; domain.AllocateStrains(numElem); CalcKinematicsForElems(domain, vnew, deltatime, numElem) ; // element loop to do some stuff not included in the elemlib function. #pragma omp parallel for firstprivate(numElem) for ( Index_t k=0 ; k<numElem ; ++k ) { // calc strain rate and apply as constraint (only done in FB element) Real_t vdov = domain.dxx(k) + domain.dyy(k) + domain.dzz(k) ; Real_t vdovthird = vdov/Real_t(3.0) ; // make the rate of deformation tensor deviatoric domain.vdov(k) = vdov ; domain.dxx(k) -= vdovthird ; domain.dyy(k) -= vdovthird ; domain.dzz(k) -= vdovthird ; // See if any volumes are negative, and take appropriate action. if (vnew[k] <= Real_t(0.0)) { #if USE_MPI MPI_Abort(MPI_COMM_WORLD, VolumeError) ; #else exit(VolumeError); #endif } } domain.DeallocateStrains(); } } /******************************************/ static inline void CalcMonotonicQGradientsForElems(Domain& domain, Real_t vnew[]) { Index_t numElem = domain.numElem(); #pragma omp parallel for firstprivate(numElem) for (Index_t i = 0 ; i < numElem ; ++i ) { const Real_t ptiny = Real_t(1.e-36) ; Real_t ax,ay,az ; Real_t dxv,dyv,dzv ; const Index_t *elemToNode = domain.nodelist(i); Index_t n0 = elemToNode[0] ; Index_t n1 = elemToNode[1] ; Index_t n2 = elemToNode[2] ; Index_t n3 = elemToNode[3] ; Index_t n4 = elemToNode[4] ; Index_t n5 = elemToNode[5] ; Index_t n6 = elemToNode[6] ; Index_t n7 = elemToNode[7] ; Real_t x0 = domain.x(n0) ; Real_t x1 = domain.x(n1) ; Real_t x2 = domain.x(n2) ; Real_t x3 = domain.x(n3) ; Real_t x4 = domain.x(n4) ; Real_t x5 = domain.x(n5) ; Real_t x6 = domain.x(n6) ; Real_t x7 = domain.x(n7) ; Real_t y0 = domain.y(n0) ; Real_t y1 = domain.y(n1) ; Real_t y2 = domain.y(n2) ; Real_t y3 = domain.y(n3) ; Real_t y4 = domain.y(n4) ; Real_t y5 = domain.y(n5) ; Real_t y6 = domain.y(n6) ; Real_t y7 = domain.y(n7) ; Real_t z0 = domain.z(n0) ; Real_t z1 = domain.z(n1) ; Real_t z2 = domain.z(n2) ; Real_t z3 = domain.z(n3) ; Real_t z4 = domain.z(n4) ; Real_t z5 = domain.z(n5) ; Real_t z6 = domain.z(n6) ; Real_t z7 = domain.z(n7) ; Real_t xv0 = domain.xd(n0) ; Real_t xv1 = domain.xd(n1) ; Real_t xv2 = domain.xd(n2) ; Real_t xv3 = domain.xd(n3) ; Real_t xv4 = domain.xd(n4) ; Real_t xv5 = domain.xd(n5) ; Real_t xv6 = domain.xd(n6) ; Real_t xv7 = domain.xd(n7) ; Real_t yv0 = domain.yd(n0) ; Real_t yv1 = domain.yd(n1) ; Real_t yv2 = domain.yd(n2) ; Real_t yv3 = domain.yd(n3) ; Real_t yv4 = domain.yd(n4) ; Real_t yv5 = domain.yd(n5) ; Real_t yv6 = domain.yd(n6) ; Real_t yv7 = domain.yd(n7) ; Real_t zv0 = domain.zd(n0) ; Real_t zv1 = domain.zd(n1) ; Real_t zv2 = domain.zd(n2) ; Real_t zv3 = domain.zd(n3) ; Real_t zv4 = domain.zd(n4) ; Real_t zv5 = domain.zd(n5) ; Real_t zv6 = domain.zd(n6) ; Real_t zv7 = domain.zd(n7) ; Real_t vol = domain.volo(i)*vnew[i] ; Real_t norm = Real_t(1.0) / ( vol + ptiny ) ; Real_t dxj = Real_t(-0.25)*((x0+x1+x5+x4) - (x3+x2+x6+x7)) ; Real_t dyj = Real_t(-0.25)*((y0+y1+y5+y4) - (y3+y2+y6+y7)) ; Real_t dzj = Real_t(-0.25)*((z0+z1+z5+z4) - (z3+z2+z6+z7)) ; Real_t dxi = Real_t( 0.25)*((x1+x2+x6+x5) - (x0+x3+x7+x4)) ; Real_t dyi = Real_t( 0.25)*((y1+y2+y6+y5) - (y0+y3+y7+y4)) ; Real_t dzi = Real_t( 0.25)*((z1+z2+z6+z5) - (z0+z3+z7+z4)) ; Real_t dxk = Real_t( 0.25)*((x4+x5+x6+x7) - (x0+x1+x2+x3)) ; Real_t dyk = Real_t( 0.25)*((y4+y5+y6+y7) - (y0+y1+y2+y3)) ; Real_t dzk = Real_t( 0.25)*((z4+z5+z6+z7) - (z0+z1+z2+z3)) ; /* find delvk and delxk ( i cross j ) */ ax = dyi*dzj - dzi*dyj ; ay = dzi*dxj - dxi*dzj ; az = dxi*dyj - dyi*dxj ; domain.delx_zeta(i) = vol / SQRT(ax*ax + ay*ay + az*az + ptiny) ; ax *= norm ; ay *= norm ; az *= norm ; dxv = Real_t(0.25)*((xv4+xv5+xv6+xv7) - (xv0+xv1+xv2+xv3)) ; dyv = Real_t(0.25)*((yv4+yv5+yv6+yv7) - (yv0+yv1+yv2+yv3)) ; dzv = Real_t(0.25)*((zv4+zv5+zv6+zv7) - (zv0+zv1+zv2+zv3)) ; domain.delv_zeta(i) = ax*dxv + ay*dyv + az*dzv ; /* find delxi and delvi ( j cross k ) */ ax = dyj*dzk - dzj*dyk ; ay = dzj*dxk - dxj*dzk ; az = dxj*dyk - dyj*dxk ; domain.delx_xi(i) = vol / SQRT(ax*ax + ay*ay + az*az + ptiny) ; ax *= norm ; ay *= norm ; az *= norm ; dxv = Real_t(0.25)*((xv1+xv2+xv6+xv5) - (xv0+xv3+xv7+xv4)) ; dyv = Real_t(0.25)*((yv1+yv2+yv6+yv5) - (yv0+yv3+yv7+yv4)) ; dzv = Real_t(0.25)*((zv1+zv2+zv6+zv5) - (zv0+zv3+zv7+zv4)) ; domain.delv_xi(i) = ax*dxv + ay*dyv + az*dzv ; /* find delxj and delvj ( k cross i ) */ ax = dyk*dzi - dzk*dyi ; ay = dzk*dxi - dxk*dzi ; az = dxk*dyi - dyk*dxi ; domain.delx_eta(i) = vol / SQRT(ax*ax + ay*ay + az*az + ptiny) ; ax *= norm ; ay *= norm ; az *= norm ; dxv = Real_t(-0.25)*((xv0+xv1+xv5+xv4) - (xv3+xv2+xv6+xv7)) ; dyv = Real_t(-0.25)*((yv0+yv1+yv5+yv4) - (yv3+yv2+yv6+yv7)) ; dzv = Real_t(-0.25)*((zv0+zv1+zv5+zv4) - (zv3+zv2+zv6+zv7)) ; domain.delv_eta(i) = ax*dxv + ay*dyv + az*dzv ; } } /******************************************/ static inline void CalcMonotonicQRegionForElems(Domain &domain, Int_t r, Real_t vnew[], Real_t ptiny) { Real_t monoq_limiter_mult = domain.monoq_limiter_mult(); Real_t monoq_max_slope = domain.monoq_max_slope(); Real_t qlc_monoq = domain.qlc_monoq(); Real_t qqc_monoq = domain.qqc_monoq(); #pragma omp parallel for firstprivate(qlc_monoq, qqc_monoq, monoq_limiter_mult, monoq_max_slope, ptiny) for ( Index_t ielem = 0 ; ielem < domain.regElemSize(r); ++ielem ) { Index_t i = domain.regElemlist(r,ielem); Real_t qlin, qquad ; Real_t phixi, phieta, phizeta ; Int_t bcMask = domain.elemBC(i) ; Real_t delvm = 0.0, delvp =0.0; /* phixi */ Real_t norm = Real_t(1.) / (domain.delv_xi(i)+ ptiny ) ; switch (bcMask & XI_M) { case XI_M_COMM: /* needs comm data */ case 0: delvm = domain.delv_xi(domain.lxim(i)); break ; case XI_M_SYMM: delvm = domain.delv_xi(i) ; break ; case XI_M_FREE: delvm = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvm = 0; /* ERROR - but quiets the compiler */ break; } switch (bcMask & XI_P) { case XI_P_COMM: /* needs comm data */ case 0: delvp = domain.delv_xi(domain.lxip(i)) ; break ; case XI_P_SYMM: delvp = domain.delv_xi(i) ; break ; case XI_P_FREE: delvp = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvp = 0; /* ERROR - but quiets the compiler */ break; } delvm = delvm * norm ; delvp = delvp * norm ; phixi = Real_t(.5) * ( delvm + delvp ) ; delvm *= monoq_limiter_mult ; delvp *= monoq_limiter_mult ; if ( delvm < phixi ) phixi = delvm ; if ( delvp < phixi ) phixi = delvp ; if ( phixi < Real_t(0.)) phixi = Real_t(0.) ; if ( phixi > monoq_max_slope) phixi = monoq_max_slope; /* phieta */ norm = Real_t(1.) / ( domain.delv_eta(i) + ptiny ) ; switch (bcMask & ETA_M) { case ETA_M_COMM: /* needs comm data */ case 0: delvm = domain.delv_eta(domain.letam(i)) ; break ; case ETA_M_SYMM: delvm = domain.delv_eta(i) ; break ; case ETA_M_FREE: delvm = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvm = 0; /* ERROR - but quiets the compiler */ break; } switch (bcMask & ETA_P) { case ETA_P_COMM: /* needs comm data */ case 0: delvp = domain.delv_eta(domain.letap(i)) ; break ; case ETA_P_SYMM: delvp = domain.delv_eta(i) ; break ; case ETA_P_FREE: delvp = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvp = 0; /* ERROR - but quiets the compiler */ break; } delvm = delvm * norm ; delvp = delvp * norm ; phieta = Real_t(.5) * ( delvm + delvp ) ; delvm *= monoq_limiter_mult ; delvp *= monoq_limiter_mult ; if ( delvm < phieta ) phieta = delvm ; if ( delvp < phieta ) phieta = delvp ; if ( phieta < Real_t(0.)) phieta = Real_t(0.) ; if ( phieta > monoq_max_slope) phieta = monoq_max_slope; /* phizeta */ norm = Real_t(1.) / ( domain.delv_zeta(i) + ptiny ) ; switch (bcMask & ZETA_M) { case ZETA_M_COMM: /* needs comm data */ case 0: delvm = domain.delv_zeta(domain.lzetam(i)) ; break ; case ZETA_M_SYMM: delvm = domain.delv_zeta(i) ; break ; case ZETA_M_FREE: delvm = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvm = 0; /* ERROR - but quiets the compiler */ break; } switch (bcMask & ZETA_P) { case ZETA_P_COMM: /* needs comm data */ case 0: delvp = domain.delv_zeta(domain.lzetap(i)) ; break ; case ZETA_P_SYMM: delvp = domain.delv_zeta(i) ; break ; case ZETA_P_FREE: delvp = Real_t(0.0) ; break ; default: fprintf(stderr, "Error in switch at %s line %d\n", __FILE__, __LINE__); delvp = 0; /* ERROR - but quiets the compiler */ break; } delvm = delvm * norm ; delvp = delvp * norm ; phizeta = Real_t(.5) * ( delvm + delvp ) ; delvm *= monoq_limiter_mult ; delvp *= monoq_limiter_mult ; if ( delvm < phizeta ) phizeta = delvm ; if ( delvp < phizeta ) phizeta = delvp ; if ( phizeta < Real_t(0.)) phizeta = Real_t(0.); if ( phizeta > monoq_max_slope ) phizeta = monoq_max_slope; /* Remove length scale */ if ( domain.vdov(i) > Real_t(0.) ) { qlin = Real_t(0.) ; qquad = Real_t(0.) ; } else { Real_t delvxxi = domain.delv_xi(i) * domain.delx_xi(i) ; Real_t delvxeta = domain.delv_eta(i) * domain.delx_eta(i) ; Real_t delvxzeta = domain.delv_zeta(i) * domain.delx_zeta(i) ; if ( delvxxi > Real_t(0.) ) delvxxi = Real_t(0.) ; if ( delvxeta > Real_t(0.) ) delvxeta = Real_t(0.) ; if ( delvxzeta > Real_t(0.) ) delvxzeta = Real_t(0.) ; Real_t rho = domain.elemMass(i) / (domain.volo(i) * vnew[i]) ; qlin = -qlc_monoq * rho * ( delvxxi * (Real_t(1.) - phixi) + delvxeta * (Real_t(1.) - phieta) + delvxzeta * (Real_t(1.) - phizeta) ) ; qquad = qqc_monoq * rho * ( delvxxi*delvxxi * (Real_t(1.) - phixi*phixi) + delvxeta*delvxeta * (Real_t(1.) - phieta*phieta) + delvxzeta*delvxzeta * (Real_t(1.) - phizeta*phizeta) ) ; } domain.qq(i) = qquad ; domain.ql(i) = qlin ; } } /******************************************/ static inline void CalcMonotonicQForElems(Domain& domain, Real_t vnew[]) { // // initialize parameters // const Real_t ptiny = Real_t(1.e-36) ; // // calculate the monotonic q for all regions // for (Index_t r=0 ; r<domain.numReg() ; ++r) { if (domain.regElemSize(r) > 0) { CalcMonotonicQRegionForElems(domain, r, vnew, ptiny) ; } } } /******************************************/ static inline void CalcQForElems(Domain& domain, Real_t vnew[]) { // // MONOTONIC Q option // Index_t numElem = domain.numElem() ; if (numElem != 0) { Int_t allElem = numElem + /* local elem */ 2*domain.sizeX()*domain.sizeY() + /* plane ghosts */ 2*domain.sizeX()*domain.sizeZ() + /* row ghosts */ 2*domain.sizeY()*domain.sizeZ() ; /* col ghosts */ domain.AllocateGradients(numElem, allElem); #if USE_MPI CommRecv(domain, MSG_MONOQ, 3, domain.sizeX(), domain.sizeY(), domain.sizeZ(), true, true) ; #endif /* Calculate velocity gradients */ CalcMonotonicQGradientsForElems(domain, vnew); #if USE_MPI Domain_member fieldData[3] ; /* Transfer veloctiy gradients in the first order elements */ /* problem->commElements->Transfer(CommElements::monoQ) ; */ fieldData[0] = &Domain::delv_xi ; fieldData[1] = &Domain::delv_eta ; fieldData[2] = &Domain::delv_zeta ; CommSend(domain, MSG_MONOQ, 3, fieldData, domain.sizeX(), domain.sizeY(), domain.sizeZ(), true, true) ; CommMonoQ(domain) ; #endif CalcMonotonicQForElems(domain, vnew) ; // Free up memory domain.DeallocateGradients(); /* Don't allow excessive artificial viscosity */ Index_t idx = -1; for (Index_t i=0; i<numElem; ++i) { if ( domain.q(i) > domain.qstop() ) { idx = i ; break ; } } if(idx >= 0) { #if USE_MPI MPI_Abort(MPI_COMM_WORLD, QStopError) ; #else exit(QStopError); #endif } } } /******************************************/ static inline void CalcPressureForElems(Real_t* p_new, Real_t* bvc, Real_t* pbvc, Real_t* e_old, Real_t* compression, Real_t *vnewc, Real_t pmin, Real_t p_cut, Real_t eosvmax, Index_t length, Index_t *regElemList) { #pragma omp parallel for firstprivate(length) for (Index_t i = 0; i < length ; ++i) { Real_t c1s = Real_t(2.0)/Real_t(3.0) ; bvc[i] = c1s * (compression[i] + Real_t(1.)); pbvc[i] = c1s; } #pragma omp parallel for firstprivate(length, pmin, p_cut, eosvmax) for (Index_t i = 0 ; i < length ; ++i){ Index_t elem = regElemList[i]; p_new[i] = bvc[i] * e_old[i] ; if (FABS(p_new[i]) < p_cut ) p_new[i] = Real_t(0.0) ; if ( vnewc[elem] >= eosvmax ) /* impossible condition here? */ p_new[i] = Real_t(0.0) ; if (p_new[i] < pmin) p_new[i] = pmin ; } } /******************************************/ static inline void CalcEnergyForElems(Real_t* p_new, Real_t* e_new, Real_t* q_new, Real_t* bvc, Real_t* pbvc, Real_t* p_old, Real_t* e_old, Real_t* q_old, Real_t* compression, Real_t* compHalfStep, Real_t* vnewc, Real_t* work, Real_t* delvc, Real_t pmin, Real_t p_cut, Real_t e_cut, Real_t q_cut, Real_t emin, Real_t* qq_old, Real_t* ql_old, Real_t rho0, Real_t eosvmax, Index_t length, Index_t *regElemList) { Real_t *pHalfStep = Allocate<Real_t>(length) ; #pragma omp parallel for firstprivate(length, emin) for (Index_t i = 0 ; i < length ; ++i) { e_new[i] = e_old[i] - Real_t(0.5) * delvc[i] * (p_old[i] + q_old[i]) + Real_t(0.5) * work[i]; if (e_new[i] < emin ) { e_new[i] = emin ; } } CalcPressureForElems(pHalfStep, bvc, pbvc, e_new, compHalfStep, vnewc, pmin, p_cut, eosvmax, length, regElemList); #pragma omp parallel for firstprivate(length, rho0) for (Index_t i = 0 ; i < length ; ++i) { Real_t vhalf = Real_t(1.) / (Real_t(1.) + compHalfStep[i]) ; if ( delvc[i] > Real_t(0.) ) { q_new[i] /* = qq_old[i] = ql_old[i] */ = Real_t(0.) ; } else { Real_t ssc = ( pbvc[i] * e_new[i] + vhalf * vhalf * bvc[i] * pHalfStep[i] ) / rho0 ; if ( ssc <= Real_t(.1111111e-36) ) { ssc = Real_t(.3333333e-18) ; } else { ssc = SQRT(ssc) ; } q_new[i] = (ssc*ql_old[i] + qq_old[i]) ; } e_new[i] = e_new[i] + Real_t(0.5) * delvc[i] * ( Real_t(3.0)*(p_old[i] + q_old[i]) - Real_t(4.0)*(pHalfStep[i] + q_new[i])) ; } #pragma omp parallel for firstprivate(length, emin, e_cut) for (Index_t i = 0 ; i < length ; ++i) { e_new[i] += Real_t(0.5) * work[i]; if (FABS(e_new[i]) < e_cut) { e_new[i] = Real_t(0.) ; } if ( e_new[i] < emin ) { e_new[i] = emin ; } } CalcPressureForElems(p_new, bvc, pbvc, e_new, compression, vnewc, pmin, p_cut, eosvmax, length, regElemList); #pragma omp parallel for firstprivate(length, rho0, emin, e_cut) for (Index_t i = 0 ; i < length ; ++i){ const Real_t sixth = Real_t(1.0) / Real_t(6.0) ; Index_t elem = regElemList[i]; Real_t q_tilde ; if (delvc[i] > Real_t(0.)) { q_tilde = Real_t(0.) ; } else { Real_t ssc = ( pbvc[i] * e_new[i] + vnewc[elem] * vnewc[elem] * bvc[i] * p_new[i] ) / rho0 ; if ( ssc <= Real_t(.1111111e-36) ) { ssc = Real_t(.3333333e-18) ; } else { ssc = SQRT(ssc) ; } q_tilde = (ssc*ql_old[i] + qq_old[i]) ; } e_new[i] = e_new[i] - ( Real_t(7.0)*(p_old[i] + q_old[i]) - Real_t(8.0)*(pHalfStep[i] + q_new[i]) + (p_new[i] + q_tilde)) * delvc[i]*sixth ; if (FABS(e_new[i]) < e_cut) { e_new[i] = Real_t(0.) ; } if ( e_new[i] < emin ) { e_new[i] = emin ; } } CalcPressureForElems(p_new, bvc, pbvc, e_new, compression, vnewc, pmin, p_cut, eosvmax, length, regElemList); #pragma omp parallel for firstprivate(length, rho0, q_cut) for (Index_t i = 0 ; i < length ; ++i){ Index_t elem = regElemList[i]; if ( delvc[i] <= Real_t(0.) ) { Real_t ssc = ( pbvc[i] * e_new[i] + vnewc[elem] * vnewc[elem] * bvc[i] * p_new[i] ) / rho0 ; if ( ssc <= Real_t(.1111111e-36) ) { ssc = Real_t(.3333333e-18) ; } else { ssc = SQRT(ssc) ; } q_new[i] = (ssc*ql_old[i] + qq_old[i]) ; if (FABS(q_new[i]) < q_cut) q_new[i] = Real_t(0.) ; } } Release(&pHalfStep) ; return ; } /******************************************/ static inline void CalcSoundSpeedForElems(Domain &domain, Real_t *vnewc, Real_t rho0, Real_t *enewc, Real_t *pnewc, Real_t *pbvc, Real_t *bvc, Real_t ss4o3, Index_t len, Index_t *regElemList) { #pragma omp parallel for firstprivate(rho0, ss4o3) for (Index_t i = 0; i < len ; ++i) { Index_t elem = regElemList[i]; Real_t ssTmp = (pbvc[i] * enewc[i] + vnewc[elem] * vnewc[elem] * bvc[i] * pnewc[i]) / rho0; if (ssTmp <= Real_t(.1111111e-36)) { ssTmp = Real_t(.3333333e-18); } else { ssTmp = SQRT(ssTmp); } domain.ss(elem) = ssTmp ; } } /******************************************/ static inline void EvalEOSForElems(Domain& domain, Real_t *vnewc, Int_t numElemReg, Index_t *regElemList, Int_t rep) { Real_t e_cut = domain.e_cut() ; Real_t p_cut = domain.p_cut() ; Real_t ss4o3 = domain.ss4o3() ; Real_t q_cut = domain.q_cut() ; Real_t eosvmax = domain.eosvmax() ; Real_t eosvmin = domain.eosvmin() ; Real_t pmin = domain.pmin() ; Real_t emin = domain.emin() ; Real_t rho0 = domain.refdens() ; // These temporaries will be of different size for // each call (due to different sized region element // lists) Real_t *e_old = Allocate<Real_t>(numElemReg) ; Real_t *delvc = Allocate<Real_t>(numElemReg) ; Real_t *p_old = Allocate<Real_t>(numElemReg) ; Real_t *q_old = Allocate<Real_t>(numElemReg) ; Real_t *compression = Allocate<Real_t>(numElemReg) ; Real_t *compHalfStep = Allocate<Real_t>(numElemReg) ; Real_t *qq_old = Allocate<Real_t>(numElemReg) ; Real_t *ql_old = Allocate<Real_t>(numElemReg) ; Real_t *work = Allocate<Real_t>(numElemReg) ; Real_t *p_new = Allocate<Real_t>(numElemReg) ; Real_t *e_new = Allocate<Real_t>(numElemReg) ; Real_t *q_new = Allocate<Real_t>(numElemReg) ; Real_t *bvc = Allocate<Real_t>(numElemReg) ; Real_t *pbvc = Allocate<Real_t>(numElemReg) ; //loop to add load imbalance based on region number for(Int_t j = 0; j < rep; j++) { /* compress data, minimal set */ #pragma omp parallel { #pragma omp for nowait firstprivate(numElemReg) for (Index_t i=0; i<numElemReg; ++i) { Index_t elem = regElemList[i]; e_old[i] = domain.e(elem) ; delvc[i] = domain.delv(elem) ; p_old[i] = domain.p(elem) ; q_old[i] = domain.q(elem) ; qq_old[i] = domain.qq(elem) ; ql_old[i] = domain.ql(elem) ; } #pragma omp for firstprivate(numElemReg) for (Index_t i = 0; i < numElemReg ; ++i) { Index_t elem = regElemList[i]; Real_t vchalf ; compression[i] = Real_t(1.) / vnewc[elem] - Real_t(1.); vchalf = vnewc[elem] - delvc[i] * Real_t(.5); compHalfStep[i] = Real_t(1.) / vchalf - Real_t(1.); } /* Check for v > eosvmax or v < eosvmin */ if ( eosvmin != Real_t(0.) ) { #pragma omp for nowait firstprivate(numElemReg, eosvmin) for(Index_t i=0 ; i<numElemReg ; ++i) { Index_t elem = regElemList[i]; if (vnewc[elem] <= eosvmin) { /* impossible due to calling func? */ compHalfStep[i] = compression[i] ; } } } if ( eosvmax != Real_t(0.) ) { #pragma omp for nowait firstprivate(numElemReg, eosvmax) for(Index_t i=0 ; i<numElemReg ; ++i) { Index_t elem = regElemList[i]; if (vnewc[elem] >= eosvmax) { /* impossible due to calling func? */ p_old[i] = Real_t(0.) ; compression[i] = Real_t(0.) ; compHalfStep[i] = Real_t(0.) ; } } } #pragma omp for nowait firstprivate(numElemReg) for (Index_t i = 0 ; i < numElemReg ; ++i) { work[i] = Real_t(0.) ; } } CalcEnergyForElems(p_new, e_new, q_new, bvc, pbvc, p_old, e_old, q_old, compression, compHalfStep, vnewc, work, delvc, pmin, p_cut, e_cut, q_cut, emin, qq_old, ql_old, rho0, eosvmax, numElemReg, regElemList); } #pragma omp parallel for firstprivate(numElemReg) for (Index_t i=0; i<numElemReg; ++i) { Index_t elem = regElemList[i]; domain.p(elem) = p_new[i] ; domain.e(elem) = e_new[i] ; domain.q(elem) = q_new[i] ; } CalcSoundSpeedForElems(domain, vnewc, rho0, e_new, p_new, pbvc, bvc, ss4o3, numElemReg, regElemList) ; Release(&pbvc) ; Release(&bvc) ; Release(&q_new) ; Release(&e_new) ; Release(&p_new) ; Release(&work) ; Release(&ql_old) ; Release(&qq_old) ; Release(&compHalfStep) ; Release(&compression) ; Release(&q_old) ; Release(&p_old) ; Release(&delvc) ; Release(&e_old) ; } /******************************************/ static inline void ApplyMaterialPropertiesForElems(Domain& domain, Real_t vnew[]) { Index_t numElem = domain.numElem() ; if (numElem != 0) { /* Expose all of the variables needed for material evaluation */ Real_t eosvmin = domain.eosvmin() ; Real_t eosvmax = domain.eosvmax() ; #pragma omp parallel { // Bound the updated relative volumes with eosvmin/max if (eosvmin != Real_t(0.)) { #pragma omp for firstprivate(numElem) for(Index_t i=0 ; i<numElem ; ++i) { if (vnew[i] < eosvmin) vnew[i] = eosvmin ; } } if (eosvmax != Real_t(0.)) { #pragma omp for nowait firstprivate(numElem) for(Index_t i=0 ; i<numElem ; ++i) { if (vnew[i] > eosvmax) vnew[i] = eosvmax ; } } // This check may not make perfect sense in LULESH, but // it's representative of something in the full code - // just leave it in, please #pragma omp for nowait firstprivate(numElem) for (Index_t i=0; i<numElem; ++i) { Real_t vc = domain.v(i) ; if (eosvmin != Real_t(0.)) { if (vc < eosvmin) vc = eosvmin ; } if (eosvmax != Real_t(0.)) { if (vc > eosvmax) vc = eosvmax ; } if (vc <= 0.) { #if USE_MPI MPI_Abort(MPI_COMM_WORLD, VolumeError) ; #else exit(VolumeError); #endif } } } for (Int_t r=0 ; r<domain.numReg() ; r++) { Index_t numElemReg = domain.regElemSize(r); Index_t *regElemList = domain.regElemlist(r); Int_t rep; //Determine load imbalance for this region //round down the number with lowest cost if(r < domain.numReg()/2) rep = 1; //you don't get an expensive region unless you at least have 5 regions else if(r < (domain.numReg() - (domain.numReg()+15)/20)) rep = 1 + domain.cost(); //very expensive regions else rep = 10 * (1+ domain.cost()); EvalEOSForElems(domain, vnew, numElemReg, regElemList, rep); } } } /******************************************/ static inline void UpdateVolumesForElems(Domain &domain, Real_t *vnew, Real_t v_cut, Index_t length) { if (length != 0) { #pragma omp parallel for firstprivate(length, v_cut) for(Index_t i=0 ; i<length ; ++i) { Real_t tmpV = vnew[i] ; if ( FABS(tmpV - Real_t(1.0)) < v_cut ) tmpV = Real_t(1.0) ; domain.v(i) = tmpV ; } } return ; } /******************************************/ static inline void LagrangeElements(Domain& domain, Index_t numElem) { Real_t *vnew = Allocate<Real_t>(numElem) ; /* new relative vol -- temp */ CalcLagrangeElements(domain, vnew) ; /* Calculate Q. (Monotonic q option requires communication) */ CalcQForElems(domain, vnew) ; ApplyMaterialPropertiesForElems(domain, vnew) ; UpdateVolumesForElems(domain, vnew, domain.v_cut(), numElem) ; Release(&vnew); } /******************************************/ static inline void CalcCourantConstraintForElems(Domain &domain, Index_t length, Index_t *regElemlist, Real_t qqc, Real_t& dtcourant) { #if _OPENMP Index_t threads = omp_get_max_threads(); static Index_t *courant_elem_per_thread; static Real_t *dtcourant_per_thread; static bool first = true; if (first) { courant_elem_per_thread = new Index_t[threads]; dtcourant_per_thread = new Real_t[threads]; first = false; } #else Index_t threads = 1; Index_t courant_elem_per_thread[1]; Real_t dtcourant_per_thread[1]; #endif #pragma omp parallel firstprivate(length, qqc) { Real_t qqc2 = Real_t(64.0) * qqc * qqc ; Real_t dtcourant_tmp = dtcourant; Index_t courant_elem = -1 ; #if _OPENMP Index_t thread_num = omp_get_thread_num(); #else Index_t thread_num = 0; #endif #pragma omp for for (Index_t i = 0 ; i < length ; ++i) { Index_t indx = regElemlist[i] ; Real_t dtf = domain.ss(indx) * domain.ss(indx) ; if ( domain.vdov(indx) < Real_t(0.) ) { dtf = dtf + qqc2 * domain.arealg(indx) * domain.arealg(indx) * domain.vdov(indx) * domain.vdov(indx) ; } dtf = SQRT(dtf) ; dtf = domain.arealg(indx) / dtf ; if (domain.vdov(indx) != Real_t(0.)) { if ( dtf < dtcourant_tmp ) { dtcourant_tmp = dtf ; courant_elem = indx ; } } } dtcourant_per_thread[thread_num] = dtcourant_tmp ; courant_elem_per_thread[thread_num] = courant_elem ; } for (Index_t i = 1; i < threads; ++i) { if (dtcourant_per_thread[i] < dtcourant_per_thread[0] ) { dtcourant_per_thread[0] = dtcourant_per_thread[i]; courant_elem_per_thread[0] = courant_elem_per_thread[i]; } } if (courant_elem_per_thread[0] != -1) { dtcourant = dtcourant_per_thread[0] ; } return ; } /******************************************/ static inline void CalcHydroConstraintForElems(Domain &domain, Index_t length, Index_t *regElemlist, Real_t dvovmax, Real_t& dthydro) { #if _OPENMP Index_t threads = omp_get_max_threads(); static Index_t *hydro_elem_per_thread; static Real_t *dthydro_per_thread; static bool first = true; if (first) { hydro_elem_per_thread = new Index_t[threads]; dthydro_per_thread = new Real_t[threads]; first = false; } #else Index_t threads = 1; Index_t hydro_elem_per_thread[1]; Real_t dthydro_per_thread[1]; #endif #pragma omp parallel firstprivate(length, dvovmax) { Real_t dthydro_tmp = dthydro ; Index_t hydro_elem = -1 ; #if _OPENMP Index_t thread_num = omp_get_thread_num(); #else Index_t thread_num = 0; #endif #pragma omp for for (Index_t i = 0 ; i < length ; ++i) { Index_t indx = regElemlist[i] ; if (domain.vdov(indx) != Real_t(0.)) { Real_t dtdvov = dvovmax / (FABS(domain.vdov(indx))+Real_t(1.e-20)) ; if ( dthydro_tmp > dtdvov ) { dthydro_tmp = dtdvov ; hydro_elem = indx ; } } } dthydro_per_thread[thread_num] = dthydro_tmp ; hydro_elem_per_thread[thread_num] = hydro_elem ; } for (Index_t i = 1; i < threads; ++i) { if(dthydro_per_thread[i] < dthydro_per_thread[0]) { dthydro_per_thread[0] = dthydro_per_thread[i]; hydro_elem_per_thread[0] = hydro_elem_per_thread[i]; } } if (hydro_elem_per_thread[0] != -1) { dthydro = dthydro_per_thread[0] ; } return ; } /******************************************/ static inline void CalcTimeConstraintsForElems(Domain& domain) { // Initialize conditions to a very large value domain.dtcourant() = 1.0e+20; domain.dthydro() = 1.0e+20; for (Index_t r=0 ; r < domain.numReg() ; ++r) { /* evaluate time constraint */ CalcCourantConstraintForElems(domain, domain.regElemSize(r), domain.regElemlist(r), domain.qqc(), domain.dtcourant()) ; /* check hydro constraint */ CalcHydroConstraintForElems(domain, domain.regElemSize(r), domain.regElemlist(r), domain.dvovmax(), domain.dthydro()) ; } } /******************************************/ static inline void LagrangeLeapFrog(Domain& domain) { #ifdef SEDOV_SYNC_POS_VEL_LATE Domain_member fieldData[6] ; #endif /* calculate nodal forces, accelerations, velocities, positions, with * applied boundary conditions and slide surface considerations */ LagrangeNodal(domain); #ifdef SEDOV_SYNC_POS_VEL_LATE #endif /* calculate element quantities (i.e. velocity gradient & q), and update * material states */ LagrangeElements(domain, domain.numElem()); #if USE_MPI #ifdef SEDOV_SYNC_POS_VEL_LATE CommRecv(domain, MSG_SYNC_POS_VEL, 6, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, false, false) ; fieldData[0] = &Domain::x ; fieldData[1] = &Domain::y ; fieldData[2] = &Domain::z ; fieldData[3] = &Domain::xd ; fieldData[4] = &Domain::yd ; fieldData[5] = &Domain::zd ; CommSend(domain, MSG_SYNC_POS_VEL, 6, fieldData, domain.sizeX() + 1, domain.sizeY() + 1, domain.sizeZ() + 1, false, false) ; #endif #endif CalcTimeConstraintsForElems(domain); #if USE_MPI #ifdef SEDOV_SYNC_POS_VEL_LATE CommSyncPosVel(domain) ; #endif #endif } /******************************************/ int main(int argc, char *argv[]) { Domain *locDom ; Int_t numRanks ; Int_t myRank ; struct cmdLineOpts opts; #if USE_MPI Domain_member fieldData ; MPI_Init(&argc, &argv) ; MPI_Comm_size(MPI_COMM_WORLD, &numRanks) ; MPI_Comm_rank(MPI_COMM_WORLD, &myRank) ; #else numRanks = 1; myRank = 0; #endif /* Set defaults that can be overridden by command line opts */ opts.its = 9999999; opts.nx = 30; opts.numReg = 11; opts.numFiles = (int)(numRanks+10)/9; opts.showProg = 0; opts.quiet = 0; opts.viz = 0; opts.balance = 1; opts.cost = 1; ParseCommandLineOptions(argc, argv, myRank, &opts); if ((myRank == 0) && (opts.quiet == 0)) { printf("Running problem size %d^3 per domain until completion\n", opts.nx); printf("Num processors: %d\n", numRanks); #if _OPENMP printf("Num threads: %d\n", omp_get_max_threads()); #endif printf("Total number of elements: %lld\n\n", (long long int)(numRanks*opts.nx*opts.nx*opts.nx)); printf("To run other sizes, use -s <integer>.\n"); printf("To run a fixed number of iterations, use -i <integer>.\n"); printf("To run a more or less balanced region set, use -b <integer>.\n"); printf("To change the relative costs of regions, use -c <integer>.\n"); printf("To print out progress, use -p\n"); printf("To write an output file for VisIt, use -v\n"); printf("See help (-h) for more options\n\n"); } // Set up the mesh and decompose. Assumes regular cubes for now Int_t col, row, plane, side; InitMeshDecomp(numRanks, myRank, &col, &row, &plane, &side); // Build the main data structure and initialize it locDom = new Domain(numRanks, col, row, plane, opts.nx, side, opts.numReg, opts.balance, opts.cost) ; #if USE_MPI fieldData = &Domain::nodalMass ; // Initial domain boundary communication CommRecv(*locDom, MSG_COMM_SBN, 1, locDom->sizeX() + 1, locDom->sizeY() + 1, locDom->sizeZ() + 1, true, false) ; CommSend(*locDom, MSG_COMM_SBN, 1, &fieldData, locDom->sizeX() + 1, locDom->sizeY() + 1, locDom->sizeZ() + 1, true, false) ; CommSBN(*locDom, 1, &fieldData) ; // End initialization MPI_Barrier(MPI_COMM_WORLD); #endif // BEGIN timestep to solution */ #if USE_MPI double start = MPI_Wtime(); #else timeval start; gettimeofday(&start, NULL) ; #endif //debug to see region sizes // for(Int_t i = 0; i < locDom->numReg(); i++) // std::cout << "region" << i + 1<< "size" << locDom->regElemSize(i) <<std::endl; //Initialize Kokkos Kokkos::initialize(argc,argv); while((locDom->time() < locDom->stoptime()) && (locDom->cycle() < opts.its)) { TimeIncrement(*locDom) ; LagrangeLeapFrog(*locDom) ; if ((opts.showProg != 0) && (opts.quiet == 0) && (myRank == 0)) { printf("cycle = %d, time = %e, dt=%e\n", locDom->cycle(), double(locDom->time()), double(locDom->deltatime()) ) ; } } // Shutdown Kokkos Kokkos::finalize(); // Use reduced max elapsed time double elapsed_time; #if USE_MPI elapsed_time = MPI_Wtime() - start; #else timeval end; gettimeofday(&end, NULL) ; elapsed_time = (double)(end.tv_sec - start.tv_sec) + ((double)(end.tv_usec - start.tv_usec))/1000000 ; #endif double elapsed_timeG; #if USE_MPI MPI_Reduce(&elapsed_time, &elapsed_timeG, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); #else elapsed_timeG = elapsed_time; #endif // Write out final viz file */ if (opts.viz) { DumpToVisit(*locDom, opts.numFiles, myRank, numRanks) ; } if ((myRank == 0) && (opts.quiet == 0)) { VerifyAndWriteFinalOutput(elapsed_timeG, *locDom, opts.nx, numRanks); } #if USE_MPI MPI_Finalize() ; #endif return 0 ; }
89ff6a1e4ac83d1ac43bee3125d2a61ecf5d4cc4
e638d561c72355c58df1246dd32e12778ccdb4dd
/alvr_server/FreePIE.h
c886ab158d81a0b9579da62d557d64f54f7bdda7
[ "MIT" ]
permissive
RealMG/ALVR
0377b048315447694a08d1c9acfb2da7d317292b
e4a4af6acf8eddfac5daa50dd83bc4681c31ef37
refs/heads/master
2020-03-23T04:20:04.018167
2020-03-17T03:21:01
2020-03-17T03:21:01
141,077,046
0
0
NOASSERTION
2020-03-17T03:21:02
2018-07-16T02:29:55
C++
UTF-8
C++
false
false
5,013
h
#pragma once #include "openvr-utils\ipctools.h" #include "resource.h" #include "packet_types.h" #include "Utils.h" #include "Logger.h" class FreePIE { public: static const uint32_t ALVR_FREEPIE_SIGNATURE_V3 = 0x11223346; static const uint32_t ALVR_FREEPIE_FLAG_OVERRIDE_HEAD_ORIENTATION = 1 << 0; static const uint32_t ALVR_FREEPIE_FLAG_OVERRIDE_CONTROLLER_ORIENTATION0 = 1 << 1; static const uint32_t ALVR_FREEPIE_FLAG_OVERRIDE_HEAD_POSITION = 1 << 2; static const uint32_t ALVR_FREEPIE_FLAG_OVERRIDE_CONTROLLER_POSITION0 = 1 << 3; static const uint32_t ALVR_FREEPIE_FLAG_OVERRIDE_BUTTONS = 1 << 4; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_TRACKPAD_CLICK = 1 << 0; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_TRACKPAD_TOUCH = 1 << 1; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_BACK = 1 << 2; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_VOLUME_UP = 1 << 3; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_VOLUME_DOWN = 1 << 4; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_A = 1 << 5; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_B = 1 << 6; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_RTHUMB = 1 << 7; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_RSHOULDER = 1 << 8; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_X = 1 << 9; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_Y = 1 << 10; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_LTHUMB = 1 << 11; static const uint32_t ALVR_FREEPIE_INPUT_BUTTON_LSHOULDER = 1 << 12; static const uint32_t ALVR_FREEPIE_BUTTONS = 21; static const uint32_t ALVR_FREEPIE_MESSAGE_LENGTH = 512; static const int BUTTON_MAP[FreePIE::ALVR_FREEPIE_BUTTONS]; #pragma pack(push, 1) struct FreePIEFileMapping { uint32_t version; uint32_t flags; double input_head_orientation[3]; double input_controller_orientation[2][3]; double input_head_position[3]; double input_controller_position[2][3]; double input_trackpad[2][2]; uint64_t inputControllerButtons[2]; double input_haptic_feedback[2][3]; uint32_t controllers; uint32_t controllerButtons[2]; double head_orientation[3]; double controller_orientation[2][3]; double head_position[3]; double controller_position[2][3]; double trigger[2]; double trigger_left[2]; double trigger_right[2]; double joystick_left[2][2]; double joystick_right[2][2]; double trackpad[2][2]; char message[ALVR_FREEPIE_MESSAGE_LENGTH]; }; #pragma pack(pop) FreePIE() : mFileMapping(ALVR_FREEPIE_FILEMAPPING_NAME, sizeof(FreePIEFileMapping)) , mMutex(ALVR_FREEPIE_MUTEX_NAME) { Initialize(); } ~FreePIE() { } void UpdateTrackingInfoByFreePIE(const TrackingInfo &info, vr::HmdQuaternion_t &head_orientation , vr::HmdQuaternion_t controller_orientation[TrackingInfo::MAX_CONTROLLERS] , const TrackingVector3 &head_position , const TrackingVector3 controller_position[TrackingInfo::MAX_CONTROLLERS] , double haptic_feedback[2][3]) { mMutex.Wait(); QuaternionToEulerAngle(head_orientation, mMapped->input_head_orientation); mMapped->input_head_position[0] = head_position.x; mMapped->input_head_position[1] = head_position.y; mMapped->input_head_position[2] = head_position.z; for (int i = 0; i < TrackingInfo::MAX_CONTROLLERS; i++) { QuaternionToEulerAngle(controller_orientation[i], mMapped->input_controller_orientation[i]); mMapped->input_controller_position[i][0] = controller_position[i].x; mMapped->input_controller_position[i][1] = controller_position[i].y; mMapped->input_controller_position[i][2] = controller_position[i].z; mMapped->input_trackpad[i][0] = info.controller[i].trackpadPosition.x; mMapped->input_trackpad[i][1] = info.controller[i].trackpadPosition.y; mMapped->inputControllerButtons[i] = info.controller[i].buttons; } // When client sends two controller information and FreePIE is not running, detect it here. if (info.controller[1].flags & TrackingInfo::Controller::FLAG_CONTROLLER_ENABLE) { mMapped->controllers = 2; } mMapped->message[ALVR_FREEPIE_MESSAGE_LENGTH - 1] = 0; mMapped->input_haptic_feedback[0][0] = haptic_feedback[0][0]; mMapped->input_haptic_feedback[0][1] = haptic_feedback[0][1]; mMapped->input_haptic_feedback[0][2] = haptic_feedback[0][2]; mMapped->input_haptic_feedback[1][0] = haptic_feedback[1][0]; mMapped->input_haptic_feedback[1][1] = haptic_feedback[1][1]; mMapped->input_haptic_feedback[1][2] = haptic_feedback[1][2]; memcpy(&mCopy, mMapped, sizeof(FreePIEFileMapping)); mMutex.Release(); } const FreePIEFileMapping& GetData() { return mCopy; } private: void Initialize() { mMutex.Wait(); mMapped = (FreePIEFileMapping *)mFileMapping.Map(FILE_MAP_WRITE); memset(mMapped, 0, sizeof(FreePIEFileMapping)); mMapped->version = ALVR_FREEPIE_SIGNATURE_V3; mMapped->flags = 0; mMapped->controllers = 1; memcpy(&mCopy, mMapped, sizeof(FreePIEFileMapping)); mMutex.Release(); } IPCFileMapping mFileMapping; IPCMutex mMutex; FreePIEFileMapping *mMapped; FreePIEFileMapping mCopy; };
242c44d89ac795f4bf1a5907499f653803fcc7c3
1d813e7123dbd3f04cf2a151c321e7dea23ef192
/Source/WebKit2/UIProcess/WebResourceLoadStatisticsManager.cpp
5d6cb6cc4e1acafe51d9923808398a0539323a4f
[]
no_license
junhuac/webkit
c2b1be3fdc3852496c2553619b3c9592e687ed5f
1961514e0b8e324498dccfa0c26ed582f97e124f
refs/heads/master
2022-12-28T21:04:47.764386
2017-03-13T14:42:38
2017-03-13T14:42:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,378
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. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS 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 "config.h" #include "WebResourceLoadStatisticsManager.h" #include "Logging.h" #include "WebResourceLoadStatisticsStore.h" #include <WebCore/ResourceLoadObserver.h> #include <WebCore/URL.h> using namespace WebCore; namespace WebKit { void WebResourceLoadStatisticsManager::setPrevalentResource(const String& hostName, bool value) { if (value) WebCore::ResourceLoadObserver::sharedObserver().setPrevalentResource(URL(URL(), hostName)); else WebCore::ResourceLoadObserver::sharedObserver().clearPrevalentResource(URL(URL(), hostName)); } bool WebResourceLoadStatisticsManager::isPrevalentResource(const String& hostName) { return WebCore::ResourceLoadObserver::sharedObserver().isPrevalentResource(URL(URL(), hostName)); } void WebResourceLoadStatisticsManager::setHasHadUserInteraction(const String& hostName, bool value) { if (value) WebCore::ResourceLoadObserver::sharedObserver().logUserInteraction(URL(URL(), hostName)); else WebCore::ResourceLoadObserver::sharedObserver().clearUserInteraction(URL(URL(), hostName)); } bool WebResourceLoadStatisticsManager::hasHadUserInteraction(const String& hostName) { return WebCore::ResourceLoadObserver::sharedObserver().hasHadUserInteraction(URL(URL(), hostName)); } void WebResourceLoadStatisticsManager::setSubframeUnderTopFrameOrigin(const String& hostName, const String& topFrameHostName) { WebCore::ResourceLoadObserver::sharedObserver().setSubframeUnderTopFrameOrigin(URL(URL(), hostName), URL(URL(), topFrameHostName)); } void WebResourceLoadStatisticsManager::setSubresourceUnderTopFrameOrigin(const String& hostName, const String& topFrameHostName) { WebCore::ResourceLoadObserver::sharedObserver().setSubresourceUnderTopFrameOrigin(URL(URL(), hostName), URL(URL(), topFrameHostName)); } void WebResourceLoadStatisticsManager::setSubresourceUniqueRedirectTo(const String& hostName, const String& hostNameRedirectedTo) { WebCore::ResourceLoadObserver::sharedObserver().setSubresourceUniqueRedirectTo(URL(URL(), hostName), URL(URL(), hostNameRedirectedTo)); } void WebResourceLoadStatisticsManager::setTimeToLiveUserInteraction(double seconds) { WebCore::ResourceLoadObserver::sharedObserver().setTimeToLiveUserInteraction(seconds); } void WebResourceLoadStatisticsManager::fireDataModificationHandler() { WebCore::ResourceLoadObserver::sharedObserver().fireDataModificationHandler(); } void WebResourceLoadStatisticsManager::fireShouldPartitionCookiesHandler(const String& hostName, bool value) { WebCore::ResourceLoadObserver::sharedObserver().fireShouldPartitionCookiesHandler(hostName, value); } void WebResourceLoadStatisticsManager::setNotifyPagesWhenDataRecordsWereScanned(bool value) { WebResourceLoadStatisticsStore::setNotifyPagesWhenDataRecordsWereScanned(value); } void WebResourceLoadStatisticsManager::setShouldClassifyResourcesBeforeDataRecordsRemoval(bool value) { WebResourceLoadStatisticsStore::setShouldClassifyResourcesBeforeDataRecordsRemoval(value); } void WebResourceLoadStatisticsManager::setMinimumTimeBetweeenDataRecordsRemoval(double seconds) { WebResourceLoadStatisticsStore::setMinimumTimeBetweeenDataRecordsRemoval(seconds); } void WebResourceLoadStatisticsManager::clearInMemoryAndPersistentStore() { auto store = WebCore::ResourceLoadObserver::sharedObserver().statisticsStore(); if (store) store->clearInMemoryAndPersistent(); } void WebResourceLoadStatisticsManager::resetToConsistentState() { WebCore::ResourceLoadObserver::sharedObserver().setTimeToLiveUserInteraction(2592000); WebResourceLoadStatisticsStore::setNotifyPagesWhenDataRecordsWereScanned(false); WebResourceLoadStatisticsStore::setShouldClassifyResourcesBeforeDataRecordsRemoval(true); WebResourceLoadStatisticsStore::setMinimumTimeBetweeenDataRecordsRemoval(60); auto store = WebCore::ResourceLoadObserver::sharedObserver().statisticsStore(); if (store) store->clear(); } } // namespace WebKit
[ "[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc
5eaf7167f035daf745b989366b5ef539381f344b
3432877d0cda264bc7b883415734090c3e50c078
/ir_debug.cc
e1691b1862176100aa8c08d3f3bdfcd2d9266b8b
[]
no_license
dbperry17/ProjectBonus
0f44c46f318cb77aebe65a26d712626d05b5b698
a603193948fc97dccc9a2bcf3460ffeaebc6f069
refs/heads/master
2022-03-15T10:59:35.934777
2017-04-29T06:22:09
2017-04-29T06:22:09
89,535,268
0
0
null
null
null
null
UTF-8
C++
false
false
5,474
cc
/* * Copyright (C) Mohsen Zohrevandi, 2017 * * Do not share this file with anyone */ #include <iostream> #include <string> #include <sstream> #include <cassert> #include "ir_debug.h" using namespace std; static void print_statements(struct StatementNode* pc, struct StatementNode* last, int indent); static void print_value_node(struct ValueNode* v) { if (v != NULL) { //if (v->name == "") // cout << v->value; //else // cout << v->name; // Alternatively, you could print both: cout << v->name << " (" << v->value << ")"; // You could also print the address of the node as well: // cout << " @ " << v; } else { cout << "NULL"; } } static void print_arithmetic_operator(ArithmeticOperatorType op) { switch (op) { case OPERATOR_NONE: break; case OPERATOR_PLUS: cout << " + "; break; case OPERATOR_MULT: cout << " * "; break; default: cout << " ? "; break; } } static void print_conditional_operator(ConditionalOperatorType op) { switch (op) { case CONDITION_GREATER: cout << " > "; break; case CONDITION_LESS: cout << " < "; break; case CONDITION_NOTEQUAL: cout << " <> "; break; default: cout << " ? "; break; } } static void print_line_prefix(struct StatementNode* st, int indent, bool right_brace) { stringstream ss; ss << st << ": "; string p = ss.str(); if (!right_brace) { cout << p; } else { cout << string(p.size() , ' '); } cout << string(indent * 4, ' '); } static void print_print(struct StatementNode* st, int indent) { assert(st->print_stmt->id != NULL); print_line_prefix(st, indent, false); cout << "print "; print_value_node(st->print_stmt->id); cout << ";\n"; } static void print_if(struct StatementNode* st, int indent) { assert(st->if_stmt->condition_operand1 != NULL); assert(st->if_stmt->condition_operand2 != NULL); assert(st->if_stmt->true_branch != NULL); assert(st->if_stmt->false_branch != NULL); bool inverted = false; print_line_prefix(st, indent, false); if (st->if_stmt->true_branch->type == NOOP_STMT) inverted = true; cout << "if ( "; if (inverted) cout << "! ( "; print_value_node(st->if_stmt->condition_operand1); print_conditional_operator(st->if_stmt->condition_op); print_value_node(st->if_stmt->condition_operand2); if (inverted) cout << " ) "; cout << " ) {\n"; if (inverted) // NOTE: This is for SWITCH statements { print_line_prefix(st, indent, true); cout << "TRUE SWITCH: \n"; print_statements(st->if_stmt->false_branch, st->if_stmt->true_branch, indent + 1); } else { print_line_prefix(st, indent, true); cout << "TRUE IF: \n"; print_statements(st->if_stmt->true_branch, st->if_stmt->false_branch, indent + 1); } print_line_prefix(st, indent, true); cout << "}\n"; print_line_prefix(st, indent, true); if(inverted) cout << "FALSE SWITCH: " << endl; else cout << "FALSE: " << endl; } static void print_assignment(struct StatementNode* st, int indent) { assert(st->assign_stmt->left_hand_side != NULL); assert(st->assign_stmt->operand1 != NULL); if (st->assign_stmt->op == OPERATOR_NONE) assert(st->assign_stmt->operand2 == NULL); else assert(st->assign_stmt->operand2 != NULL); print_line_prefix(st, indent, false); print_value_node(st->assign_stmt->left_hand_side); cout << " = "; print_value_node(st->assign_stmt->operand1); print_arithmetic_operator(st->assign_stmt->op); ExprNode* current = st->assign_stmt->operand2; while (current != NULL) { print_value_node(current->op1); print_arithmetic_operator(current->arith); current = current->op2; } cout << ";\n"; } static void print_goto(struct StatementNode* st, int indent) { assert(st->goto_stmt->target != NULL); print_line_prefix(st, indent, false); cout << "goto " << st->goto_stmt->target << "\n"; } static void print_noop(struct StatementNode* st, int indent) { print_line_prefix(st, indent, false); cout << "noop;\n"; } static void print_statements(struct StatementNode* pc, struct StatementNode* last, int indent) { while (pc != last) { switch (pc->type) { case NOOP_STMT: print_noop(pc, indent); break; case GOTO_STMT: assert(pc->goto_stmt != NULL); print_goto(pc, indent); break; case ASSIGN_STMT: assert(pc->assign_stmt != NULL); print_assignment(pc, indent); break; case IF_STMT: assert(pc->if_stmt != NULL); print_if(pc, indent); break; case PRINT_STMT: assert(pc->print_stmt != NULL); print_print(pc, indent); break; default: print_line_prefix(pc, indent, false); cout << "Unknown Statement (type = " << pc->type << ")\n"; break; } pc = pc->next; } } void print_program(struct StatementNode* program) { assert(program != NULL); print_statements(program, NULL, 1); }
6d0908e1048ffefe0b59ed400506c85ff4be711a
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/77/1189.c
2618bc667f27b809d081bcd00f8b1117402d6720
[]
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
344
c
void Q(char a[]) { char c; c = a[0]; int pos[100]; int i = 0, num = 0; do { if (a[i] == c) { num++; pos[num] = i; } else { cout << pos[num] << " " << i << endl; num--; } i++; }while (i <= strlen(a) - 1); } int main() { char children[100]; cin >> children; Q(children); return 0; }
64a3ac664a4859a8360439b20e5558eb35a75995
297497957c531d81ba286bc91253fbbb78b4d8be
/gfx/skia/skia/src/core/SkSamplingPriv.h
5808c0b285aa4db76ab94d670f1b595e20c36f2d
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
1,899
h
#ifndef SkSamplingPriv_DEFINED #define SkSamplingPriv_DEFINED #include "include/core/SkSamplingOptions.h" class SkReadBuffer; class SkWriteBuffer; enum SkLegacyFQ { kNone_SkLegacyFQ = 0, kLow_SkLegacyFQ = 1, kMedium_SkLegacyFQ = 2, kHigh_SkLegacyFQ = 3, kLast_SkLegacyFQ = kHigh_SkLegacyFQ, }; enum SkMediumAs { kNearest_SkMediumAs, kLinear_SkMediumAs, }; class SkSamplingPriv { public: static size_t FlatSize(const SkSamplingOptions& options) { size_t size = sizeof(uint32_t); if (!options.isAniso()) { size += 3 * sizeof(uint32_t); } return size; } static bool NoChangeWithIdentityMatrix(const SkSamplingOptions& sampling) { return !sampling.useCubic || sampling.cubic.B == 0; } static SkSamplingOptions AnisoFallback(bool imageIsMipped) { auto mm = imageIsMipped ? SkMipmapMode::kLinear : SkMipmapMode::kNone; return SkSamplingOptions(SkFilterMode::kLinear, mm); } static SkSamplingOptions FromFQ(SkLegacyFQ fq, SkMediumAs behavior = kNearest_SkMediumAs) { switch (fq) { case kHigh_SkLegacyFQ: return SkSamplingOptions(SkCubicResampler{1/3.0f, 1/3.0f}); case kMedium_SkLegacyFQ: return SkSamplingOptions(SkFilterMode::kLinear, behavior == kNearest_SkMediumAs ? SkMipmapMode::kNearest : SkMipmapMode::kLinear); case kLow_SkLegacyFQ: return SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNone); case kNone_SkLegacyFQ: break; } return SkSamplingOptions(SkFilterMode::kNearest, SkMipmapMode::kNone); } }; #endif
3f84658aea7a075106618a488568b9e7fcdc94cf
819684f7fb6b98505b23a5f85c7ce955ebc47227
/Level1/String/p3.cpp
41f1c6c3484ec3da4347590d51e48bd00de1f1f7
[]
no_license
dhruvagg987/Problem_Solving
7c2c14c99faa18ab9289a224b28a8ae54b90ba5f
07d271e9e0569053acd5a850ef08407f6d85c97f
refs/heads/master
2023-04-14T20:54:15.334644
2021-04-13T18:14:17
2021-04-13T18:14:17
289,731,708
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include<iostream> using namespace std; int main() { int i,j; string s="COMPUTER"; for(i=0;i<s.length();i++) { for(j=i;j<s.length();j++) cout<<s[j]<<" "; cout<<endl; } return 0; }
9279d061b989be2de11b3bd7226dba8b267cf7f6
21ef7695b2d571883b7acdaa0c86c46c1c446e20
/serman/history.cc
9aa920bd7847401cc5bce4eda23e15a18f5cf1fa
[ "BSD-2-Clause" ]
permissive
buzzz321/SerMan
39a0866fbeb01ab8c9aaff6d45cfc461d09500f2
d6d6be3b674ec4be577c5a248dc7e3f558c14bec
refs/heads/master
2021-05-04T11:03:48.210544
2019-11-24T10:58:36
2019-11-24T10:58:36
52,677,429
0
0
null
null
null
null
UTF-8
C++
false
false
2,285
cc
#include "history.h" #include <fstream> #include <iostream> #include <regex> #include<limits> History::History() : position(std::numeric_limits<std::size_t>::max()), currentSearchIndex(0), fileName(".serman_history") { cmdHistory.clear(); } History::History(std::string path) : position(std::numeric_limits<std::size_t>::max()), currentSearchIndex(0), fileName(path + "/.serman_history") { cmdHistory.clear(); } void History::addToHistory(std::string line) { std::cout << "adding " << std::endl; cmdHistory.push_back(line); position = cmdHistory.size() - 1; } std::string History::getFromHistory() { if ( position < std::numeric_limits<std::size_t>::max() ) { return cmdHistory[position]; } else { return ""; } } void History::stepBackHistory() { if (0 != position && position < std::numeric_limits<std::size_t>::max()) { position -= 1; } } void History::stepForwardHistory() { if (position < cmdHistory.size() - 1) { position += 1; } } HistoryList History::dumpHistory() { return cmdHistory; } HistoryList History::find(std::string cmd) { HistoryList retVal; std::smatch m; std::regex e(cmd); // matches words beginning by "sub" for (auto &item : cmdHistory) { bool found = std::regex_search(item, m, e); if (found) { std::cout << item << std::endl; retVal.push_back(item); } } currentSearch = retVal; return retVal; } std::string History::stepForwardSearch() { std::string retVal; if (currentSearchIndex < currentSearch.size()) { currentSearchIndex += 1; } if (currentSearchIndex >= currentSearch.size()) { currentSearchIndex = 0; } if (currentSearch.size() > 0) { retVal = currentSearch[currentSearchIndex]; } return retVal; } void History::readFromDisc() { std::ifstream myfile; std::string line; myfile.open(fileName); if (myfile.is_open()) { while (std::getline(myfile, line)) { cmdHistory.push_back((line)); } myfile.close(); } } void History::saveToDisc() { std::ofstream myfile; myfile.open(fileName); if (myfile.is_open()) { for (auto &item : cmdHistory) { myfile << item << std::endl; } myfile.close(); } } HistoryList History::removeDuplicates() { return cmdHistory; }
b591ab930527d87ca5d5ea2dc2119ddbb2c3e92c
980b4735da4ac1882bf74d0d40530f2370fa9389
/yesod.old/yesod/storage/detail/memory_pointer_facade.hpp
dfa9c854dc43852e5ef442c79427c4e454351982
[]
no_license
oakad/ucpf
24790c6f8247e16b8ef48bc3012da15bdd775205
cb832e39776237af5fd901e3942d671af37a8005
refs/heads/master
2021-03-16T07:17:54.219223
2017-04-01T05:57:33
2017-04-01T05:57:33
337,931
0
0
null
null
null
null
UTF-8
C++
false
false
839
hpp
/* * Copyright (c) 2016 Alex Dubov <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 as publi- * shed by the Free Software Foundation. */ #if !defined(HPP_320E3B8FEFCB5DF0FD6E60B5CB133C24) #define HPP_320E3B8FEFCB5DF0FD6E60B5CB133C24 namespace ucpf { namespace yesod { namespace storage { namespace detail { struct memory_pointer_facade { typedef std::uint8_t *address_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static constexpr bool is_stateful = false; address_type access( address_type p, size_type unit_size ) { return p; } address_type access( address_type p, size_type unit_size, difference_type offset ) { return p + unit_size * offset; } }; }}}} #endif
c2546501d9a91ee032c1e677c18897bcb4a28f6e
d872333f8c95a2b7481a280ca576af6a1c19318c
/src/operator/nn/mkldnn/mkldnn_log_softmax.cc
eb0ff379cdb598e268d507f840350454cf867265
[ "Apache-2.0", "BSD-3-Clause", "BSL-1.0", "MIT", "BSD-2-Clause", "Zlib", "Unlicense" ]
permissive
channel960608/incubator-mxnet
6a5d472a0808db6625cd5b6cd044d6a830782e3b
3480ba2c6df02bb907d3a975d354efa8697c4e71
refs/heads/master
2023-08-13T00:03:25.572159
2021-07-16T21:30:24
2021-07-16T21:30:24
379,127,391
0
0
Apache-2.0
2021-09-25T12:40:34
2021-06-22T03:12:56
C++
UTF-8
C++
false
false
8,572
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file mkldnn_log_softmax.cc * \brief Implementation of log_softmax function with MKLDNN support */ #include "../softmax-inl.h" #include "./mkldnn_ops-inl.h" #include "./mkldnn_base-inl.h" #if MXNET_USE_ONEDNN == 1 namespace mxnet { namespace op { static mkldnn::logsoftmax_forward::primitive_desc GetLogSoftmaxFwdPd( bool is_train, const int axis, const mkldnn::memory &input_mem) { mkldnn::memory::desc data_md = input_mem.get_desc(); auto cpu_engine = CpuEngine::Get()->get_engine(); auto prop = is_train ? mkldnn::prop_kind::forward_training : mkldnn::prop_kind::forward_scoring; auto desc = mkldnn::logsoftmax_forward::desc(prop, data_md, axis); return mkldnn::logsoftmax_forward::primitive_desc(desc, cpu_engine); } static mkldnn::logsoftmax_backward::primitive_desc GetLogSoftmaxBwdPd( const mkldnn::memory &diff_mem, const mkldnn::memory &data_mem, const int axis, const mkldnn::logsoftmax_forward::primitive_desc &hint_fwd_pd) { mkldnn::memory::desc diff_md = diff_mem.get_desc(); mkldnn::memory::desc data_md = data_mem.get_desc(); auto cpu_engine = CpuEngine::Get()->get_engine(); auto desc = mkldnn::logsoftmax_backward::desc(diff_md, data_md, axis); return mkldnn::logsoftmax_backward::primitive_desc(desc, cpu_engine, hint_fwd_pd); } bool SupportMKLDNNLogSoftmax(const SoftmaxParam &param, const NDArray &data, const NDArray &output) { const int ndim = data.shape().ndim(); const int in_dtype = data.dtype(); const int out_dtype = output.dtype(); const int axis = CheckAxis(param.axis, ndim); // MKLDNN does not support temperature argument in their log_softmax function // now. Need update this once they start to support it. // Currently, MKLDNN shows bad performance when log_softmax is not performed on the last dimension if (param.temperature.has_value() || in_dtype != mshadow::kFloat32 || in_dtype != out_dtype || axis != (ndim - 1)) { return false; } // only supports ndim = 1, 2, 3, 4 for now return (ndim >= 1 && ndim <= 4); } class MKLDNNLogSoftmaxFwd { public: mkldnn::logsoftmax_forward::primitive_desc pd; MKLDNNLogSoftmaxFwd(const bool is_train, const int axis, const mkldnn::memory &input) : pd(GetLogSoftmaxFwdPd(is_train, axis, input)) { fwd_ = std::make_shared<mkldnn::logsoftmax_forward>(pd); } const mkldnn::logsoftmax_forward &GetFwd() const { return *fwd_; } private: std::shared_ptr<mkldnn::logsoftmax_forward> fwd_; }; typedef ParamOpSign<SoftmaxParam> MKLDNNSoftmaxSignature; static MKLDNNLogSoftmaxFwd &GetLogSoftmaxFwd(const SoftmaxParam &param, const int real_axis, const bool is_train, const NDArray &data, const NDArray &output) { #if DMLC_CXX11_THREAD_LOCAL static thread_local std::unordered_map<MKLDNNSoftmaxSignature, MKLDNNLogSoftmaxFwd, OpHash> fwds; #else static MX_THREAD_LOCAL std::unordered_map<MKLDNNSoftmaxSignature, MKLDNNLogSoftmaxFwd, OpHash> fwds; #endif MKLDNNSoftmaxSignature key(param); key.AddSign(real_axis); key.AddSign(is_train); key.AddSign(data); key.AddSign(output); auto it = fwds.find(key); if (it == fwds.end()) { MKLDNNLogSoftmaxFwd fwd(is_train, real_axis, *(data.GetMKLDNNData())); it = AddToCache(&fwds, key, fwd); } return it->second; } void MKLDNNLogSoftmaxForward(const nnvm::NodeAttrs& attrs, const OpContext &ctx, const NDArray &in_data, const OpReqType &req, const NDArray &out_data) { if (req == kNullOp) return; // same as the FCompute path, log_softmax only supports kWriteTo and kWriteInplace for now. CHECK_NE(req, kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, in_data.shape().ndim()); auto fwd = GetLogSoftmaxFwd(param, axis, ctx.is_train, in_data, out_data); auto in_mem = in_data.GetMKLDNNData(); auto out_mem = out_data.GetMKLDNNData(fwd.pd.dst_desc()); MKLDNNStream *stream = MKLDNNStream::Get(); stream->RegisterPrimArgs(fwd.GetFwd(), {{MKLDNN_ARG_SRC, *in_mem}, {MKLDNN_ARG_DST, *out_mem}}); stream->Submit(); } class MKLDNNLogSoftmaxBwd { public: mkldnn::logsoftmax_backward::primitive_desc pd; MKLDNNLogSoftmaxBwd(const mkldnn::memory &diff_mem, const mkldnn::memory &data_mem, const int axis, const mkldnn::logsoftmax_forward::primitive_desc &hint_fwd_pd) : pd(GetLogSoftmaxBwdPd(diff_mem, data_mem, axis, hint_fwd_pd)) { bwd_ = std::make_shared<mkldnn::logsoftmax_backward>(pd); } const mkldnn::logsoftmax_backward &GetBwd() const { return *bwd_; } private: std::shared_ptr<mkldnn::logsoftmax_backward> bwd_; }; static MKLDNNLogSoftmaxBwd &GetLogSoftmaxBwd(const SoftmaxParam &param, const int real_axis, const std::vector<NDArray> &data, const std::vector<NDArray> &output) { #if DMLC_CXX11_THREAD_LOCAL static thread_local std::unordered_map<MKLDNNSoftmaxSignature, MKLDNNLogSoftmaxBwd, OpHash> bwds; #else static MX_THREAD_LOCAL std::unordered_map<MKLDNNSoftmaxSignature, MKLDNNLogSoftmaxBwd, OpHash> bwds; #endif MKLDNNSoftmaxSignature key(param); key.AddSign(real_axis); key.AddSign(data); key.AddSign(output); auto it = bwds.find(key); if (it == bwds.end()) { auto diff_mem = data[0].GetMKLDNNData(); auto data_mem = data[1].GetMKLDNNData(); auto fwd_pd = GetLogSoftmaxFwdPd(true, real_axis, *data_mem); MKLDNNLogSoftmaxBwd bwd(*diff_mem, *data_mem, real_axis, fwd_pd); it = AddToCache(&bwds, key, bwd); } return it->second; } void MKLDNNLogSoftmaxBackward(const nnvm::NodeAttrs& attrs, const OpContext &ctx, const std::vector<NDArray> &in_data, const std::vector<OpReqType> &req, const std::vector<NDArray> &out_data) { if (req[0] == kNullOp) return; CHECK_EQ(in_data.size(), 2U); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, in_data[1].shape().ndim()); auto diff_mem = in_data[0].GetMKLDNNData(); auto data_mem = in_data[1].GetMKLDNNData(); auto bwd = GetLogSoftmaxBwd(param, axis, in_data, out_data); auto out_mem = CreateMKLDNNMem(out_data[0], bwd.pd.diff_src_desc(), req[0]); MKLDNNStream *stream = MKLDNNStream::Get(); mkldnn_args_map_t args = { { MKLDNN_ARG_DST, *data_mem }, { MKLDNN_ARG_DIFF_DST, *diff_mem }, { MKLDNN_ARG_DIFF_SRC, *out_mem.second } }; stream->RegisterPrimArgs(bwd.GetBwd(), args); CommitOutput(out_data[0], out_mem); stream->Submit(); } } // namespace op } // namespace mxnet #endif
a85df5290eede8b03d1fe01b0c4ca475f774b7ac
a5aa31e31625779b76025369a0689f73c3d8f2b4
/granary/arch/x86/cpu.cc
1f38f56503ec7fd56653ce699eb9b9175fd77077
[ "Apache-2.0", "MIT" ]
permissive
gavz/grr
0d672c1edecd732b371e5ffd3fbadebfc08ad280
76f6ee96cedbd6b7c4f0c0b9481a5e1601e6a710
refs/heads/master
2022-04-27T15:26:12.615701
2019-09-04T16:41:09
2019-09-04T16:41:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
394
cc
/* Copyright 2015 Peter Goodman, all rights reserved. */ #include "granary/base/base.h" #include "granary/base/breakpoint.h" namespace granary { namespace arch { void Relax(void) { GRANARY_INLINE_ASSEMBLY("pause;" ::: "memory"); } void SerializePipeline(void) { GRANARY_INLINE_ASSEMBLY("cpuid;" ::: "eax", "ebx", "ecx", "edx", "memory"); } } // namespace arch } // namespace granary
f958d1d6b9ca56c0ae23c6411cca78cb3d0b640e
2befdb4bc91b861372c3353511558bc30d70aec7
/Source/GranularVoice.h
070118803558556a97a5f06bb217cfd4f7dcb67f
[]
no_license
BennetLeff/Nave
24eb74d15f33879fc56946cd2527f949fb4023ee
c02e513c7a356cf98e89b06b20532bb50b08a8ef
refs/heads/develop
2020-11-24T02:27:36.552006
2020-01-08T19:40:57
2020-01-08T19:40:57
227,925,673
0
0
null
2020-01-08T19:40:59
2019-12-13T21:33:53
C++
UTF-8
C++
false
false
1,720
h
/* ============================================================================== GranularVoice.h Created: 18 Dec 2019 5:05:09pm Author: Bennet Leff Code structure heavily borrows from Juce's SamplerVoice. ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== /** A subclass of SynthesiserVoice that can play a GranularSound. To use it, create a Synthesiser, add some GranularVoice objects to it, then give it some GranularSound objects to play. */ class GranularVoice : public SynthesiserVoice { public: //============================================================================== /** Creates a SamplerVoice. */ GranularVoice(); /** Destructor. */ ~GranularVoice() override; //============================================================================== bool canPlaySound (SynthesiserSound*) override; void startNote (int midiNoteNumber, float velocity, SynthesiserSound*, int pitchWheel) override; void stopNote (float velocity, bool allowTailOff) override; void pitchWheelMoved (int newValue) override; void controllerMoved (int controllerNumber, int newValue) override; void renderNextBlock (AudioBuffer<float>&, int startSample, int numSamples) override; using SynthesiserVoice::renderNextBlock; private: //============================================================================== double pitchRatio = 0; double sourceSamplePosition = 0; float lgain = 0, rgain = 0; ADSR adsr; JUCE_LEAK_DETECTOR (GranularVoice) };
9ac5992a976a08a6e99221cc9a4fec5b27f77960
bf66c35d8866a701c1a41429045fab9823f12cd5
/src/timedata.cpp
f5401a871762bed2b98737ae4372fd45efcfd6ce
[ "MIT" ]
permissive
cboic-project/cboic
d1035cfaaaa97814cc96d7652b5848ba8cda1cc6
ea15fa59e4ce28b847e1be8e58720e3232e9735a
refs/heads/master
2021-01-21T20:16:59.185644
2017-05-25T23:52:30
2017-05-25T23:52:30
92,213,242
0
0
null
null
null
null
UTF-8
C++
false
false
3,656
cpp
// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netbase.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; /** * "Never go to sea with two chronometers; take one or three." * Our three time sources are: * - System clock * - Median of other nodes clocks * - The user (asking the user to fix the system clock if the first two disagree) */ int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } static int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } void AddTimeData(const CNetAddr& ip, int64_t nTime) { int64_t nOffsetSample = nTime - GetTime(); LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(200,0); vTimeOffsets.input(nOffsetSample); LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 35 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Cboic Core will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64_t n, vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } }
[ "root@home" ]
root@home
72b54435a65c7493d5d79f77fd58e3237a01e311
e0faafe09f9dc664db1dbe1556947b4cbc40f812
/37_Truncatable-primes.cpp
3653dcae132bbd1acf9abf2355206e29b66423fc
[]
no_license
kmilliner/Project-Euler-Solutions-1
6f2e02dcfe8d01b8758399af2a1ef1955469774b
1ee93e678f4fdcc8cf1d2ab2818713a313c59b52
refs/heads/master
2021-09-21T00:56:24.080518
2018-08-18T08:39:03
2018-08-18T08:39:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
#include <bits/stdc++.h> using namespace std; set<int> primes; void Sieve(int n) { vector<bool> sieve(1000010, false); int p = 2; sieve[2] = true; while(p <= n) { primes.insert(p); for(int i=2; p*i <= n; i++) sieve[p*i] = true; while(p < sieve.size() && sieve[p]) p++; sieve[p] = true; } } int main() { Sieve(1000000); int n; cin >> n; long ans = 0; for(auto p : primes) { if(p <= 7) continue; if(p >= n) break; string s = to_string(p); bool valid = true; for(int i=1; i<s.size(); i++) { if(primes.count(stoi(s.substr(i))) == 0) { valid = false; break; } if(primes.count(stoi(s.substr(0, s.size()-i))) == 0) { valid = false; break; } } if(valid) { cerr << p << endl; ans += p; } } cout << ans << endl; return 0; }
83f6a45540cbed7870138ef23418f78cae7c3e09
eb4cfc5f3d38e85510218cd4162d7ccc14782fd1
/trunk/project/library/include/positions/medicalRecorder.h
2ab096cdad3cfbcaa35e18e8dbda26cfa942608b
[]
no_license
MichalDudkiewicz/workScheduler
1cad606a969e47fbcbce927d839114f87905bda3
5ac2310fc1d557716994a6150efe0df18d403a05
refs/heads/master
2023-01-21T06:15:57.548517
2020-12-05T22:46:08
2020-12-05T22:46:08
230,484,915
0
0
null
null
null
null
UTF-8
C++
false
false
354
h
#ifndef medicalRecorderClass #define medicalRecorderClass #include "position.h" class MedicalRecorder : public Position { public: MedicalRecorder() = default; ~MedicalRecorder() override = default; std::string positionInfo() const override; unsigned int positionID() const override; std::string shortcut() const override; }; #endif
0e9f8d509b3b47d9a1b843278d412f91b3e64d53
3a4080fb1ca1ac5b9f57c29ab9bc7ad660ba16b3
/C_C++/C++/lambda.cpp
666915a7594365e613d378eb042c3879750b87cb
[]
no_license
changmu/Practice-code
0646d2fd580d2103f3ef8985b2b3ca3c0862716f
c5d87c787ea0e28001240cd4f49270ea07d4f1e4
refs/heads/master
2022-08-03T15:05:34.514213
2022-07-27T03:14:45
2022-07-27T03:14:45
48,113,031
2
0
null
2022-06-18T09:11:54
2015-12-16T13:50:08
C
UTF-8
C++
false
false
367
cpp
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sz = 0; int *p = find_if(a, a + 10, [sz](int a) { return a > sz; }); cout << *p << endl; int sz = 1; auto f = [&]() { return ++sz; }; cout << f() << endl; cout << f() << endl; return 0; }
50a85f7a2d8462de2a54f7e483f31c94be65d6c1
a43cf211ffd0ad3ae440fd859bc3255014fe30be
/Parquet_src/src/parquet/file/reader.h
7d3c3f97705ecd36b5ede3f81f800deea14f28b1
[]
no_license
DaigaPlase/tpc_hive
8ee6c3d9ab02af401929eb379426b97e9acdaf58
262ae311e170fef87c9afeb356da55b2a83f1d27
refs/heads/master
2021-01-10T17:39:08.015909
2018-05-29T08:22:52
2018-05-29T08:22:52
51,431,269
0
0
null
null
null
null
UTF-8
C++
false
false
4,554
h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef PARQUET_FILE_READER_H #define PARQUET_FILE_READER_H #include <cstdint> #include <iosfwd> #include <list> #include <memory> #include <string> #include <vector> #include "parquet/column/page.h" #include "parquet/column/properties.h" #include "parquet/column/statistics.h" #include "parquet/file/metadata.h" #include "parquet/schema.h" #include "parquet/util/memory.h" #include "parquet/util/visibility.h" namespace parquet { class ColumnReader; class PARQUET_EXPORT RowGroupReader { public: // Forward declare a virtual class 'Contents' to aid dependency injection and more // easily create test fixtures // An implementation of the Contents class is defined in the .cc file struct Contents { virtual ~Contents() {} virtual std::unique_ptr<PageReader> GetColumnPageReader(int i) = 0; virtual const RowGroupMetaData* metadata() const = 0; virtual const ReaderProperties* properties() const = 0; }; explicit RowGroupReader(std::unique_ptr<Contents> contents); // Returns the rowgroup metadata const RowGroupMetaData* metadata() const; // Construct a ColumnReader for the indicated row group-relative // column. Ownership is shared with the RowGroupReader. std::shared_ptr<ColumnReader> Column(int i); private: // Holds a pointer to an instance of Contents implementation std::unique_ptr<Contents> contents_; }; class PARQUET_EXPORT ParquetFileReader { public: // Forward declare a virtual class 'Contents' to aid dependency injection and more // easily create test fixtures // An implementation of the Contents class is defined in the .cc file struct Contents { virtual ~Contents() {} // Perform any cleanup associated with the file contents virtual void Close() = 0; virtual std::shared_ptr<RowGroupReader> GetRowGroup(int i) = 0; virtual std::shared_ptr<FileMetaData> metadata() const = 0; }; ParquetFileReader(); ~ParquetFileReader(); // Create a reader from some implementation of parquet-cpp's generic file // input interface // // If you cannot provide exclusive access to your file resource, create a // subclass of RandomAccessSource that wraps the shared resource static std::unique_ptr<ParquetFileReader> Open( std::unique_ptr<RandomAccessSource> source, const ReaderProperties& props = default_reader_properties(), const std::shared_ptr<FileMetaData>& metadata = nullptr); // Create a file reader instance from an Arrow file object. Thread-safety is // the responsibility of the file implementation static std::unique_ptr<ParquetFileReader> Open( const std::shared_ptr<::arrow::io::ReadableFileInterface>& source, const ReaderProperties& props = default_reader_properties(), const std::shared_ptr<FileMetaData>& metadata = nullptr); // API Convenience to open a serialized Parquet file on disk, using Arrow IO // interfaces. static std::unique_ptr<ParquetFileReader> OpenFile(const std::string& path, bool memory_map = true, const ReaderProperties& props = default_reader_properties(), const std::shared_ptr<FileMetaData>& metadata = nullptr); void Open(std::unique_ptr<Contents> contents); void Close(); // The RowGroupReader is owned by the FileReader std::shared_ptr<RowGroupReader> RowGroup(int i); // Returns the file metadata. Only one instance is ever created std::shared_ptr<FileMetaData> metadata() const; private: // Holds a pointer to an instance of Contents implementation std::unique_ptr<Contents> contents_; }; // Read only Parquet file metadata std::shared_ptr<FileMetaData> PARQUET_EXPORT ReadMetaData( const std::shared_ptr<::arrow::io::ReadableFileInterface>& source); } // namespace parquet #endif // PARQUET_FILE_READER_H
b6e522047102b44221a85e0d601847ec6fc6fa12
5032b027a316f418192f6a28320c139ec025079f
/坦克大战/EndUI.h
cc604dc83c6e613320e8f72aa1ef85c02ff0f8a2
[]
no_license
li-guoyin/Tank-war
e4ec24d34bef6c0a6715f8c2afa8b28bccd91390
7b63ae0bfe4ff509040bd02a1f5d6eab17239f8c
refs/heads/master
2020-04-09T18:39:29.498972
2018-03-07T13:25:06
2018-03-07T13:25:06
124,239,407
0
0
null
null
null
null
UTF-8
C++
false
false
679
h
// EndUI.h: interface for the CEndUI class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_ENDUI_H__EA7E2148_706B_46D6_9238_F7D59C96B005__INCLUDED_) #define AFX_ENDUI_H__EA7E2148_706B_46D6_9238_F7D59C96B005__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 # include <cv.h> # include <highgui.h> class CMange; class CEndUI { public: void InitEndUI(); void GetGradeNum(CMange *manger); void ShowImage(CMange *manger); CEndUI(); virtual ~CEndUI(); private: IplImage *endImg; IplImage *endImgclone; IplImage *grade[10]; }; #endif // !defined(AFX_ENDUI_H__EA7E2148_706B_46D6_9238_F7D59C96B005__INCLUDED_)
d46ab55110461b95c3cca662b4a9bf2dc70bf1b3
c204459ab145d0738a18969feffe5619fa2b0fb4
/StreamsZylab/streamspart1.cpp
c78333af5e70956b790a75eb223bf761ffd897a2
[]
no_license
beckahenryl/C-Programs
0963dbc8f0a3477fce5d8b94abe10fae1dbdfed2
9302c7ebe18b281eeaf508e9414b5351aee08bc8
refs/heads/master
2020-05-02T02:40:32.075830
2019-09-20T22:02:32
2019-09-20T22:02:32
177,709,442
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
cpp
#include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> using namespace std; int main() { std::string inputString; std::string findComma = ","; std::vector<string> vect; while (true){ cout << "Enter input string:" << endl; getline(cin, inputString); if (inputString != "q"){ std::size_t found = inputString.find(findComma); if (found!=std::string::npos){ //remove the space inputString.erase(std::remove(inputString.begin(), inputString.end(), ' '), inputString.end()); std::stringstream ss(inputString); std::string substring; while(getline(ss, substring, ',')){ vect.push_back(substring); } cout << "First word: " << vect[0] << endl; cout << "Second word: " << vect[1] << endl; cout << endl; vect.erase(vect.begin(), vect.begin()+2); } else{ cout << "Error: No comma in string." << endl << endl; } } else{ break; } } return 0; }
c4d4dbdf20663bd5e6272c388d46444acc37f7a6
b8376621d63394958a7e9535fc7741ac8b5c3bdc
/lib/lib_XT12/Samples/ReportControl/ReportItemControls/MessageRecord.cpp
5045395578a0a53d188fb3cee137e3a23c27993a
[]
no_license
15831944/job_mobile
4f1b9dad21cb7866a35a86d2d86e79b080fb8102
ebdf33d006025a682e9f2dbb670b23d5e3acb285
refs/heads/master
2021-12-02T10:58:20.932641
2013-01-09T05:20:33
2013-01-09T05:20:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
cpp
// MessageRecord.cpp: implementation of the CMessageRecord class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ReportItemControls.h" #include "MessageRecord.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // CMessageRecord class IMPLEMENT_SERIAL(CMessageRecord, CXTPReportRecord, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMessageRecord::CMessageRecord() { CreateItems(); } CMessageRecord::CMessageRecord(CString strItem1, CString strItem2, CString strItem3) { AddItem(new CXTPReportRecordItemText(strItem1)); AddItem(new CXTPReportRecordItemText(strItem2)); AddItem(new CXTPReportRecordItemText(strItem3)); } CMessageRecord::CMessageRecord(CMessageRecord* pRecord) { for(int i = 0; i < 3; i++) { AddItem(new CXTPReportRecordItemText(((CXTPReportRecordItemText*)pRecord->GetItem(i))->GetValue())); } } CMessageRecord& CMessageRecord::operator= (const CMessageRecord& x) { for(int i = 0; i < GetItemCount(); i++) { ((CXTPReportRecordItemText*)GetItem(i))->SetValue(((CXTPReportRecordItemText*)x.GetItem(i))->GetValue()); } return *this; } void CMessageRecord::CreateItems() { // Initialize record items with empty values AddItem(new CXTPReportRecordItemText(_T(""))); AddItem(new CXTPReportRecordItemText(_T(""))); AddItem(new CXTPReportRecordItemText(_T(""))); } CMessageRecord::~CMessageRecord() { } void CMessageRecord::GetItemMetrics(XTP_REPORTRECORDITEM_DRAWARGS* pDrawArgs, XTP_REPORTRECORDITEM_METRICS* pItemMetrics) { CXTPReportRecord::GetItemMetrics(pDrawArgs, pItemMetrics); }
40c3104de253722965e5e5e23d5e596723cc3ab8
1160a21510f2b41af307a2f4cf7fbbcf7a004431
/controleur.cpp
18fd9fb1583e9702347a1eb80f639637aa525bb5
[]
no_license
ParvilusLM/Jeu-Dames
e1b74694e1c0799be376106af11e3b0cb1a18766
0c1060c504cded4135c9940cb6ce2d712531fba7
refs/heads/master
2022-12-30T19:02:33.683449
2020-09-11T03:06:21
2020-09-11T03:06:21
242,615,825
1
0
null
null
null
null
UTF-8
C++
false
false
1,581
cpp
#include "controleur.h" Controleur::Controleur(sf::RenderWindow &fenetre):m_fenetre(0),m_decor(0) { m_fenetre=&fenetre; m_decor= new Decor(*m_fenetre); } void Controleur::debutJeu() { fin_partie=false; m_decor->CreationTableDeJeu(); m_decor->InitInfo(); m_decor->demarrerHorl(); } void Controleur::retourMenu() { m_decor->retourMenu(); jeu_en_cours=false; ensembleCaseValide.clear(); ensembleImCaseValide.clear(); ensemblePionValide.clear(); ensembleImPionValide.clear(); m_decor->effacementTJ(); } void Controleur::afficheMenu() { m_decor->AfficherMenu(); } void Controleur::afficheJeu() { m_decor->Afficher(); } void Controleur::demarrerHorl() { m_decor->demarrerHorl(); } void Controleur::compteurTemps() { m_decor->compteurTemps(); } void Controleur::gestionTour(int ind_J) { int indic=ind_J; m_decor->gestionTour(indic); //Fin_Jeu(); } void Controleur::gestionDplSouris() { m_decor->gestionDplSouris(); } void Controleur::gestionSelectionSouris() { m_decor->gestionSelectionSouris(); } void Controleur::Fin_Jeu() { m_decor->Fin_Jeu(); if(fin_partie) { ensembleCaseValide.clear(); ensembleImCaseValide.clear(); ensemblePionValide.clear(); ensembleImPionValide.clear(); m_decor->effacementTJ(); m_decor->retourMenu(); jeu_en_cours=false; } } Decor* Controleur::getDecor() { return m_decor; } void Controleur::gestMajD() { m_decor->gestMajD(); } Controleur::~Controleur() { delete m_decor; }
ede57dc9a0c79dbda9b39ee9920639eae583ec0e
ee6ff3af175a37c2b2377c5ed5f184609e134755
/oshgui/Input/Input.cpp
d280c10af3fdfc220a9d419c7cc33acb5dff2034
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
EternityX/DEADCELL-CSGO
c1363ecf5a62941954514d946137a4b791da3b36
7b873216637977d914b2eeb6893cb0cc4708aff2
refs/heads/master
2023-08-28T07:09:39.914038
2021-11-30T12:27:01
2021-11-30T12:27:01
175,938,531
597
233
MIT
2020-09-27T02:29:08
2019-03-16T07:07:59
C++
UTF-8
C++
false
false
1,150
cpp
/* * OldSchoolHack GUI * * by KN4CK3R https://www.oldschoolhack.me/ * * See license in OSHGui.hpp */ #include "Input.hpp" #include "../Application.hpp" namespace OSHGui { namespace Input { Input::Input() : enableMouseInput( true ), enableKeyboardInput( true ) { } //--------------------------------------------------------------------------- void Input::SetMouseInputEnabled( bool enable ) { enableMouseInput = enable; } //--------------------------------------------------------------------------- void Input::SetKeyboardInputEnabled( bool enable ) { enableKeyboardInput = enable; } //--------------------------------------------------------------------------- bool Input::InjectMouseMessage( const MouseMessage &mouse ) { return Application::Instance().ProcessMouseMessage( mouse ); } //--------------------------------------------------------------------------- bool Input::InjectKeyboardMessage( const KeyboardMessage &keyboard ) { return Application::Instance().ProcessKeyboardMessage( keyboard ); } //--------------------------------------------------------------------------- } }
5b4e24a30e56a9e4ac9d7236c32a9cecb1d90a15
d46f6f21bd0f49b9ceadb9d59d910767aecbed4b
/test/unit/traits_tests.cpp
8a13b011b222ddb819b4d36c69a8a3f974b8db18
[ "MIT" ]
permissive
jupp0r/hsm
ed844f17f95ba7c698577e3c1d2496b83434d231
0f2c0c989695f488d67c57ac54cd4ef4e2bb059b
refs/heads/master
2023-05-31T05:49:32.762588
2020-01-15T22:14:45
2020-01-15T22:14:45
234,135,091
1
0
MIT
2020-01-15T17:28:43
2020-01-15T17:28:42
null
UTF-8
C++
false
false
2,970
cpp
#include "hsm/hsm.h" #include <gtest/gtest.h> #include <boost/hana.hpp> using namespace ::testing; class TraitsTests : public Test { }; struct S1 { constexpr auto on_entry(){ } constexpr auto on_exit(){ } constexpr auto make_transition_table(){ } constexpr auto make_internal_transition_table() { } }; struct S2 { }; TEST_F(TraitsTests, should_recognize_exit_state) { auto exit = hsm::Exit(S1 {}, S2 {}); boost::hana::if_( hsm::is_exit_state(exit), [](auto /*exit*/) { ASSERT_TRUE(true); }, [&](auto) { ASSERT_TRUE(false); })(exit); } TEST_F(TraitsTests, should_call_callable) { namespace bh = boost::hana; auto called = false; auto callable = [&called](int){called = true;}; auto arg = 1; auto args = bh::make_tuple(arg); bh::if_(hsm::is_callable(callable, args), [arg](auto callable){return callable(arg);}, [](auto callable){return 1;})(callable); ASSERT_TRUE(called); } TEST_F(TraitsTests, should_not_call_callable) { namespace bh = boost::hana; struct Arg { }; auto callable = [](Arg /*arg*/){return 42; }; auto not_callable = [] (){throw 42; }; Arg arg; auto args = bh::make_tuple(arg); bh::if_(hsm::is_callable(callable, args), [arg](auto callable){ return callable(arg);}, [](auto callable){ return 1; })(callable); bh::if_(hsm::is_callable(not_callable, args), [arg](auto callable){ return callable(arg);}, [](auto /*callable*/){ return 1; })(not_callable); } TEST_F(TraitsTests, should_recognize_transition_table) { namespace bh = boost::hana; auto result = bh::if_(hsm::has_transition_table(S1{}), [](){ return true;}, [](){ return false;})(); ASSERT_TRUE(result); } TEST_F(TraitsTests, should_recognize_internal_transition_table) { namespace bh = boost::hana; auto result = bh::if_( hsm::has_internal_transition_table(S1 {}), []() { return true; }, []() { return false; })(); ASSERT_TRUE(result); } TEST_F(TraitsTests, should_recognize_on_entry_function) { namespace bh = boost::hana; auto result = bh::if_(hsm::has_entry_action(S1{}), [](){ return true;}, [](){ return false;})(); ASSERT_TRUE(result); } TEST_F(TraitsTests, should_recognize_on_exit_function) { namespace bh = boost::hana; auto result = bh::if_(hsm::has_exit_action(S1{}), [](){ return true;}, [](){ return false;})(); ASSERT_TRUE(result); } TEST_F(TraitsTests, should_recognize_history_state) { namespace bh = boost::hana; auto result = bh::if_( hsm::is_history_state(hsm::History { S1 {} }), []() { return true; }, []() { return false; })(); ASSERT_TRUE(result); }
2cf661035a99594de50dc0c5abd9b8fd1b0ff043
8857cab5f338cfe23756076a227afea2765f09e3
/101.cpp
640fa7cf568b963d2f1c0e1b449f998c005a6edc
[ "MIT" ]
permissive
nitin-maharana/LeetCode
c62a9b3cdc8c9e17c0a0dfb5bb05bccb0c126d37
d5e99fa313df3fda65bf385f46f8a62b6d061306
refs/heads/master
2021-01-21T13:34:39.792741
2016-05-12T16:34:29
2016-05-12T16:34:29
51,347,751
4
0
null
null
null
null
UTF-8
C++
false
false
1,658
cpp
/* * Written by Nitin Kumar Maharana * [email protected] */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //Iterative Solution. class Solution { queue<TreeNode*> q1, q2; public: bool isSymmetric(TreeNode *l, TreeNode *r) { q1.push(l); q2.push(r); TreeNode *l1, *h1; while(!q1.empty() && !q2.empty()) { l1 = q1.front(); h1 = q2.front(); q1.pop(); q2.pop(); if(!l1 && !h1) continue; if(!l1 || !h1 || (l1->val != h1->val)) return false; q1.push(l1->left); q1.push(l1->right); q2.push(h1->right); q2.push(h1->left); } return true; } bool isSymmetric(TreeNode* root) { if(!root) return true; return isSymmetric(root->left, root->right); } }; //Recursive Solution. class Solution { public: bool isSymmetric(TreeNode* l, TreeNode* r) { if(!l && !r) return true; if((!l || !r || (l->val != r->val)) return false; return (isSymmetric(l->left, r->right) && isSymmetric(l->right, r->left)); } bool isSymmetric(TreeNode* root) { if(!root) return true; return isSymmetric(root->left, root->right); } };
075bf857d672537a4349767ecef82ea372db4163
63f0a2d2d9a0231be481dcc021dd9616439bf568
/protobuf/stdafx.cpp
2c56411d770039e7ffd00dcd9da8d7a4e90604cb
[]
no_license
wdy0401/exchange_vs
ce80ac804ad03288929ddecc08d922054b785d31
b03e7033fa16db245c4b5c3528cd34258c66f7e1
refs/heads/master
2021-01-01T05:33:11.413882
2014-11-03T11:39:08
2014-11-03T11:39:08
null
0
0
null
null
null
null
GB18030
C++
false
false
270
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // write_proto_buffer.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
9b1298d5361f2b9fafca10d4010dfb2bd2c07ae0
9c713425498c8366c47c3a4ce1a50c791c24572f
/src/app/EventManagement.h
86c8e87eab3f9e71ba581e2eb21cc1f9dd6994f5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
krzysztofziobro/connectedhomeip
d17a754c88bf9a4703baf1bef222e34327042139
f07ff95183d33af17bc833c92c64e7409c6fd2eb
refs/heads/master
2023-07-17T22:46:22.035503
2021-08-28T16:08:30
2021-08-28T16:08:30
385,177,354
0
0
Apache-2.0
2021-07-12T11:39:14
2021-07-12T08:28:33
null
UTF-8
C++
false
false
25,090
h
/* * * Copyright (c) 2021 Project CHIP Authors * Copyright (c) 2015-2017 Nest Labs, Inc. * 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. */ /** * @file * * @brief * Management of the CHIP Event Logging. * */ #pragma once #include "EventLoggingDelegate.h" #include "EventLoggingTypes.h" #include <app/ClusterInfo.h> #include <app/MessageDef/EventDataElement.h> #include <app/util/basic-types.h> #include <core/CHIPCircularTLVBuffer.h> #include <messaging/ExchangeMgr.h> #include <support/PersistedCounter.h> #include <system/SystemMutex.h> #define CHIP_CONFIG_EVENT_GLOBAL_PRIORITY PriorityLevel::Debug namespace chip { namespace app { constexpr size_t kMaxEventSizeReserve = 512; constexpr uint16_t kRequiredEventField = (1 << EventDataElement::kCsTag_PriorityLevel) | (1 << EventDataElement::kCsTag_DeltaSystemTimestamp) | (1 << EventDataElement::kCsTag_EventPath); /** * @brief * Internal event buffer, built around the TLV::CHIPCircularTLVBuffer */ class CircularEventBuffer : public TLV::CHIPCircularTLVBuffer { public: /** * @brief * A constructor for the CircularEventBuffer (internal API). */ CircularEventBuffer() : CHIPCircularTLVBuffer(nullptr, 0){}; /** * @brief * A Init for the CircularEventBuffer (internal API). * * @param[in] apBuffer The actual storage to use for event storage. * * @param[in] aBufferLength The length of the \c apBuffer in bytes. * * @param[in] apPrev The pointer to CircularEventBuffer storing * events of lesser priority. * * @param[in] apNext The pointer to CircularEventBuffer storing * events of greater priority. * * @param[in] aPriorityLevel CircularEventBuffer priority level */ void Init(uint8_t * apBuffer, uint32_t aBufferLength, CircularEventBuffer * apPrev, CircularEventBuffer * apNext, PriorityLevel aPriorityLevel); /** * @brief * A helper function that determines whether the event of * specified priority is final destination * * @param[in] aPriority Priority of the event. * * @retval true/false event's priority is same as current buffer's priority, otherwise, false */ bool IsFinalDestinationForPriority(PriorityLevel aPriority) const; /** * @brief * Allocate a new event Number based on the event priority, and advance the counter * if we have one. * * @return EventNumber Event Number for this priority. */ EventNumber VendEventNumber(); /** * @brief * Remove the number of event * * @param[in] aNumEvents the number of the event. */ void RemoveEvent(EventNumber aNumEvents); /** * @brief * Given a timestamp of an event, compute the delta time to store in the log * * @param aEventTimestamp The event timestamp. * */ void UpdateFirstLastEventTime(Timestamp aEventTimestamp); void InitCounter(MonotonicallyIncreasingCounter * apEventNumberCounter) { if (apEventNumberCounter == nullptr) { mNonPersistedCounter.Init(1); mpEventNumberCounter = &(mNonPersistedCounter); return; } mpEventNumberCounter = apEventNumberCounter; mFirstEventNumber = mpEventNumberCounter->GetValue(); } PriorityLevel GetPriorityLevel() { return mPriority; } CircularEventBuffer * GetPreviousCircularEventBuffer() { return mpPrev; } CircularEventBuffer * GetNextCircularEventBuffer() { return mpNext; } void SetRequiredSpaceforEvicted(size_t aRequiredSpace) { mRequiredSpaceForEvicted = aRequiredSpace; } size_t GetRequiredSpaceforEvicted() { return mRequiredSpaceForEvicted; } EventNumber GetFirstEventNumber() { return mFirstEventNumber; } EventNumber GetLastEventNumber() { return mLastEventNumber; } uint64_t GetFirstEventSystemTimestamp() { return mFirstEventSystemTimestamp.mValue; } void SetFirstEventSystemTimestamp(uint64_t aValue) { mLastEventSystemTimestamp.mValue = aValue; } uint64_t GetLastEventSystemTimestamp() { return mLastEventSystemTimestamp.mValue; } virtual ~CircularEventBuffer() = default; private: CircularEventBuffer * mpPrev = nullptr; ///< A pointer CircularEventBuffer storing events less important events CircularEventBuffer * mpNext = nullptr; ///< A pointer CircularEventBuffer storing events more important events PriorityLevel mPriority = PriorityLevel::Invalid; ///< The buffer is the final bucket for events of this priority. Events of ///< lesser priority are dropped when they get bumped out of this buffer // The counter we're going to actually use. MonotonicallyIncreasingCounter * mpEventNumberCounter = nullptr; // The backup counter to use if no counter is provided for us. MonotonicallyIncreasingCounter mNonPersistedCounter; size_t mRequiredSpaceForEvicted = 0; ///< Required space for previous buffer to evict event to new buffer EventNumber mFirstEventNumber = 0; ///< First event Number stored in the logging subsystem for this priority EventNumber mLastEventNumber = 0; ///< Last event Number vended for this priority Timestamp mFirstEventSystemTimestamp; ///< The timestamp of the first event in this buffer Timestamp mLastEventSystemTimestamp; ///< The timestamp of the last event in this buffer }; class CircularEventReader; /** * @brief * A CircularEventBufferWrapper which has a pointer to the "current CircularEventBuffer". When trying to locate next buffer, * if nothing left there update its CircularEventBuffer until the buffer with data has been found, * the tlv reader will have a pointer to this impl. */ class CircularEventBufferWrapper : public TLV::CHIPCircularTLVBuffer { public: CircularEventBufferWrapper() : CHIPCircularTLVBuffer(nullptr, 0), mpCurrent(nullptr){}; CircularEventBuffer * mpCurrent; private: CHIP_ERROR GetNextBuffer(chip::TLV::TLVReader & aReader, const uint8_t *& aBufStart, uint32_t & aBufLen) override; }; enum class EventManagementStates { Idle = 1, // No log offload in progress, log offload can begin without any constraints InProgress = 2, // Log offload in progress Shutdown = 3 // Not capable of performing any logging operation }; /** * @brief * A helper class used in initializing logging management. * * The class is used to encapsulate the resources allocated by the caller and denotes * resources to be used in logging events of a particular priority. Note that * while resources referring to the counters are used exclusively by the * particular priority level, the buffers are shared between `this` priority * level and events that are "more" important. */ struct LogStorageResources { // TODO: Update CHIPCircularTLVBuffer with size_t for buffer size, then use ByteSpan uint8_t * mpBuffer = nullptr; // Buffer to be used as a storage at the particular priority level and shared with more important events. // Must not be nullptr. Must be large enough to accommodate the largest event emitted by the system. uint32_t mBufferSize = 0; ///< The size, in bytes, of the `mBuffer`. Platform::PersistedStorage::Key * mCounterKey = nullptr; // Name of the key naming persistent counter for events of this priority. When NULL, the persistent // counters will not be used for this priority level. uint32_t mCounterEpoch = 0; // The interval used in incrementing persistent counters. When 0, the persistent counters will not // be used for this priority level. PersistedCounter * mpCounterStorage = nullptr; // application provided storage for persistent counter for this priority level. PriorityLevel mPriority = PriorityLevel::Invalid; // Log priority level associated with the resources provided in this structure. PersistedCounter * InitializeCounter() const { if (mpCounterStorage != nullptr && mCounterKey != nullptr && mCounterEpoch != 0) { return (mpCounterStorage->Init(*mCounterKey, mCounterEpoch) != CHIP_NO_ERROR) ? mpCounterStorage : nullptr; } return nullptr; } }; /** * @brief * A class for managing the in memory event logs. * Assume we have two importance levels. DEBUG and CRITICAL, for simplicity, * A new incoming event will always get logged in buffer with debug buffer no matter it is Debug or CRITICAL event. * In order for it to get logged, we need to free up space. So we look at the tail of the buffer. * If the tail of the buffer contains a DEBUG event, that will be dropped. If the tail of the buffer contains * a CRITICAL event, that event will be 'promoted' to the next level of buffers, where it will undergo the same procedure * The outcome of this management policy is that the critical buffer is dedicated to the critical events, and the * debug buffer is shared between critical and debug events. */ class EventManagement { public: /** * @brief * Initialize the EventManagement with an array of LogStorageResources. The * array must provide a resource for each valid priority level, the elements * of the array must be in increasing numerical value of priority (and in * increasing priority); the first element in the array corresponds to the * resources allocated for least important events, and the last element * corresponds to the most critical events. * * @param[in] apExchangeManager ExchangeManager to be used with this logging subsystem * * @param[in] aNumBuffers Number of elements in inLogStorageResources array * * @param[in] apCircularEventBuffer An array of CircularEventBuffer for each priority level. * * @param[in] apLogStorageResources An array of LogStorageResources for each priority level. * */ void Init(Messaging::ExchangeManager * apExchangeManager, uint32_t aNumBuffers, CircularEventBuffer * apCircularEventBuffer, const LogStorageResources * const apLogStorageResources); static EventManagement & GetInstance(); /** * @brief Create EventManagement object and initialize the logging management * subsystem with provided resources. * * Initialize the EventManagement with an array of LogStorageResources. The * array must provide a resource for each valid priority level, the elements * of the array must be in increasing numerical value of priority (and in * decreasing priority); the first element in the array corresponds to the * resources allocated for the most critical events, and the last element * corresponds to the least important events. * * @param[in] apExchangeManager ExchangeManager to be used with this logging subsystem * * @param[in] aNumBuffers Number of elements in inLogStorageResources array * * @param[in] apCircularEventBuffer An array of CircularEventBuffer for each priority level. * @param[in] apLogStorageResources An array of LogStorageResources for each priority level. * * @note This function must be called prior to the logging being used. */ static void CreateEventManagement(Messaging::ExchangeManager * apExchangeManager, uint32_t aNumBuffers, CircularEventBuffer * apCircularEventBuffer, const LogStorageResources * const apLogStorageResources); static void DestroyEventManagement(); #if !CHIP_SYSTEM_CONFIG_NO_LOCKING class ScopedLock { public: ScopedLock(EventManagement & aEventManagement) : mEventManagement(aEventManagement) { mEventManagement.mAccessLock.Lock(); } ~ScopedLock() { mEventManagement.mAccessLock.Unlock(); } private: EventManagement & mEventManagement; }; #endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING /** * @brief * Log an event via a EventLoggingDelegate, with options. * * The EventLoggingDelegate writes the event metadata and calls the `apDelegate` * with an TLV::TLVWriter reference so that the user code can emit * the event data directly into the event log. This form of event * logging minimizes memory consumption, as event data is serialized * directly into the target buffer. The event data MUST contain * context tags to be interpreted within the schema identified by * `ClusterID` and `EventId`. The tag of the first element will be * ignored; the event logging system will replace it with the * eventData tag. * * The event is logged if the schema priority exceeds the logging * threshold specified in the LoggingConfiguration. If the event's * priority does not meet the current threshold, it is dropped and * the function returns a `0` as the resulting event ID. * * This variant of the invocation permits the caller to set any * combination of `EventOptions`: * - timestamp, when 0 defaults to the current time at the point of * the call, * - "root" section of the event source (event source and cluster ID); * if NULL, it defaults to the current device. the event is marked as * relating to the device that is making the call, * * @param[in] apDelegate The EventLoggingDelegate to serialize the event data * * @param[in] aEventOptions The options for the event metadata. * * @param[out] aEventNumber The event Number if the event was written to the * log, 0 otherwise. * * @return CHIP_ERROR CHIP Error Code */ CHIP_ERROR LogEvent(EventLoggingDelegate * apDelegate, EventOptions & aEventOptions, EventNumber & aEventNumber); /** * @brief * A helper method to get tlv reader along with buffer has data from particular priority * * @param[in,out] aReader A reference to the reader that will be * initialized with the backing storage from * the event log * * @param[in] aPriority The starting priority for the reader. * Note that in this case the starting * priority is somewhat counter intuitive: * more important events share the buffers * with less priority events, in addition to * their dedicated buffers. As a result, the * reader will traverse the least data when * the Debug priority is passed in. * * @param[in] apBufWrapper CircularEventBufferWrapper * @return #CHIP_NO_ERROR Unconditionally. */ CHIP_ERROR GetEventReader(chip::TLV::TLVReader & aReader, PriorityLevel aPriority, app::CircularEventBufferWrapper * apBufWrapper); /** * @brief * A function to retrieve events of specified priority since a specified event ID. * * Given a TLV::TLVWriter, an priority type, and an event ID, the * function will fetch events of specified priority since the * specified event. The function will continue fetching events until * it runs out of space in the TLV::TLVWriter or in the log. The function * will terminate the event writing on event boundary. * * @param[in] aWriter The writer to use for event storage * @param[in] apClusterInfolist the interested cluster info list with event path inside * @param[in] aPriority The priority of events to be fetched * * @param[in,out] aEventNumber On input, the Event number immediately * prior to the one we're fetching. On * completion, the event number of the last event * fetched. * * @param[out] aEventCount The number of fetched event * @retval #CHIP_END_OF_TLV The function has reached the end of the * available log entries at the specified * priority level * * @retval #CHIP_ERROR_NO_MEMORY The function ran out of space in the * aWriter, more events in the log are * available. * * @retval #CHIP_ERROR_BUFFER_TOO_SMALL The function ran out of space in the * aWriter, more events in the log are * available. * */ CHIP_ERROR FetchEventsSince(chip::TLV::TLVWriter & aWriter, ClusterInfo * apClusterInfolist, PriorityLevel aPriority, EventNumber & aEventNumber, size_t & aEventCount); /** * @brief * Schedule a log offload task. * * The function decides whether to schedule a task offload process, * and if so, it schedules the `LoggingFlushHandler` to be run * asynchronously on the Chip thread. * * The decision to schedule a flush is dependent on three factors: * * -- an explicit request to flush the buffer * * -- the state of the event buffer and the amount of data not yet * synchronized with the event consumers * * -- whether there is an already pending request flush request event. * * The explicit request to schedule a flush is passed via an input * parameter. * * The automatic flush is typically scheduled when the event buffers * contain enough data to merit starting a new offload. Additional * triggers -- such as minimum and maximum time between offloads -- * may also be taken into account depending on the offload strategy. * * * @param aUrgent indiate whether the flush should be scheduled if it is urgent * * @retval #CHIP_ERROR_INCORRECT_STATE EventManagement module was not initialized fully. * @retval #CHIP_NO_ERROR On success. */ CHIP_ERROR ScheduleFlushIfNeeded(EventOptions::Type aUrgent); /** * @brief * Fetch the most recently vended Number for a particular priority level * * @param aPriority Priority level * * @return EventNumber most recently vended event Number for that event priority */ EventNumber GetLastEventNumber(PriorityLevel aPriority); /** * @brief * Fetch the first event Number currently stored for a particular priority level * * @param aPriority Priority level * * @return EventNumber First currently stored event Number for that event priority */ EventNumber GetFirstEventNumber(PriorityLevel aPriority); /** * @brief * IsValid returns whether the EventManagement instance is valid */ bool IsValid(void) { return EventManagementStates::Shutdown != mState; }; /** * Logger would save last logged event number for each logger buffer into schedule event number array */ void SetScheduledEventEndpoint(EventNumber * aEventEndpoints); private: CHIP_ERROR CalculateEventSize(EventLoggingDelegate * apDelegate, const EventOptions * apOptions, uint32_t & requiredSize); /** * @brief Helper function for writing event header and data according to event * logging protocol. * * @param[in,out] apContext EventLoadOutContext, initialized with stateful * information for the buffer. State is updated * and preserved by ConstructEvent using this context. * * @param[in] apDelegate The EventLoggingDelegate to serialize the event data * * @param[in] apOptions EventOptions describing timestamp and other tags * relevant to this event. * */ CHIP_ERROR ConstructEvent(EventLoadOutContext * apContext, EventLoggingDelegate * apDelegate, const EventOptions * apOptions); // Internal function to log event CHIP_ERROR LogEventPrivate(EventLoggingDelegate * apDelegate, EventOptions & aEventOptions, EventNumber & aEventNumber); /** * @brief copy the event outright to next buffer with higher priority * * @param[in] apEventBuffer CircularEventBuffer * */ CHIP_ERROR CopyToNextBuffer(CircularEventBuffer * apEventBuffer); /** * @brief eusure current buffer has enough space, if not, when current buffer is final destination of last tail's event * priority, we need to drop event, otherwises, move the last event to the buffer with higher priority * * @param[in] aRequiredSpace require space * */ CHIP_ERROR EnsureSpaceInCircularBuffer(size_t aRequiredSpace); /** * @brief * Internal API used to implement #FetchEventsSince * * Iterator function to used to copy an event from the log into a * TLVWriter. The included apContext contains the context of the copy * operation, including the TLVWriter that will hold the copy of an * event. If event cannot be written as a whole, the TLVWriter will * be rolled back to event boundary. * * @retval #CHIP_END_OF_TLV Function reached the end of the event * @retval #CHIP_ERROR_NO_MEMORY Function could not write a portion of * the event to the TLVWriter. * @retval #CHIP_ERROR_BUFFER_TOO_SMALL Function could not write a * portion of the event to the TLVWriter. */ static CHIP_ERROR CopyEventsSince(const TLV::TLVReader & aReader, size_t aDepth, void * apContext); /** * @brief Internal iterator function used to scan and filter though event logs * * The function is used to scan through the event log to find events matching the spec in the supplied context. * Particularly, it would check against mStartingEventNumber, and skip fetched event. */ static CHIP_ERROR EventIterator(const TLV::TLVReader & aReader, size_t aDepth, EventLoadOutContext * apEventLoadOutContext); /** * @brief Internal iterator function used to fetch event into EventEnvelopeContext, then EventIterator would filter event * based upon EventEnvelopeContext * */ static CHIP_ERROR FetchEventParameters(const TLV::TLVReader & aReader, size_t aDepth, void * apContext); /** * @brief Internal iterator function used to scan and filter though event logs * First event gets a timestamp, subsequent ones get a delta T * First event in the sequence gets a event number neatly packaged */ static CHIP_ERROR CopyAndAdjustDeltaTime(const TLV::TLVReader & aReader, size_t aDepth, void * apContext); /** * @brief checking if the tail's event can be moved to higher priority, if not, dropped, if yes, note how much space it * requires, and return. */ static CHIP_ERROR EvictEvent(chip::TLV::CHIPCircularTLVBuffer & aBuffer, void * apAppData, TLV::TLVReader & aReader); static CHIP_ERROR AlwaysFail(chip::TLV::CHIPCircularTLVBuffer & aBuffer, void * apAppData, TLV::TLVReader & aReader) { return CHIP_ERROR_NO_MEMORY; }; /** * @brief copy event from circular buffer to target buffer for report */ static CHIP_ERROR CopyEvent(const TLV::TLVReader & aReader, TLV::TLVWriter & aWriter, EventLoadOutContext * apContext); /** * @brief * A function to get the circular buffer for particular priority * * @param aPriority PriorityLevel * * @return A pointer for the CircularEventBuffer */ CircularEventBuffer * GetPriorityBuffer(PriorityLevel aPriority) const; // EventBuffer for debug level, CircularEventBuffer * mpEventBuffer = nullptr; Messaging::ExchangeManager * mpExchangeMgr = nullptr; EventManagementStates mState = EventManagementStates::Shutdown; uint32_t mBytesWritten = 0; #if !CHIP_SYSTEM_CONFIG_NO_LOCKING System::Mutex mAccessLock; #endif // !CHIP_SYSTEM_CONFIG_NO_LOCKING }; } // namespace app } // namespace chip
158387ca03d0730f80cc46bf824dc70ffda97a57
5161777e938bb937b0670559fe9b020938fd2579
/kernel/x86/apci/LocalAPCI.h
a318394bebbda177bf0a79ef3014e034162d7f82
[ "Apache-2.0" ]
permissive
KKRainbow/FreeCROS
30fc53aca1138854cdaf57afb02c09838536b234
312f3f7d802187a9324d6c7f028d3c53e8a23b51
refs/heads/master
2021-01-10T16:40:51.568765
2015-06-04T10:49:13
2015-06-04T10:49:13
36,864,694
5
0
null
null
null
null
UTF-8
C++
false
false
1,451
h
/* * Copyright 2015 <copyright holder> <email> * * 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. * */ #pragma once #include"Global.h" union IPIMessage; class LocalAPIC { private: static volatile char* baseAddr; static bool CPUHasMSR(); static void CPUGetMSR(uint32_t _Msr, uint32_t *_Lo, uint32_t *_Hi); static void CPUSetMSR(uint32_t _Msr, uint32_t _Lo, uint32_t _Hi); static void WriteRegister(int _Offset,uint32_t _Val); static uint32_t ReadRegister(int _Offset); static void SetAPICBaseReg(uint64_t _Addr); static uint64_t GetAPICBaseReg(); static void SendIPI(IPIMessage* _Msg); static void ResetLAPIC(); static void EnableLAPIC(); public: static bool InitAPCI(); static void EOI(); static int GetLocalAPICID(); static void InitAPs(int _APICID,void (*_Entry)(),addr_t _StackAddr,size_t _StackSize); static void InterruptCPU(int _APICID,int _Irq); static void InterruptAllOtherCPU(int _Irq); };
05c41f33c3afd614c2e25f8f5aab9d70dbc9b108
534744706ed8c8cfb5614c0ccc6485c0b1c9181d
/usaco/test.cpp
882785ba3efa033820c836834ed7101450ad092d
[]
no_license
walterpcasas/icpc
a7e72e0e69afa7f2a6a2dde4fa0268e743f9cf7a
758ce006dfc3945a9f62c525d55528ada64749a5
refs/heads/master
2022-12-15T01:04:05.218437
2020-09-04T09:00:17
2020-09-04T09:00:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
/* ID: wperezc1 TASK:test LANG: C++ */ #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ ofstream fout ("test.out"); ifstream fin ("test.in"); int a, b; fin >> a >> b; fout << a+b << endl; return 0; }
6eba6b26bb989d1a37f4c1b736fafcf57060d37a
72f2992a3659ff746ba5ce65362acbe85a918df9
/apps-src/apps/external/zxing/pdf417/PDFBarcodeValue.h
d7d8ca7e92b51433160b4cb365a0f3e114eac678
[ "BSD-2-Clause" ]
permissive
chongtianfeiyu/Rose
4742f06ee9ecd55f9717ac6378084ccf8bb02a15
412175b57265ba2cda1e33dd2047a5a989246747
refs/heads/main
2023-05-23T14:03:08.095087
2021-06-19T13:23:58
2021-06-19T14:00:25
391,238,554
0
1
BSD-2-Clause
2021-07-31T02:39:25
2021-07-31T02:39:24
null
UTF-8
C++
false
false
1,183
h
#pragma once /* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * 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 <map> #include <vector> namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class BarcodeValue { std::map<int, int> _values; public: /** * Add an occurrence of a value */ void setValue(int value); /** * Determines the maximum occurrence of a set value and returns all values which were set with this occurrence. * @return an array of int, containing the values with the highest occurrence, or null, if no value was set */ std::vector<int> value() const; int confidence(int value) const; }; } // Pdf417 } // ZXing
896c9aef6f2324be98e417d77d492554b2109625
1f80af8f6e0b6b3cbfe66f4b04feb6620524f895
/solutions/354. Russian Doll Envelopes.cpp
3097cc6d8c6d941af630f9ec83c8f3208f9cee0d
[]
no_license
satvik-2-9/Leetcode
fff6d3484e0c053a6401225293ca8478c0debdec
422586dfe3ca7b36e6a2e140808f73288561f4d2
refs/heads/master
2023-06-21T22:05:05.779773
2021-07-15T14:37:57
2021-07-15T14:37:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
struct node{    int l,w; }; bool comp(node a ,node b){    if(a.l==b.l)        return a.w>b.w;    return a.l<b.l; } class Solution { public:    int maxEnvelopes(vector<vector<int>>& p) {        int n=p.size();        if(n==0)            return 0;        node arr[n];        for(int i=0;i<n;i++){            arr[i].l=p[i][0];            arr[i].w=p[i][1];       }        sort(arr,arr+n,comp);        int ans=0,temp[n];        for(int i=0;i<n;i++){            int lo=0,hi=ans;            while(lo<hi){                int mid=lo+(hi-lo)/2;                if(temp[mid]<arr[i].w)                    lo=mid+1;                else                    hi=mid;           }            temp[lo]=arr[i].w;            if(lo==ans)                ans++;       }        return ans;   } };