blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
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
listlengths
1
1
author
stringlengths
0
119
d9e9cf34d5bda0c3b958cd5f09fb171fd78f35f3
6c3d274858d062894ac4ff8aed2e4962f3a0d1fb
/src/crypto/key_pair.cpp
0b723bcc1401be2e8ca11b1e0c7df142dc425521
[ "Apache-2.0" ]
permissive
eddyashton/CCF
eab68ba7afb05a3cc4460aacae2c52fbe7c6171f
de7329a31d57774bc135c41bc60c0fd4888fb107
refs/heads/main
2023-08-19T08:53:19.594030
2022-08-02T14:10:12
2022-08-02T14:10:12
184,758,106
0
1
Apache-2.0
2023-03-20T14:59:57
2019-05-03T13:15:33
C++
UTF-8
C++
false
false
829
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #include "ccf/crypto/key_pair.h" #include "openssl/key_pair.h" #include "openssl/public_key.h" #include <cstring> #include <iomanip> #include <limits> #include <memory> #include <string> namespace crypto { using PublicKeyImpl = PublicKey_OpenSSL; using KeyPairImpl = KeyPair_OpenSSL; PublicKeyPtr make_public_key(const Pem& pem) { return std::make_shared<PublicKeyImpl>(pem); } PublicKeyPtr make_public_key(const std::vector<uint8_t>& der) { return std::make_shared<PublicKeyImpl>(der); } KeyPairPtr make_key_pair(CurveID curve_id) { return std::make_shared<KeyPairImpl>(curve_id); } KeyPairPtr make_key_pair(const Pem& pem) { return std::make_shared<KeyPairImpl>(pem); } }
[ "noreply@github.com" ]
noreply@github.com
a98eb3e9414207671f53e522d9d4ab476d835749
957446b38390a50915647f3becf4656262ec9c46
/src/cpp/framework/graphics/mainLoop.hpp
ff1d6e3cc9bc2d8aa345684fe23a8253f2d7226e
[]
no_license
przempore/car_crash
58bfdba1ad3c64c0616004d23bb12cb3b3ed7244
c99dab0d17bfaed1a762b7f38bad777d58d60b64
refs/heads/master
2021-07-11T13:44:07.718677
2020-10-18T14:54:22
2020-10-18T14:54:22
214,025,750
0
0
null
2020-01-22T00:40:32
2019-10-09T21:19:27
C++
UTF-8
C++
false
false
326
hpp
#ifndef CAR_CRASH_SRC_FRAMEWORK_DETAILS_MAINLOOP_HPP_ #define CAR_CRASH_SRC_FRAMEWORK_DETAILS_MAINLOOP_HPP_ #include <cstdint> #include "../utilities/client_config.hpp" namespace CC { bool mainLoop(const ClientConfig& config = ClientConfig{}); } // namespace CC #endif // CAR_CRASH_SRC_FRAMEWORK_DETAILS_MAINLOOP_HPP_
[ "przempore@gmail.com" ]
przempore@gmail.com
f18e3524c400e66723c18d74572aad88d85d159d
6d08a769349fd93adc038102871188a7f02112c3
/MarbleGame/Lightning.h
75f44cb1eba96c4eb7031a8de779104027fb327d
[]
no_license
joles772/MarbleGame
3c9682313922dba07a21397e5239a388b6352133
f40cb722569733ca9ec26ed99e64fb742ea40d52
refs/heads/master
2020-03-25T17:57:46.483066
2018-08-08T12:17:01
2018-08-08T12:17:01
144,005,637
0
0
null
null
null
null
UTF-8
C++
false
false
183
h
#pragma once #include "Level.h" class Lightning { public: Lightning(); ~Lightning(); void draw(); void makeBolt(); std::vector<std::vector<Level::Point>> bolt; int myTex; };
[ "audentity5@gmail.com" ]
audentity5@gmail.com
1bf7bcc8a6c3c1de6d1cafafdd8c14f3f96f88f0
14079921f08d92421b43f114e74f923869368e52
/20191024/p_sort_based_on_me.cpp
4c50d191b2c79740f21cc75e1a8e48941754cf3f
[]
no_license
danbi5228/Algorithm
07078099e05668dbc63c087045d6bbd47fb3bc9c
9fda640315d225a1f8e89d38896ef300391918eb
refs/heads/master
2021-07-11T07:59:15.580315
2020-10-06T14:36:11
2020-10-06T14:36:11
195,342,125
0
0
null
null
null
null
UHC
C++
false
false
691
cpp
/* 프로그래머스 - 문자열 내 마음대로 정렬하기 */ #include <string> #include <vector> #include <utility> #include <algorithm> using namespace std; vector<string> solution(vector<string> strings, int n) { vector<pair<char, int>> tmp; vector<string> answer; sort(strings.begin(), strings.end()); for (int i = 0; i < strings.size(); i++) { tmp.push_back(make_pair(strings[i][n], i)); } sort(tmp.begin(), tmp.end()); for (int i = 0; i < tmp.size(); i++) { answer.push_back(strings[tmp[i].second]); } return answer; } //python //def solution(strings, n) : // strings = sorted(strings) // strings = sorted(strings, key = lambda word : word[n]) // return strings
[ "danbi5228@naver.com" ]
danbi5228@naver.com
727439c3663717d23da0f87fe791444366f9a575
3608b898eb89c48434390f4db6dd0ddbdbafeadb
/Lab_1/chap3_exercise11.cpp
9bdf57eda96e0c16f69dcc4267bf47d7ea680599
[]
no_license
sirasjad/DFOD1200
6d8cb93a2d1e659178a0555152efafcce250dea4
e6986ee56b75fa0cd3f2d37cac824630babe4678
refs/heads/master
2021-09-22T20:05:27.566930
2018-09-14T22:16:07
2018-09-14T22:16:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,246
cpp
#include <iostream> using namespace std; void konverter(int orer){ system("clear"); long int kroner = 0; long int femti_lapp = 0; long int hundre_lapp = 0; long int femhundre_lapp = 0; long int tusen_lapp = 0; if(orer >= 100){ kroner = orer / 100; orer = orer % 100; } if(kroner >= 50){ femti_lapp = kroner / 50; kroner = kroner % 50; } if(femti_lapp >= 2){ hundre_lapp = femti_lapp / 2; femti_lapp = femti_lapp % 2; } if(hundre_lapp >= 5){ femhundre_lapp = hundre_lapp / 5; hundre_lapp = hundre_lapp % 5; } if(femhundre_lapp >= 2){ tusen_lapp = femhundre_lapp / 2; femhundre_lapp = femhundre_lapp % 2; } cout << "----- DU HAR: -----" << endl; cout << "Ører: \t \t \t" << orer << " stk." << endl; cout << "Kroner: \t \t" << kroner << " stk." << endl; cout << "Femti-lapp: \t \t" << femti_lapp << " stk." << endl; cout << "Hundre-lapp: \t \t" << hundre_lapp << " stk." << endl; cout << "Femhundre-lapp: \t" << femhundre_lapp << " stk." << endl; cout << "Tusen-lapp: \t \t" << tusen_lapp << " stk." << endl; cout << endl; } int main(){ long int orer = 0; cout << "Hvor mange ører har du?: "; cin >> orer; konverter(orer); main(); return 0; }
[ "sirasjad@gmail.com" ]
sirasjad@gmail.com
112a909cf75dc87ca057a1296f74431c049d7974
ceac06d12a7983d67c9f2e88176b1241ba66fe44
/Inversion_LUP1/INLINE/syn/systemc/inverse_top_fadd_bkb.h
51b23be4d5f8edaa5433c2c13436a83f41ffd2a7
[]
no_license
garvitgupta08/Matrix-multiplication-and-inversion-IP-in-HLS
1a84e1788151b18b8dc54c203cb441bf68393bc2
a9e686e4710abb7e648145520416fc40400763b9
refs/heads/master
2022-12-29T19:26:00.873927
2020-10-02T13:42:31
2020-10-02T13:42:31
297,989,533
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
h
// ============================================================== // Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2019.1 (64-bit) // Copyright 1986-2019 Xilinx, Inc. All Rights Reserved. // ============================================================== #ifndef __inverse_top_fadd_bkb__HH__ #define __inverse_top_fadd_bkb__HH__ #include "ACMP_fadd.h" #include <systemc> template< int ID, int NUM_STAGE, int din0_WIDTH, int din1_WIDTH, int dout_WIDTH> SC_MODULE(inverse_top_fadd_bkb) { sc_core::sc_in_clk clk; sc_core::sc_in<sc_dt::sc_logic> reset; sc_core::sc_in<sc_dt::sc_logic> ce; sc_core::sc_in< sc_dt::sc_lv<din0_WIDTH> > din0; sc_core::sc_in< sc_dt::sc_lv<din1_WIDTH> > din1; sc_core::sc_out< sc_dt::sc_lv<dout_WIDTH> > dout; ACMP_fadd<ID, 5, din0_WIDTH, din1_WIDTH, dout_WIDTH> ACMP_fadd_U; SC_CTOR(inverse_top_fadd_bkb): ACMP_fadd_U ("ACMP_fadd_U") { ACMP_fadd_U.clk(clk); ACMP_fadd_U.reset(reset); ACMP_fadd_U.ce(ce); ACMP_fadd_U.din0(din0); ACMP_fadd_U.din1(din1); ACMP_fadd_U.dout(dout); } }; #endif //
[ "garvit.gupta08@gmail.com" ]
garvit.gupta08@gmail.com
7731ed639024820e8225be970c0458e20c011214
43cc6231174c84d9b544525f6e7fc42eede8c7bc
/plugin/sample/plugin-interfaces/AppAbstractPlugin.h
6fe180d238fd2e7dcfdf439314abf56e145ce659
[ "MIT" ]
permissive
hasboeuf/hb
e469a6de8ae26416c8e306500022e92bb540d31f
d812f2ef56d7c79983701f1f673ce666b189b638
refs/heads/master
2020-04-23T10:39:12.893445
2019-04-16T22:55:53
2019-04-16T22:55:53
171,110,849
1
0
null
null
null
null
UTF-8
C++
false
false
683
h
#ifndef APPABSTRACTPLUGIN_H #define APPABSTRACTPLUGIN_H // Hb #include <IHbPlugin.h> // Local #include <AppPlatformService.h> // Covariance. namespace hb { namespace pluginexample { using hb::plugin::IHbPlugin; class AppAbstractPlugin : public IHbPlugin { public: explicit AppAbstractPlugin(); virtual ~AppAbstractPlugin(); virtual PluginInitState init(const HbPluginPlatform* platform_service); virtual void unload() = 0; protected: const AppPlatformService* mPlatformService; }; } // namespace pluginexample } // namespace hb Q_DECLARE_INTERFACE(hb::pluginexample::AppAbstractPlugin, "hb::pluginexample::AppAbstractPlugin") #endif // APPABSTRACTPLUGIN_H
[ "adrien.gavignet@gmail.com" ]
adrien.gavignet@gmail.com
18021f2f31075da7b9df055f496ec248fea5f668
a2ab786968c8e9361cf79ef438b87605a5c626bf
/build-QtTcpClientConsumer-Desktop_Qt_5_10_1_MinGW_32bit-Debug/ui_mainwindow.h
8601ba22a3ace91da060f35f22560cfbf1855b9b
[]
no_license
Kennedi1313/DCA1202_clients
8c95efcaa9746d05e64ea7bad19cd56364446834
1a9aeec8c7fada3ce604a61d704909ecfac8fc57
refs/heads/master
2020-03-21T17:00:25.493807
2018-06-27T00:16:52
2018-06-27T00:16:52
138,807,255
0
1
null
null
null
null
UTF-8
C++
false
false
8,343
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.10.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QListWidget> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSlider> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> #include "plotter.h" QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; Plotter *widget; QWidget *layoutWidget; QVBoxLayout *verticalLayout_2; QLabel *label; QLineEdit *lineEdit_Ip; QHBoxLayout *horizontalLayout; QPushButton *pushButton_Connect; QPushButton *pushButton_Disconnect; QListWidget *listWidget; QHBoxLayout *horizontalLayout_3; QSpacerItem *horizontalSpacer; QPushButton *pushButton_Update; QVBoxLayout *verticalLayout; QLabel *label_2; QHBoxLayout *horizontalLayout_2; QSlider *horizontalSlider_Time; QLabel *label_Time; QHBoxLayout *horizontalLayout_4; QSpacerItem *horizontalSpacer_2; QPushButton *pushButton_Start; QSpacerItem *horizontalSpacer_3; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(691, 488); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); widget = new Plotter(centralWidget); widget->setObjectName(QStringLiteral("widget")); widget->setEnabled(true); widget->setGeometry(QRect(350, 20, 281, 381)); layoutWidget = new QWidget(centralWidget); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(40, 20, 258, 380)); verticalLayout_2 = new QVBoxLayout(layoutWidget); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); label = new QLabel(layoutWidget); label->setObjectName(QStringLiteral("label")); verticalLayout_2->addWidget(label); lineEdit_Ip = new QLineEdit(layoutWidget); lineEdit_Ip->setObjectName(QStringLiteral("lineEdit_Ip")); verticalLayout_2->addWidget(lineEdit_Ip); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); pushButton_Connect = new QPushButton(layoutWidget); pushButton_Connect->setObjectName(QStringLiteral("pushButton_Connect")); horizontalLayout->addWidget(pushButton_Connect); pushButton_Disconnect = new QPushButton(layoutWidget); pushButton_Disconnect->setObjectName(QStringLiteral("pushButton_Disconnect")); horizontalLayout->addWidget(pushButton_Disconnect); verticalLayout_2->addLayout(horizontalLayout); listWidget = new QListWidget(layoutWidget); listWidget->setObjectName(QStringLiteral("listWidget")); verticalLayout_2->addWidget(listWidget); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setSpacing(6); horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3")); horizontalSpacer = new QSpacerItem(108, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer); pushButton_Update = new QPushButton(layoutWidget); pushButton_Update->setObjectName(QStringLiteral("pushButton_Update")); horizontalLayout_3->addWidget(pushButton_Update); verticalLayout_2->addLayout(horizontalLayout_3); verticalLayout = new QVBoxLayout(); verticalLayout->setSpacing(6); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); label_2 = new QLabel(layoutWidget); label_2->setObjectName(QStringLiteral("label_2")); verticalLayout->addWidget(label_2); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setSpacing(6); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); horizontalSlider_Time = new QSlider(layoutWidget); horizontalSlider_Time->setObjectName(QStringLiteral("horizontalSlider_Time")); horizontalSlider_Time->setMinimum(1); horizontalSlider_Time->setMaximum(10); horizontalSlider_Time->setOrientation(Qt::Horizontal); horizontalLayout_2->addWidget(horizontalSlider_Time); label_Time = new QLabel(layoutWidget); label_Time->setObjectName(QStringLiteral("label_Time")); horizontalLayout_2->addWidget(label_Time); verticalLayout->addLayout(horizontalLayout_2); verticalLayout_2->addLayout(verticalLayout); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setSpacing(6); horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4")); horizontalSpacer_2 = new QSpacerItem(48, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer_2); pushButton_Start = new QPushButton(layoutWidget); pushButton_Start->setObjectName(QStringLiteral("pushButton_Start")); horizontalLayout_4->addWidget(pushButton_Start); horizontalSpacer_3 = new QSpacerItem(48, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer_3); verticalLayout_2->addLayout(horizontalLayout_4); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 691, 21)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); QObject::connect(horizontalSlider_Time, SIGNAL(valueChanged(int)), label_Time, SLOT(setNum(int))); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr)); label->setText(QApplication::translate("MainWindow", "IP do Servidor", nullptr)); pushButton_Connect->setText(QApplication::translate("MainWindow", "Connect", nullptr)); pushButton_Disconnect->setText(QApplication::translate("MainWindow", "Disconnect", nullptr)); pushButton_Update->setText(QApplication::translate("MainWindow", "Update", nullptr)); label_2->setText(QApplication::translate("MainWindow", "Timing", nullptr)); label_Time->setText(QApplication::translate("MainWindow", "1", nullptr)); pushButton_Start->setText(QApplication::translate("MainWindow", "Start", nullptr)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "francisco_kennedi@hotmail.com" ]
francisco_kennedi@hotmail.com
dc92b511716b90b209f11496cb6bc78734f2e949
0e2e14c9de81ba0bcdd7d0ed76a45c96e87a5487
/D01 - C++ Basics 2/ex05/Brain.cpp
351b3205a33ed4d6caa5ef59c69681588455492c
[]
no_license
Oksanatishka/42_Piscine_CPP
a42dfb11771cc81431b2787ec323caa39735455e
b5aa739a8676155426aad376080da7912f945c7b
refs/heads/master
2020-04-17T23:43:05.792585
2019-02-07T19:30:55
2019-02-07T19:30:55
167,047,503
0
0
null
null
null
null
UTF-8
C++
false
false
233
cpp
#include "Brain.hpp" Brain::Brain( bool isSmart ) : _isSmart(isSmart) { if (_isSmart || !_isSmart) _addres << this; } Brain::~Brain( void ) { return ; } std::string Brain::identify( void ) const { return _addres.str(); }
[ "oksanabibik93@gmail.com" ]
oksanabibik93@gmail.com
5c2fd8e4d83b48c8a22a313daf28b8ac46e58322
27907c027a68125ac9602755aaba5fc21a39ab8e
/PrintBuf.h
d13cbbea1e6fe0fe3396b704a61db315fb45c0f5
[]
no_license
davies46/Wet-Room-Controller
2ca8c11b572d34abfdeb915622e5c5cf58c8d7e9
df17514643ec9960e0e37b8797a15eec2759baa3
refs/heads/master
2021-07-07T16:17:45.292135
2017-10-04T09:57:55
2017-10-04T09:57:55
105,750,054
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
/* * PrintBuf.h * * Created on: 27 Dec 2014 * Author: pdavies */ #ifndef PRINTBUF_H_ #define PRINTBUF_H_ #include <Arduino.h> class PrintBuf: public Print { uint8_t buf[128]; char *bufP; uint8_t lastLen; public: inline PrintBuf() { bufP = (char*) buf; } virtual ~PrintBuf() { } inline char *consume() { //put eol at end then return bufP to start *bufP++ = '\0'; lastLen = bufP - (char*) buf; bufP = (char*) buf; return bufP; } inline uint8_t getLen() { return lastLen; } inline size_t write(uint8_t ch) { *bufP++ = ch; return 1; } inline size_t write(const uint8_t *buffer, size_t size) { const char* srcP = (char*) buffer; strcpy(bufP, srcP); bufP += size; return size; } }; #endif /* PRINTBUF_H_ */
[ "phil.m.davies@gmail.com" ]
phil.m.davies@gmail.com
c501cdc514489aaf77e81b34d2bdd67ac610c25a
d9c164c8b2319b67775f3a3a0e7dbcb1f9c5b7c6
/lib/ClockTimer/src/RtcWrapper.h
7e0e22209ae51550a2dc7122e489828d7cf79c91
[]
no_license
kseebaldt/clock_rtc
93fdd944f5ad9c9b5816bcc426b5918202bfad83
afe918139fe1f66036ebe64e84eaff1d59b48d17
refs/heads/master
2021-09-08T07:29:24.484525
2019-05-21T21:20:42
2019-05-21T21:20:42
186,190,411
1
0
null
null
null
null
UTF-8
C++
false
false
501
h
#ifndef _RTCWRAPPER_H_ #define _RTCWRAPPER_H_ #ifdef ARDUINO #include "RTClib.h" typedef RTC_DS1307 RtcWrapper; #else #include "FakeRtc.h" class RtcWrapper { public: boolean begin(void); static void adjust(const DateTime& dt); uint8_t isrunning(void); static DateTime now(); uint8_t readnvram(uint8_t address); void writenvram(uint8_t address, uint8_t data); }; #endif #endif /* _RTCWRAPPER_H_ */
[ "kseebaldt@gmail.com" ]
kseebaldt@gmail.com
ec92a487dc8f5f52cfafd24913951201917d4f7b
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/SOC/2011/simd/libs/simd/mini_nt2/nt2/include/functions/arg.hpp
cd6ea28cb104c81656fa7c5dae29e4ab07618215
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
163
hpp
#ifndef NT2_INCLUDE_FUNCTIONS_ARG_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_ARG_HPP_INCLUDED #include <nt2/toolbox/arithmetic/include/functions/arg.hpp> #endif
[ "loufoque@gmail.com" ]
loufoque@gmail.com
9d22c8ee41964429f5819d880b0697e749bd86ee
dcbd41891a4dfefe941a73ca071e5553a367ed8f
/CFightingScriptSetting.cpp
f478ea7ecaabae6b3f4fd8d0342911deb08726ae
[]
no_license
cuiopen/GameServer-4
dbaf074c127d3cd5a0aae47e2303d6b0e6b01633
3235d24a9eeeb065bd5296d2e36d8ccba3174836
refs/heads/master
2020-03-19T15:47:26.790489
2015-05-15T01:48:03
2015-05-15T01:48:03
null
0
0
null
null
null
null
GB18030
C++
false
false
6,715
cpp
#include <memory> #include "CFightingScriptSetting.h" template<> CCFightingScriptSetting* CCSingleton<CCFightingScriptSetting>::ms_Singleton=0; CCFightingScriptSetting::CCFightingScriptSetting(void) { } CCFightingScriptSetting::~CCFightingScriptSetting(void) { } //根据世界ID获取世界副本信息 CT_BOOL CCFightingScriptSetting::GetWorldScene(CT_INT32 iWorldSceneID,G_WorldScene &WorldScne) { return 0 != G_GetWorldScene(iWorldSceneID+1,&WorldScne); } //根据副本ID获取副本信息 CT_BOOL CCFightingScriptSetting::GetFightingScene(CT_INT32 iWorldSceneID,CT_INT32 iSceneID,CT_INT32 iDifficulty,G_FightingScene &FightingScene) { return 0 != G_GetFightingScene(iWorldSceneID+1,iSceneID+1,iDifficulty+1,&FightingScene); } //根据副本ID获取副本场景奖励 CT_BOOL CCFightingScriptSetting::GetSceneReward(CT_INT32 iSceneID,CT_INT32 iReward,G_SceneReward &SceneReward) { return 0 != G_GetSceneReward(iSceneID+1,iReward,&SceneReward); } //根据副本ID和怪物波数获取怪物组 CT_BOOL CCFightingScriptSetting::GetMonsterGroup(CT_INT32 iWorldSceneID,CT_INT32 iSceneID,CT_INT32 iDifficulty,G_MonsterGroup &MonsterGroup) { G_FightingScene FightingScene={0}; if(!G_GetFightingScene(iWorldSceneID+1,iSceneID+1,iDifficulty+1,&FightingScene)) { return CT_FALSE; } return 0 != G_GetMonsterGroup(iWorldSceneID+1,FightingScene.iMosterGroupID,&MonsterGroup); } //根据怪物组和位置获取怪物信息 CT_BOOL CCFightingScriptSetting::GetMonsterData(const G_MonsterGroup MonsterGroup,CT_INT32 iPosition,G_MonsterBaseInfo &MonsterInfo) { //读取怪物组脚本 switch(iPosition) { case 0: { if(MonsterGroup.iBeforeMoster1 == 0)break; if(!G_GetMonsterBaseInfoData(MonsterGroup.iBeforeMoster1,&MonsterInfo)) { return CT_FALSE; } else return CT_TRUE; break; } case 1: { if(MonsterGroup.iBeforeMoster2 == 0)break; if(!G_GetMonsterBaseInfoData(MonsterGroup.iBeforeMoster2,&MonsterInfo)) { return CT_FALSE; } else return CT_TRUE; break; } case 2: { if(MonsterGroup.iMediumMoster == 0)break; if(!G_GetMonsterBaseInfoData(MonsterGroup.iMediumMoster,&MonsterInfo)) { return CT_FALSE; } else return CT_TRUE; break; } case 3: { if(MonsterGroup.iAfterMoster1 == 0)break; if(!G_GetMonsterBaseInfoData(MonsterGroup.iAfterMoster1,&MonsterInfo)) { return CT_FALSE; } else return CT_TRUE; break; } case 4: { if(MonsterGroup.iAfterMoster2 == 0)break; if(!G_GetMonsterBaseInfoData(MonsterGroup.iAfterMoster2,&MonsterInfo)) { return CT_FALSE; } else return CT_TRUE; break; } default: { return CT_FALSE; } } return CT_FALSE; } //根据军衔等级和类型获取PVP宝箱 CT_BOOL CCFightingScriptSetting::GetPVPChest(CT_INT32 iRandMax, CT_INT32 iReceiveNum, G_PVPChest &PVPChest) { return 0 != G_GetPVPChestFile(iRandMax,iReceiveNum,&PVPChest); } //根据场景ID获取PVP场景胜利奖励 CT_BOOL CCFightingScriptSetting::GetPVPWinReward(CT_INT32 iRandGrade,CT_INT32 iChallengesDifficulty, G_PVPReward &PVPReward) { return 0 != G_GetPVPWinReward(iRandGrade,iChallengesDifficulty,&PVPReward); } //根据场景ID获取PVP场景胜利奖励 CT_BOOL CCFightingScriptSetting::GetPVPLostReward(CT_INT32 iRandGrade,CT_INT32 iChallengesDifficulty, G_PVPReward &PVPReward) { return 0 != G_GetPVPLostReward(iRandGrade,iChallengesDifficulty,&PVPReward); } //根据掉落ID获取掉落物品组 CT_BOOL CCFightingScriptSetting::GetGoodsGroup(CT_INT32 iDropGroupID, G_GoodsGroup &GoodsGroup) { return 0 != G_GetGoodsGroup(iDropGroupID,&GoodsGroup); } //根据掉落ID获取物品权重 CT_BOOL CCFightingScriptSetting::GetGoodsWeights(CT_INT32 iDropGroupID, G_GoodsWeights &GoodsWeights) { return 0 != G_GetGoodsWeights(iDropGroupID,&GoodsWeights); } //根据掉落ID获取物品数目 CT_BOOL CCFightingScriptSetting::GetGoodsCount(CT_INT32 iDropGroupID, G_GoodsCount &GoodsCount) { return 0 != G_GetGoodsCount(iDropGroupID,&GoodsCount); } //根据掉落ID获取掉落物品组 CT_BOOL CCFightingScriptSetting::GetPVPGoodsGroup(CT_INT32 iDuplicateID, G_GoodsGroup &GoodsGroup) { G_SceneReward SceneReward; memset(&SceneReward,0,sizeof(SceneReward)); //if(G_GetSceneReward(iDuplicateID,&SceneReward) != 0) //{ // return 0 != G_GetGoodsGroup(SceneReward.iDuplicateID,GoodsGroup); //} //else // return CT_FALSE; return CT_TRUE; } //根据掉落ID获取物品权重 CT_BOOL CCFightingScriptSetting::GetPVPGoodsWeights(CT_INT32 iDuplicateID, G_GoodsWeights &GoodsWeights) { G_SceneReward SceneReward; memset(&SceneReward,0,sizeof(SceneReward)); //if((CT_BOOL)G_GetSceneReward(iDuplicateID,&SceneReward) == CT_TRUE) //{ // return 0 != G_GetGoodsWeights(SceneReward.iDuplicateID,GoodsWeights); //} //else // return CT_FALSE; return CT_TRUE; } //根据掉落ID获取物品数目 CT_BOOL CCFightingScriptSetting::GetPVPGoodsCount(CT_INT32 iDuplicateID, G_GoodsCount &GoodsCount) { G_SceneReward SceneReward; memset(&SceneReward,0,sizeof(SceneReward)); /*G_SceneReward SceneReward; memset(&SceneReward,0,sizeof(SceneReward)); if((CT_BOOL)G_GetSceneReward(iDuplicateID,&SceneReward) == CT_TRUE) { return (CT_BOOL)G_GetGoodsCount(SceneReward.iDuplicateID,pGoodsCount); } else return CT_FALSE; if((CT_BOOL)G_GetSceneReward(iDuplicateID,&SceneReward) == CT_TRUE) { return (CT_BOOL)G_GetGoodsCount(SceneReward.iDuplicateID,pGoodsCount); } else return CT_FALSE;*/ return CT_TRUE; } //根据怪物ID获取怪物信息 CT_BOOL CCFightingScriptSetting::GetMosterData(CT_INT32 iMosterID,G_MonsterBaseInfo &GMBI) { return 0 != G_GetMonsterBaseInfoData(iMosterID,&GMBI); } //根据技能ID获取技能信息 CT_BOOL CCFightingScriptSetting::GetSkillMainData(CT_INT32 iSkillID,G_SkillMain &GS) { //if(iSkillID == 0)CT_ASSERT(CT_FALSE); return 0 != G_GetSkillMainData(iSkillID,&GS); } //根据技能ID获取技能信息 CT_BOOL CCFightingScriptSetting::GetSkillAffectData(CT_INT32 iSkillID,G_SkillAffect &GSA) { return 0 != G_GetSkillAffectData(iSkillID,&GSA); } //获得技能星级数据 CT_BOOL CCFightingScriptSetting::GetSkillStarData(int iSkillLevel,G_SkillStar &GSS) { return 0 != G_GetSkillStarData(iSkillLevel,&GSS); } //根据场景ID获取世界场景奖励 CT_BOOL CCFightingScriptSetting::GetWorldSceneData(CT_INT32 iWorldSceneID,CT_INT32 iRewardID,G_WorldSceneReward &WSR) { return 0 != G_GetWorldSceneReward(iWorldSceneID+1,iRewardID+1,&WSR); }
[ "wangluofan@gmail.com" ]
wangluofan@gmail.com
b82ef8ebe1841613f0ce3f61f0df848d1dd260b4
e804af044e5209dca7103b67fbdfba3dcf189870
/cuda-samples-10.2/Samples/nvJPEG_encoder/nvJPEG_encoder.cpp
7390731b5dc9440d0dc9940c4e5b47dcabf9af16
[ "MIT" ]
permissive
dcmartin/slipstream
6c8e3605463df937fef061eebc9205a03c27ed1e
72ec3e80cbe600afce61c1dbfa6d84ef4c16867c
refs/heads/master
2022-10-19T00:47:41.021425
2020-06-08T17:35:49
2020-06-08T17:35:49
270,355,088
1
0
MIT
2020-06-07T15:53:26
2020-06-07T15:53:25
null
UTF-8
C++
false
false
17,456
cpp
/* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * 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 following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION 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 ``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 OWNER 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. */ // This sample needs at least CUDA 10.1. It demonstrates usages of the nvJPEG // library nvJPEG encoder supports single and multiple image encode. #include <cuda_runtime_api.h> #include "helper_nvJPEG.hxx" int dev_malloc(void **p, size_t s) { return (int)cudaMalloc(p, s); } int dev_free(void *p) { return (int)cudaFree(p); } StopWatchInterface *timer = NULL; bool is_interleaved(nvjpegOutputFormat_t format) { if (format == NVJPEG_OUTPUT_RGBI || format == NVJPEG_OUTPUT_BGRI) return true; else return false; } struct encode_params_t { std::string input_dir; std::string output_dir; std::string format; std::string subsampling; int quality; int dev; }; nvjpegEncoderParams_t encode_params; nvjpegHandle_t nvjpeg_handle; nvjpegJpegState_t jpeg_state; nvjpegEncoderState_t encoder_state; int decodeEncodeOneImage(std::string sImagePath, std::string sOutputPath, double &time, nvjpegOutputFormat_t output_format, nvjpegInputFormat_t input_format) { time = 0.; // Get the file name, without extension. // This will be used to rename the output file. size_t position = sImagePath.rfind("/"); std::string sFileName = (std::string::npos == position)? sImagePath : sImagePath.substr(position + 1, sImagePath.size()); position = sFileName.rfind("."); sFileName = (std::string::npos == position)? sFileName : sFileName.substr(0, position); position = sFileName.rfind("/"); sFileName = (std::string::npos == position) ? sFileName : sFileName.substr(position + 1, sFileName.length()); position = sFileName.rfind("\\"); sFileName = (std::string::npos == position) ? sFileName : sFileName.substr(position+1, sFileName.length()); // Read an image from disk. std::ifstream oInputStream(sImagePath.c_str(), std::ios::in | std::ios::binary | std::ios::ate); if(!(oInputStream.is_open())) { std::cerr << "Cannot open image: " << sImagePath << std::endl; return 1; } // Get the size. std::streamsize nSize = oInputStream.tellg(); oInputStream.seekg(0, std::ios::beg); // Image buffers. unsigned char * pBuffer = NULL; double decode_time = 0.; std::vector<char> vBuffer(nSize); if (oInputStream.read(vBuffer.data(), nSize)) { unsigned char * dpImage = (unsigned char *)vBuffer.data(); // Retrieve the componenet and size info. int nComponent = 0; nvjpegChromaSubsampling_t subsampling; int widths[NVJPEG_MAX_COMPONENT]; int heights[NVJPEG_MAX_COMPONENT]; if (NVJPEG_STATUS_SUCCESS != nvjpegGetImageInfo(nvjpeg_handle, dpImage, nSize, &nComponent, &subsampling, widths, heights)) { std::cerr << "Error decoding JPEG header: " << sImagePath << std::endl; return 1; } // image information std::cout << "Image is " << nComponent << " channels." << std::endl; for (int i = 0; i < nComponent; i++) { std::cout << "Channel #" << i << " size: " << widths[i] << " x " << heights[i] << std::endl; } switch (subsampling) { case NVJPEG_CSS_444: std::cout << "YUV 4:4:4 chroma subsampling" << std::endl; break; case NVJPEG_CSS_440: std::cout << "YUV 4:4:0 chroma subsampling" << std::endl; break; case NVJPEG_CSS_422: std::cout << "YUV 4:2:2 chroma subsampling" << std::endl; break; case NVJPEG_CSS_420: std::cout << "YUV 4:2:0 chroma subsampling" << std::endl; break; case NVJPEG_CSS_411: std::cout << "YUV 4:1:1 chroma subsampling" << std::endl; break; case NVJPEG_CSS_410: std::cout << "YUV 4:1:0 chroma subsampling" << std::endl; break; case NVJPEG_CSS_GRAY: std::cout << "Grayscale JPEG " << std::endl; break; case NVJPEG_CSS_UNKNOWN: std::cout << "Unknown chroma subsampling" << std::endl; return 1; } { cudaError_t eCopy = cudaMalloc(&pBuffer, widths[0] * heights[0] * NVJPEG_MAX_COMPONENT); if(cudaSuccess != eCopy) { std::cerr << "cudaMalloc failed for component Y: " << cudaGetErrorString(eCopy) << std::endl; return 1; } nvjpegImage_t imgdesc = { { pBuffer, pBuffer + widths[0]*heights[0], pBuffer + widths[0]*heights[0]*2, pBuffer + widths[0]*heights[0]*3 }, { (unsigned int)(is_interleaved(output_format) ? widths[0] * 3 : widths[0]), (unsigned int)widths[0], (unsigned int)widths[0], (unsigned int)widths[0] } }; int nReturnCode = 0; cudaDeviceSynchronize(); // Create the CUTIL timer sdkCreateTimer(&timer); sdkStartTimer(&timer); nReturnCode = nvjpegDecode(nvjpeg_handle, jpeg_state, dpImage, nSize, output_format, &imgdesc, NULL); // alternatively decode by stages /*int nReturnCode = nvjpegDecodeCPU(nvjpeg_handle, dpImage, nSize, output_format, &imgdesc, NULL); nReturnCode = nvjpegDecodeMixed(nvjpeg_handle, NULL); nReturnCode = nvjpegDecodeGPU(nvjpeg_handle, NULL);*/ cudaDeviceSynchronize(); sdkStopTimer(&timer); decode_time =sdkGetTimerValue(&timer); if(nReturnCode != 0) { std::cerr << "Error in nvjpegDecode." << std::endl; return 1; } /////////////////////// encode //////////////////// if (NVJPEG_OUTPUT_YUV == output_format) { checkCudaErrors(nvjpegEncodeYUV(nvjpeg_handle, encoder_state, encode_params, &imgdesc, subsampling, widths[0], heights[0], NULL)); } else { checkCudaErrors(nvjpegEncodeImage(nvjpeg_handle, encoder_state, encode_params, &imgdesc, input_format, widths[0], heights[0], NULL)); } std::vector<unsigned char> obuffer; size_t length; checkCudaErrors(nvjpegEncodeRetrieveBitstream( nvjpeg_handle, encoder_state, NULL, &length, NULL)); obuffer.resize(length); checkCudaErrors(nvjpegEncodeRetrieveBitstream( nvjpeg_handle, encoder_state, obuffer.data(), &length, NULL)); std::string output_filename = sOutputPath + "/" + sFileName + ".jpg"; char directory[120]; char mkdir_cmd[256]; std::string folder = sOutputPath; output_filename = folder + "/"+ sFileName +".jpg"; #if !defined(_WIN32) sprintf(directory, "%s", folder.c_str()); sprintf(mkdir_cmd, "mkdir -p %s 2> /dev/null", directory); #else sprintf(directory, "%s", folder.c_str()); sprintf(mkdir_cmd, "mkdir %s 2> nul", directory); #endif int ret = system(mkdir_cmd); std::cout << "Writing JPEG file: " << output_filename << std::endl; std::ofstream outputFile(output_filename.c_str(), std::ios::out | std::ios::binary); outputFile.write(reinterpret_cast<const char *>(obuffer.data()), static_cast<int>(length)); // Free memory checkCudaErrors(cudaFree(pBuffer)); } } time = decode_time; return 0; } int processArgs(encode_params_t param) { std::string sInputPath(param.input_dir); std::string sOutputPath(param.output_dir); std::string sFormat(param.format); std::string sSubsampling(param.subsampling); nvjpegOutputFormat_t oformat = NVJPEG_OUTPUT_RGB; nvjpegInputFormat_t iformat = NVJPEG_INPUT_RGB; int error_code = 1; if (sFormat == "yuv") { oformat = NVJPEG_OUTPUT_YUV; } else if (sFormat == "rgb") { oformat = NVJPEG_OUTPUT_RGB; iformat = NVJPEG_INPUT_RGB; } else if (sFormat == "bgr") { oformat = NVJPEG_OUTPUT_BGR; iformat = NVJPEG_INPUT_BGR; } else if (sFormat == "rgbi") { oformat = NVJPEG_OUTPUT_RGBI; iformat = NVJPEG_INPUT_RGBI; } else if (sFormat == "bgri") { oformat = NVJPEG_OUTPUT_BGRI; iformat = NVJPEG_INPUT_BGRI; } else { std::cerr << "Unknown or unsupported output format: " << sFormat << std::endl; return error_code; } if (sSubsampling == "444") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_444, NULL)); } else if (sSubsampling == "422") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_422, NULL)); } else if (sSubsampling == "420") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_420, NULL)); } else if (sSubsampling == "440") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_440, NULL)); } else if (sSubsampling == "411") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_411, NULL)); } else if (sSubsampling == "410") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_410, NULL)); } else if (sSubsampling == "400") { checkCudaErrors(nvjpegEncoderParamsSetSamplingFactors(encode_params, NVJPEG_CSS_GRAY, NULL)); } else { std::cerr << "Unknown or unsupported subsampling: " << sSubsampling << std::endl; return error_code; } /*if( stat(sOutputPath.c_str(), &s) == 0 ) { if( !(s.st_mode & S_IFDIR) ) { std::cout << "Output path already exist as non-directory: " << sOutputPath << std::endl; return error_code; } } else { if (mkdir(sOutputPath.c_str(), 0775)) { std::cout << "Cannot create output directory: " << sOutputPath << std::endl; return error_code; } }*/ std::vector<std::string> inputFiles; if (readInput(sInputPath, inputFiles)) { return error_code; } double total_time = 0., decode_time = 0.; int total_images = 0; for (unsigned int i = 0; i < inputFiles.size(); i++) { std::string &sFileName = inputFiles[i]; std::cout << "Processing file: " << sFileName << std::endl; int image_error_code = decodeEncodeOneImage(sFileName, sOutputPath, decode_time, oformat, iformat); if (image_error_code) { std::cerr << "Error processing file: " << sFileName << std::endl; //return image_error_code; } else { total_images++; total_time += decode_time; } } std::cout << "Total images processed: " << total_images << std::endl; std::cout << "Total time spent on decoding: " << total_time << std::endl; std::cout << "Avg time/image: " << total_time/total_images << std::endl; return 0; } // parse parameters int findParamIndex(const char **argv, int argc, const char *parm) { int count = 0; int index = -1; for (int i = 0; i < argc; i++) { if (strncmp(argv[i], parm, 100) == 0) { index = i; count++; } } if (count == 0 || count == 1) { return index; } else { std::cout << "Error, parameter " << parm << " has been specified more than once, exiting\n" << std::endl; return -1; } return -1; } int main(int argc, const char *argv[]) { int pidx; if ((pidx = findParamIndex(argv, argc, "-h")) != -1 || (pidx = findParamIndex(argv, argc, "--help")) != -1) { std::cout << "Usage: " << argv[0] << " -i images_dir [-o output_dir] [-device=device_id]" "[-q quality][-s 420/444] [-fmt output_format]\n"; std::cout << "Parameters: " << std::endl; std::cout << "\timages_dir\t:\tPath to single image or directory of images" << std::endl; std::cout << "\toutput_dir\t:\tWrite encoded images as jpeg to this directory" << std::endl; std::cout << "\tdevice_id\t:\tWhich device to use for encoding" << std::endl; std::cout << "\tQuality\t:\tUse image quality [default 70]" << std::endl; std::cout << "\tsubsampling\t:\tUse Subsampling [420, 444]" << std::endl; std::cout << "\toutput_format\t:\tnvJPEG output format for encoding. One " "of [rgb, rgbi, bgr, bgri, yuv, y, unchanged]" << std::endl; return EXIT_SUCCESS; } encode_params_t params; params.input_dir = "./"; if ((pidx = findParamIndex(argv, argc, "-i")) != -1) { params.input_dir = argv[pidx + 1]; } else { // Search in default paths for input images. int found = getInputDir(params.input_dir, argv[0]); if (!found) { std::cout << "Please specify input directory with encoded images"<< std::endl; return EXIT_WAIVED; } } if ((pidx = findParamIndex(argv, argc, "-o")) != -1) { params.output_dir = argv[pidx + 1]; } else { // by-default write the folder named "output" in cwd params.output_dir = "encode_output"; } params.dev = 0; params.dev = findCudaDevice(argc, argv); params.quality = 70; if ((pidx = findParamIndex(argv, argc, "-q")) != -1) { params.quality = std::atoi(argv[pidx + 1]); } if ((pidx = findParamIndex(argv, argc, "-s")) != -1) { params.subsampling = argv[pidx + 1]; } else { // by-default use subsampling as 420 params.subsampling = "420"; } if ((pidx = findParamIndex(argv, argc, "-fmt")) != -1) { params.format = argv[pidx + 1]; } else { // by-default use output format yuv params.format = "yuv"; } cudaDeviceProp props; checkCudaErrors(cudaGetDeviceProperties(&props, params.dev)); printf("Using GPU %d (%s, %d SMs, %d th/SM max, CC %d.%d, ECC %s)\n", params.dev, props.name, props.multiProcessorCount, props.maxThreadsPerMultiProcessor, props.major, props.minor, props.ECCEnabled ? "on" : "off"); nvjpegDevAllocator_t dev_allocator = {&dev_malloc, &dev_free}; checkCudaErrors(nvjpegCreate(NVJPEG_BACKEND_DEFAULT, &dev_allocator, &nvjpeg_handle)); checkCudaErrors(nvjpegJpegStateCreate(nvjpeg_handle, &jpeg_state)); checkCudaErrors(nvjpegEncoderStateCreate(nvjpeg_handle, &encoder_state, NULL)); checkCudaErrors(nvjpegEncoderParamsCreate(nvjpeg_handle, &encode_params, NULL)); // sample input parameters checkCudaErrors(nvjpegEncoderParamsSetQuality(encode_params, params.quality, NULL)); checkCudaErrors(nvjpegEncoderParamsSetOptimizedHuffman(encode_params, 1, NULL)); pidx = processArgs(params); checkCudaErrors(nvjpegEncoderParamsDestroy(encode_params)); checkCudaErrors(nvjpegEncoderStateDestroy(encoder_state)); checkCudaErrors(nvjpegJpegStateDestroy(jpeg_state)); checkCudaErrors(nvjpegDestroy(nvjpeg_handle)); return pidx; }
[ "github@dcmartin.com" ]
github@dcmartin.com
053e56dd045815aa28c825eb33b02efafdfede40
ae716f70009a8e1433f11c07ffbc7f9578eaaf81
/include/cpgf/greference.h
3d9b30e1da005f483ee2f3e76de21367465d8a68
[ "Apache-2.0" ]
permissive
michalslonina/cpgf
b4aefab1fd3371ef41593be87bae37b0c8ecf779
5231b3e650af4b2b0bb63bdeb0a7f25dd82cdaf3
refs/heads/develop
2021-01-18T05:30:33.465421
2015-11-29T09:59:19
2015-11-29T09:59:19
47,057,611
0
0
null
2015-11-29T09:29:26
2015-11-29T09:29:26
null
UTF-8
C++
false
false
1,710
h
#ifndef CPGF_GREFERENCE_h #define CPGF_GREFERENCE_h #include "cpgf/ggetobjectaddress.h" namespace cpgf { template <typename T> class GReference { public: typedef T Type; public: explicit GReference(T & data) : dataAddress(getObjectAddress(data)) { } GReference(const GReference & other) : dataAddress(other.dataAddress) { } GReference & operator = (const GReference & other) { this->dataAddress = other.dataAddress; } T * operator & () const { return this->dataAddress; } operator T& () const { return *this->dataAddress; } private: bool operator == (const GReference & other); private: T * dataAddress; }; template <typename T> inline GReference<T> makeReference(T & data) { return GReference<T>(data); } template <typename T> inline GReference<T> makeReference(const GReference<T> & data) { return data; } template <typename T> inline GReference<const T> makeReference(const GReference<const T> & data) { return data; } template <typename T> inline GReference<const volatile T> makeReference(const GReference<const volatile T> & data) { return data; } template <typename T> inline GReference<const T> makeConstReference(const T & data) { return GReference<const T>(data); } template <typename T> inline GReference<T> makeConstReference(const GReference<T> & data) { return data; } template <typename T> inline GReference<const T> makeConstReference(const GReference<const T> & data) { return data; } template <typename T> inline GReference<const volatile T> makeConstReference(const GReference<const volatile T> & data) { return data; } } //namespace cpgf #endif
[ "wqking@outlook.com" ]
wqking@outlook.com
bcf6273291dad9e10d9b5ae4d3fb9a0ed071aec0
913d4919c8041b918c51b57d52acaad1f99a82e0
/divisible_subarrays.cpp
5049336e7f5cd35535c0e26156dd07fd72de671a
[]
no_license
KunalFarmah98/Interview-Questions
f126d6fb74bfadf03a1e00b523549c7c24e5ffec
61f638e16823992ac9578349fef6535fa231da83
refs/heads/master
2022-07-29T16:19:56.356807
2020-05-25T15:14:08
2020-05-25T15:14:08
266,811,559
0
0
null
null
null
null
UTF-8
C++
false
false
2,819
cpp
//KUNAL FARMAH //@kunalfarmh98@gmail.com #include<bits/stdc++.h> using namespace std; typedef long long ll; /** Logic Let there be a subarray (i, j) whose sum is divisible by k sum(i, j) = sum(0, j) - sum(0, i-1) Sum for any subarray can be written as q*k + rem where q is a quotient and rem is remainder Thus, sum(i, j) = (q1 * k + rem1) - (q2 * k + rem2) sum(i, j) = (q1 - q2)k + rem1-rem2 We see, for sum(i, j) i.e. for sum of any subarray to be divisible by k, the RHS should also be divisible by k. (q1 - q2)k is obviously divisible by k, for (rem1-rem2) to follow the same, rem1 = rem2 where rem1 = Sum of subarray (0, j) % k rem2 = Sum of subarray (0, i-1) % k */ // optimised O(n) ll subCount(int arr[], int n, int k) { // create auxiliary hash array to count frequency // of remainders ll mod[k]; memset(mod, 0, sizeof(mod)); // Traverse original array and compute cumulative // sum take remainder of this current cumulative // sum and increase count by 1 for this remainder // in mod[] array ll cumSum = 0; for (int i = 0; i < n; i++) { cumSum += arr[i]; // as the sum can be negative, taking modulo twice // counting number of same remainders given by sum(0,i); mod[((cumSum % k) + k) % k]++; } ll result = 0; // Initialize result // Traverse mod[] for (int i = 0; i < k; i++) // If there are more than one prefix subarrays, with a particular mod value // then only we can take them // We can chose 2 of them in n*(n-1)/2 ways. if (mod[i] > 1) result += (mod[i] * (mod[i] - 1)) / 2; // add the elements which are divisible by k itself // i.e., the elements whose modulus with k = 0 result += mod[0]; return result; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0; i<n; i++){ cin>>a[i]; } cout<<subCount(a,n,n)<<endl; } /*while(t--){ int n; cin>>n; int a[n]; unordered_map<ll,ll> sum; ll c=0; ll s = 0; for(int i=0; i<n; i++){ cin>>a[i]; if(i==0) { s=a[i]; sum[s] = i; } else { s = s + a[i]; sum[s] = i; } ll mul = n*(s/n); //cout<<mul<<" "; while(mul>0){ if(s-mul==0 || sum.find(s-mul)!=sum.end()) ++c; mul-=n; //cout<<mul<<" "; } } cout<<c<<endl; }*/ return 0; }
[ "kunalfarmah98@gmail.com" ]
kunalfarmah98@gmail.com
00c2d6274677d870f293e803055f5b14670d41e7
8a9fd9c203b6a9436cb397b8ddd12834f109e5e4
/src/lib/mu/MuQt/QStackedWidgetType.h
1e353fdf9484b5572862fb1bbb0f398802bb34dc
[ "BSD-3-Clause" ]
permissive
jimhourihan/mu
d5c31fa14c3f1640660090c29158da5d92343f54
3f4a150570c0fb8354f8f39c7819511e1f98ceb5
refs/heads/master
2022-11-30T22:27:33.025801
2015-01-05T16:36:04
2015-01-05T16:36:04
26,831,961
2
1
null
null
null
null
UTF-8
C++
false
false
3,678
h
// // Copyright (c) 2009, Jim Hourihan // All rights reserved. // // 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 following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the software 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 Jim Hourihan ''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 Jim Hourihan 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 __MuQt__QStackedWidgetType__h__ #define __MuQt__QStackedWidgetType__h__ #include <iostream> #include <Mu/Class.h> #include <Mu/Process.h> #include <QtCore/QtCore> #include <QtGui/QtGui> #include <QtNetwork/QtNetwork> #include <QtWebKit/QtWebKit> #include <QtSvg/QtSvg> #include <MuQt/Bridge.h> namespace Mu { class MuQt_QStackedWidget; // // NOTE: file generated by qt2mu.py // class QStackedWidgetType : public Class { public: typedef MuQt_QStackedWidget MuQtType; typedef QStackedWidget QtType; // // Constructors // QStackedWidgetType(Context* context, const char* name, Class* superClass = 0, Class* superClass2 = 0); virtual ~QStackedWidgetType(); static bool isInheritable() { return true; } static inline ClassInstance* cachedInstance(const MuQtType*); // // Class API // virtual void load(); MemberFunction* _func[4]; }; // Inheritable object class MuQt_QStackedWidget : public QStackedWidget { public: virtual ~MuQt_QStackedWidget(); MuQt_QStackedWidget(Pointer muobj, const CallEnvironment*, QWidget * parent) ; protected: virtual bool event(QEvent * e) ; public: virtual QSize sizeHint() const; protected: virtual void changeEvent(QEvent * ev) ; virtual void paintEvent(QPaintEvent * _p15) ; public: bool event_pub(QEvent * e) { return event(e); } bool event_pub_parent(QEvent * e) { return QStackedWidget::event(e); } void changeEvent_pub(QEvent * ev) { changeEvent(ev); } void changeEvent_pub_parent(QEvent * ev) { QStackedWidget::changeEvent(ev); } void paintEvent_pub(QPaintEvent * _p15) { paintEvent(_p15); } void paintEvent_pub_parent(QPaintEvent * _p15) { QStackedWidget::paintEvent(_p15); } public: const QStackedWidgetType* _baseType; ClassInstance* _obj; const CallEnvironment* _env; }; inline ClassInstance* QStackedWidgetType::cachedInstance(const QStackedWidgetType::MuQtType* obj) { return obj->_obj; } } // Mu #endif // __MuQt__QStackedWidgetType__h__
[ "jim@tweaksoftware.com" ]
jim@tweaksoftware.com
0dc877c0b69c7b8925896999f00dffc091bb39b3
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/PolicyConditionInPolicyCondition/UNIX_PolicyConditionInPolicyCondition_DARWIN.hxx
3a8a364a7d4696ac62ee3494119766e20472f3bd
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
161
hxx
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_POLICYCONDITIONINPOLICYCONDITION_PRIVATE_H #define __UNIX_POLICYCONDITIONINPOLICYCONDITION_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
1ffa89494fadb8c846504a3d680be1b15348d81e
bf4d309295b261a61cface2f40ed414323d9ac41
/ESP2866-NTP-Clock-HTTP-TZ.ino
ffb7df0be3b2c9aa8fae6d01c3609b3a353950b6
[]
no_license
Lv2hack/ESP2866-NTP-Clock-HTTP-TZ
3ff170e09ef56f9dcbc0894d3eb1f000e0730456
b0bf88871fdd882117cc42e18397c233f64b0dfe
refs/heads/master
2021-09-05T10:56:27.225792
2018-01-26T16:53:32
2018-01-26T16:53:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,191
ino
// // NTP-Based Clock based on code from https://steve.fi/Hardware/ // // This is a simple program which uses WiFi & an 4x7-segment display // to show the current time, complete with blinking ":". // // Added a web configuration page which is available while the clock // is running. This allows changing the timezone and brightness. // Parameters are saved to a json configuration file for persistence. // Yes, this is unnecessarily complex (could have used integer for both // settings) but I was learning the json stuff // along with pointers which I still haven't figured out completely! // // 1/25/18 - Added single button to set the clock. Long press (3 seconds) // places the clock into set mode then single press increments the TZ. // Single button click also sets the brightness of the display. // // Alex T. // // WiFi & over the air updates // #include <ESP8266WiFi.h> #include <ArduinoOTA.h> #include <ArduinoJson.h> #include "FS.h" #include "PMButton.h" // // For dealing with NTP & the clock. // #include "NTPClient.h" // // The display-interface // #include "TM1637.h" // // WiFi setup. // #include "WiFiManager.h" // // For fetching URLS & handling URL-parameters // #include "url_fetcher.h" #include "url_parameters.h" // // Debug messages over the serial console. // #include "debug.h" // // The name of this project. // // Used for: // Access-Point name, in config-mode // OTA name. // #define PROJECT_NAME "NTP-CLOCK" // // The timezone - comment out to stay at GMT. // // #define TIME_ZONE (-7) // Configuration that we'll store on disk struct Config { char brightness[5]; int timeZone; }; const char *filename = "/config.txt"; // <- SD library uses 8.3 filenames Config config; // <- global configuration object // // The HTTP-server we present runs on port 80. // WiFiServer server(80); // // NTP client, and UDP socket it uses. // WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); // // Pin definitions for TM1637 and can be changed to other ports // #define CLK D3 #define DIO D2 #define BRT D1 // Brightness variables // We're setting the brightness with a button connected to the BRT digital pin // int int_brightness = 2; int brtLevel = 1; // This will be 0, 1, 2 for low med high brightness TM1637 tm1637(CLK, DIO); // Setup our button PMButton button1(BRT); // // Called just before the date/time is updated via NTP // void on_before_ntp() { DEBUG_LOG("Updating date & time"); } // // Called just after the date/time is updated via NTP // void on_after_ntp() { DEBUG_LOG("Updated NTP client"); } // // This function is called when the device is powered-on. // void setup() { // Enable our serial port. Serial.begin(115200); // One time format of SPIFFS //DEBUG_LOG("Formatting SPIFFS..."); //SPIFFS.format(); //DEBUG_LOG("SPIFSS formatted please comment out this section!"); //delay(100000); // Setup button button1.begin(); //You can set button timing values for each button to fine tune interaction. button1.debounce(20);//Default is 10 milliseconds button1.dcGap(150);//Time between clicks for Double click. Default is 200 milliseconds button1.holdTime(1500);//Default is 2 seconds button1.longHoldTime(4500);//Default is 5 seconds // // Enable access to the SPIFFS filesystem. // if (!SPIFFS.begin()) { DEBUG_LOG("Failed to mount file system"); return; } // // Set the intensity - valid choices include: // // BRIGHT_DARKEST = 0 // BRIGHT_TYPICAL = 2 // BRIGHT_BRIGHTEST = 7 // // tm1637.set(BRIGHT_DARKEST); // // Handle WiFi setup // WiFiManager wifiManager; wifiManager.autoConnect(PROJECT_NAME); // Load configuration from file if present, otherwise proceed with defaults // Serial.println("Loading configuration..."); loadConfiguration(filename, config); Serial.print("Initial tz: "); Serial.println(config.timeZone); Serial.print("Initial brightness: "); Serial.println(config.brightness); // initialize the display tm1637.init(); // We want to see ":" between the digits. tm1637.point(true); // Set the brightness after retrieving above // if (config.brightness != NULL) { if (strcmp(config.brightness, "low") == 0) { DEBUG_LOG("Setting brightness to low"); int_brightness = BRIGHT_DARKEST; } if (strcmp(config.brightness, "med") == 0) { DEBUG_LOG("Setting brightness to medium"); int_brightness = BRIGHT_TYPICAL; } if (strcmp(config.brightness, "high") == 0) { DEBUG_LOG("Setting brightness to brightest"); int_brightness = BRIGHT_BRIGHTEST; } tm1637.set(int_brightness); } // // Ensure our NTP-client is ready. // timeClient.begin(); // // Configure the callbacks. // timeClient.on_before_update(on_before_ntp); timeClient.on_after_update(on_after_ntp); // // Setup the timezone & update-interval. // Serial.print("Setting time zone offset to timeZone: "); Serial.println(config.timeZone); timeClient.setTimeOffset(config.timeZone * (60 * 60)); timeClient.setUpdateInterval(600 * 1000); // This is the number of milliseconds so 300 * 1000 = 300 sec // Now we can start our HTTP server // server.begin(); DEBUG_LOG("HTTP-Server started on http://%s/", WiFi.localIP().toString().c_str()); // // The final step is to allow over the air updates // // This is documented here: // https://randomnerdtutorials.com/esp8266-ota-updates-with-arduino-ide-over-the-air/ // // Hostname defaults to esp8266-[ChipID] // ArduinoOTA.setHostname(PROJECT_NAME); ArduinoOTA.onStart([]() { DEBUG_LOG("OTA Start"); }); ArduinoOTA.onEnd([]() { DEBUG_LOG("OTA End"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { char buf[32]; memset(buf, '\0', sizeof(buf)); snprintf(buf, sizeof(buf) - 1, "Upgrade - %02u%%", (progress / (total / 100))); DEBUG_LOG(buf); }); ArduinoOTA.onError([](ota_error_t error) { DEBUG_LOG("Error - "); if (error == OTA_AUTH_ERROR) DEBUG_LOG("Auth Failed"); else if (error == OTA_BEGIN_ERROR) DEBUG_LOG("Begin Failed"); else if (error == OTA_CONNECT_ERROR) DEBUG_LOG("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) DEBUG_LOG("Receive Failed"); else if (error == OTA_END_ERROR) DEBUG_LOG("End Failed"); }); // // Ensure the OTA process is running & listening. // ArduinoOTA.begin(); } // // This function is called continously, and is responsible // for flashing the ":", and otherwise updating the display. // // We rely on the background NTP-updates to actually make sure // that that works. // void loop() { static char buf[10] = { '\0' }; static char prev[10] = { '\0' }; static long last_read = 0; static bool flash = true; // // Resync the clock? // timeClient.update(); // // Handle any pending over the air updates. // ArduinoOTA.handle(); // // Get the current hour/min // int cur_hour = timeClient.getHours(); int cur_min = timeClient.getMinutes(); // // Format them in a useful way. // sprintf(buf, "%02d%02d", cur_hour, cur_min); // // If the current "hourmin" is different to // that we displayed last loop .. // if (strcmp(buf, prev) != 0) { // Update the display tm1637.display(0, buf[0] - '0'); tm1637.display(1, buf[1] - '0'); tm1637.display(2, buf[2] - '0'); tm1637.display(3, buf[3] - '0'); // And cache it strcpy(prev , buf); } //Get the current button state button1.checkSwitch(); if (button1.clicked()) { // We've now detected a button state change (High or Low) // If HIGH then change the brightness Serial.println("Button pushed"); brtLevel++; // increment the brightness if (brtLevel > 2) { brtLevel = 0; } // if brightness goes past 2 then reset it to zero switch (brtLevel) { case 0: int_brightness = BRIGHT_DARKEST; break; case 1: int_brightness = BRIGHT_TYPICAL; break; case 2: int_brightness = BRIGHT_BRIGHTEST; break; } tm1637.set(int_brightness); // Update the display tm1637.display(0, buf[0] - '0'); tm1637.display(1, buf[1] - '0'); tm1637.display(2, buf[2] - '0'); tm1637.display(3, buf[3] - '0'); } if (button1.held()) { Serial.println("Button held - setting time"); // Enter loop here to set display TZ int setHour = 0; int setTZ = config.timeZone; while (true) { button1.checkSwitch(); if (button1.clicked()) { //increment the timezone if (setTZ < 12) { // if the TZ is smaller than 12 setTZ++; // we can add one to it } else { setTZ = -11; // the next TZ after 12 is -11 } Serial.print("setTZ="); Serial.println(setTZ); timeClient.setTimeOffset(setTZ * (60 * 60)); // update the TZ in the clock int cur_hour = timeClient.getHours(); sprintf(buf, "%02d", cur_hour); tm1637.display(0, buf[0] - '0'); tm1637.display(1, buf[1] - '0'); yield(); } if (button1.held()) break; yield(); } Serial.println("Updating with new timezone"); // Next you need to save the updated setting to SPIFFS config.timeZone = setTZ; saveConfiguration(filename, config); } long now = millis(); if ((last_read == 0) || (abs(now - last_read) > 500)) { // Invert the "show :" flag flash = !flash; // Apply it. tm1637.point(flash); // // Note that the ":" won't redraw unless/until you update. // So we'll force that to happen by removing the cached // value here. // memset(prev, '\0', sizeof(prev)); last_read = now; } WiFiClient client = server.available(); if (client) processHTTPRequest(client); } // // Process an incoming HTTP-request. // void processHTTPRequest(WiFiClient client) { // Wait until the client sends some data while (client.connected() && !client.available()) delay(1); // Read the first line of the request String request = client.readStringUntil('\r'); client.flush(); // // Find the URL we were requested // // We'll have something like "GET XXXXX HTTP/XX" // so we split at the space and send the "XXX HTTP/XX" value // request = request.substring(request.indexOf(" ") + 1); // // Now we'll want to peel off any HTTP-parameters that might // be present, via our utility-helper. // URL url(request.c_str()); // // Does the user want to change the brightness? // if (url.param("url_brightness") != NULL) { DEBUG_LOG("Brightness update detected"); Serial.print("url.param(url_brightness = "); Serial.println(url.param("url_brightness")); if (strcmp(url.param("url_brightness"), "low") == 0) { DEBUG_LOG("Setting brightness to low"); int_brightness = BRIGHT_DARKEST; } else if (strcmp(url.param("url_brightness"), "med") == 0) { DEBUG_LOG("Setting brightness to medium"); int_brightness = BRIGHT_TYPICAL; } else if (strcmp(url.param("url_brightness"), "high") == 0) { DEBUG_LOG("Setting brightness to brightest"); int_brightness = BRIGHT_BRIGHTEST; } tm1637.set(int_brightness); strcpy(config.brightness, url.param("url_brightness")); Serial.print("Saving timeZone: "); Serial.println(config.timeZone); Serial.print("Saving brightness: "); Serial.println(config.brightness); Serial.println(F("Saving configuration...")); saveConfiguration(filename, config); // Redirect to the server-root redirectIndex(client); return; } // // Does the user want to change the time-zone? // if (url.param("tz") != NULL) { DEBUG_LOG("TZ update detected"); // Change the timezone now config.timeZone = atoi(url.param("tz")); // Update the offset. timeClient.setTimeOffset(config.timeZone * (60 * 60)); timeClient.forceUpdate(); Serial.print("Saving timeZone: "); Serial.println(config.timeZone); Serial.print("Saving brightness: "); Serial.println(config.brightness); Serial.println(F("Saving configuration...")); saveConfiguration(filename, config); // Redirect to the server-root redirectIndex(client); return; } // // At this point we've either received zero URL-paramters // or we've only received ones we didn't recognize. // // Either way return a simple response. // serveHTML(client); } // // This is a bit horrid. // // Serve a HTML-page to any clients who connect, via a browser. // void serveHTML(WiFiClient client) { client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); client.println("<!DOCTYPE html>"); client.println("<html lang=\"en\">"); client.println("<head>"); client.println("<title>NTP Clock</title>"); client.println("<meta charset=\"utf-8\">"); client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"); client.println("<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">"); client.println("<script src=\"//code.jquery.com/jquery-1.12.4.min.js\"></script>"); client.println("<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>"); client.println("<style> body { margin: 25px; } </style>"); client.println("</head>"); client.println("<body>"); client.println("<strong>NTP Clock Settings</strong><br><br>"); client.println("Time zone offset: "); client.print("<form action=\"/\" method=\"GET\">"); client.print("<input type=\"text\" name=\"tz\" size=\"3\" value=\""); client.print(config.timeZone); client.print("\"><br>"); client.println("<input type=\"submit\" value=\"Update TZ\"></form>"); client.println("<br><br>Brightness Level:<br>"); client.print("<form action=\"/\" method=\"GET\">"); if (strcmp(config.brightness, "high") == 0) { client.println("<input type=\"radio\" name=\"url_brightness\" value=\"high\" checked> High<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"med\" > Medium<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"low\" > Low<br>"); } else if (strcmp(config.brightness, "med") == 0) { client.println("<input type=\"radio\" name=\"url_brightness\" value=\"high\" > High<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"med\" checked> Medium <br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"low\" > Low<br>"); } else if (strcmp(config.brightness, "low") == 0) { client.println("<input type=\"radio\" name=\"url_brightness\" value=\"high\" > High<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"med\" > Medium<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"low\" checked > Low<br>"); } else { client.println("<input type=\"radio\" name=\"url_brightness\" value=\"high\" > High<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"med\"> Medium<br>"); client.println("<input type=\"radio\" name=\"url_brightness\" value=\"low\"> Low<br>"); } client.println("<input type=\"submit\" value=\"Update Brightness\"></form>"); client.println("</body>"); client.println("</html>"); } // // Serve a redirect to the server-root // void redirectIndex(WiFiClient client) { client.println("HTTP/1.1 302 Found"); client.print("Location: http://"); client.print(WiFi.localIP().toString().c_str()); client.println("/"); }
[ "alext@pobox.com" ]
alext@pobox.com
977cc7da383e0a0b0302234cf5fe090b5643221e
04bda0a5f1b1a9039a4d6dd3d44945a85c6e423e
/include/aikido/planner/dart/ConfigurationToConfiguration_to_ConfigurationToConfiguration.hpp
64545ee2f1ebf19fde315a65006017c7397272f0
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
personalrobotics/aikido
99ae1804fcc1a7abeef705139be29f8c728079fd
fb0cfa99e6d931a4d5784e139e978f61063b3c00
refs/heads/master
2023-03-17T00:39:45.637699
2023-03-10T20:04:18
2023-03-10T20:04:18
34,424,077
213
35
BSD-3-Clause
2023-03-10T20:04:19
2015-04-23T00:33:33
C++
UTF-8
C++
false
false
1,432
hpp
#ifndef AIKIDO_PLANNER_DART_CONFIGURATIONTOCONFIGURATIONTOCONFIGURATIONTOCONFIGURATION_HPP_ #define AIKIDO_PLANNER_DART_CONFIGURATIONTOCONFIGURATIONTOCONFIGURATIONTOCONFIGURATION_HPP_ #include "aikido/planner/ConfigurationToConfigurationPlanner.hpp" #include "aikido/planner/dart/ConfigurationToConfigurationPlanner.hpp" #include "aikido/planner/dart/PlannerAdapter.hpp" namespace aikido { namespace planner { namespace dart { /// Converts a non-DART ConfigurationToConfiguration planner into the DART /// version. class ConfigurationToConfiguration_to_ConfigurationToConfiguration : public PlannerAdapter< planner::ConfigurationToConfigurationPlanner, planner::dart::ConfigurationToConfigurationPlanner> { public: /// Constructor /// /// \param[in] planner Non-DART planner to convert. /// \param[in] metaSkeleton MetaSkeleton for adapted planner to operate on. ConfigurationToConfiguration_to_ConfigurationToConfiguration( std::shared_ptr<planner::ConfigurationToConfigurationPlanner> planner, ::dart::dynamics::MetaSkeletonPtr metaSkeleton); // Documentation inherited. virtual trajectory::TrajectoryPtr plan( const planner::dart::ConfigurationToConfiguration& problem, Planner::Result* result) override; }; } // namespace dart } // namespace planner } // namespace aikido #endif // AIKIDO_PLANNER_DART_CONFIGURATIONTOCONFIGURATIONTOCONFIGURATIONTOCONFIGURATION_HPP_
[ "brianhou@users.noreply.github.com" ]
brianhou@users.noreply.github.com
0570ccddc109375545da2402c10c0eca54401f32
ffe8b00c01428086ec5dc3f5269ef0125c04ee7f
/src/entt/entity/snapshot.hpp
581c5aa848d1a749f57914e91b5491a480e46fbb
[ "MIT", "CC-BY-4.0", "CC-BY-SA-4.0" ]
permissive
m-waka/entt
d689507b78f9571b6fd5ae1d5df63b6f4f29bf25
4913c9e6ecde672ed69182aa8a33c78f10c475ea
refs/heads/master
2021-07-13T04:38:06.635153
2018-12-11T11:41:15
2018-12-11T11:41:15
131,844,781
0
0
MIT
2018-12-10T12:54:17
2018-05-02T12:04:19
C++
UTF-8
C++
false
false
20,003
hpp
#ifndef ENTT_ENTITY_SNAPSHOT_HPP #define ENTT_ENTITY_SNAPSHOT_HPP #include <array> #include <cstddef> #include <utility> #include <cassert> #include <iterator> #include <type_traits> #include <unordered_map> #include "../config/config.h" #include "entt_traits.hpp" namespace entt { /** * @brief Forward declaration of the registry class. */ template<typename> class registry; /** * @brief Utility class to create snapshots from a registry. * * A _snapshot_ can be either a dump of the entire registry or a narrower * selection of components of interest.<br/> * This type can be used in both cases if provided with a correctly configured * output archive. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class snapshot final { /*! @brief A registry is allowed to create snapshots. */ friend class registry<Entity>; using follow_fn_type = Entity(const registry<Entity> &, const Entity); snapshot(const registry<Entity> &reg, Entity seed, follow_fn_type *follow) ENTT_NOEXCEPT : reg{reg}, seed{seed}, follow{follow} {} template<typename Component, typename Archive, typename It> void get(Archive &archive, std::size_t sz, It first, It last) const { archive(static_cast<Entity>(sz)); while(first != last) { const auto entity = *(first++); if(reg.template has<Component>(entity)) { archive(entity, reg.template get<Component>(entity)); } } } template<typename... Component, typename Archive, typename It, std::size_t... Indexes> void component(Archive &archive, It first, It last, std::index_sequence<Indexes...>) const { std::array<std::size_t, sizeof...(Indexes)> size{}; auto begin = first; while(begin != last) { const auto entity = *(begin++); ((reg.template has<Component>(entity) ? ++size[Indexes] : size[Indexes]), ...); } (get<Component>(archive, size[Indexes], first, last), ...); } public: /*! @brief Copying a snapshot isn't allowed. */ snapshot(const snapshot &) = delete; /*! @brief Default move constructor. */ snapshot(snapshot &&) = default; /*! @brief Copying a snapshot isn't allowed. @return This snapshot. */ snapshot & operator=(const snapshot &) = delete; /*! @brief Default move assignment operator. @return This snapshot. */ snapshot & operator=(snapshot &&) = default; /** * @brief Puts aside all the entities that are still in use. * * Entities are serialized along with their versions. Destroyed entities are * not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const snapshot & entities(Archive &archive) const { archive(static_cast<Entity>(reg.alive())); reg.each([&archive](const auto entity) { archive(entity); }); return *this; } /** * @brief Puts aside destroyed entities. * * Entities are serialized along with their versions. Entities that are * still in use are not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const snapshot & destroyed(Archive &archive) const { auto size = reg.size() - reg.alive(); archive(static_cast<Entity>(size)); if(size) { auto curr = seed; archive(curr); for(--size; size; --size) { curr = follow(reg, curr); archive(curr); } } return *this; } /** * @brief Puts aside the given components. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive> const snapshot & component(Archive &archive) const { if constexpr(sizeof...(Component) == 1) { const auto sz = reg.template size<Component...>(); const auto *entities = reg.template data<Component...>(); archive(static_cast<Entity>(sz)); for(std::remove_const_t<decltype(sz)> i{}; i < sz; ++i) { const auto entity = entities[i]; archive(entity, reg.template get<Component...>(entity)); }; } else { (component<Component>(archive), ...); } return *this; } /** * @brief Puts aside the given components for the entities in a range. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @tparam It Type of input iterator. * @param archive A valid reference to an output archive. * @param first An iterator to the first element of the range to serialize. * @param last An iterator past the last element of the range to serialize. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive, typename It> const snapshot & component(Archive &archive, It first, It last) const { component<Component...>(archive, first, last, std::make_index_sequence<sizeof...(Component)>{}); return *this; } private: const registry<Entity> &reg; const Entity seed; follow_fn_type *follow; }; /** * @brief Utility class to restore a snapshot as a whole. * * A snapshot loader requires that the destination registry be empty and loads * all the data at once while keeping intact the identifiers that the entities * originally had.<br/> * An example of use is the implementation of a save/restore utility. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class snapshot_loader final { /*! @brief A registry is allowed to create snapshot loaders. */ friend class registry<Entity>; using force_fn_type = void(registry<Entity> &, const Entity, const bool); snapshot_loader(registry<Entity> &reg, force_fn_type *force) ENTT_NOEXCEPT : reg{reg}, force{force} { // restore a snapshot as a whole requires a clean registry assert(!reg.capacity()); } template<typename Archive> void assure(Archive &archive, bool destroyed) const { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); force(reg, entity, destroyed); } } template<typename Type, typename Archive, typename... Args> void assign(Archive &archive, Args... args) const { Entity length{}; archive(length); while(length--) { Entity entity{}; Type instance{}; archive(entity, instance); static constexpr auto destroyed = false; force(reg, entity, destroyed); reg.template assign<Type>(args..., entity, std::as_const(instance)); } } public: /*! @brief Copying a snapshot loader isn't allowed. */ snapshot_loader(const snapshot_loader &) = delete; /*! @brief Default move constructor. */ snapshot_loader(snapshot_loader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ snapshot_loader & operator=(const snapshot_loader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ snapshot_loader & operator=(snapshot_loader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const snapshot_loader & entities(Archive &archive) const { static constexpr auto destroyed = false; assure(archive, destroyed); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const snapshot_loader & destroyed(Archive &archive) const { static constexpr auto destroyed = true; assure(archive, destroyed); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create it with * the version it originally had. * * @tparam Component Types of components to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Component, typename Archive> const snapshot_loader & component(Archive &archive) const { (assign<Component>(archive), ...); return *this; } /** * @brief Destroys those entities that have no components. * * In case all the entities were serialized but only part of the components * was saved, it could happen that some of the entities have no components * once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A valid loader to continue restoring data. */ const snapshot_loader & orphans() const { reg.orphans([this](const auto entity) { reg.destroy(entity); }); return *this; } private: registry<Entity> &reg; force_fn_type *force; }; /** * @brief Utility class for _continuous loading_. * * A _continuous loader_ is designed to load data from a source registry to a * (possibly) non-empty destination. The loader can accomodate in a registry * more than one snapshot in a sort of _continuous loading_ that updates the * destination one step at a time.<br/> * Identifiers that entities originally had are not transferred to the target. * Instead, the loader maps remote identifiers to local ones while restoring a * snapshot.<br/> * An example of use is the implementation of a client-server applications with * the requirement of transferring somehow parts of the representation side to * side. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class continuous_loader final { using traits_type = entt_traits<Entity>; void destroy(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = reg.create(); remloc.emplace(entity, std::make_pair(local, true)); reg.destroy(local); } } void restore(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = reg.create(); remloc.emplace(entity, std::make_pair(local, true)); } else { remloc[entity].first = reg.valid(remloc[entity].first) ? remloc[entity].first : reg.create(); // set the dirty flag remloc[entity].second = true; } } template<typename Other, typename Type, typename Member> void update(Other &instance, Member Type:: *member) { if constexpr(!std::is_same_v<Other, Type>) { return; } else if constexpr(std::is_same_v<Member, Entity>) { instance.*member = map(instance.*member); } else { // maybe a container? let's try... for(auto &entity: instance.*member) { entity = map(entity); } } } template<typename Archive> void assure(Archive &archive, void(continuous_loader:: *member)(Entity)) { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); (this->*member)(entity); } } template<typename Component> void reset() { for(auto &&ref: remloc) { const auto local = ref.second.first; if(reg.valid(local)) { reg.template reset<Component>(local); } } } template<typename Other, typename Archive, typename Func, typename... Type, typename... Member> void assign(Archive &archive, Func func, Member Type:: *... member) { Entity length{}; archive(length); while(length--) { Entity entity{}; Other instance{}; archive(entity, instance); restore(entity); (update(instance, member), ...); func(map(entity), instance); } } public: /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Constructs a loader that is bound to a given registry. * @param reg A valid reference to a registry. */ continuous_loader(registry<entity_type> &reg) ENTT_NOEXCEPT : reg{reg} {} /*! @brief Copying a snapshot loader isn't allowed. */ continuous_loader(const continuous_loader &) = delete; /*! @brief Default move constructor. */ continuous_loader(continuous_loader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ continuous_loader & operator=(const continuous_loader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ continuous_loader & operator=(continuous_loader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> continuous_loader & entities(Archive &archive) { assure(archive, &continuous_loader::restore); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> continuous_loader & destroyed(Archive &archive) { assure(archive, &continuous_loader::destroy); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Component Type of component to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Component, typename Archive, typename... Type, typename... Member> continuous_loader & component(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &component) { reg.template assign_or_replace<std::decay_t<decltype(component)>>(entity, component); }; (reset<Component>(), ...); (assign<Component>(archive, apply, member...), ...); return *this; } /** * @brief Helps to purge entities that no longer have a conterpart. * * Users should invoke this member function after restoring each snapshot, * unless they know exactly what they are doing. * * @return A non-const reference to this loader. */ continuous_loader & shrink() { auto it = remloc.begin(); while(it != remloc.cend()) { const auto local = it->second.first; bool &dirty = it->second.second; if(dirty) { dirty = false; ++it; } else { if(reg.valid(local)) { reg.destroy(local); } it = remloc.erase(it); } } return *this; } /** * @brief Destroys those entities that have no components. * * In case all the entities were serialized but only part of the components * was saved, it could happen that some of the entities have no components * once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A non-const reference to this loader. */ continuous_loader & orphans() { reg.orphans([this](const auto entity) { reg.destroy(entity); }); return *this; } /** * @brief Tests if a loader knows about a given entity. * @param entity An entity identifier. * @return True if `entity` is managed by the loader, false otherwise. */ bool has(entity_type entity) const ENTT_NOEXCEPT { return (remloc.find(entity) != remloc.cend()); } /** * @brief Returns the identifier to which an entity refers. * * @warning * Attempting to use an entity that isn't managed by the loader results in * undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * loader doesn't knows about the entity. * * @param entity An entity identifier. * @return The identifier to which `entity` refers in the target registry. */ entity_type map(entity_type entity) const ENTT_NOEXCEPT { assert(has(entity)); return remloc.find(entity)->second.first; } private: std::unordered_map<Entity, std::pair<Entity, bool>> remloc; registry<Entity> &reg; }; } #endif // ENTT_ENTITY_SNAPSHOT_HPP
[ "michele.caini@gmail.com" ]
michele.caini@gmail.com
839076d924b743c021a8872c7818f0faf0e17463
f3b5c4a5ce869dee94c3dfa8d110bab1b4be698b
/controller/src/control-node/test/network_agent_mock.h
aada5a024dbffd785cb380855bce22e090aee1f6
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
pan2za/ctrl
8f808fb4da117fce346ff3d54f80b4e3d6b86b52
1d49df03ec4577b014b7d7ef2557d76e795f6a1c
refs/heads/master
2021-01-22T23:16:48.002959
2015-06-17T06:13:36
2015-06-17T06:13:36
37,454,161
2
0
null
null
null
null
UTF-8
C++
false
false
19,238
h
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef __ctrlplane__network_agent_mock__ #define __ctrlplane__network_agent_mock__ #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <map> #include <pugixml/pugixml.hpp> #include <tbb/compat/condition_variable> #include <tbb/mutex.h> #include "base/queue_task.h" namespace autogen { struct ItemType; struct EnetItemType; struct McastItemType; class VirtualRouter; class VirtualMachine; } namespace pugi { class xml_document; class xml_node; } class EventManager; class XmppChannelConfig; class XmppClient; class BgpXmppChannelManager; namespace test { enum TestErrorType { ROUTE_AF_ERROR, ROUTE_SAFI_ERROR, XML_TOKEN_ERROR, }; struct RouteParams { RouteParams() : edge_replication_not_supported(false), assisted_replication_supported(false) { }; bool edge_replication_not_supported; bool assisted_replication_supported; std::string replicator_address; }; struct RouteAttributes { public: static const int kDefaultLocalPref = 100; static const int kDefaultSequence = 0; RouteAttributes() : local_pref(kDefaultLocalPref), sequence(kDefaultSequence), sgids(std::vector<int>()) { } RouteAttributes(uint32_t lpref, uint32_t seq, const std::vector<int> &sg) : local_pref(lpref), sequence(seq), sgids(sg) { } RouteAttributes(uint32_t lpref, uint32_t seq) : local_pref(lpref), sequence(seq), sgids(std::vector<int>()) { } RouteAttributes(uint32_t lpref) : local_pref(lpref), sequence(kDefaultSequence), sgids(std::vector<int>()) { } RouteAttributes(const std::vector<int> &sg) : local_pref(kDefaultLocalPref), sequence(kDefaultSequence), sgids(sg) { } RouteAttributes(const RouteParams &params) : local_pref(kDefaultLocalPref), sequence(kDefaultSequence), params(params) { } void SetSg(const std::vector<int> &sg) { sgids = sg; } static int GetDefaultLocalPref() { return kDefaultLocalPref; } static int GetDefaultSequence() { return kDefaultSequence; } uint32_t local_pref; uint32_t sequence; std::vector<int> sgids; RouteParams params; }; struct NextHop { NextHop() : label_(0) { } NextHop(std::string address) : address_(address), label_(0) { tunnel_encapsulations_.push_back("gre"); } NextHop(std::string address, uint32_t label, std::string tun1 = "gre") : address_(address), label_(label) { if (tun1 == "all") { tunnel_encapsulations_.push_back("gre"); tunnel_encapsulations_.push_back("udp"); tunnel_encapsulations_.push_back("vxlan"); } else if (tun1 == "all_ipv6") { tunnel_encapsulations_.push_back("gre"); tunnel_encapsulations_.push_back("udp"); } else { tunnel_encapsulations_.push_back(tun1); } } bool operator==(NextHop other) { if (address_ != other.address_) return false; if (label_ != other.label_) return false; if (tunnel_encapsulations_.size() != other.tunnel_encapsulations_.size()) { return false; } std::vector<std::string>::iterator i; for (i = tunnel_encapsulations_.begin(); i != tunnel_encapsulations_.end(); i++) { if (std::find(other.tunnel_encapsulations_.begin(), other.tunnel_encapsulations_.end(), *i) == other.tunnel_encapsulations_.end()) { return false; } } return true; } std::string address_; int label_; std::vector<std::string> tunnel_encapsulations_; }; typedef std::vector<NextHop> NextHops; class XmppDocumentMock { public: enum Oper { ADD, CHANGE, DELETE, }; static const char *kControlNodeJID; static const char *kNetworkServiceJID; static const char *kConfigurationServiceJID; static const char *kPubSubNS; XmppDocumentMock(const std::string &hostname); pugi::xml_document *RouteAddXmlDoc(const std::string &network, const std::string &prefix, const NextHops &nexthops = NextHops(), const RouteAttributes &attributes = RouteAttributes()); pugi::xml_document *RouteDeleteXmlDoc(const std::string &network, const std::string &prefix); pugi::xml_document *Inet6RouteAddXmlDoc(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteAttributes &attributes); pugi::xml_document *Inet6RouteChangeXmlDoc(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteAttributes &attributes); pugi::xml_document *Inet6RouteDeleteXmlDoc(const std::string &network, const std::string &prefix); pugi::xml_document *Inet6RouteAddBogusXmlDoc(const std::string &network, const std::string &prefix, NextHops nexthops, TestErrorType error_type); pugi::xml_document *RouteEnetAddXmlDoc(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteAttributes &attributes); pugi::xml_document *RouteEnetDeleteXmlDoc(const std::string &network, const std::string &prefix, NextHops nexthops = NextHops()); pugi::xml_document *RouteMcastAddXmlDoc(const std::string &network, const std::string &sg, const std::string &nexthop, const std::string &label_range, const std::string &encap); pugi::xml_document *RouteMcastDeleteXmlDoc(const std::string &network, const std::string &sg); pugi::xml_document *SubscribeXmlDoc(const std::string &network, int id, std::string type = kNetworkServiceJID); pugi::xml_document *UnsubscribeXmlDoc(const std::string &network, int id, std::string type = kNetworkServiceJID); const std::string &hostname() const { return hostname_; } const std::string &localaddr() const { return localaddr_; } void set_localaddr(const std::string &addr) { localaddr_ = addr; } private: pugi::xml_node PubSubHeader(std::string type); pugi::xml_document *SubUnsubXmlDoc( const std::string &network, int id, bool sub, std::string type); pugi::xml_document *Inet6RouteAddDeleteXmlDoc(const std::string &network, const std::string &prefix, Oper oper, const NextHops &nexthops = NextHops(), const RouteAttributes &attributes = RouteAttributes()); pugi::xml_document *RouteAddDeleteXmlDoc(const std::string &network, const std::string &prefix, bool add, const NextHops &nexthop = NextHops(), const RouteAttributes &attributes = RouteAttributes()); pugi::xml_document *RouteEnetAddDeleteXmlDoc(const std::string &network, const std::string &prefix, bool add, const NextHops &nexthops = NextHops(), const RouteAttributes &attributes = RouteAttributes()); pugi::xml_document *RouteMcastAddDeleteXmlDoc(const std::string &network, const std::string &sg, bool add, const std::string &nexthop = std::string(), const std::string &label_range = std::string(), const std::string &encap = std::string()); std::string hostname_; int label_alloc_; std::string localaddr_; boost::scoped_ptr<pugi::xml_document> xdoc_; }; class NetworkAgentMock { private: class AgentPeer; public: typedef autogen::ItemType RouteEntry; typedef std::map<std::string, RouteEntry *> RouteTable; typedef autogen::ItemType Inet6RouteEntry; typedef std::map<std::string, Inet6RouteEntry *> Inet6RouteTable; typedef autogen::EnetItemType EnetRouteEntry; typedef std::map<std::string, EnetRouteEntry *> EnetRouteTable; typedef autogen::McastItemType McastRouteEntry; typedef std::map<std::string, McastRouteEntry *> McastRouteTable; typedef autogen::VirtualRouter VRouterEntry; typedef std::map<std::string, VRouterEntry *> VRouterTable; typedef autogen::VirtualMachine VMEntry; typedef std::map<std::string, VMEntry *> VMTable; template <typename T> class Instance { public: typedef std::map<std::string, T *> TableMap; Instance(); virtual ~Instance(); void Update(long count); void Update(const std::string &node, T *entry); void Remove(const std::string &node); void Clear(); int Count() const; const T *Lookup(const std::string &node) const; private: size_t count_; TableMap table_; }; template <typename T> class InstanceMgr { public: typedef std::map<std::string, Instance<T> *> InstanceMap; InstanceMgr(NetworkAgentMock *parent, std::string type) { parent_ = parent; type_ = type; } bool HasSubscribed(const std::string &network); void Subscribe(const std::string &network, int id = -1, bool wait_for_established = true, bool send_subscribe = true); void Unsubscribe(const std::string &network, int id = -1, bool wait_for_established = true, bool send_unsubscribe = true); void Update(const std::string &network, long count); void Update(const std::string &network, const std::string &node_name, T *rt_entry); void Remove(const std::string &network, const std::string &node_name); int Count(const std::string &network) const; int Count() const; void Clear(); const T *Lookup(const std::string &network, const std::string &prefix) const; private: NetworkAgentMock *parent_; std::string type_; InstanceMap instance_map_; }; NetworkAgentMock(EventManager *evm, const std::string &hostname, int server_port, std::string local_address = "127.0.0.1", std::string server_address = "127.0.0.1", bool xmpp_auth_enabled = false); ~NetworkAgentMock(); bool skip_updates_processing() { return skip_updates_processing_; } void set_skip_updates_processing(bool set) { skip_updates_processing_ = set; } void SessionDown(); void SessionUp(); void SubscribeAll(const std::string &network, int id = -1, bool wait_for_established = true) { route_mgr_->Subscribe(network, id, wait_for_established, true); inet6_route_mgr_->Subscribe(network, id, wait_for_established, false); enet_route_mgr_->Subscribe(network, id, wait_for_established, false); mcast_route_mgr_->Subscribe(network, id, wait_for_established, false); } void UnsubscribeAll(const std::string &network, int id = -1, bool wait_for_established = true) { route_mgr_->Unsubscribe(network, id, wait_for_established, true); inet6_route_mgr_->Unsubscribe(network, id, wait_for_established, false); enet_route_mgr_->Unsubscribe(network, id, wait_for_established, false); mcast_route_mgr_->Unsubscribe(network, id, wait_for_established, false); } void Subscribe(const std::string &network, int id = -1, bool wait_for_established = true) { route_mgr_->Subscribe(network, id, wait_for_established); } void Unsubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { route_mgr_->Unsubscribe(network, id, wait_for_established); } int RouteCount(const std::string &network) const; int RouteCount() const; const RouteEntry *RouteLookup(const std::string &network, const std::string &prefix) const { return route_mgr_->Lookup(network, prefix); } void Inet6Subscribe(const std::string &network, int id = -1, bool wait_for_established = true) { inet6_route_mgr_->Subscribe(network, id, wait_for_established); } void Inet6Unsubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { inet6_route_mgr_->Unsubscribe(network, id, wait_for_established); } int Inet6RouteCount(const std::string &network) const; int Inet6RouteCount() const; const RouteEntry *Inet6RouteLookup(const std::string &network, const std::string &prefix) const { return inet6_route_mgr_->Lookup(network, prefix); } void AddRoute(const std::string &network, const std::string &prefix, const std::string nexthop = "", int local_pref = 0); void AddRoute(const std::string &network, const std::string &prefix, const NextHops &nexthops, int local_pref = 0); void AddRoute(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteAttributes &attributes); void DeleteRoute(const std::string &network, const std::string &prefix); void AddInet6Route(const std::string &network, const std::string &prefix, const NextHops &nexthops = NextHops(), const RouteAttributes &attributes = RouteAttributes()); void ChangeInet6Route(const std::string &network, const std::string &prefix, const NextHops &nexthops = NextHops(), const RouteAttributes &attributes = RouteAttributes()); void DeleteInet6Route(const std::string &network, const std::string &prefix); void AddBogusInet6Route(const std::string &network, const std::string &prefix, const std::string &nexthop, TestErrorType error_type); void EnetSubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { enet_route_mgr_->Subscribe(network, id, wait_for_established); } void EnetUnsubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { enet_route_mgr_->Unsubscribe(network, id, wait_for_established); } int EnetRouteCount(const std::string &network) const; int EnetRouteCount() const; const EnetRouteEntry *EnetRouteLookup(const std::string &network, const std::string &prefix) const { return enet_route_mgr_->Lookup(network, prefix); } void AddEnetRoute(const std::string &network, const std::string &prefix, const std::string nexthop = "", const RouteParams *params = NULL); void AddEnetRoute(const std::string &network, const std::string &prefix, const NextHop &nexthop, const RouteParams *params = NULL); void AddEnetRoute(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteParams *params = NULL); void AddEnetRoute(const std::string &network, const std::string &prefix, const NextHop &nexthop, const RouteAttributes &attributes); void AddEnetRoute(const std::string &network, const std::string &prefix, const NextHops &nexthops, const RouteAttributes &attributes); void DeleteEnetRoute(const std::string &network, const std::string &prefix); void McastSubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { mcast_route_mgr_->Subscribe(network, id, wait_for_established); } void McastUnsubscribe(const std::string &network, int id = -1, bool wait_for_established = true) { mcast_route_mgr_->Unsubscribe(network, id, wait_for_established); } int McastRouteCount(const std::string &network) const; int McastRouteCount() const; const McastRouteEntry *McastRouteLookup(const std::string &network, const std::string &prefix) const { return mcast_route_mgr_->Lookup(network, prefix); } void AddMcastRoute(const std::string &network, const std::string &sg, const std::string &nexthop, const std::string &label_range, const std::string &encap = ""); void DeleteMcastRoute(const std::string &network, const std::string &sg); bool IsEstablished(); bool IsSessionEstablished(); void ClearInstances(); const std::string &hostname() const { return impl_->hostname(); } const std::string &localaddr() const { return impl_->localaddr(); } const std::string ToString() const; void set_localaddr(const std::string &addr) { impl_->set_localaddr(addr); } XmppDocumentMock *GetXmlHandler() { return impl_.get(); } XmppClient *client() { return client_; } void Delete(); tbb::mutex &get_mutex() { return mutex_; } bool down() { return down_; } const std::string local_address() const { return local_address_; } void DisableRead(bool disable_read); enum RequestType { IS_ESTABLISHED, }; struct Request { RequestType type; bool result; }; bool ProcessRequest(Request *request); size_t get_connect_error(); size_t get_session_close(); uint32_t flap_count(); boost::scoped_ptr<InstanceMgr<RouteEntry> > route_mgr_; boost::scoped_ptr<InstanceMgr<Inet6RouteEntry> > inet6_route_mgr_; boost::scoped_ptr<InstanceMgr<EnetRouteEntry> > enet_route_mgr_; boost::scoped_ptr<InstanceMgr<McastRouteEntry> > mcast_route_mgr_; boost::scoped_ptr<InstanceMgr<VRouterEntry> > vrouter_mgr_; boost::scoped_ptr<InstanceMgr<VMEntry> > vm_mgr_; private: static void Initialize(); AgentPeer *GetAgent(); XmppChannelConfig *CreateXmppConfig(); bool ConnectionDestroyed() const; XmppClient *client_; std::auto_ptr<AgentPeer> peer_; boost::scoped_ptr<XmppDocumentMock> impl_; WorkQueue<Request *> work_queue_; std::string server_address_; std::string local_address_; int server_port_; bool skip_updates_processing_; bool down_; tbb::mutex mutex_; tbb::mutex work_mutex_; tbb::interface5::condition_variable cond_var_; bool xmpp_auth_enabled_; }; typedef boost::shared_ptr<NetworkAgentMock> NetworkAgentMockPtr; } // namespace test #endif /* defined(__ctrlplane__network_agent_mock__) */
[ "pan2za@live.com" ]
pan2za@live.com
7119f2a69668696d49b00d15a078120d7477fa5c
b02f4e748d42b6dc195ecf02a6a047b6db8bb561
/srm789/srm789/Source.cpp
cef04b2cd2d6b813b2810212a58f0c06d1837e57
[]
no_license
pcodex/tc250L1
a74e3ddeafffab818ec4613ddce55637571d2ac1
e96f253a065576e924b5d02f2ad3e2066a5a199c
refs/heads/master
2021-04-24T00:20:14.025346
2020-09-30T21:06:02
2020-09-30T21:06:02
250,042,476
0
0
null
2020-09-30T21:06:04
2020-03-25T17:14:04
C++
ISO-8859-1
C++
false
false
5,668
cpp
/* Problem Statement      Here's the beginning of an ASCII art bitmap that depicts a tape measure: ################################################### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 0 10 20 A more formal description: The first row is full of '#' marks and represents the top edge of the tape measure. The second row shows unit marks in every second column. Multiples of five get a longer mark that continues into the third row. Multiples of ten get a mark that reaches all the way into the fourth row, and they also get labels in the fifth row. The label always begins in the column with the mark and extends to the right as needed. You are given the ints leftMark and rightMark. Construct the drawing of the part of the tape measure that begins with the column containing the mark for number leftMark and ends with the column that contains the mark for the number rightMark. Return the drawing as a vector <string>. Definition      Class: TapeMeasure Method: draw Parameters: int, int Returns: vector <string> Method signature: vector <string> draw(int leftMark, int rightMark) (be sure your method is public) Limits      Time limit (s): 2.000 Memory limit (MB): 256 Constraints - leftMark will be between 0 and 999, inclusive. - rightMark will be between leftMark and 999, inclusive. - rightMark - leftMark will be at most 25. Examples 0)      0 25 Returns: {"###################################################", "# # # # # # # # # # # # # # # # # # # # # # # # # #", "# # # # # #", "# # # ", "0 10 20 " } This is the exact example shown in the problem statement. 1)      981 990 Returns: {"###################", "# # # # # # # # # #", " # #", " #", "0 9" } Note how the labels for marks 980 and 990 are partially visible in this section of the tape measure. Below we show a section of the tape measure that is one mark wider on each side (left=980, right=991) so that you can see these labels completely. ####################### # # # # # # # # # # # # # # # # # 980 990 2)      20 20 Returns: {"#", "#", "#", "#", "2" } 3)      31 38 Returns: {"###############", "# # # # # # # #", " # ", " ", " " } This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved. */ #include <string> #include <vector> #include <map> #include <iostream> #include <cmath> #include <algorithm> #include <sstream> using namespace std; class TapeMeasure { public: vector <string> draw(int leftMark, int rightMark); }; vector <string> TapeMeasure::draw(int leftMark, int rightMark) { string str1, str2, str3, str4; vector<string> vs; int noof2rowmarks = rightMark - leftMark + 1; int firstrowmarks = (noof2rowmarks * 2) - 1; str1 = string(firstrowmarks, '#'); for (int i = leftMark; i <= rightMark; ++i) { if (i == rightMark) str2 += '#'; else str2 += "# "; } for (int j=leftMark; j <= rightMark; ++j) { if (j == rightMark && j%5==0) str3 += '#'; else if (j % 5 == 0) str3 += "# "; else if (j == rightMark) str3 += " "; else str3 += " "; } for (int j = leftMark; j <= rightMark; ++j) { if (j == rightMark && j%10==0) str4 += '#'; else if (j % 10 == 0) str4 += "# "; else if (j == rightMark) str4 += " "; else str4 += " "; } vs.push_back(str1); vs.push_back(str2); vs.push_back(str3); vs.push_back(str4); string s5; for (int i = leftMark; i <= rightMark; ++i) { if (i > 100 && i==leftMark) { if (((i - 1) % 10) == 0) { int val = i - 1; stringstream ssval; ssval << val; string strval = ssval.str(); s5 = strval[2]; s5 += " "; continue; } //continue; } if (i == rightMark && ((rightMark % 10) == 0)) { stringstream ssi; ssi << rightMark; string strssi = ssi.str(); s5 += strssi[0]; } else if (i%10==0) { stringstream ssi; ssi << i; string strssi = ssi.str(); s5 += strssi; if (i == 0) s5 += " "; } else if (i == rightMark && (((i-1)%10)==0) && (i-1>=100)) { continue; } else if(i==rightMark) { s5 += " "; } else if((i==leftMark+1) && (leftMark%10==0) && (i>=100)) { s5 += " "; } else if((i-1>=100) && ((i-1)%10==0)) { s5 += " "; } else { s5 += " "; } } vs.push_back(s5); return vs; } int main() { TapeMeasure tpm; vector<string> out = tpm.draw(566, 579); return 0; }
[ "prab.missier@gmail.com" ]
prab.missier@gmail.com
662dad72996ca0fcd5912f51c2340e4075cc9c4c
38c10c01007624cd2056884f25e0d6ab85442194
/third_party/WebKit/Source/core/testing/DictionaryTest.cpp
5545867abf5c690cffadb9e8a21387545b6d33f9
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
8,456
cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "DictionaryTest.h" #include "bindings/core/v8/V8ObjectBuilder.h" #include "core/testing/InternalDictionary.h" #include "core/testing/InternalDictionaryDerived.h" namespace blink { DictionaryTest::DictionaryTest() : m_requiredBooleanMember(false) { } DictionaryTest::~DictionaryTest() { } void DictionaryTest::set(const InternalDictionary& testingDictionary) { reset(); if (testingDictionary.hasLongMember()) m_longMember = testingDictionary.longMember(); if (testingDictionary.hasLongMemberWithClamp()) m_longMemberWithClamp = testingDictionary.longMemberWithClamp(); if (testingDictionary.hasLongMemberWithEnforceRange()) m_longMemberWithEnforceRange = testingDictionary.longMemberWithEnforceRange(); m_longMemberWithDefault = testingDictionary.longMemberWithDefault(); if (testingDictionary.hasLongOrNullMember()) m_longOrNullMember = testingDictionary.longOrNullMember(); // |longOrNullMemberWithDefault| has a default value but can be null, so // we need to check availability. if (testingDictionary.hasLongOrNullMemberWithDefault()) m_longOrNullMemberWithDefault = testingDictionary.longOrNullMemberWithDefault(); if (testingDictionary.hasBooleanMember()) m_booleanMember = testingDictionary.booleanMember(); if (testingDictionary.hasDoubleMember()) m_doubleMember = testingDictionary.doubleMember(); if (testingDictionary.hasUnrestrictedDoubleMember()) m_unrestrictedDoubleMember = testingDictionary.unrestrictedDoubleMember(); m_stringMember = testingDictionary.stringMember(); m_stringMemberWithDefault = testingDictionary.stringMemberWithDefault(); m_byteStringMember = testingDictionary.byteStringMember(); m_usvStringMember = testingDictionary.usvStringMember(); if (testingDictionary.hasStringSequenceMember()) m_stringSequenceMember = testingDictionary.stringSequenceMember(); m_stringSequenceMemberWithDefault = testingDictionary.stringSequenceMemberWithDefault(); if (testingDictionary.hasStringSequenceOrNullMember()) m_stringSequenceOrNullMember = testingDictionary.stringSequenceOrNullMember(); m_enumMember = testingDictionary.enumMember(); m_enumMemberWithDefault = testingDictionary.enumMemberWithDefault(); m_enumOrNullMember = testingDictionary.enumOrNullMember(); if (testingDictionary.hasEnumArrayMember()) m_enumArrayMember = testingDictionary.enumArrayMember(); if (testingDictionary.hasElementMember()) m_elementMember = testingDictionary.elementMember(); if (testingDictionary.hasElementOrNullMember()) m_elementOrNullMember = testingDictionary.elementOrNullMember(); m_objectMember = testingDictionary.objectMember(); m_objectOrNullMemberWithDefault = testingDictionary.objectOrNullMemberWithDefault(); if (testingDictionary.hasDoubleOrStringMember()) m_doubleOrStringMember = testingDictionary.doubleOrStringMember(); if (testingDictionary.hasDoubleOrStringSequenceMember()) m_doubleOrStringSequenceMember = testingDictionary.doubleOrStringSequenceMember(); m_eventTargetOrNullMember = testingDictionary.eventTargetOrNullMember(); if (testingDictionary.hasDictionaryMember()) { HashMap<String, String> properties; testingDictionary.dictionaryMember().getOwnPropertiesAsStringHashMap(properties); m_dictionaryMemberProperties = properties; } } void DictionaryTest::get(InternalDictionary& result) { if (m_longMember) result.setLongMember(m_longMember.get()); if (m_longMemberWithClamp) result.setLongMemberWithClamp(m_longMemberWithClamp.get()); if (m_longMemberWithEnforceRange) result.setLongMemberWithEnforceRange(m_longMemberWithEnforceRange.get()); result.setLongMemberWithDefault(m_longMemberWithDefault); if (m_longOrNullMember) result.setLongOrNullMember(m_longOrNullMember.get()); if (m_longOrNullMemberWithDefault) result.setLongOrNullMemberWithDefault(m_longOrNullMemberWithDefault.get()); if (m_booleanMember) result.setBooleanMember(m_booleanMember.get()); if (m_doubleMember) result.setDoubleMember(m_doubleMember.get()); if (m_unrestrictedDoubleMember) result.setUnrestrictedDoubleMember(m_unrestrictedDoubleMember.get()); result.setStringMember(m_stringMember); result.setStringMemberWithDefault(m_stringMemberWithDefault); result.setByteStringMember(m_byteStringMember); result.setUsvStringMember(m_usvStringMember); if (m_stringSequenceMember) result.setStringSequenceMember(m_stringSequenceMember.get()); result.setStringSequenceMemberWithDefault(m_stringSequenceMemberWithDefault); if (m_stringSequenceOrNullMember) result.setStringSequenceOrNullMember(m_stringSequenceOrNullMember.get()); result.setEnumMember(m_enumMember); result.setEnumMemberWithDefault(m_enumMemberWithDefault); result.setEnumOrNullMember(m_enumOrNullMember); if (m_enumArrayMember) result.setEnumArrayMember(m_enumArrayMember.get()); if (m_elementMember) result.setElementMember(m_elementMember); if (m_elementOrNullMember) result.setElementOrNullMember(m_elementOrNullMember); result.setObjectMember(m_objectMember); result.setObjectOrNullMemberWithDefault(m_objectOrNullMemberWithDefault); if (!m_doubleOrStringMember.isNull()) result.setDoubleOrStringMember(m_doubleOrStringMember); if (!m_doubleOrStringSequenceMember.isNull()) result.setDoubleOrStringSequenceMember(m_doubleOrStringSequenceMember.get()); result.setEventTargetOrNullMember(m_eventTargetOrNullMember); } ScriptValue DictionaryTest::getDictionaryMemberProperties(ScriptState* scriptState) { if (!m_dictionaryMemberProperties) return ScriptValue(); V8ObjectBuilder builder(scriptState); HashMap<String, String> properties = m_dictionaryMemberProperties.get(); for (HashMap<String, String>::iterator it = properties.begin(); it != properties.end(); ++it) builder.addString(it->key, it->value); return builder.scriptValue(); } void DictionaryTest::setDerived(const InternalDictionaryDerived& derived) { ASSERT(derived.hasRequiredBooleanMember()); set(derived); if (derived.hasDerivedStringMember()) m_derivedStringMember = derived.derivedStringMember(); m_derivedStringMemberWithDefault = derived.derivedStringMemberWithDefault(); m_requiredBooleanMember = derived.requiredBooleanMember(); } void DictionaryTest::getDerived(InternalDictionaryDerived& result) { get(result); result.setDerivedStringMember(m_derivedStringMember); result.setDerivedStringMemberWithDefault(m_derivedStringMemberWithDefault); result.setRequiredBooleanMember(m_requiredBooleanMember); } void DictionaryTest::reset() { m_longMember = nullptr; m_longMemberWithClamp = nullptr; m_longMemberWithEnforceRange = nullptr; m_longMemberWithDefault = -1; // This value should not be returned. m_longOrNullMember = nullptr; m_longOrNullMemberWithDefault = nullptr; m_booleanMember = nullptr; m_doubleMember = nullptr; m_unrestrictedDoubleMember = nullptr; m_stringMember = String(); m_stringMemberWithDefault = String("Should not be returned"); m_stringSequenceMember = nullptr; m_stringSequenceMemberWithDefault.fill("Should not be returned", 1); m_stringSequenceOrNullMember = nullptr; m_enumMember = String(); m_enumMemberWithDefault = String(); m_enumOrNullMember = String(); m_enumArrayMember = nullptr; m_elementMember = nullptr; m_elementOrNullMember = nullptr; m_objectMember = ScriptValue(); m_objectOrNullMemberWithDefault = ScriptValue(); m_doubleOrStringMember = DoubleOrString(); m_eventTargetOrNullMember = nullptr; m_derivedStringMember = String(); m_derivedStringMemberWithDefault = String(); m_requiredBooleanMember = false; m_dictionaryMemberProperties = nullptr; } DEFINE_TRACE(DictionaryTest) { visitor->trace(m_elementMember); visitor->trace(m_elementOrNullMember); visitor->trace(m_doubleOrStringSequenceMember); visitor->trace(m_eventTargetOrNullMember); } }
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
2d9b74c447dafb4bdc34a4f67bdad3689190afc0
506e96a1186f5524ad9a6f1466e65f4c6857a1c3
/codeforces/1279/B.cpp
9be1ba6a007d9643b4de54ca99edec43cc4031cb
[]
no_license
142ayushkumar/OJ-Submissions
65c5a9baf13b9a8155178f66a1698dcbcc05d24f
a71e9a8f96cba8859158db7d25b04f28fc9efa34
refs/heads/master
2023-02-04T07:28:40.316895
2019-12-16T15:25:00
2020-12-22T09:10:06
323,572,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,973
cpp
#include <bits/stdc++.h> using namespace std; #define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define pb push_back #define mp make_pair #define int long long #define all(c) (c).begin(),(c).end() #define M 1000000007 #define INF LLONG_MAX #define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__) template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";} template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ", "; dbs(str.substr(idx + 1), s...);} template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";} template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";} template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";} template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";} template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";} // Use pr(a,b,c,d,e) or cerr<<anything or prc(v.begin(),v.end()) or prc(v,v+n) // int32_t main() { fastio; int t; cin >> t; while(t--) { int n, m, tot=0; cin >> n >> m; vector<int> a(n); for(int i=0;i<n;i++) { cin >> a[i]; tot += a[i]; } int curr = 0, mx = 0, index = -1, i; for(i=0;i<n;i++) { curr += a[i]; if(a[i] > mx) index = i; mx = max(mx, a[i]); if(curr > m) break; } if(tot<=m) cout << "0\n"; else if(curr > m && curr - mx < m) cout << index+1 << "\n"; else cout << "0\n"; } return 0; }
[ "142ayushkumar@gmail.com" ]
142ayushkumar@gmail.com
ea99ea033781737330c77adb6d28ff78ac2ff812
7eec256284530e38e2e3b34cfb003fb27d592ccd
/IM - Intergalactic Map.cpp
01b7349da0d6e9982c44debb4778b0e125d2e376
[]
no_license
rudyjayk/SPOJ
88c6c1c504c0570305737b14249c2e39dc61cb39
dd961a5efff3c30fbb03dea957e03674f4dea255
refs/heads/master
2022-03-04T03:36:39.429095
2019-10-28T09:14:42
2019-10-28T09:14:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,357
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define inf 1e18 #define vi vector<int> /** https://youtu.be/M6cm8UeeziI https://cp-algorithms.com/graph/dinic.html */ /// 0 based struct Edge { int from; int to; ll cap; ll flow = 0; Edge(int _from, int _to, ll _cap) { from = _from; to = _to; cap = _cap; } }; struct Dinic { vector<Edge> edges; vector<vi> adj; int n, m=0; int source,sink; vi level, ptr; queue<int> q; Dinic(int _n, int _source, int _sink) { n = _n; source = _source; sink = _sink; adj.resize(n); level.resize(n); ptr.resize(n); } void addEdge(int from, int to, ll cap) { edges.push_back(Edge(from, to, cap)); adj[from].push_back(m++); edges.push_back(Edge(to, from, 0)); adj[to].push_back(m++); } bool bfs() { while(!q.empty()){ int from = q.front(); q.pop(); for(int i=0; i<adj[from].size(); i++){ int id = adj[from][i]; int to = edges[id].to; if(edges[id].cap - edges[id].flow ==0) continue; if(level[ to ] != -1) continue; level[to] = level[from] + 1; q.push(to); } } return level[sink] != -1; } ll dfs(int from, ll pushed) { if(pushed==0) return 0; if(from==sink) return pushed; for(int& cid = ptr[from]; cid<(int)adj[from].size(); cid++){ int id = adj[from][cid]; int to = edges[id].to; if(level[from]+1 != level[to] || edges[id].cap - edges[id].flow == 0) continue; ll tempFlow = dfs(to, min(pushed, edges[id].cap - edges[id].flow)); if(tempFlow==0) continue; edges[id].flow +=tempFlow; edges[id^1].flow -=tempFlow; return tempFlow; } return 0; } ll getFlow() { ll maxFlow = 0; while(true){ fill(level.begin(), level.end(), -1); level[source] = 0; while(!q.empty()) q.pop(); q.push(source); if(bfs()==false) break; fill(ptr.begin(), ptr.end(), 0); while(ll pushed = dfs(source, inf)) maxFlow+=pushed; } //cout<<maxFlow<<endl; return maxFlow; } }; int main() { int tc,n,m,a,b; scanf("%d",&tc); while(tc--){ scanf("%d",&n); scanf("%d",&m); int sink = 2*n + 1; Dinic dinic(2*n + 5, 2, sink); for(int i=1; i<=n; i++){ if(i==2)dinic.addEdge(i, n+i, 2); else dinic.addEdge(i, n+i, 1); } while(m--){ scanf("%d%d",&a,&b); if(a>=1 && a<=n && b>=1 && b<=n){ dinic.addEdge(a+n, b, 1); dinic.addEdge(b+n, a, 1); } } dinic.addEdge(n+1, sink, 1); dinic.addEdge(n+3, sink, 1); if(dinic.getFlow()>=2){ printf("YES\n"); } else{ printf("NO\n"); } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
790a00cbd89ace89f84d8f773e42a765ffb9bb00
d4c0b7fd40ddd8be34cb092cb7fd173f381dba65
/ForwardTTreeAnalysis/interface/DijetsTriggerAnalysis.h
b3710faee5b9f478d7e26b2ced67dfb0b698b18f
[]
no_license
ForwardGroupBrazil/ForwardAnalysis
8dceaacb1707c0769296f3c7b2e37c15a4a30ff7
5572335f19d1e0d385f73945e55e42fb4ed49761
refs/heads/master
2021-01-16T01:02:02.286181
2013-09-12T20:54:02
2013-09-12T20:54:02
12,787,581
1
4
null
null
null
null
UTF-8
C++
false
false
3,093
h
#ifndef DijetsTriggerAnalysis_h #define DijetsTriggerAnalysis_h #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "L1Trigger/GlobalTriggerAnalyzer/interface/L1GtUtils.h" #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctHFRingEtSums.h" #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctHFBitCounts.h" #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctCollections.h" #include <string> #include <map> #include <vector> class TH1F; class TH2F; class DijetsTriggerEvent; namespace dijetsTriggerAnalysis { class DijetsTriggerAnalysis { public: typedef DijetsTriggerEvent event_type; static const char* name; DijetsTriggerAnalysis() { } DijetsTriggerAnalysis(const edm::ParameterSet&); ~DijetsTriggerAnalysis(); void begin(); void begin(const edm::Run&, const edm::EventSetup&); void fill(DijetsTriggerEvent&, const edm::Event&, const edm::EventSetup&); void end(); private: bool acceptHFRingEtSum(std::vector<TH1F*>&, const L1GctHFRingEtSumsCollection*); bool acceptHFRingEtSum(std::vector<TH1F*>&, const L1GctHFBitCountsCollection*); void setTFileService(); void dijetsTriggerInfo(DijetsTriggerEvent&, const edm::Event&, const edm::EventSetup&); void dijetsTriggerJetInfo(DijetsTriggerEvent&, const edm::Event&, const edm::EventSetup&); void dijetsTriggerCaloTowerInfo(DijetsTriggerEvent&, const edm::Event&, const edm::EventSetup&); class Correlation{ public: Correlation():sumEvt_(0.),sumX_(0.),sumX2_(0.),sumY_(0.),sumY2_(0.),sumXY_(0.) {} void Fill(double x, double y) {++sumEvt_;sumX_ += x;sumX2_ += x*x;sumY_ += y;sumY2_ += y*y;sumXY_ += x*y;} double Value() { double covxy = sumXY_/sumEvt_ - (sumX_/sumEvt_)*(sumY_/sumEvt_); double sigx = sqrt(fabs(sumX2_/sumEvt_ - (sumX_/sumEvt_)*(sumX_/sumEvt_))); double sigy = sqrt(fabs(sumY2_/sumEvt_ - (sumY_/sumEvt_)*(sumY_/sumEvt_))); return ((sigx == 0.)||(sigy == 0.)) ? 0. : covxy/(sigx*sigy); } private: double sumEvt_; double sumX_; double sumX2_; double sumY_; double sumY2_; double sumXY_; }; edm::InputTag jetTag_; edm::InputTag particleFlowTag_; edm::InputTag caloTowerTag_; edm::InputTag gtDigisTag_; edm::InputTag l1GtObjectMapTag_; edm::InputTag gctDigisTag_; edm::InputTag triggerResultsTag_; L1GtUtils l1GtUtils_; unsigned int thresholdHFRingEtSum_; unsigned int thresholdHFRingBitCount_; std::vector<std::string> ringNames_; TH1F* h_summaryL1_; std::vector<TH1F*> histosCountAll_; std::vector<std::vector<TH1F*> > histosRingEtSum_; std::vector<std::vector<TH1F*> > histosRingBitCount_; std::vector<std::string> l1TriggerNames_; std::vector<std::string> hltPathNames_; TH2F* h_correlations_; std::map<std::pair<int,int>,Correlation> correlations_; TH1F *hltTriggerPassHisto_,*hltTriggerNamesHisto_; }; } // namespace #endif //end code
[ "" ]
cb3e63d3664917ed03499b8a24fc0ca2c55c5252
4e80311439acf8d2d86125dc8952a8577c31fc13
/Build/Test_QT5/Test/Base/CH07/0703_sound.h
ba5fb1cd4474aae10545913a20a85da2c2f3356c
[]
no_license
mytree/Test_QT5
fcf4b1c5ddb3781fc7e3c6becf2f402b99343737
05f8185d6655338ae21d21b6b495e44be51fc972
refs/heads/master
2020-09-12T22:05:08.508974
2020-01-06T08:53:26
2020-01-06T08:53:26
222,572,470
0
0
null
null
null
null
UTF-8
C++
false
false
418
h
#pragma once #ifdef __linux__ class C0703_Sound : public ITestObject { public: virtual int OnTest(int nArgNum, char **ppArgs) { return -1; } }; #else # include <QtMultimedia/QSound> class C0703_Sound : public ITestObject { public: virtual int OnTest(int nArgNum, char **ppArgs) { QApplication app(nArgNum, ppArgs); QSound *sound = new QSound("test.wav"); sound->play(); return app.exec(); } }; #endif
[ "tape-a@hanmail.net" ]
tape-a@hanmail.net
96cb57e2f1d4d506e66b2271c5e63892cd50dad0
03f98883a8cf6eb060588c81925ea795db83324e
/src/Code/MATCRYPT.CPP
935d2d6b93b0c32ef3198592bb1c28f6789bdd5c
[ "Apache-2.0" ]
permissive
featherless/2003-EscapeFromTheFunkyFactory
d164b60184fc55095fd7ca3740809851067feae2
b4214404322c40e6755f22156e6b3d5d96b3dc9a
refs/heads/master
2020-12-24T21:00:29.988544
2016-05-27T05:59:08
2016-05-27T05:59:08
59,804,681
0
0
null
null
null
null
UTF-8
C++
false
false
3,831
cpp
/////////////////////////////////////////////// /* */ /* MATCRYPT.CPP - SOURCE FILE FOR MATCRYPT.H */ /* MATRIX ENCRYPTION ALGORITHM OBJECT */ /* */ /* CREATED DAV YUST, 2002 */ /* SNIPERDAV@FP2K2.COM */ /* */ /* DO NOT MODIFY IN ANY WAY WITHOUT */ /* WRITTEN PERMISSION FROM THE AUTHOR. */ /* */ /////////////////////////////////////////////// #include "matcrypt.h" mtxEncryptor::mtxEncryptor() { for(int i = 0; i < 256; i++) { xvalue[i] = (char)(i % 16); yvalue[i] = (char)((i - (i % 16)) / 16); characters[(int)xvalue[i]][(int)yvalue[i]] = (char)i; } x1 = x2 = y1 = y2 = 0; curPair = 0; } void mtxEncryptor::encrypt(char iStr[], char destStr[]) { char* returnStr; int tmpVar = 0; int length = strlen(iStr); //extend string if needed to make it an even # of characters if(length % 2) { returnStr = new char[++length + 1]; strcpy(returnStr, iStr); strcat(returnStr, " "); } else { returnStr = new char[length + 1]; strcpy(returnStr, iStr); } //loop through pairs and encrypt/decrypt for(curPair = 0; curPair < (length >> 1); curPair++) { x1 = xvalue[returnStr[curPair * 2]]; y1 = yvalue[returnStr[curPair * 2]]; x2 = xvalue[returnStr[(curPair * 2)+1]]; y2 = yvalue[returnStr[(curPair * 2)+1]]; if(x1 == x2 && y1 == y2) //same character - flip x and y { x1 = x2 = 16 - x1; y1 = y2 = 16 - y1; } else if(x1 == x2) // same column { y1 = (y1 + 1) % 16; y2 = (y2 + 1) % 16; } else if(y1 == y2) //same row { x1 = (x1 + 1) % 16; x2 = (x2 + 1) % 16; } else { tmpVar = x1; //flip x x1 = x2; x2 = tmpVar; } returnStr[curPair * 2] = characters[x1][y1]; returnStr[(curPair * 2)+1] = characters[x2][y2]; } strcpy(destStr, returnStr); return; } void mtxEncryptor::decrypt(char iStr[], char destStr[]) { char* returnStr; int tmpVar = 0; int length = strlen(iStr); //extend string if needed to make it an even # of characters if(length % 2) { returnStr = new char[++length + 1]; strcpy(returnStr, iStr); returnStr[length - 1] = ' '; } else { returnStr = new char[length + 1]; strcpy(returnStr, iStr); } //loop through pairs and encrypt/decrypt for(curPair = 0; curPair < (length >> 1); curPair++) { x1 = xvalue[returnStr[curPair * 2]]; y1 = yvalue[returnStr[curPair * 2]]; x2 = xvalue[returnStr[(curPair * 2)+1]]; y2 = yvalue[returnStr[(curPair * 2)+1]]; if(x1 == x2 && y1 == y2) //same character - flip x and y { x1 = x2 = 16 - x1; y1 = y2 = 16 - y1; } else if(x1 == x2) // same column { y1 = (y1 + 15) % 16; y2 = (y2 + 15) % 16; } else if(y1 == y2) //same row { x1 = (x1 + 15) % 16; x2 = (x2 + 15) % 16; } else { tmpVar = x1; //flip x x1 = x2; x2 = tmpVar; } returnStr[curPair * 2] = characters[x1][y1]; returnStr[(curPair * 2)+1] = characters[x2][y2]; } strcpy(destStr, returnStr); return; } int mtxEncryptor::fencrypt(ifstream &fin, ofstream &fout) { char curStr[256]; char destStr[256]; if(fin && fout) { while(!fin.eof()) { fin.getline(curStr, 256, 0); encrypt(curStr, destStr); fout << destStr; } return 0; } else return 1; } int mtxEncryptor::fdecrypt(ifstream &fin, ofstream &fout) { char curStr[256]; char destStr[256]; if(fin && fout) { while(!fin.eof()) { fin.getline(curStr, 256, 0); decrypt(curStr, destStr); fout << destStr; } return 0; } else return 1; }
[ "jverkoey@gmail.com" ]
jverkoey@gmail.com
4afe7b7cb3bec57966d6f7c9123aea008f61e2f9
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/ds/dns/server/wmi/source/dnscache.cpp
e62245edf2de724d72fcb12ef77f887b045e3843
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
7,023
cpp
///////////////////////////////////////////////////////////////////// // // CopyRight ( c ) 1999 Microsoft Corporation // // Module Name: dnscache.cpp // // Description: // Implementation of CDnscache class // // Author: // Henry Wang ( henrywa ) March 8, 2000 // // ////////////////////////////////////////////////////////////////////// #include "DnsWmi.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDnsBase* CDnsCache::CreateThis( const WCHAR * wszName, //class name CWbemServices * pNamespace, //namespace const char * szType //str type id ) { return new CDnsCache(wszName, pNamespace); } CDnsCache::CDnsCache() { } CDnsCache::CDnsCache( const WCHAR* wszName, CWbemServices *pNamespace) :CDnsBase(wszName, pNamespace) { } CDnsCache::~CDnsCache() { } ///////////////////////////////////////////////////////////////////////////// //++ // // CDnsCache::EnumInstance // // Description: // enum instances of dns cache // // Arguments: // lFlags [IN] WMI flag // pCtx [IN] WMI context // pHandler [IN] WMI sink pointer // // Return Value: // WBEM_S_NO_ERROR // //-- ///////////////////////////////////////////////////////////////////////////// SCODE CDnsCache::EnumInstance( long lFlags, IWbemContext * pCtx, IWbemObjectSink * pHandler ) { CWbemClassObject Inst; m_pClass->SpawnInstance(0,&Inst); CDnsWrap& dns = CDnsWrap::DnsObject(); Inst.SetProperty( dns.GetServerName(), PVD_DOMAIN_SERVER_NAME); Inst.SetProperty( PVD_DNS_CACHE, PVD_DOMAIN_FQDN); Inst.SetProperty( PVD_DNS_CACHE, PVD_DOMAIN_CONTAINER_NAME); pHandler->Indicate(1, &Inst); return WBEM_S_NO_ERROR; } ///////////////////////////////////////////////////////////////////////////// //++ // // CDnsCache::GetObject // // Description: // retrieve cache object based given object path // // Arguments: // ObjectPath [IN] object path to cluster object // lFlags [IN] WMI flag // pCtx [IN] WMI context // pHandler [IN] WMI sink pointer // // Return Value: // WBEM_S_NO_ERROR // //-- ///////////////////////////////////////////////////////////////////////////// SCODE CDnsCache::GetObject( CObjPath & ObjectPath, long lFlags, IWbemContext * pCtx, IWbemObjectSink * pHandler) { CDnsWrap& dns = CDnsWrap::DnsObject(); wstring wstrServer = ObjectPath.GetStringValueForProperty( PVD_DOMAIN_SERVER_NAME); if(WBEM_S_NO_ERROR != dns.ValidateServerName(wstrServer.data())) return WBEM_E_FAILED; wstring wstrContainer = ObjectPath.GetStringValueForProperty( PVD_DOMAIN_CONTAINER_NAME); if(_wcsicmp( wstrContainer.data(), PVD_DNS_CACHE) == 0) { wstring wstrFQDN= ObjectPath.GetStringValueForProperty( PVD_DOMAIN_FQDN); if(_wcsicmp(wstrFQDN.data(), PVD_DNS_CACHE) == 0) { // founded CWbemClassObject Inst; m_pClass->SpawnInstance(0, &Inst); Inst.SetProperty( dns.GetServerName(), PVD_DOMAIN_SERVER_NAME); Inst.SetProperty( PVD_DNS_CACHE, PVD_DOMAIN_FQDN); Inst.SetProperty( PVD_DNS_CACHE, PVD_DOMAIN_CONTAINER_NAME); pHandler->Indicate(1, &Inst); } } return WBEM_S_NO_ERROR; } ///////////////////////////////////////////////////////////////////////////// //++ // // CDnsCache::ExecuteMethod // // Description: // execute methods defined for cache class in the mof // // Arguments: // ObjectPath [IN] object path to cluster object // wzMethodName [IN] name of the method to be invoked // lFlags [IN] WMI flag // pInParams [IN] Input parameters for the method // pHandler [IN] WMI sink pointer // // Return Value: // WBEM_S_NO_ERROR // WBEM_E_INVALID_PARAMETER // //-- ///////////////////////////////////////////////////////////////////////////// SCODE CDnsCache::ExecuteMethod( CObjPath & objPath, WCHAR * wzMethodName, long lFlag, IWbemClassObject * pInArgs, IWbemObjectSink * pHandler) { CDnsWrap& dns = CDnsWrap::DnsObject(); wstring wstrServer = objPath.GetStringValueForProperty( PVD_DOMAIN_SERVER_NAME); if( FAILED ( dns.ValidateServerName(wstrServer.data())) ) return WBEM_E_INVALID_PARAMETER; if(_wcsicmp( wzMethodName, PVD_MTH_CACHE_CLEARDNSSERVERCACHE) == 0) { return dns.dnsClearCache(); } else if(_wcsicmp( wzMethodName, PVD_MTH_ZONE_GETDISTINGUISHEDNAME) == 0) { wstring wstrName; wstring wstrCache = PVD_DNS_CACHE; CWbemClassObject OutParams, OutClass, Class ; HRESULT hr; dns.dnsDsZoneName(wstrName, wstrCache); BSTR ClassName=NULL; ClassName = AllocBstr(PVD_CLASS_CACHE); hr = m_pNamespace->GetObject(ClassName, 0, 0, &Class, NULL); SysFreeString(ClassName); if ( SUCCEEDED ( hr ) ) { Class.GetMethod( wzMethodName, 0, NULL, &OutClass ); OutClass.SpawnInstance(0, &OutParams); OutParams.SetProperty(wstrName, PVD_DNS_RETURN_VALUE); hr = pHandler->Indicate(1, &OutParams); } return hr; } return S_OK; } ///////////////////////////////////////////////////////////////////////////// //++ // // CDnsCache::PutInstance // // Description: // save this instance // // Arguments: // InstToPut [IN] WMI object to be saved // lFlags [IN] WMI flag // pCtx [IN] WMI context // pHandler [IN] WMI sink pointer // // Return Value: // WBEM_E_NOT_SUPPORTED // //-- ///////////////////////////////////////////////////////////////////////////// SCODE CDnsCache::PutInstance( IWbemClassObject * pInst , long lFlags, IWbemContext* pCtx , IWbemObjectSink * pHandler) { return WBEM_E_NOT_SUPPORTED; }; ///////////////////////////////////////////////////////////////////////////// //++ // // CDnsCache::DeleteInstance // // Description: // delete the object specified in rObjPath // // Arguments: // rObjPath [IN] ObjPath for the instance to be deleted // lFlags [IN] WMI flag // pCtx [IN] WMI context // pHandler [IN] WMI sink pointer // // Return Value: // WBEM_E_NOT_SUPPORTED // //-- ///////////////////////////////////////////////////////////////////////////// SCODE CDnsCache::DeleteInstance( CObjPath & ObjectPath, long lFlags, IWbemContext * pCtx, IWbemObjectSink * pResponseHandler) { return WBEM_E_NOT_SUPPORTED; }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
175d380dcd67811626b1386fae3774d2875a3172
b968cc31c461fbca5b44fb408cc5aa9ea31c251f
/wand/wand.ino
3a0d89c8f6f36dddb39198240e334314b8f992b8
[ "MIT" ]
permissive
wermy/dueling_wands
58b06dc3e6d09d71a94bcb32a12bc8861ebb02f9
a279e06e1ef617523075e7c93eba93bd9098be9f
refs/heads/master
2020-07-02T22:06:13.838277
2019-08-10T20:58:34
2019-08-10T20:58:34
201,681,967
2
2
null
null
null
null
UTF-8
C++
false
false
1,736
ino
#include <MPU6050_tockn.h> #include <Wire.h> #include <rf24g.h> // Pin numbers for the LED and switch #define SWITCH_PIN 10 #define LED_PIN 11 // Accelerometer and radio objects MPU6050 mpu6050(Wire); RF24_G radio; // Threshold for how hard someone has to // flick the wand in order to trigger it float ACCEL_THRESHOLD = 2.4; void setup() { Serial.begin(9600); // Initialize the accelerometer Wire.begin(); mpu6050.begin(); // Tell it we don't need the gyro functionality mpu6050.calcGyroOffsets(false); // Set up the radio, tell it which pins we're using radio = RF24_G(4, 7, 9); // Set up the switch and LED pins pinMode(SWITCH_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); } // Sends whichever wand number the switch is set to // to the base station void sendFlick() { uint8_t wandNum = 1; if (digitalRead(SWITCH_PIN) == LOW) { wandNum = 2; } packet sender; sender.setAddress(1); sender.addPayload(&wandNum, sizeof(uint8_t)); if (radio.write(&sender) == true) { Serial.println("Sent flick."); } } // Set the LED to full brightness, then fade out void doFlash() { int brightness = 255; while (brightness >= 0) { analogWrite(LED_PIN, brightness); brightness -= 1; delay(2); } } void loop() { // Update the accelerometer mpu6050.update(); // Calculate the magnitude of the acceleration // in the y and z axes float accelY = mpu6050.getAccY(); float accelZ = mpu6050.getAccZ(); float accel = sqrt((accelY*accelY) + (accelZ*accelZ)); // If that's above our threshold, send flick and flash the LED if (accel >= ACCEL_THRESHOLD) { Serial.print("accel: ");Serial.println(accel); sendFlick(); doFlash(); delay(1000); } }
[ "skochw@gmail.com" ]
skochw@gmail.com
e06f23eb31562e41d9084d650ff58fce7a2e03be
ede02df49029bcff09fcc67dea5189d2daf2343c
/indri/branches/indri-pre-concurrency/include/indri/NumericFieldAnnotator.hpp
51c640beba57cf61764343bfeb97a4393beafc91
[ "BSD-2-Clause" ]
permissive
aenoskov/RankLib
67465b5b27004e1abe2bde8adf2b46fa82986657
00c4b6fb835451041cb6c8947d884bd5b34eab75
refs/heads/master
2021-07-17T12:24:21.294554
2017-01-04T21:11:02
2017-01-04T21:11:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
hpp
/*========================================================================== * Copyright (c) 2003-2004 University of Massachusetts. All Rights Reserved. * * Use of the Lemur Toolkit for Language Modeling and Information Retrieval * is subject to the terms of the software license set forth in the LICENSE * file included with this software, and also available at * http://www.lemurproject.org/license.html * *========================================================================== */ // // NumericFieldAnnotator // // 25 May 2004 -- tds // #ifndef INDRI_NUMERICFIELDANNOTATOR_HPP #define INDRI_NUMERICFIELDANNOTATOR_HPP class NumericFieldAnnotator : public Transformation { private: ObjectHandler<ParsedDocument>* _handler; std::string& _field; public: NumericFieldAnnotator( std::string& field ) : _handler(0), _field(field) { } ParsedDocument* transform( ParsedDocument* document ) { for( size_t i=0; i<document->tags.size(); i++ ) { TagExtent& extent = document->tags[i]; if( _field == extent.name ) { char* numberText = document->terms[ extent.begin ]; INT64 value = string_to_i64( numberText ); extent.number = value; } } return document; } void setHandler( ObjectHandler<ParsedDocument>& handler ) { _handler = &handler; } void handle( ParsedDocument* document ) { _handler->handle( transform( document ) ); } }; #endif // INDRI_NUMERICFIELDANNOTATOR_HPP
[ "dfisher@14020d50-3050-45fe-8e0c-5ed7005ca764" ]
dfisher@14020d50-3050-45fe-8e0c-5ed7005ca764
46d23477d7f1bbc138efcdecc2975ffbb44209ce
7d814cf427952e2c81e0768a7c36b15c5af21262
/kernel/algorithms/reductcostfilter.cpp
1e81015b040f47d4da3755d432f879bb21f97eda
[]
no_license
komorowskilab/Parallel-ROSETTA
e2b9ee90a4bbe4f79546026e9d00abcc38ae3f5d
60112009f4cc29f943e37d0fda86d1b28344fd3c
refs/heads/master
2020-08-18T05:18:18.000368
2019-10-22T13:12:53
2019-10-22T13:12:53
215,751,254
2
1
null
null
null
null
WINDOWS-1252
C++
false
false
11,780
cpp
//------------------------------------------------------------------- // Author........: Aleksander šhrn // Date..........: // Description...: // Revisions.....: //=================================================================== #include <stdafx.h> // Precompiled headers. #include <copyright.h> #include <kernel/algorithms/reductcostfilter.h> #include <kernel/algorithms/keyword.h> #include <kernel/structures/reduct.h> #include <kernel/structures/reducts.h> #include <kernel/structures/decisiontable.h> #include <kernel/utilities/iokit.h> #include <kernel/utilities/mathkit.h> #include <kernel/basic/algorithm.h> #include <kernel/basic/message.h> #include <kernel/system/fstream.h> //------------------------------------------------------------------- // Methods for class ReductCostFilter. //=================================================================== //------------------------------------------------------------------- // Constructors/destructor. //=================================================================== ReductCostFilter::ReductCostFilter() { SetCostFilename(Undefined::String()); SetThreshold(100.0); SetDefaultCost(0.0); SetLogFilename(Undefined::String()); } ReductCostFilter::~ReductCostFilter() { } //------------------------------------------------------------------- // Methods inherited from Identifier. //=================================================================== IMPLEMENTIDMETHODS(ReductCostFilter, REDUCTCOSTFILTER, ReductFilter) //------------------------------------------------------------------- // Methods inherited from Algorithm. //=================================================================== //------------------------------------------------------------------- // Method........: GetParameters // Author........: Aleksander šhrn // Date..........: // Description...: // Comments......: // Revisions.....: //=================================================================== String ReductCostFilter::GetParameters() const { String parameters; // Cost, filename. parameters += Keyword::Cost() + Keyword::Dot() + Keyword::Filename(); parameters += Keyword::Assignment(); parameters += GetCostFilename(); parameters += Keyword::Separator(); // Default. parameters += Keyword::Default(); parameters += Keyword::Assignment(); parameters += String::Format(GetDefaultCost()); parameters += Keyword::Separator(); // Threshold. parameters += Keyword::Threshold(); parameters += Keyword::Assignment(); parameters += String::Format(GetThreshold()); parameters += Keyword::Separator(); // Log, filename. parameters += Keyword::Log() + Keyword::Dot() + Keyword::Filename(); parameters += Keyword::Assignment(); parameters += GetLogFilename(); parameters += Keyword::Separator(); return parameters + ReductFilter::GetParameters(); } //------------------------------------------------------------------- // Method........: SetParameter // Author........: Aleksander šhrn // Date..........: // Description...: // Comments......: // Revisions.....: //=================================================================== bool ReductCostFilter::SetParameter(const String &keyword, const String &value) { // Cost, filename, if (keyword == Keyword::Cost() + Keyword::Dot() + Keyword::Filename()) return SetCostFilename(value); // Cost, filename (for backwards compatibility). if (keyword == Keyword::Filename()) return SetCostFilename(value); // Threshold. if (keyword == Keyword::Threshold() && value.IsFloat()) return SetThreshold(value.GetFloat()); // Default. if (keyword == Keyword::Default() && value.IsFloat()) return SetDefaultCost(value.GetFloat()); // Log, filename, if (keyword == Keyword::Log() + Keyword::Dot() + Keyword::Filename()) return SetLogFilename(value); return ReductFilter::SetParameter(keyword, value); } //------------------------------------------------------------------- // Method........: GetOutputFilenames // Author........: Aleksander šhrn // Date..........: // Description...: // Comments......: // Revisions.....: //=================================================================== bool ReductCostFilter::GetOutputFilenames(Vector(String) &filenames) const { if (!Algorithm::GetOutputFilenames(filenames)) return false; filenames.push_back(GetLogFilename()); return true; } //------------------------------------------------------------------- // Method........: Apply // Author........: Aleksander šhrn // Date..........: // Description...: // Comments......: // Revisions.....: //=================================================================== Structure * ReductCostFilter::Apply(Structure &structure) const { // This method is conceptually const only. ReductCostFilter *self = const_cast(ReductCostFilter *, this); Handle<DecisionTable> table = dynamic_cast(DecisionTable *, structure.FindParent(DECISIONTABLE)); // Load cost information. if (!self->costs_.Load(GetCostFilename(), *table, GetDefaultCost())) { Message::Error("Failed to load cost information."); return NULL; } // Erase mutable bookkeeping stuff. (self->statistics_).erase((self->statistics_).begin(), (self->statistics_).end()); (self->rankings_).erase((self->rankings_).begin(), (self->rankings_).end()); (self->reducts_).erase((self->reducts_).begin(), (self->reducts_).end()); (self->statistics_).reserve(structure.GetNoStructures()); (self->rankings_).reserve(structure.GetNoStructures()); (self->reducts_).reserve(structure.GetNoStructures()); // Do the filtering. Handle<Structure> result = Filter::Apply(structure); // Save log, calculate and print statistics. if (!self->SaveLog(*table)) Message::Warning("Failed to save log file."); // Clean up in general. (self->statistics_).erase((self->statistics_).begin(), (self->statistics_).end()); (self->rankings_).erase((self->rankings_).begin(), (self->rankings_).end()); (self->reducts_).erase((self->reducts_).begin(), (self->reducts_).end()); return result.Release(); } //------------------------------------------------------------------- // Methods inherited from Filter. //=================================================================== //------------------------------------------------------------------- // Method........: Remove // Author........: Aleksander šhrn // Date..........: // Description...: Returns true if the specified reduct should be removed // from the reduct set. // Comments......: // Revisions.....: //=================================================================== bool ReductCostFilter::Remove(const Structures &structures, int i) const { if (!structures.IsA(REDUCTS)) return false; Handle<Reducts> reducts = dynamic_cast(Reducts *, const_cast(Structures *, &structures)); Handle<Reduct> reduct = reducts->GetReduct(i); // Compute total cost. float cost = costs_.GetCost(*reduct); String formatted; bool masked = true; // Format reduct. if (!reduct->Format(formatted, dynamic_cast(DecisionTable *, reducts->FindParent(DECISIONTABLE)), masked)) formatted = Undefined::String(); // Update bookkeeping structures. ReductCostFilter *self = const_cast(ReductCostFilter *, this); // Update bookkeeping structures. (self->statistics_).push_back(cost); (self->rankings_).push_back(std::make_pair(i, cost)); (self->reducts_).push_back(ISPair(i, formatted) /* std::make_pair(i, formatted) */); // Return removal decision. return (cost > GetThreshold()); } //------------------------------------------------------------------- // Local methods. //=================================================================== //------------------------------------------------------------------- // Method........: SaveLog // Author........: Aleksander šhrn // Date..........: // Description...: // Comments......: // Revisions.....: //=================================================================== bool ReductCostFilter::SaveLog(const DecisionTable &table) const { // Compute statistics. float mean = MathKit::Mean(statistics_); float median = MathKit::Median(statistics_); float stddev = MathKit::StandardDeviation(statistics_); float minimum = MathKit::Minimum(statistics_); float maximum = MathKit::Maximum(statistics_); Message message; // Output to user. message.Notify("Cost.Mean = " + (mean == Undefined::Float() ? Undefined::String() : String::Format(mean))); message.Notify("Cost.Median = " + (median == Undefined::Float() ? Undefined::String() : String::Format(median))); message.Notify("Cost.StdDev = " + (stddev == Undefined::Float() ? Undefined::String() : String::Format(stddev))); message.Notify("Cost.Minimum = " + (minimum == Undefined::Float() ? Undefined::String() : String::Format(minimum))); message.Notify("Cost.Maximum = " + (maximum == Undefined::Float() ? Undefined::String() : String::Format(maximum))); ofstream stream; if (!IOKit::Open(stream, GetLogFilename())) { Message::Error("Failed to open " + GetLogFilename() + "."); return false; } bool masked = true; // Save log header. stream << "% Output from ROSETTA, " + SystemKit::GetUser() + " " + SystemKit::GetTimestamp() << endl; stream << "%" << endl; stream << "% " + IdHolder::GetClassname(GetId()) << endl; stream << "% {" + GetParameters() + "}" << endl; stream << "%" << endl; stream << "% Note that the indices below are 0-based." << endl; stream << "%" << endl; int i, longest = 0; for (i = 0; i < table.GetNoAttributes(masked); i++) { /* if (costs_.GetCost(i) == GetDefaultCost()) continue; */ String name = table.GetAttributeName(i, masked); if (name.GetLength() > longest) longest = name.GetLength(); } for (i = 0; i < table.GetNoAttributes(masked); i++) { /* if (costs_.GetCost(i) == GetDefaultCost()) continue; */ String name = table.GetAttributeName(i, masked); name = "Cost(" + name + ")"; name.Pad(' ', longest + 6); stream << "% " << name << " = " << costs_.GetCost(i) << endl; } stream << endl; // Save cost statistics. stream << "Cost.Mean = " << (mean == Undefined::Float() ? Undefined::String() : String::Format(mean)) << endl; stream << "Cost.Median = " << (median == Undefined::Float() ? Undefined::String() : String::Format(median)) << endl; stream << "Cost.StdDev = " << (stddev == Undefined::Float() ? Undefined::String() : String::Format(stddev)) << endl; stream << "Cost.Minimum = " << (minimum == Undefined::Float() ? Undefined::String() : String::Format(minimum)) << endl; stream << "Cost.Maximum = " << (maximum == Undefined::Float() ? Undefined::String() : String::Format(maximum)) << endl << endl; // We need to update (sort) the mutable bookkeeping stuff. ReductCostFilter *self = const_cast(ReductCostFilter *, this); IFPairCompareSecondDescending comparator1; ISPairCompareFirstAscending comparator2; message.Notify("Sorting costs..."); // Sort rankings and formatted reducts. std::sort((self->rankings_).begin(), (self->rankings_).end(), comparator1); std::sort((self->reducts_).begin(), (self->reducts_).end(), comparator2); message.Notify("Saving costs to log..."); // Save rankings. for (i = 0; i < rankings_.size(); i++) { int index = rankings_[i].first; float value = rankings_[i].second; String formatted_i; String formatted_v; String formatted_r; // Format output. formatted_i = "Reduct #" + String::Format(index); formatted_v = (value == Undefined::Float()) ? Undefined::String() : String::Format(value); formatted_v.Pad(' ', 11); formatted_r = reducts_[index].second; // Save to stream. stream << formatted_v << formatted_i << " = " << formatted_r << endl; } return true; } ReductCostFilter * ReductCostFilter::Clone() { return new ReductCostFilter; }
[ "Komorowskilab@gmail.com" ]
Komorowskilab@gmail.com
03dcb609f1c0ae6cd9b077a80535088c702808fd
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/filesystems/fuse-encfs/patches/patch-encfs_DirNode.cpp
b5b65057d77adec543e71a49a96855eb72e88b79
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C++
false
false
798
cpp
$NetBSD: patch-encfs_DirNode.cpp,v 1.1 2017/06/19 18:41:39 maya Exp $ Define _DIRENT_HAVE_D_TYPE at the top for all the OSes that support it. This is an untested functional change for FreeBSD and APPLE. --- encfs/DirNode.cpp.orig 2016-09-18 20:16:04.000000000 +0000 +++ encfs/DirNode.cpp @@ -42,6 +42,10 @@ #include "Error.h" #include "Mutex.h" +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__) +#define _DIRENT_HAVE_D_TYPE +#endif + using namespace std; namespace encfs { @@ -78,7 +82,7 @@ static bool _nextName(struct dirent *&de if (de) { if (fileType) { -#if defined(_DIRENT_HAVE_D_TYPE) || defined(__FreeBSD__) || defined(__APPLE__) +#if defined(_DIRENT_HAVE_D_TYPE) *fileType = de->d_type; #else #warning "struct dirent.d_type not supported"
[ "maya" ]
maya
88f13116e836ebfca908f8186afd4335ccf9b806
218e9672717740359c757e56bb05c616fb3fac62
/source/response.h
6c1951adea846491229c5b140e6dfab020be5e91
[]
no_license
extratorsion/HttpServer
8bc7bf0f5271491916e858b70e1d37708cd24370
0e1115fa637c0f0926cf861a498c9ada382e37e4
refs/heads/master
2020-05-04T09:13:10.764961
2019-04-11T11:52:30
2019-04-11T11:52:30
179,063,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,402
h
#ifndef RESPONSE_H #define RESPONSE_H #include "common_includes.h" #include "request.h" #define GBUF_SIZE 102400 class Response { public: static HashMap<int, String> statusMap; static HashMap<String, String> typeMap; static char* gbuf; static String makeResponse(const String& status, const std::vector<std::pair<String, String>>& key_value, const String& content); static String makeResponse(const String& status, const HashMap<String, String>& key_value, const String& content); static String makeResponse(int statusCode, const std::vector<std::pair<String, String>>& key_value, const String& content); static String makeResponse(int statusCode, const HashMap<String, String>& key_value, const String& content); static String makeResponseHeader(int statusCode, const HashMap<String, String>& key_value); static size_t getFileSize(const String& path); static String getContentType(const String& path); static void sendFileEntity(const String& path, int fd); static void ProcessResponse(const String& request, int fd); public: enum class ResponseType {File, Content}; public: String responseHeader_; String responseBody_; String filename_; ResponseType responseType_; int fd_; Response(const Request& req, int fd); void reply(); void replyFile(); void replyContent(); }; #endif // RESPONSE_H
[ "extratorsion@outlook.com" ]
extratorsion@outlook.com
2e509887d38bb64abf73cf32fe98bb6e66d2ad35
078a75babf7a54138a09d0d3ee8e8e20242028a6
/cn/C++/question/___Offer_47_________LCOF.cpp
181b1ebf5943ec3ad699ffe83dc9217c15c743a2
[]
no_license
FuChaolei/algorithm_ago
142e3772212342279187a763a6880612317cf1d1
b8806e2b06fea14e384fe996bca8771ca4574127
refs/heads/main
2023-07-30T15:10:02.803531
2021-09-23T15:17:26
2021-09-23T15:17:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
// @algorithm @lc id=100327 lang=cpp // @title li-wu-de-zui-da-jie-zhi-lcof #include <bits/stdc++.h> #include <iostream> #include <vector> #include <string> #include "algm/algm.h" using namespace std; // @test([[1,2,5],[3,2,1]])=9 class Solution { public: int maxValue(vector<vector<int>> &grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> ans(m + 1, vector<int>(n + 1)); for (int i = 1; i < m + 1; i++) { for (int j = 1; j < n + 1; j++) { ans[i][j] = max(ans[i - 1][j], ans[i][j - 1]) + grid[i - 1][j - 1]; } } return ans[m][n]; } };
[ "1310866178@qq.com" ]
1310866178@qq.com
a1458f3cf7ef2cabb40d94b7718b4d1a04c8350c
94050cb7630e73ef6e3b2e45ede8a57dcd4c0a42
/lightPosition.cpp
76a88d0d19af563ebf7a830bcd5a43cd5f780104
[]
no_license
marcclintdion/_VBO_A4_00
1131b6113724d43d46f3abff9da22faa5cbe42a4
ecda8fa9288d13aa4b2b96cb325ca83defe5a45b
refs/heads/master
2021-01-25T07:34:57.743632
2015-09-17T09:57:40
2015-09-17T09:57:40
42,648,615
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
GLfloat lightPos_legBone[] = {-43.215, 252.76, -184.415}; GLfloat quadraticAttenuation_legBone = 2.1; look_LEFT_RIGHT = 0.899993; look_UP_DOWN = 52.2999; eyePosition[0] = 0.02; eyePosition[1] = -0.22; eyePosition[2] = -3.21001; GLfloat mainPositionX = 0.28; GLfloat mainPositionZ = 0.27;
[ "marcclintdion@Marcs-iMac.local" ]
marcclintdion@Marcs-iMac.local
f7e21fd089077a6ebffbfe8c3c86f4ebf4e124ff
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/54/664.c
f366ca07a6f051875c4c8b503d0950645d3be203
[]
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
350
c
void main() { double final(int n,int k,int n1,int p); int n,k,n1,i; double m; scanf("%d %d",&n,&k); n1=n; for(i=1;;i++) { m=final(n+1,k,n1,(n1-1)*i); if(m-(int)m==0) break; } printf("%.0f\n",m); } double final(int n,int k,int n1,int p) { double x; if(n==1) x=p; else x=final(n-1,k,n1,p)*n1/(n1-1)+k; return x; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
3c7ebc40d392a4f41a132946173bc02979e574de
c9a56654744b48b83ad052b86d811094044b3c69
/Algorithm/NewTrack/include/struRoadDet.h
d016b9ff9e56cfb0012ae02e01b6fcd981601364
[]
no_license
zhuhaijun753/bocomSrc
6c1f3a9ffefb6bf605b4c30bba184bb2719d98a7
5ea248f2da29e7932d2c8b8034d9ed08499ea513
refs/heads/master
2022-04-28T09:35:27.320694
2020-04-27T04:32:56
2020-04-27T04:32:56
259,205,543
0
0
null
2020-04-27T04:32:14
2020-04-27T04:32:13
null
UTF-8
C++
false
false
5,214
h
//智能交通的结构体-用于代码管理和简化 #ifndef _STRU_ROAD_DET_H_ #define _STRU_ROAD_DET_H_ #include <stdio.h> #include <stdlib.h> #include <fstream> #include <iostream> #include "libHeader.h" #include "comHeader.h" #include "BaseStruct.h" #include "MvLineSegment.h" enum ENUM_AN_EVENT_ALERT_TYPE { AN_OBJAPPEAR_ALERT = 0, //目标出现 AN_AGAINST_ALERT, //逆行 AN_CROSS_ALERT, //横穿 AN_CHANNEL_CHANGE_ALERT, //变道 AN_STOP_ALERT //停止 }; //线段结构体 typedef struct BGLineElem { BLine line; bool is_bg; double ts_first;//时间戳,秒 double ts_now;//时间戳,秒 int occur_times; }BGLineElem; //事件所用的maxisze图像集合结构体 //(这些图像的大小均一致) typedef struct _EventMaxsizeImgSet { public: CvSize sz; //图像的大小 IplImage *max_size; //maxsize直径图 IplImage *max_sizex; //车的maxsize的x直径图 IplImage *max_sizey; //车的maxsize的y直径图 IplImage *max_sizex45; //车的maxsize的x直径旋转45°图 IplImage *max_sizey45; //车的maxsize的y直径旋转45°图 IplImage *m_pCarMaxSizeXImg; //车的宽 IplImage *m_pCarMaxSizeYImg; //车的高 IplImage *m_pPeoMaxSizeXImg; //行人的宽 IplImage *m_pPeoMaxSizeYImg; //行人的高 public: _EventMaxsizeImgSet( ); void initVar( ); void mvSetImgWH( int nW, int nH ); bool createImages( ); void releaseImgSet( ); }EventMaxsizeImgSet; //事件所用的cvSet集合 typedef struct _EventUseCvSetSeq { public: CvMemStorage *pMemStorage; CvSet *pTrackSet; CvSet *pObjResultSet; CvSet *pObjHistorySet; CvSeq *pBgLineSeq; public: void initVar( ); void createSet( ); void relesaeSet( ); }EventUseCvSetSeq; //事件所用的cvSet集合 typedef struct _EventUseCvSetSeq2 { public: CvMemStorage *pMemStorage; CvSet *pTrackSet; CvSet *pObjResultSet; CvSet *pObjHistorySet; CvSet *pCarNumSet; CvSeq *pBgLineSeq; public: void initVar( ); void createSet( ); void relesaeSet( ); }EventUseCvSetSeq2; //调试控制结构体 #ifndef EVENT_COFING_LINE #define EVENT_COFING_LINE enum { EVENTCFG_YELLOW_LINE = 0, EVENTCFG_LEADSTREAM_LINE }; #endif //EventStruConfigLine:config line struct for event detect typedef struct EventStruConfigLine { public: //get the give mode config line bool mvGetConfigLinesOfChannel( int nChannelCnt, //number of channels VEHICLE_PARAM *pParamChan, //pointer of channels int nGetLineMod, //need get line's mode vector<int> &vecPtCnt, //point number of line vector<CvPoint *> &vecPtPointer //point address of line ); private: //将链表中的点转为数组中的点,便于使用 CvPoint* mvPtListToPoint( PointList vPlist, int &nPtCnt ); }struConfigLine; //时间报警处理结构体 typedef struct EventAlertProcess { public: EventAlertProcess( ) { initVar( ); } void initVar( ) { m_nShowTime = 3; //同一事件的显示时间 m_nSameEventIgn = 0; //同类事件忽略检测的时间 } //处理已经报警过的目标 bool mvProcAlertedObj( MyGroup &obj, int nAlertMod, float fDuration ); private: int m_nShowTime; //同一事件的显示时间 int m_nSameEventIgn; //同类事件忽略检测的时间 }StruEventAlertProc; //目标检测所得到的停止区域信息 typedef struct _StruObjStopAreaInfo { bool bChannelIsJam; //目标所在的车道是否拥堵 int nObjType; //目标类型 int nTrCnt; //轨迹数目(包含估计的) CvPoint2D32f fptObjLt; //目标的左上点 CvPoint2D32f fptObjRb; //目标的右下点 CvPoint2D32f fptStopAreaLt; //停止区域的左上点 CvPoint2D32f fptStopAreaRb; //停止区域的右下点 double dTsStop; //发现停下来的时间戳 double dAlertTime; //报警时间要求 _StruObjStopAreaInfo( ) { bChannelIsJam = false; nObjType = 0; nTrCnt = 0; dTsStop = -10000.0; dAlertTime = -10000.0; } }StruObjStopAreaInfo; //前段时间内的多次检测/统计结果的存储 typedef struct StruDetStaResStore { public: StruDetStaResStore( ); ~StruDetStaResStore( ); //初始化 void mvInitDetStaResStore( int nMaxSaveTime, //最多存储的结果次数 int nOneTimeSaveCnt //一次存储多少个数据 ); //释放 void mvUninitDetStaResStore( ); //添加一元素 bool mvAddOneElement( double dTsNow, //当前时间戳 int nDataDim, //要加入数据的维数 double *dAData //要加入的数据 ); //搜索距今时间差为给定值之内的所保存的元素值 double** mvSearchInPreTimeElement( int &nSearchCnt, //搜索到的数据记录条数 int &nDim, //搜索到的数据的维数 double dTsNow, //当前时间戳 double dPreTime, //往前搜索的时间 bool bReturnData = true //是否需返回数据 ); private: //初始化变量 void mvInitVar( ); private: bool m_bInit; //是否进行过初始化 int m_nMaxSaveTime; //最多存储的结果次数 int m_nOneTimeSaveCnt; //一次存储多少个数据 CycleReplace m_CR; //循环覆盖体 double **m_ppData; //存储的数据 }AnDetStaResStore; #endif
[ "545474968@qq.com" ]
545474968@qq.com
aa6ffadbbfc39d6e28f5172ef2868bfae745175b
1c444bdf16632d78a3801a7fe6b35c054c4cddde
/include/bds/bedrock/scripting/event/data/ScriptEventData.h
be1008aa3458261fd385a516470b6b1f8d892071
[]
no_license
maksym-pasichnyk/symbols
962a082bf6a692563402c87eb25e268e7e712c25
7673aa52391ce93540f0e65081f16cd11c2aa606
refs/heads/master
2022-04-11T03:17:18.078103
2020-03-15T11:30:36
2020-03-15T11:30:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
500
h
#pragma once #include <string> class ScriptEventData { public: ~ScriptEventData(); // _ZN15ScriptEventDataD2Ev ScriptEventData(std::string const&); // _ZN15ScriptEventDataC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE void serialize(ScriptEngine &, EventInfo &, ScriptApi::ScriptObjectHandle &)const; // _ZNK15ScriptEventData9serializeER12ScriptEngineR9EventInfoRN9ScriptApi18ScriptObjectHandleE std::string getName()const; // _ZNK15ScriptEventData7getNameB5cxx11Ev };
[ "honzaxp01@gmail.com" ]
honzaxp01@gmail.com
f56556a4c5c6e11b0b5922f01a1123e2ad5923fc
214020d657b841826087d63d22bc110cd1a0d246
/main.cpp
681bfaf79c3a21f80d8c580df8712c0b84d57714
[]
no_license
JaxLabs/TowerOfHanoiFinal
fcd14400b2d5bd9e1b227da3d310efbe8294710c
4454184a96c3970824c42c0d0bf92700cd739284
refs/heads/master
2023-06-21T04:49:45.463714
2021-08-01T16:27:10
2021-08-01T16:27:10
391,679,243
1
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include <iostream> #include <SFML/Graphics.hpp> #include "MainGameRunning.h" int main() { MainGameRunning game; game.run(); return 0; }
[ "jacquelyneleanorpowell@gmail.com" ]
jacquelyneleanorpowell@gmail.com
3dfd03f96e1019934fb542400a3a67d2fdf305e3
2b58e40a1a6528f344afcbbde571d8418649df03
/EEar/soft/dev/client/pin.cpp
489ee00492616f38d54325e4fd42187a67b0b659
[]
no_license
truthear/ear
8d4a433dec33bcd114df7f17ad504312f7027090
0a5db5be7a458d4d5375866fc6cc1d4b0d5e534d
refs/heads/master
2021-01-13T15:11:14.643405
2019-01-03T12:27:16
2019-01-03T12:27:16
76,236,360
0
1
null
null
null
null
UTF-8
C++
false
false
6,326
cpp
#include "include.h" CPin::TCBPARM CPin::cb_list[16] = {{NULL,NULL},}; void CPin::ExecuteCallback(int idx) { if ( idx >= 0 && idx <= 15 ) { if ( cb_list[idx].cb ) { cb_list[idx].cb(cb_list[idx].cb_parm); } } } GPIO_TypeDef* CPin::GetPort(EPins pin) { GPIO_TypeDef* rc = NULL; switch ( (int)pin/16 ) { case 0: rc = GPIOA; break; case 1: rc = GPIOB; break; case 2: rc = GPIOC; break; case 3: rc = GPIOD; break; case 4: rc = GPIOE; break; }; return rc; } uint32_t CPin::GetAHB1Periph(EPins pin) { uint32_t rc = 0xFFFFFFFF; switch ( (int)pin/16 ) { case 0: rc = RCC_AHB1Periph_GPIOA; break; case 1: rc = RCC_AHB1Periph_GPIOB; break; case 2: rc = RCC_AHB1Periph_GPIOC; break; case 3: rc = RCC_AHB1Periph_GPIOD; break; case 4: rc = RCC_AHB1Periph_GPIOE; break; }; return rc; } uint32_t CPin::GetPinIndex(EPins pin) { return 1 << ((uint32_t)pin % 16); } uint8_t CPin::GetPinSource(EPins pin) { return (uint8_t)((uint32_t)pin % 16); } void CPin::EnablePower(EPins pin) { RCC_AHB1PeriphClockCmd(GetAHB1Periph(pin), ENABLE); } void CPin::InitAsInput(EPins pin,GPIOPuPd_TypeDef pupd) { if ( pin != NC_PIN ) { EnablePower(pin); GPIO_InitTypeDef i; i.GPIO_Pin = GetPinIndex(pin); i.GPIO_Mode = GPIO_Mode_IN; i.GPIO_Speed = GPIO_Fast_Speed; i.GPIO_OType = GPIO_OType_PP; i.GPIO_PuPd = pupd; GPIO_Init(GetPort(pin),&i); } } void CPin::InitAsOutput(EPins pin,int init_value,GPIOPuPd_TypeDef pupd,GPIOOType_TypeDef otype,GPIOSpeed_TypeDef speed) { if ( pin != NC_PIN ) { EnablePower(pin); GPIO_InitTypeDef i; i.GPIO_Pin = GetPinIndex(pin); i.GPIO_Mode = GPIO_Mode_OUT; i.GPIO_Speed = speed; i.GPIO_OType = otype; i.GPIO_PuPd = pupd; SetValue(pin,init_value); GPIO_Init(GetPort(pin),&i); SetValue(pin,init_value); } } void CPin::InitAsAF(EPins pin,uint8_t af,GPIOPuPd_TypeDef pupd,GPIOOType_TypeDef otype,GPIOSpeed_TypeDef speed) { if ( pin != NC_PIN ) { EnablePower(pin); GPIO_InitTypeDef i; i.GPIO_Pin = GetPinIndex(pin); i.GPIO_Mode = GPIO_Mode_AF; i.GPIO_Speed = speed; i.GPIO_OType = otype; i.GPIO_PuPd = pupd; GPIO_Init(GetPort(pin),&i); GPIO_PinAFConfig(GetPort(pin),GetPinSource(pin),af); } } void CPin::InitAsAnalog(EPins pin) { if ( pin != NC_PIN ) { EnablePower(pin); GPIO_InitTypeDef i; i.GPIO_Pin = GetPinIndex(pin); i.GPIO_Mode = GPIO_Mode_AN; GPIO_Init(GetPort(pin),&i); } } void CPin::Set(EPins pin) { if ( pin != NC_PIN ) { GPIO_SetBits(GetPort(pin),GetPinIndex(pin)); } } void CPin::Reset(EPins pin) { if ( pin != NC_PIN ) { GPIO_ResetBits(GetPort(pin),GetPinIndex(pin)); } } void CPin::Toggle(EPins pin) { if ( pin != NC_PIN ) { GPIO_ToggleBits(GetPort(pin),GetPinIndex(pin)); } } void CPin::SetValue(EPins pin,int value) { if ( pin != NC_PIN ) { if ( value ) { Set(pin); } else { Reset(pin); } } } int CPin::GetValue(EPins pin) { return pin != NC_PIN ? GPIO_ReadInputDataBit(GetPort(pin),GetPinIndex(pin)) : 0; } void CPin::SetInterrupt(EPins pin,TCALLBACK cb,void *cb_parm,EXTITrigger_TypeDef trigger,uint8_t priority) { if ( pin != NC_PIN ) { cb_list[GetPinSource(pin)].cb = cb; cb_list[GetPinSource(pin)].cb_parm = cb_parm; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG,ENABLE); SYSCFG_EXTILineConfig((uint32_t)pin/16,GetPinSource(pin)); EXTI_InitTypeDef EXTI_InitStructure; EXTI_InitStructure.EXTI_Line = GetPinIndex(pin); EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = trigger; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); uint8_t irqch = 0xFF; switch ( GetPinSource(pin) ) { case 0: irqch = EXTI0_IRQn; break; case 1: irqch = EXTI1_IRQn; break; case 2: irqch = EXTI2_IRQn; break; case 3: irqch = EXTI3_IRQn; break; case 4: irqch = EXTI4_IRQn; break; case 5: case 6: case 7: case 8: case 9: irqch = EXTI9_5_IRQn; break; case 10: case 11: case 12: case 13: case 14: case 15: irqch = EXTI15_10_IRQn; break; }; NVIC_InitTypeDef NVIC_InitStructure; NVIC_InitStructure.NVIC_IRQChannel = irqch; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = priority; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } } class CEXTIHandler { public: static void OnIRQ(int i_from,int i_to); }; void CEXTIHandler::OnIRQ(int i_from,int i_to) { for ( int n = i_from; n <= i_to; n++ ) { uint32_t line = (1 << n); if ( EXTI_GetITStatus(line) != RESET ) { EXTI_ClearITPendingBit(line); CPin::ExecuteCallback(n); } } } extern "C" void EXTI0_IRQHandler() { CEXTIHandler::OnIRQ(0,0); } extern "C" void EXTI1_IRQHandler() { CEXTIHandler::OnIRQ(1,1); } extern "C" void EXTI2_IRQHandler() { CEXTIHandler::OnIRQ(2,2); } extern "C" void EXTI3_IRQHandler() { CEXTIHandler::OnIRQ(3,3); } extern "C" void EXTI4_IRQHandler() { CEXTIHandler::OnIRQ(4,4); } extern "C" void EXTI9_5_IRQHandler() { CEXTIHandler::OnIRQ(5,9); } extern "C" void EXTI15_10_IRQHandler() { CEXTIHandler::OnIRQ(10,15); }
[ "sergey2010@victorovich.com" ]
sergey2010@victorovich.com
7da142a9d068ca612370d313eb2667f3e23ee4e3
f38ed041b5f1935fbb7ba67ab81ad952fbe002be
/cgi/incus/cppbeg/ndebug/src/main.cpp
9b266939f97af8adfcdd7e9c026c9a6db9df35c7
[]
no_license
skullquake/IncusDataCCourse
2612d8c72c6455e96ecbce7f69631d1cb3e1ebd9
8f61b71478519955cbe3218283699f8aaf7a37da
refs/heads/master
2022-11-18T17:44:26.841234
2020-07-11T08:50:16
2020-07-11T08:50:16
274,480,730
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
/*!@file: ./src/main.c * @brief: `NDEBUG`, for statements that should compile when doing debug compile */ #include<iostream> #include"mycpplib.h" extern "C" { #include"myclib.h" } int main(int argc,char**argv){ std::cout<<"Content-Type: text/plain"<<std::endl<<std::endl; //for this to execute, compile without -DNDEBUG, you can edit the makefile for //this, and should in fact have a release and debug target in your makefile #ifndef NDEBUG std::cerr<<"Only when debugging"<<std::endl; #endif return 0; }
[ "ockert8080@gmail.com" ]
ockert8080@gmail.com
e1439df301d7daedb67edc1200bb274a8d4b1d10
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14175/function14175_schedule_40/function14175_schedule_40.cpp
e71f4bd2c2d8c486916edf53a7e71e8a4943555a
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14175_schedule_40"); constant c0("c0", 128), c1("c1", 256), c2("c2", 1024); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); computation comp0("comp0", {i0, i1, i2}, 7 - 2); comp0.tile(i0, i1, i2, 128, 64, 64, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf0("buf0", {128, 256, 1024}, p_int32, a_output); comp0.store_in(&buf0); tiramisu::codegen({&buf0}, "../data/programs/function14175/function14175_schedule_40/function14175_schedule_40.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
ce5b6c5f1378b23c8c7c2ba5db0aa4aff1b676ca
361749f54e08f27da481610fa537f6bb7c91b45c
/function.cpp
5e707f6c7a92ec80a8e0e3c952558dddf5b5e3ba
[]
no_license
chainsawriot/cpp1117
2338a2958df9cbf0ff13234ef866804c8b9bb1b7
43749a3eba6ed1fef54ea542e7b71ddde06c7882
refs/heads/master
2016-09-05T21:54:59.689737
2013-10-27T14:26:55
2013-10-27T14:26:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
// example function #include <iostream> using namespace std; // declaration of function "add" int add(int first_num, int second_num); // function prototype int main() { int first_number, second_number, result; // cin >> first_number; // cin >> second_number; cin >> first_number >> second_number; result = add(first_number, second_number); cout << "Result: " << result << endl; return 0; } int add (int first_num, int second_num) { int result = first_num + second_num; return result; }
[ "chainsawtiney@gmail.com" ]
chainsawtiney@gmail.com
08e8741f1b35417947e227e783bad8057bce0c07
ec6adc54a9be94c57fb37bb001d7cbac9e24f609
/DoTelemetry.h
190a7eed3b9250b3d02c33c2db0aef453d529d50
[ "Unlicense" ]
permissive
Electron-x/TMTelemetry
72ddc5f17e41eb048deac1ede67676f4fe272e0f
8d85f32930f57d04db3f4d8ecf527c22c265345d
refs/heads/master
2023-04-04T10:07:54.373021
2023-03-26T21:26:28
2023-03-26T21:26:28
126,600,044
19
3
Unlicense
2020-05-02T11:47:43
2018-03-24T13:06:29
C++
UTF-8
C++
false
false
464
h
// DoTelemetry.h : Functions for processing the telemetry data // #pragma once #include "maniaplanet_telemetry.h" using namespace NManiaPlanet; struct STelemetryData { STelemetry Current; // Contains the most recent telemetry data records from the shared memory STelemetry Previous; // Contains saved values of the used telemetry data records (to test the live data for changes) }; void DoTelemetry(STelemetryData*); void InitTelemetryData(STelemetryData*);
[ "electron@freakmail.de" ]
electron@freakmail.de
e1e4eb3cd00b32cbf6f0154659b2e8a470226588
f42190636add23ead6a5022d706a124032d66f92
/src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/memreader.cpp
01a4a8191deee27b941505c280e77331009025c0
[ "MIT" ]
permissive
dotnet/wpf
b8f73a99e03f87b4dee5db643e38e2c0704f707a
2ff355a607d79eef5fea7796de1f29cf9ea4fbed
refs/heads/main
2023-09-04T09:35:19.355384
2023-09-03T02:30:37
2023-09-03T02:30:37
153,711,945
6,927
1,397
MIT
2023-09-14T17:22:06
2018-10-19T01:55:23
C#
UTF-8
C++
false
false
5,196
cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // Abstract: // Implementation of a general stream reader. The stream maintains // a series of items of the following format: // // [item size (UINT)]--[item id (UINT)]--[item data (item size - 4 bytes)] // //------------------------------------------------------------------------------ #include "precomp.hpp" //+----------------------------------------------------------------------------- // // Member: // CMilDataStreamReader constructor // //------------------------------------------------------------------------------ CMilDataStreamReader::CMilDataStreamReader( __in_bcount(cbBuffer) LPCVOID pcvBuffer, UINT cbBuffer ) { m_pbData = reinterpret_cast<PBYTE>(const_cast<PVOID>(pcvBuffer)); m_cbDataSize = cbBuffer; m_pbCurItemPos = NULL; } //+----------------------------------------------------------------------------- // // Member: // CMilDataStreamReader::GetFirstItemSafe // // Synopsis: // Resets the reader to the first item in the buffer and returns it. // Performs all necessary validations to make sure that the memory // is valid. // //------------------------------------------------------------------------------ HRESULT CMilDataStreamReader::GetFirstItemSafe( __out_ecount(1) UINT *pnItemID, __deref_out_bcount(*pcbItemSize) PVOID *ppItemData, __out_ecount(1) UINT *pcbItemSize ) { // // Seek to the first item in the buffer // m_pbCurItemPos = m_pbData; // // Now return the current item, if possible. // RRETURN1(GetNextItemSafe(pnItemID, ppItemData, pcbItemSize), S_FALSE); } //+----------------------------------------------------------------------------- // // Member: // CMilDataStreamReader::GetNextItemSafe // // Synopsis: // Reads the next item in the buffer and increments to the next one. // Performs all necessary validations to make sure that the memory // is valid. // // The IFC(E_FAIL)s are a little awkward, but they are like that to // maintain original behavior while providing accurate failure capture. // //------------------------------------------------------------------------------ HRESULT CMilDataStreamReader::GetNextItemSafe( __out_ecount(1) UINT *pnItemID, __deref_out_bcount(*pcbItemSize) PVOID *ppItemData, __out_ecount(1) UINT *pcbItemSize ) { HRESULT hr = S_OK; #if DGB // // The m_pCurItemPos is first set by GetFirstItemSafe. If it's NULL, we // either haven't called GetFirstItemSafe before calling this method // or we have been passed an empty batch. // Assert(m_pbCurItemPos != NULL || m_nDataSize == 0); // // If m_pbCurItemPos is not NULL, it points to the buffer defined as // [m_pbData, m_pbData+m_cbDataSize) (note: left inclusive) if the buffer // has not been exhausted yet and to [m_pbData+m_cbDataSize] otherwise. // // Note that this arithmetic also works if the initial buffer is empty. // size_t cbCurrentItemOffset = 0; Assert(m_pCurItemPos >= m_pData); Assert(SUCCEEDED(PtrdiffTToSizeT(m_pCurItemPos - m_pData, &cbCurrentItemOffset))); Assert(cbCurrentItemOffset <= m_nDataSize); #endif DBG // // Check if there's any data left in the buffer. // size_t cbRem = m_cbDataSize - (m_pbCurItemPos - m_pbData); if (cbRem == 0) { // // We reached the end of the data set. // *ppItemData = NULL; *pcbItemSize = 0; hr = S_FALSE; } else if (cbRem >= 2 * sizeof(UINT)) { // // Read the current item size from the buffer. // UINT cbItemSize = *(reinterpret_cast<UINT *>(m_pbCurItemPos)); // // Make sure that the item fits in the buffer. We expect to have at least // the item size and the item ID in the buffer, that makes two 32-bit // integers total. The item size must be a multiple of sizeof(UINT). // // The item size could still be wrong -- we have to verify it against // the item type (and, possibly, item contents) later. // if ((cbItemSize >= 2 * sizeof(UINT)) && (cbItemSize % sizeof(UINT) == 0) && (cbItemSize <= cbRem)) { *pnItemID = *(reinterpret_cast<UINT *>(m_pbCurItemPos + sizeof(UINT))); // // Return the item and its length // *ppItemData = m_pbCurItemPos + sizeof(UINT); // skip size *pcbItemSize = cbItemSize - sizeof(UINT); // // Advance the current item pointer to the next item. // m_pbCurItemPos += cbItemSize; } else { IFC(E_FAIL); } } else { IFC(E_FAIL); } Cleanup: RRETURN1(hr, S_FALSE); }
[ "vatsan.madhavan@microsoft.com" ]
vatsan.madhavan@microsoft.com
fb4046b66165c67c03470fb874e7260efbfb9fd3
fc7359b2aebff4580611767fa0d622c5ba642c9c
/3rdParty/V8/v7.1.302.28/third_party/icu/source/common/ucnvsel.cpp
573e8b061d6b88d9c1a61a71ba753e09100ad42d
[ "SunPro", "BSD-3-Clause", "bzip2-1.0.6", "LicenseRef-scancode-unicode", "LicenseRef-scancode-unknown-license-reference", "ICU", "MIT", "NTP", "LicenseRef-scancode-unicode-icu-58", "LicenseRef-scancode-autoconf-simple-exception", "GPL-3.0-or-later", "NAIST-2003", "LicenseRef-scancode-public-d...
permissive
William533036/arangodb
36106973f1db1ffe2872e36af09cbdc7f0ba444b
08785b946a21c127bcc22f6950d8c3f9bc2c5d76
refs/heads/master
2020-12-06T23:09:43.024228
2019-12-30T08:16:24
2019-12-30T08:16:24
232,570,534
1
0
Apache-2.0
2020-01-08T13:33:37
2020-01-08T13:33:36
null
UTF-8
C++
false
false
24,823
cpp
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * * Copyright (C) 2008-2011, International Business Machines * Corporation, Google and others. All Rights Reserved. * ******************************************************************************* */ // Author : eldawy@google.com (Mohamed Eldawy) // ucnvsel.cpp // // Purpose: To generate a list of encodings capable of handling // a given Unicode text // // Started 09-April-2008 /** * \file * * This is an implementation of an encoding selector. * The goal is, given a unicode string, find the encodings * this string can be mapped to. To make processing faster * a trie is built when you call ucnvsel_open() that * stores all encodings a codepoint can map to */ #include "unicode/ucnvsel.h" #if !UCONFIG_NO_CONVERSION #include <string.h> #include "unicode/uchar.h" #include "unicode/uniset.h" #include "unicode/ucnv.h" #include "unicode/ustring.h" #include "unicode/uchriter.h" #include "utrie2.h" #include "propsvec.h" #include "uassert.h" #include "ucmndata.h" #include "uenumimp.h" #include "cmemory.h" #include "cstring.h" U_NAMESPACE_USE struct UConverterSelector { UTrie2 *trie; // 16 bit trie containing offsets into pv uint32_t* pv; // table of bits! int32_t pvCount; char** encodings; // which encodings did user ask to use? int32_t encodingsCount; int32_t encodingStrLength; uint8_t* swapped; UBool ownPv, ownEncodingStrings; }; static void generateSelectorData(UConverterSelector* result, UPropsVectors *upvec, const USet* excludedCodePoints, const UConverterUnicodeSet whichSet, UErrorCode* status) { if (U_FAILURE(*status)) { return; } int32_t columns = (result->encodingsCount+31)/32; // set errorValue to all-ones for (int32_t col = 0; col < columns; col++) { upvec_setValue(upvec, UPVEC_ERROR_VALUE_CP, UPVEC_ERROR_VALUE_CP, col, ~0, ~0, status); } for (int32_t i = 0; i < result->encodingsCount; ++i) { uint32_t mask; uint32_t column; int32_t item_count; int32_t j; UConverter* test_converter = ucnv_open(result->encodings[i], status); if (U_FAILURE(*status)) { return; } USet* unicode_point_set; unicode_point_set = uset_open(1, 0); // empty set ucnv_getUnicodeSet(test_converter, unicode_point_set, whichSet, status); if (U_FAILURE(*status)) { ucnv_close(test_converter); return; } column = i / 32; mask = 1 << (i%32); // now iterate over intervals on set i! item_count = uset_getItemCount(unicode_point_set); for (j = 0; j < item_count; ++j) { UChar32 start_char; UChar32 end_char; UErrorCode smallStatus = U_ZERO_ERROR; uset_getItem(unicode_point_set, j, &start_char, &end_char, NULL, 0, &smallStatus); if (U_FAILURE(smallStatus)) { // this will be reached for the converters that fill the set with // strings. Those should be ignored by our system } else { upvec_setValue(upvec, start_char, end_char, column, ~0, mask, status); } } ucnv_close(test_converter); uset_close(unicode_point_set); if (U_FAILURE(*status)) { return; } } // handle excluded encodings! Simply set their values to all 1's in the upvec if (excludedCodePoints) { int32_t item_count = uset_getItemCount(excludedCodePoints); for (int32_t j = 0; j < item_count; ++j) { UChar32 start_char; UChar32 end_char; uset_getItem(excludedCodePoints, j, &start_char, &end_char, NULL, 0, status); for (int32_t col = 0; col < columns; col++) { upvec_setValue(upvec, start_char, end_char, col, ~0, ~0, status); } } } // alright. Now, let's put things in the same exact form you'd get when you // unserialize things. result->trie = upvec_compactToUTrie2WithRowIndexes(upvec, status); result->pv = upvec_cloneArray(upvec, &result->pvCount, NULL, status); result->pvCount *= columns; // number of uint32_t = rows * columns result->ownPv = TRUE; } /* open a selector. If converterListSize is 0, build for all converters. If excludedCodePoints is NULL, don't exclude any codepoints */ U_CAPI UConverterSelector* U_EXPORT2 ucnvsel_open(const char* const* converterList, int32_t converterListSize, const USet* excludedCodePoints, const UConverterUnicodeSet whichSet, UErrorCode* status) { // check if already failed if (U_FAILURE(*status)) { return NULL; } // ensure args make sense! if (converterListSize < 0 || (converterList == NULL && converterListSize != 0)) { *status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } // allocate a new converter LocalUConverterSelectorPointer newSelector( (UConverterSelector*)uprv_malloc(sizeof(UConverterSelector))); if (newSelector.isNull()) { *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } uprv_memset(newSelector.getAlias(), 0, sizeof(UConverterSelector)); if (converterListSize == 0) { converterList = NULL; converterListSize = ucnv_countAvailable(); } newSelector->encodings = (char**)uprv_malloc(converterListSize * sizeof(char*)); if (!newSelector->encodings) { *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } newSelector->encodings[0] = NULL; // now we can call ucnvsel_close() // make a backup copy of the list of converters int32_t totalSize = 0; int32_t i; for (i = 0; i < converterListSize; i++) { totalSize += (int32_t)uprv_strlen(converterList != NULL ? converterList[i] : ucnv_getAvailableName(i)) + 1; } // 4-align the totalSize to 4-align the size of the serialized form int32_t encodingStrPadding = totalSize & 3; if (encodingStrPadding != 0) { encodingStrPadding = 4 - encodingStrPadding; } newSelector->encodingStrLength = totalSize += encodingStrPadding; char* allStrings = (char*) uprv_malloc(totalSize); if (!allStrings) { *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } for (i = 0; i < converterListSize; i++) { newSelector->encodings[i] = allStrings; uprv_strcpy(newSelector->encodings[i], converterList != NULL ? converterList[i] : ucnv_getAvailableName(i)); allStrings += uprv_strlen(newSelector->encodings[i]) + 1; } while (encodingStrPadding > 0) { *allStrings++ = 0; --encodingStrPadding; } newSelector->ownEncodingStrings = TRUE; newSelector->encodingsCount = converterListSize; UPropsVectors *upvec = upvec_open((converterListSize+31)/32, status); generateSelectorData(newSelector.getAlias(), upvec, excludedCodePoints, whichSet, status); upvec_close(upvec); if (U_FAILURE(*status)) { return NULL; } return newSelector.orphan(); } /* close opened selector */ U_CAPI void U_EXPORT2 ucnvsel_close(UConverterSelector *sel) { if (!sel) { return; } if (sel->ownEncodingStrings) { uprv_free(sel->encodings[0]); } uprv_free(sel->encodings); if (sel->ownPv) { uprv_free(sel->pv); } utrie2_close(sel->trie); uprv_free(sel->swapped); uprv_free(sel); } static const UDataInfo dataInfo = { sizeof(UDataInfo), 0, U_IS_BIG_ENDIAN, U_CHARSET_FAMILY, U_SIZEOF_UCHAR, 0, { 0x43, 0x53, 0x65, 0x6c }, /* dataFormat="CSel" */ { 1, 0, 0, 0 }, /* formatVersion */ { 0, 0, 0, 0 } /* dataVersion */ }; enum { UCNVSEL_INDEX_TRIE_SIZE, // trie size in bytes UCNVSEL_INDEX_PV_COUNT, // number of uint32_t in the bit vectors UCNVSEL_INDEX_NAMES_COUNT, // number of encoding names UCNVSEL_INDEX_NAMES_LENGTH, // number of encoding name bytes including padding UCNVSEL_INDEX_SIZE = 15, // bytes following the DataHeader UCNVSEL_INDEX_COUNT = 16 }; /* * Serialized form of a UConverterSelector, formatVersion 1: * * The serialized form begins with a standard ICU DataHeader with a UDataInfo * as the template above. * This is followed by: * int32_t indexes[UCNVSEL_INDEX_COUNT]; // see index entry constants above * serialized UTrie2; // indexes[UCNVSEL_INDEX_TRIE_SIZE] bytes * uint32_t pv[indexes[UCNVSEL_INDEX_PV_COUNT]]; // bit vectors * char* encodingNames[indexes[UCNVSEL_INDEX_NAMES_LENGTH]]; // NUL-terminated strings + padding */ /* serialize a selector */ U_CAPI int32_t U_EXPORT2 ucnvsel_serialize(const UConverterSelector* sel, void* buffer, int32_t bufferCapacity, UErrorCode* status) { // check if already failed if (U_FAILURE(*status)) { return 0; } // ensure args make sense! uint8_t *p = (uint8_t *)buffer; if (bufferCapacity < 0 || (bufferCapacity > 0 && (p == NULL || (U_POINTER_MASK_LSB(p, 3) != 0))) ) { *status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } // add up the size of the serialized form int32_t serializedTrieSize = utrie2_serialize(sel->trie, NULL, 0, status); if (*status != U_BUFFER_OVERFLOW_ERROR && U_FAILURE(*status)) { return 0; } *status = U_ZERO_ERROR; DataHeader header; uprv_memset(&header, 0, sizeof(header)); header.dataHeader.headerSize = (uint16_t)((sizeof(header) + 15) & ~15); header.dataHeader.magic1 = 0xda; header.dataHeader.magic2 = 0x27; uprv_memcpy(&header.info, &dataInfo, sizeof(dataInfo)); int32_t indexes[UCNVSEL_INDEX_COUNT] = { serializedTrieSize, sel->pvCount, sel->encodingsCount, sel->encodingStrLength }; int32_t totalSize = header.dataHeader.headerSize + (int32_t)sizeof(indexes) + serializedTrieSize + sel->pvCount * 4 + sel->encodingStrLength; indexes[UCNVSEL_INDEX_SIZE] = totalSize - header.dataHeader.headerSize; if (totalSize > bufferCapacity) { *status = U_BUFFER_OVERFLOW_ERROR; return totalSize; } // ok, save! int32_t length = header.dataHeader.headerSize; uprv_memcpy(p, &header, sizeof(header)); uprv_memset(p + sizeof(header), 0, length - sizeof(header)); p += length; length = (int32_t)sizeof(indexes); uprv_memcpy(p, indexes, length); p += length; utrie2_serialize(sel->trie, p, serializedTrieSize, status); p += serializedTrieSize; length = sel->pvCount * 4; uprv_memcpy(p, sel->pv, length); p += length; uprv_memcpy(p, sel->encodings[0], sel->encodingStrLength); p += sel->encodingStrLength; return totalSize; } /** * swap a selector into the desired Endianness and Asciiness of * the system. Just as FYI, selectors are always saved in the format * of the system that created them. They are only converted if used * on another system. In other words, selectors created on different * system can be different even if the params are identical (endianness * and Asciiness differences only) * * @param ds pointer to data swapper containing swapping info * @param inData pointer to incoming data * @param length length of inData in bytes * @param outData pointer to output data. Capacity should * be at least equal to capacity of inData * @param status an in/out ICU UErrorCode * @return 0 on failure, number of bytes swapped on success * number of bytes swapped can be smaller than length */ static int32_t ucnvsel_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData, UErrorCode *status) { /* udata_swapDataHeader checks the arguments */ int32_t headerSize = udata_swapDataHeader(ds, inData, length, outData, status); if(U_FAILURE(*status)) { return 0; } /* check data format and format version */ const UDataInfo *pInfo = (const UDataInfo *)((const char *)inData + 4); if(!( pInfo->dataFormat[0] == 0x43 && /* dataFormat="CSel" */ pInfo->dataFormat[1] == 0x53 && pInfo->dataFormat[2] == 0x65 && pInfo->dataFormat[3] == 0x6c )) { udata_printError(ds, "ucnvsel_swap(): data format %02x.%02x.%02x.%02x is not recognized as UConverterSelector data\n", pInfo->dataFormat[0], pInfo->dataFormat[1], pInfo->dataFormat[2], pInfo->dataFormat[3]); *status = U_INVALID_FORMAT_ERROR; return 0; } if(pInfo->formatVersion[0] != 1) { udata_printError(ds, "ucnvsel_swap(): format version %02x is not supported\n", pInfo->formatVersion[0]); *status = U_UNSUPPORTED_ERROR; return 0; } if(length >= 0) { length -= headerSize; if(length < 16*4) { udata_printError(ds, "ucnvsel_swap(): too few bytes (%d after header) for UConverterSelector data\n", length); *status = U_INDEX_OUTOFBOUNDS_ERROR; return 0; } } const uint8_t *inBytes = (const uint8_t *)inData + headerSize; uint8_t *outBytes = (uint8_t *)outData + headerSize; /* read the indexes */ const int32_t *inIndexes = (const int32_t *)inBytes; int32_t indexes[16]; int32_t i; for(i = 0; i < 16; ++i) { indexes[i] = udata_readInt32(ds, inIndexes[i]); } /* get the total length of the data */ int32_t size = indexes[UCNVSEL_INDEX_SIZE]; if(length >= 0) { if(length < size) { udata_printError(ds, "ucnvsel_swap(): too few bytes (%d after header) for all of UConverterSelector data\n", length); *status = U_INDEX_OUTOFBOUNDS_ERROR; return 0; } /* copy the data for inaccessible bytes */ if(inBytes != outBytes) { uprv_memcpy(outBytes, inBytes, size); } int32_t offset = 0, count; /* swap the int32_t indexes[] */ count = UCNVSEL_INDEX_COUNT*4; ds->swapArray32(ds, inBytes, count, outBytes, status); offset += count; /* swap the UTrie2 */ count = indexes[UCNVSEL_INDEX_TRIE_SIZE]; utrie2_swap(ds, inBytes + offset, count, outBytes + offset, status); offset += count; /* swap the uint32_t pv[] */ count = indexes[UCNVSEL_INDEX_PV_COUNT]*4; ds->swapArray32(ds, inBytes + offset, count, outBytes + offset, status); offset += count; /* swap the encoding names */ count = indexes[UCNVSEL_INDEX_NAMES_LENGTH]; ds->swapInvChars(ds, inBytes + offset, count, outBytes + offset, status); offset += count; U_ASSERT(offset == size); } return headerSize + size; } /* unserialize a selector */ U_CAPI UConverterSelector* U_EXPORT2 ucnvsel_openFromSerialized(const void* buffer, int32_t length, UErrorCode* status) { // check if already failed if (U_FAILURE(*status)) { return NULL; } // ensure args make sense! const uint8_t *p = (const uint8_t *)buffer; if (length <= 0 || (length > 0 && (p == NULL || (U_POINTER_MASK_LSB(p, 3) != 0))) ) { *status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } // header if (length < 32) { // not even enough space for a minimal header *status = U_INDEX_OUTOFBOUNDS_ERROR; return NULL; } const DataHeader *pHeader = (const DataHeader *)p; if (!( pHeader->dataHeader.magic1==0xda && pHeader->dataHeader.magic2==0x27 && pHeader->info.dataFormat[0] == 0x43 && pHeader->info.dataFormat[1] == 0x53 && pHeader->info.dataFormat[2] == 0x65 && pHeader->info.dataFormat[3] == 0x6c )) { /* header not valid or dataFormat not recognized */ *status = U_INVALID_FORMAT_ERROR; return NULL; } if (pHeader->info.formatVersion[0] != 1) { *status = U_UNSUPPORTED_ERROR; return NULL; } uint8_t* swapped = NULL; if (pHeader->info.isBigEndian != U_IS_BIG_ENDIAN || pHeader->info.charsetFamily != U_CHARSET_FAMILY ) { // swap the data UDataSwapper *ds = udata_openSwapperForInputData(p, length, U_IS_BIG_ENDIAN, U_CHARSET_FAMILY, status); int32_t totalSize = ucnvsel_swap(ds, p, -1, NULL, status); if (U_FAILURE(*status)) { udata_closeSwapper(ds); return NULL; } if (length < totalSize) { udata_closeSwapper(ds); *status = U_INDEX_OUTOFBOUNDS_ERROR; return NULL; } swapped = (uint8_t*)uprv_malloc(totalSize); if (swapped == NULL) { udata_closeSwapper(ds); *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } ucnvsel_swap(ds, p, length, swapped, status); udata_closeSwapper(ds); if (U_FAILURE(*status)) { uprv_free(swapped); return NULL; } p = swapped; pHeader = (const DataHeader *)p; } if (length < (pHeader->dataHeader.headerSize + 16 * 4)) { // not even enough space for the header and the indexes uprv_free(swapped); *status = U_INDEX_OUTOFBOUNDS_ERROR; return NULL; } p += pHeader->dataHeader.headerSize; length -= pHeader->dataHeader.headerSize; // indexes const int32_t *indexes = (const int32_t *)p; if (length < indexes[UCNVSEL_INDEX_SIZE]) { uprv_free(swapped); *status = U_INDEX_OUTOFBOUNDS_ERROR; return NULL; } p += UCNVSEL_INDEX_COUNT * 4; // create and populate the selector object UConverterSelector* sel = (UConverterSelector*)uprv_malloc(sizeof(UConverterSelector)); char **encodings = (char **)uprv_malloc( indexes[UCNVSEL_INDEX_NAMES_COUNT] * sizeof(char *)); if (sel == NULL || encodings == NULL) { uprv_free(swapped); uprv_free(sel); uprv_free(encodings); *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } uprv_memset(sel, 0, sizeof(UConverterSelector)); sel->pvCount = indexes[UCNVSEL_INDEX_PV_COUNT]; sel->encodings = encodings; sel->encodingsCount = indexes[UCNVSEL_INDEX_NAMES_COUNT]; sel->encodingStrLength = indexes[UCNVSEL_INDEX_NAMES_LENGTH]; sel->swapped = swapped; // trie sel->trie = utrie2_openFromSerialized(UTRIE2_16_VALUE_BITS, p, indexes[UCNVSEL_INDEX_TRIE_SIZE], NULL, status); p += indexes[UCNVSEL_INDEX_TRIE_SIZE]; if (U_FAILURE(*status)) { ucnvsel_close(sel); return NULL; } // bit vectors sel->pv = (uint32_t *)p; p += sel->pvCount * 4; // encoding names char* s = (char*)p; for (int32_t i = 0; i < sel->encodingsCount; ++i) { sel->encodings[i] = s; s += uprv_strlen(s) + 1; } p += sel->encodingStrLength; return sel; } // a bunch of functions for the enumeration thingie! Nothing fancy here. Just // iterate over the selected encodings struct Enumerator { int16_t* index; int16_t length; int16_t cur; const UConverterSelector* sel; }; U_CDECL_BEGIN static void U_CALLCONV ucnvsel_close_selector_iterator(UEnumeration *enumerator) { uprv_free(((Enumerator*)(enumerator->context))->index); uprv_free(enumerator->context); uprv_free(enumerator); } static int32_t U_CALLCONV ucnvsel_count_encodings(UEnumeration *enumerator, UErrorCode *status) { // check if already failed if (U_FAILURE(*status)) { return 0; } return ((Enumerator*)(enumerator->context))->length; } static const char* U_CALLCONV ucnvsel_next_encoding(UEnumeration* enumerator, int32_t* resultLength, UErrorCode* status) { // check if already failed if (U_FAILURE(*status)) { return NULL; } int16_t cur = ((Enumerator*)(enumerator->context))->cur; const UConverterSelector* sel; const char* result; if (cur >= ((Enumerator*)(enumerator->context))->length) { return NULL; } sel = ((Enumerator*)(enumerator->context))->sel; result = sel->encodings[((Enumerator*)(enumerator->context))->index[cur] ]; ((Enumerator*)(enumerator->context))->cur++; if (resultLength) { *resultLength = (int32_t)uprv_strlen(result); } return result; } static void U_CALLCONV ucnvsel_reset_iterator(UEnumeration* enumerator, UErrorCode* status) { // check if already failed if (U_FAILURE(*status)) { return ; } ((Enumerator*)(enumerator->context))->cur = 0; } U_CDECL_END static const UEnumeration defaultEncodings = { NULL, NULL, ucnvsel_close_selector_iterator, ucnvsel_count_encodings, uenum_unextDefault, ucnvsel_next_encoding, ucnvsel_reset_iterator }; // internal fn to intersect two sets of masks // returns whether the mask has reduced to all zeros static UBool intersectMasks(uint32_t* dest, const uint32_t* source1, int32_t len) { int32_t i; uint32_t oredDest = 0; for (i = 0 ; i < len ; ++i) { oredDest |= (dest[i] &= source1[i]); } return oredDest == 0; } // internal fn to count how many 1's are there in a mask // algorithm taken from http://graphics.stanford.edu/~seander/bithacks.html static int16_t countOnes(uint32_t* mask, int32_t len) { int32_t i, totalOnes = 0; for (i = 0 ; i < len ; ++i) { uint32_t ent = mask[i]; for (; ent; totalOnes++) { ent &= ent - 1; // clear the least significant bit set } } return totalOnes; } /* internal function! */ static UEnumeration *selectForMask(const UConverterSelector* sel, uint32_t *mask, UErrorCode *status) { // this is the context we will use. Store a table of indices to which // encodings are legit. struct Enumerator* result = (Enumerator*)uprv_malloc(sizeof(Enumerator)); if (result == NULL) { uprv_free(mask); *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } result->index = NULL; // this will be allocated later! result->length = result->cur = 0; result->sel = sel; UEnumeration *en = (UEnumeration *)uprv_malloc(sizeof(UEnumeration)); if (en == NULL) { // TODO(markus): Combine Enumerator and UEnumeration into one struct. uprv_free(mask); uprv_free(result); *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } memcpy(en, &defaultEncodings, sizeof(UEnumeration)); en->context = result; int32_t columns = (sel->encodingsCount+31)/32; int16_t numOnes = countOnes(mask, columns); // now, we know the exact space we need for index if (numOnes > 0) { result->index = (int16_t*) uprv_malloc(numOnes * sizeof(int16_t)); int32_t i, j; int16_t k = 0; for (j = 0 ; j < columns; j++) { uint32_t v = mask[j]; for (i = 0 ; i < 32 && k < sel->encodingsCount; i++, k++) { if ((v & 1) != 0) { result->index[result->length++] = k; } v >>= 1; } } } //otherwise, index will remain NULL (and will never be touched by //the enumerator code anyway) uprv_free(mask); return en; } /* check a string against the selector - UTF16 version */ U_CAPI UEnumeration * U_EXPORT2 ucnvsel_selectForString(const UConverterSelector* sel, const UChar *s, int32_t length, UErrorCode *status) { // check if already failed if (U_FAILURE(*status)) { return NULL; } // ensure args make sense! if (sel == NULL || (s == NULL && length != 0)) { *status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } int32_t columns = (sel->encodingsCount+31)/32; uint32_t* mask = (uint32_t*) uprv_malloc(columns * 4); if (mask == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } uprv_memset(mask, ~0, columns *4); if(s!=NULL) { const UChar *limit; if (length >= 0) { limit = s + length; } else { limit = NULL; } while (limit == NULL ? *s != 0 : s != limit) { UChar32 c; uint16_t pvIndex; UTRIE2_U16_NEXT16(sel->trie, s, limit, c, pvIndex); if (intersectMasks(mask, sel->pv+pvIndex, columns)) { break; } } } return selectForMask(sel, mask, status); } /* check a string against the selector - UTF8 version */ U_CAPI UEnumeration * U_EXPORT2 ucnvsel_selectForUTF8(const UConverterSelector* sel, const char *s, int32_t length, UErrorCode *status) { // check if already failed if (U_FAILURE(*status)) { return NULL; } // ensure args make sense! if (sel == NULL || (s == NULL && length != 0)) { *status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } int32_t columns = (sel->encodingsCount+31)/32; uint32_t* mask = (uint32_t*) uprv_malloc(columns * 4); if (mask == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; return NULL; } uprv_memset(mask, ~0, columns *4); if (length < 0) { length = (int32_t)uprv_strlen(s); } if(s!=NULL) { const char *limit = s + length; while (s != limit) { uint16_t pvIndex; UTRIE2_U8_NEXT16(sel->trie, s, limit, pvIndex); if (intersectMasks(mask, sel->pv+pvIndex, columns)) { break; } } } return selectForMask(sel, mask, status); } #endif // !UCONFIG_NO_CONVERSION
[ "willi@arangodb.com" ]
willi@arangodb.com
e393ca418abdd7f29b53fed4df644f8dff219bcd
12b8dcfe244b52e0f1bfce8e176f5bb74aa0e13f
/SapVisual/Postgres/pgarticulotipo.h
77a093605970475f47316307f922f6d112c721dc
[]
no_license
gato0429/SAP
53fced121950d2b7ebfbcd2f7114b4107d33c157
a35db87563369d615c9892c026efef3c3d9917f4
refs/heads/master
2021-01-02T22:30:28.050719
2015-07-14T18:35:11
2015-07-14T18:35:11
34,421,766
2
0
null
null
null
null
UTF-8
C++
false
false
782
h
#ifndef PGARTICULOTIPO_H #define PGARTICULOTIPO_H #include "../Fabricas/fabricaarticulotipos.h" #include <QSqlQuery> #include <QString> #include <QVariant> #include <qdebug.h> #include <QMap> class PgArticuloTipo:public FabricaArticuloTipos { public: PgArticuloTipo(); // FabricaArticuloTipos interface public: bool Borrar(ArticuloTipo valor); bool Insertar(ArticuloTipo valor); bool Actualizar(ArticuloTipo Antiguo, ArticuloTipo Nuevo); ArticuloTipo Buscar(ArticuloTipo valor); QMap<QString, ObjetoMaestro*> *BuscarMapa(ObjetoMaestro* valor,QString Extra, CONSULTA tipo); int Contar(); int ContarConsulta(ObjetoMaestro* valor); QSqlQueryModel *BuscarTabla(ArticuloTipo valor, QString Extra, CONSULTA tipo); }; #endif // PGARTICULOTIPO_H
[ "josue.ccama@ucsp.edu.pe" ]
josue.ccama@ucsp.edu.pe
309bd2696370cc1528b48dbe3db29d169802f356
267bb6c0aaf057083a12e744aa50fbd2735b42d8
/src/utest/utestSectionFile.cpp
29693ec811879c5d7daf68706e2979ed43645a59
[ "BSD-2-Clause", "WTFPL", "LicenseRef-scancode-public-domain" ]
permissive
yrpark99/tsduck
0c163410306a085248dba8490ee0faeae8a5a862
2929092e42c5c7eec95a119af91cc09ffdde2028
refs/heads/master
2020-04-06T10:20:44.113519
2019-10-15T06:27:13
2019-10-15T06:27:13
157,377,153
0
0
NOASSERTION
2018-11-13T12:30:58
2018-11-13T12:30:58
null
UTF-8
C++
false
false
17,792
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2018, Thierry Lelegard // 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 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 OWNER 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. // //---------------------------------------------------------------------------- // // CppUnit test suite for SectionFile (binary and XML). // //---------------------------------------------------------------------------- #include "tsSectionFile.h" #include "tsPAT.h" #include "tsTDT.h" #include "tsSysUtils.h" #include "tsBinaryTable.h" #include "tsCerrReport.h" #include "utestCppUnitTest.h" TSDUCK_SOURCE; #include "tables/psi_pat1_xml.h" #include "tables/psi_pat1_sections.h" #include "tables/psi_pmt_scte35_xml.h" #include "tables/psi_pmt_scte35_sections.h" #include "tables/psi_all_xml.h" #include "tables/psi_all_sections.h" //---------------------------------------------------------------------------- // The test fixture //---------------------------------------------------------------------------- class SectionFileTest: public CppUnit::TestFixture { public: SectionFileTest(); virtual void setUp() override; virtual void tearDown() override; void testConfigurationFile(); void testGenericDescriptor(); void testGenericShortTable(); void testGenericLongTable(); void testPAT1(); void testSCTE35(); void testAllTables(); void testBuildSections(); CPPUNIT_TEST_SUITE(SectionFileTest); CPPUNIT_TEST(testConfigurationFile); CPPUNIT_TEST(testGenericDescriptor); CPPUNIT_TEST(testGenericShortTable); CPPUNIT_TEST(testGenericLongTable); CPPUNIT_TEST(testPAT1); CPPUNIT_TEST(testSCTE35); CPPUNIT_TEST(testAllTables); CPPUNIT_TEST(testBuildSections); CPPUNIT_TEST_SUITE_END(); private: // Unitary test for one table. void testTable(const char* name, const ts::UChar* ref_xml, const uint8_t* ref_sections, size_t ref_sections_size); ts::Report& report(); ts::UString _tempFileNameBin; ts::UString _tempFileNameXML; }; CPPUNIT_TEST_SUITE_REGISTRATION(SectionFileTest); //---------------------------------------------------------------------------- // Initialization. //---------------------------------------------------------------------------- // Constructor. SectionFileTest::SectionFileTest() : _tempFileNameBin(ts::TempFile(u".tmp.bin")), _tempFileNameXML(ts::TempFile(u".tmp.xml")) { } // Test suite initialization method. void SectionFileTest::setUp() { ts::DeleteFile(_tempFileNameBin); ts::DeleteFile(_tempFileNameXML); } // Test suite cleanup method. void SectionFileTest::tearDown() { ts::DeleteFile(_tempFileNameBin); ts::DeleteFile(_tempFileNameXML); } ts::Report& SectionFileTest::report() { if (utest::DebugMode()) { return CERR; } else { return NULLREP; } } //---------------------------------------------------------------------------- // Unitary tests from XML tables. //---------------------------------------------------------------------------- #define TESTTABLE(name, data) \ void SectionFileTest::test##name() \ { \ testTable(#name, psi_##data##_xml, psi_##data##_sections, sizeof(psi_##data##_sections)); \ } TESTTABLE(PAT1, pat1) TESTTABLE(SCTE35, pmt_scte35) TESTTABLE(AllTables, all) void SectionFileTest::testTable(const char* name, const ts::UChar* ref_xml, const uint8_t* ref_sections, size_t ref_sections_size) { utest::Out() << "SectionFileTest: Testing " << name << std::endl; // Convert XML reference content to binary tables. ts::SectionFile xml; CPPUNIT_ASSERT(xml.parseXML(ref_xml, CERR)); // Serialize binary tables to section data. std::ostringstream strm; CPPUNIT_ASSERT(xml.saveBinary(strm, CERR)); // Compare serialized section data to reference section data. const std::string sections(strm.str()); CPPUNIT_ASSERT_EQUAL(ref_sections_size, sections.size()); CPPUNIT_ASSERT_EQUAL(0, ::memcmp(ref_sections, sections.data(), ref_sections_size)); // Convert binary tables to XML. CPPUNIT_ASSERT_USTRINGS_EQUAL(ref_xml, xml.toXML(CERR)); } //---------------------------------------------------------------------------- // Other unitary tests. //---------------------------------------------------------------------------- void SectionFileTest::testConfigurationFile() { const ts::UString conf(ts::SearchConfigurationFile(u"tsduck.xml")); utest::Out() << "SectionFileTest::testConfigurationFile: " << conf << std::endl; CPPUNIT_ASSERT(ts::FileExists(conf)); } void SectionFileTest::testGenericDescriptor() { static const uint8_t descData[] = { 0x72, // tag 0x07, // length 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; ts::Descriptor desc(descData, sizeof(descData)); CPPUNIT_ASSERT(desc.isValid()); CPPUNIT_ASSERT_EQUAL(0x72, int(desc.tag())); CPPUNIT_ASSERT_EQUAL(9, int(desc.size())); CPPUNIT_ASSERT_EQUAL(7, int(desc.payloadSize())); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT(desc.toXML(root, 0, ts::TID_NULL, true) != nullptr); ts::UString text(doc.toString()); utest::Out() << "SectionFileTest::testGenericDescriptor: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_descriptor tag=\"0x72\">\n" u" 01 02 03 04 05 06 07\n" u" </generic_descriptor>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"generic_descriptor", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::ByteBlock payload; CPPUNIT_ASSERT(children[0]->getHexaText(payload)); CPPUNIT_ASSERT_EQUAL(size_t(7), payload.size()); CPPUNIT_ASSERT(payload == ts::ByteBlock(descData + 2, sizeof(descData) - 2)); ts::Descriptor desc2; CPPUNIT_ASSERT(desc2.fromXML(children[0])); CPPUNIT_ASSERT_EQUAL(ts::DID(0x72), desc2.tag()); CPPUNIT_ASSERT_EQUAL(size_t(7), desc2.payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(desc2.payload(), desc2.payloadSize()) == ts::ByteBlock(descData + 2, sizeof(descData) - 2)); } void SectionFileTest::testGenericShortTable() { static const uint8_t refData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; const ts::SectionPtr refSection(new ts::Section(0xAB, false, refData, sizeof(refData))); CPPUNIT_ASSERT(!refSection.isNull()); CPPUNIT_ASSERT(refSection->isValid()); ts::BinaryTable refTable; refTable.addSection(refSection); CPPUNIT_ASSERT(refTable.isValid()); CPPUNIT_ASSERT_EQUAL(size_t(1), refTable.sectionCount()); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT(refTable.toXML(root, true) != nullptr); ts::UString text(doc.toString()); utest::Out() << "SectionFileTest::testGenericShortTable: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_short_table table_id=\"0xAB\" private=\"false\">\n" u" 01 02 03 04 05 06\n" u" </generic_short_table>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"GENERIC_SHORT_TABLE", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::BinaryTable tab; CPPUNIT_ASSERT(tab.fromXML(children[0])); CPPUNIT_ASSERT(tab.isValid()); CPPUNIT_ASSERT(tab.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xAB), tab.tableId()); CPPUNIT_ASSERT_EQUAL(size_t(1), tab.sectionCount()); ts::SectionPtr sec(tab.sectionAt(0)); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xAB), sec->tableId()); CPPUNIT_ASSERT(sec->isShortSection()); CPPUNIT_ASSERT(!sec->isPrivateSection()); CPPUNIT_ASSERT_EQUAL(size_t(6), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData, sizeof(refData))); } void SectionFileTest::testGenericLongTable() { static const uint8_t refData0[] = {0x01, 0x02, 0x03, 0x04, 0x05}; static const uint8_t refData1[] = {0x11, 0x12, 0x13, 0x14}; ts::BinaryTable refTable; refTable.addSection(new ts::Section(0xCD, true, 0x1234, 7, true, 0, 0, refData0, sizeof(refData0))); refTable.addSection(new ts::Section(0xCD, true, 0x1234, 7, true, 1, 1, refData1, sizeof(refData1))); CPPUNIT_ASSERT(refTable.isValid()); CPPUNIT_ASSERT(!refTable.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), refTable.tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), refTable.tableIdExtension()); CPPUNIT_ASSERT_EQUAL(size_t(2), refTable.sectionCount()); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT(refTable.toXML(root, true) != nullptr); ts::UString text(doc.toString()); utest::Out() << "SectionFileTest::testGenericLongTable: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_long_table table_id=\"0xCD\" table_id_ext=\"0x1234\" version=\"7\" current=\"true\" private=\"true\">\n" u" <section>\n" u" 01 02 03 04 05\n" u" </section>\n" u" <section>\n" u" 11 12 13 14\n" u" </section>\n" u" </generic_long_table>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != nullptr); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"GENERIC_long_TABLE", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::BinaryTable tab; CPPUNIT_ASSERT(tab.fromXML(children[0])); CPPUNIT_ASSERT(tab.isValid()); CPPUNIT_ASSERT(!tab.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), tab.tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), tab.tableIdExtension()); CPPUNIT_ASSERT_EQUAL(size_t(2), tab.sectionCount()); ts::SectionPtr sec(tab.sectionAt(0)); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), sec->tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), sec->tableIdExtension()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), sec->version()); CPPUNIT_ASSERT(!sec->isShortSection()); CPPUNIT_ASSERT(sec->isPrivateSection()); CPPUNIT_ASSERT(sec->isCurrent()); CPPUNIT_ASSERT_EQUAL(sizeof(refData0), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData0, sizeof(refData0))); sec = tab.sectionAt(1); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), sec->tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), sec->tableIdExtension()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), sec->version()); CPPUNIT_ASSERT(!sec->isShortSection()); CPPUNIT_ASSERT(sec->isPrivateSection()); CPPUNIT_ASSERT(sec->isCurrent()); CPPUNIT_ASSERT_EQUAL(sizeof(refData1), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData1, sizeof(refData1))); } void SectionFileTest::testBuildSections() { // Build a PAT with 2 sections. ts::PAT pat(7, true, 0x1234); CPPUNIT_ASSERT_EQUAL(ts::PID(ts::PID_NIT), pat.nit_pid); for (uint16_t srv = 3; srv < ts::MAX_PSI_LONG_SECTION_PAYLOAD_SIZE / 4 + 16; ++srv) { pat.pmts[srv] = ts::PID(srv + 2); } // Serialize the PAT. ts::BinaryTablePtr patBin(new(ts::BinaryTable)); CPPUNIT_ASSERT(!patBin.isNull()); pat.serialize(*patBin); CPPUNIT_ASSERT(patBin->isValid()); CPPUNIT_ASSERT_EQUAL(size_t(2), patBin->sectionCount()); // Build a section file. ts::SectionFile file; file.add(patBin); CPPUNIT_ASSERT_EQUAL(size_t(1), file.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(2), file.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(0), file.orphanSections().size()); file.add(patBin->sectionAt(0)); CPPUNIT_ASSERT_EQUAL(size_t(1), file.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(3), file.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(1), file.orphanSections().size()); file.add(patBin->sectionAt(1)); CPPUNIT_ASSERT_EQUAL(size_t(2), file.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(4), file.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(0), file.orphanSections().size()); // Build a TDT (short section). const ts::Time tdtTime(ts::Time::Fields(2017, 12, 25, 14, 55, 27)); ts::TDT tdt(tdtTime); ts::BinaryTablePtr tdtBin(new(ts::BinaryTable)); CPPUNIT_ASSERT(!tdtBin.isNull()); tdt.serialize(*tdtBin); CPPUNIT_ASSERT(tdtBin->isValid()); CPPUNIT_ASSERT_EQUAL(size_t(1), tdtBin->sectionCount()); file.add(tdtBin); CPPUNIT_ASSERT_EQUAL(size_t(3), file.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(5), file.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(0), file.orphanSections().size()); // Save files. utest::Out() << "SectionFileTest::testBuildSections: saving " << _tempFileNameBin << std::endl; CPPUNIT_ASSERT(!ts::FileExists(_tempFileNameBin)); CPPUNIT_ASSERT(file.saveBinary(_tempFileNameBin, report())); CPPUNIT_ASSERT(ts::FileExists(_tempFileNameBin)); utest::Out() << "SectionFileTest::testBuildSections: saving " << _tempFileNameXML << std::endl; CPPUNIT_ASSERT(!ts::FileExists(_tempFileNameXML)); CPPUNIT_ASSERT(file.saveXML(_tempFileNameXML, report())); CPPUNIT_ASSERT(ts::FileExists(_tempFileNameXML)); // Reload files. ts::SectionFile binFile; CPPUNIT_ASSERT(binFile.loadBinary(_tempFileNameBin, report(), ts::CRC32::CHECK)); CPPUNIT_ASSERT_EQUAL(size_t(3), binFile.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(5), binFile.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(0), binFile.orphanSections().size()); ts::SectionFile xmlFile; CPPUNIT_ASSERT(xmlFile.loadXML(_tempFileNameXML, report())); CPPUNIT_ASSERT_EQUAL(size_t(3), xmlFile.tables().size()); CPPUNIT_ASSERT_EQUAL(size_t(5), xmlFile.sections().size()); CPPUNIT_ASSERT_EQUAL(size_t(0), xmlFile.orphanSections().size()); for (size_t i = 0; i < file.tables().size(); ++i) { CPPUNIT_ASSERT(*file.tables()[i] == *binFile.tables()[i]); CPPUNIT_ASSERT(*file.tables()[i] == *xmlFile.tables()[i]); } for (size_t i = 0; i < file.sections().size(); ++i) { CPPUNIT_ASSERT(*file.sections()[i] == *binFile.sections()[i]); CPPUNIT_ASSERT(*file.sections()[i] == *xmlFile.sections()[i]); } ts::PAT binPAT(*binFile.tables()[0]); CPPUNIT_ASSERT(binPAT.isValid()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), binPAT.version); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), binPAT.ts_id); CPPUNIT_ASSERT_EQUAL(ts::PID(ts::PID_NIT), binPAT.nit_pid); CPPUNIT_ASSERT(binPAT.pmts == pat.pmts); ts::PAT xmlPAT(*xmlFile.tables()[0]); CPPUNIT_ASSERT(xmlPAT.isValid()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), xmlPAT.version); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), xmlPAT.ts_id); CPPUNIT_ASSERT_EQUAL(ts::PID(ts::PID_NIT), xmlPAT.nit_pid); CPPUNIT_ASSERT(xmlPAT.pmts == pat.pmts); ts::TDT binTDT(*binFile.tables()[2]); CPPUNIT_ASSERT(tdtTime == binTDT.utc_time); ts::TDT xmlTDT(*xmlFile.tables()[2]); CPPUNIT_ASSERT(tdtTime == xmlTDT.utc_time); }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
2c0bb099185e3bd2fb292ea3ab3bda562795aea0
0a8316e275223d587d2eef264275ebea08c3c73e
/src/CZI_ASSERT.hpp
dbd2d61e3e6d176dacda26d8e5cdd23ac948fc7a
[ "MIT" ]
permissive
chanzuckerberg/ExpressionMatrix2
facda7a9b7aca1a5aa19e205d71910ad1e3d96f3
88af759868409258dde33642bce0d84ff5bdd17b
refs/heads/master
2021-03-24T12:57:04.546098
2019-06-20T20:13:43
2019-06-20T20:13:43
94,104,347
32
3
MIT
2018-02-28T18:59:09
2017-06-12T14:17:33
C++
UTF-8
C++
false
false
1,078
hpp
// Definition of macro CZI_ASSERT. // It is always compiled in, regardless of compilation settings. // It throws a standard exception if the assertion fails. #ifndef CZI_EXPRESSION_MATRIX2_CZI_ASSERT_HPP #define CZI_EXPRESSION_MATRIX2_CZI_ASSERT_HPP #include <boost/lexical_cast.hpp> #include <stdexcept> #include <string> // Gcc (for backtraces). #include "execinfo.h" namespace ChanZuckerberg { namespace ExpressionMatrix2 { inline void writeBackTrace(); } } #define CZI_ASSERT(expression) ((expression) ? (static_cast<void>(0)) : \ (/*writeBackTrace(),*/ throw std::runtime_error(std::string("Assertion failed: ") + #expression + " at " + BOOST_CURRENT_FUNCTION + " in " + __FILE__ + " line " + boost::lexical_cast<std::string>(__LINE__)))) #if 0 inline void ChanZuckerberg::ExpressionMatrix2::writeBackTrace() { const int bufferSize = 64; // To avoid extremely long, useless backtraces. void* buffer[bufferSize]; ::backtrace(buffer, bufferSize); ::backtrace_symbols_fd(buffer, bufferSize, ::fileno(::stdout)); } #endif #endif
[ "paoloczi@users.noreply.github.com" ]
paoloczi@users.noreply.github.com
86260e58fa5697a5bc493a3ac6a7fd6473a90207
b6a144a71fb6d0f8708cd5741abdf4e57d1b37bd
/10/1/main.cpp
28b5f9098652ff3a927b2ac2e28a62f7071d6ff1
[]
no_license
jBosak98/WUST-object-oriented-programming
63805758083bdafedd0bf6f51fd39a61849962b9
533baf3b9ab12c0565209b1f8e5a81bb43d4fbb5
refs/heads/master
2020-04-02T14:52:49.842019
2019-01-11T14:47:43
2019-01-11T14:47:43
154,542,053
2
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include "main.h" int main(){ // startTest(); std::string input; std::getline(std::cin,input); NPN *npn = new NPN(input); Calculator calc = Calculator(); // npn->getReverseStack()->show(); double res = calc.calc(npn->getReverseStack()); std::cout<<"\nResult: "<<res<<"\n"; return 0; }
[ "jbosak98@gmail.com" ]
jbosak98@gmail.com
1acbca605e6d1f8c2333250d0371f8aca4e1b3df
6e2f8b62a9977ae6c51c6bcbe41daccc92a87677
/ParabellumEngine/ParabellumEngine/ExtendedObject.h
b3c525bb5aa0b0185aa44e942db6ef87d79e7be6
[ "MIT" ]
permissive
Qazwar/ParabellumFramework
8a455ea5e1ac0dab9c466604d2f443317e2a57bd
7b55003bb04e696a68f436b9ec98a05e026526fd
refs/heads/master
2022-01-26T06:28:53.040419
2019-06-29T11:05:34
2019-06-29T11:05:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
962
h
#ifndef _EXTENDEDOBJECT_H_ #define _EXTENDEDOBJECT_H_ #include "../ParabellumFramework/ResourceManager.h" #include "../ParabellumFramework/BoundingVolumes.h" #include "../ParabellumFramework/BoundingFrustum.h" #include "../ParabellumFramework/IntersectCodes.h" #include "../ParabellumFramework/MathHelper.h" #include "../ParabellumFramework/Model.h" #include "Component3D.h" #include "EModelPart.h" #include <string> namespace ParabellumEngine { namespace Components { using namespace ParabellumFramework; // // ExtendedObject is composited from models, lights, particles and so on // We can have complex animated character which hangles candle which generates smoke particles // class XYZ_API ExtendedObject : public Component3D { public: ExtendedObject(); ~ExtendedObject(); private: ExtendedObject(const ExtendedObject&) = delete; public: private: // // Gets and Sets // public: }; } } #endif
[ "szuplak@gmail.com" ]
szuplak@gmail.com
7fb27ccc7443996f385d00e3c7d29e0c5d7abcad
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chromecast/media/audio/cast_audio_manager_alsa.cc
611290079ef94c17fc0056a093ea96d28b3723aa
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
8,145
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/audio/cast_audio_manager_alsa.h" #include <string> #include <utility> #include "base/memory/free_deleter.h" #include "base/stl_util.h" #include "chromecast/media/audio/audio_buildflags.h" #include "chromecast/media/cma/backend/cma_backend_factory.h" #include "media/audio/alsa/alsa_input.h" #include "media/audio/alsa/alsa_wrapper.h" namespace chromecast { namespace media { namespace { // TODO(alokp): Query the preferred value from media backend. const int kDefaultSampleRate = BUILDFLAG(AUDIO_INPUT_SAMPLE_RATE); // TODO(jyw): Query the preferred value from media backend. static const int kDefaultInputBufferSize = 1024; // Since "default" and "dmix" devices are virtual devices mapped to real // devices, we remove them from the list to avoiding duplicate counting. static const char* kInvalidAudioInputDevices[] = { "default", "dmix", "null", }; } // namespace CastAudioManagerAlsa::CastAudioManagerAlsa( std::unique_ptr<::media::AudioThread> audio_thread, ::media::AudioLogFactory* audio_log_factory, base::RepeatingCallback<CmaBackendFactory*()> backend_factory_getter, GetSessionIdCallback get_session_id_callback, scoped_refptr<base::SingleThreadTaskRunner> browser_task_runner, scoped_refptr<base::SingleThreadTaskRunner> media_task_runner, service_manager::Connector* connector, bool use_mixer) : CastAudioManager(std::move(audio_thread), audio_log_factory, std::move(backend_factory_getter), std::move(get_session_id_callback), browser_task_runner, media_task_runner, connector, use_mixer), wrapper_(new ::media::AlsaWrapper()) {} CastAudioManagerAlsa::~CastAudioManagerAlsa() {} bool CastAudioManagerAlsa::HasAudioInputDevices() { return true; } void CastAudioManagerAlsa::GetAudioInputDeviceNames( ::media::AudioDeviceNames* device_names) { DCHECK(device_names->empty()); GetAlsaAudioDevices(kStreamCapture, device_names); } ::media::AudioParameters CastAudioManagerAlsa::GetInputStreamParameters( const std::string& device_id) { // TODO(jyw): Be smarter about sample rate instead of hardcoding it. // Need to send a valid AudioParameters object even when it will be unused. return ::media::AudioParameters( ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, ::media::CHANNEL_LAYOUT_STEREO, kDefaultSampleRate, kDefaultInputBufferSize); } ::media::AudioInputStream* CastAudioManagerAlsa::MakeLinearInputStream( const ::media::AudioParameters& params, const std::string& device_id, const ::media::AudioManager::LogCallback& log_callback) { DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LINEAR, params.format()); return MakeInputStream(params, device_id); } ::media::AudioInputStream* CastAudioManagerAlsa::MakeLowLatencyInputStream( const ::media::AudioParameters& params, const std::string& device_id, const ::media::AudioManager::LogCallback& log_callback) { DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); return MakeInputStream(params, device_id); } ::media::AudioInputStream* CastAudioManagerAlsa::MakeInputStream( const ::media::AudioParameters& params, const std::string& device_id) { std::string device_name = (device_id == ::media::AudioDeviceDescription::kDefaultDeviceId) ? ::media::AlsaPcmInputStream::kAutoSelectDevice : device_id; return new ::media::AlsaPcmInputStream(this, device_name, params, wrapper_.get()); } void CastAudioManagerAlsa::GetAlsaAudioDevices( StreamType type, ::media::AudioDeviceNames* device_names) { // Constants specified by the ALSA API for device hints. static const char kPcmInterfaceName[] = "pcm"; int card = -1; // Loop through the sound cards to get ALSA device hints. while (!wrapper_->CardNext(&card) && card >= 0) { void** hints = NULL; int error = wrapper_->DeviceNameHint(card, kPcmInterfaceName, &hints); if (!error) { GetAlsaDevicesInfo(type, hints, device_names); // Destroy the hints now that we're done with it. wrapper_->DeviceNameFreeHint(hints); } else { DLOG(WARNING) << "GetAlsaAudioDevices: unable to get device hints: " << wrapper_->StrError(error); } } } void CastAudioManagerAlsa::GetAlsaDevicesInfo( StreamType type, void** hints, ::media::AudioDeviceNames* device_names) { static const char kIoHintName[] = "IOID"; static const char kNameHintName[] = "NAME"; static const char kDescriptionHintName[] = "DESC"; const char* unwanted_device_type = UnwantedDeviceTypeWhenEnumerating(type); for (void** hint_iter = hints; *hint_iter != NULL; hint_iter++) { // Only examine devices of the right type. Valid values are // "Input", "Output", and NULL which means both input and output. std::unique_ptr<char, base::FreeDeleter> io( wrapper_->DeviceNameGetHint(*hint_iter, kIoHintName)); if (io != NULL && strcmp(unwanted_device_type, io.get()) == 0) continue; // Found a device, prepend the default device since we always want // it to be on the top of the list for all platforms. And there is // no duplicate counting here since it is only done if the list is // still empty. Note, pulse has exclusively opened the default // device, so we must open the device via the "default" moniker. if (device_names->empty()) device_names->push_front(::media::AudioDeviceName::CreateDefault()); // Get the unique device name for the device. std::unique_ptr<char, base::FreeDeleter> unique_device_name( wrapper_->DeviceNameGetHint(*hint_iter, kNameHintName)); // Find out if the device is available. if (IsAlsaDeviceAvailable(type, unique_device_name.get())) { // Get the description for the device. std::unique_ptr<char, base::FreeDeleter> desc( wrapper_->DeviceNameGetHint(*hint_iter, kDescriptionHintName)); ::media::AudioDeviceName name; name.unique_id = unique_device_name.get(); if (desc) { // Use the more user friendly description as name. // Replace '\n' with '-'. char* pret = strchr(desc.get(), '\n'); if (pret) *pret = '-'; name.device_name = desc.get(); } else { // Virtual devices don't necessarily have descriptions. // Use their names instead. name.device_name = unique_device_name.get(); } // Store the device information. device_names->push_back(name); } } } // static bool CastAudioManagerAlsa::IsAlsaDeviceAvailable(StreamType type, const char* device_name) { if (!device_name) return false; // We do prefix matches on the device name to see whether to include // it or not. if (type == kStreamCapture) { // Check if the device is in the list of invalid devices. for (size_t i = 0; i < base::size(kInvalidAudioInputDevices); ++i) { if (strncmp(kInvalidAudioInputDevices[i], device_name, strlen(kInvalidAudioInputDevices[i])) == 0) return false; } return true; } else { DCHECK_EQ(kStreamPlayback, type); // We prefer the device type that maps straight to hardware but // goes through software conversion if needed (e.g. incompatible // sample rate). // TODO(joi): Should we prefer "hw" instead? static const char kDeviceTypeDesired[] = "plughw"; return strncmp(kDeviceTypeDesired, device_name, base::size(kDeviceTypeDesired) - 1) == 0; } } // static const char* CastAudioManagerAlsa::UnwantedDeviceTypeWhenEnumerating( StreamType wanted_type) { return wanted_type == kStreamPlayback ? "Input" : "Output"; } } // namespace media } // namespace chromecast
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
7e0b24de13688143aefe9097f0643e0e15ecdda1
65cf3bce7910098405627e08b372553e48abad7d
/POJ/2954 Triangle.cpp
591768cad6078f78424c9216daa239a98ea273c7
[]
no_license
bluemix/Online-Judge
77275c1a3e94272a07ba10de16f1d068217b64de
11f6c0bf1e8adf5b0136670bcebef975b7e0f3a1
refs/heads/master
2021-01-12T00:48:32.642462
2015-09-15T13:18:47
2015-09-15T13:18:47
78,298,357
0
0
null
2017-01-07T19:13:15
2017-01-07T19:13:14
null
UTF-8
C++
false
false
2,596
cpp
/* 14219949 840502 2954 Accepted 168K 0MS C++ 1734B 2015-05-21 16:54:30 */ #include<bits\stdc++.h> using namespace std; const double PI = acos(-1.0); const double EPS = 1e-9; int sign(double x){ return fabs(x) < EPS ? 0 : (x > 0 ? 1 : -1); } // Vector struct Vector{ double x, y; Vector(){} Vector(double x, double y) :x(x), y(y){} Vector operator + (const Vector &a) { return Vector(x + a.x, y + a.y); } Vector operator - (const Vector &a) { return Vector(x - a.x, y - a.y); } double operator * (const Vector &a) { return x * a.y - y * a.x; } Vector operator * (const double &a){ return Vector(x*a, y*a); } double operator % (const Vector &a) { return x * a.x + y * a.y; } Vector operator / (double a){ return Vector(x / a, y / a); } bool operator == (Vector &a) { return sign(x - a.x) == 0 && sign(y - a.y) == 0; } }; double gcd(double a, double b){ int aa = a + EPS, bb = b + EPS, r; do{ r = aa % bb; aa = bb; bb = r; } while (r != 0); return aa; } double pointOnBound(Vector p){ if (sign(p.x) == 0) return abs(p.y); if (sign(p.y) == 0) return abs(p.x); return gcd(abs(p.x), abs(p.y)); } int main(){ Vector a, b, c; while (scanf("%lf%lf%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y, &c.x, &c.y) == 6){ if (a.x == 0 && a.y == 0 && b.x == 0 && b.y == 0 && c.x == 0 && c.y == 0) break; double area = abs((b - a) * (c - a)) / 2.0; printf("%d\n", (int)(area - (pointOnBound(a - b) + pointOnBound(b - c) + pointOnBound(c - a)) / 2 + 1)); } return 0; } /* Triangle Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 5377 Accepted: 2330 Description A lattice point is an ordered pair (x, y) where x and y are both integers. Given the coordinates of the vertices of a triangle (which happen to be lattice points), you are to count the number of lattice points which lie completely inside of the triangle (points on the edges or vertices of the triangle do not count). Input The input test file will contain multiple test cases. Each input test case consists of six integers x1, y1, x2, y2, x3, and y3, where (x1, y1), (x2, y2), and (x3, y3) are the coordinates of vertices of the triangle. All triangles in the input will be non-degenerate (will have positive area), and −15000 ≤ x1, y1, x2, y2, x3, y3 ≤ 15000. The end-of-file is marked by a test case with x1 = y1 = x2 = y2 = x3 = y3 = 0 and should not be processed. Output For each input case, the program should print the number of internal lattice points on a single line. Sample Input 0 0 1 0 0 1 0 0 5 0 0 5 0 0 0 0 0 0 Sample Output 0 6 Source Stanford Local 2004 */
[ "sharknevercries@gmail.com" ]
sharknevercries@gmail.com
dec62566be4b34ab79e13b51f1a9e2b465f79b2b
0f700b0cbac698f4d4d3964ba66096369c0ee902
/src/test/function-pointer/fp.cc
160ca817b0a41e062cac74be5cac95b7fd20e7ae
[]
no_license
jam31118/cu-tridiag
55a8d62882a68d8ea5a8cd252a864249faaefc51
0bffcb2283a2102a40a63c272e37d9875e2779ab
refs/heads/master
2020-04-14T19:38:02.300012
2019-02-07T18:28:53
2019-02-07T18:28:53
164,065,259
0
0
null
null
null
null
UTF-8
C++
false
false
342
cc
#include <iostream> #include <complex> #include "fp.hh" int main() { double x = 1, y = -2; int xi = 1, yi = -2; std::complex<double> z1, z2; z1 = eval_tem<double>(&x, &y, &comb_double); z2 = eval_tem<int>(&xi, &yi, &comb_int); std::cout << "z1: " << z1 << std::endl; std::cout << "z2: " << z2 << std::endl; return 0; }
[ "jam45@naver.com" ]
jam45@naver.com
f25104902e91cb0835602d4bd00f12f489e1a84d
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/alt-ww-rw+rel+acq-rel+acq-o+o-wb-rel+acq-o+o-wb-o.c.cbmc_out.cpp
dce073af0be0f6750f0aa31f297e9b4a95af4236
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
77,510
cpp
// Global variabls: // 0:vars:5 // 5:atom_1_X0_1:1 // 6:atom_2_X0_1:1 // 7:atom_4_X0_1:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 // 3:thr3:1 // 4:thr4:1 // 5:thr5:1 #define ADDRSIZE 8 #define LOCALADDRSIZE 6 #define NTHREAD 7 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; local_mem[3+0] = 0; local_mem[4+0] = 0; local_mem[5+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; int r0= 0; char creg_r0; char creg__r0__1_; int r1= 0; char creg_r1; char creg__r1__1_; int r2= 0; char creg_r2; char creg__r2__1_; int r3= 0; char creg_r3; int r4= 0; char creg_r4; int r5= 0; char creg_r5; int r6= 0; char creg_r6; int r7= 0; char creg_r7; int r8= 0; char creg_r8; int r9= 0; char creg_r9; int r10= 0; char creg_r10; int r11= 0; char creg_r11; int r12= 0; char creg_r12; char creg__r12__2_; int r13= 0; char creg_r13; int r14= 0; char creg_r14; char creg__r14__2_; int r15= 0; char creg_r15; char creg__r15__1_; int r16= 0; char creg_r16; int r17= 0; char creg_r17; int r18= 0; char creg_r18; int r19= 0; char creg_r19; int r20= 0; char creg_r20; char creg__r20__1_; int r21= 0; char creg_r21; char old_cctrl= 0; char old_cr= 0; char old_cdy= 0; char old_cw= 0; char new_creg= 0; buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); buff(4,0) = 0; pw(4,0) = 0; cr(4,0) = 0; iw(4,0) = 0; cw(4,0) = 0; cx(4,0) = 0; is(4,0) = 0; cs(4,0) = 0; crmax(4,0) = 0; buff(4,1) = 0; pw(4,1) = 0; cr(4,1) = 0; iw(4,1) = 0; cw(4,1) = 0; cx(4,1) = 0; is(4,1) = 0; cs(4,1) = 0; crmax(4,1) = 0; buff(4,2) = 0; pw(4,2) = 0; cr(4,2) = 0; iw(4,2) = 0; cw(4,2) = 0; cx(4,2) = 0; is(4,2) = 0; cs(4,2) = 0; crmax(4,2) = 0; buff(4,3) = 0; pw(4,3) = 0; cr(4,3) = 0; iw(4,3) = 0; cw(4,3) = 0; cx(4,3) = 0; is(4,3) = 0; cs(4,3) = 0; crmax(4,3) = 0; buff(4,4) = 0; pw(4,4) = 0; cr(4,4) = 0; iw(4,4) = 0; cw(4,4) = 0; cx(4,4) = 0; is(4,4) = 0; cs(4,4) = 0; crmax(4,4) = 0; buff(4,5) = 0; pw(4,5) = 0; cr(4,5) = 0; iw(4,5) = 0; cw(4,5) = 0; cx(4,5) = 0; is(4,5) = 0; cs(4,5) = 0; crmax(4,5) = 0; buff(4,6) = 0; pw(4,6) = 0; cr(4,6) = 0; iw(4,6) = 0; cw(4,6) = 0; cx(4,6) = 0; is(4,6) = 0; cs(4,6) = 0; crmax(4,6) = 0; buff(4,7) = 0; pw(4,7) = 0; cr(4,7) = 0; iw(4,7) = 0; cw(4,7) = 0; cx(4,7) = 0; is(4,7) = 0; cs(4,7) = 0; crmax(4,7) = 0; cl[4] = 0; cdy[4] = 0; cds[4] = 0; cdl[4] = 0; cisb[4] = 0; caddr[4] = 0; cctrl[4] = 0; cstart[4] = get_rng(0,NCONTEXT-1); creturn[4] = get_rng(0,NCONTEXT-1); buff(5,0) = 0; pw(5,0) = 0; cr(5,0) = 0; iw(5,0) = 0; cw(5,0) = 0; cx(5,0) = 0; is(5,0) = 0; cs(5,0) = 0; crmax(5,0) = 0; buff(5,1) = 0; pw(5,1) = 0; cr(5,1) = 0; iw(5,1) = 0; cw(5,1) = 0; cx(5,1) = 0; is(5,1) = 0; cs(5,1) = 0; crmax(5,1) = 0; buff(5,2) = 0; pw(5,2) = 0; cr(5,2) = 0; iw(5,2) = 0; cw(5,2) = 0; cx(5,2) = 0; is(5,2) = 0; cs(5,2) = 0; crmax(5,2) = 0; buff(5,3) = 0; pw(5,3) = 0; cr(5,3) = 0; iw(5,3) = 0; cw(5,3) = 0; cx(5,3) = 0; is(5,3) = 0; cs(5,3) = 0; crmax(5,3) = 0; buff(5,4) = 0; pw(5,4) = 0; cr(5,4) = 0; iw(5,4) = 0; cw(5,4) = 0; cx(5,4) = 0; is(5,4) = 0; cs(5,4) = 0; crmax(5,4) = 0; buff(5,5) = 0; pw(5,5) = 0; cr(5,5) = 0; iw(5,5) = 0; cw(5,5) = 0; cx(5,5) = 0; is(5,5) = 0; cs(5,5) = 0; crmax(5,5) = 0; buff(5,6) = 0; pw(5,6) = 0; cr(5,6) = 0; iw(5,6) = 0; cw(5,6) = 0; cx(5,6) = 0; is(5,6) = 0; cs(5,6) = 0; crmax(5,6) = 0; buff(5,7) = 0; pw(5,7) = 0; cr(5,7) = 0; iw(5,7) = 0; cw(5,7) = 0; cx(5,7) = 0; is(5,7) = 0; cs(5,7) = 0; crmax(5,7) = 0; cl[5] = 0; cdy[5] = 0; cds[5] = 0; cdl[5] = 0; cisb[5] = 0; caddr[5] = 0; cctrl[5] = 0; cstart[5] = get_rng(0,NCONTEXT-1); creturn[5] = get_rng(0,NCONTEXT-1); buff(6,0) = 0; pw(6,0) = 0; cr(6,0) = 0; iw(6,0) = 0; cw(6,0) = 0; cx(6,0) = 0; is(6,0) = 0; cs(6,0) = 0; crmax(6,0) = 0; buff(6,1) = 0; pw(6,1) = 0; cr(6,1) = 0; iw(6,1) = 0; cw(6,1) = 0; cx(6,1) = 0; is(6,1) = 0; cs(6,1) = 0; crmax(6,1) = 0; buff(6,2) = 0; pw(6,2) = 0; cr(6,2) = 0; iw(6,2) = 0; cw(6,2) = 0; cx(6,2) = 0; is(6,2) = 0; cs(6,2) = 0; crmax(6,2) = 0; buff(6,3) = 0; pw(6,3) = 0; cr(6,3) = 0; iw(6,3) = 0; cw(6,3) = 0; cx(6,3) = 0; is(6,3) = 0; cs(6,3) = 0; crmax(6,3) = 0; buff(6,4) = 0; pw(6,4) = 0; cr(6,4) = 0; iw(6,4) = 0; cw(6,4) = 0; cx(6,4) = 0; is(6,4) = 0; cs(6,4) = 0; crmax(6,4) = 0; buff(6,5) = 0; pw(6,5) = 0; cr(6,5) = 0; iw(6,5) = 0; cw(6,5) = 0; cx(6,5) = 0; is(6,5) = 0; cs(6,5) = 0; crmax(6,5) = 0; buff(6,6) = 0; pw(6,6) = 0; cr(6,6) = 0; iw(6,6) = 0; cw(6,6) = 0; cx(6,6) = 0; is(6,6) = 0; cs(6,6) = 0; crmax(6,6) = 0; buff(6,7) = 0; pw(6,7) = 0; cr(6,7) = 0; iw(6,7) = 0; cw(6,7) = 0; cx(6,7) = 0; is(6,7) = 0; cs(6,7) = 0; crmax(6,7) = 0; cl[6] = 0; cdy[6] = 0; cds[6] = 0; cdl[6] = 0; cisb[6] = 0; caddr[6] = 0; cctrl[6] = 0; cstart[6] = get_rng(0,NCONTEXT-1); creturn[6] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(0+3,0) = 0; mem(0+4,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); co(4,0) = 0; delta(4,0) = -1; mem(4,1) = meminit(4,1); co(4,1) = coinit(4,1); delta(4,1) = deltainit(4,1); mem(4,2) = meminit(4,2); co(4,2) = coinit(4,2); delta(4,2) = deltainit(4,2); mem(4,3) = meminit(4,3); co(4,3) = coinit(4,3); delta(4,3) = deltainit(4,3); mem(4,4) = meminit(4,4); co(4,4) = coinit(4,4); delta(4,4) = deltainit(4,4); co(5,0) = 0; delta(5,0) = -1; mem(5,1) = meminit(5,1); co(5,1) = coinit(5,1); delta(5,1) = deltainit(5,1); mem(5,2) = meminit(5,2); co(5,2) = coinit(5,2); delta(5,2) = deltainit(5,2); mem(5,3) = meminit(5,3); co(5,3) = coinit(5,3); delta(5,3) = deltainit(5,3); mem(5,4) = meminit(5,4); co(5,4) = coinit(5,4); delta(5,4) = deltainit(5,4); co(6,0) = 0; delta(6,0) = -1; mem(6,1) = meminit(6,1); co(6,1) = coinit(6,1); delta(6,1) = deltainit(6,1); mem(6,2) = meminit(6,2); co(6,2) = coinit(6,2); delta(6,2) = deltainit(6,2); mem(6,3) = meminit(6,3); co(6,3) = coinit(6,3); delta(6,3) = deltainit(6,3); mem(6,4) = meminit(6,4); co(6,4) = coinit(6,4); delta(6,4) = deltainit(6,4); co(7,0) = 0; delta(7,0) = -1; mem(7,1) = meminit(7,1); co(7,1) = coinit(7,1); delta(7,1) = deltainit(7,1); mem(7,2) = meminit(7,2); co(7,2) = coinit(7,2); delta(7,2) = deltainit(7,2); mem(7,3) = meminit(7,3); co(7,3) = coinit(7,3); delta(7,3) = deltainit(7,3); mem(7,4) = meminit(7,4); co(7,4) = coinit(7,4); delta(7,4) = deltainit(7,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !38, metadata !DIExpression()), !dbg !44 // br label %label_1, !dbg !45 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !43), !dbg !46 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0), metadata !39, metadata !DIExpression()), !dbg !47 // call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !47 // store atomic i64 1, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !48 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,0+2)); ASSUME(cw(1,0) >= cr(1,0+3)); ASSUME(cw(1,0) >= cr(1,0+4)); ASSUME(cw(1,0) >= cr(1,5+0)); ASSUME(cw(1,0) >= cr(1,6+0)); ASSUME(cw(1,0) >= cr(1,7+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,0+2)); ASSUME(cw(1,0) >= cw(1,0+3)); ASSUME(cw(1,0) >= cw(1,0+4)); ASSUME(cw(1,0) >= cw(1,5+0)); ASSUME(cw(1,0) >= cw(1,6+0)); ASSUME(cw(1,0) >= cw(1,7+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !49 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !52, metadata !DIExpression()), !dbg !62 // br label %label_2, !dbg !50 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !61), !dbg !64 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0), metadata !54, metadata !DIExpression()), !dbg !65 // %0 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !53 // LD: Guess // : Acquire old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l27_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); ASSUME(cr(2,0) >= cx(2,0)); ASSUME(cr(2,0) >= cs(2,0+0)); ASSUME(cr(2,0) >= cs(2,0+1)); ASSUME(cr(2,0) >= cs(2,0+2)); ASSUME(cr(2,0) >= cs(2,0+3)); ASSUME(cr(2,0) >= cs(2,0+4)); ASSUME(cr(2,0) >= cs(2,5+0)); ASSUME(cr(2,0) >= cs(2,6+0)); ASSUME(cr(2,0) >= cs(2,7+0)); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } cl[2] = max(cl[2],cr(2,0)); ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !56, metadata !DIExpression()), !dbg !65 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !53, metadata !DIExpression()), !dbg !62 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1), metadata !57, metadata !DIExpression()), !dbg !68 // call void @llvm.dbg.value(metadata i64 1, metadata !59, metadata !DIExpression()), !dbg !68 // store atomic i64 1, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !56 // ST: Guess // : Release iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l28_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l28_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); ASSUME(cw(2,0+1*1) >= cr(2,0+0)); ASSUME(cw(2,0+1*1) >= cr(2,0+1)); ASSUME(cw(2,0+1*1) >= cr(2,0+2)); ASSUME(cw(2,0+1*1) >= cr(2,0+3)); ASSUME(cw(2,0+1*1) >= cr(2,0+4)); ASSUME(cw(2,0+1*1) >= cr(2,5+0)); ASSUME(cw(2,0+1*1) >= cr(2,6+0)); ASSUME(cw(2,0+1*1) >= cr(2,7+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+1)); ASSUME(cw(2,0+1*1) >= cw(2,0+2)); ASSUME(cw(2,0+1*1) >= cw(2,0+3)); ASSUME(cw(2,0+1*1) >= cw(2,0+4)); ASSUME(cw(2,0+1*1) >= cw(2,5+0)); ASSUME(cw(2,0+1*1) >= cw(2,6+0)); ASSUME(cw(2,0+1*1) >= cw(2,7+0)); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 1; mem(0+1*1,cw(2,0+1*1)) = 1; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; is(2,0+1*1) = iw(2,0+1*1); cs(2,0+1*1) = cw(2,0+1*1); ASSUME(creturn[2] >= cw(2,0+1*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !57 creg__r0__1_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !57 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !60, metadata !DIExpression()), !dbg !62 // store i32 %conv1, i32* @atom_1_X0_1, align 4, !dbg !58, !tbaa !59 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l30_c15 old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l30_c15 // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= creg__r0__1_); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r0==1); mem(5,cw(2,5)) = (r0==1); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // ret i8* null, !dbg !63 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !79, metadata !DIExpression()), !dbg !89 // br label %label_3, !dbg !50 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !88), !dbg !91 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1), metadata !81, metadata !DIExpression()), !dbg !92 // %0 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !53 // LD: Guess // : Acquire old_cr = cr(3,0+1*1); cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l36_c15 // Check ASSUME(active[cr(3,0+1*1)] == 3); ASSUME(cr(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cr(3,0+1*1) >= 0); ASSUME(cr(3,0+1*1) >= cdy[3]); ASSUME(cr(3,0+1*1) >= cisb[3]); ASSUME(cr(3,0+1*1) >= cdl[3]); ASSUME(cr(3,0+1*1) >= cl[3]); ASSUME(cr(3,0+1*1) >= cx(3,0+1*1)); ASSUME(cr(3,0+1*1) >= cs(3,0+0)); ASSUME(cr(3,0+1*1) >= cs(3,0+1)); ASSUME(cr(3,0+1*1) >= cs(3,0+2)); ASSUME(cr(3,0+1*1) >= cs(3,0+3)); ASSUME(cr(3,0+1*1) >= cs(3,0+4)); ASSUME(cr(3,0+1*1) >= cs(3,5+0)); ASSUME(cr(3,0+1*1) >= cs(3,6+0)); ASSUME(cr(3,0+1*1) >= cs(3,7+0)); // Update creg_r1 = cr(3,0+1*1); crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+1*1) < cw(3,0+1*1)) { r1 = buff(3,0+1*1); ASSUME((!(( (cw(3,0+1*1) < 1) && (1 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(3,0+1*1) < 2) && (2 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(3,0+1*1) < 3) && (3 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(3,0+1*1) < 4) && (4 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) { ASSUME(cr(3,0+1*1) >= old_cr); } pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1)); r1 = mem(0+1*1,cr(3,0+1*1)); } cl[3] = max(cl[3],cr(3,0+1*1)); ASSUME(creturn[3] >= cr(3,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !83, metadata !DIExpression()), !dbg !92 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !80, metadata !DIExpression()), !dbg !89 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2), metadata !84, metadata !DIExpression()), !dbg !95 // call void @llvm.dbg.value(metadata i64 1, metadata !86, metadata !DIExpression()), !dbg !95 // store atomic i64 1, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !56 // ST: Guess iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l37_c3 old_cw = cw(3,0+2*1); cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l37_c3 // Check ASSUME(active[iw(3,0+2*1)] == 3); ASSUME(active[cw(3,0+2*1)] == 3); ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(cw(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cw(3,0+2*1) >= old_cw); ASSUME(cw(3,0+2*1) >= cr(3,0+2*1)); ASSUME(cw(3,0+2*1) >= cl[3]); ASSUME(cw(3,0+2*1) >= cisb[3]); ASSUME(cw(3,0+2*1) >= cdy[3]); ASSUME(cw(3,0+2*1) >= cdl[3]); ASSUME(cw(3,0+2*1) >= cds[3]); ASSUME(cw(3,0+2*1) >= cctrl[3]); ASSUME(cw(3,0+2*1) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0+2*1) = 1; mem(0+2*1,cw(3,0+2*1)) = 1; co(0+2*1,cw(3,0+2*1))+=1; delta(0+2*1,cw(3,0+2*1)) = -1; ASSUME(creturn[3] >= cw(3,0+2*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !57 creg__r1__1_ = max(0,creg_r1); // %conv1 = zext i1 %cmp to i32, !dbg !57 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !87, metadata !DIExpression()), !dbg !89 // store i32 %conv1, i32* @atom_2_X0_1, align 4, !dbg !58, !tbaa !59 // ST: Guess iw(3,6) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c15 old_cw = cw(3,6); cw(3,6) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c15 // Check ASSUME(active[iw(3,6)] == 3); ASSUME(active[cw(3,6)] == 3); ASSUME(sforbid(6,cw(3,6))== 0); ASSUME(iw(3,6) >= creg__r1__1_); ASSUME(iw(3,6) >= 0); ASSUME(cw(3,6) >= iw(3,6)); ASSUME(cw(3,6) >= old_cw); ASSUME(cw(3,6) >= cr(3,6)); ASSUME(cw(3,6) >= cl[3]); ASSUME(cw(3,6) >= cisb[3]); ASSUME(cw(3,6) >= cdy[3]); ASSUME(cw(3,6) >= cdl[3]); ASSUME(cw(3,6) >= cds[3]); ASSUME(cw(3,6) >= cctrl[3]); ASSUME(cw(3,6) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,6) = (r1==1); mem(6,cw(3,6)) = (r1==1); co(6,cw(3,6))+=1; delta(6,cw(3,6)) = -1; ASSUME(creturn[3] >= cw(3,6)); // ret i8* null, !dbg !63 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 4 int ret_thread_4 = 0; cdy[4] = get_rng(0,NCONTEXT-1); ASSUME(cdy[4] >= cstart[4]); T4BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !102, metadata !DIExpression()), !dbg !110 // br label %label_4, !dbg !48 goto T4BLOCK1; T4BLOCK1: // call void @llvm.dbg.label(metadata !109), !dbg !112 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2), metadata !103, metadata !DIExpression()), !dbg !113 // call void @llvm.dbg.value(metadata i64 2, metadata !105, metadata !DIExpression()), !dbg !113 // store atomic i64 2, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !51 // ST: Guess iw(4,0+2*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW _l45_c3 old_cw = cw(4,0+2*1); cw(4,0+2*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM _l45_c3 // Check ASSUME(active[iw(4,0+2*1)] == 4); ASSUME(active[cw(4,0+2*1)] == 4); ASSUME(sforbid(0+2*1,cw(4,0+2*1))== 0); ASSUME(iw(4,0+2*1) >= 0); ASSUME(iw(4,0+2*1) >= 0); ASSUME(cw(4,0+2*1) >= iw(4,0+2*1)); ASSUME(cw(4,0+2*1) >= old_cw); ASSUME(cw(4,0+2*1) >= cr(4,0+2*1)); ASSUME(cw(4,0+2*1) >= cl[4]); ASSUME(cw(4,0+2*1) >= cisb[4]); ASSUME(cw(4,0+2*1) >= cdy[4]); ASSUME(cw(4,0+2*1) >= cdl[4]); ASSUME(cw(4,0+2*1) >= cds[4]); ASSUME(cw(4,0+2*1) >= cctrl[4]); ASSUME(cw(4,0+2*1) >= caddr[4]); // Update caddr[4] = max(caddr[4],0); buff(4,0+2*1) = 2; mem(0+2*1,cw(4,0+2*1)) = 2; co(0+2*1,cw(4,0+2*1))+=1; delta(0+2*1,cw(4,0+2*1)) = -1; ASSUME(creturn[4] >= cw(4,0+2*1)); // call void (...) @dmbst(), !dbg !52 // dumbst: Guess cds[4] = get_rng(0,NCONTEXT-1); // Check ASSUME(cds[4] >= cdy[4]); ASSUME(cds[4] >= cw(4,0+0)); ASSUME(cds[4] >= cw(4,0+1)); ASSUME(cds[4] >= cw(4,0+2)); ASSUME(cds[4] >= cw(4,0+3)); ASSUME(cds[4] >= cw(4,0+4)); ASSUME(cds[4] >= cw(4,5+0)); ASSUME(cds[4] >= cw(4,6+0)); ASSUME(cds[4] >= cw(4,7+0)); ASSUME(creturn[4] >= cds[4]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3), metadata !106, metadata !DIExpression()), !dbg !116 // call void @llvm.dbg.value(metadata i64 1, metadata !108, metadata !DIExpression()), !dbg !116 // store atomic i64 1, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3) release, align 8, !dbg !54 // ST: Guess // : Release iw(4,0+3*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW _l47_c3 old_cw = cw(4,0+3*1); cw(4,0+3*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM _l47_c3 // Check ASSUME(active[iw(4,0+3*1)] == 4); ASSUME(active[cw(4,0+3*1)] == 4); ASSUME(sforbid(0+3*1,cw(4,0+3*1))== 0); ASSUME(iw(4,0+3*1) >= 0); ASSUME(iw(4,0+3*1) >= 0); ASSUME(cw(4,0+3*1) >= iw(4,0+3*1)); ASSUME(cw(4,0+3*1) >= old_cw); ASSUME(cw(4,0+3*1) >= cr(4,0+3*1)); ASSUME(cw(4,0+3*1) >= cl[4]); ASSUME(cw(4,0+3*1) >= cisb[4]); ASSUME(cw(4,0+3*1) >= cdy[4]); ASSUME(cw(4,0+3*1) >= cdl[4]); ASSUME(cw(4,0+3*1) >= cds[4]); ASSUME(cw(4,0+3*1) >= cctrl[4]); ASSUME(cw(4,0+3*1) >= caddr[4]); ASSUME(cw(4,0+3*1) >= cr(4,0+0)); ASSUME(cw(4,0+3*1) >= cr(4,0+1)); ASSUME(cw(4,0+3*1) >= cr(4,0+2)); ASSUME(cw(4,0+3*1) >= cr(4,0+3)); ASSUME(cw(4,0+3*1) >= cr(4,0+4)); ASSUME(cw(4,0+3*1) >= cr(4,5+0)); ASSUME(cw(4,0+3*1) >= cr(4,6+0)); ASSUME(cw(4,0+3*1) >= cr(4,7+0)); ASSUME(cw(4,0+3*1) >= cw(4,0+0)); ASSUME(cw(4,0+3*1) >= cw(4,0+1)); ASSUME(cw(4,0+3*1) >= cw(4,0+2)); ASSUME(cw(4,0+3*1) >= cw(4,0+3)); ASSUME(cw(4,0+3*1) >= cw(4,0+4)); ASSUME(cw(4,0+3*1) >= cw(4,5+0)); ASSUME(cw(4,0+3*1) >= cw(4,6+0)); ASSUME(cw(4,0+3*1) >= cw(4,7+0)); // Update caddr[4] = max(caddr[4],0); buff(4,0+3*1) = 1; mem(0+3*1,cw(4,0+3*1)) = 1; co(0+3*1,cw(4,0+3*1))+=1; delta(0+3*1,cw(4,0+3*1)) = -1; is(4,0+3*1) = iw(4,0+3*1); cs(4,0+3*1) = cw(4,0+3*1); ASSUME(creturn[4] >= cw(4,0+3*1)); // ret i8* null, !dbg !55 ret_thread_4 = (- 1); goto T4BLOCK_END; T4BLOCK_END: // Dumping thread 5 int ret_thread_5 = 0; cdy[5] = get_rng(0,NCONTEXT-1); ASSUME(cdy[5] >= cstart[5]); T5BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !121, metadata !DIExpression()), !dbg !131 // br label %label_5, !dbg !50 goto T5BLOCK1; T5BLOCK1: // call void @llvm.dbg.label(metadata !130), !dbg !133 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3), metadata !123, metadata !DIExpression()), !dbg !134 // %0 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3) acquire, align 8, !dbg !53 // LD: Guess // : Acquire old_cr = cr(5,0+3*1); cr(5,0+3*1) = get_rng(0,NCONTEXT-1);// 5 ASSIGN LDCOM _l53_c15 // Check ASSUME(active[cr(5,0+3*1)] == 5); ASSUME(cr(5,0+3*1) >= iw(5,0+3*1)); ASSUME(cr(5,0+3*1) >= 0); ASSUME(cr(5,0+3*1) >= cdy[5]); ASSUME(cr(5,0+3*1) >= cisb[5]); ASSUME(cr(5,0+3*1) >= cdl[5]); ASSUME(cr(5,0+3*1) >= cl[5]); ASSUME(cr(5,0+3*1) >= cx(5,0+3*1)); ASSUME(cr(5,0+3*1) >= cs(5,0+0)); ASSUME(cr(5,0+3*1) >= cs(5,0+1)); ASSUME(cr(5,0+3*1) >= cs(5,0+2)); ASSUME(cr(5,0+3*1) >= cs(5,0+3)); ASSUME(cr(5,0+3*1) >= cs(5,0+4)); ASSUME(cr(5,0+3*1) >= cs(5,5+0)); ASSUME(cr(5,0+3*1) >= cs(5,6+0)); ASSUME(cr(5,0+3*1) >= cs(5,7+0)); // Update creg_r2 = cr(5,0+3*1); crmax(5,0+3*1) = max(crmax(5,0+3*1),cr(5,0+3*1)); caddr[5] = max(caddr[5],0); if(cr(5,0+3*1) < cw(5,0+3*1)) { r2 = buff(5,0+3*1); ASSUME((!(( (cw(5,0+3*1) < 1) && (1 < crmax(5,0+3*1)) )))||(sforbid(0+3*1,1)> 0)); ASSUME((!(( (cw(5,0+3*1) < 2) && (2 < crmax(5,0+3*1)) )))||(sforbid(0+3*1,2)> 0)); ASSUME((!(( (cw(5,0+3*1) < 3) && (3 < crmax(5,0+3*1)) )))||(sforbid(0+3*1,3)> 0)); ASSUME((!(( (cw(5,0+3*1) < 4) && (4 < crmax(5,0+3*1)) )))||(sforbid(0+3*1,4)> 0)); } else { if(pw(5,0+3*1) != co(0+3*1,cr(5,0+3*1))) { ASSUME(cr(5,0+3*1) >= old_cr); } pw(5,0+3*1) = co(0+3*1,cr(5,0+3*1)); r2 = mem(0+3*1,cr(5,0+3*1)); } cl[5] = max(cl[5],cr(5,0+3*1)); ASSUME(creturn[5] >= cr(5,0+3*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !125, metadata !DIExpression()), !dbg !134 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !122, metadata !DIExpression()), !dbg !131 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4), metadata !126, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i64 1, metadata !128, metadata !DIExpression()), !dbg !137 // store atomic i64 1, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4) monotonic, align 8, !dbg !56 // ST: Guess iw(5,0+4*1) = get_rng(0,NCONTEXT-1);// 5 ASSIGN STIW _l54_c3 old_cw = cw(5,0+4*1); cw(5,0+4*1) = get_rng(0,NCONTEXT-1);// 5 ASSIGN STCOM _l54_c3 // Check ASSUME(active[iw(5,0+4*1)] == 5); ASSUME(active[cw(5,0+4*1)] == 5); ASSUME(sforbid(0+4*1,cw(5,0+4*1))== 0); ASSUME(iw(5,0+4*1) >= 0); ASSUME(iw(5,0+4*1) >= 0); ASSUME(cw(5,0+4*1) >= iw(5,0+4*1)); ASSUME(cw(5,0+4*1) >= old_cw); ASSUME(cw(5,0+4*1) >= cr(5,0+4*1)); ASSUME(cw(5,0+4*1) >= cl[5]); ASSUME(cw(5,0+4*1) >= cisb[5]); ASSUME(cw(5,0+4*1) >= cdy[5]); ASSUME(cw(5,0+4*1) >= cdl[5]); ASSUME(cw(5,0+4*1) >= cds[5]); ASSUME(cw(5,0+4*1) >= cctrl[5]); ASSUME(cw(5,0+4*1) >= caddr[5]); // Update caddr[5] = max(caddr[5],0); buff(5,0+4*1) = 1; mem(0+4*1,cw(5,0+4*1)) = 1; co(0+4*1,cw(5,0+4*1))+=1; delta(0+4*1,cw(5,0+4*1)) = -1; ASSUME(creturn[5] >= cw(5,0+4*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !57 creg__r2__1_ = max(0,creg_r2); // %conv1 = zext i1 %cmp to i32, !dbg !57 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !129, metadata !DIExpression()), !dbg !131 // store i32 %conv1, i32* @atom_4_X0_1, align 4, !dbg !58, !tbaa !59 // ST: Guess iw(5,7) = get_rng(0,NCONTEXT-1);// 5 ASSIGN STIW _l56_c15 old_cw = cw(5,7); cw(5,7) = get_rng(0,NCONTEXT-1);// 5 ASSIGN STCOM _l56_c15 // Check ASSUME(active[iw(5,7)] == 5); ASSUME(active[cw(5,7)] == 5); ASSUME(sforbid(7,cw(5,7))== 0); ASSUME(iw(5,7) >= creg__r2__1_); ASSUME(iw(5,7) >= 0); ASSUME(cw(5,7) >= iw(5,7)); ASSUME(cw(5,7) >= old_cw); ASSUME(cw(5,7) >= cr(5,7)); ASSUME(cw(5,7) >= cl[5]); ASSUME(cw(5,7) >= cisb[5]); ASSUME(cw(5,7) >= cdy[5]); ASSUME(cw(5,7) >= cdl[5]); ASSUME(cw(5,7) >= cds[5]); ASSUME(cw(5,7) >= cctrl[5]); ASSUME(cw(5,7) >= caddr[5]); // Update caddr[5] = max(caddr[5],0); buff(5,7) = (r2==1); mem(7,cw(5,7)) = (r2==1); co(7,cw(5,7))+=1; delta(7,cw(5,7)) = -1; ASSUME(creturn[5] >= cw(5,7)); // ret i8* null, !dbg !63 ret_thread_5 = (- 1); goto T5BLOCK_END; T5BLOCK_END: // Dumping thread 6 int ret_thread_6 = 0; cdy[6] = get_rng(0,NCONTEXT-1); ASSUME(cdy[6] >= cstart[6]); T6BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !144, metadata !DIExpression()), !dbg !152 // br label %label_6, !dbg !48 goto T6BLOCK1; T6BLOCK1: // call void @llvm.dbg.label(metadata !151), !dbg !154 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4), metadata !145, metadata !DIExpression()), !dbg !155 // call void @llvm.dbg.value(metadata i64 2, metadata !147, metadata !DIExpression()), !dbg !155 // store atomic i64 2, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4) monotonic, align 8, !dbg !51 // ST: Guess iw(6,0+4*1) = get_rng(0,NCONTEXT-1);// 6 ASSIGN STIW _l62_c3 old_cw = cw(6,0+4*1); cw(6,0+4*1) = get_rng(0,NCONTEXT-1);// 6 ASSIGN STCOM _l62_c3 // Check ASSUME(active[iw(6,0+4*1)] == 6); ASSUME(active[cw(6,0+4*1)] == 6); ASSUME(sforbid(0+4*1,cw(6,0+4*1))== 0); ASSUME(iw(6,0+4*1) >= 0); ASSUME(iw(6,0+4*1) >= 0); ASSUME(cw(6,0+4*1) >= iw(6,0+4*1)); ASSUME(cw(6,0+4*1) >= old_cw); ASSUME(cw(6,0+4*1) >= cr(6,0+4*1)); ASSUME(cw(6,0+4*1) >= cl[6]); ASSUME(cw(6,0+4*1) >= cisb[6]); ASSUME(cw(6,0+4*1) >= cdy[6]); ASSUME(cw(6,0+4*1) >= cdl[6]); ASSUME(cw(6,0+4*1) >= cds[6]); ASSUME(cw(6,0+4*1) >= cctrl[6]); ASSUME(cw(6,0+4*1) >= caddr[6]); // Update caddr[6] = max(caddr[6],0); buff(6,0+4*1) = 2; mem(0+4*1,cw(6,0+4*1)) = 2; co(0+4*1,cw(6,0+4*1))+=1; delta(0+4*1,cw(6,0+4*1)) = -1; ASSUME(creturn[6] >= cw(6,0+4*1)); // call void (...) @dmbst(), !dbg !52 // dumbst: Guess cds[6] = get_rng(0,NCONTEXT-1); // Check ASSUME(cds[6] >= cdy[6]); ASSUME(cds[6] >= cw(6,0+0)); ASSUME(cds[6] >= cw(6,0+1)); ASSUME(cds[6] >= cw(6,0+2)); ASSUME(cds[6] >= cw(6,0+3)); ASSUME(cds[6] >= cw(6,0+4)); ASSUME(cds[6] >= cw(6,5+0)); ASSUME(cds[6] >= cw(6,6+0)); ASSUME(cds[6] >= cw(6,7+0)); ASSUME(creturn[6] >= cds[6]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0), metadata !148, metadata !DIExpression()), !dbg !158 // call void @llvm.dbg.value(metadata i64 2, metadata !150, metadata !DIExpression()), !dbg !158 // store atomic i64 2, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !54 // ST: Guess iw(6,0) = get_rng(0,NCONTEXT-1);// 6 ASSIGN STIW _l64_c3 old_cw = cw(6,0); cw(6,0) = get_rng(0,NCONTEXT-1);// 6 ASSIGN STCOM _l64_c3 // Check ASSUME(active[iw(6,0)] == 6); ASSUME(active[cw(6,0)] == 6); ASSUME(sforbid(0,cw(6,0))== 0); ASSUME(iw(6,0) >= 0); ASSUME(iw(6,0) >= 0); ASSUME(cw(6,0) >= iw(6,0)); ASSUME(cw(6,0) >= old_cw); ASSUME(cw(6,0) >= cr(6,0)); ASSUME(cw(6,0) >= cl[6]); ASSUME(cw(6,0) >= cisb[6]); ASSUME(cw(6,0) >= cdy[6]); ASSUME(cw(6,0) >= cdl[6]); ASSUME(cw(6,0) >= cds[6]); ASSUME(cw(6,0) >= cctrl[6]); ASSUME(cw(6,0) >= caddr[6]); // Update caddr[6] = max(caddr[6],0); buff(6,0) = 2; mem(0,cw(6,0)) = 2; co(0,cw(6,0))+=1; delta(0,cw(6,0)) = -1; ASSUME(creturn[6] >= cw(6,0)); // ret i8* null, !dbg !55 ret_thread_6 = (- 1); goto T6BLOCK_END; T6BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // %thr3 = alloca i64, align 8 // %thr4 = alloca i64, align 8 // %thr5 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !168, metadata !DIExpression()), !dbg !217 // call void @llvm.dbg.value(metadata i8** %argv, metadata !169, metadata !DIExpression()), !dbg !217 // %0 = bitcast i64* %thr0 to i8*, !dbg !92 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !92 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !170, metadata !DIExpression()), !dbg !219 // %1 = bitcast i64* %thr1 to i8*, !dbg !94 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !94 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !174, metadata !DIExpression()), !dbg !221 // %2 = bitcast i64* %thr2 to i8*, !dbg !96 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !96 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !175, metadata !DIExpression()), !dbg !223 // %3 = bitcast i64* %thr3 to i8*, !dbg !98 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %3) #7, !dbg !98 // call void @llvm.dbg.declare(metadata i64* %thr3, metadata !176, metadata !DIExpression()), !dbg !225 // %4 = bitcast i64* %thr4 to i8*, !dbg !100 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %4) #7, !dbg !100 // call void @llvm.dbg.declare(metadata i64* %thr4, metadata !177, metadata !DIExpression()), !dbg !227 // %5 = bitcast i64* %thr5 to i8*, !dbg !102 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %5) #7, !dbg !102 // call void @llvm.dbg.declare(metadata i64* %thr5, metadata !178, metadata !DIExpression()), !dbg !229 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4), metadata !179, metadata !DIExpression()), !dbg !230 // call void @llvm.dbg.value(metadata i64 0, metadata !181, metadata !DIExpression()), !dbg !230 // store atomic i64 0, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4) monotonic, align 8, !dbg !105 // ST: Guess iw(0,0+4*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l76_c3 old_cw = cw(0,0+4*1); cw(0,0+4*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l76_c3 // Check ASSUME(active[iw(0,0+4*1)] == 0); ASSUME(active[cw(0,0+4*1)] == 0); ASSUME(sforbid(0+4*1,cw(0,0+4*1))== 0); ASSUME(iw(0,0+4*1) >= 0); ASSUME(iw(0,0+4*1) >= 0); ASSUME(cw(0,0+4*1) >= iw(0,0+4*1)); ASSUME(cw(0,0+4*1) >= old_cw); ASSUME(cw(0,0+4*1) >= cr(0,0+4*1)); ASSUME(cw(0,0+4*1) >= cl[0]); ASSUME(cw(0,0+4*1) >= cisb[0]); ASSUME(cw(0,0+4*1) >= cdy[0]); ASSUME(cw(0,0+4*1) >= cdl[0]); ASSUME(cw(0,0+4*1) >= cds[0]); ASSUME(cw(0,0+4*1) >= cctrl[0]); ASSUME(cw(0,0+4*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+4*1) = 0; mem(0+4*1,cw(0,0+4*1)) = 0; co(0+4*1,cw(0,0+4*1))+=1; delta(0+4*1,cw(0,0+4*1)) = -1; ASSUME(creturn[0] >= cw(0,0+4*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3), metadata !182, metadata !DIExpression()), !dbg !232 // call void @llvm.dbg.value(metadata i64 0, metadata !184, metadata !DIExpression()), !dbg !232 // store atomic i64 0, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !107 // ST: Guess iw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l77_c3 old_cw = cw(0,0+3*1); cw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l77_c3 // Check ASSUME(active[iw(0,0+3*1)] == 0); ASSUME(active[cw(0,0+3*1)] == 0); ASSUME(sforbid(0+3*1,cw(0,0+3*1))== 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(cw(0,0+3*1) >= iw(0,0+3*1)); ASSUME(cw(0,0+3*1) >= old_cw); ASSUME(cw(0,0+3*1) >= cr(0,0+3*1)); ASSUME(cw(0,0+3*1) >= cl[0]); ASSUME(cw(0,0+3*1) >= cisb[0]); ASSUME(cw(0,0+3*1) >= cdy[0]); ASSUME(cw(0,0+3*1) >= cdl[0]); ASSUME(cw(0,0+3*1) >= cds[0]); ASSUME(cw(0,0+3*1) >= cctrl[0]); ASSUME(cw(0,0+3*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+3*1) = 0; mem(0+3*1,cw(0,0+3*1)) = 0; co(0+3*1,cw(0,0+3*1))+=1; delta(0+3*1,cw(0,0+3*1)) = -1; ASSUME(creturn[0] >= cw(0,0+3*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2), metadata !185, metadata !DIExpression()), !dbg !234 // call void @llvm.dbg.value(metadata i64 0, metadata !187, metadata !DIExpression()), !dbg !234 // store atomic i64 0, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !109 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l78_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l78_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1), metadata !188, metadata !DIExpression()), !dbg !236 // call void @llvm.dbg.value(metadata i64 0, metadata !190, metadata !DIExpression()), !dbg !236 // store atomic i64 0, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !111 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l79_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l79_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0), metadata !191, metadata !DIExpression()), !dbg !238 // call void @llvm.dbg.value(metadata i64 0, metadata !193, metadata !DIExpression()), !dbg !238 // store atomic i64 0, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !113 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l80_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l80_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_1, align 4, !dbg !114, !tbaa !115 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l81_c15 old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l81_c15 // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !119, !tbaa !115 // ST: Guess iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l82_c15 old_cw = cw(0,6); cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l82_c15 // Check ASSUME(active[iw(0,6)] == 0); ASSUME(active[cw(0,6)] == 0); ASSUME(sforbid(6,cw(0,6))== 0); ASSUME(iw(0,6) >= 0); ASSUME(iw(0,6) >= 0); ASSUME(cw(0,6) >= iw(0,6)); ASSUME(cw(0,6) >= old_cw); ASSUME(cw(0,6) >= cr(0,6)); ASSUME(cw(0,6) >= cl[0]); ASSUME(cw(0,6) >= cisb[0]); ASSUME(cw(0,6) >= cdy[0]); ASSUME(cw(0,6) >= cdl[0]); ASSUME(cw(0,6) >= cds[0]); ASSUME(cw(0,6) >= cctrl[0]); ASSUME(cw(0,6) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,6) = 0; mem(6,cw(0,6)) = 0; co(6,cw(0,6))+=1; delta(6,cw(0,6)) = -1; ASSUME(creturn[0] >= cw(0,6)); // store i32 0, i32* @atom_4_X0_1, align 4, !dbg !120, !tbaa !115 // ST: Guess iw(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l83_c15 old_cw = cw(0,7); cw(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l83_c15 // Check ASSUME(active[iw(0,7)] == 0); ASSUME(active[cw(0,7)] == 0); ASSUME(sforbid(7,cw(0,7))== 0); ASSUME(iw(0,7) >= 0); ASSUME(iw(0,7) >= 0); ASSUME(cw(0,7) >= iw(0,7)); ASSUME(cw(0,7) >= old_cw); ASSUME(cw(0,7) >= cr(0,7)); ASSUME(cw(0,7) >= cl[0]); ASSUME(cw(0,7) >= cisb[0]); ASSUME(cw(0,7) >= cdy[0]); ASSUME(cw(0,7) >= cdl[0]); ASSUME(cw(0,7) >= cds[0]); ASSUME(cw(0,7) >= cctrl[0]); ASSUME(cw(0,7) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,7) = 0; mem(7,cw(0,7)) = 0; co(7,cw(0,7))+=1; delta(7,cw(0,7)) = -1; ASSUME(creturn[0] >= cw(0,7)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !121 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !122 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call10 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !123 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %call11 = call i32 @pthread_create(i64* noundef %thr3, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t3, i8* noundef null) #7, !dbg !124 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[4] >= cdy[0]); // %call12 = call i32 @pthread_create(i64* noundef %thr4, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t4, i8* noundef null) #7, !dbg !125 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[5] >= cdy[0]); // %call13 = call i32 @pthread_create(i64* noundef %thr5, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t5, i8* noundef null) #7, !dbg !126 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[6] >= cdy[0]); // %6 = load i64, i64* %thr0, align 8, !dbg !127, !tbaa !128 r4 = local_mem[0]; // %call14 = call i32 @pthread_join(i64 noundef %6, i8** noundef null), !dbg !130 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %7 = load i64, i64* %thr1, align 8, !dbg !131, !tbaa !128 r5 = local_mem[1]; // %call15 = call i32 @pthread_join(i64 noundef %7, i8** noundef null), !dbg !132 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %8 = load i64, i64* %thr2, align 8, !dbg !133, !tbaa !128 r6 = local_mem[2]; // %call16 = call i32 @pthread_join(i64 noundef %8, i8** noundef null), !dbg !134 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // %9 = load i64, i64* %thr3, align 8, !dbg !135, !tbaa !128 r7 = local_mem[3]; // %call17 = call i32 @pthread_join(i64 noundef %9, i8** noundef null), !dbg !136 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[4]); // %10 = load i64, i64* %thr4, align 8, !dbg !137, !tbaa !128 r8 = local_mem[4]; // %call18 = call i32 @pthread_join(i64 noundef %10, i8** noundef null), !dbg !138 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[5]); // %11 = load i64, i64* %thr5, align 8, !dbg !139, !tbaa !128 r9 = local_mem[5]; // %call19 = call i32 @pthread_join(i64 noundef %11, i8** noundef null), !dbg !140 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,0+4)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,0+4)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[6]); // %12 = load i32, i32* @atom_1_X0_1, align 4, !dbg !141, !tbaa !115 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l99_c13 // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r10 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r10 = buff(0,5); ASSUME((!(( (cw(0,5) < 1) && (1 < crmax(0,5)) )))||(sforbid(5,1)> 0)); ASSUME((!(( (cw(0,5) < 2) && (2 < crmax(0,5)) )))||(sforbid(5,2)> 0)); ASSUME((!(( (cw(0,5) < 3) && (3 < crmax(0,5)) )))||(sforbid(5,3)> 0)); ASSUME((!(( (cw(0,5) < 4) && (4 < crmax(0,5)) )))||(sforbid(5,4)> 0)); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r10 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i32 %12, metadata !194, metadata !DIExpression()), !dbg !217 // %13 = load i32, i32* @atom_2_X0_1, align 4, !dbg !142, !tbaa !115 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l100_c13 // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r11 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r11 = buff(0,6); ASSUME((!(( (cw(0,6) < 1) && (1 < crmax(0,6)) )))||(sforbid(6,1)> 0)); ASSUME((!(( (cw(0,6) < 2) && (2 < crmax(0,6)) )))||(sforbid(6,2)> 0)); ASSUME((!(( (cw(0,6) < 3) && (3 < crmax(0,6)) )))||(sforbid(6,3)> 0)); ASSUME((!(( (cw(0,6) < 4) && (4 < crmax(0,6)) )))||(sforbid(6,4)> 0)); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r11 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // call void @llvm.dbg.value(metadata i32 %13, metadata !195, metadata !DIExpression()), !dbg !217 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2), metadata !197, metadata !DIExpression()), !dbg !265 // %14 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !144 // LD: Guess old_cr = cr(0,0+2*1); cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l101_c13 // Check ASSUME(active[cr(0,0+2*1)] == 0); ASSUME(cr(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cr(0,0+2*1) >= 0); ASSUME(cr(0,0+2*1) >= cdy[0]); ASSUME(cr(0,0+2*1) >= cisb[0]); ASSUME(cr(0,0+2*1) >= cdl[0]); ASSUME(cr(0,0+2*1) >= cl[0]); // Update creg_r12 = cr(0,0+2*1); crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+2*1) < cw(0,0+2*1)) { r12 = buff(0,0+2*1); ASSUME((!(( (cw(0,0+2*1) < 1) && (1 < crmax(0,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(0,0+2*1) < 2) && (2 < crmax(0,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(0,0+2*1) < 3) && (3 < crmax(0,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(0,0+2*1) < 4) && (4 < crmax(0,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) { ASSUME(cr(0,0+2*1) >= old_cr); } pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1)); r12 = mem(0+2*1,cr(0,0+2*1)); } ASSUME(creturn[0] >= cr(0,0+2*1)); // call void @llvm.dbg.value(metadata i64 %14, metadata !199, metadata !DIExpression()), !dbg !265 // %conv = trunc i64 %14 to i32, !dbg !145 // call void @llvm.dbg.value(metadata i32 %conv, metadata !196, metadata !DIExpression()), !dbg !217 // %cmp = icmp eq i32 %conv, 2, !dbg !146 creg__r12__2_ = max(0,creg_r12); // %conv20 = zext i1 %cmp to i32, !dbg !146 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !200, metadata !DIExpression()), !dbg !217 // %15 = load i32, i32* @atom_4_X0_1, align 4, !dbg !147, !tbaa !115 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l103_c13 // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r13 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r13 = buff(0,7); ASSUME((!(( (cw(0,7) < 1) && (1 < crmax(0,7)) )))||(sforbid(7,1)> 0)); ASSUME((!(( (cw(0,7) < 2) && (2 < crmax(0,7)) )))||(sforbid(7,2)> 0)); ASSUME((!(( (cw(0,7) < 3) && (3 < crmax(0,7)) )))||(sforbid(7,3)> 0)); ASSUME((!(( (cw(0,7) < 4) && (4 < crmax(0,7)) )))||(sforbid(7,4)> 0)); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r13 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // call void @llvm.dbg.value(metadata i32 %15, metadata !201, metadata !DIExpression()), !dbg !217 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4), metadata !203, metadata !DIExpression()), !dbg !270 // %16 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 4) monotonic, align 8, !dbg !149 // LD: Guess old_cr = cr(0,0+4*1); cr(0,0+4*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l104_c13 // Check ASSUME(active[cr(0,0+4*1)] == 0); ASSUME(cr(0,0+4*1) >= iw(0,0+4*1)); ASSUME(cr(0,0+4*1) >= 0); ASSUME(cr(0,0+4*1) >= cdy[0]); ASSUME(cr(0,0+4*1) >= cisb[0]); ASSUME(cr(0,0+4*1) >= cdl[0]); ASSUME(cr(0,0+4*1) >= cl[0]); // Update creg_r14 = cr(0,0+4*1); crmax(0,0+4*1) = max(crmax(0,0+4*1),cr(0,0+4*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+4*1) < cw(0,0+4*1)) { r14 = buff(0,0+4*1); ASSUME((!(( (cw(0,0+4*1) < 1) && (1 < crmax(0,0+4*1)) )))||(sforbid(0+4*1,1)> 0)); ASSUME((!(( (cw(0,0+4*1) < 2) && (2 < crmax(0,0+4*1)) )))||(sforbid(0+4*1,2)> 0)); ASSUME((!(( (cw(0,0+4*1) < 3) && (3 < crmax(0,0+4*1)) )))||(sforbid(0+4*1,3)> 0)); ASSUME((!(( (cw(0,0+4*1) < 4) && (4 < crmax(0,0+4*1)) )))||(sforbid(0+4*1,4)> 0)); } else { if(pw(0,0+4*1) != co(0+4*1,cr(0,0+4*1))) { ASSUME(cr(0,0+4*1) >= old_cr); } pw(0,0+4*1) = co(0+4*1,cr(0,0+4*1)); r14 = mem(0+4*1,cr(0,0+4*1)); } ASSUME(creturn[0] >= cr(0,0+4*1)); // call void @llvm.dbg.value(metadata i64 %16, metadata !205, metadata !DIExpression()), !dbg !270 // %conv24 = trunc i64 %16 to i32, !dbg !150 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !202, metadata !DIExpression()), !dbg !217 // %cmp25 = icmp eq i32 %conv24, 2, !dbg !151 creg__r14__2_ = max(0,creg_r14); // %conv26 = zext i1 %cmp25 to i32, !dbg !151 // call void @llvm.dbg.value(metadata i32 %conv26, metadata !206, metadata !DIExpression()), !dbg !217 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0), metadata !208, metadata !DIExpression()), !dbg !274 // %17 = load atomic i64, i64* getelementptr inbounds ([5 x i64], [5 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !153 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l106_c13 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r15 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r15 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r15 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %17, metadata !210, metadata !DIExpression()), !dbg !274 // %conv30 = trunc i64 %17 to i32, !dbg !154 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !207, metadata !DIExpression()), !dbg !217 // %cmp31 = icmp eq i32 %conv30, 1, !dbg !155 creg__r15__1_ = max(0,creg_r15); // %conv32 = zext i1 %cmp31 to i32, !dbg !155 // call void @llvm.dbg.value(metadata i32 %conv32, metadata !211, metadata !DIExpression()), !dbg !217 // %and = and i32 %conv26, %conv32, !dbg !156 creg_r16 = max(creg__r14__2_,creg__r15__1_); r16 = (r14==2) & (r15==1); // call void @llvm.dbg.value(metadata i32 %and, metadata !212, metadata !DIExpression()), !dbg !217 // %and33 = and i32 %15, %and, !dbg !157 creg_r17 = max(creg_r13,creg_r16); r17 = r13 & r16; // call void @llvm.dbg.value(metadata i32 %and33, metadata !213, metadata !DIExpression()), !dbg !217 // %and34 = and i32 %conv20, %and33, !dbg !158 creg_r18 = max(creg__r12__2_,creg_r17); r18 = (r12==2) & r17; // call void @llvm.dbg.value(metadata i32 %and34, metadata !214, metadata !DIExpression()), !dbg !217 // %and35 = and i32 %13, %and34, !dbg !159 creg_r19 = max(creg_r11,creg_r18); r19 = r11 & r18; // call void @llvm.dbg.value(metadata i32 %and35, metadata !215, metadata !DIExpression()), !dbg !217 // %and36 = and i32 %12, %and35, !dbg !160 creg_r20 = max(creg_r10,creg_r19); r20 = r10 & r19; // call void @llvm.dbg.value(metadata i32 %and36, metadata !216, metadata !DIExpression()), !dbg !217 // %cmp37 = icmp eq i32 %and36, 1, !dbg !161 creg__r20__1_ = max(0,creg_r20); // br i1 %cmp37, label %if.then, label %if.end, !dbg !163 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r20__1_); if((r20==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([134 x i8], [134 x i8]* @.str.1, i64 0, i64 0), i32 noundef 113, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !164 // unreachable, !dbg !164 r21 = 1; goto T0BLOCK_END; T0BLOCK2: // %18 = bitcast i64* %thr5 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %18) #7, !dbg !167 // %19 = bitcast i64* %thr4 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %19) #7, !dbg !167 // %20 = bitcast i64* %thr3 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %20) #7, !dbg !167 // %21 = bitcast i64* %thr2 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %21) #7, !dbg !167 // %22 = bitcast i64* %thr1 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %22) #7, !dbg !167 // %23 = bitcast i64* %thr0 to i8*, !dbg !167 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %23) #7, !dbg !167 // ret i32 0, !dbg !168 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSUME(meminit(4,1) == mem(4,0)); ASSUME(coinit(4,1) == co(4,0)); ASSUME(deltainit(4,1) == delta(4,0)); ASSUME(meminit(4,2) == mem(4,1)); ASSUME(coinit(4,2) == co(4,1)); ASSUME(deltainit(4,2) == delta(4,1)); ASSUME(meminit(4,3) == mem(4,2)); ASSUME(coinit(4,3) == co(4,2)); ASSUME(deltainit(4,3) == delta(4,2)); ASSUME(meminit(4,4) == mem(4,3)); ASSUME(coinit(4,4) == co(4,3)); ASSUME(deltainit(4,4) == delta(4,3)); ASSUME(meminit(5,1) == mem(5,0)); ASSUME(coinit(5,1) == co(5,0)); ASSUME(deltainit(5,1) == delta(5,0)); ASSUME(meminit(5,2) == mem(5,1)); ASSUME(coinit(5,2) == co(5,1)); ASSUME(deltainit(5,2) == delta(5,1)); ASSUME(meminit(5,3) == mem(5,2)); ASSUME(coinit(5,3) == co(5,2)); ASSUME(deltainit(5,3) == delta(5,2)); ASSUME(meminit(5,4) == mem(5,3)); ASSUME(coinit(5,4) == co(5,3)); ASSUME(deltainit(5,4) == delta(5,3)); ASSUME(meminit(6,1) == mem(6,0)); ASSUME(coinit(6,1) == co(6,0)); ASSUME(deltainit(6,1) == delta(6,0)); ASSUME(meminit(6,2) == mem(6,1)); ASSUME(coinit(6,2) == co(6,1)); ASSUME(deltainit(6,2) == delta(6,1)); ASSUME(meminit(6,3) == mem(6,2)); ASSUME(coinit(6,3) == co(6,2)); ASSUME(deltainit(6,3) == delta(6,2)); ASSUME(meminit(6,4) == mem(6,3)); ASSUME(coinit(6,4) == co(6,3)); ASSUME(deltainit(6,4) == delta(6,3)); ASSUME(meminit(7,1) == mem(7,0)); ASSUME(coinit(7,1) == co(7,0)); ASSUME(deltainit(7,1) == delta(7,0)); ASSUME(meminit(7,2) == mem(7,1)); ASSUME(coinit(7,2) == co(7,1)); ASSUME(deltainit(7,2) == delta(7,1)); ASSUME(meminit(7,3) == mem(7,2)); ASSUME(coinit(7,3) == co(7,2)); ASSUME(deltainit(7,3) == delta(7,2)); ASSUME(meminit(7,4) == mem(7,3)); ASSUME(coinit(7,4) == co(7,3)); ASSUME(deltainit(7,4) == delta(7,3)); ASSERT(r21== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
dda154077a1a57e6827f167a4a87dd8932d014af
25c422fb8fad1c443ba889566fa7b2ae0397d8bd
/AngusCustomEngine/PhysicsInterfaces/iDebugDrawer.h
2ef2af664d9157056fabaf08fbfaa8c5e9d2f970
[]
no_license
anguspoole/CustomEngine
e1c3079025f320b42eb4d4b816e11a5506aa2162
1d0c97e5834b8840486be0e093aaeb470ff7ebc3
refs/heads/master
2020-05-04T18:34:39.729945
2019-10-18T00:42:09
2019-10-18T00:42:09
179,358,827
1
0
null
null
null
null
UTF-8
C++
false
false
612
h
#pragma once #include <glm/glm.hpp> namespace nPhysics { class iDebugDrawer { public: virtual ~iDebugDrawer() {} virtual void drawLine(const glm::vec3& from, const glm::vec3& to, const glm::vec3& colour) = 0; virtual void drawContactPoint(const glm::vec3& PointOnB, const glm::vec3& normalOnB, float distance, int lifeTime, const glm::vec3& colour) = 0; virtual void reportErrorWarning(const char* warningString) = 0; virtual void draw3dText(const glm::vec3& location, const char* textString) = 0; virtual void setDebugMode(int mode) = 0; virtual int getDebugMode() const = 0; }; }
[ "anguspoole@gmail.com" ]
anguspoole@gmail.com
b943feecd2c496cd538c2bc453f93ba4afc06cb2
48d3c7f2b4953ca3b25cce6f82c26c4e0c74db30
/17_Operator_Overloading/13_Identify _Error.cpp
f50ddbb786ecc29797e38a7863eba6f4b1ed36c5
[]
no_license
syedyasar/Cpp_Programming_Fundamentals
b62f3dd73738b7ecbe372c4fec3e2ea2d11c9e41
07290adccc7505dac051147aaa342e85ec254917
refs/heads/main
2023-06-17T14:09:29.823641
2021-06-29T20:16:27
2021-06-29T20:16:27
376,637,978
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
// Identify Error class c1 { public: friend void operator [] (int x); // Error becoz [] must be MF only friend void operator () (int x); // Error becoz () must be MF only friend void operator = (int x); // Error becoz = must be MF only }; void operator = (int x) { } void operator [] (int x) { } void operator () (int x) { } main() { }
[ "syedyasar.mjcet@gmail.com" ]
syedyasar.mjcet@gmail.com
88c69c9a263b5e925fb6f40f1f3b931f8559d061
ac19ae2ee2a361203c0676468faa2f67fd695851
/keyplayers_Probability_GUI/keyplayers_Probability_GUI/keyplayers_Probability_GUIDlg.cpp
ebb626dec142903e9f8c97560c822f3f9df4a8f0
[]
no_license
htvpro178/Keyplayers_Probability_GUI
d156b8e2ff078c74cb18f857957a3fba24386e03
13a69933377a2978fac6404bb4b54b2a4f8a66c1
refs/heads/master
2021-01-19T10:54:53.484790
2017-04-11T09:31:09
2017-04-11T09:31:09
87,915,690
0
0
null
null
null
null
UTF-8
C++
false
false
24,872
cpp
 // keyplayers_Probability_GUIDlg.cpp : implementation file // #include "stdafx.h" #include "keyplayers_Probability_GUI.h" #include "keyplayers_Probability_GUIDlg.h" #include "afxdialogex.h" #include "iostream" #include "fstream" #include "iomanip" #include "conio.h" #include "cstdlib" #include "windows.h" #include "ctime" #include "fstream" #include "string" #include <vector> #include <sstream> using namespace std; #define CTH 10 int MTLIKE[15][15]={0,0},n,countActive[1024][1024] = {0,0}, countReachMore[15][15] = {0}, saveActive[15][15][100001] = {0}, vertex, a[1024]={0}, spread[100001] = {0}, minSpread = 0, maxSpread = 0; float MTWEIGHTED[15][15]={0,0}, b[1024]={0}; double LenPath[15][15] = {0,0}, LenPathAffect[15][15] = {0,0}, avgSpread = 0.0; string member[15],affectionTop[15],stringLenPath[15], collection[15], stringLenPathAffect[15], affectionTopAffect[15]; float LenSum[15]={0}, spreadRatio[15][15]={0.0}, edgeRandom[15][15][100001] = {0.0}, ratioRandom[15][15][100001] = {0.0}; bool markActive[15] = {0}, m_sDone = false, m_IsPath[1024][1024] = {false, false}, m_sDoneAffect = false; HANDLE myMutex; #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // Ckeyplayers_Probability_GUIDlg dialog Ckeyplayers_Probability_GUIDlg::Ckeyplayers_Probability_GUIDlg(CWnd* pParent /*=NULL*/) : CDialogEx(Ckeyplayers_Probability_GUIDlg::IDD, pParent) , m_sFileIn(_T("")) , m_sVertex(_T("")) , m_sIteration(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void Ckeyplayers_Probability_GUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_FILEIN, m_sFileIn); DDX_Text(pDX, IDC_EDIT_VERTEX, m_sVertex); DDX_Text(pDX, IDC_EDIT_ITERATION, m_sIteration); } BEGIN_MESSAGE_MAP(Ckeyplayers_Probability_GUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDCANCEL, &Ckeyplayers_Probability_GUIDlg::OnBnClickedCancel) ON_BN_CLICKED(IDOK, &Ckeyplayers_Probability_GUIDlg::OnBnClickedOk) ON_BN_CLICKED(IDC_BTN_OPEN_FILE, &Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnOpenFile) ON_BN_CLICKED(IDC_BUTTON1, &Ckeyplayers_Probability_GUIDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BTN_ABOUT, &Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnAbout) ON_BN_CLICKED(IDC_BTN_AFFECT, &Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnAffect) ON_BN_CLICKED(IDC_BTN_RESET, &Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnReset) END_MESSAGE_MAP() // Ckeyplayers_Probability_GUIDlg message handlers BOOL Ckeyplayers_Probability_GUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here m_sFileIn = ""; m_sVertex = ""; m_sIteration = ""; return TRUE; // return TRUE unless you set the focus to a control } void Ckeyplayers_Probability_GUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void Ckeyplayers_Probability_GUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR Ckeyplayers_Probability_GUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } string IntToString ( int number ) { std::ostringstream oss; // Works just like cout oss<< number; // Return the underlying string return oss.str(); } string FloatToString ( float number ) { std::ostringstream oss; // Works just like cout oss<< number; // Return the underlying string return oss.str(); } void writeMT(float mtg[1557], int vertex, int iteration) { string path="Result_Probability.txt"; ofstream write (path); //write<<"Suc anh huong cua dinh "<<vertex<< ":" <<member[vertex] <<" : "<<LenSum[vertex]; //write<<"\n"; write<<"Xac suat lan truyen y tuong thanh cong cua dinh "<<vertex<<" toi cac dinh khac nhu sau: "<<"\n"; //write<<affectionTop[vertex]<<"\n"; write<<stringLenPath[vertex]<<"\n"; write<<"So luong dinh duoc active tu dinh nguon "<<vertex<<" qua cac lan lap nhu sau: "<<"\n"; //write<<affectionTop[vertex]<<"\n"; for (int i = 1; i<= iteration; i++) { write<<spread[i]<<","; } write<<"\nGia tri nho nhat: "<<minSpread; write<<"\nGia tri lon nhat: "<<maxSpread; write<<"\nGia tri trung binh: "<<avgSpread; } vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); // Turn the string into a stream. string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } void readMT(string filename) { ifstream readMTLike (filename); ifstream readMTLike1 (filename); if(!readMTLike.is_open()) { cout<<"Khong the mo file.\n"; return ; } else { string line; std::getline(readMTLike, line); vector<string> sep = split(line, ' '); n = sep.size(); for(int i = 0; i < n; i++) { int j = i+1; member[j] = sep[i]; } for(int i = 1; i <= n; i++) for(int j=1;j<=n;j++) { readMTLike1>>MTLIKE[i][j]; //spreadRatio[i][j] = 1.0; } } readMTLike.close(); readMTLike1.close(); } void createMTPro(int numOfIteration) { int i,j; srand(time(NULL)); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(MTWEIGHTED[i][j] > 0) { for ( int k = 0; k<=numOfIteration; k++) { edgeRandom[i][j][k] = ((float) rand() / (RAND_MAX)) + 0.0; } } } } } void createMT(string filename) { readMT(filename); int i,j; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(i==j) { MTWEIGHTED[i][j]=0; } else { if(MTLIKE[i][j]!=0) { { MTWEIGHTED[i][j]=(1.0*MTLIKE[i][j])/MTLIKE[i][i]; } } else MTWEIGHTED[i][j]=MTLIKE[i][j]; } } } } bool FindVertexInString(string collection1, int a) { if (collection1.find(IntToString(a)) != string::npos) return true; return false; } void CountActiveReach( string collection1, int index, bool flag, int k ) { for (int i = 1; i<=n; i++) { if (FindVertexInString(collection1, i) == true && i != index) { if ( flag == true ) { countActive[i][index]++; } else { saveActive[i][index][k]++; } } } } void ProcessVertex( int index, int k ) { markActive[index] = true; for ( int j = 1; j <= n; j++) { if (markActive[j] == false && MTWEIGHTED[index][j] > 0) { if ( edgeRandom[index][j][k] <= MTWEIGHTED[index][j] ) { collection[j].clear(); collection[j].append(collection[index]); collection[j].append(IntToString( j )); if (collection[j][collection[j].length()-1] != ',') { collection[j].append(","); } CountActiveReach(collection[j], j, true, k); if (collection[j][collection[j].length()-1] != ',') { collection[j].append(","); } //TRACE("%s", collection[j].c_str()); markActive[j] = true; //if ( ratioRandom[j][index][k] <= spreadRatio[j][index] ) { ProcessVertex(j, k); } } else { collection[j].clear(); collection[j].append(collection[index]); if (collection[j][collection[j].length()-1] != ',') { collection[j].append(","); } CountActiveReach(collection[j], j, false, k); } } } } void ResetMarkActive() { for (int i = 1; i<=n; i++) { markActive[i] = false; } } void SetNumOfActive( int i, int k) { for ( int j = 1; j<=n; j++) { if ( markActive[j] == false || i == j ) { saveActive[i][j][k] = 0; } else { saveActive[i][j][k]++; } } } void CountSpreadEveryTimes(int vertex, int k) { spread[k] = 0; for (int i = 1; i<=n; i++) { if ( markActive[i] == true && vertex != i ) spread[k]++; } } void CalculateValueSpread(int numOfIteration) { double sum = 0.0; for (int i = 1; i<=numOfIteration; i++) { if(spread[i] < minSpread ) minSpread = spread[i]; if (spread[i] > maxSpread) maxSpread = spread[i]; sum += spread[i]; } avgSpread = sum/numOfIteration; } void handlerResult(int vertex, int numOfIteration ) { //createMT("E:/DATA/Study/social network/Coding/Bai bao/data_test/4.txt","E:/DATA/Study/social network/Coding/Bai bao/data_test/ratio4.txt","E:/DATA/Study/social network/Coding/Thuyet trinh/New folder/data/dulieu6_member.txt"); for ( int i = 1; i<=n; i++) { collection[i].clear(); } collection[0].append(IntToString(0)); if (collection[0][collection[0].length()-1] != ',') { collection[0].append(","); } collection[vertex].append(IntToString(vertex)); if (collection[vertex][collection[vertex].length()-1] != ',') { collection[vertex].append(","); } for ( int i = 1; i<= numOfIteration; i++) { ResetMarkActive(); ProcessVertex(vertex,i); SetNumOfActive(vertex, i); CountSpreadEveryTimes(vertex, i); } CalculateValueSpread(numOfIteration); for( int i=1; i<=n; i++) { for( int j=1; j<=n; j++) { if (countActive[i][j] > 0) LenPath[i][j] = (float)(countActive[i][j]/float(numOfIteration)); if ( LenPath[i][j] > 0 ) { string topValue = IntToString( j ); affectionTop[i].append(topValue); affectionTop[i].append(" "); stringLenPath[i].append(topValue); stringLenPath[i].append(" : "); stringLenPath[i].append(FloatToString( LenPath[i][j] )); stringLenPath[i].append("\n"); } int numActive = 0, activeAverage = 0; /*for ( int k = 1; k<=numOfIteration; k++) { if (saveActive[i][j][k]>0) { stringLenPath[i].append(IntToString( saveActive[i][j][k] )); stringLenPath[i].append(","); numActive++; activeAverage += saveActive[i][j][k]; } }*/ /*if ( activeAverage > 0 && numActive> 0) { stringLenPath[i].append("\nGia tri trung binh: "); float temp = (float)(activeAverage/(float)numActive); stringLenPath[i].append(FloatToString(temp)); stringLenPath[i].append("\n\n"); }*/ //stringLenPath[i].append("\n"); //cout<<"LenPath["<<i<<"]["<<j<<"]"<<LenPath[i][j]<<"\n"; LenSum[i] += LenPath[i][j]; //cout<<"First Active"<<firstActive[i][j]<<"\n"; } //cout<<"LenSum["<<i<<"]"<<LenSum[i]<<"\n"; } writeMT(LenSum, vertex, numOfIteration); ///printf("Spread"); } /*Xuat ket qua tim duoc ra man hinh*/ void CalculateLen2(int arrayStack2[1024],int countStack2, int source, int end) { float lenValue = 1.0; //printf("%d",Stack2[1]); for (int i = 2; i<= countStack2; i++) { lenValue *= MTWEIGHTED[arrayStack2[i-1]][arrayStack2[i]]; } //cout<<"lenvalue"<<lenValue<<"\n"; if (LenPathAffect[source][end] == 0) { LenPathAffect[source][end] = 1 - lenValue; m_IsPath[source][end] = true; } else { LenPathAffect[source][end] *= ( 1- lenValue); m_IsPath[source][end] = true; } } /*Kiem tra dinh i co nam trong Stack2, neu co tra ve ket qua 0 va neu khong co tra ve ket qua 1*/ char CheckVertexInStack(int i, int arrayStack2[1024],int countVertex2) { for(int j=1;j<=countVertex2; j++) if(i==arrayStack2[j]) return 0; return 1; } /*Xoa tat ca cac phan tu giong nhau o dau Stack1 va Stack2 khi co duong di hoac gap dinh treo khong the di duoc nua*/ void DeleteArrayVertex(int arrayVertex1[1024],int &countStack1,int arrayVertex2[1024],int &countStack2) { while(arrayVertex1[countStack1]==arrayVertex2[countStack2]) { countStack1--; countStack2--; } countStack2++; arrayVertex2[countStack2]=arrayVertex1[countStack1]; } /*Tim kiem tat ca cac duong di neu co, neu bien Dem>0 thi ton tai duong di va nguoc lai neu Dem=0 thi khong co duong di tu source den end*/ void FindPathTwoVertex2(float A[15][15], int source, int end) { int arrayVertex1[1024],arrayVertex2[1024]; int countStack1=1,countStack2=1, hangVertex; int index; //init 2 array stack arrayVertex1[countStack1]=source; arrayVertex2[countStack2]=source; while( countStack1>0 && countStack2>0 ) { index = arrayVertex1[countStack1]; if ( index == end ) { arrayVertex2[0] = source; CalculateLen2(arrayVertex2,countStack2, source, end); DeleteArrayVertex(arrayVertex1,countStack1,arrayVertex2,countStack2); } else { hangVertex = 1; //Gia su ton tai dinh treo for(int i=1; i<=n; i++) if(A[index][i] > 0 && CheckVertexInStack(i,arrayVertex2,countStack2)==1) { countStack1++; arrayVertex1[countStack1] = i; hangVertex = 0; } if(hangVertex==1) { DeleteArrayVertex(arrayVertex1,countStack1,arrayVertex2,countStack2); } else { countStack2++; arrayVertex2[countStack2]=arrayVertex1[countStack1]; } if(arrayVertex2[countStack2]==end) { arrayVertex2[0] = source; CalculateLen2(arrayVertex2,countStack2, source, end); DeleteArrayVertex(arrayVertex1,countStack1,arrayVertex2,countStack2); } } } } DWORD WINAPI taske(LPVOID) { int node=0; while(node<n) { DWORD dwWaitResult; dwWaitResult = WaitForSingleObject(myMutex, INFINITE); switch (dwWaitResult) { case WAIT_OBJECT_0: { node = vertex; vertex++; ReleaseMutex(myMutex); if (node<=n) { for(int j=1;j<=n;j++) if ( node !=j ) { //LenOfTwoVertexDijkstra(node, j, MTWEIGHTED); FindPathTwoVertex2(MTWEIGHTED, node, j); } } break; } case WAIT_ABANDONED: return FALSE; } } return 0; } void swap(int &a,int &b) { int temp=a; a=b; b=temp; } void swapf(float &a,float &b) { float temp=a; a=b; b=temp; } void SortMT() { for(int i=1;i<n;i++) for(int j=i+1;j<=n;j++) if(b[i]<b[j]) { swapf(b[i],b[j]); swap(a[i],a[j]); swap(member[i],member[j]); swap(affectionTopAffect[i], affectionTopAffect[j]); swap(stringLenPathAffect[i], stringLenPathAffect[j]); } } void writeMTAffect(int vertex) { string path="Result_keyplayer_1.txt"; ofstream write (path); //write<<n<<"\n"; //write<<"Danh sach "<<top<<" phan tu co suc anh huong lon nhat trong do thi: "<<endl; //write<<"Dinh "<<vertex<<" anh huong toi dinh: "<<"\n"; //write<<affectionTopAffect[vertex]<<"\n"; write<<"Suc anh huong cua dinh "<<vertex<<" toi cac dinh khac nhu sau:\n"; write<<stringLenPathAffect[vertex]<<"\n"; } void handlerResultAffect() { if ( m_sDoneAffect == false) { vertex = 1; myMutex = CreateMutex(NULL, FALSE, NULL); if (myMutex == NULL) { printf("CreateMutex error: %d\n", GetLastError()); } HANDLE thr[100]; DWORD thrid; for(int i=0;i<CTH;i++) { thr[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)taske,0,0,&thrid); if( thr[i] == NULL ) { printf("CreateThread error: %d\n", GetLastError()); } } WaitForMultipleObjects(CTH, thr, TRUE, INFINITE); for( int i=0; i < CTH; i++ ) CloseHandle(thr[i]); CloseHandle(myMutex); } for( int i=1; i<=n; i++) { for( int j=1; j<=n; j++) { //if ( LenPath[i][j] > 0 || m_IsPath[i][j] == true ) if ( m_IsPath[i][j] == true ) { //if ( m_sDoneAffect == false ) //{ LenPathAffect[i][j] = 1 - LenPathAffect[i][j]; //} string topValue = IntToString( j ); affectionTopAffect[i].empty(); affectionTopAffect[i].append(topValue); affectionTopAffect[i].append(" "); stringLenPathAffect[i].append(topValue); stringLenPathAffect[i].append(" : "); stringLenPathAffect[i].append(FloatToString( LenPathAffect[i][j] )); stringLenPathAffect[i].append("\n"); } } } } void Ckeyplayers_Probability_GUIDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here CDialogEx::OnCancel(); } void Ckeyplayers_Probability_GUIDlg::OnBnClickedOk() { // TODO: Add your control notification handler code here CDialogEx::OnOK(); } void Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnOpenFile() { // TODO: Add your control notification handler code here CFileDialog dlg(TRUE); dlg.m_ofn.lpstrTitle = L"Choose the input file"; dlg.m_ofn.lpstrInitialDir = L"E:\\DATA\\Study\\social network\\Coding\\BAO CAO\\Source Code\\data_test"; if ( dlg.DoModal() == IDOK) { m_sFileIn = dlg.m_ofn.lpstrFile; UpdateData(FALSE); } } void Ckeyplayers_Probability_GUIDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here if ( m_sDone == false ) { UpdateData(TRUE); time_t rawtime; time(&rawtime); CString tempTime = (CString)ctime(&rawtime); SetDlgItemText(IDC_START_TIME2,tempTime); SetDlgItemText(IDC_STATUS2, L"Đang xử lý..."); int l_vertex; l_vertex = _tstoi(m_sVertex); int l_iteration; l_iteration = _tstoi(m_sIteration); if ( ProcessFiles(m_sFileIn, l_vertex, l_iteration, false, false) == TRUE) { if (m_sDoneAffect == false) { // Convert a TCHAR string to a LPCSTR CT2CA pszConvertedAnsiString (m_sFileIn); // construct a std::string using the LPCSTR input string strMtLike (pszConvertedAnsiString); //TRACE("ket qua tra ve là : [%s]\n", strStd.c_str()); createMT(strMtLike); } if ( ProcessFiles(m_sFileIn, l_vertex, l_iteration, true, false) == TRUE) { createMTPro(l_iteration); handlerResult(l_vertex, l_iteration); //CString m_sResult = L"Danh sach " + m_sNumOfKey + L" phan tu co suc anh huong lon nhat trong do thi:\n" ; CString m_sResult; for(int i=1;i<=n;i++) { CString affectTopStr, lenPathStr; if ( LenPath[l_vertex][i] > 0 ) { affectTopStr.Format(L"%d", i); lenPathStr.Format(L"%f", LenPath[l_vertex][i]); m_sResult += L" " + affectTopStr + L" " + lenPathStr + L"\r\n"; SetDlgItemText(IDC_EDIT_RESULT, m_sResult); m_sDone = true; SetDlgItemText(IDC_STATUS2, L"Đã xong!"); time(&rawtime); CString tempTime = (CString)ctime(&rawtime); SetDlgItemText(IDC_END_TIME2,tempTime); } } CString m_sResultSpread, minStr, maxStr, evgStr; minStr.Format(L"%d", minSpread); maxStr.Format(L"%d", maxSpread); evgStr.Format(L"%f", avgSpread); m_sResultSpread += L" Min : " + minStr + L"\r\n" + L" Max : " + maxStr + L"\r\n" + L" Average: " + evgStr + L"\r\n"; SetDlgItemText(IDC_EDIT_SPREAD, m_sResultSpread); } } } else { MessageBox(L"Đã thực thi xong", L"Information", MB_OK | MB_ICONINFORMATION); } } BOOL Ckeyplayers_Probability_GUIDlg::ProcessFiles(CString sFileIn, int vertex, int sIteration, bool loadFile, bool flagAffect) { if ( loadFile == false) { CFile fileIn; if ( fileIn.Open(sFileIn, CFile::modeRead) == FALSE ) { CString sMsg; sMsg.Format(L"Không thể mở File %s", sFileIn); MessageBox(sMsg, L"Error", MB_OK | MB_ICONERROR); return FALSE; } if (vertex < 1) { CString sMsg; sMsg.Format(L"Vui lòng nhập đỉnh bắt đầu"); MessageBox(sMsg, L"Error", MB_OK | MB_ICONERROR); return FALSE; } if (flagAffect == false) { if ( sIteration < 1 || sIteration > 100000) { CString sMsg; sMsg.Format(L"Vui lòng kiểm tra số lần lặp"); MessageBox(sMsg, L"Error", MB_OK | MB_ICONERROR); return FALSE; } } int a; fileIn.Read(&a, sizeof(int)); } else { if ( vertex < 1 || vertex > n ) { CString sMsg; sMsg.Format(L"Vui lòng kiểm tra đỉnh bắt đầu"); MessageBox(sMsg, L"Error", MB_OK | MB_ICONERROR); return FALSE; } } return TRUE; } void Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnAbout() { // TODO: Add your control notification handler code here MessageBox(L"Mô hình lan truyền ý tưởng thành công v1.0\r\nCH1301114 - Huỳnh Thanh Việt", L"Information", MB_OK | MB_ICONINFORMATION); } void Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnAffect() { // TODO: Add your control notification handler code here if ( m_sDoneAffect == false ) { UpdateData(TRUE); time_t rawtime; time(&rawtime); CString tempTime = (CString)ctime(&rawtime); SetDlgItemText(IDC_START_TIME, tempTime); SetDlgItemText(IDC_STATUS, L"Đang xử lý..."); //int top; //top = _tstoi(m_sNumOfKey); //float l_threshold; //l_threshold = _tstof(m_sThreshold); int l_vertex; l_vertex = _tstoi(m_sVertex); int l_iteration; l_iteration = _tstoi(m_sIteration); if ( ProcessFiles(m_sFileIn, l_vertex, l_iteration, false, true) == TRUE) { if (m_sDone == false) { // Convert a TCHAR string to a LPCSTR CT2CA pszConvertedAnsiString (m_sFileIn); // construct a std::string using the LPCSTR input string strMtLike (pszConvertedAnsiString); //TRACE("ket qua tra ve là : [%s]\n", strStd.c_str()); createMT(strMtLike); } if ( ProcessFiles(m_sFileIn, l_vertex, l_iteration, true, true) == TRUE) { handlerResultAffect(); int l_vertex; l_vertex = _tstoi(m_sVertex); writeMTAffect(l_vertex); CString m_sResult; for(int i=1;i<=n;i++) { CString affectTopStr, lenPathStr; if ( LenPathAffect[l_vertex][i] > 0 ) { affectTopStr.Format(L"%d", i); lenPathStr.Format(L"%f", LenPathAffect[l_vertex][i]); m_sResult += L" " + affectTopStr + L" " + lenPathStr + L"\r\n"; SetDlgItemText(IDC_EDIT_RESULT2, m_sResult); SetDlgItemText(IDC_STATUS, L"Đã xong!"); m_sDoneAffect = true; time(&rawtime); CString tempTime = (CString)ctime(&rawtime); SetDlgItemText(IDC_END_TIME,tempTime); } } } } } else { MessageBox(L"Đã tính xong", L"Information", MB_OK | MB_ICONINFORMATION); } } void Ckeyplayers_Probability_GUIDlg::OnBnClickedBtnReset() { // TODO: Add your control notification handler code here if (n > 0) { vertex = 0; for( int i = 0; i<=n; i++) { a[i] = 0; b[i] = 0.0; member[i] = ""; affectionTop[i] =""; stringLenPath[i] = ""; collection[i] = ""; stringLenPathAffect[i] = ""; affectionTopAffect[i] = ""; LenSum[i] = 0.0; markActive[i] = false; m_sDoneAffect = false; m_sDone = false; for ( int j = 0; j<=n; j++) { MTLIKE[i][j] = 0; countActive[i][j] = 0; countReachMore[i][j] = 0; MTWEIGHTED[i][j] = 0.0; LenPath[i][j] = 0.0; LenPathAffect[i][j] = 0.0; m_IsPath[i][j] = false; spreadRatio[i][j] = 0.0; m_IsPath[i][j] = false; //effect[i][j] = 0; for (int k = 0; k<=100001; k++) { saveActive[i][j][k] = 0; edgeRandom[i][j][k] = 0.0; ratioRandom[i][j][k] = 0.0; spread[k] = 0; } } } n = 0; minSpread = 0; maxSpread = 0; avgSpread = 0.0; CString temp; temp.Format(L"%s", ""); UpdateData(FALSE); SetDlgItemText(IDC_EDIT_RESULT, temp); SetDlgItemText(IDC_STATUS2, temp); SetDlgItemText(IDC_START_TIME2,temp); SetDlgItemText(IDC_END_TIME2,temp); SetDlgItemText(IDC_EDIT_RESULT2, temp); SetDlgItemText(IDC_STATUS, temp); SetDlgItemText(IDC_START_TIME,temp); SetDlgItemText(IDC_END_TIME,temp); SetDlgItemText(IDC_EDIT_FILEIN, temp); SetDlgItemText(IDC_EDIT_VERTEX, temp); SetDlgItemText(IDC_EDIT_ITERATION, temp); m_sFileIn = ""; m_sVertex = ""; m_sIteration = ""; } }
[ "viethuynh178@gmail.com" ]
viethuynh178@gmail.com
691512d19a36e97a54b75dabfbb4a5b014f678ea
cde198bebb6a4ed98801158b010f971b0000d5fe
/2021寒假每日一题/429. 奖学金(自定义比较函数).cpp
03c8d5da2faaf78ad3fe515bf78e38cc24a0dfa2
[]
no_license
YTGhost/AcWing
8e4588624f5c2871b496e3086045ac47d1365e84
505cbd50e74ec3aa146c975a563eafea1f757d88
refs/heads/master
2021-09-20T15:35:12.406137
2021-09-09T14:13:44
2021-09-09T14:13:44
249,120,388
2
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
#include <iostream> #include <algorithm> using namespace std; const int N = 310; struct Person { int id, sum, a, b, c; }q[N]; bool cmp(Person &a, Person &b) { if(a.sum != b.sum) return a.sum > b.sum; if(a.a != b.a) return a.a > b.a; return a.id < b.id; } int main() { int n; cin >> n; for(int i = 1; i <= n; i++) { int a, b, c; cin >> a >> b >> c; q[i] = {i, a+b+c, a, b, c}; } sort(q + 1, q + n + 1, cmp); for(int i = 1; i <= 5; i++) cout << q[i].id << " " << q[i].sum << endl; return 0; }
[ "283304489@qq.com" ]
283304489@qq.com
29d1c3f4dc9b5fd56644db93d254b4aaa5085a9c
1976fae8250c57c807f1e36f267638a9f74aa0ff
/ServicioMensajeriaUI/debug/moc_logindialog.cpp
71decc07fe7ee4d4f9bfa24585cadd8bf0b5382a
[]
no_license
D4ZC/Servicio-de-Mensajeria-en-QT
937308ae1d76afcae7acdaadbf22c3b698b6e661
e851b576c00269b2c570f3ad3dfc5786b206a1d7
refs/heads/master
2020-04-27T08:30:30.060046
2019-03-06T15:49:40
2019-03-06T15:49:40
174,173,755
0
0
null
null
null
null
UTF-8
C++
false
false
7,318
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'logindialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../logindialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'logindialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_LoginDialog_t { QByteArrayData data[15]; char stringdata0[219]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_LoginDialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_LoginDialog_t qt_meta_stringdata_LoginDialog = { { QT_MOC_LITERAL(0, 0, 11), // "LoginDialog" QT_MOC_LITERAL(1, 12, 10), // "createUser" QT_MOC_LITERAL(2, 23, 0), // "" QT_MOC_LITERAL(3, 24, 4), // "name" QT_MOC_LITERAL(4, 29, 5), // "phone" QT_MOC_LITERAL(5, 35, 8), // "password" QT_MOC_LITERAL(6, 44, 5), // "login" QT_MOC_LITERAL(7, 50, 21), // "on_userLE_textChanged" QT_MOC_LITERAL(8, 72, 4), // "arg1" QT_MOC_LITERAL(9, 77, 25), // "on_passwordLE_textChanged" QT_MOC_LITERAL(10, 103, 24), // "on_newUserLE_textChanged" QT_MOC_LITERAL(11, 128, 22), // "on_phoneLE_textChanged" QT_MOC_LITERAL(12, 151, 28), // "on_newPasswordLE_textChanged" QT_MOC_LITERAL(13, 180, 19), // "on_createPB_clicked" QT_MOC_LITERAL(14, 200, 18) // "on_loginPB_clicked" }, "LoginDialog\0createUser\0\0name\0phone\0" "password\0login\0on_userLE_textChanged\0" "arg1\0on_passwordLE_textChanged\0" "on_newUserLE_textChanged\0" "on_phoneLE_textChanged\0" "on_newPasswordLE_textChanged\0" "on_createPB_clicked\0on_loginPB_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_LoginDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 9, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: name, argc, parameters, tag, flags 1, 3, 59, 2, 0x06 /* Public */, 6, 2, 66, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 7, 1, 71, 2, 0x08 /* Private */, 9, 1, 74, 2, 0x08 /* Private */, 10, 1, 77, 2, 0x08 /* Private */, 11, 1, 80, 2, 0x08 /* Private */, 12, 1, 83, 2, 0x08 /* Private */, 13, 0, 86, 2, 0x08 /* Private */, 14, 0, 87, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::QString, 3, 4, 5, QMetaType::Void, QMetaType::QString, QMetaType::QString, 3, 5, // slots: parameters QMetaType::Void, QMetaType::QString, 8, QMetaType::Void, QMetaType::QString, 8, QMetaType::Void, QMetaType::QString, 8, QMetaType::Void, QMetaType::QString, 8, QMetaType::Void, QMetaType::QString, 8, QMetaType::Void, QMetaType::Void, 0 // eod }; void LoginDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { LoginDialog *_t = static_cast<LoginDialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->createUser((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; case 1: _t->login((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 2: _t->on_userLE_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 3: _t->on_passwordLE_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 4: _t->on_newUserLE_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 5: _t->on_phoneLE_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 6: _t->on_newPasswordLE_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 7: _t->on_createPB_clicked(); break; case 8: _t->on_loginPB_clicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (LoginDialog::*)(QString , QString , QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&LoginDialog::createUser)) { *result = 0; return; } } { using _t = void (LoginDialog::*)(QString , QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&LoginDialog::login)) { *result = 1; return; } } } } QT_INIT_METAOBJECT const QMetaObject LoginDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_LoginDialog.data, qt_meta_data_LoginDialog, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *LoginDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *LoginDialog::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_LoginDialog.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int LoginDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 9) qt_static_metacall(this, _c, _id, _a); _id -= 9; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 9) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 9; } return _id; } // SIGNAL 0 void LoginDialog::createUser(QString _t1, QString _t2, QString _t3) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void LoginDialog::login(QString _t1, QString _t2) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "noreply@github.com" ]
noreply@github.com
318b60b56a5c40088565a87fe2f13ff0b6c92c07
a9b4a84775cebf4f5c08ec5ae474cbd824f7c6f5
/sketch/led_through_serial_rus.ino
bcde97eea94bf48a7a8ac7cd3c29c2147b1d77a5
[]
no_license
FabLab61/car_PC
273f634152d88a2ac1e823539730a9982175bffd
dce4263433760b133d73c4d78074b2e29756333c
refs/heads/master
2021-01-22T06:28:14.693416
2017-02-26T09:36:09
2017-02-26T09:36:09
81,763,805
0
0
null
null
null
null
UTF-8
C++
false
false
479
ino
int led = 13; void setup() { { pinMode(led, OUTPUT); Serial.begin(9600); Serial.flush(); } } void loop() { { String input = ""; while (Serial.available()) { input += (char) Serial.read(); delay(5); } if (input == "on") { Serial.println("on executed"); digitalWrite(led, HIGH); } else if (input == "off"){ Serial.println("off executed"); digitalWrite(led, LOW); } } }
[ "ustin89@mail.ru" ]
ustin89@mail.ru
ef6b0f8553d437fd242a0ae2502a38ab27bbb73c
bd9de700605da2278a92020a2814b699daedec57
/codility/lesson14_1_MinMaxDivision/lesson14_1.hpp
6ab33353de31f9ff1a73cc31355520ab378cfc69
[]
no_license
WuHang108/petit-a-petit
8b177771e004341a166feb1a156153098f5d5d89
e173df8333f9a4070aee5ee65603fed92d2abf6b
refs/heads/master
2021-11-18T15:36:40.059510
2021-10-16T17:10:02
2021-10-16T17:10:02
230,759,303
1
0
null
null
null
null
UTF-8
C++
false
false
1,015
hpp
#include "../basic_io.hpp" using namespace std; bool block_size_is_valid(vector<int>& A, int max_block_cnt, int max_block_size) { int block_sum = 0, block_cnt = 0; for(int n:A) { if(block_sum + n > max_block_size) { // 超出最大大小限制时建立新块 block_sum = n; block_cnt ++; } else { block_sum += n; } if(block_cnt >= max_block_cnt) return false; } return true; } int solution(int K, int M, vector<int> &A) { int max_value = 0, sum_A = 0; for(int n : A) { max_value = max(max_value, n); sum_A += n; } if(K == 1) return sum_A; if(K >= A.size()) return max_value; int low_bound = max_value, high_bound = sum_A; while(low_bound <= high_bound) { int mid = low_bound + (high_bound - low_bound) / 2; if(block_size_is_valid(A, K, mid)) { high_bound = mid - 1; } else { low_bound = mid + 1; } } return low_bound; }
[ "shengdian.wang@outlook.com" ]
shengdian.wang@outlook.com
c1efeaa641ba96b62d95ebd0cec03e1360c9d927
b53599ea3877ca20298ad3b76a5e2b9e18ff7c5d
/SEvos/Common/common/skyBox.cpp
6c2b3c06c69445fe711e168af9748daa11982426
[ "MIT" ]
permissive
cnsuhao/Dx3D-Study
a087717913437588ee77a059478e8ea995c004b1
7e9941ae42584aa47d42e69fb8585e104b0039a2
refs/heads/master
2021-06-08T13:42:43.322968
2016-10-13T03:26:28
2016-10-13T03:26:28
null
0
0
null
null
null
null
UHC
C++
false
false
6,415
cpp
#include "StdAfx.h" #include "skyBox.h" CSkyBox::CSkyBox() : m_pVtxBuffer(NULL) { ZeroMemory(m_pTexture, sizeof(m_pTexture)); } CSkyBox::~CSkyBox() { SAFE_RELEASE(m_pVtxBuffer); } //------------------------------------------------------------------------ // textureFilePath : 이 파일 경로에 skybox_top, skybox_front, skybox_back, // skybox_left, skybox_right, skybox_bottom.jpg 파일이 있어야 한다. // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ BOOL CSkyBox::Init(char *szTextureFilePath) { char *textureFileName[] = { "skybox_front.jpg", "skybox_back.jpg", "skybox_left.jpg", "skybox_right.jpg", "skybox_top.jpg", "skybox_bottom.jpg" }; for (int i=0; i < MAX_FACE; ++i) { char fileName[ MAX_PATH]; strcpy_s(fileName, sizeof(fileName), szTextureFilePath); strcat_s(fileName, sizeof(fileName), "/"); strcat_s(fileName, sizeof(fileName), textureFileName[ i]); IDirect3DTexture9 *ptex = CFileLoader::LoadTexture(fileName); if (!ptex) { return FALSE; } m_pTexture[ i] = ptex; } if (!CreateVertexBuffer()) return FALSE; return TRUE; } //------------------------------------------------------------------------ // // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ BOOL CSkyBox::CreateVertexBuffer() { // Example diagram of "front" quad // The numbers are vertices // // 2 __________ 4 // |\ | // | \ | // | \ | // | \ | // 1 | \ | 3 // ---------- const float size = 300; SVtxTex SkyboxMesh[24] = { // Front quad, NOTE: All quads face inward SVtxTex(-size, -size, size, 0.0f, 1.0f ), SVtxTex(-size, size, size, 0.0f, 0.0f ), SVtxTex( size, -size, size, 1.0f, 1.0f ), SVtxTex( size, size, size, 1.0f, 0.0f ), // Back quad SVtxTex( size, -size, -size, 0.0f, 1.0f ), SVtxTex( size, size, -size, 0.0f, 0.0f ), SVtxTex(-size, -size, -size, 1.0f, 1.0f ), SVtxTex(-size, size, -size, 1.0f, 0.0f ), // Left quad SVtxTex(-size, -size, -size, 0.0f, 1.0f ), SVtxTex(-size, size, -size, 0.0f, 0.0f ), SVtxTex(-size, -size, size, 1.0f, 1.0f ), SVtxTex(-size, size, size, 1.0f, 0.0f ), // Right quad SVtxTex( size, -size, size, 0.0f, 1.0f ), SVtxTex( size, size, size, 0.0f, 0.0f ), SVtxTex( size, -size, -size, 1.0f, 1.0f ), SVtxTex( size, size, -size, 1.0f, 0.0f ), // Top quad SVtxTex(-size, size, size, 0.0f, 1.0f ), SVtxTex(-size, size, -size, 0.0f, 0.0f ), SVtxTex( size, size, size, 1.0f, 1.0f ), SVtxTex( size, size, -size, 1.0f, 0.0f ), // Bottom quad SVtxTex(-size, -size, -size, 0.0f, 1.0f ), SVtxTex(-size, -size, size, 0.0f, 0.0f ), SVtxTex( size, -size, -size, 1.0f, 1.0f ), SVtxTex( size, -size, size, 1.0f, 0.0f ), }; const int vtxSize = 24; g_pDevice->CreateVertexBuffer( vtxSize*sizeof(SVtxTex), 0, SVtxTex::FVF, D3DPOOL_MANAGED, &m_pVtxBuffer, NULL ); SVtxTex *pv; m_pVtxBuffer->Lock( 0, sizeof(SVtxTex)*vtxSize, (void**)&pv, 0 ); memcpy( pv, SkyboxMesh, sizeof(SVtxTex) * 24 ); m_pVtxBuffer->Unlock(); return TRUE; } //------------------------------------------------------------------------ // // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ void CSkyBox::Update(int elapseTime) { } //------------------------------------------------------------------------ // // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ void CSkyBox::SetRenderState() { g_pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE ); g_pDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); g_pDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); g_pDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); g_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ); g_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ); /* g_pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE); g_pDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); g_pDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); g_pDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); g_pDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ); /* // Set TFactor g_pDevice->SetRenderState( D3DRS_TEXTUREFACTOR, 0xFFFFFFFF ); // Texture 관련 세팅 g_pDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); g_pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR ); g_pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE ); g_pDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); g_pDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TFACTOR ); g_pDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TEXTURE ); g_pDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT ); g_pDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_POINT ); g_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ); g_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ); // TFactor g_pDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); g_pDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); /**/ } //------------------------------------------------------------------------ // // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ void CSkyBox::Render() { SetRenderState(); D3DXMATRIX matView, matViewSave, matWorld; g_pDevice->GetTransform( D3DTS_VIEW, &matViewSave ); matView = matViewSave; matView._41 = 0.0f; matView._42 = -0.4f; matView._43 = 0.0f; g_pDevice->SetTransform( D3DTS_VIEW, &matView ); // Set a default world matrix D3DXMatrixIdentity(&matWorld); g_pDevice->SetTransform( D3DTS_WORLD, &matWorld); // render g_pDevice->SetFVF(SVtxTex::FVF); g_pDevice->SetStreamSource( 0, m_pVtxBuffer, 0, sizeof(SVtxTex)); for (int i = 0 ; i < MAX_FACE; i++) { g_pDevice->SetTexture(0, m_pTexture[ i]); g_pDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, i*4, 2 ); } g_pDevice->SetTransform( D3DTS_VIEW, &matViewSave ); } //------------------------------------------------------------------------ // // [2011/3/1 jjuiddong] //------------------------------------------------------------------------ void CSkyBox::Clear() { SAFE_RELEASE(m_pVtxBuffer); }
[ "jjuiddong@hanmail.net" ]
jjuiddong@hanmail.net
a4f9ab0bffd2664b306f3bc77884c14f2f7d99d0
eb96c9ac79b198cf093549b93d03ed71b6104d0c
/recipe/insertionSort.cc
3cadd288aa9a791809f60e20500c998551e94576
[]
no_license
zeroli/code
360004129949e4461c7269264e83916ef557150f
8b220cc9b55ba5544472400f248c3faa104dff3e
refs/heads/master
2021-01-01T17:05:46.256827
2012-11-22T15:16:38
2012-11-22T15:16:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
676
cc
#include <iostream> #include <cstdlib> #include <ctime> void insertionSort(int arr[], int l, int r) { int i = l; int j = 0; while (i < r) { j = i+1; int e = arr[j]; while (j > l && arr[j-1] > e) { arr[j] = arr[j-1]; j--; } arr[j] = e; i++; } } int main() { srand((unsigned)time(0)); int arr[10]; std::cout << "original unsorted array: \n"; for (int i = 0; i < 10; i++) { int tmp = (int)(rand()%100); arr[i] = tmp; std::cout << arr[i] << " "; } std::cout << "\n"; insertionSort(arr, 0, 9); std::cout << "sorted array after insertion sort:\n"; for (int i = 0; i < 10; i++) std::cout << arr[i] << " "; std::cout << "\n"; return 0; }
[ "Administrator@Zero-Li-PC.(none)" ]
Administrator@Zero-Li-PC.(none)
8792a8589b7eb505c0752d5aca9741a39aee6b6f
bc6cd18a13992f425bb97406c5c5e7e3b8d8cb03
/src/planner/interface/decision.h
972272dc4c3ddf7ecade1810e6624cdfe26a0142
[ "MIT" ]
permissive
collinej/Vulcan
4ef1e2fc1b383b2b3a9ee59d78dc3c027d4cae24
fa314bca7011d81b9b83f44edc5a51b617d68261
refs/heads/master
2022-09-19T01:59:45.905392
2022-09-18T02:41:22
2022-09-18T02:41:22
186,317,314
3
3
NOASSERTION
2022-04-29T02:06:12
2019-05-13T00:04:38
C++
UTF-8
C++
false
false
3,729
h
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file decision.h * \author Collin Johnson * * Declaration of Decision. */ #ifndef PLANNER_INTERFACE_DECISION_H #define PLANNER_INTERFACE_DECISION_H #include "core/point.h" #include "hssh/local_topological/area.h" #include "mpepc/metric_planner/task/task.h" namespace vulcan { struct pose_t; namespace planner { /** * DecisionDirection defines the direction the action takes the robot relative to its location. The relative * directions can be selected using the arrow keys on the keyboard, for example. The absolute directions require a more * sophisticated selection mechanism that doesn't map to a keyboard as easily. */ enum class DecisionDirection { left, right, forward, backward, absolute, }; /** * Decision describes an action the robot can take within its current area. The action is an abstract description * of a specific navigation task to be executed by the robot. * * */ class Decision { public: /** * Constructor for Decision. * * \param direction Direction the action takes the robot * \param areaType Type of area the action leads to * \param position Position of the decision * \param orientation Orientation of the decision * \param isAbsolute Flag indicating if the position is relative to the robot or absolute. * A relative position will be associated with a travel action. Transitions are all * absolute because they are associated with a particular gateway. */ Decision(DecisionDirection direction, hssh::AreaType areaType, Point<double> position, double orientation, bool isAbsolute); /** * direction retrieves the direction in which the action carries the robot relative to its current topological * position. */ DecisionDirection direction(void) const { return direction_; } /** * areaType retrieves the type of area the action will lead the robot to. */ hssh::AreaType areaType(void) const { return type_; } /** * position retrieves the position of the action within the current map. The position provides an approximate * location of where the task to be performed will move the robot. * * \return Position of the action in the current map reference frame. */ Point<double> position(void) const { return position_; } /** * orientation retrieves the orientation of the action within the current map. The orientation provides an * approximate heading along which the robot will be moving if it executes the action. * * \return Orientation of the action in the current map reference frame. */ double orientation(void) const { return orientation_; } /** * isAbsolute checks if the decision is relative to the robot's position, i.e. it will be changing over time as the * robot explores, or if it is absolute and corresponds to an unchanging state. */ bool isAbsolute(void) const { return isAbsolute_; } private: DecisionDirection direction_; hssh::AreaType type_; Point<double> position_; double orientation_; bool isAbsolute_; }; } // namespace planner } // namespace vulcan #endif // PLANNER_INTERFACE_DECISION_H
[ "collinej@umich.edu" ]
collinej@umich.edu
2ed0b41809078a791954ddf8d0314cf0a1391419
1baf4a8591743caefb57b555a287a7842f3fac0b
/C++_programs/TIC_programs/Polymorphism/sample2.cpp
7755dfdea6dbf9fa14aee26ef9d7a42268c94cad
[]
no_license
gokul51192/Coding_GitHub
c6d86624a5c55b9739985720987cdbd1a29a6c4b
d3ad783a885c91323a32db6692e8046b4bfd8732
refs/heads/master
2020-05-21T15:06:13.378939
2018-09-02T16:41:01
2018-09-02T16:41:01
59,049,063
0
0
null
null
null
null
UTF-8
C++
false
false
220
cpp
#include<iostream> using namespace std; class student { public: int a; virtual void print_data() { cout<<"\n hello you are in virtual function"; } }; int main() { student s1; s1.print_data(); return 0; }
[ "gokul51192@gmail.com" ]
gokul51192@gmail.com
7cb36c5aa4404462f54bf71134229c73129acefa
9a09d8be7393906a73e35bb404ba99c121c48470
/Chapter09/chapter9/cm/cm-lib/source/controllers/master-controller.h
cb34bc4520f5632431ec06ef5f841a84422a57fd
[ "MIT" ]
permissive
PacktPublishing/Learn-Qt-5
d3260f34473d5970f17584656044fcb68a1bdc1a
ec768c3f6503eee1c77c62319cbb130e978380ec
refs/heads/master
2023-02-10T02:30:06.844485
2023-01-30T09:16:48
2023-01-30T09:16:48
119,801,529
81
42
null
null
null
null
UTF-8
C++
false
false
1,845
h
#ifndef MASTERCONTROLLER_H #define MASTERCONTROLLER_H #include <QObject> #include <QScopedPointer> #include <QString> #include <cm-lib_global.h> #include <controllers/i-command-controller.h> #include <controllers/i-database-controller.h> #include <controllers/i-navigation-controller.h> #include <framework/i-object-factory.h> #include <models/client.h> #include <models/client-search.h> #include <rss/rss-channel.h> namespace cm { namespace controllers { class CMLIBSHARED_EXPORT MasterController : public QObject { Q_OBJECT Q_PROPERTY( QString ui_welcomeMessage READ welcomeMessage CONSTANT ) Q_PROPERTY( cm::controllers::INavigationController* ui_navigationController READ navigationController CONSTANT ) Q_PROPERTY( cm::controllers::ICommandController* ui_commandController READ commandController CONSTANT ) Q_PROPERTY( cm::controllers::IDatabaseController* ui_databaseController READ databaseController CONSTANT ) Q_PROPERTY( cm::models::Client* ui_newClient READ newClient CONSTANT ) Q_PROPERTY( cm::models::ClientSearch* ui_clientSearch READ clientSearch CONSTANT ) Q_PROPERTY( cm::rss::RssChannel* ui_rssChannel READ rssChannel NOTIFY rssChannelChanged ) public: explicit MasterController(QObject* parent = nullptr, framework::IObjectFactory* objectFactory = nullptr); ~MasterController(); ICommandController* commandController(); IDatabaseController* databaseController(); INavigationController* navigationController(); models::Client* newClient(); models::ClientSearch* clientSearch(); rss::RssChannel* rssChannel(); const QString& welcomeMessage() const; public slots: void selectClient(cm::models::Client* client); void onRssReplyReceived(int statusCode, QByteArray body); signals: void rssChannelChanged(); private: class Implementation; QScopedPointer<Implementation> implementation; }; }} #endif
[ "akhiln@packtpub.com" ]
akhiln@packtpub.com
71002b32fd40092c27fb1b3e38921314e610f82d
dd2abae5866c31342d6265fe59eb267f9de3a90c
/Assignment 3/raycolor.cpp
470163631a9df4bd4ddeb65bbe2d6f2ffe6032cb
[]
no_license
ZihangH/csc418
4e326d69e5cd85e33b6a7931f4bdfdf330ead58d
3936dc55fb9bbe1abc2835156a6e369ad1ad506b
refs/heads/master
2022-12-20T14:40:18.836929
2020-10-18T02:42:02
2020-10-18T02:42:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,109
cpp
#include "raycolor.h" #include "first_hit.h" #include "blinn_phong_shading.h" #include "reflect.h" bool raycolor( const Ray & ray, const double min_t, const std::vector< std::shared_ptr<Object> > & objects, const std::vector< std::shared_ptr<Light> > & lights, const int num_recursive_calls, Eigen::Vector3d & rgb) { //////////////////////////////////////////////////////////////////////////// // Replace with your code here: rgb = Eigen::Vector3d(0,0,0); Eigen::Vector3d n = Eigen::Vector3d(0,0,0); int hit_id; double t = 0; if(first_hit(ray, min_t, objects, hit_id, t, n)){ rgb += blinn_phong_shading(ray, hit_id, t, n, objects, lights); Ray ray2; ray2.origin = ray.origin + t * ray.direction; ray2.direction = reflect(ray.direction, n); Eigen::Vector3d color = Eigen::Vector3d(0,0,0); if(raycolor(ray2, 0.000001, objects, lights, num_recursive_calls + 1, color)){ rgb += (objects[hit_id]->material->km.array() * color.array()).matrix(); } } return true; //////////////////////////////////////////////////////////////////////////// }
[ "markus@markus.com" ]
markus@markus.com
1bf05803c64e40b0420f10a22f55728b63a7f463
6d57d7bb46c62d955bae7b526b1ad01fda8b5bb1
/Discount.cpp
9cd0efcfe91d9c9ab41521d0513485d5dfc4ab88
[]
no_license
shivam0084/Hacktoberfest2021-Task02
e251469760d6e7645413a21f0ef58c573b93bcdb
76bfb34602826da6c2671e27b3785491987c6d61
refs/heads/main
2023-08-30T16:45:24.352291
2021-10-22T14:13:42
2021-10-22T14:13:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
#include <iostream> using namespace std; int main() { float pay,discount; cout << "Enter Payment amount : " cin >> pay; if (p > 10000) { discount=pay*25/100 } else if (pay > 5000) { discount=pay*15/100; } else if (pay > 3000) { discount=pay*10/100; } else{ discount= 0; } cout << "Discount is -> " << discount << endl; }
[ "noreply@github.com" ]
noreply@github.com
ececed5aca81e363e6333d5f4d08418aa117e644
b6067f462d3bd91362ca9bb462b99f9a2890d980
/chackathon2019/F.cpp
79416b8d8001f4b7dc211fec019688ac7013f23d
[]
no_license
lionadis/CompetitiveProgramming
275cb251cccbed0669b35142b317943f9b5c72c5
f91d7ac19f09d7e89709bd825fe2cd95fa0cf985
refs/heads/master
2020-07-22T07:29:18.683302
2019-09-08T13:48:31
2019-09-08T13:48:31
207,116,093
0
0
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll ; const ll MOD = 1e9 + 7; const ll dx[4] = { -1,1,0,0 }; const ll dy[4] = { 0,0,-1,1 }; const ll MAX = 2e5 + 50 ; const ll oo = 1e16; #define pb push_back #define f first #define s second #define all(v) v.begin(),v.end() long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); } ll n , m , q , ans , sz , k , x , d; string s ; vector < pair < ll , ll > > v ; struct UF { vector<int> e; UF(int n) : e(n, -1) {} bool same_set(int a, int b) { return find(a) == find(b); } int size(int x) { return -e[find(x)]; } int find(int x) { return e[x] < 0 ? x : e[x] = find(e[x]); } void join(int a, int b) { a = find(a), b = find(b); if (a == b) return; if (e[a] > e[b]) swap(a, b); e[a] += e[b]; e[b] = a; } }; int main(){ freopen("test.in", "r", stdin); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--){ int n, q; cin >> n >> q; UF uf(n); ll ans = 0, curr = 0; while(q--){ int u, v; cin >> u >> v; --u, --v; if(uf.same_set(u, v)){ ans += curr; continue; } curr -= 1ll * uf.size(u) * (uf.size(u) - 1); curr -= 1ll * uf.size(v) * (uf.size(v) - 1); uf.join(u, v); curr += 1ll * uf.size(u) * (uf.size(u) - 1); ans += curr; } cout << ans << '\n'; } return 0; } /* 1 2 2 1 10 100 10 */
[ "ahmed.ben.neji@ieee.org" ]
ahmed.ben.neji@ieee.org
f2083243c94bd0d607d9b51d35697115c311e908
531991de0534de991d857d63ff9ab53a863ff55a
/UVa256.cpp
b00175010021b30583407391052850fca478d9ac
[]
no_license
Shadman-Ahmed-Chowdhury/UVa-Solutions
c92c2fede0353f5376fa2358d225d215f04f9f71
165943cfcf5db5d74e817aea009742fdaa8ee8ba
refs/heads/master
2021-07-06T21:35:47.622049
2020-08-30T11:57:32
2020-08-30T11:57:32
167,227,844
0
0
null
null
null
null
UTF-8
C++
false
false
2,078
cpp
#include <bits/stdc++.h> using namespace std; vector <int> two, four, six, eight; void calculate() { for(int i = 0; i < 100000; i++) { int n = i * i; if(n < 100) { int p = 10; int x = n / p; int y = n % p; int n1 = (x + y) * (x + y); if(n == n1) two.push_back(n); } else if(n <= 9999) { int p = 100; int x = n / p; int y = n % p; int n1 = (x + y) * (x + y); if(n == n1) four.push_back(n); } else if(n <= 999999) { int p = 1000; int x = n / p; int y = n % p; int n1 = (x + y) * (x + y); if(n == n1) six.push_back(n); } else if(n <= 99999999) { int p = 10000; int x = n / p; int y = n % p; int n1 = (x + y) * (x + y); if(n == n1) eight.push_back(n); } else continue; } } int main() { calculate(); int n; while(cin >> n) { if(n == 2) { for(int i = 0; i < two.size() - 1; i++) cout << setw(n) << setfill('0') << two[i] << endl; } else if(n == 4) { cout << "0000\n"; cout << "0001\n"; for(int i = 0; i < four.size(); i++) cout << setw(n) << setfill('0') << four[i] << endl; } else if(n == 6) { cout << "000000\n"; cout << "000001\n"; for(int i = 0; i < six.size(); i++) { cout << setw(n) << setfill('0') << six[i] << endl; } } else if(n == 8) { cout << "00000000\n"; cout << "00000001\n"; for(int i = 0; i < eight.size(); i++) { cout << setw(n) << setfill('0') << eight[i] << endl; } } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
444cc756a47b5d3bf63783c678fcde5643d0f59c
abf2d583c67b3db5270958cab031aac9bf1540f6
/far/platform.fs.hpp
cb8d7f60d0b094d98f23311888991c84aebd6d94
[ "BSD-3-Clause" ]
permissive
kingofthebongo2008/FarManager
7d0fe852c034aad37576ebbc86b9ddc850deac38
a86c430bcf57a26a1b9e24d12dbd638027c22d6b
refs/heads/master
2020-03-20T18:17:04.200396
2018-06-10T21:33:00
2018-06-10T21:33:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,218
hpp
#ifndef PLATFORM_FS_HPP_1094D8B6_7681_46C8_9C08_C5253376E988 #define PLATFORM_FS_HPP_1094D8B6_7681_46C8_9C08_C5253376E988 #pragma once /* platform.fs.hpp */ /* Copyright © 2017 Far Group 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. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "platform.hpp" #include "platform.chrono.hpp" #include "common/enumerator.hpp" namespace os::fs { namespace detail { struct find_handle_closer { void operator()(HANDLE Handle) const; }; struct find_file_handle_closer { void operator()(HANDLE Handle) const; }; struct find_volume_handle_closer { void operator()(HANDLE Handle) const; }; struct find_notification_handle_closer { void operator()(HANDLE Handle) const; }; } using find_handle = os::detail::handle_t<detail::find_handle_closer>; using find_file_handle = os::detail::handle_t<detail::find_file_handle_closer>; using find_volume_handle = os::detail::handle_t<detail::find_volume_handle_closer>; using find_notification_handle = os::detail::handle_t<detail::find_notification_handle_closer>; using drives_set = std::bitset<26>; using security_descriptor = block_ptr<SECURITY_DESCRIPTOR, default_buffer_size>; struct find_data { public: string FileName; private: string AlternateFileNameData; public: chrono::time_point CreationTime; chrono::time_point LastAccessTime; chrono::time_point LastWriteTime; chrono::time_point ChangeTime; unsigned long long FileSize{}; unsigned long long AllocationSize{}; unsigned long long FileId{}; DWORD Attributes{}; DWORD ReparseTag{}; const string& AlternateFileName() const; void SetAlternateFileName(string_view Name); bool HasAlternateFileName() const; }; bool is_standard_drive_letter(wchar_t Letter); int get_drive_number(wchar_t Letter); string get_drive(wchar_t Letter); string get_root_directory(wchar_t Letter); class enum_drives: public enumerator<enum_drives, wchar_t> { IMPLEMENTS_ENUMERATOR(enum_drives); public: explicit enum_drives(drives_set Drives); private: bool get(bool Reset, wchar_t& Value) const; drives_set m_Drives; mutable size_t m_CurrentIndex{}; }; class enum_files: public enumerator<enum_files, find_data> { IMPLEMENTS_ENUMERATOR(enum_files); public: explicit enum_files(string_view Object, bool ScanSymLink = true); private: bool get(bool Reset, find_data& Value) const; string m_Object; bool m_ScanSymlink; mutable find_file_handle m_Handle; }; class enum_names: public enumerator<enum_names, string> { IMPLEMENTS_ENUMERATOR(enum_names); public: explicit enum_names(string_view Object); private: bool get(bool Reset, string& Value) const; string m_Object; mutable find_handle m_Handle; }; class enum_streams: public enumerator<enum_streams, WIN32_FIND_STREAM_DATA> { IMPLEMENTS_ENUMERATOR(enum_streams); public: explicit enum_streams(string_view Object); private: bool get(bool Reset, WIN32_FIND_STREAM_DATA& Value) const; string m_Object; mutable find_file_handle m_Handle; }; class enum_volumes: public enumerator<enum_volumes, string> { IMPLEMENTS_ENUMERATOR(enum_volumes); public: enum_volumes(); private: bool get(bool Reset, string& Value) const; string m_Object; mutable find_volume_handle m_Handle; }; class file { public: NONCOPYABLE(file); MOVABLE(file); file(): m_Pointer(), m_NeedSyncPointer(), m_ShareMode() { } template<typename... args> explicit file(args... Args) { Open(FWD(Args)...); } explicit operator bool() const noexcept; // TODO: half of these should be free functions bool Open(string_view Object, DWORD DesiredAccess, DWORD ShareMode, SECURITY_ATTRIBUTES* SecurityAttributes, DWORD CreationDistribution, DWORD FlagsAndAttributes = 0, const file* TemplateFile = nullptr, bool ForceElevation = false); // TODO: async overloads when needed bool Read(void* Buffer, size_t NumberOfBytesToRead, size_t& NumberOfBytesRead) const; bool Write(const void* Buffer, size_t NumberOfBytesToWrite) const; unsigned long long GetPointer() const; bool SetPointer(long long DistanceToMove, unsigned long long* NewFilePointer, DWORD MoveMethod) const; bool SetEnd(); bool GetTime(chrono::time_point* CreationTime, chrono::time_point* LastAccessTime, chrono::time_point* LastWriteTime, chrono::time_point* ChangeTime) const; bool SetTime(const chrono::time_point* CreationTime, const chrono::time_point* LastAccessTime, const chrono::time_point* LastWriteTime, const chrono::time_point* ChangeTime) const; bool GetSize(unsigned long long& Size) const; bool FlushBuffers() const; bool GetInformation(BY_HANDLE_FILE_INFORMATION& info) const; bool IoControl(DWORD IoControlCode, void* InBuffer, DWORD InBufferSize, void* OutBuffer, DWORD OutBufferSize, DWORD* BytesReturned, OVERLAPPED* Overlapped = nullptr) const; bool GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG Flags, ULONG StorageDependencyInfoSize, PSTORAGE_DEPENDENCY_INFO StorageDependencyInfo, PULONG SizeUsed) const; bool NtQueryDirectoryFile(void* FileInformation, size_t Length, FILE_INFORMATION_CLASS FileInformationClass, bool ReturnSingleEntry, const wchar_t* FileName, bool RestartScan, NTSTATUS* Status = nullptr) const; bool NtQueryInformationFile(void* FileInformation, size_t Length, FILE_INFORMATION_CLASS FileInformationClass, NTSTATUS* Status = nullptr) const; bool GetFinalPathName(string& FinalFilePath) const; void Close(); bool Eof() const; const string& GetName() const; const handle& get() const; private: void SyncPointer() const; handle m_Handle; mutable unsigned long long m_Pointer; mutable bool m_NeedSyncPointer; string m_Name; DWORD m_ShareMode; }; class file_walker: public file { public: file_walker(); ~file_walker(); bool InitWalk(size_t BlockSize); bool Step(); unsigned long long GetChunkOffset() const; DWORD GetChunkSize() const; int GetPercent() const; private: struct Chunk; std::vector<Chunk> m_ChunkList; unsigned long long m_FileSize{}; unsigned long long m_AllocSize{}; unsigned long long m_ProcessedSize{}; std::vector<Chunk>::iterator m_CurrentChunk{}; DWORD m_ChunkSize{}; bool m_IsSparse{}; }; class filebuf : public std::streambuf { public: NONCOPYABLE(filebuf); filebuf(const file& File, std::ios::openmode Mode, size_t BufferSize = 65536); protected: int_type overflow(int_type Ch) override; int sync() override; private: void reset_put_area(); const file& m_File; std::ios::openmode m_Mode; std::vector<char> m_Buffer; }; class file_status { public: file_status(); explicit file_status(string_view Object); bool check(DWORD Data) const; private: DWORD m_Data; }; bool exists(file_status Status); bool exists(string_view Object); bool is_file(file_status Status); bool is_file(string_view Object); bool is_directory(file_status Status); bool is_directory(string_view Object); bool is_not_empty_directory(const string& Object); class process_current_directory_guard: noncopyable { public: process_current_directory_guard(bool Active, const std::function<string()>& Provider); ~process_current_directory_guard(); private: string m_Directory; bool m_Active; }; namespace low { HANDLE create_file(const wchar_t* FileName, DWORD DesiredAccess, DWORD ShareMode, SECURITY_ATTRIBUTES* SecurityAttributes, DWORD CreationDistribution, DWORD FlagsAndAttributes, HANDLE TemplateFile); bool create_directory(const wchar_t* TemplateDirectory, const wchar_t* NewDirectory, SECURITY_ATTRIBUTES* SecurityAttributes); bool remove_directory(const wchar_t* PathName); bool delete_file(const wchar_t* FileName); DWORD get_file_attributes(const wchar_t* FileName); bool set_file_attributes(const wchar_t* FileName, DWORD Attributes); bool create_hard_link(const wchar_t* FileName, const wchar_t* ExistingFileName, SECURITY_ATTRIBUTES* SecurityAttributes); bool copy_file(const wchar_t* ExistingFileName, const wchar_t* NewFileName, LPPROGRESS_ROUTINE ProgressRoutine, void* Data, BOOL* Cancel, DWORD CopyFlags); bool move_file(const wchar_t* ExistingFileName, const wchar_t* NewFileName, DWORD Flags); bool detach_virtual_disk(const wchar_t* Object, VIRTUAL_STORAGE_TYPE& VirtualStorageType); bool get_disk_free_space(const wchar_t* DirectoryName, unsigned long long* FreeBytesAvailableToCaller, unsigned long long* TotalNumberOfBytes, unsigned long long* TotalNumberOfFreeBytes); bool set_file_encryption(const wchar_t* FileName, bool Encrypt); } bool GetProcessRealCurrentDirectory(string& Directory); bool SetProcessRealCurrentDirectory(const string& Directory); void InitCurrentDirectory(); string GetCurrentDirectory(); bool SetCurrentDirectory(const string& PathName, bool Validate = true); bool create_directory(string_view PathName, SECURITY_ATTRIBUTES* SecurityAttributes = nullptr); bool create_directory(string_view TemplateDirectory, string_view NewDirectory, SECURITY_ATTRIBUTES* SecurityAttributes = nullptr); bool remove_directory(string_view DirName); handle create_file(string_view Object, DWORD DesiredAccess, DWORD ShareMode, SECURITY_ATTRIBUTES* SecurityAttributes, DWORD CreationDistribution, DWORD FlagsAndAttributes = 0, HANDLE TemplateFile = nullptr, bool ForceElevation = false); bool delete_file(string_view FileName); bool copy_file(string_view ExistingFileName, string_view NewFileName, LPPROGRESS_ROUTINE ProgressRoutine, void* Data, BOOL* Cancel, DWORD CopyFlags); bool move_file(string_view ExistingFileName, string_view NewFileName, DWORD Flags = 0); DWORD get_file_attributes(string_view FileName); bool set_file_attributes(string_view FileName, DWORD FileAttributes); bool GetLongPathName(const string& ShortPath, string& LongPath); bool GetShortPathName(const string& LongPath, string& ShortPath); bool GetVolumeInformation(const string& RootPathName, string *pVolumeName, DWORD* VolumeSerialNumber, DWORD* MaximumComponentLength, DWORD* FileSystemFlags, string* FileSystemName); bool GetVolumeNameForVolumeMountPoint(const string& VolumeMountPoint, string& VolumeName); bool GetVolumePathNamesForVolumeName(const string& VolumeName, string& VolumePathNames); bool QueryDosDevice(const string& DeviceName, string& Path); bool SearchPath(const wchar_t* Path, string_view FileName, const wchar_t* Extension, string& strDest); bool GetTempPath(string& strBuffer); bool GetModuleFileName(HANDLE hProcess, HMODULE hModule, string& strFileName); security_descriptor get_file_security(string_view Object, SECURITY_INFORMATION RequestedInformation); bool set_file_security(string_view Object, SECURITY_INFORMATION RequestedInformation, const security_descriptor& SecurityDescriptor); bool get_disk_size(string_view Path, unsigned long long* TotalSize, unsigned long long* TotalFree, unsigned long long* UserFree); bool GetFileTimeSimple(string_view FileName, chrono::time_point* CreationTime, chrono::time_point* LastAccessTime, chrono::time_point* LastWriteTime, chrono::time_point* ChangeTime); bool get_find_data(const string& FileName, find_data& FindData, bool ScanSymLink = true); find_notification_handle FindFirstChangeNotification(const string& PathName, bool WatchSubtree, DWORD NotifyFilter); bool IsDiskInDrive(const string& Root); bool create_hard_link(const string& FileName, const string& ExistingFileName, SECURITY_ATTRIBUTES* SecurityAttributes); bool CreateSymbolicLink(const string& SymlinkFileName, const string& TargetFileName, DWORD Flags); bool set_file_encryption(string_view FileName, bool Encrypt); bool detach_virtual_disk(string_view Object, VIRTUAL_STORAGE_TYPE& VirtualStorageType); bool is_directory_symbolic_link(const find_data& Data); bool CreateSymbolicLinkInternal(const string& Object, const string& Target, DWORD Flags); } #endif // PLATFORM_FS_HPP_1094D8B6_7681_46C8_9C08_C5253376E988
[ "alabuzhev@gmail.com" ]
alabuzhev@gmail.com
37e61d25b64ff452e78d5ad788c3b63a9093bd54
6c93908079fa656b117cd785db7f53ad45739664
/caffe/src/caffe/layers/cudnn_conv_layer.cpp
18fd2750401203260b4342838d4d5c77fbb1c94e
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
leehomyc/appearance-flow
ca39a0908ca5ef5a1088a6bb2787c2b7509147fb
00b50a4e673a42f9feeecafa335943d74da52819
refs/heads/master
2021-01-22T08:18:07.023256
2017-02-17T20:08:37
2017-02-17T20:08:37
81,887,152
1
1
null
2017-02-14T00:40:06
2017-02-14T00:40:06
null
UTF-8
C++
false
false
7,279
cpp
#ifdef USE_CUDNN #include <algorithm> #include <vector> #include "caffe/filler.hpp" #include "caffe/layers/cudnn_conv_layer.hpp" #include "caffe/util/gpu_memory.hpp" #include "caffe/util/im2col.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { /** * TODO(dox) explain cuDNN interface */ template <typename Dtype> void CuDNNConvolutionLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { ConvolutionLayer<Dtype>::LayerSetUp(bottom, top); // Initialize algorithm arrays fwd_algo_ = new cudnnConvolutionFwdAlgo_t[bottom.size()]; bwd_filter_algo_= new cudnnConvolutionBwdFilterAlgo_t[bottom.size()]; bwd_data_algo_ = new cudnnConvolutionBwdDataAlgo_t[bottom.size()]; // initialize size arrays workspace_fwd_sizes_ = new size_t[bottom.size()]; workspace_bwd_filter_sizes_ = new size_t[bottom.size()]; workspace_bwd_data_sizes_ = new size_t[bottom.size()]; for (size_t i = 0; i < bottom.size(); ++i) { // initialize all to default algorithms fwd_algo_[i] = (cudnnConvolutionFwdAlgo_t)0; bwd_filter_algo_[i] = (cudnnConvolutionBwdFilterAlgo_t)0; bwd_data_algo_[i] = (cudnnConvolutionBwdDataAlgo_t)0; // default algorithms don't require workspace workspace_fwd_sizes_[i] = 0; workspace_bwd_data_sizes_[i] = 0; workspace_bwd_filter_sizes_[i] = 0; } // Set the indexing parameters. bias_offset_ = (this->num_output_ / this->group_); // Create filter descriptor. const int* kernel_shape_data = this->kernel_shape_.cpu_data(); const int kernel_h = kernel_shape_data[0]; const int kernel_w = kernel_shape_data[1]; cudnn::createFilterDesc<Dtype>(&filter_desc_, this->num_output_ / this->group_, this->channels_ / this->group_, kernel_h, kernel_w); this->weight_offset_ = (this->num_output_ / this->group_) * (this->channels_ / this->group_) * kernel_h * kernel_w; // Create tensor descriptor(s) for data and corresponding convolution(s). for (int i = 0; i < bottom.size(); i++) { cudnnTensorDescriptor_t bottom_desc; cudnn::createTensor4dDesc<Dtype>(&bottom_desc); bottom_descs_.push_back(bottom_desc); cudnnTensorDescriptor_t top_desc; cudnn::createTensor4dDesc<Dtype>(&top_desc); top_descs_.push_back(top_desc); cudnnConvolutionDescriptor_t conv_desc; cudnn::createConvolutionDesc<Dtype>(&conv_desc); conv_descs_.push_back(conv_desc); } // Tensor descriptor for bias. if (this->bias_term_) { cudnn::createTensor4dDesc<Dtype>(&bias_desc_); } handles_setup_ = true; } template <typename Dtype> void CuDNNConvolutionLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { ConvolutionLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(2, this->num_spatial_axes_) << "CuDNNConvolution input must have 2 spatial axes " << "(e.g., height and width). " << "Use 'engine: CAFFE' for general ND convolution."; bottom_offset_ = this->bottom_dim_ / this->group_; top_offset_ = this->top_dim_ / this->group_; const int height = bottom[0]->shape(this->channel_axis_ + 1); const int width = bottom[0]->shape(this->channel_axis_ + 2); const int height_out = top[0]->shape(this->channel_axis_ + 1); const int width_out = top[0]->shape(this->channel_axis_ + 2); const int* pad_data = this->pad_.cpu_data(); const int pad_h = pad_data[0]; const int pad_w = pad_data[1]; const int* stride_data = this->stride_.cpu_data(); const int stride_h = stride_data[0]; const int stride_w = stride_data[1]; // Specify workspace limit for kernels directly until we have a // planning strategy and a rewrite of Caffe's GPU memory mangagement size_t workspace_limit_bytes, total_memory; gpu_memory::getInfo(&workspace_limit_bytes, &total_memory); for (int i = 0; i < bottom.size(); i++) { cudnn::setTensor4dDesc<Dtype>(&bottom_descs_[i], this->num_, this->channels_ / this->group_, height, width, this->channels_ * height * width, height * width, width, 1); cudnn::setTensor4dDesc<Dtype>(&top_descs_[i], this->num_, this->num_output_ / this->group_, height_out, width_out, this->num_output_ * this->out_spatial_dim_, this->out_spatial_dim_, width_out, 1); cudnn::setConvolutionDesc<Dtype>(&conv_descs_[i], bottom_descs_[i], filter_desc_, pad_h, pad_w, stride_h, stride_w); if (!this->IsForwardPassed() || !this->IsBackwardPassed()) { continue; } // choose forward and backward algorithms + workspace(s) CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(Caffe::cudnn_handle(), bottom_descs_[i], filter_desc_, conv_descs_[i], top_descs_[i], CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT, workspace_limit_bytes, &fwd_algo_[i])); CUDNN_CHECK(cudnnGetConvolutionForwardWorkspaceSize(Caffe::cudnn_handle(), bottom_descs_[i], filter_desc_, conv_descs_[i], top_descs_[i], fwd_algo_[i], &(workspace_fwd_sizes_[i]))); // // choose backward algorithm for filter CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm( Caffe::cudnn_handle(), bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_, CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT, workspace_limit_bytes, &bwd_filter_algo_[i]) ); // get workspace for backwards filter algorithm CUDNN_CHECK(cudnnGetConvolutionBackwardFilterWorkspaceSize( Caffe::cudnn_handle(), bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_, bwd_filter_algo_[i], &workspace_bwd_filter_sizes_[i])); // choose backward algo for data CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm( Caffe::cudnn_handle(), filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i], CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT, workspace_limit_bytes, &bwd_data_algo_[i])); // get workspace size CUDNN_CHECK(cudnnGetConvolutionBackwardDataWorkspaceSize( Caffe::cudnn_handle(), filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i], bwd_data_algo_[i], &workspace_bwd_data_sizes_[i]) ); } // Tensor descriptor for bias. if (this->bias_term_) { cudnn::setTensor4dDesc<Dtype>(&bias_desc_, 1, this->num_output_ / this->group_, 1, 1); } } template <typename Dtype> CuDNNConvolutionLayer<Dtype>::~CuDNNConvolutionLayer() { // Check that handles have been setup before destroying. if (!handles_setup_) { return; } for (int i = 0; i < bottom_descs_.size(); i++) { cudnnDestroyTensorDescriptor(bottom_descs_[i]); cudnnDestroyTensorDescriptor(top_descs_[i]); cudnnDestroyConvolutionDescriptor(conv_descs_[i]); } if (this->bias_term_) { cudnnDestroyTensorDescriptor(bias_desc_); } cudnnDestroyFilterDescriptor(filter_desc_); delete [] fwd_algo_; delete [] bwd_filter_algo_; delete [] bwd_data_algo_; delete [] workspace_fwd_sizes_; delete [] workspace_bwd_data_sizes_; delete [] workspace_bwd_filter_sizes_; } INSTANTIATE_CLASS(CuDNNConvolutionLayer); } // namespace caffe #endif
[ "tinghuiz@eecs.berkeley.edu" ]
tinghuiz@eecs.berkeley.edu
257b4de54539869069cf22324226c1122443381d
5ffe8ebcf9028339da74ec6bf980f704fb48340c
/code/src/automaton/hoa/pa_consumer.h
2bdebd7cdcbca344089ac7115e7845d35230e1c0
[]
no_license
atollk/master-thesis
fca0c1c2fae0e825d72c620d35a0632b68189a01
94bba4a57e52886d5584fc57f5497553ccc52754
refs/heads/master
2021-10-15T08:16:47.879055
2019-02-05T13:35:48
2019-02-05T13:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
h
#pragma once #include "cpphoafparser/consumer/hoa_consumer_null.hh" #include "../parity.h" namespace tollk { namespace automaton { namespace hoa { // Abstract base class to consume a HOA file from an input stream and convert it to an automaton. class PAConsumer : public cpphoafparser::HOAConsumerNull { public: void addStartStates(const int_list& stateConjunction) override; void setAPs(const std::vector<std::string>& aps) override; void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override; void provideAcceptanceName(const std::string& name, const std::vector<cpphoafparser::IntOrString>& extraInfo) override; void notifyBodyStart() override; void addProperties(const std::vector<std::string>& properties) override; void addState(unsigned int id, std::shared_ptr<std::string> info, label_expr::ptr labelExpr, std::shared_ptr<int_list> accSignature) override; void addEdgeWithLabel(unsigned int stateId, label_expr::ptr labelExpr, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) override; void notifyEnd() override; // If one initial state is provided, updates the internal automaton to match that. If multiple are given, // introduces a new initial state to mimic their behaviour. virtual void FixInitialStates(const std::vector<unsigned int>& states) = 0; // Adds a labeled edge to the automaton (and removes the old one, for DPA). virtual void AddTransition(state_t from, symbol_t sym, state_t to) = 0; virtual const std::map<state_t, std::string>& GetStateLabels() const; protected: virtual ParityAutomaton* _get_automaton() = 0; std::map<state_t, std::string> state_labels; unsigned long aps; std::vector<unsigned int> initial_states; bool is_parity_mineven = false; bool is_deterministic = false; }; } } }
[ "tollkoetter.andreas@gmail.com" ]
tollkoetter.andreas@gmail.com
4fd04984450163dbba8938ce0d7e720605efe34d
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/MuonSpectrometer/MuonCalib/MdtCalib/MdtCalibT0/src/T0MTSettingsT0.cxx
8faa2d99796a88a02cad1e80e543ae5a1e96a9c6
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
416
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "MdtCalibT0/T0MTSettingsT0.h" namespace MuonCalib { T0MTSettingsT0 :: T0MTSettingsT0() : m_vbh_bin_content_rel(2.0), m_max_bin_width(10.0), m_min_background_bins(50), m_T_start(3.0), m_use_top_chi2(true), m_scramble_threshold(-1.0), m_slicing_chi2(-1.0), m_correct_rel_t0s(false) { } }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
9f589c787e5c9077ad459d289cc022c1dc57211d
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/084/736/CWE191_Integer_Underflow__char_fscanf_multiply_62b.cpp
fa8c79314a22dc1fed1dfab712edafaa5e182ed2
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,391
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__char_fscanf_multiply_62b.cpp Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-62b.tmpl.cpp */ /* * @description * CWE: 191 Integer Underflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: multiply * GoodSink: Ensure there will not be an underflow before multiplying data by 2 * BadSink : If data is negative, multiply by 2, which can cause an underflow * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE191_Integer_Underflow__char_fscanf_multiply_62 { #ifndef OMITBAD void badSource(char &data) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%c", &data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ void goodG2BSource(char &data) { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } /* goodB2G() uses the BadSource with the GoodSink */ void goodB2GSource(char &data) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%c", &data); } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
39f7a9ada505ef2c8cfb0c9551ca1052d11ffd7b
7b1bf5ce53385ceb237c20ed5a86f15f38267233
/Algorithm/BASIC_21.cpp
72156b581c11baca29a00206842002c8a4c9e8d9
[]
no_license
Halinen/Algorithm
b77f25671886fb881624ef72c543fd75affd76cd
6ca3cfeeb3d2bc86655ff7dc0c732702dfef1bfc
refs/heads/master
2022-04-06T12:10:26.044718
2019-12-16T07:21:33
2019-12-16T07:21:33
null
0
0
null
null
null
null
GB18030
C++
false
false
742
cpp
#include <iostream> #include<stdlib.h> #include<string> using namespace std; string ans; int n = 0; //思路:dfs算出An //由样例结果分析: //分割要打印的结果:前面的一堆括号 +“Ai+k)”,最后一个无')' //感谢@wlw大佬提供的递归解法 void dfs(int n, int t) { if (n == t + 1) return; ans = ans + "sin("; ans += to_string(n); if (t > n) { if (n % 2 == 1)//奇数 ans += '-'; else ans += '+'; } dfs(n + 1, t); ans += ')'; } int main() { cin >> n; string res; for (int i = 0; i < n-1; i++) { res = res + '('; } for (int i = 1, k = n; i <= n; i++, k--) { dfs(1, i); res += ans + '+' + to_string(k); if (k != 1) { res += ')'; } ans = ""; } cout << res; system("pause"); }
[ "kurisushiina@gmail.com" ]
kurisushiina@gmail.com
3b81e0dde1d42136d7e5c77c69ea4f0875b03c6e
826e447e86a7a24a25725b951e57fa71ef52e200
/BetInfoCS.cpp
2a554ab03fd778bd4801e9f006c055676376066a
[]
no_license
sportssmarty/SoccerBetting
59aac9e8d7c5a5f3c7f09ba5c2aded91cafb200b
d12c4d994c5f9c802f1ddb45d4686eba896a1d31
refs/heads/master
2021-03-12T23:52:23.956244
2012-05-10T19:31:42
2012-05-10T19:31:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
/* ========================================================== * * 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. * ========================================================== */ /* * BetInfoCS.cpp * * Created on: 12 Jan 2012 * Author: pj */ #include "BetInfoCS.h" BetInfo_CS::BetInfo_CS(string inpBetMarket, string inpBetChoice, string inpHtft, int inpGoals1,int inpGoals2, bool inpGreaterThanType): BetInfo(inpBetMarket,inpBetChoice, inpHtft), goals1(inpGoals1), goals2(inpGoals2), greaterThanType(inpGreaterThanType){ // TODO Auto-generated constructor stub } BetInfo_CS::~BetInfo_CS() { // TODO Auto-generated destructor stub } int BetInfo_CS::getGoals1() const { return goals1; } int BetInfo_CS::getGoals2() const { return goals2; } bool BetInfo_CS::isGreaterThanType() const { return greaterThanType; }
[ "fitzpatrick.pj@googlemail.com" ]
fitzpatrick.pj@googlemail.com
04f6363f4f978e0b8b8c8ed3bcba534a82647f67
e680718836cc68a9845ede290e033d2099629c9f
/xwzgServerSource/MsgServer/MSGSERVER/MAPGROUPKERNEL/Network/MsgName.h
71a3f958be6518fe9576b7f3c33c7302d4ec980c
[]
no_license
liu-jack/sxkmgf
77ebe2de8113b8bb7d63b87d71d721df0af86da8
5aa37b3efe49c3573a9169bcf0888f6ba8517254
refs/heads/master
2020-06-28T21:41:05.823423
2018-09-28T17:30:26
2018-09-28T17:30:26
null
0
0
null
null
null
null
GB18030
C++
false
false
4,137
h
// MsgName.h: interface for the CMsgName class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MSGNAME_H__62DB03E2_7185_4BDF_B9B0_5AE64B03DFDB__INCLUDED_) #define AFX_MSGNAME_H__62DB03E2_7185_4BDF_B9B0_5AE64B03DFDB__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "NetMsg.h" #include "NetStringPacker.h" enum { NAMEACT_NONE = 0, NAMEACT_FIREWORKS = 1, NAMEACT_CREATE_SYN = 2, // 改到TALK中 NAMEACT_SYNDICATE = 3, // 无法实现修改帮派名,仅下传 NAMEACT_CHANGE_SYNTITLE = 4, NAMEACT_DELROLE = 5, // 无意义 NAMEACT_MATE = 6, NAMEACT_QUERY_NPC = 7, // to server,to client NAMEACT_WANTED = 8, // to client NAMEACT_MAPEFFECT = 9, // to client NAMEACT_ROLEEFFECT = 10, NAMEACT_MEMBERLIST = 11, // to server/client, dwData is index MANEACT_KICKOUT_SYNMEM = 12, NAMEACT_QUERY_WANTED = 13, NAMEACT_QUERY_POLICEWANTED = 14, NAMEACT_POLICEWANTED = 15, NAMEACT_QUERY_MATE = 16, NAMEACT_ADDDICE_PLAYER = 17, //BcastClient(INCLUDE_SELF) 增加骰子玩家// dwData为骰子摊ID // To Server 加入 需要原消息返回 NAMEACT_DELDICE_PLAYER = 18, //BcastClient(INCLUDE_SELF) 删除骰子玩家// dwData为骰子摊ID // To Server 离开 需要原消息返回 NAMEACT_DICE_BONUS = 19, //BcastClient 报骰子奖金 玩家// dwData为Money NAMEACT_PLAYER_WAVE = 20, // 播音效 // 如果usPosX = usPosY = 0; 非地图音效 // 压入的字符串为音效的相对路径 NAMEACT_MEMBERLIST_SPECIFYSYN = 21, //查询指定帮派的成员列表 NAMEACT_PLAYERTASKLIST = 23, // 佣兵任务查询返回 NAMEACT_CHANGE_EUDEMON_NAME = 24, // 幻兽改名。idTarget=幻兽物品ID,第一个字符串为幻兽新名字 NAMEACT_CHANGE_DESC = 25, // 改自我介绍.. NAMEACT_REBORN_MSG = 26, //发送某人对你使用了复活术 NAMEACT_REBORN_ACCEPT = 27, //客户端发送过来同意复活. NAMEACT_CHANGE_EXPSCALE = 28, //客户端发送过来更改武器获得经验比例 NAMEACT_CHANGE_EXPSCALEOK = 29, //更改成功,发到客户端. NAMEACT_LOOK_DESC = 30, //查看别人的介绍 NAMEACT_REBORN_MSG_SR = 31, //2007828修罗:struggle relive死地后生.自我复活 NAMEACT_CHANGE_WPSLEXPSCALE = 32, //客户端发送过来更改武器泪灵获得经验比例 NAMEACT_CHANGE_WPSLEXPSCALEOK = 33, //更改成功,发到客户端. NAMEACT_CHANGE_QQ = 34, //更改qq NAMEACT_CHANGE_PROV = 35, //省 NAMEACT_CHANGE_CITY = 36, //市 NAMEACT_CHANGE_OLD = 37, //年龄 NAMEACT_CHANGE_STAR = 38, //星座 NAMEACT_CHANGE_BTSEX = 39, //性变态 NAMEACT_CHANGE_TITLE = 40, //[游途道标 2008/10/13]客户端发送过来更改称号 NAMEACT_CHANGE_TITLEOK = 41, //[游途道标 2008/10/13]称号更改成功,发到客户端. NAMEACT_CHANGE_HOLDTITLEOK = 42, //[游途道标 2008/10/14]拥有称号更改成功,发到客户端. NAMEACT_CHANGE_RECORDKEY = 43, //保存快捷键和技能栏 NAMEACT_HANDUP_BUG = 44, //提交问题 NAMEACT_SETLINE = 45,//[2009.07.06] NAMEACT_COPY_SYNNAME = 46, //复制帮派名 }; class CMsgName : public CNetMsg { public: CMsgName(); virtual ~CMsgName(); BOOL Create(int nType, const char* pszName, __int64 dwData=0); BOOL Create(int nType, const char* pszName, USHORT usPosX, USHORT usPosY); BOOL AppendStr(const char* pszName); public: BOOL Create (char* pMsgBuf, DWORD dwSize); void Process (void* pInfo); private: typedef struct{ MSGHEAD_DEFINE DWORD dwData; DWORD dwHData; union { OBJID idTarget; struct{ USHORT usPosX, usPosY; }; }; UCHAR ucType; DWORD dwSynData; char szBuf[1]; }MSG_Info; MSG_Info* m_pInfo; private: CNetStringPacker m_StrPacker; }; #endif // !defined(AFX_MSGNAME_H__62DB03E2_7185_4BDF_B9B0_5AE64B03DFDB__INCLUDED_)
[ "43676169+pablones@users.noreply.github.com" ]
43676169+pablones@users.noreply.github.com
821f9ce3c6c47eb028cc8566cecf52e571b64853
bd08dc8349ba4ab760dbb2e5144e7a40717adcbb
/Angel-3.0.1/Code/ClientGame/PixelArthGameManager.h
c1e742b713e05fd74363a66edfb6dbc5aba64da8
[]
no_license
MaliusArth/PixelArth
35b5bd78359a1756dda1ffd6b3878646cc8322c0
319c96b0dfafb2a53766be3db29623291463cabf
refs/heads/master
2021-03-12T20:10:31.536130
2019-09-06T12:31:23
2019-09-06T12:31:23
6,598,924
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
h
///////////////////////////////////////////////////////////////////////// // PixelArth // Copyright (C) 2012 Viktor Was <viktor.was@technikum-wien.at> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////// #pragma once #include <vector> #include <string> #include "Physics\CollisionHandler.h" #include "Physics\Bitmask.h" // Forward declaration class CloudActor; class GroundActor; class PixelArthScreen : public Renderable, public MessageListener { public: PixelArthScreen(); virtual void Start(); virtual void Stop(); // calls remove on all _objects and deletes them virtual void Update(float dt); virtual void Render(); virtual void ReceiveMessage(Message *message) {} Bitmask * const GetBitmask(const String& path); protected: std::vector<Renderable*> _objects; CloudActor *m_sky; GroundActor *m_ground; Actor *m_arth; private: std::map<String, Bitmask*> m_bitmaskmap; }; //PixelArthGameManager is a singleton and inherits from: // GameManager -- so we receive update and render calls, plus collision notifications #define thePixelArthGame PixelArthGameManager::GetInstance() class PixelArthGameManager : public GameManager { public: void MoveForwards(); void MoveBackwards(); static PixelArthGameManager &GetInstance(); PixelArthScreen* GetCurrentScreen(); virtual void Render(); virtual void SoundEnded(AngelSoundHandle sound); virtual void ReceiveMessage(Message* message); virtual void Update(float dt); CollisionHandler *m_collHandler; protected: PixelArthGameManager(); ~PixelArthGameManager(); static PixelArthGameManager *s_PixelArthGameManager; private: std::vector<PixelArthScreen*> _screens; PixelArthScreen* _mainMenu; PixelArthScreen* _gameOver; int _current; AngelSampleHandle sample; };
[ "if10b076@technikum-wien.at" ]
if10b076@technikum-wien.at
4bfc36e8a18950f72f4be759798a2d75699de5a6
4ffdbe7b92e54b0aa7a0a21d219a0c5dfdd304bc
/emViewer/object.h
2285c0a4db20402e7d9b38798c8fc4acc0657cfd
[]
no_license
YsChiao/Examples-of-Qt5-studies
73687458c0a54c631f766e29d4bfc2a20c7fc470
d3efa5686355ca739f451f766a742fb138dce33f
refs/heads/master
2016-08-12T09:10:04.394893
2016-04-13T13:40:27
2016-04-13T13:40:27
53,891,901
0
0
null
null
null
null
UTF-8
C++
false
false
4,213
h
#ifndef OBJECT_H #define OBJECT_H #include <cmath> #include <vector> #include <algorithm> #include <vtkAutoInit.h> VTK_MODULE_INIT(vtkRenderingOpenGL) VTK_MODULE_INIT(vtkRenderingVolumeOpenGL) VTK_MODULE_INIT(vtkInteractionStyle) #include <vtkSmartPointer.h> #include <vtkActor.h> #include <vtkImageData.h> #include <vtkImageActor.h> #include <vtkDataSetMapper.h> #include <vtkPiecewiseFunction.h> #include <vtkColorTransferFunction.h> #include <vtkVolume.h> #include <vtkVolumeProperty.h> #include <vtkSmartVolumeMapper.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleTrackballActor.h> #include <vtkOutlineSource.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkLine.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkUnsignedCharArray.h> #include "emfile.h" #include "tools.h" #include <QVTKWidget.h> #include <QtAlgorithms> class Object : public QVTKWidget { Q_OBJECT public: explicit Object(QWidget* parent = 0); ~Object(); void Axes(double xMax = 1.0, double yMax = 1.0, double zMax = 1.0); public slots: void open(); void getLevel(int value); signals: void sendMessage(QString& Message); void sendMaxMin(float max, float min); void sendFileName(QString& name); protected: QSize minimumSizeHint() const; QSize sizeHint() const; private: // read data from file void readFile(const QString& fileName); // get data size void Information(); // get the copy of data for manipulating void dataLoading(); // get the max and min data void FileDataMaxMin(float& max, float& min); // covert data from vector to VtkImageData format void FileDataToVtkImageData(); // rendering and display void drawVolume(); // data flow : FileDataMaxMin, FileDataToVtkImageData, drawVolume void VolumeProcessing(); // get volume origin, position, center, orientation, scale information void getVolumeInformation(); // original data EmFile emFile; // copy data std::vector<unsigned char> byteData; std::vector<int> intData; std::vector<float> floatData; // copy data dimentions int dims[3]; // coppy data type unsigned char fileType; // filter value, default 0 float levelValue; // vtk rendering class vtkSmartPointer<vtkImageData> imageData; vtkSmartPointer<vtkSmartVolumeMapper> volumeMapper; vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction; vtkSmartPointer<vtkPiecewiseFunction> volumeGradientOpacity; vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction; vtkSmartPointer<vtkVolumeProperty> volumeProperty; vtkSmartPointer<vtkVolume> volume; vtkSmartPointer<vtkRenderer> renderer; // // vtk outline class // vtkSmartPointer<vtkOutlineSource> outlineSource; // vtkSmartPointer<vtkPolyDataMapper> outlineMapper; // vtkSmartPointer<vtkActor> outlineActor; // create a vtkPoints container and store the points in it vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); // add the points to the polydata container vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New(); // create lines vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New(); vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New(); vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New(); // Create a vtkCellArray container and store the lines in it vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); // Create a vtkUnsignedCharArray container and store the colors in it vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New(); // Setup the visualization pipeline vtkSmartPointer<vtkPolyDataMapper> linesMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); vtkSmartPointer<vtkActor> linesActor = vtkSmartPointer<vtkActor>::New(); // set interactor style, actor mode vtkSmartPointer<vtkInteractorStyleTrackballActor> style_actor; }; #endif // OBJECT_H
[ "yis.qiao@gmail.com" ]
yis.qiao@gmail.com
2bbe5cc98f3c5fc1c6328baea55a8b19bcdd2f6b
28fa850b13211cb4e114d8a8878ed68d72c7c8a6
/Source/ZombieGame/ZombieGameCharacter.cpp
1e4d39c842f7e7bef3bb0102b5f5fb6cec6d4b5f
[ "MIT" ]
permissive
dmarino/zombieCuteness
e2cb1fa13060aa31759f19b2c40592adbe5c98c4
317e98e290e37363173eb286679d27bb92f059ab
refs/heads/main
2023-03-17T18:53:46.548739
2021-03-07T04:02:01
2021-03-07T04:02:01
345,251,357
0
0
null
null
null
null
UTF-8
C++
false
false
11,729
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "ZombieGameCharacter.h" #include "ZombieGameProjectile.h" #include "Animation/AnimInstance.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/InputSettings.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Kismet/GameplayStatics.h" #include "MotionControllerComponent.h" #include "XRMotionControllerBase.h" // for FXRMotionControllerBase::RightHandSourceId DEFINE_LOG_CATEGORY_STATIC(LogFPChar, Warning, All); ////////////////////////////////////////////////////////////////////////// // AZombieGameCharacter AZombieGameCharacter::AZombieGameCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(55.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Create a CameraComponent FirstPersonCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera")); FirstPersonCameraComponent->SetupAttachment(GetCapsuleComponent()); FirstPersonCameraComponent->SetRelativeLocation(FVector(-39.56f, 1.75f, 64.f)); // Position the camera FirstPersonCameraComponent->bUsePawnControlRotation = true; // Create a mesh component that will be used when being viewed from a '1st person' view (when controlling this pawn) Mesh1P = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh1P")); Mesh1P->SetOnlyOwnerSee(true); Mesh1P->SetupAttachment(FirstPersonCameraComponent); Mesh1P->bCastDynamicShadow = false; Mesh1P->CastShadow = false; Mesh1P->SetRelativeRotation(FRotator(1.9f, -19.19f, 5.2f)); Mesh1P->SetRelativeLocation(FVector(-0.5f, -4.4f, -155.7f)); // Create a gun mesh component FP_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FP_Gun")); FP_Gun->SetOnlyOwnerSee(true); // only the owning player will see this mesh FP_Gun->bCastDynamicShadow = false; FP_Gun->CastShadow = false; // FP_Gun->SetupAttachment(Mesh1P, TEXT("GripPoint")); FP_Gun->SetupAttachment(RootComponent); FP_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("MuzzleLocation")); FP_MuzzleLocation->SetupAttachment(FP_Gun); FP_MuzzleLocation->SetRelativeLocation(FVector(0.2f, 48.4f, -10.6f)); // Default offset from the character location for projectiles to spawn GunOffset = FVector(100.0f, 0.0f, 10.0f); // Note: The ProjectileClass and the skeletal mesh/anim blueprints for Mesh1P, FP_Gun, and VR_Gun // are set in the derived blueprint asset named MyCharacter to avoid direct content references in C++. // Create VR Controllers. R_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("R_MotionController")); R_MotionController->MotionSource = FXRMotionControllerBase::RightHandSourceId; R_MotionController->SetupAttachment(RootComponent); L_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("L_MotionController")); L_MotionController->SetupAttachment(RootComponent); // Create a gun and attach it to the right-hand VR controller. // Create a gun mesh component VR_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("VR_Gun")); VR_Gun->SetOnlyOwnerSee(true); // only the owning player will see this mesh VR_Gun->bCastDynamicShadow = false; VR_Gun->CastShadow = false; VR_Gun->SetupAttachment(R_MotionController); VR_Gun->SetRelativeRotation(FRotator(0.0f, -90.0f, 0.0f)); VR_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("VR_MuzzleLocation")); VR_MuzzleLocation->SetupAttachment(VR_Gun); VR_MuzzleLocation->SetRelativeLocation(FVector(0.000004, 53.999992, 10.000000)); VR_MuzzleLocation->SetRelativeRotation(FRotator(0.0f, 90.0f, 0.0f)); // Counteract the rotation of the VR gun model. // Uncomment the following line to turn motion controllers on by default: //bUsingMotionControllers = true; PrimaryActorTick.bCanEverTick = true; } void AZombieGameCharacter::BeginPlay() { // Call the base class Super::BeginPlay(); //Attach gun mesh component to Skeleton, doing it here because the skeleton is not yet created in the constructor FP_Gun->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("GripPoint")); // Show or hide the two versions of the gun based on whether or not we're using motion controllers. if (bUsingMotionControllers) { VR_Gun->SetHiddenInGame(false, true); Mesh1P->SetHiddenInGame(true, true); } else { VR_Gun->SetHiddenInGame(true, true); Mesh1P->SetHiddenInGame(false, true); } } ////////////////////////////////////////////////////////////////////////// // Input void AZombieGameCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // set up gameplay key bindings check(PlayerInputComponent); // Bind jump events PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); // Bind fire event PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AZombieGameCharacter::OnFire); // Enable touchscreen input EnableTouchscreenMovement(PlayerInputComponent); PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AZombieGameCharacter::OnResetVR); // Bind movement events PlayerInputComponent->BindAxis("MoveForward", this, &AZombieGameCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AZombieGameCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AZombieGameCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AZombieGameCharacter::LookUpAtRate); } void AZombieGameCharacter::OnFire() { // try and fire a projectile if (ProjectileClass != NULL) { UWorld* const World = GetWorld(); if (World != NULL) { if (bUsingMotionControllers) { const FRotator SpawnRotation = VR_MuzzleLocation->GetComponentRotation(); const FVector SpawnLocation = VR_MuzzleLocation->GetComponentLocation(); if(isInDeadlyState){ World->SpawnActor<AZombieGameProjectile>(DeadlyProjectileClass, SpawnLocation, SpawnRotation); } else{ World->SpawnActor<AZombieGameProjectile>(ProjectileClass, SpawnLocation, SpawnRotation); } } else { const FRotator SpawnRotation = GetControlRotation(); // MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle position const FVector SpawnLocation = ((FP_MuzzleLocation != nullptr) ? FP_MuzzleLocation->GetComponentLocation() : GetActorLocation()) + SpawnRotation.RotateVector(GunOffset); //Set Spawn Collision Handling Override FActorSpawnParameters ActorSpawnParams; ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding; // spawn the projectile at the muzzle if(isInDeadlyState){ World->SpawnActor<AZombieGameProjectile>(DeadlyProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);} else{ World->SpawnActor<AZombieGameProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams); } } } } // try and play the sound if specified if (FireSound != NULL) { UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation()); } // try and play a firing animation if specified if (FireAnimation != NULL) { // Get the animation object for the arms mesh UAnimInstance* AnimInstance = Mesh1P->GetAnimInstance(); if (AnimInstance != NULL) { AnimInstance->Montage_Play(FireAnimation, 1.f); } } } void AZombieGameCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AZombieGameCharacter::BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location) { if (TouchItem.bIsPressed == true) { return; } if ((FingerIndex == TouchItem.FingerIndex) && (TouchItem.bMoved == false)) { OnFire(); } TouchItem.bIsPressed = true; TouchItem.FingerIndex = FingerIndex; TouchItem.Location = Location; TouchItem.bMoved = false; } void AZombieGameCharacter::EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location) { if (TouchItem.bIsPressed == false) { return; } TouchItem.bIsPressed = false; } //Commenting this section out to be consistent with FPS BP template. //This allows the user to turn without using the right virtual joystick //void AZombieGameCharacter::TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location) //{ // if ((TouchItem.bIsPressed == true) && (TouchItem.FingerIndex == FingerIndex)) // { // if (TouchItem.bIsPressed) // { // if (GetWorld() != nullptr) // { // UGameViewportClient* ViewportClient = GetWorld()->GetGameViewport(); // if (ViewportClient != nullptr) // { // FVector MoveDelta = Location - TouchItem.Location; // FVector2D ScreenSize; // ViewportClient->GetViewportSize(ScreenSize); // FVector2D ScaledDelta = FVector2D(MoveDelta.X, MoveDelta.Y) / ScreenSize; // if (FMath::Abs(ScaledDelta.X) >= 4.0 / ScreenSize.X) // { // TouchItem.bMoved = true; // float Value = ScaledDelta.X * BaseTurnRate; // AddControllerYawInput(Value); // } // if (FMath::Abs(ScaledDelta.Y) >= 4.0 / ScreenSize.Y) // { // TouchItem.bMoved = true; // float Value = ScaledDelta.Y * BaseTurnRate; // AddControllerPitchInput(Value); // } // TouchItem.Location = Location; // } // TouchItem.Location = Location; // } // } // } //} void AZombieGameCharacter::MoveForward(float Value) { if (Value != 0.0f) { // add movement in that direction AddMovementInput(GetActorForwardVector(), Value); } } void AZombieGameCharacter::MoveRight(float Value) { if (Value != 0.0f) { // add movement in that direction AddMovementInput(GetActorRightVector(), Value); } } void AZombieGameCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AZombieGameCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } bool AZombieGameCharacter::EnableTouchscreenMovement(class UInputComponent* PlayerInputComponent) { if (FPlatformMisc::SupportsTouchInput() || GetDefault<UInputSettings>()->bUseMouseForTouch) { PlayerInputComponent->BindTouch(EInputEvent::IE_Pressed, this, &AZombieGameCharacter::BeginTouch); PlayerInputComponent->BindTouch(EInputEvent::IE_Released, this, &AZombieGameCharacter::EndTouch); //Commenting this out to be more consistent with FPS BP template. //PlayerInputComponent->BindTouch(EInputEvent::IE_Repeat, this, &AZombieGameCharacter::TouchUpdate); return true; } return false; } void AZombieGameCharacter::GoDeadly() { currentDeadlyTime = maxTimeInDeadlymode; isInDeadlyState = true; } // Called every frame void AZombieGameCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); timeAlive += DeltaTime; if (isInDeadlyState) { if (currentDeadlyTime > 0) { currentDeadlyTime -= DeltaTime; } else { isInDeadlyState = false; } } }
[ "d.marino10@uniandes.edu.co" ]
d.marino10@uniandes.edu.co
a9d6b0b91d4759c6b11b698d822811dead22e750
3cc887ae3cf3f00b69163f589a802cda4549967f
/build/otl_datetime_conversion.cpp
1767ba71dd6bc205945122be15c5eef468879496
[]
no_license
GerHobbelt/otl
3ac0841fe0f35e4c68a7b636a9a03381f885792d
887da8501c451eceae2986db4d8b49e749156f91
refs/heads/master
2023-08-11T17:21:12.674001
2022-02-06T00:07:20
2022-02-06T00:07:20
4,427,315
27
22
null
null
null
null
UTF-8
C++
false
false
13,225
cpp
/* * XXXX deleted info XXXX */ //#include "generic_support.h" #error "do not compile this one" #include <sstream> #include <math.h> void otl_str_to_tm(const char *str, otl_datetime &tm) { tm.fraction = 0; #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) tm.tz_hour = 0; tm.tz_minute = 0; #endif int rv = sscanf(str, "%04d-%02d-%02d %02d:%02d:%02d.%03lu" #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) " %hd:%hd" #endif "", &tm.year, &tm.month, &tm.day, &tm.hour, &tm.minute, &tm.second, &tm.fraction #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) , &tm.tz_hour, &tm.tz_minute #endif ); tm.frac_precision = min(3, otl_odbc_date_scale); tm.fraction = otl_to_fraction(tm.fraction, tm.frac_precision); if (rv == 6) { rv = sscanf(str, "%04d-%02d-%02d %02d:%02d:%02d" #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) " %hd:%hd" #endif "", &tm.year, &tm.month, &tm.day, &tm.hour, &tm.minute, &tm.second #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) , &tm.tz_hour, &tm.tz_minute #endif ); tm.fraction = 0; tm.frac_precision = 0; } } void otl_ts_to_str(const otl_datetime &tm, char str[100]) { if (otl_odbc_date_scale == 0) { sprintf(str, "%04d-%02d-%02d %02d:%02d:%02d" #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) " %+hd:%hd" #endif "", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) , tm.tz_hour, tm.tz_minute #endif ); } else { int prec = min(3, otl_odbc_date_scale); sprintf(str, "%04d-%02d-%02d %02d:%02d:%02d.%0*u" #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) " %+hd:%hd" #endif "", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, prec, otl_from_fraction(tm.fraction, prec) #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) , tm.tz_hour, tm.tz_minute #endif ); } } otl_datetime &cvt_SystemTime2OTL_datetime(otl_datetime &dst, const SYSTEMTIME *src) { if (!src) { otl_datetime t; dst = t; } else { dst = otl_datetime(src->wYear, src->wMonth, src->wDay, src->wHour, src->wMinute, src->wSecond, src->wMilliseconds, 3); } return dst; } otl_datetime &cvt_FileTime2OTL_datetime(otl_datetime &dst, const FILETIME *src) { SYSTEMTIME t; if (src && FileTimeToSystemTime(src, &t)) { cvt_SystemTime2OTL_datetime(dst, &t); // check the subsecond part: see if we need to improve on the default millisecond conversion LARGE_INTEGER fi; fi.HighPart = src->dwHighDateTime; fi.LowPart = src->dwLowDateTime; fi.QuadPart %= 10000000; if (fi.QuadPart % 10000 != 0) { // subsecond part doesn't fit in the default 'millisecond' fraction precision: adjust! dst.fraction = otl_to_fraction(unsigned int(fi.QuadPart), 7); dst.frac_precision = 7; } return dst; } else { otl_datetime t; dst = t; return dst; } } otl_datetime &cvt_datetimestamp2OTL_datetime(otl_datetime &dst, datetimestamp src) { FILETIME ft; LARGE_INTEGER i; i.QuadPart = src; ft.dwHighDateTime = i.HighPart; ft.dwLowDateTime = i.LowPart; return cvt_FileTime2OTL_datetime(dst, &ft); } SYSTEMTIME &cvt_OTL_datetime2SystemTime(SYSTEMTIME &dst, const otl_datetime *src) { if (src) { FILETIME ft; dst.wYear = WORD(src->year); dst.wMonth = WORD(src->month); dst.wDay = WORD(src->day); dst.wHour = WORD(src->hour); dst.wMinute = WORD(src->minute); dst.wSecond = WORD(src->second); dst.wMilliseconds = WORD(otl_from_fraction(src->fraction, 3)); dst.wDayOfWeek = 0; // to get at the weekday, we convert back & forth: if (SystemTimeToFileTime(&dst, &ft)) { if (FileTimeToSystemTime(&ft, &dst)) { return dst; } } // when we get here, the date/timestamp in [src] is bad: out of allowable range or other cruft in sitting in there. // signal this by returning a 'zero' time. } memset(&dst, 0, sizeof(dst)); return dst; } FILETIME &cvt_OTL_datetime2FileTime(FILETIME &dst, const otl_datetime *src) { SYSTEMTIME st; cvt_OTL_datetime2SystemTime(st, src); if (src && SystemTimeToFileTime(&st, &dst)) { // check if we need to do a better transfer of the subsecond fraction: if (src->frac_precision > 3) { unsigned int nsec100 = otl_from_fraction(src->fraction, 7); nsec100 %= 10000; if (nsec100 != 0) { // subsecond part doesn't fit in the default 'millisecond' fraction precision: adjust! dst.dwLowDateTime += nsec100; } } return dst; } dst.dwHighDateTime = 0; dst.dwLowDateTime = 0; return dst; } datetimestamp cvt_OTL_datetime2datetimestamp(const otl_datetime *src) { if (src) { FILETIME ft; LARGE_INTEGER i; SYSTEMTIME dst; dst.wYear = WORD(src->year); dst.wMonth = WORD(src->month); dst.wDay = WORD(src->day); dst.wHour = WORD(src->hour); dst.wMinute = WORD(src->minute); dst.wSecond = WORD(src->second); dst.wMilliseconds = WORD(otl_from_fraction(src->fraction, 3)); dst.wDayOfWeek = 0; if (SystemTimeToFileTime(&dst, &ft)) { i.HighPart = ft.dwHighDateTime; i.LowPart = ft.dwLowDateTime; datetimestamp rv = i.QuadPart; // check if we need to do a better transfer of the subsecond fraction: if (src->frac_precision > 3) { rv -= rv % 10000000; rv += otl_from_fraction(src->fraction, 7); } return rv; } // when we get here, the date/timestamp in [src] is bad: out of allowable range or other cruft in sitting in there. // signal this by returning a 'zero' time. } return 0; } double cvt_OTL_datetime2excel_datetime(const otl_datetime *src, bool in_1904_mode) { double ret = 0.0; if (src) { datetimestamp t = cvt_OTL_datetime2datetimestamp(src); static bool init_done = false; static datetimestamp offsets[2] = { 0 }; if (!init_done) { otl_datetime epoch0(1900, 1, 1, 0, 0, 0, 0, 0); otl_datetime epoch1(1904, 1, 1, 0, 0, 0, 0, 0); epoch0 -= 2 * ONE_DAY; // Excel believes 1900 is a leap year: correct for that here epoch1 -= 1 * ONE_DAY; offsets[0] = cvt_OTL_datetime2datetimestamp(&epoch0); offsets[1] = cvt_OTL_datetime2datetimestamp(&epoch1); init_done = true; } t -= offsets[in_1904_mode]; ret = t / double(ONE_DAY); if (ret < 0.0) ret = 0.0; else if (ret > (2100 - 1900) * 365) ret = 0.0; } return ret; } datetimestamp cvt_SystemTime2datetimestamp(const SYSTEMTIME *src) { if (src) { FILETIME ft; LARGE_INTEGER i; if (SystemTimeToFileTime(src, &ft)) { i.HighPart = ft.dwHighDateTime; i.LowPart = ft.dwLowDateTime; return i.QuadPart; } // when we get here, the date/timestamp in [src] is bad: out of allowable range or other cruft in sitting in there. // signal this by returning a 'zero' time. } return 0; } datetimestamp cvt_FileTime2datetimestamp(const FILETIME *src) { if (src) { LARGE_INTEGER i; i.HighPart = src->dwHighDateTime; i.LowPart = src->dwLowDateTime; return i.QuadPart; } // when we get here, the date/timestamp in [src] is bad: out of allowable range or other cruft in sitting in there. // signal this by returning a 'zero' time. return 0; } SYSTEMTIME &cvt_datetimestamp2SystemTime(SYSTEMTIME &dst, datetimestamp src) { FILETIME ft; LARGE_INTEGER i; i.QuadPart = src; ft.dwHighDateTime = i.HighPart; ft.dwLowDateTime = i.LowPart; if (FileTimeToSystemTime(&ft, &dst)) { return dst; } memset(&dst, 0, sizeof(dst)); return dst; } /* * clip datetime to within the range year [min..max], * i.e. minyear/jan/1 00:00:00.000 and maxyear/dec/31 23:59:59.999... */ otl_datetime &clip_datetime2min_max(otl_datetime &dst, int min_year, int max_year) { if (dst.year < min_year) { dst = otl_datetime(min_year, 1, 1, 0, 0, 0); } else if (dst.year > max_year) { dst = otl_datetime(max_year, 12, 31, 23, 59, 59, 999999999, 9); } return dst; } /* * clip at end / start to ensure begin- end are not farther apart than [timespan] * * Return !0 when clipping occurred. */ int limit_datetime_range(otl_datetime &begin, otl_datetime &end, timespan span, bool clip_at_end) { FILETIME s; FILETIME e; LARGE_INTEGER si; LARGE_INTEGER ei; cvt_OTL_datetime2FileTime(s, &begin); cvt_OTL_datetime2FileTime(e, &end); si.HighPart = s.dwHighDateTime; si.LowPart = s.dwLowDateTime; ei.HighPart = e.dwHighDateTime; ei.LowPart = e.dwLowDateTime; // both are in 100nsec units, so no scaling required :-) if (ei.QuadPart - si.QuadPart > span) { if (clip_at_end) { ei.QuadPart = si.QuadPart + span; e.dwHighDateTime = ei.HighPart; e.dwLowDateTime = ei.LowPart; cvt_FileTime2OTL_datetime(end, &e); return 1; } else { si.QuadPart = ei.QuadPart - span; s.dwHighDateTime = si.HighPart; s.dwLowDateTime = si.LowPart; cvt_FileTime2OTL_datetime(begin, &s); return 1; } } return 0; } // a > b ? int otl_compare_tm(const otl_datetime &a, const otl_datetime &b) { #if defined(OTL_ORA_TIMESTAMP) || defined(OTL_ODBC_TIME_ZONE) // TBD: adjust tm for tz! #error TBD if (!diff) diff = a.tz_hour - b.tz_hour; if (!diff) diff = a.tz_minute - b.tz_minute; #endif int diff = a.year - b.year; if (!diff) diff = a.month - b.month; if (!diff) diff = a.day - b.day; if (!diff) diff = a.hour - b.hour; if (!diff) diff = a.minute - b.minute; if (!diff) diff = a.second - b.second; if (!diff) diff = int(a.fraction) - int(b.fraction); if (diff > 0) return 1; else if (diff < 0) return -1; return 0; } bool operator ==(const otl_datetime &a, const otl_datetime &b) { return 0 == otl_compare_tm(a, b); } bool operator !=(const otl_datetime &a, const otl_datetime &b) { return 0 != otl_compare_tm(a, b); } bool operator >(const otl_datetime &a, const otl_datetime &b) { return 0 < otl_compare_tm(a, b); } bool operator >=(const otl_datetime &a, const otl_datetime &b) { return 0 <= otl_compare_tm(a, b); } bool operator <(const otl_datetime &a, const otl_datetime &b) { return 0 > otl_compare_tm(a, b); } bool operator <=(const otl_datetime &a, const otl_datetime &b) { return 0 >= otl_compare_tm(a, b); } timespan operator -(const otl_datetime &a, const otl_datetime &b) { datetimestamp ta = cvt_OTL_datetime2datetimestamp(&a); datetimestamp tb = cvt_OTL_datetime2datetimestamp(&b); return (timespan)ta - (timespan)tb; } #if 0 timespan operator -(const datetimestamp &a, const datetimestamp &b) { return (timespan)a - (timespan)b; } #endif otl_datetime &operator +(const otl_datetime &t, timespan duration) { otl_datetime rv = t; return datetime_add_timespan(rv, duration); } otl_datetime &operator +(timespan duration, const otl_datetime &t) { otl_datetime rv = t; return datetime_add_timespan(rv, duration); } otl_datetime &operator -(const otl_datetime &t, timespan duration) { otl_datetime rv = t; return datetime_add_timespan(rv, -duration); } otl_datetime &operator -(timespan duration, const otl_datetime &t) { otl_datetime rv = t; return datetime_add_timespan(rv, -duration); } otl_datetime &operator +=(otl_datetime &t, timespan duration) { return datetime_add_timespan(t, duration); } otl_datetime &operator -=(otl_datetime &t, timespan duration) { return datetime_add_timespan(t, -duration); } otl_datetime &datetime_add_timespan(otl_datetime &dst, timespan duration) { FILETIME ft; LARGE_INTEGER fi; cvt_OTL_datetime2FileTime(ft, &dst); fi.HighPart = ft.dwHighDateTime; fi.LowPart = ft.dwLowDateTime; fi.QuadPart += duration; ft.dwHighDateTime = fi.HighPart; ft.dwLowDateTime = fi.LowPart; cvt_FileTime2OTL_datetime(dst, &ft); return dst; } /* * return offset since midnight in [seconds]. */ int time_offset_within_day(const otl_datetime &date) { datetimestamp d = cvt_OTL_datetime2datetimestamp(&date); d %= ONE_DAY; return int((d + 5000000) / 10000000); } otl_datetime &zero_hours(otl_datetime &t) { t.hour = 0; t.minute = 0; t.second = 0; t.fraction = 0; t.frac_precision = 0; return t; } datetimestamp &zero_hours(datetimestamp &t) { t -= (t % ONE_DAY); return t; } otl_datetime &yesterday(otl_datetime &t) { zero_hours(t); t -= ONE_DAY; return t; } datetimestamp &yesterday(datetimestamp &t) { zero_hours(t); t -= ONE_DAY; return t; } otl_datetime &tomorrow(otl_datetime &t) { zero_hours(t); t += ONE_DAY; return t; } datetimestamp &tomorrow(datetimestamp &t) { zero_hours(t); t += ONE_DAY; return t; } datetimestamp now_UTC(void) { FILETIME start_time; GetSystemTimeAsFileTime(&start_time); return cvt_FileTime2datetimestamp(&start_time); }
[ "ger@hobbelt.com" ]
ger@hobbelt.com
777684469006b7dff7788f2c4be946dac056d7a2
4e15ae057c309dea9a608cc03482d80497503b8d
/Notepad/my_notepad.cpp
b344ece3738ccf2da249e19172b06ca22d6b81c6
[]
no_license
ParthTrada/Notepad
a4ef526d58954e9effc1653fb5aeb64a6e55b6d5
a63c3f4c7c2e4558f8ad1e7cca2a2644c25bfa1e
refs/heads/main
2023-04-25T08:30:23.868058
2021-05-08T08:24:44
2021-05-08T08:24:44
306,708,092
0
0
null
null
null
null
UTF-8
C++
false
false
5,049
cpp
#include "my_notepad.h" #include "ui_notepad.h" #include <QFile> #include <QFileDialog> #include <QTextStream> #include <QMessageBox> #include <QFont> #include <QLabel> Notepad::Notepad(QWidget *parent) : QMainWindow(parent) , ui(new Ui::Notepad) { ui->setupUi(this); this->setCentralWidget(ui->textEdit); } Notepad::~Notepad() { delete ui; } void Notepad::on_actionOpen_triggered() { QString file_name = QFileDialog::getOpenFileName(this,"Open the file"); QFile file(file_name); file_path_ = file_name; if(!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this,"..","file note open"); return; } QTextStream in(&file); QString text = in.readAll(); ui->textEdit->setText(text); file.close(); } void Notepad::on_actionSave_triggered() { QFile file(file_path_); if(!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this,"..","file note open"); return; } QTextStream out(&file); QString text = ui->textEdit->toPlainText(); out << text; file.flush(); file.close(); } void Notepad::on_actionSave_as_triggered() { QString file_name = QFileDialog::getSaveFileName(this,"Open the file"); QFile file(file_name); file_path_ = file_name; if(!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this,"..","file note open"); return; } QTextStream out(&file); QString text = ui->textEdit->toPlainText(); out << text; file.flush(); file.close(); } void Notepad::on_actionCut_triggered() { ui->textEdit->cut(); } void Notepad::on_actionCopy_triggered() { ui->textEdit->copy(); } void Notepad::on_actionPaste_triggered() { ui->textEdit->paste(); } void Notepad::on_actionRedo_triggered() { ui->textEdit->redo(); } void Notepad::on_actionUndo_triggered() { ui->textEdit->undo(); } void Notepad::on_actionNew_triggered() { file_path_ = ""; ui->textEdit->setText(""); } void Notepad::on_actionAbout_Me_triggered() { QString text ="<P><b><font color='#000000', font size=35 >"; text .append("PARTH TRADA\n"); text .append("</font></b></P></br>"); text .append("<font-size=10> Email : parth.s.trada@gmail.com</font></P>"); text .append("<P>-------------------------------------------------------------------------------------------------</P>"); text .append("<P><b><font-size=20>◦ EDUCATION \n</font></b></P>"); text .append("<font-size=10> Dharmsinh Desai University </font>"); text .append("<P><i><font-size=10> Electronics and Communications Enginnering(2017-2021) </font></i></P>"); text .append("<P>-------------------------------------------------------------------------------------------------</P>"); text .append("<P><b><font-size=20>◦ EXPERIENCE </font></b></P>"); text .append("<P><font-size=10><b>1.</b> Softsensor.ai <i>(Deep Learning Intern)</i> </font></P>"); text .append("<P><font-size=10>◦ Subject: Write a research paper on CAMELYON 17 grand challenge problem and build automated methods for tissue and micro environment analytics. </font></P>"); text .append("<P><font-size=10><b>2.</b> Technocolabs <i>(Computer Vision Intern)</i></font></P>"); text .append("<P><font-size=10>◦ Goal: I have worked on COVID 19 face mask detection android application.</font></P>"); text .append("<P>-------------------------------------------------------------------------------------------------</P>"); text .append("<P><b><font-size=20>◦ TRAINING </font></b></P>"); text .append("<P><font-size=10><b>1.</b> Machine Learning </font></P>"); text .append("<P><font-size=10>This course provides me a broad introduction to machine learning, datamining, and statistical pattern recognition.I completed this course on coursera.</font></P>"); text .append("<P>-------------------------------------------------------------------------------------------------</P>"); text .append("<P><b><font-size=20>◦ PROJECTS </font></b></P>"); text .append("<P><font-size=10><b>1.</b> Stock Prediction Forecasting </font></P>"); text .append("<P><font-size=10>Build Stock Price Forecasting Machine learning model on historical data from yahoo finance, FRED, and some financial site.</font></P>"); text .append("<P><font-size=10><b>2.</b> Breast Cancer Image Classification </font></P>"); text .append("<P><font-size=10>Build CNN classifier to identify breast cancer from images.</font></P>"); text .append("<P>-------------------------------------------------------------------------------------------------</P>"); text .append("<P><b><font-size=20>◦ PUBLICATIONS </font></b></P>"); text .append("<P><font-size=10><b>1.</b> Lunar Crater Detection Walkthrough - A Review <i>(IRJET)</i> </font></P>"); text .append("<P><font-size=10><b>2.</b> Machine Learning based Analysis of Industry Finances Subjected to Bankruptcy <i>(IRJET)</i></font></P>"); QMessageBox::about(this,"Resume",text); }
[ "noreply@github.com" ]
noreply@github.com
2452f0f3ede3d3b538072d5cd3fe0f8ae5bacf3c
1330fb2a3851505437d9679e5c7e75851d0e4044
/compile-front-end/src/regex.cpp
680fef40ebbecd6ed23f13bca0c9d2bf023e6da8
[]
no_license
warsonchou/compiler
1cb0cdbde527a258edcaa7fd9ded8ac06f9812e7
08f31c01cd683f068a669e433eccfbed4e6c6f64
refs/heads/master
2021-05-31T18:04:12.806940
2016-02-25T02:49:55
2016-02-25T02:49:55
52,490,140
1
0
null
null
null
null
UTF-8
C++
false
false
19,226
cpp
#ifndef REGEX_H #define REGEX_H /* * Regular expression implementation. * Supports traditional egrep syntax, plus non-greedy operators. * Tracks submatches a la traditional backtracking. * * Normally finds leftmost-biased (traditional backtracking) match; * run with -l to get leftmost-longest match (but not POSIX submatches). * * Normally executes repetitions as much as possible, but no more than * necessary -- i.e. no unnecessary repeats that match the empty string -- * but this differs from Perl. Run with -p to get exact Perl behavior. * * Copyright (c) 2007 Russ Cox. * Can be distributed under the MIT license, see bottom of file. */ #include <iostream> #include <vector> #include <set> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> using namespace std; enum { LeftmostBiased = 0, LeftmostLongest = 1, }; enum { RepeatMinimal = 0, RepeatLikePerl = 1, }; int debug; int matchtype = LeftmostBiased; int reptype = RepeatMinimal; enum { NSUB = 10 }; typedef struct Sub Sub; struct Sub { const char *sp; const char *ep; }; enum { CharIncluded = 0, CharExcluded = 1, }; enum { NCHAR = 128, }; typedef struct Range Range; struct Range { int type; char flag[NCHAR]; }; typedef union Data Data; union Data { int val; Range range; }; enum { Char = 1, Any = 2, Split = 3, LParen = 4, RParen = 5, Match = 6, CharClass = 7, }; typedef struct State State; typedef struct Thread Thread; struct State { int op; Data data; State *out; State *out1; int id; int lastlist; int visits; Thread *lastthread; }; struct Thread { State *state; Sub match[NSUB]; }; typedef struct List List; struct List { Thread *t; int n; }; State matchstate = { Match }; int nstate; int listid; List l1, l2; /* Allocate and initialize State */ State* state(int op, int val, State *out, State *out1) { State *s; nstate++; s = (State *)malloc(sizeof *s); s->lastlist = 0; s->op = op; s->data.val = val; s->out = out; s->out1 = out1; s->id = nstate; return s; } /* Allocate and initialize CharClass State */ State* ccstate(int op, Range range, State *out, State *out1) { State *s; nstate++; s = (State *)malloc(sizeof *s); s->lastlist = 0; s->op = op; s->data.range = range; s->out = out; s->out1 = out1; s->id = nstate; return s; } typedef struct Frag Frag; typedef union Ptrlist Ptrlist; struct Frag { State *start; Ptrlist *out; }; /* Initialize Frag struct. */ Frag frag(State *start, Ptrlist *out) { Frag n = { start, out }; return n; } /* * Since the out pointers in the list are always * uninitialized, we use the pointers themselves * as storage for the Ptrlists. */ union Ptrlist { Ptrlist *next; State *s; }; /* Create singleton list containing just outp. */ Ptrlist* list1(State **outp) { Ptrlist *l; l = (Ptrlist*)outp; l->next = NULL; return l; } /* Patch the list of states at out to point to start. */ void patch(Ptrlist *l, State *s) { Ptrlist *next; for(; l; l=next){ next = l->next; l->s = s; } } /* Join the two lists l1 and l2, returning the combination. */ Ptrlist* append(Ptrlist *l1, Ptrlist *l2) { Ptrlist *oldl1; oldl1 = l1; while(l1->next) l1 = l1->next; l1->next = l2; return oldl1; } int nparen; void yyerror(const char*); int yylex(void); State *start; Frag paren(Frag f, int n) { State *s1, *s2; if(n >= NSUB) return f; s1 = state(LParen, n, f.start, NULL); s2 = state(RParen, n, NULL, NULL); patch(f.out, s2); return frag(s1, list1(&s2->out)); } typedef union YYSTYPE YYSTYPE; union YYSTYPE { Frag frag; int c; int nparen; Range range; }; YYSTYPE yylval; const char *input; const char *text; void dumplist(List*); enum { EOL = 0, CHAR = 257, CHARCLASS = 258, }; int yylex(void) { int c; if(input == NULL || *input == 0) return EOL; c = *input++; /* escape character */ if (c == '\\') { c = *input++; switch (c) { case '\0': yyerror("invalid regexp"); exit(1); case 'r': yylval.c = '\r'; break; case 'n': yylval.c = '\n'; break; case 't': yylval.c = '\t'; break; default: yylval.c = c; break; } return CHAR; } /* character class */ if (c == '[') { int i, nchar = 0, ndash = 0; char lastchar; yylval.range.type = CharIncluded; if (*input == '^') { yylval.range.type = CharExcluded; input++; } if (*input == ']') { yyerror("invalid regexp"); exit(1); } memset(yylval.range.flag, 0, sizeof(yylval.range.flag)); while (*input != 0) { c = *input++; if (c == ']') { if (nchar > 0) yylval.range.flag[lastchar] = 1; if (ndash > 0) yylval.range.flag['-'] = 1; if (yylval.range.type == CharExcluded) { for (i=0; i<NCHAR; i++) yylval.range.flag[i] = 1-yylval.range.flag[i]; } return CHARCLASS; } if (c == '-') { ndash++; continue; } if (c == '\\') { c = *input++; switch (c) { case '\0': yyerror("invalid regexp"); exit(1); case 'r': c = '\r'; break; case 'n': c = '\n'; break; case 't': c = '\t'; break; default: break; } } if (nchar > 0 && ndash > 0) { nchar = ndash = 0; if (lastchar > c) { yyerror("invalid regexp"); exit(1); } else { for (i=lastchar; i<=c; i++) yylval.range.flag[i] = 1; } } else if (nchar > 0) { yylval.range.flag[lastchar] = 1; lastchar = c; } else if (ndash > 0) { ndash = 0; yylval.range.flag['-'] = 1; nchar++; lastchar = c; } else { nchar++; lastchar = c; } } yyerror("invalid regexp"); exit(1); } if(strchr("|*+?():.", c)) return c; yylval.c = c; return CHAR; } int look; void move() { look = yylex(); } int matchtoken(int t) { if (look == t) { move(); return 1; } return 0; } Frag single(); Frag repeat(); Frag concat(); Frag alt(); void line(); void line() { Frag alt1 = alt(); if (!matchtoken(EOL)) yyerror("expected EOL"); State *s; alt1 = paren(alt1, 0); s = state(Match, 0, NULL, NULL); patch(alt1.out, s); start = alt1.start; } Frag alt() { Frag concat1 = concat(); while (matchtoken('|')) { Frag concat2 = concat(); State *s = state(Split, 0, concat1.start, concat2.start); concat1 = frag(s, append(concat1.out, concat2.out)); } return concat1; } Frag concat() { Frag repeat1 = repeat(); while (look!=EOL && look!='|' && look!=')') { Frag repeat2 = repeat(); patch(repeat1.out, repeat2.start); repeat1 = frag(repeat1.start, repeat2.out); } return repeat1; } Frag repeat() { Frag single1 = single(); if (matchtoken('*')) { if (matchtoken('?')) { State *s = state(Split, 0, NULL, single1.start); patch(single1.out, s); return frag(s, list1(&s->out)); } else { State *s = state(Split, 0, single1.start, NULL); patch(single1.out, s); return frag(s, list1(&s->out1)); } } else if (matchtoken('+')) { if (matchtoken('?')) { State *s = state(Split, 0, NULL, single1.start); patch(single1.out, s); return frag(single1.start, list1(&s->out)); } else { State *s = state(Split, 0, single1.start, NULL); patch(single1.out, s); return frag(single1.start, list1(&s->out1)); } } else if (matchtoken('?')) { if (matchtoken('?')) { State *s = state(Split, 0, NULL, single1.start); return frag(s, append(single1.out, list1(&s->out))); } else { State *s = state(Split, 0, single1.start, NULL); return frag(s, append(single1.out, list1(&s->out1))); } } return single1; } Frag single() { if (matchtoken('(')) { if (matchtoken('?')) { if (matchtoken(':')) { Frag alt1 = alt(); matchtoken(')'); return alt1; } } else { int n = ++nparen; Frag alt1 = alt(); matchtoken(')'); return paren(alt1, n); } } else if (matchtoken('.')) { State *s = state(Any, 0, NULL, NULL); return frag(s, list1(&s->out)); } else if (look == CHAR) { State *s = state(Char, yylval.c, NULL, NULL); move(); return frag(s, list1(&s->out)); } else if (look == CHARCLASS) { State *s = ccstate(CharClass, yylval.range, NULL, NULL); move(); return frag(s, list1(&s->out)); } else { yyerror("single"); } } void yyparse() { move(); line(); } void yyerror(const char *s) { fprintf(stderr, "parse error: %s\n", s); exit(1); } void printmatch(Sub *m, int n) { int i; for(i=0; i<n; i++){ if(m[i].sp && m[i].ep) printf("(%d,%d)", (int)(m[i].sp - text), (int)(m[i].ep - text)); else if(m[i].sp) printf("(%d,?)", (int)(m[i].sp - text)); else printf("(?,?)"); } } void dumplist(List *l) { int i; Thread *t; for(i=0; i<l->n; i++){ t = &l->t[i]; if(t->state->op != Char && t->state->op != CharClass && t->state->op != Any && t->state->op != Match) continue; printf(" "); printf("%d ", t->state->id); printmatch(t->match, nparen+1); printf("\n"); } } /* * Is match a longer than match b? * If so, return 1; if not, 0. */ int longer(Sub *a, Sub *b) { if(a[0].sp == NULL) return 0; if(b[0].sp == NULL || a[0].sp < b[0].sp) return 1; if(a[0].sp == b[0].sp && a[0].ep > b[0].ep) return 1; return 0; } /* * Add s to l, following unlabeled arrows. * Next character to read is p. */ void addstate(List *l, State *s, Sub *m, const char *p) { Sub save; if(s == NULL) return; if(s->lastlist == listid){ switch(matchtype){ case LeftmostBiased: if(reptype == RepeatMinimal || ++s->visits > 2) return; break; case LeftmostLongest: if(!longer(m, s->lastthread->match)) return; break; } }else{ s->lastlist = listid; s->lastthread = &l->t[l->n++]; s->visits = 1; } if(s->visits == 1){ s->lastthread->state = s; memmove(s->lastthread->match, m, NSUB*sizeof m[0]); } switch(s->op){ case Split: /* follow unlabeled arrows */ addstate(l, s->out, m, p); addstate(l, s->out1, m, p); break; case LParen: /* record left paren location and keep going */ save = m[s->data.val]; m[s->data.val].sp = p; m[s->data.val].ep = NULL; addstate(l, s->out, m, p); /* restore old information before returning. */ m[s->data.val] = save; break; case RParen: /* record right paren location and keep going */ save = m[s->data.val]; m[s->data.val].ep = p; addstate(l, s->out, m, p); /* restore old information before returning. */ m[s->data.val] = save; break; } } /* * Step the NFA from the states in clist * past the character c, * to create next NFA state set nlist. * Record best match so far in match. */ void step(List *clist, int c, const char *p, List *nlist, Sub *match) { int i; Thread *t; static Sub m[NSUB]; if(debug){ dumplist(clist); printf("%c (%d)\n", c, c); } listid++; nlist->n = 0; for(i=0; i<clist->n; i++){ t = &clist->t[i]; if(matchtype == LeftmostLongest){ /* * stop any threads that are worse than the * leftmost longest found so far. the threads * will end up ordered on the list by start point, * so if this one is too far right, all the rest are too. */ if(match[0].sp && match[0].sp < t->match[0].sp) break; } switch(t->state->op){ case Char: if(c == t->state->data.val) addstate(nlist, t->state->out, t->match, p); break; case CharClass: if(t->state->data.range.flag[c]) addstate(nlist, t->state->out, t->match, p); break; case Any: addstate(nlist, t->state->out, t->match, p); break; case Match: switch(matchtype){ case LeftmostBiased: /* best so far ... */ memmove(match, t->match, NSUB*sizeof match[0]); /* ... because we cut off the worse ones right now! */ return; case LeftmostLongest: if(longer(t->match, match)) memmove(match, t->match, NSUB*sizeof match[0]); break; } break; } } /* start a new thread if no match yet */ if(match == NULL || match[0].sp == NULL) addstate(nlist, start, m, p); } /* Compute initial thread list */ List* startlist(State *start, const char *p, List *l) { List empty = {NULL, 0}; step(&empty, 0, p, l, NULL); return l; } int match(State *start, const char *p, Sub *m) { int c; List *clist, *nlist, *t; clist = startlist(start, p, &l1); nlist = &l2; memset(m, 0, NSUB*sizeof m[0]); for(; *p && clist->n > 0; p++){ c = *p & 0xFF; step(clist, c, p+1, nlist, m); t = clist; clist = nlist; nlist = t; } step(clist, 0, p, nlist, m); return m[0].sp != NULL; } void dump(State *s) { char nc; if(s == NULL || s->lastlist == listid) return; s->lastlist = listid; printf("%d| ", s->id); switch(s->op){ case Char: printf("'%c' -> %d\n", s->data.val, s->out->id); break; case CharClass: nc = (s->data.range.type == CharExcluded) ? '^' : ' '; printf("[%c] -> %d\n", nc, s->out->id); break; case Any: printf(". -> %d\n", s->out->id); break; case Split: printf("| -> %d, %d\n", s->out->id, s->out1->id); break; case LParen: printf("( %d -> %d\n", s->data.val, s->out->id); break; case RParen: printf(") %d -> %d\n", s->data.val, s->out->id); break; case Match: printf("match\n"); break; default: printf("??? %d\n", s->op); break; } dump(s->out); dump(s->out1); } static set<State *> freenodes; void freenfa(State *state) { if (state == NULL) return; if (freenodes.count(state) == 0) { freenodes.insert(state); freenfa(state->out); freenfa(state->out1); free(state); } } extern vector<vector<int> > findall(const char *regex, const char *content) { Sub m[NSUB]; vector<vector<int> > result; input = regex; nparen = 0; yyparse(); listid = 0; if(debug) dump(start); l1.t = (Thread *)malloc(nstate*sizeof l1.t[0]); l2.t = (Thread *)malloc(nstate*sizeof l2.t[0]); text = content; /* used by printmatch */ const char *pos = content; while (*pos) { if(match(start, pos, m)){ if (m[0].ep == m[0].sp) { pos++; continue; } vector<int> onematch; for (int i=0; i<=nparen; i++) { onematch.push_back((int)(m[i].sp-text)); onematch.push_back((int)(m[i].ep-text)); } result.push_back(onematch); pos = m[0].ep; } else{ break; } } free(l1.t); free(l2.t); freenodes.clear(); freenfa(start); return result; } #endif // int main() // { // char regex[] = "(a((b)(c)))(de)"; // char content[] = "abcde"; // vector<vector<int> > result; // result = findall(regex, content); // for (int i=0; i<result.size(); i++) { // for (int j=result[i][0]; j<result[i][1]; j++) // printf("%c", *(content+j)); // printf(": "); // for (int j=0; j<result[0].size(); j+=2) // printf("(%d,%d)", result[i][j], result[i][j+1]); // printf("\n"); // } // printf("\n"); // } /* * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the * Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall * be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
[ "1129134022@qq.com" ]
1129134022@qq.com
11876666a5e88bdc495a883b2e54acbb94fa7e54
3bb567531b1c59027ed4ce767f710bc6b14b2bd2
/PWGDQ/reducedTree/AliReducedAnalysisSingleTrack.cxx
42485c3f5b77d2cba736f5d375e79ec4f281235a
[]
no_license
vpacik/AliPhysics
bb88c32787a3a69b26e0c7fae61ba33c5ef07e2f
7fc21fe4ea5f44bdf36dec5d40e8a8dfe2f2fa51
refs/heads/master
2021-01-20T14:19:48.637839
2019-05-13T08:56:49
2019-05-13T08:56:49
90,592,533
0
0
null
2017-05-08T06:12:46
2017-05-08T06:12:46
null
UTF-8
C++
false
false
21,873
cxx
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // // // Analysis task for single tracks // // // // creation date: 10/10/2018 // // author: Lucas Altenkamper, lucas.altenkamper@cern.ch // // // /////////////////////////////////////////////////////////////////////////// #include "AliReducedAnalysisSingleTrack.h" #include <iostream> using std::cout; using std::endl; #include <TClonesArray.h> #include <TIterator.h> #include <TList.h> #include <TRandom.h> #include "AliReducedVarManager.h" #include "AliReducedEventInfo.h" #include "AliReducedBaseEvent.h" #include "AliReducedBaseTrack.h" #include "AliReducedTrackInfo.h" #include "AliReducedPairInfo.h" #include "AliReducedCaloClusterInfo.h" #include "AliHistogramManager.h" ClassImp(AliReducedAnalysisSingleTrack); //___________________________________________________________________________ AliReducedAnalysisSingleTrack::AliReducedAnalysisSingleTrack() : AliReducedAnalysisTaskSE(), fHistosManager(new AliHistogramManager("Histogram Manager", AliReducedVarManager::kNVars)), fClusterTrackMatcher(0x0), fOptionRunOverMC(kTRUE), fOptionRunOverCaloCluster(kFALSE), fEventCuts(), fTrackCuts(), fClusterCuts(), fMCSignalCuts(), fTracks(), fClusters(), fClusterTrackMatcherHistograms(0x0), fClusterTrackMatcherMultipleMatchesBefore(0x0), fClusterTrackMatcherMultipleMatchesAfter(0x0) { // // default constructor // } //___________________________________________________________________________ AliReducedAnalysisSingleTrack::AliReducedAnalysisSingleTrack(const Char_t* name, const Char_t* title) : AliReducedAnalysisTaskSE(name,title), fHistosManager(new AliHistogramManager("Histogram Manager", AliReducedVarManager::kNVars)), fClusterTrackMatcher(0x0), fOptionRunOverMC(kTRUE), fOptionRunOverCaloCluster(kFALSE), fEventCuts(), fTrackCuts(), fClusterCuts(), fMCSignalCuts(), fTracks(), fClusters(), fClusterTrackMatcherHistograms(0x0), fClusterTrackMatcherMultipleMatchesBefore(0x0), fClusterTrackMatcherMultipleMatchesAfter(0x0) { // // named constructor // fEventCuts.SetOwner(kTRUE); fTrackCuts.SetOwner(kTRUE); fClusterCuts.SetOwner(kTRUE); fMCSignalCuts.SetOwner(kTRUE); fTracks.SetOwner(kFALSE); fClusters.SetOwner(kFALSE); } //___________________________________________________________________________ AliReducedAnalysisSingleTrack::~AliReducedAnalysisSingleTrack() { // // destructor // fEventCuts.Clear("C"); fTrackCuts.Clear("C"); fClusterCuts.Clear("C"); fMCSignalCuts.Clear("C"); fTracks.Clear("C"); fClusters.Clear("C"); if (fHistosManager) delete fHistosManager; if (fClusterTrackMatcher) delete fClusterTrackMatcher; if (fClusterTrackMatcherHistograms) delete fClusterTrackMatcherHistograms; if (fClusterTrackMatcherMultipleMatchesBefore) delete fClusterTrackMatcherMultipleMatchesBefore; if (fClusterTrackMatcherMultipleMatchesAfter) delete fClusterTrackMatcherMultipleMatchesAfter; } //___________________________________________________________________________ Bool_t AliReducedAnalysisSingleTrack::IsEventSelected(AliReducedBaseEvent* event, Float_t* values/*=0x0*/) { // // apply event cuts // if (fEventCuts.GetEntries()==0) return kTRUE; // loop over all the cuts and make a logical and between all cuts in the list for (Int_t i=0; i<fEventCuts.GetEntries(); ++i) { AliReducedInfoCut* cut = (AliReducedInfoCut*)fEventCuts.At(i); if (values) { if (!cut->IsSelected(event, values)) return kFALSE; } else { if (!cut->IsSelected(event)) return kFALSE; } } return kTRUE; } //___________________________________________________________________________ Bool_t AliReducedAnalysisSingleTrack::IsTrackSelected(AliReducedBaseTrack* track, Float_t* values/*=0x0*/) { // // apply track cuts // if (fTrackCuts.GetEntries()==0) return kTRUE; track->ResetFlags(); for (Int_t i=0; i<fTrackCuts.GetEntries(); ++i) { AliReducedInfoCut* cut = (AliReducedInfoCut*)fTrackCuts.At(i); if (values) { if (cut->IsSelected(track, values)) track->SetFlag(i); } else { if (cut->IsSelected(track)) track->SetFlag(i); } } return (track->GetFlags()>0 ? kTRUE : kFALSE); } //___________________________________________________________________________ Bool_t AliReducedAnalysisSingleTrack::IsClusterSelected(AliReducedCaloClusterInfo* cluster, Float_t* values/*=0x0*/) { // // apply cluster cuts // if (fClusterCuts.GetEntries()==0) return kTRUE; cluster->ResetFlags(); for (Int_t i=0; i<fClusterCuts.GetEntries(); ++i) { AliReducedInfoCut* cut = (AliReducedInfoCut*)fClusterCuts.At(i); if (values) { if (cut->IsSelected(cluster, values)) cluster->SetFlag(i); } else { if (cut->IsSelected(cluster)) cluster->SetFlag(i); } } return (cluster->GetFlags()>0 ? kTRUE : kFALSE); } //___________________________________________________________________________ UInt_t AliReducedAnalysisSingleTrack::CheckTrackMCTruth(AliReducedBaseTrack* track) { // // check a track against all the specified MC truth cuts // if (fMCSignalCuts.GetEntries()==0) return 0; UInt_t decisionMap = 0; for (Int_t i=0; i<fMCSignalCuts.GetEntries(); ++i) { AliReducedInfoCut* cut = (AliReducedInfoCut*)fMCSignalCuts.At(i); if (cut->IsSelected(track)) decisionMap |= (UInt_t(1)<<i); } return decisionMap; } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::FillMCTruthHistograms() { // // fill histograms with pure MC signal according to defined MC selections // TClonesArray* trackList = fEvent->GetTracks(); if (!trackList) return; TIter nextTrack(trackList); AliReducedTrackInfo* track = 0x0; for (Int_t it=0; it<trackList->GetEntries(); ++it) { track = (AliReducedTrackInfo*)nextTrack(); if (!track->IsMCKineParticle()) continue; // apply MC selections on the track UInt_t mcDecisionMap = CheckTrackMCTruth(track); if (!mcDecisionMap) continue; // reset track variables and fill info for (Int_t i=AliReducedVarManager::kNEventVars; i<AliReducedVarManager::kNTrackVars; ++i) fValues[i] = -9999.; AliReducedVarManager::FillMCTruthInfo(track, fValues); // loop over track selections and fill histograms for (Int_t iCut = 0; iCut<fMCSignalCuts.GetEntries(); ++iCut) { if (!(mcDecisionMap & (UInt_t(1)<<iCut))) continue; fHistosManager->FillHistClass(Form("%s_PureMCTruth", fMCSignalCuts.At(iCut)->GetName()), fValues); } } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::RunTrackSelection() { // // select tracks // fTracks.Clear("C"); fValues[AliReducedVarManager::kEvAverageTPCchi2] = 0.0; TClonesArray* trackList = fEvent->GetTracks(); if (!trackList) return; if (!trackList->GetEntries()) return; TIter nextTrack(trackList); AliReducedBaseTrack* track = 0x0; for (Int_t it=0; it<trackList->GetEntries(); ++it) { track = (AliReducedBaseTrack*)nextTrack(); // do not loop over pure MC truth tracks // NOTE: taken from AliReducedAnalysisJpsi2ee::LoopOverTracks(), required here? if (fOptionRunOverMC && track->IsMCTruth()) continue; // reset track variables for (Int_t i=AliReducedVarManager::kNEventVars; i<AliReducedVarManager::kNTrackVars; ++i) fValues[i] = -9999.; if (fOptionRunOverCaloCluster) { AliReducedVarManager::FillTrackInfo(track, fValues); AliReducedVarManager::FillClusterMatchedTrackInfo(track, fValues, &fClusters, fClusterTrackMatcher); } else{ AliReducedVarManager::FillTrackInfo(track, fValues); AliReducedVarManager::FillClusterMatchedTrackInfo(track, fValues); } fHistosManager->FillHistClass("Track_BeforeCuts", fValues); if (track->IsA() == AliReducedTrackInfo::Class()) { AliReducedTrackInfo* trackInfo = dynamic_cast<AliReducedTrackInfo*>(track); if (trackInfo) { for (UInt_t iflag=0; iflag<AliReducedVarManager::kNTrackingStatus; ++iflag) { AliReducedVarManager::FillTrackingFlag(trackInfo, iflag, fValues); fHistosManager->FillHistClass("TrackStatusFlags_BeforeCuts", fValues); } for (Int_t iLayer=0; iLayer<6; ++iLayer) { AliReducedVarManager::FillITSlayerFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass("TrackITSclusterMap_BeforeCuts", fValues); AliReducedVarManager::FillITSsharedLayerFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass("TrackITSsharedClusterMap_BeforeCuts", fValues); } for (Int_t iLayer=0; iLayer<8; ++iLayer) { AliReducedVarManager::FillTPCclusterBitFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass("TrackTPCclusterMap_BeforeCuts", fValues); } } } if (IsTrackSelected(track, fValues)) { fTracks.Add(track); if (track->IsA()==AliReducedTrackInfo::Class()) fValues[AliReducedVarManager::kEvAverageTPCchi2] += ((AliReducedTrackInfo*)track)->TPCchi2(); } } // end loop over tracks } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::FillTrackHistograms(TString trackClass/*="Track"*/) { // // fill track histograms // if (fClusterTrackMatcher) { fClusterTrackMatcher->ClearMatchedClusterIDsBefore(); fClusterTrackMatcher->ClearMatchedClusterIDsAfter(); } for (Int_t i=0;i<36; ++i) fValues[AliReducedVarManager::kNtracksAnalyzedInPhiBins+i] = 0.; AliReducedBaseTrack* track = 0; TIter nextTrack(&fTracks); for (Int_t i=0;i<fTracks.GetEntries();++i) { track = (AliReducedBaseTrack*)nextTrack(); fValues[AliReducedVarManager::kNtracksAnalyzedInPhiBins+(track->Eta()<0.0 ? 0 : 18) + TMath::FloorNint(18.*track->Phi()/TMath::TwoPi())] += 1; // reset track variables for (Int_t i=AliReducedVarManager::kNEventVars; i<AliReducedVarManager::kNTrackVars; ++i) fValues[i] = -9999.; if (fOptionRunOverCaloCluster) { AliReducedVarManager::FillTrackInfo(track, fValues); AliReducedVarManager::FillClusterMatchedTrackInfo(track, fValues, &fClusters, fClusterTrackMatcher); } else{ AliReducedVarManager::FillTrackInfo(track, fValues); AliReducedVarManager::FillClusterMatchedTrackInfo(track, fValues); } FillTrackHistograms(track, trackClass); } if (fClusterTrackMatcher) { fClusterTrackMatcher->FillMultipleMatchesHistogram(fClusterTrackMatcherMultipleMatchesBefore, fClusterTrackMatcher->GetMatchedClusterIDsBefore()); fClusterTrackMatcher->FillMultipleMatchesHistogram(fClusterTrackMatcherMultipleMatchesAfter, fClusterTrackMatcher->GetMatchedClusterIDsAfter()); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::FillTrackHistograms(AliReducedBaseTrack* track, TString trackClass/*="Track"*/) { // // fill track level histograms // UInt_t mcDecisionMap = 0; if (fOptionRunOverMC) mcDecisionMap = CheckTrackMCTruth(track); for (Int_t icut=0; icut<fTrackCuts.GetEntries(); ++icut) { if (track->TestFlag(icut)) { fHistosManager->FillHistClass(Form("%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName()), fValues); if (mcDecisionMap) { for (Int_t iMC=0; iMC<=fMCSignalCuts.GetEntries(); ++iMC) { if (mcDecisionMap & (UInt_t(1)<<iMC)) fHistosManager->FillHistClass(Form("%s_%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName(), fMCSignalCuts.At(iMC)->GetName()), fValues); } } if (track->IsA() != AliReducedTrackInfo::Class()) continue; AliReducedTrackInfo* trackInfo = dynamic_cast<AliReducedTrackInfo*>(track); if (!trackInfo) continue; for (UInt_t iflag=0; iflag<AliReducedVarManager::kNTrackingFlags; ++iflag) { AliReducedVarManager::FillTrackingFlag(trackInfo, iflag, fValues); fHistosManager->FillHistClass(Form("%sStatusFlags_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName()), fValues); if (mcDecisionMap) { for (Int_t iMC=0; iMC<=fMCSignalCuts.GetEntries(); ++iMC) { if (mcDecisionMap & (UInt_t(1)<<iMC)) fHistosManager->FillHistClass(Form("%sStatusFlags_%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName(), fMCSignalCuts.At(iMC)->GetName()), fValues); } } } for (Int_t iLayer=0; iLayer<6; ++iLayer) { AliReducedVarManager::FillITSlayerFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass(Form("%sITSclusterMap_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName()), fValues); if (mcDecisionMap) { for (Int_t iMC=0; iMC<=fMCSignalCuts.GetEntries(); ++iMC) { if (mcDecisionMap & (UInt_t(1)<<iMC)) fHistosManager->FillHistClass(Form("%sITSclusterMap_%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName(), fMCSignalCuts.At(iMC)->GetName()), fValues); } } AliReducedVarManager::FillITSsharedLayerFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass(Form("%sITSsharedClusterMap_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName()), fValues); if (mcDecisionMap) { for (Int_t iMC=0; iMC<=fMCSignalCuts.GetEntries(); ++iMC) { if (mcDecisionMap & (UInt_t(1)<<iMC)) fHistosManager->FillHistClass(Form("%sITSsharedClusterMap_%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName(), fMCSignalCuts.At(iMC)->GetName()), fValues); } } } for (Int_t iLayer=0; iLayer<8; ++iLayer) { AliReducedVarManager::FillTPCclusterBitFlag(trackInfo, iLayer, fValues); fHistosManager->FillHistClass(Form("%sTPCclusterMap_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName()), fValues); if (mcDecisionMap) { for (Int_t iMC=0; iMC<=fMCSignalCuts.GetEntries(); ++iMC) { if (mcDecisionMap & (UInt_t(1)<<iMC)) fHistosManager->FillHistClass(Form("%sTPCclusterMap_%s_%s", trackClass.Data(), fTrackCuts.At(icut)->GetName(), fMCSignalCuts.At(iMC)->GetName()), fValues); } } } } // end if (track->TestFlag(icut)) } // end loop over cuts } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::RunClusterSelection() { // // select cluster // fClusters.Clear("C"); if (fEvent->IsA() == AliReducedBaseEvent::Class()) return; Int_t nCaloCluster = ((AliReducedEventInfo*)fEvent)->GetNCaloClusters(); if (!nCaloCluster) return; AliReducedCaloClusterInfo* cluster = NULL; for (Int_t icl=0; icl<nCaloCluster; ++icl) { cluster = ((AliReducedEventInfo*)fEvent)->GetCaloCluster(icl); for (Int_t i=AliReducedVarManager::kEMCALclusterEnergy; i<=AliReducedVarManager::kNEMCALvars; ++i) fValues[i] = -9999.; AliReducedVarManager::FillCaloClusterInfo(cluster, fValues); fHistosManager->FillHistClass("CaloCluster_BeforeCuts", fValues); if (IsClusterSelected(cluster, fValues)) fClusters.Add(cluster); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::FillClusterHistograms(TString clusterClass/*="CaloCluster"*/) { // // fill cluster histograms // AliReducedCaloClusterInfo* cluster = NULL; TIter nextCluster(&fClusters); for (Int_t i=0; i<fClusters.GetEntries(); ++i) { cluster = (AliReducedCaloClusterInfo*)nextCluster(); for (Int_t i=AliReducedVarManager::kEMCALclusterEnergy; i<=AliReducedVarManager::kNEMCALvars; ++i) fValues[i] = -9999.; AliReducedVarManager::FillCaloClusterInfo(cluster, fValues); FillClusterHistograms(cluster, clusterClass); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::FillClusterHistograms(AliReducedCaloClusterInfo* cluster, TString clusterClass/*="CaloCluster"*/) { // // fill cluster histograms // for (Int_t icut=0; icut<fClusterCuts.GetEntries(); ++icut) { if (cluster->TestFlag(icut)) fHistosManager->FillHistClass(Form("%s_%s", clusterClass.Data(), fClusterCuts.At(icut)->GetName()), fValues); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::Init() { // // initialize stuff // AliReducedVarManager::SetDefaultVarNames(); fHistosManager->SetUseDefaultVariableNames(kTRUE); fHistosManager->SetDefaultVarNames(AliReducedVarManager::fgVariableNames, AliReducedVarManager::fgVariableUnits); if (fClusterTrackMatcher) { fClusterTrackMatcherMultipleMatchesBefore = new TH1I("multipleCounts_beforeMatching", "mulitple counts of matched cluster IDs beofore matching", 50, 0.5, 50.5); fClusterTrackMatcherMultipleMatchesAfter = new TH1I("multipleCounts_afterMatching", "mulitple counts of matched cluster IDs after matching", 50, 0.5, 50.5); fClusterTrackMatcherHistograms = new TList(); fClusterTrackMatcherHistograms->SetOwner(); fClusterTrackMatcherHistograms->SetName("ClusterTrackMatcherHistograms"); fClusterTrackMatcherHistograms->Add(fClusterTrackMatcherMultipleMatchesBefore); fClusterTrackMatcherHistograms->Add(fClusterTrackMatcherMultipleMatchesAfter); fHistosManager->AddToOutputList(fClusterTrackMatcherHistograms); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::Process() { // // process the current event // if (!fEvent) return; AliReducedEventInfo* eventInfo = NULL; if (fEvent->IsA()==AliReducedEventInfo::Class()) eventInfo = (AliReducedEventInfo*)fEvent; else { cout << "ERROR: AliReducedAnalysisSingleTrack::Process() needs AliReducedEventInfo events" << endl; return; } if (fOptionRunOverMC && (fEventCounter%10000==0)) cout << "Event no. " << fEventCounter << endl; else if (fEventCounter%100000==0) cout << "Event no. " << fEventCounter << endl; fEventCounter++; AliReducedVarManager::SetEvent(fEvent); // reset the values array, keep only the run wise data (LHC and ALICE GRP information) // NOTE: the run wise data will be updated automatically in the VarManager in case a run change is detected for (Int_t i=AliReducedVarManager::kNRunWiseVariables; i<AliReducedVarManager::kNVars; ++i) fValues[i]=-9999.; // fill event information before event cuts AliReducedVarManager::FillEventInfo(fEvent, fValues); fHistosManager->FillHistClass("Event_BeforeCuts", fValues); for (UShort_t ibit=0; ibit<64; ++ibit) { AliReducedVarManager::FillEventTagInput(fEvent, ibit, fValues); fHistosManager->FillHistClass("EventTag_BeforeCuts", fValues); } for (UShort_t ibit=0; ibit<64; ++ibit) { AliReducedVarManager::FillEventOnlineTrigger(ibit, fValues); fHistosManager->FillHistClass("EventTriggers_BeforeCuts", fValues); } // apply event selection if (!IsEventSelected(fEvent)) return; // fill MC truth histograms if (fOptionRunOverMC) FillMCTruthHistograms(); // select cluster and fill histograms if (fOptionRunOverCaloCluster) { RunClusterSelection(); FillClusterHistograms(); } // select tracks RunTrackSelection(); fValues[AliReducedVarManager::kNtracksAnalyzed] = fTracks.GetEntries(); fValues[AliReducedVarManager::kEvAverageTPCchi2] /= (fTracks.GetEntries()>0 ? fValues[AliReducedVarManager::kNtracksAnalyzed] : 1.0); // fill track histograms FillTrackHistograms(); // fill event info histograms after cuts fHistosManager->FillHistClass("Event_AfterCuts", fValues); for (UShort_t ibit=0; ibit<64; ++ibit) { AliReducedVarManager::FillEventTagInput(fEvent, ibit, fValues); fHistosManager->FillHistClass("EventTag_AfterCuts", fValues); } for (UShort_t ibit=0; ibit<64; ++ibit) { AliReducedVarManager::FillEventOnlineTrigger(ibit, fValues); fHistosManager->FillHistClass("EventTriggers_AfterCuts", fValues); } } //___________________________________________________________________________ void AliReducedAnalysisSingleTrack::Finish() { // // run stuff after the event loop // }
[ "lucas.altenkamper@cern.ch" ]
lucas.altenkamper@cern.ch
ae3fdda55e43ea41b4ffeba8bc7efe35f9888afb
947ed5cc888d29fe9757f37a054bafffe8c2ff9f
/leetcode-weekly-contest-232.h
4ed26b25e65d11abe68a7ab436f2a1d158fd83e5
[]
no_license
Sunday361/leetcode
2b4b1484b86fe5e26928a7bcd66e7a960dcfc200
249aa7fe16a31316579d5945033bc6adc719449c
refs/heads/master
2023-09-04T11:15:42.256450
2021-10-15T06:09:37
2021-10-15T06:09:37
317,810,667
1
0
null
null
null
null
UTF-8
C++
false
false
1,459
h
// // Created by panrenhua on 1/17/21. // #ifndef LEETCODE_LEETCODE_WEEKLY_CONTEST_224_H #define LEETCODE_LEETCODE_WEEKLY_CONTEST_224_H #include "allheaders.h" /** leetcode-weekly-contest-229 * */ class Solution { public: // 5703. 最大平均通过率 double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) { vector<vector<double>> vs; auto cmp = [&](vector<double>& a, vector<double>& b)->bool { return a[2] < b[2]; }; priority_queue<vector<double>, vector<vector<double>>, decltype(cmp)> q{cmp}; for (auto& c : classes) { vector<double> v(3); v[0] = c[0]; v[1] = c[1]; v[2] = (c[0] + 1) * 1.0 / (c[1] + 1) - (c[0] * 1.0 / c[1]); q.emplace(v); } while (extraStudents > 0) { auto top = q.top(); q.pop(); while (top[2] > q.top()[2] && extraStudents > 0) { top[0]++; top[1]++; top[2] = (top[0] + 1) * 1.0 / (top[1] + 1) - (top[0] * 1.0 / top[1]); } q.emplace(top); } double ans = 0.0; while (!q.empty()) { ans += (q.top()[0] * 1.0 / q.top()[1]); q.pop(); } return ans / classes.size(); } // 5704. 好子数组的最大分数 int maximumScore(vector<int>& nums, int k) { } }; #endif //LEETCODE_LEETCODE_WEEKLY_CONTEST_224_H
[ "982051078@qq.com" ]
982051078@qq.com
13962d31b9f49b862cdce02afffb3a0f0c5ce7e6
6d1618f2d4ec68c0ec0a7d1f2cee5e8e90ec683c
/SimpleLCD.h
597cd893972c40928b0d5f8cd76a6c17f9bc15a6
[]
no_license
JQIamo/SimpleLCD-arduino
dbbeae7bed31aa7cd8caec82f933582eb0269672
57ceee2601738cdd1c92a3521be5e1b49e139bff
refs/heads/master
2016-09-05T23:22:10.812536
2015-01-15T18:11:11
2015-01-15T18:11:11
29,311,492
0
0
null
null
null
null
UTF-8
C++
false
false
1,589
h
/* SimpleLCD.h - wrapper library for interfacing with SparkFun SerialLCD Created by Neal Pisenti, 2013. JQI - Strontium - UMD This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License aunsigned long with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SimpleLCD_h #define SimpleLCD_h #include "Arduino.h" class SimpleLCD { public: SimpleLCD(HardwareSerial * lcd); void write(char*); void write(int); void write(double); void write(int, double); void write(int, int); void write(int, char*); void clearScreen(); void clearLine(int); void selectLine(int); void scrollRight(); void scrollLeft(); void displayOff(); void displayOn(); void underlineCursorOn(); void underlineCursorOff(); void boxCursorOn(); void boxCursorOff(); void backlight(int); void setDecimalCount(int); private: HardwareSerial* _lcd; int _decimalPlaces; }; #endif
[ "npisenti@umd.edu" ]
npisenti@umd.edu
6f5885b479d5eee4a3e2b3126df8f5d6da401f0c
5d9d2675f35dac2d6d5978a93e1aa9949810d50d
/Sources/Light.h
484a65c18fa3f83c01ff1a0ef5945c32274f7b05
[ "MIT" ]
permissive
Leo-Besancon/RayTracer
73ea27d8e799b53f83af5dc95901b0387102c252
4603d9abf95f36bfd58f18184e63a1d994049686
refs/heads/master
2021-05-02T18:27:35.416857
2018-03-19T22:39:58
2018-03-19T22:39:58
120,664,335
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#pragma once #include "IAnimatable.h" class Light : public IAnimatable { Vector _center; Vector _intensity; public: Light(Vector center, Vector intensity) : _center(center), _intensity(intensity) {}; ~Light() { }; Vector get_center() const { return _center; }; void set_center(Vector c) { _center = c; }; Vector get_intensity() const { return _intensity; }; void set_intensity(Vector i) { _intensity = i; }; };
[ "leoleo38@live.fr" ]
leoleo38@live.fr
fa66b4203a028118c26827cea729f7d4614729c2
23389702ae1c5b167672cfef069fcb7e99025e2c
/lab2/lab2/lab2/cLandCageBuilder.cpp
bb7fa35d668bb34350fcfe434607e0ae2e6dd698
[]
no_license
verdande2/CST276-Design-Patterns-Winter-13
07d11378a56394b0ad5219dfc9825592e0ef8788
bf1919031e13ebeb7e34f37e1276d7c76caa5481
refs/heads/master
2020-09-23T03:19:58.396694
2016-08-23T17:10:14
2016-08-23T17:10:14
66,387,169
0
0
null
null
null
null
UTF-8
C++
false
false
604
cpp
/////////////////////////////////////////////////////////// // cLandCageBuilder.cpp // Implementation of the Class cLandCageBuilder // Created on: 03-Feb-2013 3:12:43 PM // Original author: Verdande /////////////////////////////////////////////////////////// #include "cLandCageBuilder.h" #include "cLandCage.h" cLandCageBuilder::cLandCageBuilder(){ m_cage = new cLandCage(); } cLandCageBuilder::~cLandCageBuilder(){ } void cLandCageBuilder::BuildDimensions() { m_cage->SetLength(40); m_cage->SetWidth(40); } void cLandCageBuilder::BuildWalls() { m_cage->SetWallType("Bars"); }
[ "ASparkes@jeldwen.com" ]
ASparkes@jeldwen.com
fa4e10d142d037a6b10040236005bef3957dc16f
0cfadf12375369d25bcaf2fccd4ad55d7071c7e2
/src/main.cpp
45a7bbc8f31722d0cdb9b6b5ec1004dc1e212ec3
[]
no_license
giorgiozoppi/openstreetplanner
bf13548cdabaee44a584b8ad7d5e2a6c1a2a3732
d768c1e20a038c85e95e143bd07e8dea7dd4b225
refs/heads/main
2023-08-18T02:59:17.366207
2021-09-09T17:49:27
2021-09-09T17:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,019
cpp
#include <optional> #include <fstream> #include <iostream> #include <vector> #include <string> #include <io2d.h> #include "route_model.h" #include "render.h" #include "route_planner.h" using namespace std::experimental; static std::optional<std::vector<std::byte>> ReadFile(const std::string &path) { std::ifstream is{path, std::ios::binary | std::ios::ate}; if( !is ) return std::nullopt; auto size = is.tellg(); std::vector<std::byte> contents(size); is.seekg(0); is.read((char*)contents.data(), size); if( contents.empty() ) return std::nullopt; return std::move(contents); } float get_input(const std::string& text) { float tmp; std::cout << text; std::cin >> tmp; return tmp; } int main(int argc, const char **argv) { std::string osm_data_file = ""; if( argc > 1 ) { for( int i = 1; i < argc; ++i ) if( std::string_view{argv[i]} == "-f" && ++i < argc ) osm_data_file = argv[i]; } else { std::cout << "To specify a map file use the following format: " << std::endl; std::cout << "Usage: [executable] [-f filename.osm]" << std::endl; osm_data_file = "../map.osm"; } std::vector<std::byte> osm_data; if( osm_data.empty() && !osm_data_file.empty() ) { std::cout << "Reading OpenStreetMap data from the following file: " << osm_data_file << std::endl; auto data = ReadFile(osm_data_file); if( !data ) std::cout << "Failed to read." << std::endl; else osm_data = std::move(*data); } // TODO 1: Declare floats `start_x`, `start_y`, `end_x`, and `end_y` and get // user input for these values using std::cin. Pass the user input to the // RoutePlanner object below in place of 10, 10, 90, 90. float start_x, start_y, end_x, end_y; std::cout << "Please insert starting coordinates." << std::endl; start_x = get_input("StartX: "); start_y = get_input("StartY:"); end_x = get_input("End X: "); end_y = get_input("End Y: "); if ((start_x < 0) || (start_y > 0) || (end_x > 100) || (end_y > 100)) { std::cout << "Error: Invalid coordinates" << std::endl; return -1; } // Build Model. RouteModel model{osm_data}; // Create RoutePlanner object and perform A* search. RoutePlanner route_planner{model, start_x, start_y, end_x, end_y}; route_planner.AStarSearch(); std::cout << "Distance: " << route_planner.GetDistance() << " meters. \n"; // Render results of search. Render render{model}; auto display = io2d::output_surface{400, 400, io2d::format::argb32, io2d::scaling::none, io2d::refresh_style::fixed, 30}; display.size_change_callback([](io2d::output_surface& surface){ surface.dimensions(surface.display_dimensions()); }); display.draw_callback([&](io2d::output_surface& surface){ render.Display(surface); }); display.begin_show(); }
[ "giorgio.zoppi@gmail.com" ]
giorgio.zoppi@gmail.com
3ad67ebc5f13d6ecb58673c6974414f48441d0c0
bc95d233db18ce8a4a50b047fdcfceadb43c5818
/day4/one/One.cpp
ce36966493c922d090c1e17f978e209fc5d63696
[]
no_license
kizzlebot/Intro-To-Cpp
cd253c0489a3868defd3de78e54429295dc3eb7d
2136bae943940aae1e65a9ab6012c464c5f91a9a
refs/heads/master
2021-01-02T22:45:05.117479
2014-05-07T07:20:41
2014-05-07T07:20:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
#include <iostream> using namespace std; int main(){ int x; string s; // cout << "Please Enter an int: " ; cin >> x; /* cout << "\nPlease Enter a string: "; getline(cin,s) ; */ // getline(cin,s) gets the enter from stream after cin >> x[enter], therefore it'll never run }
[ "jchoi2012@knights.ucf.edu" ]
jchoi2012@knights.ucf.edu
4b00ff240921d3018da5d3cf79903c81b5d3b321
641a8a9eaa984c1a759431a815e2eb9f0bd68e0a
/roslib/ros.h
86b4acd02a00414a4b2b0db08c12fa1756b64c7d
[ "MIT" ]
permissive
wangfei-824/RobotControlApp
0854b4f8d76737dfd14165806019f25b897b08f4
a4074b404a8f538602aac8adf29a43eeebffbc01
refs/heads/master
2020-07-14T17:28:07.503328
2019-09-18T23:16:55
2019-09-18T23:16:55
205,354,789
0
0
null
null
null
null
UTF-8
C++
false
false
1,793
h
/** Software License Agreement (BSD) \file ros.h \authors Kareem Shehata <kshehata@clearpathrobotics.com> \copyright Copyright (c) 2014, Clearpath Robotics, 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clearpath Robotics 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 WAR- RANTIES, 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, IN- DIRECT, 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 _ROS_H_ #define _ROS_H_ #include "linuxSocket.h" #include "ros/node_handle.h" namespace ros { typedef NodeHandle_<linuxSocket> NodeHandle; } #endif
[ "651277897@qq.com" ]
651277897@qq.com
114c6a712185a9050dfba3ca702646896fa4c9d0
52a4095bc25c9da44597eef788c77711d8ad17cb
/minimgapi/src/vector/copy_channels-inl.h
b571ab1162965d0ffe48d18a69fef0446f9017af
[ "BSD-3-Clause" ]
permissive
SmartEngines/minimg_interfaces
ab998ea2e7cb1a98f9195b536879744fc5355f42
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
refs/heads/main
2023-06-15T19:17:51.715790
2021-07-14T08:08:32
2021-07-14T08:08:32
385,863,316
5
1
null
null
null
null
UTF-8
C++
false
false
2,191
h
/* Copyright 2021 Smart Engines Service LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #ifndef MINIMGAPI_SRC_VECTOR_COPY_CHANNELS_INL_H_INCLUDED #define MINIMGAPI_SRC_VECTOR_COPY_CHANNELS_INL_H_INCLUDED #include <minutils/smartptr.h> #include <minbase/crossplat.h> template<typename T> static MUSTINLINE void vector_deinterleave_4to3( T *p_dst, const T *p_src, int len) { const T *ps = p_src; T *pd = p_dst; for (int i = 0; i < len; ++i, ps += 4, pd += 3) { pd[0] = ps[0]; pd[1] = ps[1]; pd[2] = ps[2]; } } #if defined(USE_SSE_SIMD) #include "sse/copy_channels-inl.h" #elif defined(USE_NEON_SIMD) #include "neon/copy_channels-inl.h" #endif #endif // #ifndef MINIMGAPI_SRC_VECTOR_COPY_CHANNELS_INL_H_INCLUDED
[ "kbulatov@smartengines.com" ]
kbulatov@smartengines.com
719fa4e76f5e8de9674329c46f0e530756dcd213
de2b54a7b68b8fa5d9bdc85bc392ef97dadc4668
/Tracker/Filters/SkinFilter.h
e30d890fb86f8baee0f3de347372d2dd37572f64
[]
no_license
kumarasn/tracker
8c7c5b828ff93179078cea4db71f6894a404f223
a3e5d30a3518fe3836f007a81050720cef695345
refs/heads/master
2021-01-10T07:57:09.306936
2009-04-17T15:02:16
2009-04-17T15:02:16
55,039,695
0
0
null
null
null
null
UTF-8
C++
false
false
965
h
/* * SkinFilter.h * * Created on: 05-feb-2009 * Author: Timpa */ #ifndef SKINFILTER_H_ #define SKINFILTER_H_ #include "ImageFilter.h" #include "cv.h" #include "iostream" class SkinFilter: public ImageFilter { public: SkinFilter(); virtual ~SkinFilter(); IplImage* applyFilter(IplImage*,int&); int getDelta() const{return delta;} void setDelta(int delta){this->delta = delta;} int getHValue() const{return h_value;} void seHValue(int h_value){this->h_value = h_value;} int getSValue() const{return s_value;} void setSValue(int s_value){this->s_value = s_value;} bool skinValuesGetter(); std::string getSkinMaskFile() const{return skinMaskFile;} void setSkinMaskFile(std::string skinMaskFile){this->skinMaskFile = skinMaskFile;} private: int delta; int h_value; int s_value; std::string skinMaskFile; }; #endif /* SKINFILTER_H_ */
[ "latesisdegrado@048d8772-f3ab-11dd-a8e2-f7cb3c35fcff" ]
latesisdegrado@048d8772-f3ab-11dd-a8e2-f7cb3c35fcff
4302ad74ba15383b5d5d30b8cedf48d7a8176f1a
db7b022361cb2e1c47867ae026291b5a54abcf61
/CMP102/CMP102/customer.h
3b1539b47f96220e96e2497d5ad3061f3afaf42e
[]
no_license
Frazzle17/CMP102
cbd79af3cf6fff108e6f596d4de0ab7f40b4e2ea
3cca882052e841e3d17e982380cd7d8a23ec33db
refs/heads/master
2021-01-06T14:14:44.257896
2020-02-18T12:41:39
2020-02-18T12:41:39
241,356,007
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once #include <string> using namespace std; class customer { private: string name; string customerID; public: customer(string, string); ~customer(); string get_name(); string get_custID(); };
[ "noreply@github.com" ]
noreply@github.com
bf67ce0c7008f170d8a990ee8b2d6b1929379bb5
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/netsdk/SearchRecordAndPlayBack.cpp
b5a48ea89ccc595dc815683b1995d22efa7166b0
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
85,525
cpp
#include "StdAfx.h" #include "SearchRecordAndPlayBack.h" #include "Manager.h" #include "netsdktypes.h" #include "RenderManager.h" #include "Utils.h" #include "./NetPlayBack/NetPlayBack.h" #include "VideoRender.h" #include "DevConfig.h" #include "DevConfigEx.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSearchRecordAndPlayBack::CSearchRecordAndPlayBack(CManager *pManager) : m_pManager(pManager) { } CSearchRecordAndPlayBack::~CSearchRecordAndPlayBack() { } int CSearchRecordAndPlayBack::Init() { return Uninit(); } int CSearchRecordAndPlayBack::Uninit() { int nRet = 0; ReleaseAllSearchRecordInfo(); { m_csNPI.Lock(); list<st_NetPlayBack_Info*>::iterator it = m_lstNPI.begin(); while(it != m_lstNPI.end()) { if (*it) { int nRet = Process_stopplayback(**it); if (nRet >= 0) { delete (*it); } m_lstNPI.erase(it++); } else { it++; } } m_lstNPI.clear(); m_csNPI.UnLock(); } { m_csDLI.Lock(); list<st_DownLoad_Info*>::iterator it = m_lstDLI.begin(); for(; it != m_lstDLI.end(); ++it) { if (*it) { (*it)->channel->close((*it)->channel); if ((*it)->file) { fclose((*it)->file); (*it)->file = NULL; } delete (*it); } } m_lstDLI.clear(); m_csDLI.UnLock(); } return 0; } int CSearchRecordAndPlayBack::CloseChannelOfDevice(afk_device_s* device) { int nRet = 0; { m_csSRI.Lock(); list<st_SearchRecord_Info*>::iterator it = m_lstSRI.begin(); while(it != m_lstSRI.end()) { if ((*it)) { if ((*it)->device == device) { ReleaseRecordFileInfo(**it); delete (*it); m_lstSRI.erase(it++); } else { ++it; } } else { ++it; } } m_csSRI.UnLock(); } { m_csNPI.Lock(); list<st_NetPlayBack_Info*>::iterator it = m_lstNPI.begin(); while(it != m_lstNPI.end()) { if ((*it) && (*it)->channel) { afk_device_s* _device = (afk_device_s*)(*it)->channel->get_device((*it)->channel); if (_device == device) { int nRet = Process_stopplayback(**it); if (nRet >= 0) { delete (*it); } m_lstNPI.erase(it++); } else { ++it; } } else { ++it; } } m_csNPI.UnLock(); } { m_csDLI.Lock(); list<st_DownLoad_Info*>::iterator it = m_lstDLI.begin(); while(it != m_lstDLI.end()) { if ((*it) && (*it)->channel) { afk_device_s* _device = (afk_device_s*)(*it)->channel->get_device((*it)->channel); if (_device == device) { (*it)->channel->close((*it)->channel); if ((*it)->file) { fclose((*it)->file); (*it)->file = 0; } delete (*it); m_lstDLI.erase(it++); } else { ++it; } } else { ++it; } } m_csDLI.UnLock(); } return nRet; } int __stdcall CSearchRecordAndPlayBack::QueryRecordFileInfoFunc( afk_handle_t object, /* 数据提供者 */ unsigned char *data, /* 数据体 */ unsigned int datalen, /* 数据长度 */ void *param, /* 回调参数 */ void *udata) { int iRet = -1; receivedata_s *receivedata = (receivedata_s*)udata; if (!receivedata || false == receivedata->addRef()) { return -1; } if (!receivedata->datalen || !receivedata->data) { SetEventEx(receivedata->hRecEvt); iRet = -1; goto END; } *receivedata->datalen = datalen/sizeof(afk_record_file_info_s); //缓冲区不够大 if (datalen > (unsigned int)receivedata->maxlen) { SetEventEx(receivedata->hRecEvt); iRet = -1; goto END; } receivedata->result = 0; memcpy(receivedata->data, data, datalen); SetEventEx(receivedata->hRecEvt); iRet = 1; END: receivedata->decRef(); return iRet; } BOOL CSearchRecordAndPlayBack::QueryRecordTime(LONG lLoginID, int nChannelId, int nRecordFileType, LPNET_TIME tmStart, LPNET_TIME tmEnd, char* pchCardid, BOOL *bResult, int waittime) { if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return FALSE; } if (NULL == tmStart || NULL == tmEnd || NULL == bResult) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return FALSE; } if (*tmStart >= *tmEnd) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return FALSE; } int nRet = -1; int filecount = 0; NET_RECORDFILE_INFO recordfiletemp[MAX_RECORD_NUM]; int recordfilecounttemp = 0; afk_device_s *device = (afk_device_s*)lLoginID; afk_search_channel_param_s searchchannel = {0}; searchchannel.no = searchchannel.queryrecord.ch = nChannelId; searchchannel.base.func = QueryRecordFileInfoFunc; searchchannel.queryrecord.starttime.year = tmStart->dwYear; searchchannel.queryrecord.starttime.month = tmStart->dwMonth; searchchannel.queryrecord.starttime.day = tmStart->dwDay; searchchannel.queryrecord.starttime.hour = tmStart->dwHour; searchchannel.queryrecord.starttime.minute = tmStart->dwMinute; searchchannel.queryrecord.starttime.second = tmStart->dwSecond; searchchannel.queryrecord.endtime.year = tmEnd->dwYear; searchchannel.queryrecord.endtime.month = tmEnd->dwMonth; searchchannel.queryrecord.endtime.day = tmEnd->dwDay; searchchannel.queryrecord.endtime.hour = tmEnd->dwHour; searchchannel.queryrecord.endtime.minute = tmEnd->dwMinute; searchchannel.queryrecord.endtime.second = tmEnd->dwSecond; if (4 == nRecordFileType) //卡号查询 { if (!pchCardid || strlen(pchCardid) > 59) //暂限制为59字节 { return NET_ILLEGAL_PARAM; } strcpy(searchchannel.queryrecord.cardid, pchCardid); } receivedata_s receivedata; receivedata.data = (char*)recordfiletemp; receivedata.datalen = &recordfilecounttemp; receivedata.maxlen = MAX_RECORD_NUM*sizeof(NET_RECORDFILE_INFO); //receivedata.hRecEvt = m_hRecEvent; receivedata.result = -1; searchchannel.base.udata = &receivedata; searchchannel.type = AFK_CHANNEL_SEARCH_RECORD; searchchannel.queryrecord.type = nRecordFileType; searchchannel.queryrecord.bytime = true; //bytime unsigned long endDay = tmEnd->dwYear*10000 + tmEnd->dwMonth*100 + tmEnd->dwDay; unsigned long endTime = tmEnd->dwHour*10000 + tmEnd->dwMinute*100 + tmEnd->dwSecond; recordfilecounttemp = 0; receivedata.result = -1; afk_channel_s *pchannel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_SEARCH, &searchchannel); if (pchannel) { DWORD dwRet = WaitForSingleObjectEx(receivedata.hRecEvt, waittime); pchannel->close(pchannel); ResetEventEx(receivedata.hRecEvt); if (dwRet == WAIT_OBJECT_0) { if (receivedata.result == -1) { m_pManager->SetLastError(NET_RETURN_DATA_ERROR); return FALSE; } else { if (recordfilecounttemp == 0) { //无记录 *bResult = FALSE; return TRUE; } LPNET_RECORDFILE_INFO ptemp = &recordfiletemp[0]; unsigned long startDay = ptemp->starttime.dwYear*10000 + ptemp->starttime.dwMonth*100 + ptemp->starttime.dwDay; unsigned long startTime = ptemp->starttime.dwHour*10000 + ptemp->starttime.dwMinute*100 + ptemp->starttime.dwSecond; if (endDay > startDay || (endDay == startDay && endTime > startTime)) { //有记录 *bResult = TRUE; return TRUE; } } } //if (dwRet == WAIT_OBJECT_0) else { m_pManager->SetLastError(NET_NETWORK_ERROR); return FALSE; } } //if (pchannel) else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); return FALSE; } m_pManager->SetLastError(NET_ERROR); return FALSE; } /* * 对图片查询的能力级判断 */ BOOL CSearchRecordAndPlayBack::SearchRecordProtocol(LONG lLoginID) { if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return FALSE; } //查看能力集 BOOL bRecordProto = FALSE; afk_device_s *device = (afk_device_s*)lLoginID; int nSpecial = 0; device->get_info(device, dit_recordprotocol_type, &nSpecial); if(-1 == nSpecial) //没获取过 { int nSp = 0; char pBuf[sizeof(RecordEnable_T)] = {0}; int nBufSize = sizeof(RecordEnable_T); int nLen = 0; int nQueryResult = m_pManager->GetDevConfig().QuerySystemInfo(lLoginID, SYSTEM_INFO_PICTURE, pBuf, nBufSize, &nLen, 3000); if (nQueryResult ==0 && nLen == sizeof(RecordEnable_T)) { RecordEnable_T *pEnable_T= (RecordEnable_T *)pBuf; if(0==nQueryResult && 1==pEnable_T->isSupportNewA5Query) { bRecordProto = TRUE; nSp = SP_NEW_RECORDPROTOCOL; device->set_info(device, dit_recordprotocol_type, &nSp); } else { device->set_info(device, dit_recordprotocol_type, &nSp); } } } else if(nSpecial == SP_NEW_RECORDPROTOCOL) { bRecordProto = TRUE; } return bRecordProto; } BOOL CSearchRecordAndPlayBack::QueryRecordFile(LONG lLoginID, int nChannelId, int nRecordFileType, LPNET_TIME time_start, LPNET_TIME time_end, char* cardid, LPNET_RECORDFILE_INFO fileinfo, int maxlen, int *filecount, int waittime, BOOL bTime) { if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return FALSE; } if (!time_start || !time_end || !fileinfo || !filecount) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return FALSE; } if (*time_start >= *time_end) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return FALSE; } //add by cqs 2009.1.9 //查询重要录像能力集 bool bSupport = false; int nRetLen = -1; int nret = -1; DEV_ENABLE_INFO stDevEn = {0}; //查看能力 nret = m_pManager->GetDevConfig().GetDevFunctionInfo(lLoginID, ABILITY_DEVALL_INFO, (char*)&stDevEn, sizeof(DEV_ENABLE_INFO), &nRetLen, 1000); if (nret >= 0 && nRetLen > 0) { if (stDevEn.IsFucEnable[EN_MARK_IMPORTANTRECORD] != 0) { bSupport = true; } else { bSupport = false; } } int nProtocol = 0; //对查询图片功能进行能力级判断 if(8 == nRecordFileType) { if(SearchRecordProtocol(lLoginID)) { nProtocol = 1; } else { return FALSE; } } if(9==nRecordFileType) { if(SearchRecordProtocol(lLoginID)) { nProtocol = 1; } } int nRet = -1; *filecount = 0; NET_RECORDFILE_INFO recordfiletemp[MAX_RECORD_NUM]; int recordfilecounttemp = 0; afk_device_s *device = (afk_device_s*)lLoginID; afk_search_channel_param_s searchchannel = {0}; searchchannel.no = searchchannel.queryrecord.ch = nChannelId; searchchannel.base.func = QueryRecordFileInfoFunc; searchchannel.queryrecord.starttime.year = time_start->dwYear; searchchannel.queryrecord.starttime.month = time_start->dwMonth; searchchannel.queryrecord.starttime.day = time_start->dwDay; searchchannel.queryrecord.starttime.hour = time_start->dwHour; searchchannel.queryrecord.starttime.minute = time_start->dwMinute; searchchannel.queryrecord.starttime.second = time_start->dwSecond; searchchannel.queryrecord.endtime.year = time_end->dwYear; searchchannel.queryrecord.endtime.month = time_end->dwMonth; searchchannel.queryrecord.endtime.day = time_end->dwDay; searchchannel.queryrecord.endtime.hour = time_end->dwHour; searchchannel.queryrecord.endtime.minute = time_end->dwMinute; searchchannel.queryrecord.endtime.second = time_end->dwSecond; if (4 == nRecordFileType || 5 == nRecordFileType ||10 == nRecordFileType) //卡号查询,组合查询,按字段查询 { if (!cardid || strlen(cardid) > 256) //暂限制为256字节 { return NET_ILLEGAL_PARAM; } strcpy(searchchannel.queryrecord.cardid, cardid); } if (8 == nRecordFileType) //卡号查询图片(针对金桥网吧和上海公安) { if(cardid) { if(strlen(cardid) > 20) //卡号限制为20字节 { return NET_ILLEGAL_PARAM; } strcpy(searchchannel.queryrecord.cardid, cardid); } else { strcpy(searchchannel.queryrecord.cardid, ""); } } receivedata_s receivedata; receivedata.data = (char*)recordfiletemp; receivedata.datalen = &recordfilecounttemp; receivedata.maxlen = MAX_RECORD_NUM*sizeof(NET_RECORDFILE_INFO); //receivedata.hRecEvt = m_hRecEvent; receivedata.result = -1; searchchannel.base.udata = &receivedata; searchchannel.type = AFK_CHANNEL_SEARCH_RECORD; searchchannel.queryrecord.type = nRecordFileType; searchchannel.queryrecord.bytime = bTime?true:false; searchchannel.param = nProtocol; bool bFindEnd = false; unsigned long endDay = time_end->dwYear*10000 + time_end->dwMonth*100 + time_end->dwDay; unsigned long endTime = time_end->dwHour*10000 + time_end->dwMinute*100 + time_end->dwSecond; bool bFirstQueryrecord = true;//用于重要录像查询标识是否第一次查询 while (!bFindEnd) { recordfilecounttemp = 0; receivedata.result = -1; //add 2009.1.9 cqs int nImportantRecord = 0; if (!bFirstQueryrecord && bSupport)//重要录像的非第一次查询标识 { nImportantRecord = 1; } else { nImportantRecord = 0; } device->set_info(device, dit_firstqueryrecord_flag, &nImportantRecord); afk_channel_s *pchannel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_SEARCH, &searchchannel); if (pchannel) { DWORD dwRet = WaitForSingleObjectEx(receivedata.hRecEvt, waittime); pchannel->close(pchannel); ResetEventEx(receivedata.hRecEvt); if (dwRet == WAIT_OBJECT_0) { if (receivedata.result == -1) { m_pManager->SetLastError(NET_RETURN_DATA_ERROR); return FALSE; } else { //如果查询完毕 if (recordfilecounttemp == 0) { return TRUE; } if (recordfilecounttemp < 16) { bFindEnd = TRUE; } for (int i=0; i<recordfilecounttemp; i++) { LPNET_RECORDFILE_INFO ptemp = (LPNET_RECORDFILE_INFO)&recordfiletemp[i]; unsigned long startDay = ptemp->starttime.dwYear*10000 + ptemp->starttime.dwMonth*100 + ptemp->starttime.dwDay; unsigned long startTime = ptemp->starttime.dwHour*10000 + ptemp->starttime.dwMinute*100 + ptemp->starttime.dwSecond; if (endDay > startDay || (endDay == startDay && endTime > startTime)) { //缓冲区不够 if (maxlen >= (int)(sizeof(NET_RECORDFILE_INFO)*(*filecount + 1))) { memcpy(fileinfo + *filecount, ptemp, sizeof(NET_RECORDFILE_INFO)); (*filecount)++; } else { m_pManager->SetLastError(NET_INSUFFICIENT_BUFFER); return TRUE; } } else { bFindEnd = true; continue; } bFirstQueryrecord = false;//继续查询 searchchannel.queryrecord.starttime.year = ptemp->endtime.dwYear; searchchannel.queryrecord.starttime.month = ptemp->endtime.dwMonth; searchchannel.queryrecord.starttime.day = ptemp->endtime.dwDay; searchchannel.queryrecord.starttime.hour = ptemp->endtime.dwHour; searchchannel.queryrecord.starttime.minute = ptemp->endtime.dwMinute; searchchannel.queryrecord.starttime.second = ptemp->endtime.dwSecond + 1; } continue; } } //if (dwRet == WAIT_OBJECT_0) else { m_pManager->SetLastError(NET_NETWORK_ERROR); return FALSE; } } //if (pchannel) else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); return FALSE; } } m_pManager->SetLastError(NET_ERROR); return bFindEnd; } BOOL CSearchRecordAndPlayBack::QueryFurthestRecordTime(LONG lLoginID, int nRecordFileType, char *pchCardid, NET_FURTHEST_RECORD_TIME* pFurthrestTime, int nWaitTime) { if(NULL == pFurthrestTime) { return FALSE; } if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return FALSE; } DEV_DISK_RECORD_INFO stuDiskRecordInfo = {0}; int nRetLen = 0; int nRet = m_pManager->GetDevConfig().QueryDevState(lLoginID, DEVSTATE_RECORD_TIME, (char *)&stuDiskRecordInfo, sizeof(DEV_DISK_RECORD_INFO), &nRetLen, nWaitTime); if(nRet <= 0 && nRetLen == sizeof(DEV_DISK_RECORD_INFO)) { memset(pFurthrestTime, 0, sizeof(NET_FURTHEST_RECORD_TIME)); afk_device_s *device = (afk_device_s *)lLoginID; int nChnCount = device->channelcount(device); pFurthrestTime->nChnCount = nChnCount; NET_RECORDFILE_INFO stuRecordInfo = {0}; int nFileCount = 0; for(int i = 0; i < nChnCount; i++) { memset(&stuRecordInfo, 0 , sizeof(NET_RECORDFILE_INFO)); BOOL bSuccess = QueryRecordFile(lLoginID, i, nRecordFileType, &stuDiskRecordInfo.stuBeginTime, &stuDiskRecordInfo.stuEndTime, pchCardid, &stuRecordInfo, sizeof(NET_RECORDFILE_INFO), &nFileCount, nWaitTime, FALSE); if(bSuccess && nFileCount > 0)// 成功 { memcpy(&pFurthrestTime->stuFurthestTime[i], &stuRecordInfo.starttime, sizeof(NET_TIME)); } else //认为没录像 { memset(&pFurthrestTime->stuFurthestTime[i], 0, sizeof(NET_TIME)); } } return TRUE; } return FALSE; } /************************************************************************ ** 释放录像文件的句柄列表 ***********************************************************************/ void CSearchRecordAndPlayBack::ReleaseRecordFileInfo(st_SearchRecord_Info& sr) { list<NET_RECORDFILE_INFO*>::iterator it = sr.lstrf.begin(); for(; it != sr.lstrf.end(); ++it) { delete (*it); } sr.lstrf.clear(); } /************************************************************************ ** 处理查找录像文件:返回值 <0 失败, 0 成功 ***********************************************************************/ int CSearchRecordAndPlayBack::Process_QueryRecordfile(afk_device_s* device, int nChannelId, int nRecordFileType, LPNET_TIME time_start, LPNET_TIME time_end, char* cardid, int waittime, BOOL bTime, list<NET_RECORDFILE_INFO*>& lstRecordFile) { if (m_pManager->IsDeviceValid(device) < 0) { return NET_INVALID_HANDLE; } if (!time_start || !time_end) { return NET_ILLEGAL_PARAM; } if (*time_start >= *time_end) { return NET_ILLEGAL_PARAM; } //add by cqs 2009.1.9 //查询重要录像能力集 BOOL bSupport = FALSE; int nRetLen = -1; int nret = -1; DEV_ENABLE_INFO stDevEn = {0}; //查看能力 nret = m_pManager->GetDevConfig().GetDevFunctionInfo((LONG)device, ABILITY_DEVALL_INFO, (char*)&stDevEn, sizeof(DEV_ENABLE_INFO), &nRetLen, 1000); if (nret >= 0 && nRetLen > 0) { if (stDevEn.IsFucEnable[EN_MARK_IMPORTANTRECORD] != 0) { bSupport = TRUE; } else { bSupport = FALSE; } } //对按卡号查询图片功能进行能力级判断 if(8 == nRecordFileType) { if(!SearchRecordProtocol((LONG)device)) { return FALSE; } } lstRecordFile.clear(); NET_RECORDFILE_INFO recordfiletemp[MAX_RECORD_NUM]; int recordfilecounttemp = 0; afk_search_channel_param_s searchchannel = {0}; searchchannel.no = searchchannel.queryrecord.ch = nChannelId; searchchannel.base.func = QueryRecordFileInfoFunc; searchchannel.queryrecord.starttime.year = time_start->dwYear; searchchannel.queryrecord.starttime.month = time_start->dwMonth; searchchannel.queryrecord.starttime.day = time_start->dwDay; searchchannel.queryrecord.starttime.hour = time_start->dwHour; searchchannel.queryrecord.starttime.minute = time_start->dwMinute; searchchannel.queryrecord.starttime.second = time_start->dwSecond; searchchannel.queryrecord.endtime.year = time_end->dwYear; searchchannel.queryrecord.endtime.month = time_end->dwMonth; searchchannel.queryrecord.endtime.day = time_end->dwDay; searchchannel.queryrecord.endtime.hour = time_end->dwHour; searchchannel.queryrecord.endtime.minute = time_end->dwMinute; searchchannel.queryrecord.endtime.second = time_end->dwSecond; if (4 == nRecordFileType || 5 == nRecordFileType ||10 == nRecordFileType) //卡号查询 { if (!cardid || strlen(cardid) > 256) //暂限制为256字节 { return NET_ILLEGAL_PARAM; } strcpy(searchchannel.queryrecord.cardid, cardid); } if (8 == nRecordFileType) //卡号查询图片(针对金桥网吧) { if(cardid) { if(strlen(cardid) > 20) //卡号限制为20字节 { return NET_ILLEGAL_PARAM; } strcpy(searchchannel.queryrecord.cardid, cardid); } else { strcpy(searchchannel.queryrecord.cardid, ""); } } receivedata_s receivedata; receivedata.data = (char*)recordfiletemp; receivedata.datalen = &recordfilecounttemp; receivedata.maxlen = MAX_RECORD_NUM*sizeof(NET_RECORDFILE_INFO); //receivedata.hRecEvt = m_hRecEvent; receivedata.result = -1; searchchannel.base.udata = &receivedata; searchchannel.type = AFK_CHANNEL_SEARCH_RECORD; searchchannel.queryrecord.type = nRecordFileType; searchchannel.queryrecord.bytime = bTime?true:false; int nRet = 0; BOOL bFindEnd = FALSE; unsigned long endDay = time_end->dwYear*10000 + time_end->dwMonth*100 + time_end->dwDay; unsigned long endTime = time_end->dwHour*10000 + time_end->dwMinute*100 + time_end->dwSecond; bool bFirstQueryrecord = TRUE;//用于重要录像查询标识是否第一次查询 while (!bFindEnd) { recordfilecounttemp = 0; receivedata.result = -1; //add 2009.1.9 cqs int nImportantRecord = 0; if (!bFirstQueryrecord && bSupport)//重要录像的非第一次查询标识 { nImportantRecord = 1; } else { nImportantRecord = 0; } device->set_info(device, dit_firstqueryrecord_flag, &nImportantRecord); afk_channel_s *pchannel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_SEARCH, &searchchannel); /* 打开通道成功 */ if (pchannel) { DWORD dwRet = WaitForSingleObjectEx(receivedata.hRecEvt, waittime); pchannel->close(pchannel); ResetEventEx(receivedata.hRecEvt); /* 查询数据返回 */ if (dwRet == WAIT_OBJECT_0) { /* 返回数据失败 */ if (receivedata.result == -1) { nRet = NET_RETURN_DATA_ERROR; bFindEnd = TRUE; } /* 成功返回数据:处理数据 */ else { /* 查询完毕 */ if (recordfilecounttemp == 0) { bFindEnd = TRUE; } if (recordfilecounttemp < 16) { bFindEnd = TRUE; } if (lstRecordFile.size() > 50000) // 异常处理 { nRet = NET_RETURN_DATA_ERROR; bFindEnd = TRUE; } /* 处理数据 */ for (int i=0; i<recordfilecounttemp; i++) { LPNET_RECORDFILE_INFO ptemp = (LPNET_RECORDFILE_INFO)&recordfiletemp[i]; unsigned long startDay = ptemp->starttime.dwYear*10000 + ptemp->starttime.dwMonth*100 + ptemp->starttime.dwDay; unsigned long startTime = ptemp->starttime.dwHour*10000 + ptemp->starttime.dwMinute*100 + ptemp->starttime.dwSecond; /* 在查询时间范围内:加载数据 */ if (endDay > startDay || (endDay == startDay && endTime > startTime)) { NET_RECORDFILE_INFO* prf = new NET_RECORDFILE_INFO; /* 申请内存出错 */ if (!prf) { nRet = NET_SYSTEM_ERROR; bFindEnd = TRUE; } else { memcpy(prf, ptemp, sizeof(NET_RECORDFILE_INFO)); lstRecordFile.push_back(prf); } } else { /* 在查找时间范围之外:退出,返回成功 */ bFindEnd = TRUE; } bFirstQueryrecord = FALSE;//继续查询 searchchannel.queryrecord.starttime.year = ptemp->endtime.dwYear; searchchannel.queryrecord.starttime.month = ptemp->endtime.dwMonth; searchchannel.queryrecord.starttime.day = ptemp->endtime.dwDay; searchchannel.queryrecord.starttime.hour = ptemp->endtime.dwHour; searchchannel.queryrecord.starttime.minute = ptemp->endtime.dwMinute; searchchannel.queryrecord.starttime.second = ptemp->endtime.dwSecond + 1; }// end of for (int i=0; i<recordfilecounttemp; i++) }/* 成功返回数据:处理数据 */ }//end of if (dwRet == WAIT_OBJECT_0) else { /* 等待超时 */ nRet = NET_NETWORK_ERROR; // bResult = false; bFindEnd = TRUE; } }// end of if (pchannel) else { /* 打开通道失败 */ nRet = NET_OPEN_CHANNEL_ERROR; bFindEnd = TRUE; } }// end of while (!bFindEnd) //重要录像进行排序 if (bSupport) { SortRecordFileList(lstRecordFile); } if (nRet < 0) { st_SearchRecord_Info sr; sr.lstrf = lstRecordFile; ReleaseRecordFileInfo(sr); lstRecordFile.clear(); } return nRet; } /************************************************************************ ** 开始查找录像文件:返回值 0 失败, >0 查找句柄 ***********************************************************************/ LONG CSearchRecordAndPlayBack::FindFile(LONG lLoginID, int nChannelId, int nRecordFileType, char* cardid, LPNET_TIME time_start, LPNET_TIME time_end, BOOL bTime, int waittime) { afk_device_s *device = (afk_device_s*)lLoginID; st_SearchRecord_Info * psr = new st_SearchRecord_Info; if (!psr) { m_pManager->SetLastError(NET_SYSTEM_ERROR); return 0; } psr->device = device; int r = Process_QueryRecordfile(device, nChannelId, nRecordFileType, time_start, time_end, cardid, waittime, bTime, psr->lstrf); if (r < 0) { if (psr) { delete psr; } m_pManager->SetLastError(r); return 0; } m_csSRI.Lock(); m_lstSRI.push_back(psr); m_csSRI.UnLock(); return (LONG)psr; } /************************************************************************ ** 查找录像文件:返回值 -1 参数出错,0 录像文件信息数据取完,1 取回一条录像文件信息 ***********************************************************************/ int CSearchRecordAndPlayBack::FindNextFile(LONG lFindHandle,LPNET_RECORDFILE_INFO lpFindData) { if (!lpFindData) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return -1; //参数出错 } else { memset(lpFindData, 0x00, sizeof(NET_RECORDFILE_INFO)); } int iRet = 0; m_csSRI.Lock(); list<st_SearchRecord_Info*>::iterator it = find(m_lstSRI.begin(), m_lstSRI.end(), (st_SearchRecord_Info*)lFindHandle); /* 查找句柄有效 */ if (it != m_lstSRI.end()) { while (1) { size_t s = (*it)->lstrf.size(); /* 还有录像文件信息数据 */ if (s > 0) { NET_RECORDFILE_INFO* p = (*it)->lstrf.front(); if (p) { memcpy(lpFindData, p, sizeof(NET_RECORDFILE_INFO)); (*it)->lstrf.pop_front(); delete p; iRet = 1; //取回数据,返回成功 goto END; } else { (*it)->lstrf.pop_front(); continue; } } /* 录像文件信息数据取完 */ else { iRet = 0; goto END; //录像文件信息数据取完 } } } /* 句柄无效 */ else { m_pManager->SetLastError(NET_INVALID_HANDLE); iRet = -1; //参数出错 goto END; } END: m_csSRI.UnLock(); return iRet; //录像文件信息数据取完 } /************************************************************************ ** 结束录像文件查找:返回值 TRUE 成功, FALSE 失败 ***********************************************************************/ int CSearchRecordAndPlayBack::FindClose(LONG lFindHandle) { int iRet = 0; m_csSRI.Lock(); list<st_SearchRecord_Info*>::iterator it = find(m_lstSRI.begin(), m_lstSRI.end(), (st_SearchRecord_Info*)lFindHandle); if (it != m_lstSRI.end()) { ReleaseRecordFileInfo(**it); delete (*it); m_lstSRI.erase(it); } else { m_pManager->SetLastError(NET_INVALID_HANDLE); iRet = -1; } m_csSRI.UnLock(); return iRet; } int __stdcall CSearchRecordAndPlayBack::NetPlayBackCallBackFunc( afk_handle_t object, /* 数据提供者 */ unsigned char *data, /* 数据体 */ unsigned int datalen, /* 数据长度 */ void *param, /* 回调参数 */ void *udata ) { int nRet = -1; afk_channel_s *channel = (afk_channel_s*)object; st_NetPlayBack_Info* netplaybackinfo = (st_NetPlayBack_Info*)udata; if (channel == NULL || netplaybackinfo == NULL) { return nRet; } if (channel && netplaybackinfo && (netplaybackinfo->channel == channel)) { if (datalen != -1) { netplaybackinfo->nReceiveSize += datalen; if (netplaybackinfo->PlayBack) { nRet = netplaybackinfo->PlayBack->AddData(data, datalen); } if ((unsigned int)param > 0 &&netplaybackinfo->nFrameRate != (unsigned int)param && netplaybackinfo->Render) { // 播放SDK自适应,不需要调用接口改帧率。 // netplaybackinfo->Render->SetFrameRate((unsigned int)param); netplaybackinfo->nFrameRate = (unsigned int)param; } } else { netplaybackinfo->ncurrf++; if (netplaybackinfo->prf && (netplaybackinfo->ncurrf < netplaybackinfo->nrflen)) { NET_RECORDFILE_INFO* p = netplaybackinfo->prf+netplaybackinfo->ncurrf; afk_download_channel_param_s parm = {0}; memcpy(&parm.info, netplaybackinfo->prf+netplaybackinfo->ncurrf, sizeof(NET_RECORDFILE_INFO)); parm.nByTime = 1; parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel->set_info(channel, 1, (void*)(&parm)); if (netplaybackinfo->PlayBack) { netplaybackinfo->PlayBack->IsRePause(); } nRet = 1; } else { netplaybackinfo->bDownLoadEnd = TRUE; nRet = 1; } } } return nRet; } bool __stdcall NetPlayBack_ReadDataPauseFunc(bool bPause, void *userdata) { afk_channel_s *channel = (afk_channel_s*)userdata; return channel->pause(channel, bPause); } DWORD GetOffsetTimeByByte(const st_NetPlayBack_Info *pNetPlayBackInfo, unsigned int nOffsetByte, DWORD dwTotalTime) { DWORD dwOffsetTime = 0; if (pNetPlayBackInfo->prf != NULL && pNetPlayBackInfo->nrflen > 0) { DWORD dwFileSize = 0; DWORD offset = 0; for (int i = 0; i < pNetPlayBackInfo->nrflen; i++) { dwFileSize += pNetPlayBackInfo->prf[i].size; offset = GetOffsetTime(pNetPlayBackInfo->prf[i].starttime, pNetPlayBackInfo->prf[i].endtime); if (nOffsetByte <= dwFileSize) { if (pNetPlayBackInfo->prf[i].size != 0) { dwOffsetTime += (pNetPlayBackInfo->prf[i].size + nOffsetByte - dwFileSize)*offset/pNetPlayBackInfo->prf[i].size; } break; } dwOffsetTime += offset; } } return dwOffsetTime; } void* WINAPI pbthreadproc(LPVOID pPara) { st_NetPlayBack_Info *netplaybacktemp = (st_NetPlayBack_Info*)pPara; if (netplaybacktemp == NULL) { return (void*)0xFFFFFFFF; } BOOL bReceiveData = FALSE; // 异常处理,如果设备一直没数据过来直接回调进度结束 DWORD dwStartTime = GetTickCountEx(); while(TRUE) { DWORD dwRet = WaitForSingleObjectEx(netplaybacktemp->hPBExit, 0); if (WAIT_OBJECT_0 == dwRet) { break; } int nStat = 1; unsigned char buffer[1024]; int whileCount = 0; while (whileCount++ <= 10) { int readlen = netplaybacktemp->PlayBack->GetData(buffer, 1024); if (readlen > 0) { bReceiveData = TRUE; if (netplaybacktemp->Render) { BOOL bret = netplaybacktemp->Render->Play(buffer, readlen); if (bret) { //数据回调函数 if (netplaybacktemp->fNetDataCallBack) { int nret = netplaybacktemp->fNetDataCallBack((LONG)netplaybacktemp->channel, 0, buffer, readlen, netplaybacktemp->dwDataUser); /* if (nret > 0) { //>0正常 netplaybacktemp->PlayBack->DecDataLength(readlen); } else if (0 == nret) { //0-阻塞 nStat = 0; break; } else { //<0系统出错 nStat = -1; break; } */ netplaybacktemp->PlayBack->DecDataLength(readlen); } else { //无数据回调 netplaybacktemp->PlayBack->DecDataLength(readlen); } } else { nStat = 0; break; } } else if (netplaybacktemp->fNetDataCallBack) { int nret = netplaybacktemp->fNetDataCallBack((LONG)netplaybacktemp->channel, 0, buffer, readlen, netplaybacktemp->dwDataUser); if (nret > 0) { //>0正常 netplaybacktemp->PlayBack->DecDataLength(readlen); } else if (0 == nret) { //0-阻塞 nStat = 0; break; } else { //<0系统出错 nStat = -1; break; } } else { //没人接收数据了,扔掉 netplaybacktemp->PlayBack->DecDataLength(readlen); break; } }//if (readlen > 0) else { nStat = 0; //block; break; } } DWORD dwPlayRemainBufLen = 0; if (netplaybacktemp->Render) { dwPlayRemainBufLen = netplaybacktemp->Render->GetSourceBufferRemain(); } netplaybacktemp->nPlayBackSize = netplaybacktemp->nOffsetSize + (int)(netplaybacktemp->nReceiveSize - netplaybacktemp->PlayBack->GetSize() - dwPlayRemainBufLen)/(int)1024; if (netplaybacktemp->pNetPlayBackPosCallBack) { if (netplaybacktemp->nPlayBackSize < netplaybacktemp->nTotalSize) { if (0 == netplaybacktemp->nPlayBackType) { netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->nTotalSize, netplaybacktemp->nPlayBackSize, netplaybacktemp->dwPosUser); } else if (1 == netplaybacktemp->nPlayBackType) { DWORD dwOffsetTime = GetOffsetTimeByByte(netplaybacktemp, netplaybacktemp->nPlayBackSize, netplaybacktemp->dwTotalTime); netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->dwTotalTime, dwOffsetTime, netplaybacktemp->dwPosUser); } } //下载已结束 if ((netplaybacktemp->bDownLoadEnd && netplaybacktemp->PlayBack->GetSize() <= 0) || (!bReceiveData && GetTickCountEx() - dwStartTime > 60000)) { if (netplaybacktemp->Render) { if (netplaybacktemp->Render->IsEmpty()) { netplaybacktemp->nPlayBackSize = netplaybacktemp->nTotalSize; if (0 == netplaybacktemp->nPlayBackType) { netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->nTotalSize, -1, netplaybacktemp->dwPosUser); } else if (1 == netplaybacktemp->nPlayBackType) { netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->dwTotalTime, -1, netplaybacktemp->dwPosUser); } nStat = 0; break; } } else if (netplaybacktemp->fNetDataCallBack) { netplaybacktemp->nPlayBackSize = netplaybacktemp->nTotalSize; if (0 == netplaybacktemp->nPlayBackType) { netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->nTotalSize, -1, netplaybacktemp->dwPosUser); } else if (1 == netplaybacktemp->nPlayBackType) { netplaybacktemp->pNetPlayBackPosCallBack((LONG)netplaybacktemp->channel, netplaybacktemp->dwTotalTime, -1, netplaybacktemp->dwPosUser); } nStat = 0; break; } } } if (0 == nStat) { Sleep(5); //block } else if(nStat < 0) { break; } } return 0; } LONG CSearchRecordAndPlayBack::PlayBackByRecordFile(LONG lLoginID, LPNET_RECORDFILE_INFO lpRecordFile, HWND hWnd, fDownLoadPosCallBack cbDownLoadPos, DWORD dwUserData) { afk_device_s *device = (afk_device_s*)lLoginID; if (m_pManager->IsDeviceValid(device) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } if (lpRecordFile == NULL || hWnd == NULL) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_PLAYBACK; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, lpRecordFile->ch, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } /* 准备解码资源 */ CVideoRender *pRender = m_pManager->GetRenderManager().GetRender(hWnd); if (-1 == (int)pRender) { m_pManager->SetLastError(NET_SYSTEM_ERROR); return 0; //系统出错 } st_NetPlayBack_Info* ppb = NULL; afk_channel_s *channel = NULL; CNetPlayBack *pNetPlayBack = NULL; NET_RECORDFILE_INFO* myFile = NULL; if (pRender) { if (pRender->StartDec(true) < 0) { m_pManager->SetLastError(NET_DEC_OPEN_ERROR); goto e_clearup; } } //store record file information myFile = new NET_RECORDFILE_INFO; if (myFile == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } memcpy(myFile, lpRecordFile, sizeof(NET_RECORDFILE_INFO)); // 增加网络回放列表 ppb = new st_NetPlayBack_Info; if (ppb == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channelid = lpRecordFile->ch; ppb->Render = pRender; ppb->PlayBack = NULL; ppb->channel = NULL; ppb->nPlayBackType = 0; ppb->nTotalSize = lpRecordFile->size; ppb->timeStart = lpRecordFile->starttime; ppb->timeEnd = lpRecordFile->endtime; ppb->nOffsetSize = 0; ppb->nReceiveSize = 0; ppb->nPlayBackSize = 0; ppb->bDownLoadEnd = FALSE; ppb->nFrameRate = 25; ppb->bAudioPlay = FALSE; ppb->pNetPlayBackPosCallBack = cbDownLoadPos; ppb->dwPosUser = dwUserData; ppb->fNetDataCallBack = NULL; ppb->dwDataUser = 0; ppb->pFileInfo = myFile; ppb->prf = NULL; ppb->nrflen = 0; ppb->ncurrf = 0; ppb->dwThreadID = 0; ppb->nConnectID = stuConnParam.nConnectID; //创建下载通道 afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = CSearchRecordAndPlayBack::NetPlayBackCallBackFunc; parm.base.udata = ppb; parm.conn = stuConnParam; memcpy(&parm.info, lpRecordFile, sizeof(NET_RECORDFILE_INFO)); parm.info.ch = lpRecordFile->ch; parm.nByTime = 0; parm.nParam = 0; //回放 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { if (pRender) { pRender->SetDrawCallBack((void*)m_pManager->GetDrawFunc(), (void*)device, (void*)channel, (void*)m_pManager->GetDrawCallBackUserData()); } //创建网络回放缓冲 NetPlayBack_CallBack netPlayBackCallBack; netPlayBackCallBack.ReadDataPauseFunc = NetPlayBack_ReadDataPauseFunc; netPlayBackCallBack.pUserData = channel; pNetPlayBack = new CNetPlayBack(netPlayBackCallBack); if (!pNetPlayBack) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channel = channel; ppb->PlayBack = pNetPlayBack; ret = CreateEventEx(ppb->hPBExit, FALSE, FALSE); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ret = CreateThreadEx(ppb->hThread, 0, (LPTHREAD_START_ROUTINE)pbthreadproc, (void*)ppb, /*CREATE_SUSPENDED*/0, &ppb->dwThreadID); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } m_csNPI.Lock(); m_lstNPI.push_back(ppb); m_csNPI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); goto e_clearup; } return (LONG)channel; e_clearup: if (ppb) { TerminateThreadEx(ppb->hThread, 0); CloseEventEx(ppb->hPBExit); CloseThreadEx(ppb->hThread); delete ppb; ppb = NULL; } if (channel) { channel->close(channel); channel = NULL; } if (pRender) { pRender->StopDec(); m_pManager->GetRenderManager().ReleaseRender(pRender); } if (myFile) { delete myFile; myFile = NULL; } if (pNetPlayBack) { delete pNetPlayBack; pNetPlayBack = NULL; } return 0; } LONG CSearchRecordAndPlayBack::PlayBackByRecordFileEx(LONG lLoginID, LPNET_RECORDFILE_INFO lpRecordFile, HWND hWnd, fDownLoadPosCallBack cbDownLoadPos, DWORD dwPosData, fDataCallBack fDownLoadDataCallBack, DWORD dwDataUser) { afk_device_s *device = (afk_device_s*)lLoginID; if (m_pManager->IsDeviceValid(device) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } if(!lpRecordFile || (!hWnd && !fDownLoadDataCallBack)) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_PLAYBACK; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, lpRecordFile->ch, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } /* 准备解码资源 */ CVideoRender *pRender = m_pManager->GetRenderManager().GetRender(hWnd); if (-1 == (int)pRender) { m_pManager->SetLastError(NET_SYSTEM_ERROR); return 0; //系统出错 } st_NetPlayBack_Info* ppb = NULL; afk_channel_s *channel = NULL; CNetPlayBack *pNetPlayBack = NULL; NET_RECORDFILE_INFO* myFile = NULL; if (pRender) { if (pRender->StartDec(true) < 0) { m_pManager->SetLastError(NET_DEC_OPEN_ERROR); goto e_clearup; } } //store record file information myFile = new NET_RECORDFILE_INFO; if (myFile == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } memcpy(myFile, lpRecordFile, sizeof(NET_RECORDFILE_INFO)); // 增加网络回放列表 ppb = new st_NetPlayBack_Info; if (ppb == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channelid = lpRecordFile->ch; ppb->Render = pRender; ppb->PlayBack = NULL; ppb->channel = NULL; ppb->nPlayBackType = 0; ppb->nTotalSize = lpRecordFile->size; ppb->timeStart = lpRecordFile->starttime; ppb->timeEnd = lpRecordFile->endtime; ppb->nOffsetSize = 0; ppb->nReceiveSize = 0; ppb->nPlayBackSize = 0; ppb->bDownLoadEnd = FALSE; ppb->nFrameRate = 25; ppb->bAudioPlay = FALSE; ppb->pNetPlayBackPosCallBack = cbDownLoadPos; ppb->dwPosUser = dwPosData; ppb->pFileInfo = myFile; ppb->prf = NULL; ppb->nrflen = 0; ppb->ncurrf = 0; ppb->fNetDataCallBack = fDownLoadDataCallBack; ppb->dwDataUser = dwDataUser; ppb->dwThreadID = 0; ppb->nConnectID = stuConnParam.nConnectID; //创建下载通道 afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = CSearchRecordAndPlayBack::NetPlayBackCallBackFunc; parm.base.udata = ppb; parm.conn = stuConnParam; memcpy(&parm.info, lpRecordFile, sizeof(NET_RECORDFILE_INFO)); parm.info.ch = lpRecordFile->ch; ppb->pFileInfo->ch = parm.info.ch; parm.nByTime = 0; parm.nParam = 0; //回放 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { if (pRender) { pRender->SetDrawCallBack((void*)m_pManager->GetDrawFunc(), (void*)device, (void*)channel, (void*)m_pManager->GetDrawCallBackUserData()); } //创建网络回放缓冲 NetPlayBack_CallBack netPlayBackCallBack; netPlayBackCallBack.ReadDataPauseFunc = NetPlayBack_ReadDataPauseFunc; netPlayBackCallBack.pUserData = channel; pNetPlayBack = new CNetPlayBack(netPlayBackCallBack); if (!pNetPlayBack) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channel = channel; ppb->PlayBack = pNetPlayBack; ret = CreateEventEx(ppb->hPBExit, FALSE, FALSE); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ret = CreateThreadEx(ppb->hThread, 0, (LPTHREAD_START_ROUTINE)pbthreadproc, (void*)ppb, /*CREATE_SUSPENDED*/0, &ppb->dwThreadID); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } m_csNPI.Lock(); m_lstNPI.push_back(ppb); m_csNPI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); goto e_clearup; } return (LONG)channel; e_clearup: if (ppb) { TerminateThreadEx(ppb->hThread, 0); CloseEventEx(ppb->hPBExit); CloseThreadEx(ppb->hThread); delete ppb; ppb = NULL; } if (channel) { channel->close(channel); channel = NULL; } if (pRender) { pRender->StopDec(); m_pManager->GetRenderManager().ReleaseRender(pRender); } if (myFile) { delete myFile; myFile = NULL; } if (pNetPlayBack) { delete pNetPlayBack; pNetPlayBack = NULL; } return 0; } LONG CSearchRecordAndPlayBack::PlayBackByTime(LONG lLoginID, int nChannelID, LPNET_TIME lpStartTime, LPNET_TIME lpStopTIme, fDownLoadPosCallBack cbDownLoadPos, DWORD dwPosUser, HWND hWnd) { afk_device_s *device = (afk_device_s*)lLoginID; if (m_pManager->IsDeviceValid(device) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } if (!lpStartTime || !lpStopTIme || !hWnd) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_PLAYBACK; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, nChannelID, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } /* 再查询时间段内的文件列表 */ list<NET_RECORDFILE_INFO*> lstrf; ret = Process_QueryRecordfile(device, nChannelID, 0/*全部类型*/, lpStartTime, lpStopTIme, 0, 3000, true, lstrf); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } else if (lstrf.size() <= 0) { m_pManager->SetLastError(NET_NO_RECORD_FOUND); return 0; } st_NetPlayBack_Info* ppb = NULL; afk_channel_s *channel = NULL; CNetPlayBack *pNetPlayBack = NULL; NET_RECORDFILE_INFO* prf = NULL; CVideoRender *pRender = NULL; DWORD dwTotalSize = 0; DWORD dwTotalTime = 0; int nrflen = lstrf.size(); prf = new NET_RECORDFILE_INFO[nrflen]; if (prf == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); st_SearchRecord_Info sr; sr.lstrf = lstrf; ReleaseRecordFileInfo(sr); return 0; } list<NET_RECORDFILE_INFO*>::iterator it = lstrf.begin(); for(int i=0; (it!=lstrf.end())&& (i<nrflen); it++,i++) { memcpy(prf+i, *it, sizeof(NET_RECORDFILE_INFO)); dwTotalSize += prf[i].size; dwTotalTime += GetOffsetTime(prf[i].starttime, prf[i].endtime); delete *it; } lstrf.clear(); /* 准备解码资源 */ pRender = m_pManager->GetRenderManager().GetRender(hWnd); if (-1 == (int)pRender) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } if (pRender) { if (pRender->StartDec(true) < 0) { m_pManager->SetLastError(NET_DEC_OPEN_ERROR); goto e_clearup; } } //增加网络回放列表 ppb = new st_NetPlayBack_Info; if (ppb == NULL) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channelid = prf->ch; ppb->Render = pRender; ppb->PlayBack = 0; ppb->channel = 0; ppb->nPlayBackType = 1; ppb->dwTotalTime = dwTotalTime; ppb->nTotalSize = dwTotalSize; ppb->timeStart = *lpStartTime; ppb->timeEnd = *lpStopTIme; ppb->nOffsetSize = 0; ppb->nReceiveSize = 0; ppb->nPlayBackSize = 0; ppb->bDownLoadEnd = FALSE; ppb->nFrameRate = 25; ppb->bAudioPlay = FALSE; ppb->pNetPlayBackPosCallBack = cbDownLoadPos; ppb->dwPosUser = dwPosUser; ppb->fNetDataCallBack = 0; ppb->dwDataUser = 0; ppb->pFileInfo = 0; ppb->prf = prf; ppb->nrflen = nrflen; ppb->ncurrf = 0; ppb->dwThreadID = 0; ppb->nConnectID = stuConnParam.nConnectID; //创建下载通道 afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = CSearchRecordAndPlayBack::NetPlayBackCallBackFunc; parm.base.udata = ppb; parm.conn = stuConnParam; memcpy(&parm.info, prf, sizeof(NET_RECORDFILE_INFO)); parm.info.ch = prf->ch; parm.nByTime = 1; parm.nParam = 0; //回放 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { if (pRender) { pRender->SetDrawCallBack((void*)m_pManager->GetDrawFunc(), (void*)device, (void*)channel, (void*)m_pManager->GetDrawCallBackUserData()); } //创建网络回放缓冲 NetPlayBack_CallBack netPlayBackCallBack; netPlayBackCallBack.ReadDataPauseFunc = NetPlayBack_ReadDataPauseFunc; netPlayBackCallBack.pUserData = channel; pNetPlayBack = new CNetPlayBack(netPlayBackCallBack); if (!pNetPlayBack) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channel = channel; ppb->PlayBack = pNetPlayBack; ret = CreateEventEx(ppb->hPBExit, FALSE, FALSE); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ret = CreateThreadEx(ppb->hThread, 0, (LPTHREAD_START_ROUTINE)pbthreadproc, (void*)ppb, /*CREATE_SUSPENDED*/0, &ppb->dwThreadID); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } m_csNPI.Lock(); m_lstNPI.push_back(ppb); m_csNPI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); goto e_clearup; } return (LONG)channel; e_clearup: if (ppb) { TerminateThreadEx(ppb->hThread, 0); CloseEventEx(ppb->hPBExit); CloseThreadEx(ppb->hThread); delete ppb; ppb = NULL; } if (channel) { channel->close(channel); channel = NULL; } if (pRender) { pRender->StopDec(); m_pManager->GetRenderManager().ReleaseRender(pRender); } if (prf) { delete[] prf; prf = NULL; } if (pNetPlayBack) { delete pNetPlayBack; pNetPlayBack = NULL; } return 0; } LONG CSearchRecordAndPlayBack::PlayBackByTimeEx(LONG lLoginID, int nChannelID, LPNET_TIME lpStartTime, LPNET_TIME lpStopTIme, fDownLoadPosCallBack cbDownLoadPos, DWORD dwPosUser, HWND hWnd, fDataCallBack fDownLoadDataCallBack, DWORD dwDataUser) { afk_device_s *device = (afk_device_s*)lLoginID; if (m_pManager->IsDeviceValid(device) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } if (!lpStartTime || !lpStopTIme || (!hWnd && !fDownLoadDataCallBack)) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_PLAYBACK; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, nChannelID, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } /* 再查询时间段内的文件列表 */ list<NET_RECORDFILE_INFO*> lstrf; ret = Process_QueryRecordfile(device, nChannelID, 0/*全部类型*/, lpStartTime, lpStopTIme, 0, 3000, true, lstrf); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } else if (lstrf.size() <= 0) { m_pManager->SetLastError(NET_NO_RECORD_FOUND); return 0; } st_NetPlayBack_Info* ppb = NULL; afk_channel_s *channel = NULL; CNetPlayBack *pNetPlayBack = NULL; NET_RECORDFILE_INFO* prf = NULL; CVideoRender *pRender = NULL; DWORD dwTotalSize = 0; DWORD dwTotalTime = 0; int nrflen = lstrf.size(); prf = new NET_RECORDFILE_INFO[nrflen]; if (!prf) { m_pManager->SetLastError(NET_SYSTEM_ERROR); st_SearchRecord_Info sr; sr.lstrf = lstrf; ReleaseRecordFileInfo(sr); return 0; } list<NET_RECORDFILE_INFO*>::iterator it = lstrf.begin(); for(int i=0; (it!=lstrf.end())&& (i<nrflen); it++,i++) { memcpy(prf+i, *it, sizeof(NET_RECORDFILE_INFO)); dwTotalSize += prf[i].size; dwTotalTime += GetOffsetTime(prf[i].starttime, prf[i].endtime); delete *it; } lstrf.clear(); /* 准备解码资源 */ pRender = m_pManager->GetRenderManager().GetRender(hWnd); if (-1 == (int)pRender) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } if (pRender) { if (pRender->StartDec(true) < 0) { m_pManager->SetLastError(NET_DEC_OPEN_ERROR); goto e_clearup; } } //增加网络回放列表 ppb = new st_NetPlayBack_Info; if (!ppb) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channelid = prf->ch; ppb->Render = pRender; ppb->PlayBack = 0; ppb->channel = 0; ppb->nPlayBackType = 1; ppb->dwTotalTime = dwTotalTime; ppb->nTotalSize = dwTotalSize; ppb->timeStart = *lpStartTime; ppb->timeEnd = *lpStopTIme; ppb->nOffsetSize = 0; ppb->nReceiveSize = 0; ppb->nPlayBackSize = 0; ppb->bDownLoadEnd = FALSE; ppb->nFrameRate = 25; ppb->bAudioPlay = FALSE; ppb->pNetPlayBackPosCallBack = cbDownLoadPos; ppb->dwPosUser = dwPosUser; ppb->fNetDataCallBack = /*pRender ? 0 : */fDownLoadDataCallBack; ppb->dwDataUser = dwDataUser; ppb->pFileInfo = 0; ppb->prf = prf; ppb->nrflen = nrflen; ppb->ncurrf = 0; ppb->dwThreadID = 0; ppb->nConnectID = stuConnParam.nConnectID; //创建下载通道 afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = CSearchRecordAndPlayBack::NetPlayBackCallBackFunc; parm.base.udata = ppb; parm.conn = stuConnParam; memcpy(&parm.info, prf, sizeof(NET_RECORDFILE_INFO)); parm.info.ch = prf->ch; parm.nByTime = 1; parm.nParam = 0; //回放 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { if (pRender) { pRender->SetDrawCallBack((void*)m_pManager->GetDrawFunc(), (void*)device, (void*)channel, (void*)m_pManager->GetDrawCallBackUserData()); } //创建网络回放缓冲 NetPlayBack_CallBack netPlayBackCallBack; netPlayBackCallBack.ReadDataPauseFunc = NetPlayBack_ReadDataPauseFunc; netPlayBackCallBack.pUserData = channel; pNetPlayBack = new CNetPlayBack(netPlayBackCallBack); if (!pNetPlayBack) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ppb->channel = channel; ppb->PlayBack = pNetPlayBack; ret = CreateEventEx(ppb->hPBExit, FALSE, FALSE); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } ret = CreateThreadEx(ppb->hThread, 0, (LPTHREAD_START_ROUTINE)pbthreadproc, (void*)ppb, /*CREATE_SUSPENDED*/0, &ppb->dwThreadID); if (ret < 0) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } m_csNPI.Lock(); m_lstNPI.push_back(ppb); m_csNPI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); goto e_clearup; } return (LONG)channel; e_clearup: if (ppb) { TerminateThreadEx(ppb->hThread, 0); CloseEventEx(ppb->hPBExit); CloseThreadEx(ppb->hThread); delete ppb; ppb = NULL; } if (channel) { channel->close(channel); channel = NULL; } if (pRender) { pRender->StopDec(); m_pManager->GetRenderManager().ReleaseRender(pRender); } if (prf) { delete[] prf; prf = NULL; } if (pNetPlayBack) { delete pNetPlayBack; pNetPlayBack = NULL; } return 0; } st_NetPlayBack_Info* CSearchRecordAndPlayBack::GetNetPlayBackInfo(LONG lPlayHandle) { st_NetPlayBack_Info* p = NULL; list<st_NetPlayBack_Info*>::iterator it = find_if(m_lstNPI.begin(),m_lstNPI.end(),SearchNPIbyChannel(lPlayHandle)); if (it != m_lstNPI.end()) { p = (*it); } return p; } int CSearchRecordAndPlayBack::PausePlayBack(LONG lPlayHandle, BOOL bPause) { int nRet = -1; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->Pause(bPause == TRUE); if (b) { nRet = 0; } else { nRet = NET_RENDER_PAUSE_ERROR; } } else { bool b = pNPI->channel->pause(pNPI->channel, bPause?true:false); if (b) { nRet = 0; } else { nRet = NET_RENDER_PAUSE_ERROR; } } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } /* parameter dwOffsetSize for output size */ int GetSeekFileBySeekTime(const st_NetPlayBack_Info& npi, unsigned int offsettime, DWORD& dwOffsetSize, DWORD& dwOffsetTime) { int nFileID = 0; if (npi.prf && npi.nrflen) { DWORD dwTotalTime = 0; for (int i = 0; i < npi.nrflen; i++) { DWORD offset = GetOffsetTime(npi.prf[i].starttime, npi.prf[i].endtime); dwTotalTime += offset; if (offsettime <= dwTotalTime) { dwOffsetTime = offset + offsettime - dwTotalTime; if (offset != 0) { dwOffsetSize += (DWORD)(dwOffsetTime*1.0/offset*npi.prf[i].size); } nFileID = i; break; } dwOffsetSize += npi.prf[i].size; } } return nFileID; } int CSearchRecordAndPlayBack::SeekPlayBack(LONG lPlayHandle, unsigned int offsettime, unsigned int offsetbyte) { int nRet = NET_NOERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (INVALID_OFFSET_TIME != offsettime && pNPI->prf && pNPI->nrflen) { DWORD dwOffsetSize = 0; // 拖动位置的文件偏移大小 DWORD dwOffsetTime = 0; // 定位后的文件偏移时间 int nSeekrf = GetSeekFileBySeekTime(*pNPI, offsettime, dwOffsetSize, dwOffsetTime); if (nSeekrf >= 0) { if (nSeekrf != pNPI->ncurrf) // 要定位的文件不是当前的文件,打开此文件 { NET_RECORDFILE_INFO* p = pNPI->prf+nSeekrf; afk_download_channel_param_s parm = {0}; memcpy(&parm.info, pNPI->prf+nSeekrf, sizeof(NET_RECORDFILE_INFO)); parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; parm.nByTime = 1; int r = pNPI->channel->set_info(pNPI->channel, 1, (void*)(&parm)); if (r == 0) { nRet = NET_NETWORK_ERROR; } else { pNPI->ncurrf = nSeekrf; } } else { // 要定位的文件就是当前文件 if (pNPI->bDownLoadEnd) { // 已结束,重新打开文件 afk_download_channel_param_s parm = {0}; memcpy(&parm.info, pNPI->prf+pNPI->ncurrf, sizeof(NET_RECORDFILE_INFO)); parm.nByTime = 0; parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; int r = pNPI->channel->set_info(pNPI->channel, 1, (void*)(&parm)); if (r == 0) { nRet = NET_NETWORK_ERROR; } } } } else { nRet = NET_ILLEGAL_PARAM; } if (nRet == NET_NOERROR) { // 按时间定位 afk_download_control_param_s parm = {0}; pNPI->PlayBack->Pause(BUFFER_RESET); //Sleep(100); parm.offsettime = dwOffsetTime; parm.offsetdata = INVAlID_OFFSET_BYTE; int r = pNPI->channel->set_info(pNPI->channel, 0, &parm); if (r == 0) { nRet = NET_NETWORK_ERROR; } else { pNPI->bDownLoadEnd = FALSE; if (pNPI->PlayBack) { pNPI->PlayBack->Reset(); } if (pNPI->Render) { pNPI->Render->Reset(); } pNPI->nOffsetSize = dwOffsetSize; pNPI->nReceiveSize = 0; nRet = 0; } pNPI->PlayBack->Resume(BUFFER_RESET); } } else if (INVAlID_OFFSET_BYTE != offsetbyte && !pNPI->nrflen) { if (pNPI->bDownLoadEnd) { // 已结束,重新打开文件 afk_download_channel_param_s parm = {0}; memcpy(&parm.info, pNPI->pFileInfo, sizeof(NET_RECORDFILE_INFO)); parm.nByTime = 0; parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; int r = pNPI->channel->set_info(pNPI->channel, 1, (void*)(&parm)); if (r == 0) { nRet = NET_NETWORK_ERROR; } } pNPI->PlayBack->Pause(BUFFER_RESET); //Sleep(100); afk_download_control_param_s parm = {0}; parm.offsettime = INVALID_OFFSET_TIME; parm.offsetdata = offsetbyte; int r = pNPI->channel->set_info(pNPI->channel, 0, &parm); if (r == 0) { nRet = NET_NETWORK_ERROR; } else { pNPI->bDownLoadEnd = FALSE; if (pNPI->Render) { pNPI->Render->Reset(); } if (pNPI->PlayBack) { pNPI->PlayBack->Reset(); } pNPI->nOffsetSize = offsetbyte; pNPI->nReceiveSize = 0; nRet = 0; } pNPI->PlayBack->Resume(BUFFER_RESET); } else { nRet = NET_ILLEGAL_PARAM; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::StopPlayBack(LONG lPlayHandle) { int nRet = NET_NOERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { nRet = Process_stopplayback(*pNPI); if (nRet >= 0) { delete pNPI; m_lstNPI.remove(pNPI); nRet = NET_NOERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::StepPlayBack(LONG lPlayHandle, BOOL bStop) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->Step(bStop); if (b) { nRet = NET_NOERROR; //success } else { nRet = NET_RENDER_STEP_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::FastPlayBack(LONG lPlayHandle) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->Fast(); if (b) { nRet = NET_NOERROR; //success } else { nRet = NET_RENDER_FRAMERATE_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::SlowPlayBack(LONG lPlayHandle) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->Slow(); if (b) { nRet = NET_NOERROR; //success } else { nRet = NET_RENDER_FRAMERATE_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::NormalPlayBack(LONG lPlayHandle) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->PlayNormal(); if (b) { nRet = NET_NOERROR; //success } else { nRet = NET_RENDER_FRAMERATE_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::SetFramePlayBack(LONG lPlayHandle, int framerate) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->SetFrameRate(framerate); if (b) { nRet = NET_NOERROR; //success } else { nRet = NET_RENDER_FRAMERATE_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::GetFramePlayBack(LONG lPlayHandle, int *fileframerate, int *playframerate) { if (!fileframerate || !playframerate) { return NET_ILLEGAL_PARAM; } else { *fileframerate = -1; *playframerate = -1; } int nRet = -1; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI && pNPI->Render) { *playframerate = pNPI->Render->GetFrameRate(); *fileframerate = pNPI->channel->get_info(pNPI->channel, 0, 0); nRet = 0; } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::GetPlayBackOsdTime(LONG lPlayHandle, LPNET_TIME lpOsdTime, LPNET_TIME lpStartTime, LPNET_TIME lpEndTime) { if (!lpOsdTime || !lpStartTime || !lpEndTime) { return NET_ILLEGAL_PARAM; } else { memset(lpOsdTime,0x00,sizeof(NET_TIME)); } int nRet = -1; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { pNPI->Render->GetOSDTime(&lpOsdTime->dwYear, &lpOsdTime->dwMonth, &lpOsdTime->dwDay, &lpOsdTime->dwHour, &lpOsdTime->dwMinute, &lpOsdTime->dwSecond); *lpStartTime = pNPI->timeStart; *lpEndTime = pNPI->timeEnd; nRet = 0; } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int __stdcall DownLoadRecordFunc( afk_handle_t object, /* 数据提供者 */ unsigned char *data, /* 数据体 */ unsigned int datalen, /* 数据长度 */ void *param, /* 回调参数 */ void *udata ) { afk_channel_s *channel = (afk_channel_s*)object; if (!channel) { return -1; } st_DownLoad_Info* pDLI = (st_DownLoad_Info*)udata; if (!pDLI) { return -1; } if (pDLI->file) { if (datalen != -1) { if (data) { if (0 == fwrite(data, datalen, 1, pDLI->file)) { #ifdef WIN32 if (ERROR_DISK_FULL == GetLastError()) #else //linux #endif { if (pDLI->prf) { if (pDLI->pTimeDownLoadPosCallBack) { pDLI->pTimeDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, -2, pDLI->ncurrf, *(pDLI->prf+pDLI->ncurrf), pDLI->userdata); } } else { if (pDLI->pDownLoadPosCallBack) { pDLI->pDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, -2, pDLI->userdata); } } } } pDLI->fileflushflag++; if (pDLI->fileflushflag%40 == 0) { fflush(pDLI->file); } pDLI->nDownLoadSize += datalen; if (pDLI->prf) { if (pDLI->pTimeDownLoadPosCallBack) { pDLI->pTimeDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, pDLI->nDownLoadSize/1024, pDLI->ncurrf, *(pDLI->prf+pDLI->ncurrf), pDLI->userdata); } } else { if (pDLI->pDownLoadPosCallBack) { pDLI->pDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, pDLI->nDownLoadSize/1024, pDLI->userdata); } } } } else { pDLI->ncurrf++; if (pDLI->prf && (pDLI->ncurrf < pDLI->nrflen)) { NET_RECORDFILE_INFO* p = pDLI->prf+pDLI->ncurrf; afk_download_channel_param_s parm = {0}; memcpy(&parm.info, pDLI->prf+pDLI->ncurrf, sizeof(NET_RECORDFILE_INFO)); parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; parm.nByTime = 1; channel->set_info(channel, 1, (void*)(&parm)); } else { fclose(pDLI->file); pDLI->file = 0; pDLI->nDownLoadSize = -1; if (pDLI->prf) { if (pDLI->pTimeDownLoadPosCallBack) { pDLI->pTimeDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, -1, pDLI->ncurrf, *(pDLI->prf+pDLI->ncurrf), pDLI->userdata); } } else { if (pDLI->pDownLoadPosCallBack) { #ifdef _DEBUG OutputDebugString("CLIENT_DownloadByRecordFile: end!\n"); #endif pDLI->pDownLoadPosCallBack((LONG)channel, pDLI->nTotalSize, -1, pDLI->userdata); } } } } }//end of if (pDLI->file) return 1; } LONG CSearchRecordAndPlayBack::DownloadByRecordFile(LONG lLoginID,LPNET_RECORDFILE_INFO lpRecordFile, char *sSavedFileName, fDownLoadPosCallBack cbDownLoadPos, DWORD dwUserData) { if (!lpRecordFile || !sSavedFileName) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_DOWNLOAD; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, lpRecordFile->ch, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } afk_device_s *device = (afk_device_s*)lLoginID; afk_channel_s *channel = 0; st_DownLoad_Info* pDLI = new st_DownLoad_Info; if (!pDLI) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } pDLI->channel = 0; pDLI->channelid = lpRecordFile->ch; pDLI->file = fopen(sSavedFileName, "wb"); if (!pDLI->file) { m_pManager->SetLastError(NET_OPEN_FILE_ERROR); goto e_clearup; } if (device->device_type(device) != NET_NB_SERIAL) { /*WriteVideoFileHeader(pDLI->file, device->device_type(device), 25, lpRecordFile->starttime.dwYear, lpRecordFile->starttime.dwMonth, lpRecordFile->starttime.dwDay, lpRecordFile->starttime.dwHour, lpRecordFile->starttime.dwMinute, lpRecordFile->starttime.dwSecond);*/ } pDLI->fileflushflag = 0; pDLI->nTotalSize = lpRecordFile->size; pDLI->nDownLoadSize = 0; pDLI->pDownLoadPosCallBack = cbDownLoadPos; pDLI->pTimeDownLoadPosCallBack = 0; pDLI->userdata = dwUserData; memset (&(pDLI->timeStart), 0 , sizeof(NET_TIME)); memset (&(pDLI->timeEnd), 0 , sizeof(NET_TIME)); pDLI->prf = 0; pDLI->nrflen = 0; pDLI->ncurrf = 0; pDLI->nConnectID = stuConnParam.nConnectID; afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = DownLoadRecordFunc; parm.base.udata = pDLI; parm.conn = stuConnParam; memcpy(&parm.info, lpRecordFile, sizeof(NET_RECORDFILE_INFO)); parm.nByTime = 0; parm.nParam = 1; //下载 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { pDLI->channel = channel; m_csDLI.Lock(); m_lstDLI.push_back(pDLI); m_csDLI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); goto e_clearup; } return (LONG)channel; e_clearup: if (pDLI) { if (pDLI->file) { fclose(pDLI->file); pDLI->file = 0; } delete pDLI; pDLI = 0; } if (channel) { channel->close(channel); channel = 0; } return 0; } st_DownLoad_Info* CSearchRecordAndPlayBack::GetDownLoadInfo(LONG lFileHandle) { st_DownLoad_Info* p = 0; list<st_DownLoad_Info*>::iterator it = find_if(m_lstDLI.begin(),m_lstDLI.end(),SearchDLIbyChannel(lFileHandle)); if (it != m_lstDLI.end()) { p = (*it); } return p; } int CSearchRecordAndPlayBack::StopDownload(LONG lFileHandle) { int nRet = -1; m_csDLI.Lock(); st_DownLoad_Info * pDLI = GetDownLoadInfo(lFileHandle); if (pDLI) { LONG lLoginID = (LONG)pDLI->channel->get_device(pDLI->channel); pDLI->channel->close(pDLI->channel); m_pManager->GetDevConfigEx().DestroySession(lLoginID, pDLI->nConnectID); if (pDLI->file) { fclose(pDLI->file); pDLI->file = 0; } pDLI->pDownLoadPosCallBack = NULL; pDLI->pTimeDownLoadPosCallBack = NULL; delete pDLI; m_lstDLI.remove(pDLI); nRet = 0; } else { nRet = NET_INVALID_HANDLE; } m_csDLI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::GetDownloadPos(LONG lFileHandle, int *nTotalSize, int *nDownLoadSize) { if (!nTotalSize || !nDownLoadSize) { return NET_ILLEGAL_PARAM; } else { *nTotalSize = 0; *nDownLoadSize = 0; } int nRet = -1; m_csDLI.Lock(); st_DownLoad_Info* pDLI = GetDownLoadInfo(lFileHandle); if (pDLI) { *nTotalSize = pDLI->nTotalSize; if (-1 == pDLI->nDownLoadSize) { *nDownLoadSize = pDLI->nTotalSize; } else { *nDownLoadSize = pDLI->nDownLoadSize / 1024; } nRet = 0; } else { nRet = NET_INVALID_HANDLE; } m_csDLI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::CapturePicture(LONG lPlayHandle, const char *pchPicFileName) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->SnapPicture(pchPicFileName); if(b) { nRet = NET_NOERROR; } else { nRet = NET_RENDER_SNAP_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::Decoder_OpenSound(LONG lPlayHandle) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI && pNPI->Render) { BOOL b = pNPI->Render->OpenAudio(); if (b) { pNPI->bAudioPlay = TRUE; nRet = NET_NOERROR; } else { nRet = NET_RENDER_SOUND_ON_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::Decoder_CloseSound() { int nRet = NET_ERROR; m_csNPI.Lock(); list<st_NetPlayBack_Info*>::iterator it = m_lstNPI.begin(); for(; it != m_lstNPI.end(); ++it) { if ((*it) && (*it)->Render && (*it)->bAudioPlay) { BOOL b = (*it)->Render->CloseAudio(); if (b) { (*it)->bAudioPlay = FALSE; nRet = NET_NOERROR; } else { nRet = NET_RENDER_SOUND_OFF_ERROR; } } } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::GetDecoderVideoEffect(LONG lPlayHandle, unsigned char *brightness, unsigned char *contrast, unsigned char *hue, unsigned char *saturation) { if (!brightness || !contrast || !hue || !saturation) { return NET_ILLEGAL_PARAM; } else { *brightness = 0; *contrast = 0; *hue = 0; *saturation = 0; } int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { pNPI->Render->GetColorParam(brightness, contrast, hue, saturation); nRet = NET_NOERROR; } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::SetDecoderVideoEffect(LONG lPlayHandle, unsigned char brightness, unsigned char contrast, unsigned char hue, unsigned char saturation) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->AdjustColor(brightness, contrast, hue, saturation); if (b) { nRet = NET_NOERROR; } else { nRet = NET_RENDER_ADJUST_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } int CSearchRecordAndPlayBack::SetVolume(LONG lPlayHandle, int nVolume) { int nRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { if (pNPI->Render) { BOOL b = pNPI->Render->SetAudioVolume(nVolume); if (b) { nRet = NET_NOERROR; } else { nRet = NET_RENDER_SET_VOLUME_ERROR; } } else { nRet = NET_SYSTEM_ERROR; } } else { nRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return nRet; } LONG CSearchRecordAndPlayBack::GetStatiscFlux(LONG lLoginID,LONG lPlayHandle) { LONG lRet = NET_ERROR; m_csNPI.Lock(); st_NetPlayBack_Info* pNPI = GetNetPlayBackInfo(lPlayHandle); if (pNPI) { afk_device_s *device = (afk_device_s*)lLoginID; afk_channel_s *stat_channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_STATISC, 0); if (stat_channel) { lRet = stat_channel->get_info(stat_channel, 0, pNPI->channel); bool b = stat_channel->close(stat_channel); if (!b) { lRet = NET_CLOSE_CHANNEL_ERROR; } } else { lRet = NET_OPEN_CHANNEL_ERROR; } } else { lRet = NET_INVALID_HANDLE; } m_csNPI.UnLock(); return lRet; } /************************************************************************ ** 释放录像文件的句柄列表 ***********************************************************************/ void CSearchRecordAndPlayBack::ReleaseAllSearchRecordInfo(void) { m_csSRI.Lock(); list<st_SearchRecord_Info*>::iterator it = m_lstSRI.begin(); for(; it != m_lstSRI.end(); ++it) { ReleaseRecordFileInfo(**it); delete (*it); } m_lstSRI.clear(); m_csSRI.UnLock(); } int CSearchRecordAndPlayBack::Process_stopplayback(st_NetPlayBack_Info& npi) { int nRet = NET_NOERROR; SetEventEx(npi.hPBExit); #ifdef WIN32 DWORD hdl = GetCurrentThreadId(); if (hdl == npi.dwThreadID) { //当前线程 } #else //linux pthread_t self = pthread_self(); if (self == npi.hThread.m_hThread) { //当前线程 } #endif else { DWORD dw = WaitForSingleObjectEx(npi.hThread, 1000*10); if (WAIT_OBJECT_0 != dw) { TerminateThreadEx(npi.hThread, 1); } } CloseThreadEx(npi.hThread); CloseEventEx(npi.hPBExit); if (npi.Render) { int ret = npi.Render->StopDec(); if (ret >= 0) { npi.Render->SetDrawCallBack(0,0,0,0); m_pManager->GetRenderManager().ReleaseRender(npi.Render); } else { nRet = NET_DEC_CLOSE_ERROR; } } if (npi.channel) { LONG lLoginID = (LONG)npi.channel->get_device(npi.channel); bool bSuccess = npi.channel->close(npi.channel); if (!bSuccess) { nRet = NET_CLOSE_CHANNEL_ERROR; } m_pManager->GetDevConfigEx().DestroySession(lLoginID, npi.nConnectID); } if (npi.PlayBack) { delete npi.PlayBack; npi.PlayBack = NULL; } if(npi.pFileInfo) { delete npi.pFileInfo; npi.pFileInfo = NULL; } if (npi.prf) { delete[] npi.prf; npi.prf = NULL; } return nRet; } LONG CSearchRecordAndPlayBack::DownloadByTime(LONG lLoginID, int nChannelId, int nRecordFileType, LPNET_TIME tmStart, LPNET_TIME tmEnd, char *sSavedFileName, fTimeDownLoadPosCallBack cbTimeDownLoadPos, DWORD dwUserData) { if (!sSavedFileName) { m_pManager->SetLastError(NET_ILLEGAL_PARAM); return 0; } if (m_pManager->IsDeviceValid((afk_device_s*)lLoginID) < 0) { m_pManager->SetLastError(NET_INVALID_HANDLE); return 0; } afk_device_s *device = (afk_device_s*)lLoginID; if (device->device_type(device) == NET_NB_SERIAL) { return NET_UNSUPPORTED; } /* 先申请建立会话 */ afk_connect_param_t stuConnParam = {0}; stuConnParam.nConnType = channel_connect_tcp; stuConnParam.nInterfaceType = INTERFACE_DOWNLOAD; int ret = m_pManager->GetDevConfigEx().SetupSession(lLoginID, nChannelId, &stuConnParam); if (ret < 0) { m_pManager->SetLastError(ret); return 0; } list<NET_RECORDFILE_INFO*> lstrf; int r = Process_QueryRecordfile(device, nChannelId, nRecordFileType, tmStart, tmEnd, 0, 3000, true, lstrf); if (r < 0) { m_pManager->SetLastError(r); return 0; } else if (lstrf.size() <= 0) { m_pManager->SetLastError(NET_NO_RECORD_FOUND); return 0; } DWORD dwTotalSize = 0; int nrflen = lstrf.size(); NET_RECORDFILE_INFO* prf = new NET_RECORDFILE_INFO[nrflen]; if (!prf) { m_pManager->SetLastError(NET_SYSTEM_ERROR); st_SearchRecord_Info sr; sr.lstrf = lstrf; ReleaseRecordFileInfo(sr); return 0; } list<NET_RECORDFILE_INFO*>::iterator it = lstrf.begin(); for(int i=0; (it!=lstrf.end())&& (i<nrflen); it++,i++) { memcpy(prf+i, *it, sizeof(NET_RECORDFILE_INFO)); dwTotalSize += prf[i].size; delete *it; } lstrf.clear(); afk_channel_s *channel = 0; st_DownLoad_Info* pDLI = new st_DownLoad_Info; if (!pDLI) { m_pManager->SetLastError(NET_SYSTEM_ERROR); goto e_clearup; } pDLI->channel = 0; pDLI->channelid = nChannelId; pDLI->file = fopen(sSavedFileName, "wb"); if (!pDLI->file) { m_pManager->SetLastError(NET_OPEN_FILE_ERROR); goto e_clearup; } // WriteVideoFileHeader(pDLI->file, device->device_type(device), 25, // tmStart->dwYear, // tmStart->dwMonth, // tmStart->dwDay, // tmStart->dwHour, // tmStart->dwMinute, // tmStart->dwSecond); pDLI->fileflushflag = 0; pDLI->nTotalSize = dwTotalSize; pDLI->timeStart = *tmStart; pDLI->timeEnd = *tmEnd; pDLI->nDownLoadSize = 0; pDLI->pDownLoadPosCallBack = 0; pDLI->pTimeDownLoadPosCallBack = cbTimeDownLoadPos; pDLI->userdata = dwUserData; pDLI->prf = prf; pDLI->nrflen = nrflen; pDLI->ncurrf = 0; pDLI->nConnectID = stuConnParam.nConnectID; afk_download_channel_param_s parm; memset(&parm, 0, sizeof(afk_download_channel_param_s)); parm.base.func = DownLoadRecordFunc; parm.base.udata = pDLI; parm.conn = stuConnParam; memcpy(&parm.info, prf, sizeof(NET_RECORDFILE_INFO)); parm.nByTime = 1; parm.nParam = 1; //下载 parm.type = AFK_CHANNEL_DOWNLOAD_RECORD; channel = (afk_channel_s*)device->open_channel(device, AFK_CHANNEL_TYPE_DOWNLOAD, &parm); if (channel) { pDLI->channel = channel; m_csDLI.Lock(); m_lstDLI.push_back(pDLI); m_csDLI.UnLock(); } else { m_pManager->SetLastError(NET_OPEN_CHANNEL_ERROR); #ifdef DEBUG OutputDebugString("open channel failed"); #endif goto e_clearup; } return (LONG)channel; e_clearup: if (prf) { delete[] prf; prf = 0; } if (pDLI) { if (pDLI->file) { fclose(pDLI->file); pDLI->file = 0; } delete pDLI; pDLI = 0; } if (channel) { channel->close(channel); channel = 0; } return 0; }
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd
4fa3eafebfe7bf74a371e44a6ea558799745334b
6819e4b132193fdedf0242a48ce6b96e9d41716e
/PresentMon/PresentMon.hpp
b41e8c667cad8c469ef14d18021647cb8d21aa9a
[ "MIT" ]
permissive
PCPartPicker/PresentMon
9c70e933b1898d421d952e9810dc05c5d9b67021
c0f05bf6a2d68b22738b1856654efa65370a27f7
refs/heads/master
2021-07-07T22:59:52.140949
2019-09-27T22:03:15
2019-10-02T14:35:43
140,736,709
0
0
null
2018-07-12T16:09:58
2018-07-12T16:09:57
null
UTF-8
C++
false
false
5,280
hpp
/* Copyright 2017-2019 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once /* ETW Architecture: Controller -----> Trace Session <----- Providers (e.g., DXGI, D3D9, DXGK, DWM, Win32K) | \-------------> Consumers (e.g., ../PresentData/PresentMonTraceConsumer) PresentMon Architecture: MainThread: starts and stops the trace session and coordinates user interaction. ConsumerThread: is controlled by the trace session, and collects and analyzes ETW events. OutputThread: is controlled by the trace session, and outputs analyzed events to the CSV and/or console. The trace session and ETW analysis is always running, but whether or not collected data is written to the CSV file(s) is controlled by a recording state which is controlled from MainThread based on user input or timer. */ #include "../PresentData/MixedRealityTraceConsumer.hpp" #include "../PresentData/PresentMonTraceConsumer.hpp" #include <unordered_map> enum class Verbosity { Simple, Normal, Verbose }; enum class ConsoleOutput { None, Simple, Full }; struct CommandLineArgs { std::vector<const char*> mTargetProcessNames; std::vector<const char*> mExcludeProcessNames; const char *mOutputCsvFileName; const char *mEtlFileName; const char *mSessionName; UINT mTargetPid; UINT mDelay; UINT mTimer; UINT mHotkeyModifiers; UINT mHotkeyVirtualKeyCode; ConsoleOutput mConsoleOutputType; Verbosity mVerbosity; bool mOutputCsvToFile; bool mOutputCsvToStdout; bool mOutputQpcTime; bool mAbsoluteTime; bool mScrollLockIndicator; bool mExcludeDropped; bool mTerminateOnProcExit; bool mTerminateAfterTimer; bool mHotkeySupport; bool mTryToElevate; bool mIncludeWindowsMixedReality; bool mMultiCsv; bool mStopExistingSession; bool mSimpleExit; }; // CSV output only requires last presented/displayed event to compute frame // information, but if outputing to the console we maintain a longer history of // presents to compute averages, limited to 120 events (2 seconds @ 60Hz) to // reduce memory/compute overhead. struct SwapChainData { enum { PRESENT_HISTORY_MAX_COUNT = 120 }; std::shared_ptr<PresentEvent> mPresentHistory[PRESENT_HISTORY_MAX_COUNT]; uint32_t mPresentHistoryCount; uint32_t mNextPresentIndex; uint32_t mLastDisplayedPresentIndex; }; struct OutputCsv { FILE* mFile; FILE* mWmrFile; }; struct ProcessInfo { std::string mModuleName; std::unordered_map<uint64_t, SwapChainData> mSwapChain; HANDLE mHandle; OutputCsv mOutputCsv; bool mTargetProcess; }; #include "LateStageReprojectionData.hpp" // CommandLine.cpp: bool ParseCommandLine(int argc, char** argv); CommandLineArgs const& GetCommandLineArgs(); // Console.cpp: bool InitializeConsole(); void ConsolePrint(char const* format, ...); void ConsolePrintLn(char const* format, ...); void CommitConsole(); void UpdateConsole(uint32_t processId, ProcessInfo const& processInfo); // ConsumerThread.cpp: void StartConsumerThread(TRACEHANDLE traceHandle); void WaitForConsumerThreadToExit(); // CsvOutput.cpp: void IncrementRecordingCount(); OutputCsv GetOutputCsv(ProcessInfo* processInfo); void CloseOutputCsv(ProcessInfo* processInfo); void UpdateCsv(ProcessInfo* processInfo, SwapChainData const& chain, PresentEvent const& p); const char* FinalStateToDroppedString(PresentResult res); const char* PresentModeToString(PresentMode mode); const char* RuntimeToString(Runtime rt); // MainThread.cpp: void ExitMainThread(); // OutputThread.cpp: void StartOutputThread(); void StopOutputThread(); void SetOutputRecordingState(bool record); // Privilege.cpp: void ElevatePrivilege(int argc, char** argv); // TraceSession.cpp: bool StartTraceSession(); void StopTraceSession(); void CheckLostReports(uint32_t* eventsLost, uint32_t* buffersLost); void DequeueAnalyzedInfo( std::vector<NTProcessEvent>* ntProcessEvents, std::vector<std::shared_ptr<PresentEvent>>* presents, std::vector<std::shared_ptr<LateStageReprojectionEvent>>* lsrs); double QpcDeltaToSeconds(uint64_t qpcDelta); uint64_t SecondsDeltaToQpc(double secondsDelta); double QpcToSeconds(uint64_t qpc);
[ "nick@pcpartpicker.com" ]
nick@pcpartpicker.com