blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
c5e20e7c53a4dfd23b6f064f755f65b5e118ff9c
47b48374c6823ae666599ae8af87fdbaab28bc2e
/VulkanRenderer/Application.h
34e0c9a8355fd2ef529063be7234b16f8af367fd
[]
no_license
MalcolmMcNeely/VulkanRenderer
38c166d34b39d0e988227c395818af3c269b4764
65e9a8d8b9dc9d23bb2c8e450de1afa20f13d86c
refs/heads/master
2020-03-24T11:41:16.817935
2020-02-10T22:26:53
2020-02-10T22:26:53
142,692,269
0
0
null
null
null
null
UTF-8
C++
false
false
253
h
#pragma once #include "Window/RenderWindow.h" using namespace renderer; namespace application { class Application { public: void Initialise(); void MainLoop(); void Destroy(); private: RenderWindow* pWindow; }; }
[ "malcolm.mcneely.86@gmail.com" ]
malcolm.mcneely.86@gmail.com
a095ff896cf51e8d174e540dc780aa73f92b7a48
c1b65b3ee4db1938e9bd6ee457594d2a3174b925
/EV3DF/EV3D/Lua/CreateLua.cpp
38279983b701f40b7d211f3b6343f7e249bf554c
[]
no_license
damody/geology
f4b204700d9d710d148f360f7998fb20d4a029c1
6c1f2cb7772dae7f4370317b26159c9bab52406f
refs/heads/master
2021-01-01T04:12:50.726678
2013-05-10T08:37:08
2013-05-10T08:37:08
56,484,969
0
1
null
null
null
null
UTF-8
C++
false
false
1,289
cpp
#include "CreateLua.h" void CreateLua::AddInt( std::string name, int num ) { siv.push_back(std::make_pair(name,num)); } void CreateLua::AddDouble( std::string name, double num ) { sdv.push_back(std::make_pair(name,num)); } void CreateLua::AddString( std::string name, std::string str ) { ssv.push_back(std::make_pair(name,str)); } void CreateLua::AddRawString( std::string name, std::string str ) { rsv.push_back(std::make_pair(name,str)); } void CreateLua::SaveLua( std::wstring str ) { std::ofstream fout; fout.open(str.c_str()); if (!fout.is_open()) return; for (siVector::iterator it = siv.begin();it != siv.end();it++) { fout << it->first.c_str() << "=" << it->second << std::endl; } for (sdVector::iterator it = sdv.begin();it != sdv.end();it++) { fout << it->first.c_str() << "=" << it->second << std::endl; } for (ssVector::iterator it = ssv.begin();it != ssv.end();it++) { fout << it->first.c_str() << "=\"" << it->second.c_str() << "\"" << std::endl; } for (ssVector::iterator it = rsv.begin();it != rsv.end();it++) { fout << it->first.c_str() << "=" << it->second.c_str() << std::endl; } fout.close(); } void CreateLua::clear() { siv.clear(); sdv.clear(); ssv.clear(); rsv.clear(); }
[ "t1238142000@15cd899a-37be-affb-661b-94829f8fb904" ]
t1238142000@15cd899a-37be-affb-661b-94829f8fb904
64b05ab41b7044b77d203c3e4e142a4afb77a65b
6990bebad52934990be1403a8208ca08baf9717c
/스택/외계인의 음악연주.cpp
83e96fb87564df538332bf42883391177e2e5516
[]
no_license
tmdtjq321/Algorithm
5b77e6f28e2b37e1209064f192134ef1b72f171d
3e50326faf829fdc73e45b80a7d8706e74aa4b35
refs/heads/master
2023-08-30T02:16:26.808814
2021-11-18T11:17:35
2021-11-18T11:17:35
429,399,795
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
#include<stdio.h> #include<algorithm> #include<stack> #include<string.h> using namespace std; int N, P, cnt; stack<int> v[8]; int main(){ scanf("%d%d",&N,&P); for (int i = 0; i < N; i++){ int l, m; scanf("%d%d",&l,&m); if (!v[l].empty()) { if (v[l].top() > m){ while(!v[l].empty() && v[l].top() > m){ v[l].pop(); cnt++; } if (!v[l].empty() && v[l].top() == m){ continue; } v[l].push(m); cnt++; } else if (v[l].top() == m){ continue; } else{ v[l].push(m); cnt++; } } else{ v[l].push(m); cnt++; } printf("cnt %d\n",cnt); } printf("%d",cnt); return 0; }
[ "tmdtjq32@naver.com" ]
tmdtjq32@naver.com
66f7143eb22a21d7c42afae0e6aa808d4a5fd747
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir22441/dir22442/dir26291/file26373.cpp
72ab997cc410e0e5e8046a2e5b91a99055bb8d13
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file26373 #error "macro file26373 must be defined" #endif static const char* file26373String = "file26373";
[ "tgeng@google.com" ]
tgeng@google.com
9c18340411037be1280d0edb82ea8b0d83a479ad
778b2ac29ac51523cc26a09ac9b358d2cfcaf3b7
/algorithm/POJ/POJ1949 Chores.cpp
4af56dfc600c9f3ce9ca51b9c845852c65c74daf
[]
no_license
YurieCo/Cookie
e0a5bf77f64843335ec81ad417dd9e518ebb582c
7ad5fa52591ce4a88a45bae291be725649474370
refs/heads/master
2021-01-16T23:06:18.712626
2014-08-16T12:44:09
2014-08-16T12:44:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
507
cpp
#include <cstdio> #include <cstring> static const int MAXN = 10005; int n, m, k, t, a, b, dp[MAXN]; int max(int x, int y) { return x>y?x:y; } int main(int argc, char *argv[]) { scanf("%d",&n); a = 0; for(int i=1;i<=n;++i) { m = 0; scanf("%d%d",&t,&k); while(k--) { scanf("%d",&b); m = max(m, dp[b]); } dp[i] = m + t; a = max(a, dp[i]); } printf("%d\n",a); return 0; }
[ "CyberZHG@gmail.com" ]
CyberZHG@gmail.com
e2d819cf246e3ce944def3cc48aaa69110d28849
adb18af7cdeaf4e949738dda04b870a3ca35458b
/OMEdit/OMEditGUI/Debugger/DebuggerMainWindow.h
6de299f5417c09882c1b9c2afa1b1133c4b84a9b
[]
no_license
rfranke/OMEdit
53b37c5713e7907189edd154d4435ede5b12b24d
104cbca7b6c92b36dcd4c7aa89add0203d1bc6de
refs/heads/master
2020-04-05T23:16:00.673608
2016-02-10T16:46:07
2016-02-10T16:46:07
51,476,755
0
0
null
2016-02-10T22:19:19
2016-02-10T22:19:18
null
UTF-8
C++
false
false
6,113
h
/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC), * c/o Linköpings universitet, Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR * THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE * OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from OSMC, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * * @author Adeel Asghar <adeel.asghar@liu.se> * * RCS: $Id: DebuggerMainWindow.h 22009 2014-08-26 23:13:38Z hudson $ * */ #ifndef DEBUGGERMAINWINDOW_H #define DEBUGGERMAINWINDOW_H #include <QSettings> #include "MainWindow.h" #include "GDBAdapter.h" #include "StackFramesWidget.h" #include "LocalsWidget.h" #include "BreakpointsWidget.h" #include "Utilities.h" #include "DebuggerSourceEditor.h" #include "ProcessListModel.h" class GDBAdapter; class StackFramesWidget; class LocalsWidget; class BreakpointsWidget; class GDBLoggerWidget; class TargetOutputWidget; class DebuggerConfigurationsDialog; class DebuggerSourceEditor; class InfoBar; class DebuggerMainWindow : public QMainWindow { Q_OBJECT public: DebuggerMainWindow(MainWindow *pMainWindow = 0); void restoreWindows(); void closeEvent(QCloseEvent *event); void readFileAndNavigateToLine(QString fileName, QString lineNumber); MainWindow* getMainWindow() {return mpMainWindow;} GDBAdapter* getGDBAdapter() {return mpGDBAdapter;} StackFramesWidget* getStackFramesWidget() {return mpStackFramesWidget;} LocalsWidget* getLocalsWidget() {return mpLocalsWidget;} BreakpointsWidget* getBreakpointsWidget() {return mpBreakpointsWidget;} GDBLoggerWidget* getGDBLoggerWidget() {return mpGDBLoggerWidget;} TargetOutputWidget *getTargetOutputWidget() {return mpTargetOutputWidget;} Label* getDebuggerSourceEditorFileLabel() {return mpDebuggerSourceEditorFileLabel;} InfoBar* getDebuggerSourceEditorInfoBar() {return mpDebuggerSourceEditorInfoBar;} DebuggerSourceEditor* getDebuggerSourceEditor() {return mpDebuggerSourceEditor;} private: void createActions(); void createMenus(); MainWindow *mpMainWindow; GDBAdapter *mpGDBAdapter; StackFramesWidget *mpStackFramesWidget; QDockWidget *mpStackFramesDockWidget; BreakpointsWidget *mpBreakpointsWidget; QDockWidget *mpBreakpointsDockWidget; LocalsWidget *mpLocalsWidget; QDockWidget *mpLocalsDockWidget; GDBLoggerWidget *mpGDBLoggerWidget; QDockWidget *mpGDBLoggerDockWidget; TargetOutputWidget *mpTargetOutputWidget; QDockWidget *mpTargetOutputDockWidget; Label *mpDebuggerSourceEditorFileLabel; InfoBar *mpDebuggerSourceEditorInfoBar; DebuggerSourceEditor *mpDebuggerSourceEditor; QAction *mpDebugConfigurationsAction; QAction *mpAttachDebuggerToRunningProcessAction; public slots: void handleGDBProcessFinished(); void showConfigureDialog(); void showAttachToProcessDialog(); }; class DebuggerConfigurationPage : public QWidget { Q_OBJECT private: DebuggerConfiguration mDebuggerConfiguration; QListWidgetItem *mpConfigurationListWidgetItem; DebuggerConfigurationsDialog *mpDebuggerConfigurationsDialog; Label *mpNameLabel; QLineEdit *mpNameTextBox; Label *mpProgramLabel; QLineEdit *mpProgramTextBox; QPushButton *mpProgramBrowseButton; Label *mpWorkingDirectoryLabel; QLineEdit *mpWorkingDirectoryTextBox; QPushButton *mpWorkingDirectoryBrowseButton; Label *mpGDBPathLabel; QLineEdit *mpGDBPathTextBox; QPushButton *mpGDBPathBrowseButton; Label *mpArgumentsLabel; QPlainTextEdit *mpArgumentsTextBox; QPushButton *mpApplyButton; QPushButton *mpResetButton; QDialogButtonBox *mpButtonBox; public: DebuggerConfigurationPage(DebuggerConfiguration debuggerConfiguration, QListWidgetItem *pListWidgetItem, DebuggerConfigurationsDialog *pDebuggerConfigurationsDialog); DebuggerConfiguration getDebuggerConfiguration() {return mDebuggerConfiguration;} bool configurationExists(QString configurationKeyToCheck); public slots: void browseProgramFile(); void browseWorkingDirectory(); void browseGDBPath(); bool saveDebugConfiguration(); void resetDebugConfiguration(); }; class DebuggerConfigurationsDialog : public QDialog { Q_OBJECT public: enum { MaxDebugConfigurations = 10 }; DebuggerConfigurationsDialog(DebuggerMainWindow *pDebuggerMainWindow); QString getUniqueName(QString name = QString("New_configuration"), int number = 1); void readConfigurations(); private: DebuggerMainWindow *mpDebuggerMainWindow; QAction *mpNewConfigurationAction; QAction *mpRemoveConfigurationAction; QToolButton *mpNewToolButton; QToolButton *mpDeleteToolButton; QStatusBar *mpStatusBar; QListWidget *mpConfigurationsListWidget; QStackedWidget *mpConfigurationPagesWidget; QSplitter *mpConfigurationsSplitter; QPushButton *mpSaveButton; QPushButton *mpSaveAndDebugButton; QPushButton *mpCancelButton; QDialogButtonBox *mpConfigurationsButtonBox; bool saveAllConfigurationsHelper(); public slots: void newConfiguration(); void removeConfiguration(); void changeConfigurationPage(QListWidgetItem *current, QListWidgetItem *previous); void saveAllConfigurations(); void saveAllConfigurationsAndDebugConfiguration(); }; #endif // DEBUGGERMAINWINDOW_H
[ "martin.sjolund@liu.se" ]
martin.sjolund@liu.se
b4937539f206077cc7b8a91d59658daa36cee20c
b56a4a115b24c95877d7b11a84f4292df0bfc10b
/CodeBall/RandomGenerators.h
c82371088eca0c42651338b9323df7d49241af34
[]
no_license
tyamgin/AiCup
fd020f8b74b37b97c3a91b67ba1781585e0dcb56
5a7a7ec15d99da52b1c7a7de77f6a7ca22356903
refs/heads/master
2020-03-30T06:00:59.997652
2020-01-16T09:10:57
2020-01-16T09:10:57
15,261,033
16
8
null
null
null
null
UTF-8
C++
false
false
856
h
#ifndef CODEBALL_RANDOMGENERATORS_H #define CODEBALL_RANDOMGENERATORS_H class RandomGenerator { public: enum Mode { DummyMean, Simple }; Mode mode; double randDouble() { if (mode == DummyMean) { return 0.5; } if (mode == Simple) { // https://ru.wikipedia.org/wiki/Линейный_конгруэнтный_метод seed = 1103515245u * seed + 12345u; return ((seed >> 16) & 0x7FFF) / (0x7FFF + 0.0); } return 0.0; } double randDouble(double min, double max) { auto rnd = randDouble(); return rnd * (max - min) + min; } explicit RandomGenerator(Mode mode = DummyMean, uint32_t seed = 2707) : mode(mode), seed(seed) { } protected: uint32_t seed; }; #endif //CODEBALL_RANDOMGENERATORS_H
[ "tyamgin@gmail.com" ]
tyamgin@gmail.com
d20c7b8c86dabea939ea84e1d23b3337264f1844
04d147a936e25536937d43054c6dd3502e1e8c2a
/include/Renderable.h
f155e7f3d1e36caf564a943f3936701e305a8368
[]
no_license
Visse/dv1542_project
13e06b6245b647226599285ccc00a39060d03455
ad2aece70a78a5dec83fc3456a8b0faeefc099ee
refs/heads/master
2016-09-06T08:12:42.637948
2015-04-11T10:58:58
2015-04-11T10:58:58
30,210,427
0
0
null
null
null
null
UTF-8
C++
false
false
150
h
#pragma once class Renderer; class Renderable { public: virtual ~Renderable() = default; virtual void render( Renderer &renderer ) = 0; };
[ "visse44@gmail.com" ]
visse44@gmail.com
02c2d193427c9ecc70369f6637e5704973ba8141
f0280623b3b6cd80fa3a1102bf911e5cc736cc2b
/QtRptProject/QtRptDesigner/tmp-win32/moc_PageSettingDlg.cpp
115c3aa02a74d8ab6daa75739c9625d78a64eeb6
[]
no_license
xman199775/jeanscar
1aea4dd5b35bab07462e2af3dfc98ee7813720fa
1170c165ad0d6e50829d3d5db618406326a83c51
refs/heads/master
2021-05-05T06:09:14.336541
2018-06-25T12:49:52
2018-06-25T12:49:52
113,491,136
0
0
null
null
null
null
UTF-8
C++
false
false
3,913
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'PageSettingDlg.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../PageSettingDlg.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'PageSettingDlg.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.8.0. 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_PageSettingDlg_t { QByteArrayData data[6]; char stringdata0[68]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PageSettingDlg_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PageSettingDlg_t qt_meta_stringdata_PageSettingDlg = { { QT_MOC_LITERAL(0, 0, 14), // "PageSettingDlg" QT_MOC_LITERAL(1, 15, 17), // "changeOrientation" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 15), // "pageSizeChanged" QT_MOC_LITERAL(4, 50, 5), // "index" QT_MOC_LITERAL(5, 56, 11) // "selectColor" }, "PageSettingDlg\0changeOrientation\0\0" "pageSizeChanged\0index\0selectColor" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PageSettingDlg[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 29, 2, 0x08 /* Private */, 3, 1, 30, 2, 0x08 /* Private */, 5, 0, 33, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Int, 4, QMetaType::Void, 0 // eod }; void PageSettingDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { PageSettingDlg *_t = static_cast<PageSettingDlg *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->changeOrientation(); break; case 1: _t->pageSizeChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->selectColor(); break; default: ; } } } const QMetaObject PageSettingDlg::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_PageSettingDlg.data, qt_meta_data_PageSettingDlg, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *PageSettingDlg::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PageSettingDlg::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_PageSettingDlg.stringdata0)) return static_cast<void*>(const_cast< PageSettingDlg*>(this)); return QDialog::qt_metacast(_clname); } int PageSettingDlg::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 < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "xman199775@gmail.com" ]
xman199775@gmail.com
dd4e2141769a6d4cad3c22380b689d9679d8e845
53733f73b922407a958bebde5e674ec7f045d1ba
/VIR/0907am/arc031_2/main0.cpp
624b89d67164aeb0e32d42cd7a9613f4f666fc46
[]
no_license
makio93/atcoder
040c3982e5e867b00a0d0c34b2a918dd15e95796
694a3fd87b065049f01f7a3beb856f8260645d94
refs/heads/master
2021-07-23T06:22:59.674242
2021-03-31T02:25:55
2021-03-31T02:25:55
245,409,583
0
0
null
null
null
null
UTF-8
C++
false
false
1,999
cpp
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; #define ull unsigned long long #define ld long double #define vi vector<int> #define vll vector<ll> #define vc vector<char> #define vs vector<string> #define vpii vector<pii> #define vpll vector<pll> #define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; i++) #define rep1(i, n) for (int i = 1, i##_len = (n); i <= i##_len; i++) #define repr(i, n) for (int i = ((int)(n)-1); i >= 0; i--) #define rep1r(i, n) for (int i = ((int)(n)); i >= 1; i--) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define SORT(v, n) sort(v, v + n); #define VSORT(v) sort(v.begin(), v.end()); #define RSORT(x) sort(rall(x)); #define pb push_back #define mp make_pair #define INF (1e9) #define PI (acos(-1)) #define EPS (1e-7) ull gcd(ull a, ull b) { return b ? gcd(b, a % b) : a; } ull lcm(ull a, ull b) { return a / gcd(a, b) * b; } const string YES = "YES"; const string NO = "NO"; int main(){ vs a(10); rep(i, 10) cin >> a[i]; bool ans = false; rep(i, 10) rep(j, 10) { vs a2 = a; a2[i][j] = 'o'; queue<pii> q; q.emplace(i, j); a2[i][j] = '.'; while (!q.empty()) { auto p = q.front(); q.pop(); int y = p.first, x = p.second; const vi dy = { -1, 0, 1, 0 }, dx = { 0, 1, 0, -1 }; rep(i2, 4) { int ny = y + dy[i2], nx = x + dx[i2]; if (ny<0||ny>=10||nx<0||nx>=10) continue; if (a2[ny][nx] != 'o') continue; q.emplace(ny, nx); a2[ny][nx] = '.'; } } bool ok = true; rep(i2, 10) rep(j2, 10) { if (a2[i2][j2] == 'o') ok = false; } if (ok) ans = true; } if (ans) cout << YES << endl; else cout << NO << endl; return 0; }
[ "mergon-nitro-pale_fluorelight@hotmail.co.jp" ]
mergon-nitro-pale_fluorelight@hotmail.co.jp
0f9fe8a624659b4f0e5371ce533ef514838a0ed0
c0eda57487fa0f6324534a647951a364b8af2203
/renderer/cbuffer_structs.hpp
6726a7d0600287b021631b41ffc1b3ad55bf2bc7
[]
no_license
tuccio/fuse
6e8a9ef07faf9f6a6d04d821b4dc4e7c2ee8db59
9cf7a7c66290443fb040816a08fc65cbac1ddc08
refs/heads/master
2021-01-19T02:58:39.010535
2016-07-18T16:09:26
2016-07-18T16:09:26
48,071,253
4
0
null
null
null
null
UTF-8
C++
false
false
1,483
hpp
#pragma once #include <fuse/math.hpp> namespace fuse { struct cb_camera { float3 position; float fovy; float aspectRatio; float znear; float zfar; float __fill0; mat128 view; mat128 projection; mat128 viewProjection; mat128 invViewProjection; }; struct cb_screen { uint2 resolution; uint32_t __fill0[2]; mat128 orthoProjection; }; struct cb_render_variables { uint32_t shadowMapResolution; float vsmMinVariance; float vsmMinBleeding; float evsm2MinVariance; float evsm2MinBleeding; float evsm2Exponent; float evsm4MinVariance; float evsm4MinBleeding; float evsm4PosExponent; float evsm4NegExponent; //float __fill0[1]; }; struct cb_material { float3 baseColor; float metallic; float roughness; float specular; float __fill[2]; }; struct cb_transform { mat128 world; mat128 worldView; mat128 worldViewProjection; }; struct cb_light { uint32_t type; uint32_t castShadows; uint32_t __fill0[2]; float3 luminance; float __fill1; float3 ambient; float __fill2; float3 position; float __fill3; float3 direction; float spotAngle; }; struct cb_shadowmapping { mat128 lightMatrix; }; struct cb_per_frame { cb_camera camera; cb_screen screen; cb_render_variables rvars; }; struct cb_per_object { cb_transform transform; cb_material material; }; struct cb_per_light { cb_light light; cb_shadowmapping shadowMapping; }; }
[ "d.tuccilli@gmail.com" ]
d.tuccilli@gmail.com
ce2d2069893a6cc0eb5372d452865c95128e3c06
293c98e7b16b45853b17d1113691f0e8b1dfa2af
/cpp03/ex04/SuperTrap.hpp
493e602cd80558f8ec92964421f1ce0a6c80c121
[]
no_license
Mia-Cross/modules_cpp
b7476977ab8c1c449c033a459cbda1685afefca3
a1f03d8367fee7302e04dcc0e442834ce2fb0378
refs/heads/master
2023-03-01T07:52:02.753406
2021-02-03T22:11:40
2021-02-03T22:11:40
314,326,689
0
0
null
null
null
null
UTF-8
C++
false
false
623
hpp
#ifndef SUPERTRAP_CLASS_H # define SUPERTRAP_CLASS_H # include "NinjaTrap.hpp" class SuperTrap : public virtual FragTrap, public virtual NinjaTrap { public: SuperTrap(); //constructeur par defaut SuperTrap(std::string name); ~SuperTrap(); //destructeur par defaut SuperTrap(SuperTrap const &src); //constructeur par copie SuperTrap &operator=(SuperTrap const &that); //surcharge d'operateur d'assignation void rangedAttack(std::string const &target); void meleeAttack(std::string const &target); }; #endif
[ "leila.marabese@gmail.com" ]
leila.marabese@gmail.com
099f117a36383dfe42ed5e932ecf793181ee51e0
b4376de7e9dd92cb9de2b73d430ae9196bc6b526
/src/main.cpp
481fde3b6ef4c069be6988b6748b62bbbc96056e
[]
no_license
Sunlight4/X-Bit-Old
2190c65f4fdb4950bdd8ab9eda5b8f7cad2bc620
de4477cef5c9b55f2c0906dd5a006a15fea20fa6
refs/heads/master
2022-05-29T10:34:39.854039
2020-04-30T15:15:06
2020-04-30T15:15:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
/* main.cpp - created on Apr 29, 2020 */ #include "CentralManager.h" int main (int argc, char* args[]) { CentralManager* manager = new CentralManager(); manager->Initialize(); while (manager->Update()); manager->End(); }
[ "ethan.saff@gmail.com" ]
ethan.saff@gmail.com
1473790e7f934a707539b0d29c3c0cdb2e7e8eea
a73a90d3bf9191c67b8c8079b7521f6b75258dab
/p40/project_euler40.cpp
b8a9702c8d61a784cb3a8b5d7a66771a5af4e512
[]
no_license
afluriach/project_euler
75dbd102b104c2b012223350932e6704e82025d2
46ab194707d4888172a7c641ba017401a6f2a4b0
refs/heads/master
2020-03-21T07:56:05.280871
2018-06-22T14:06:12
2018-06-22T14:06:12
138,309,087
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
// project_euler40.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; char buf[2000000]; int _tmain(int argc, _TCHAR* argv[]) { char * pos = buf; for(int i=1; (pos - buf) <= 1000000; ++i) { pos += sprintf(pos, "%d", i); } long result = (buf[0] - '0') * (buf[9] - '0') * (buf[99]- '0') * (buf[999]- '0') * (buf[9999]- '0') * (buf[99999]- '0') * (buf[999999]- '0'); cout << result << endl; system("PAUSE"); return 0; }
[ "afluriach@gmail.com" ]
afluriach@gmail.com
d8fd438d5ae4ac91c4c682ccc73fed1d6d436e87
e31e549a9e3baeded36b61675b458f34e08c64e2
/demos/auth/client.cpp
424a43eb65bbc3c3d68ce874bdac3d76abdd1359
[]
no_license
ztenv/zeromq_demo
e669f1c1232a09b51ca2dbb99e48ecc7bd6a4b36
519049256a67919bd921de577b94ff9d38226c12
refs/heads/main
2023-04-08T12:29:51.652133
2021-04-23T15:48:20
2021-04-23T15:48:20
309,614,058
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
#include <chrono> #include <iostream> #include <sstream> #include <string> #include <array> #include <thread> #include <cstring> #include <zmq.h> using namespace std; int main() { void *context = zmq_ctx_new(); void *requester = zmq_socket(context, ZMQ_REQ); const char *name = "admin"; const char *pwd = "pwd"; auto rc = zmq_setsockopt(requester, ZMQ_PLAIN_USERNAME, name, strlen(name)); cout << "rc=" << rc <<endl; rc = zmq_setsockopt(requester, ZMQ_PLAIN_PASSWORD, pwd, strlen(pwd)); cout << "rc=" << rc <<endl; const char *id = "auth_request"; rc = zmq_setsockopt(requester, ZMQ_ROUTING_ID, id, strlen(id)); cout << "rc=" << rc <<endl; rc = zmq_connect(requester, "tcp://127.0.0.1:55555"); cout << "rc=" << rc <<endl; cout << "start to send msg" <<endl; for(int i = 0; i<1000000000; ++i) { ostringstream oss; oss << i; auto res = zmq_send(requester, oss.str().c_str(), oss.str().length(), 0); cout << "send:" << oss.str() << endl; std::array<char, 1024> buf; memset(buf.data(), 0, buf.max_size()); res = zmq_recv(requester, buf.data(), buf.max_size(), 0); cout << "recv:" << buf.data() <<endl; } return 0; }
[ "class7class@163.com" ]
class7class@163.com
19d5a47c1379869d79143b2908947dddd544a5c6
fddffa4722dce69c2b81205776cf380943ebfc50
/Tracker/HTTPTracker.hpp
32390ce44a23edb175e9364e0a7255a376dbf392
[]
no_license
bonaert/torrent
1efc3b8e9f177e581db66daf1e571208d8e94149
6860be576ca432b6c82d972a7f4c7a30457d1a95
refs/heads/master
2022-04-11T10:38:25.874391
2020-02-22T23:57:47
2020-02-22T23:57:47
86,988,018
6
0
null
null
null
null
UTF-8
C++
false
false
2,449
hpp
#ifndef TORRENT_HTTPTRACKER_HPP #define TORRENT_HTTPTRACKER_HPP #include <string> #include <vector> #include "Tracker.hpp" #include "../BEncode.hpp" class HTTPTracker : public Tracker { private: std::string announceUrl; bool sendRequest(std::string url); bool sendGetPeersRequest(); bool sendGetPeersRequest(const std::string &event); bool getResponseFromTracker(); void processGetPeersResponseFromTracker(const std::string &response); public: HTTPTracker(TrackerMaster *trackerMaster, const std::string &announceURL); void updatePeers() override; }; /* * TRACKER HTTP REQUEST (LEGACY) */ class TrackerRequest { private: std::string requestString; bool addedFirstParameter; void addKeyInRequest(const std::string &key); void addKeyValuePairInRequest(const std::string &key, const std::string &value); void addUrlEncodedKeyInRequest(const std::string &key); void addUrlEncodedKeyValuePairInRequest(const std::string &key, const std::string &value); public: TrackerRequest(std::string announceUrl); TrackerRequest &addInfoHash(const std::string &infoHash); TrackerRequest &addPeerID(const std::string &peerID); TrackerRequest &addPort(int port); TrackerRequest &addUploadedBytes(int uploadedBytes); TrackerRequest &addDownloadedBytes(int downloadedBytes); TrackerRequest &addBytesLeft(int bytesLeft); TrackerRequest &addAcceptsCompactResponseFlag(bool compactFlag); TrackerRequest &addNoPeerIDFlag(); TrackerRequest &addEvent(const std::string &event); TrackerRequest &addIP(const std::string &ip); TrackerRequest &addNumberPeersWanted(int numPeersWanted); TrackerRequest &addKey(const std::string &key); TrackerRequest &addTrackerID(const std::string &trackerID); const std::string &getRequestURL(); }; typedef struct Peer { std::string peerID; std::string ip; int port; } Peer; class TrackerResponse { private: void parseResponse(const BDictionary &response); public: bool failed; std::string failureReason; std::string warning; int intervalBetweenRequests; int minimumIntervalBetweenRequests = -1; std::string trackerID; int numSeeders; int numLeechers; std::vector<Peer> peers; TrackerResponse(const BDictionary &response); }; TrackerResponse *buildTrackerResponse(const std::string &response); #endif //TORRENT_HTTPTRACKER_HPP
[ "harokb@gmail.com" ]
harokb@gmail.com
c0f1f66e67b65f393ac04540c904fb34366506e1
49655d8700ba66e87c74da65de70b56221d1795f
/src/client/mapview.h
5a56aa338aed3c4f7f8fb04ff9eaa07aeb273150
[ "MIT" ]
permissive
totolol123/TheImaginedOTClient
d1d6e2270a6cda70c739a48c4bcb210087196dcc
9fd31ce1af5603211c7fe3ce4e3ccb0ecaf3cda8
refs/heads/master
2020-07-14T15:23:44.600054
2014-04-18T22:38:53
2014-04-18T22:38:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,987
h
/* * Copyright (c) 2010-2013 OTClient <https://github.com/edubart/otclient> * * 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. */ #ifndef MAPVIEW_H #define MAPVIEW_H #include "declarations.h" #include <framework/graphics/paintershaderprogram.h> #include <framework/graphics/declarations.h> #include <framework/luaengine/luaobject.h> #include <framework/core/declarations.h> #include "lightview.h" // @bindclass class MapView : public LuaObject { public: enum ViewMode { NEAR_VIEW, MID_VIEW, FAR_VIEW, HUGE_VIEW }; MapView(); ~MapView(); void draw(const Rect& rect); private: void updateGeometry(const Size& visibleDimension, const Size& optimizedSize); void updateVisibleTilesCache(int start = 0); void requestVisibleTilesCacheUpdate() { m_mustUpdateVisibleTilesCache = true; } protected: void onTileUpdate(const Position& pos); void onMapCenterChange(const Position& pos); friend class Map; public: // floor visibility related void lockFirstVisibleFloor(int firstVisibleFloor); void unlockFirstVisibleFloor(); int getLockedFirstVisibleFloor() { return m_lockedFirstVisibleFloor; } void setMultifloor(bool enable) { m_multifloor = enable; requestVisibleTilesCacheUpdate(); } bool isMultifloor() { return m_multifloor; } // map dimension related void setVisibleDimension(const Size& visibleDimension); Size getVisibleDimension() { return m_visibleDimension; } int getTileSize() { return m_tileSize; } Point getVisibleCenterOffset() { return m_visibleCenterOffset; } int getCachedFirstVisibleFloor() { return m_cachedFirstVisibleFloor; } int getCachedLastVisibleFloor() { return m_cachedLastVisibleFloor; } // view mode related void setViewMode(ViewMode viewMode); ViewMode getViewMode() { return m_viewMode; } void optimizeForSize(const Size& visibleSize); void setAutoViewMode(bool enable); bool isAutoViewModeEnabled() { return m_autoViewMode; } // camera related void followCreature(const CreaturePtr& creature); CreaturePtr getFollowingCreature() { return m_followingCreature; } bool isFollowingCreature() { return m_followingCreature && m_follow; } void setCameraPosition(const Position& pos); Position getCameraPosition(); void setMinimumAmbientLight(float intensity) { m_minimumAmbientLight = intensity; } float getMinimumAmbientLight() { return 0; } // drawing related void setDrawFlags(Otc::DrawFlags drawFlags) { m_drawFlags = drawFlags; requestVisibleTilesCacheUpdate(); } Otc::DrawFlags getDrawFlags() { return m_drawFlags; } void setDrawTexts(bool enable) { m_drawTexts = enable; } bool isDrawingTexts() { return m_drawTexts; } void setDrawNames(bool enable) { m_drawNames = enable; } bool isDrawingNames() { return m_drawNames; } void setDrawHealthBars(bool enable) { m_drawHealthBars = enable; } bool isDrawingHealthBars() { return m_drawHealthBars; } void setDrawShieldBars(bool enable) { m_drawShieldBars = enable; } bool isDrawingShieldBars() { return m_drawShieldBars; } void setDrawBarrierBars(bool enable) { m_drawBarrierBars = enable; } bool isDrawingBarrierBars() { return m_drawBarrierBars; } void setDrawLights(bool enable); bool isDrawingLights() { return m_drawLights; } void move(int x, int y); void setAnimated(bool animated) { m_animated = animated; requestVisibleTilesCacheUpdate(); } bool isAnimating() { return m_animated; } void setAddLightMethod(bool add) { m_lightView->setBlendEquation(add ? Painter::BlendEquation_Add : Painter::BlendEquation_Max); } void setShader(const PainterShaderProgramPtr& shader, float fadein, float fadeout); PainterShaderProgramPtr getShader() { return m_shader; } Position getPosition(const Point& point, const Size& mapSize); MapViewPtr asMapView() { return static_self_cast<MapView>(); } private: Rect calcFramebufferSource(const Size& destSize); int calcFirstVisibleFloor(); int calcLastVisibleFloor(); Point transformPositionTo2D(const Position& position, const Position& relativePosition) { return Point((m_virtualCenterOffset.x + (position.x - relativePosition.x) - (relativePosition.z - position.z)) * m_tileSize, (m_virtualCenterOffset.y + (position.y - relativePosition.y) - (relativePosition.z - position.z)) * m_tileSize); } int m_lockedFirstVisibleFloor; int m_cachedFirstVisibleFloor; int m_cachedLastVisibleFloor; int m_tileSize; int m_updateTilesPos; Size m_drawDimension; Size m_visibleDimension; Size m_optimizedSize; Point m_virtualCenterOffset; Point m_visibleCenterOffset; Point m_moveOffset; Position m_customCameraPosition; stdext::boolean<true> m_mustUpdateVisibleTilesCache; stdext::boolean<true> m_mustDrawVisibleTilesCache; stdext::boolean<true> m_mustCleanFramebuffer; stdext::boolean<true> m_multifloor; stdext::boolean<true> m_animated; stdext::boolean<true> m_autoViewMode; stdext::boolean<true> m_drawTexts; stdext::boolean<true> m_drawNames; stdext::boolean<true> m_drawHealthBars; stdext::boolean<true> m_drawShieldBars; stdext::boolean<true> m_drawBarrierBars; stdext::boolean<false> m_drawLights; stdext::boolean<true> m_smooth; stdext::boolean<true> m_follow; std::vector<TilePtr> m_cachedVisibleTiles; std::vector<CreaturePtr> m_cachedFloorVisibleCreatures; CreaturePtr m_followingCreature; FrameBufferPtr m_framebuffer; PainterShaderProgramPtr m_shader; ViewMode m_viewMode; Otc::DrawFlags m_drawFlags; std::vector<Point> m_spiral; LightViewPtr m_lightView; float m_minimumAmbientLight; Timer m_fadeTimer; PainterShaderProgramPtr m_nextShader; float m_fadeInTime; float m_fadeOutTime; stdext::boolean<true> m_shaderSwitchDone; }; #endif
[ "patman57@gmail.com" ]
patman57@gmail.com
3029dce824363ec5a580b13cbcecd1facb777c16
5097232bbb247f875628e5a00952e244584648d4
/tests/testroles.cpp
4cdc533c78c50dc44283385abf5d3315dda303d3
[ "MIT" ]
permissive
Hopham641994/SortFilterProxyModel
11ab6ade413a42abc19109a7537208b5457d92d0
0c1134b3aa27308764034158f79a106124d52c59
refs/heads/master
2021-04-09T09:51:37.029959
2020-04-20T10:52:49
2020-04-20T10:52:49
248,861,949
0
0
MIT
2020-03-20T22:13:46
2020-03-20T22:13:46
null
UTF-8
C++
false
false
885
cpp
#include "testroles.h" #include <QtQml> QVariant StaticRole::value() const { return m_value; } void StaticRole::setValue(const QVariant& value) { if (m_value == value) return; m_value = value; Q_EMIT valueChanged(); invalidate(); } QVariant StaticRole::data(const QModelIndex& sourceIndex, const qqsfpm::QQmlSortFilterProxyModel& proxyModel) { Q_UNUSED(sourceIndex) Q_UNUSED(proxyModel) return m_value; } QVariant SourceIndexRole::data(const QModelIndex& sourceIndex, const qqsfpm::QQmlSortFilterProxyModel& proxyModel) { Q_UNUSED(proxyModel) return sourceIndex.row(); } void registerTestRolesTypes() { qmlRegisterType<StaticRole>("SortFilterProxyModel.Test", 0, 2, "StaticRole"); qmlRegisterType<SourceIndexRole>("SortFilterProxyModel.Test", 0, 2, "SourceIndexRole"); } Q_COREAPP_STARTUP_FUNCTION(registerTestRolesTypes)
[ "grecko@grecko.fr" ]
grecko@grecko.fr
faefb89fa6c9c22042c7a34ff72ed609f707fb57
651c35ef003ac54446af29c42417b564f460a60e
/gj_linux.cc
88d360f5647ac85f4cbab5adbaaef30e68d24b6e
[]
no_license
m4tthartley/gjLib
0291b08aeabe158c9b85ae9023ac387283653e90
d2866eef323fcf34a93a969fe0c06a38ea335a51
refs/heads/master
2021-01-25T17:43:26.546707
2016-07-12T23:18:45
2016-07-12T23:18:45
60,809,087
0
0
null
null
null
null
UTF-8
C++
false
false
2,950
cc
// Linux versions of the gjLib functions #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <glob.h> #include <sys/mman.h> // #include <unistd.h> typedef int gjFile; void *gjGetVirtualMemory (size_t size) { void *result = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); return result; } // Alloc memory and init mem stack gjMemStack gjInitMemStack (size_t size) { gjMemStack memStack = {}; // todo: use mmap instead of malloc memStack.mem = (char*)malloc(size); memStack.size = size; return memStack; } // Read entire file and close it again gjData gjReadFile (const char *file, gjMemStack *memStack) { gjData data = {}; int fd = open(file, O_RDONLY); if (fd == -1) { assert(false); } struct stat fileInfo; int statResult = fstat(fd, &fileInfo); if (statResult == -1) { assert(false); } size_t fileSize = fileInfo.st_size; void *fileMemory = gjPushMemStack(memStack, fileSize); size_t bytesRead = read(fd, fileMemory, fileSize); if (bytesRead != fileSize) { assert(false); } close(fd); data.mem = (char*)fileMemory; data.size = fileSize; return data; } void gjWriteFile (const char *file, void *data, size_t size) { int fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); // 0644 if (fd == -1) { printf("%s open failed \n", __FUNCTION__); assert(false); } int bytesWritten = write(fd, data, size); if (bytesWritten != size) { printf("%s write failed \n", __FUNCTION__); assert(false); } close(fd); } gjFile gjCreateFile (const char *file) { int fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); // 0644 if (fd == -1) { printf("%s open failed \n", __FUNCTION__); assert(false); } return fd; } void gjRead (gjFile file, size_t size, gjMemStack *memStack) { void *fileMemory = gjPushMemStack(memStack, size); size_t bytesRead = read(file, fileMemory, size); if (bytesRead != size) { assert(false); } } void gjWrite (gjFile file, void *data, size_t size) { int bytesWritten = write(file, data, size); if (bytesWritten != size) { printf("%s write failed \n", __FUNCTION__); assert(false); } } void gjCloseFile (gjFile file) { close(file); } bool gjFileExists (const char *file) { struct stat fileInfo; int statResult = stat(file, &fileInfo); if (statResult == -1) { return false; } else { return true; } } /*struct gjFileList { char **files; int fileCount; };*/ int gjFindFiles (const char *wildCard, gjMemStack *memStack, char **fileOutput, int fileMax) { // todo: glob might not be the best since it doesn't give you control of the memory glob_t globState = {}; glob(wildCard, 0, NULL, &globState); int x = 0; if (globState.gl_pathc < fileMax) { fileMax = globState.gl_pathc; } fiz (fileMax) { fileOutput[i] = gjPushMemStack(memStack, gjStrlen(globState.gl_pathv[i]) + 1, true); gjStrcpy(fileOutput[i], globState.gl_pathv[i]); } return fileMax; }
[ "m4tthartley@gmail.com" ]
m4tthartley@gmail.com
c3777cb32727d0cd932c09d525149ff911eb5fe4
0b5e1a89958350970acf464baa12a35480b5ad45
/CS 161/Week 6/mainEntree.cpp
9f66b7b1a3d971dfc28d86c27e4be18563cf8e08
[]
no_license
mister-f/OSU
d9c0a242488b0a4c4a9edbfb75a4387b78092669
b6c8779d0b83924f27d948df3c74a51918644c18
refs/heads/master
2020-03-09T05:31:32.236849
2018-04-08T08:18:03
2018-04-08T08:18:03
128,615,982
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
#include <iostream> #include "EntreeSampler.hpp" using namespace std; int main() { Entree ent1("di san xian", 200); Entree ent2("roast salmon", 250); Entree ent3; Entree ent4("sour gummy worms", 300); EntreeSampler sampler1(ent1, ent2, ent3, ent4); sampler1.listEntrees(); cout << sampler1.totalCalories() << endl; return 0; }
[ "funkand@oregonstate.edu" ]
funkand@oregonstate.edu
4dba4898fd1b9334711139d9e03a8d21c98bbfd8
556408909acd8b50079f787f5e20e33c54b27301
/esVCAD/entities/block.h
25bf803cc8d215c95cbe95b14bfa3cef8fa551d5
[]
no_license
drink-crow/dxfviewer
a5eff8755fe7b311f5be42cd7fa2c17ae9e12819
5db6fc15b7cde546e68c2f5863b07db9a3e3995c
refs/heads/master
2020-12-10T06:51:22.955134
2018-12-04T10:03:25
2018-12-04T10:03:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,803
h
#ifndef BLOCK_H #define BLOCK_H #include "point.h" namespace Entities { class Block { public: Block(); Block(const std::string&name, const Point& insertPoint, const Point&scalePoint, double angle, int cols, int rows, double colSp, double rowSp); Block(const Block& block); ~Block(); private: std::string m_name;//块名 Point m_insertPoint;//插入基点 Point m_scalePoint;//缩放系数 double m_angle;//旋转角度 int m_cols;//块数组x索引,未使用 int m_rows;//块数组y索引,未使用 double m_colSp;//x边缘间距,未使用 double m_rowSp;//y边缘间距,未使用 bool m_isUse; Attributes m_attributes; bool m_bEndBlock; private: EntityContainer m_entities; public: const std::string &GetName()const{return m_name;} const Point& GetInsertPoint()const{return m_insertPoint;} const Point& GetScalePoint()const{return m_scalePoint;} double GetAngle()const{return m_angle;} int GetCols()const{return m_cols;} int GetRows()const{return m_rows;} double GetColSp()const{return m_colSp;} double GetRowSp()const{return m_rowSp;} bool IsUse()const{return m_isUse;} bool IsEndBlock()const{return m_bEndBlock;} const Attributes GetAttributes()const{return m_attributes;} void SetName(const std::string &name){ m_name=name;} void SetInsertPoint(const Point& insertPoint){ m_insertPoint=insertPoint;} void SetScalePoint(const Point& scalePoint){ m_scalePoint=scalePoint;} void SetAngle(double angle){ m_angle=angle;} void SetIsUse(bool bUse){m_isUse=bUse;} void SetIsEndBlock(bool bEndBlock){m_bEndBlock=bEndBlock;} void SetCols(int cols){ m_cols=cols;} void SetRows(int rows){ m_rows=rows;} void SetColSp(double colSp){m_colSp=colSp;} void SetRowSp(double rowSp){m_rowSp=rowSp;} void SetAttributes(const Attributes &attributes){m_attributes=attributes;} bool IsEmpty(){return m_entities.size()==0;} int GetElementSize()const{return m_entities.size();} Entity* ElementAt(int index)const{return m_entities[index];} void push_back(Entity* entity){m_entities.push_back(entity);} Entity* operator[](int index){return m_entities[index];} public: void CorrectCoord();//矫正块内图元的坐标,包括偏移,比例和角度 public: void Draw(QPainter& painter); Block* Clone(); void Transform(std::vector<Layer*>& layers,double*params,int size=9); void Scale(double ratio); void Transfer(double dx,double dy,double dz); void Rotate(double angle,double cx,double cy,double cz); const std::string ToString(){return "Block";} Layer*FindLayerByName(std::string& name,std::vector<Layer*>& layers); }; } #endif // BLOCK_H
[ "598767908@qq.com" ]
598767908@qq.com
b409344d810fc7e9619ab5e6da9e09a95293459e
3da815872b270b18b272259d062881c368735595
/src/BrewKeeper.h
c71e94a3d7e8299fe510f54b3d450e6033a6a267
[]
no_license
nicknotto/BrewPiLess
a65871d62525205a129356aab91dd179954262a4
21c94377d0e48c62ace910119a8e30139d2a20fc
refs/heads/master
2021-01-19T16:36:41.353263
2017-08-20T19:48:43
2017-08-20T19:48:43
86,272,031
0
0
null
2017-07-11T00:17:38
2017-03-26T23:30:05
C++
UTF-8
C++
false
false
2,907
h
#ifndef BrewKeeper_H #define BrewKeeper_H #include <Arduino.h> #include "espconfig.h" #include "GravityTracker.h" #if EnableGravitySchedule typedef int16_t Gravity; #define INVALID_GRAVITY -1 #define IsGravityValid(g) ((g)>0) #define FloatToGravity(f) ((Gravity)((f) * 1000.0 +0.5)) #define GravityToFloat(g) (((float)(g) / 1000.0)) typedef struct _ProfileStep{ float temp; float days; Gravity sg; uint8_t stableTime; uint8_t stablePoint; char condition; } ProfileStep; class BrewProfile { time_t _startDay; float _OGPoints; int _numberOfSteps; int _currentStep; time_t _timeEnterCurrentStep; time_t _currentStepDuration; ProfileStep *_steps; bool _profileLoaded; bool _statusLoaded; char _unit; uint8_t _stableThreshold; void _tempConvert(void); time_t _loadBrewingStatus(void); void _saveBrewingStatus(void); void _estimateStep(time_t now); void _toNextStep(unsigned long time); bool _loadProfile(String filename); public: BrewProfile(void):_profileLoaded(false),_statusLoaded(false),_numberOfSteps(0),_unit('U'),_steps(NULL){ _currentStep =0; _timeEnterCurrentStep = 0; _stableThreshold = 1; } int numberOfSteps(void){ return _numberOfSteps;} bool loaded(void){return _profileLoaded;} void setUnit(char unit); bool load(String filename); void setOriginalGravity(float gravity); float tempByTimeGravity(unsigned long time,Gravity gravity); void reload(void){_profileLoaded=false;} void setStableThreshold(uint8_t threshold){ _stableThreshold=threshold; } }; #else //#if EnableGravitySchedule class BrewProfile { time_t _startDay; int _numberOfSteps; time_t *_times; float *_setTemps; bool _profileLoaded; char _unit; void _tempConvert(void); public: BrewProfile(void):_profileLoaded(false),_numberOfSteps(0),_unit('U'),_setTemps(NULL),_times(NULL){} int numberOfSteps(void){ return _numberOfSteps;} bool loaded(void){return _profileLoaded;} void setUnit(char unit); bool load(String filename); float tempByTime(unsigned long time); void reload(void){_profileLoaded=false;} }; #endif //#if EnableGravitySchedule class BrewKeeper { protected: time_t _lastSetTemp; BrewProfile _profile; String _filename; #if EnableGravitySchedule Gravity _lastGravity; #endif void (*_write)(const char*); void _loadProfile(void); public: #if EnableGravitySchedule BrewKeeper(void(*puts)(const char*)):_filename(NULL),_write(puts),_lastGravity(INVALID_GRAVITY){} void updateGravity(float sg){ _lastGravity=FloatToGravity(sg);} void updateOriginalGravity(float sg){ _profile.setOriginalGravity(sg); } #else BrewKeeper(void(*puts)(const char*)):_filename(NULL),_write(puts){} #endif void setFile(String filename){_filename=filename;} void keep(time_t now); void reloadProfile(){ _profile.reload(); _lastSetTemp=0;} void setStableThreshold(uint8_t threshold){_profile.setStableThreshold(threshold);} }; #endif
[ "vitotai@mail.com" ]
vitotai@mail.com
f9dd7fe610ff2bb0e13c342022a182c77e2b2393
09b2c1fdc6677c91cfc4b4e8b4d06f308c0d6fc8
/cc/puzzle_19_1/main.cc
81c8398b14221ca7244badb69e1e9c51c55d9a65
[ "MIT" ]
permissive
craig-chasseur/aoc2019
a9fe165a4ca9fbb91f1a1383f9d3027389df1a61
e2bed89deef4cabc37ff438dd7d26efe0187500b
refs/heads/master
2020-09-24T15:28:15.275087
2019-12-25T06:29:43
2019-12-25T06:29:43
225,790,242
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
cc
#include <cstdint> #include <iostream> #include <utility> #include <vector> #include "cc/util/check.h" #include "cc/util/intcode.h" namespace { struct Coords { std::int64_t x = 0; std::int64_t y = 0; }; bool InBeam(std::vector<std::int64_t> program, const Coords& coords) { aoc2019::IntcodeMachine machine(std::move(program)); machine.PushInputs({coords.x, coords.y}); aoc2019::IntcodeMachine::RunResult result = machine.Run(); CHECK(result.state == aoc2019::IntcodeMachine::ExecState::kHalt); CHECK(!result.outputs.empty()); switch (result.outputs.front()) { case 0: return false; case 1: return true; default: std::cerr << "Invalid output code: " << result.outputs.front(); CHECK(false); } } Coords NextBottomEdge(const std::vector<std::int64_t>& program, const Coords& coords) { Coords next{coords.x, coords.y + 1}; while (!InBeam(program, next)) { ++next.x; } return next; } Coords StartPos(const std::vector<std::int64_t>& program) { // Find the left edge of the beam at y = 99. Coords start{0, 99}; while (!InBeam(program, start)) { ++start.x; } return start; } Coords FindClosest(const std::vector<std::int64_t>& program) { Coords bottom_left; for (bottom_left = StartPos(program); !InBeam(program, Coords{bottom_left.x + 99, bottom_left.y - 99}); bottom_left = NextBottomEdge(program, bottom_left)) { } return Coords{bottom_left.x, bottom_left.y - 99}; } } // namespace int main(int argc, char** argv) { if (argc != 2) { std::cerr << "USAGE: main FILENAME\n"; return 1; } std::vector<std::int64_t> program = aoc2019::ReadIntcodeProgram(argv[1]); Coords closest = FindClosest(program); std::cout << (closest.x * 10000 + closest.y) << "\n"; return 0; }
[ "spoonboy42@gmail.com" ]
spoonboy42@gmail.com
9aee43537d3988b09a4c82abaa9a15621e5ac9e4
bce20339ea8f2a862e2357717fd41341d8d8a477
/tests/boosting/none.cpp
7e229595d16e963ded406f9b50315d4b1186d5f2
[ "MIT" ]
permissive
pologrp/polo
345f701d231426e22c8c6b15f64541c0bec31177
da682618e98755738905fd19e55e5271af937661
refs/heads/master
2021-03-28T06:03:43.040922
2019-06-04T10:49:59
2019-06-04T10:49:59
123,282,035
8
0
MIT
2019-05-09T11:19:36
2018-02-28T12:29:07
C++
UTF-8
C++
false
false
1,187
cpp
#include <algorithm> #include <cstddef> #include <iterator> #include <random> #include <vector> #include "gtest/gtest.h" #include "polo/boosting/none.hpp" class BoostingNone : public polo::boosting::none<double, int>, public ::testing::Test { protected: BoostingNone() : x(3), g(3), gnew(3), gen{std::random_device{}()}, dist1(1, std::numeric_limits<int>::max()) {} void SetUp() override { polo::boosting::none<double, int>::initialize(std::begin(x), std::end(x)); } void TearDown() override {} ~BoostingNone() override = default; std::vector<double> x, g, gnew; std::mt19937 gen; std::uniform_int_distribution<int> dist1; std::normal_distribution<double> dist2; }; TEST_F(BoostingNone, ReceiveGradient) { const double *g_b = g.data(); const double *g_e = g_b + g.size(); double *gcurr = gnew.data(); const int widx = dist1(gen); const int klocal = dist1(gen); const int kglobal = dist1(gen); std::generate(std::begin(g), std::end(g), [&]() { return dist2(gen); }); boost(widx, klocal, kglobal, g_b, g_e, gcurr); for (std::size_t idx = 0; idx < g.size(); idx++) EXPECT_DOUBLE_EQ(g[idx], gnew[idx]); }
[ "aytekin@protonmail.com" ]
aytekin@protonmail.com
5a8e3dbca30d39356fcfac8012650cc5e814af22
814fd0bea5bc063a4e34ebdd0a5597c9ff67532b
/content/renderer/devtools/v8_sampling_profiler_browsertest.cc
9d9903cc5edf402f21d1ba6360c7598c597ad84d
[ "BSD-3-Clause" ]
permissive
rzr/chromium-crosswalk
1b22208ff556d69c009ad292bc17dca3fe15c493
d391344809adf7b4f39764ac0e15c378169b805f
refs/heads/master
2021-01-21T09:11:07.316526
2015-02-16T11:52:21
2015-02-16T11:52:21
38,887,985
0
0
NOASSERTION
2019-08-07T21:59:20
2015-07-10T15:35:50
C++
UTF-8
C++
false
false
953
cc
// Copyright (c) 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 "base/debug/trace_event.h" #include "content/renderer/devtools/v8_sampling_profiler.h" #include "testing/gtest/include/gtest/gtest.h" using base::debug::CategoryFilter; using base::debug::TraceLog; using base::debug::TraceOptions; namespace content { class V8SamplingProfilerTest : public testing::Test {}; TEST_F(V8SamplingProfilerTest, V8SamplingEventFired) { scoped_ptr<V8SamplingProfiler> sampling_profiler(new V8SamplingProfiler()); sampling_profiler->EnableSamplingEventForTesting(); TraceLog::GetInstance()->SetEnabled( CategoryFilter(TRACE_DISABLED_BY_DEFAULT("v8_cpu_profile")), TraceLog::RECORDING_MODE, TraceOptions()); sampling_profiler->WaitSamplingEventForTesting(); TraceLog::GetInstance()->SetDisabled(); } } // namespace content
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
bbc180cb54c4e5a2c70ea5871a3fec2cb4f824ca
722207989824a34279983aa8ecc143b34d0673d9
/src/Widgets/ctkFittedTextBrowser.h
32264aeffa3236f97a478fb60fb45c9954ef74e5
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
deepblueparticle/pyctk
cdd8e669f27f9b8816ad8cb3e4a8c5e95e0c33b4
4f2c8b9e917de8d518b47e5d4ccd63d9ee00a1c5
refs/heads/master
2020-03-27T20:46:11.519070
2015-09-22T13:59:50
2015-09-22T13:59:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,856
h
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkFittedTextBrowser_h #define __ctkFittedTextBrowser_h // Qt includes #include <QTextBrowser> // CTK includes #include "../ctkExport.h" /// \ingroup Widgets /// ctkFittedTextBrowser is a QTextBrowser that adapts its height depending /// on its contents and the width available. It always tries to show the whole /// contents. ctkFittedTextBrowser doesn't resize itself but acts on the /// sizeHint, minimumSizeHint and heightForWidth. Here sizeHint() and /// minimumSizeHint() are the same as ctkFittedTextBrowser always try to /// show the whole contents. class CTK_EXPORT ctkFittedTextBrowser : public QTextBrowser { Q_OBJECT public: ctkFittedTextBrowser(QWidget* parent = 0); virtual ~ctkFittedTextBrowser(); /// Reimplemented for internal reasons virtual QSize sizeHint() const; /// Reimplemented for internal reasons virtual QSize minimumSizeHint() const; /// Reimplemented for internal reasons virtual int heightForWidth(int width) const; protected Q_SLOTS: void heightForWidthMayHaveChanged(); protected: virtual void resizeEvent(QResizeEvent* e); }; #endif
[ "jazzycamel@users.noreply.github.com" ]
jazzycamel@users.noreply.github.com
7973e32b57594cc9c52c74e129dc183937d4e662
95b5ed0566e588e8d2f025d126b09d7531b201f3
/main.cpp
5d924956ab31a4ce1d4606fea6c79aa8692c9fe4
[]
no_license
radiumWater256/storm-glass
dac39dc755fee854e8dee1258fb2aaa6a8f19b53
131171e374b02676d344d5d8564228903102a8f5
refs/heads/master
2020-04-27T07:57:42.959419
2019-04-27T15:56:26
2019-04-27T15:56:26
174,154,442
0
1
null
2019-04-27T15:56:27
2019-03-06T13:52:13
C++
UTF-8
C++
false
false
15,410
cpp
#include "invMan.h" #define adminPassword "9527" using namespace std; item * inventory = new item [1000]; int mainMenu(string , bool); int searchItem(); bool checkDateStr(string dateStr); int addItem(string ); int removeItem(string ); int editItem(string); const string currentDateTime(){ //Custom made time-date generation function for logging purposes time_t now = time(0); struct tm timeStruct; char buf[80]; timeStruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d %X", &timeStruct); return buf; } char getch(){ //Keystroke Capture function char buf=0; struct termios old={0}; fflush(stdout); if(tcgetattr(0, &old)<0) perror("tcsetattr()"); old.c_lflag&=~ICANON; old.c_lflag&=~ECHO; old.c_cc[VMIN]=1; old.c_cc[VTIME]=0; if(tcsetattr(0, TCSANOW, &old)<0) perror("tcsetattr ICANON"); if(read(0,&buf,1)<0) perror("read()"); old.c_lflag|=ICANON; old.c_lflag|=ECHO; if(tcsetattr(0, TCSADRAIN, &old)<0) perror ("tcsetattr ~ICANON"); return buf; } ifstream userFile, invFile; fstream logFile("LOG.TXT", fstream::in | fstream::out | fstream::app); int main() { //Check if these three files exists // 1. USERS.TXT Stores valid user names // 2. LOG.TXT Stores system access log // 3. ITEMS.TXT Stores current inventory int dummy; cout << "Starting system..." << endl; cout << "Checking user file USERS.TXT ["; userFile.open("USERS.TXT"); invFile.open("ITEMS.TXT"); // Open all three file streams to check existence if(userFile.fail()){ cout << "FAILED]" << endl; perror("USERS.TXT"); cout << "Press <Enter> to exit" << endl; cin >> dummy; getchar(); return 0; } else cout << "OK]" << endl; cout << "Checking user file LOG.TXT ["; if(logFile.fail()){ cout << "FAILED]" << endl; perror("LOG.TXT"); cout << "Press <Enter> to exit" << endl; cin >> dummy; getchar(); return 0; } else cout << "OK]"<< endl; cout << "Checking user file ITEMS.TXT ["; if(invFile.fail()){ cout << "FAILED]" << endl; perror("ITEMS.TXT"); cout << "Press <Enter> to exit" << endl; cin >> dummy; getchar(); return 0; } else cout << "OK]"<< endl; cout << "File existence check passed..." << endl; cout << "Retrieving User List from file" << endl; struct user users[1000]; //Maximum of 1000 users int userCount=0, adminCount = 0; while(!userFile.eof()&&userCount<1000&&++userCount){ //Retrieve user names and privilege by going through the files string temp, parameter; //Temporary variables getline(userFile,temp); //Get the whole line istringstream tempStream(temp);//Turn the line of string to stream to separate things getline(tempStream, users[userCount].name, ' '); //Separate according to space character getline(tempStream, parameter, ' ');//Again if(parameter == "A"){ // If the user has admin privilege, there will be an 'A' after the name adminCount++; users[userCount].admin = true; //Flag the user if the user is meant to have admin privileges }else if(parameter == ""){ users[userCount].admin = false; }else { cout << "FATAL ERROR: User File corrupted, aborting initialization..." << endl; cout << "Press <Enter> to exit..."<<endl; getchar(); return 0; } } //read users to user list cout << userCount << " User(s) retrieved" << endl; //User Count has no need to add 1 cout << adminCount << " Admin(s) are found" << endl; cout << "Enter Username to Sign in:"; string signInName; cin >> signInName; bool found = false; bool admin = false; for(int i=0;i<userCount;i++){ // Simple Linear Search to check the user list if(signInName==users[i].name){ found=true; if(users[i].admin) admin=true; break; } }if(found == false){ cout << "Invalid Username, this attempt will be reported" << endl; //Log the event if the user name is invalid logFile << "User named <" << signInName << "> unsuccessful login attempt at " << currentDateTime() << endl; //Report the incident logFile.close(); userFile.close(); cout << "Press <Enter> to exit" << endl; getchar(); return 0; } //If login success cout << "Welcome <" << signInName << "> redirecting you to main menu..." << endl; logFile << "User named <" << signInName << "> successful login at " << currentDateTime() << endl; //Log the event int itemNum = readDataFromFile(inventory); for(int i=0;i<itemNum;i++){ //Check for expired merchandise if(inventory[i].shelfLife!=-1){ time_t now; struct tm dateOfImport; char buf[80]; istringstream dateStrStream(inventory[i].importDate); dateStrStream >> std::get_time(&dateOfImport, "%Y-%m-%d"); //Extract import date and convert to time structure const char *dateStrTemp = inventory[i].importDate.c_str(); strptime(dateStrTemp, "%Y-%m-%d", &dateOfImport); now = time(0); double expireTime = (-1*difftime(mktime(localtime(&now)), mktime(&dateOfImport)))/3600/24 + (double)inventory[i].shelfLife; //Comparison if(expireTime<0) cout << inventory[i].name << " is expired for " << -1*expireTime << " day(s)" << endl; } } mainMenu(signInName, admin); //Pass the function return 0; } int mainMenu(string userName, bool admin){ int dummy; if(admin==true){ //Check for admin dummy = getchar(); //Clear the input cout << "Admin privilege found" << endl; cout << "Please Enter password:"; char passChar; string password=""; while(passChar!=10&&(passChar = getch())) { if(passChar!=10) cout << "*"; password+=passChar; } if(password.substr(0,password.length() - 1)==adminPassword){ logFile << "User named <" << userName << "> successful ADMIN login attempt at " << currentDateTime() << endl; //Log failure cout << endl << "Password correct, access granted..." << endl; }else{ cout << "Wrong password, access denied..."<< endl; logFile << "User named <" << userName << "> unsuccessful ADMIN login attempt at " << currentDateTime() << endl;//Log success logFile.close(); cout << "Press <Enter> to exit..." << endl; getchar(); return 0; } } string permission="",command=""; if(admin==true) permission="ADELSQadelsq";//Privilege settings, limits the commands that the user can execute else permission="ELSQelsq"; cout << "Inventory Management System v1 \"Storm Glass\" Main Menu" << endl; //Here comes the main dish cout << "Login time: " << currentDateTime() << endl; while(command!="q"&&command!="Q"){ do{ if(admin==true){ cout << endl << underline << "A" << underline_off << "dd Item" << endl; cout << underline << "D" << underline_off << "elete Item" << endl; } cout << underline << "E" << underline_off << "dit Item" << endl; cout << underline << "L" << underline_off << "ist all Items" << endl; cout << underline << "S" << underline_off << "earch Item" << endl; cout << underline << "Q" << underline_off << "uit the Program" << endl; cout << "Please enter you choice (Type the underlined characters to select the function):"; cin >> command; }while(permission.find(command)==std::string::npos||command.length()!=1); if(command=="a"||command=="A"){ cout << "Launching Importation Subroutine..." << endl; int itemNo = addItem(userName); writeDataToFile(inventory, itemNo); }else if(command=="d"||command=="D"){ cout << "Launching Discard Subroutine..." << endl; int itemNo = removeItem(userName); writeDataToFile(inventory, itemNo); }else if(command=="e"||command=="E"){ cout << "Launching Edit Subroutine..." << endl; int itemNo = editItem(userName); writeDataToFile(inventory, itemNo); }else if(command=="s"||command=="S"){ cout << "Launching Query Subroutine..." << endl; searchItem(); }else if(command=="l"||command=="L"){ cout << "Launching Listing Subroutine..." << endl; int itemNo = readDataFromFile(inventory); printAllItem(inventory, itemNo); }else if(command=="q"||command=="Q"){ cout << "Signing out and quitting..." << endl; logFile << "User named <" << userName << "> signed out from the system at " << currentDateTime() << endl; logFile.close(); cout << "Thank you for using the commodity management system" << endl; cout << "Press <Enter> to Exit..." <<endl; getchar(); }else{ cout << "Invalid Choice, Try again..." << endl; } } return 0; } int searchItem(){ int itemNo = readDataFromFile(inventory); cout << "Total of <" << itemNo << "> items in inventory." << endl; //Print item count string str; cout << "Please enter your search item name or category: " << endl; cin.ignore(); getline(cin,str); int count = 0; for(int i=0; i<itemNo; i++){ if(inventory[i].name.find(str)!=std::string::npos || inventory[i].tag.find(str)!=std::string::npos){ //If keyword is present in name or category, display cout << "Name:\t\t" << inventory[i].name << endl; cout << "Category:\t" << inventory[i].tag << endl; cout << "Amount:\t\t" << inventory[i].amount << endl; if((inventory[i].shelfLife>=0)) cout << "Shelf life:\t" << inventory[i].shelfLife << " day(s)" <<endl; else cout << "Shelf life:\t" << "Not applicable" << endl; cout << "Import date:\t" << inventory[i].importDate << endl << endl; count++; } } if (count > 0){ cout << count << " result(s) found." << endl; } else{ cout << "Cannot find \"" << str << "\"" << endl; } cout << "Search again? (Type 'y' for yes, otherwise no) " << endl; char c; cin >> c; if (c == 'Y' || c == 'y'){ searchItem(); } else{ return 0; } return count; } bool checkDateStr(string dateStr){//Check if date is valid istringstream dateStrStream(dateStr); struct tm d; dateStrStream >> std::get_time(&d, "%Y-%m-%d"); // Conversion to time structure const char *dateStrTemp = dateStr.c_str(); return strptime(dateStrTemp, "%Y-%m-%d", &d);//Check for a successful conversion, invalid if cannot convert } int addItem(string userName){ int i = readDataFromFile(inventory); char c = 'y'; while (c == 'y'|c == 'Y'){ string itemName; cout << "Name: "; cin.ignore(); getline(cin,itemName); while(itemExist(inventory, itemName, i)){//Check for duplicate Items cout << "Item \"" << itemName << "\" already exists. You can" << endl; cout << underline << "E" << underline_off << "dit Item" << endl; cout << underline << "R" << underline_off << "e-enter Item Name" << endl; cout << "Please enter your choice: "; string c; cin >> c; if(c=="r"||c=="R"){ cout << "Launching Importation Subroutine..." << endl; cout << "Name: "; cin.ignore(); getline(cin,itemName); } else if(c=="e"||c=="E"){ cout << "Launching Edit Subroutine..." << endl; editItem(userName); }else{ cout << "Invalid choice, try again..." << endl; } } inventory[i].name = itemName; //Enter Item Properties cout << "Category: "; getline(cin,inventory[i].tag); cout << "Amount: "; cin >> inventory[i].amount; cout << "Shelf life (in days/ -1 if it won't expire): "; cin >> inventory[i].shelfLife; cout << "Import Date (yyyy-mm-dd): "; string dateStr=""; cin.ignore(); do{ getline(cin,dateStr); if (checkDateStr(dateStr)){ inventory[i].importDate = dateStr; break; }else{ cout << "Invalid date, please reenter..." << endl; cout << "Import Date (yyyy-mm-dd): "; } }while(!checkDateStr(dateStr)); writeDataToFile(inventory, i); logFile << "User <" << userName << "> added <" << itemName << "> to the inventory" << endl; cout << "Continue to add? (Type 'y' for yes, otherwise no)" << endl; cin >> c; i++; } return i; } int removeItem(string userName){ int itemNo = readDataFromFile(inventory); string str; cout << "Please enter the name of the item to be deleted: " << endl; cin.ignore(); getline(cin,str); char c; int delIndex = -1; for(int i=0; i<itemNo; i++){//Linear Search if(str == inventory[i].name){ delIndex = i; cout << "Name:\t\t" << inventory[i].name << endl; cout << "Category:\t" << inventory[i].tag << endl; cout << "Amount:\t\t" << inventory[i].amount << endl; cout << "Shelf life (in days):\t" << inventory[i].shelfLife << endl; cout << "Import date:\t" << inventory[i].importDate << endl << endl; } } if (delIndex >= 0){ cout << "Are you sure you want to permanently delete this item? ('y' if yes, otherwise no)" << endl; logFile << "User <" << userName << "> removed <" << str << "> from the inventory" << endl; cin >> c; if (c=='y'){ for (int i=delIndex; i<itemNo; i++){ inventory[i].name = inventory[i+1].name; inventory[i].tag = inventory[i+1].tag; inventory[i].amount = inventory[i+1].amount; inventory[i].shelfLife = inventory[i+1].shelfLife; inventory[i].importDate = inventory[i+1].importDate; } itemNo--; cout << "Item \"" << str << "\" deleted" << endl; } } else{ cout << "Cannot find \"" << str << "\"" << endl; cout << "Search again? ('y' if yes, otherwise no)" << endl; cin >> c; if (c=='y') removeItem(userName); } cout << "Remaining number of Items: " << itemNo << endl; return itemNo; } int editItem(string userName){ int itemNo = readDataFromFile(inventory); string str; cout << "Please enter the name of the item to be edited: " << endl; cin.ignore(); getline(cin,str); int count = 0; for(int i=0; i<itemNo; i++){ if(str == inventory[i].name){ count++; } } if (count == 1){ for (int i=0; i<itemNo; i++){ if (str == inventory[i].name){ cout << "Name:\t\t" << inventory[i].name << endl; cout << "Category:\t" << inventory[i].tag << endl; cout << "Amount:\t\t" << inventory[i].amount << endl; cout << "Shelf life (in days):\t" << inventory[i].shelfLife << endl; cout << "Import date:\t" << inventory[i].importDate << endl << endl; cout << "Please enter new information below:"; cout << "Category: "; getline(cin,inventory[i].tag); cout << "Amount: "; cin >> inventory[i].amount; cout << "Shelf Life (in days):"; cin >> inventory[i].shelfLife; logFile << "User <" << userName << "> changed details of <" << inventory[i].name << "> in the inventory" << endl; writeDataToFile(inventory, itemNo); //Writing record back to file break; } } } else{ cout << "Cannot find \"" << str << "\"" << endl; } cout << "Enter again? (Type 'y' for yes, otherwise no) " << endl; char c; cin >> c; if (c == 'Y' || c == 'y'){ editItem(userName); } else{ return itemNo; } return itemNo; }
[ "47210320+radiumWater256@users.noreply.github.com" ]
47210320+radiumWater256@users.noreply.github.com
5c43a8fcf98d2c43f611392df6161b2e18038d6e
7e1f0a28b57fd0bc5d2ab66b16bb72cd580f1b36
/examples/neat/pole_balancing/double_pole/dpole.cpp
d64e8647393fe8d0963a120732ad3fe1f5431732
[]
no_license
tyrvi/evo_layout
7a400a8c0756c33dd18e0619a83aad0340339036
6ba423c3de2270135ec104bb2e5d3fb8cdc26ebe
refs/heads/master
2020-04-10T14:54:13.569832
2019-04-08T06:44:13
2019-04-08T06:44:13
161,090,889
2
0
null
null
null
null
UTF-8
C++
false
false
4,497
cpp
/* dpole.cpp * * C -> python interface to solve Wieland's equations of motion for the * double pole balancing problem using the 4th order Runge-Kutta method. * * A direct ripoff from Stanley's C++ code (with small changes) written * by Richard Sutton, Charles Anderson, and Faustino Gomez. * * This code is intended to be used with neat-python: * http://code.google.com/p/neat-python * * To compile manually: * g++ -O2 -fPIC -Wall -I /usr/include/python2.5 -c dpole.cpp -o dpole.o * g++ -lpython2.5 -shared dpole.o -o dpole.so * * See setup.py for instructions on getting distutils to compile for you * (odds are you just need to do 'python setup.py build_ext -i'). */ #include <Python.h> #include <vector> #include <cmath> using namespace std; const double FORCE_MAG = 10.0; const double GRAVITY = -9.8; const double LENGTH_1 = 0.5; const double LENGTH_2 = 0.05; const double MASSPOLE_1 = 0.1; const double MASSPOLE_2 = 0.01; const double MASSCART = 1.0; const double MUP = 0.000002; void step(double action, const vector<double> &state, vector<double> &dydx) { double force, costheta_1, costheta_2, sintheta_1, sintheta_2; double gsintheta_1, gsintheta_2, temp_1, temp_2; double ml_1, ml_2, fi_1, fi_2, mi_1, mi_2; force = (action - 0.5) * FORCE_MAG * 2.0; costheta_1 = cos(state[2]); sintheta_1 = sin(state[2]); gsintheta_1 = GRAVITY*sintheta_1; costheta_2 = cos(state[4]); sintheta_2 = sin(state[4]); gsintheta_2 = GRAVITY*sintheta_2; ml_1 = LENGTH_1 * MASSPOLE_1; ml_2 = LENGTH_2 * MASSPOLE_2; temp_1 = MUP * state[3] / ml_1; temp_2 = MUP * state[5] / ml_2; fi_1 = (ml_1 * state[3] * state[3] * sintheta_1) + (0.75 * MASSPOLE_1 * costheta_1 * (temp_1 + gsintheta_1)); fi_2 = (ml_2 * state[5] * state[5] * sintheta_2) + (0.75 * MASSPOLE_2 * costheta_2 * (temp_2 + gsintheta_2)); mi_1 = MASSPOLE_1 * (1 - (0.75 * costheta_1 * costheta_1)); mi_2 = MASSPOLE_2 * (1 - (0.75 * costheta_2 * costheta_2)); dydx[1] = (force + fi_1 + fi_2) / (mi_1 + mi_2 + MASSCART); dydx[3] = -0.75 * (dydx[1] * costheta_1 + gsintheta_1 + temp_1) / LENGTH_1; dydx[5] = -0.75 * (dydx[1] * costheta_2 + gsintheta_2 + temp_2) / LENGTH_2; } void rk4(double f, vector<double> &state, const vector<double> &dydx) { int i; double TAU = 0.01; double hh = TAU*0.5; double h6 = TAU/6.0; vector<double> dym(6), dyt(6), yt(6); for(i = 0; i < 6; i++) yt[i] = state[i] + hh*dydx[i]; step(f, yt, dyt); dyt[0] = yt[1]; dyt[2] = yt[3]; dyt[4] = yt[5]; for(i = 0; i < 6; i++) yt[i] = state[i] + hh * dyt[i]; step(f, yt, dym); dym[0] = yt[1]; dym[2] = yt[3]; dym[4] = yt[5]; for(i = 0; i < 6; i++) { yt[i] = state[i] + TAU * dym[i]; dym[i] += dyt[i]; } step(f, yt, dyt); dyt[0] = yt[1]; dyt[2] = yt[3]; dyt[4] = yt[5]; for(i = 0; i < 6; i++) state[i] += h6 * (dydx[i] + dyt[i] + 2.0 * dym[i]); } bool list2vector(PyObject* list, vector<double>& v) { for(int i = 0; i < 6; i++) { v[i] = PyFloat_AsDouble(PyList_GET_ITEM(list, i)); if (PyErr_Occurred()) return false; } return true; } PyObject* vector2list(const vector<double>& v) { PyObject* list = PyList_New(6); if (!list) return 0; for(int i = 0; i < 6; i++) { PyList_SET_ITEM(list, i, PyFloat_FromDouble(v[i])); } return list; } PyObject* integrate(PyObject* self, PyObject* args) { PyObject* list; int stepnum; double output; vector<double> state(6), dydx(6); if (!PyArg_ParseTuple(args, "dO!i", &output, &PyList_Type, &list, &stepnum)) return 0; Py_INCREF(list); if(!list2vector(list, state)) { Py_DECREF(list); return 0; } else { Py_DECREF(list); } /*--- Apply action to the simulated cart-pole ---*/ for(int k = 0; k < stepnum; k++) { for(int i = 0; i < 2; i++){ dydx[0] = state[1]; dydx[2] = state[3]; dydx[4] = state[5]; step(output, state, dydx); rk4(output, state, dydx); } } return vector2list(state); } static PyMethodDef functions[] = { {"integrate", integrate, METH_VARARGS}, {NULL, NULL, 0} }; PyMODINIT_FUNC initdpole(void) { Py_InitModule3("dpole", functions, "Integrate double cart-pole equations."); }
[ "thais@minet.dk" ]
thais@minet.dk
2c497b8de2b09a27eb41483c0f616dc91ddfb16a
4b8296335e4fa1a38264fef02f430d3b57884cce
/base/message_loop/message_loop_current.h
947c8deb81fce58b10bf62ef101f6604f66bf2df
[ "BSD-3-Clause" ]
permissive
coxchris502/chromium
07ad6d930123bbf6e1754fe1820505f21d719fcd
f786352782a89d148a10d7bdd8ef3d0a86497926
refs/heads/master
2022-11-06T23:54:53.001812
2020-07-03T14:54:27
2020-07-03T14:54:27
276,935,925
1
0
BSD-3-Clause
2020-07-03T15:49:58
2020-07-03T15:49:57
null
UTF-8
C++
false
false
929
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_ #define BASE_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_ #include "base/task/current_thread.h" #include "build/build_config.h" // MessageLoopCurrent, MessageLoopCurrentForIO, and MessageLoopCurrentForUI are // being replaced by CurrentThread, CurrentIOThread, and CurrentUIThread // respectively (https://crbug.com/891670). You should no longer include this // header nor use these classes. This file will go away as soon as we have // migrated all uses. namespace base { using MessageLoopCurrent = CurrentThread; using MessageLoopCurrentForIO = CurrentIOThread; #if !defined(OS_NACL) using MessageLoopCurrentForUI = CurrentUIThread; #endif } // namespace base #endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ae5413df0a9bb261a5b8f830e909d925f6660123
0d77fc08a0501eb17a697c78ba32d305737f1559
/Code/MedicosDelPaciente.h
8c6e7ea48a70319a42ef94944128ba880fbfd41b
[]
no_license
Bernax512/Prog4
f32bf32d29a604aef0e3033eee5cbdb2fc7c51ba
0cde70f107c2cc32e7a57278e1e5e1747741cc05
refs/heads/master
2021-01-20T23:50:52.137256
2014-06-23T15:00:19
2014-06-23T15:00:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
327
h
#ifndef MEDICOSDELPACIENTE_H_ #define MEDICOSDELPACIENTE_H_ #include "Strategy.h" #include "ManejadorSocios.h" using namespace std; class MedicosDelPaciente: public Strategy { public: MedicosDelPaciente(); virtual ~MedicosDelPaciente(); set<DataMedico*> algoritmoDeSeleccion(); }; #endif /* MEDICOSDELPACIENTE_H_ */
[ "p.martinezben@gmail.com" ]
p.martinezben@gmail.com
6c1ab3d1919e061f8bda55124e46a38ec40b9d02
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/08_24917_50.cpp
248330ba468217631cd55273fc86a59fa5c502b9
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,039
cpp
#include<cstdio> #include<cstdlib> #include<map> using namespace std; class Train { public: int src; int start; int end; }; const int MAX = 1000; Train trains[MAX]; int turnaroundTime; class TrainPool { int count; int time[MAX]; public: void reset() { count = 0; } void add(Train t) { time[count++] = t.end + turnaroundTime; } void remove(int index) { for(int i=index +1; i<count; i++) time[i-1] = time[i]; count--; } bool find(int t) { for(int i=0; i<count; i++) { if(time[i] <= t) { remove(i); return true; } } return false; } }; TrainPool poolA; TrainPool poolB; int compare(const void *aa, const void *bb) { Train *a = (Train *)aa; Train *b = (Train *)bb; if(a->start == b->start) if(a->end == b->end) return a->src - b->src; else return a->end - b->end; return a->start - b->start; } int main() { int t, i, h1, h2, m1, m2; int T, Na, Nb, N; freopen("B-large.in", "r", stdin); freopen("b.out", "w", stdout); scanf("%d", &T); for( t=1; t<=T; t++) { scanf("%d", &turnaroundTime); scanf("%d %d", &Na, &Nb); N = Na+Nb; for(i=0; i<Na; i++) { scanf("%02d:%02d %02d:%02d", &h1, &m1, &h2, &m2); trains[i].src = 'a'; trains[i].start = h1 * 60 + m1; trains[i].end = h2 * 60 + m2; } for(; i<N; i++) { scanf("%02d:%02d %02d:%02d", &h1, &m1, &h2, &m2); trains[i].src = 'b'; trains[i].start = h1 * 60 + m1; trains[i].end = h2 * 60 + m2; } qsort(trains, N, sizeof(Train), compare); int countA =0, countB = 0; poolA.reset(); poolB.reset(); for(i=0; i<N; i++) { if(trains[i].src == 'a') { if(poolA.find(trains[i].start) == false) countA++; poolB.add(trains[i]); } else { if(poolB.find(trains[i].start) == false) countB++; poolA.add(trains[i]); } } printf("Case #%d: %d %d\n", t, countA, countB ); } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
787c1f341fea5e9a59b252d1a7423fc673664fd8
566332bd52c55e471b1e2a9ff2f906c2ce46494f
/src/resources/GenericResource.cpp
e5c8b54d6d647b303efffb7e49c9be21fef2ee75
[ "Apache-2.0" ]
permissive
deadbrainviv/crt
383c88d6f18362dbfde0cd356555f4d6a3cb52ad
ff59c245ace4fcfc9e7eacad9a95b75fb38b105b
refs/heads/master
2020-03-22T04:05:56.346145
2018-03-03T07:53:51
2018-03-03T07:53:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
//! \file //! //! GenericResource.cpp //! #include "GenericResource.h" // // Standard C++ Libary Includes // #include <sstream> GenericResource::GenericResource( CrtSvc & _crtSvc, std::uint32_t _resourceId, bool _descriptor ) : crtSvc( _crtSvc ), resourceId( _resourceId ), descriptor( _descriptor ) { } GenericResource::~GenericResource( void ) { } void GenericResource::handleRequest( HTTPServerRequest & request, HTTPServerResponse & response ) { response.setChunkedTransferEncoding( true ); response.setContentType( "application/json" ); std::ostream & ostr = response.send(); ostr << crtSvc.resourceJSON( resourceId, descriptor ); }
[ "rick@sostheim.com" ]
rick@sostheim.com
70aec8f29b72c5a78f34b4e38914ccea520b05ed
c4f5f433683860ee1a4b04b490fcbb4d4dfbcafd
/Codeforces/CF441D Valera and Swaps.cpp
51ab040e5e956b2199bf5c12975434f13c721abb
[]
no_license
mohrechi/Cookie
607290e4bb4aaaf60b2a4114c98fa8e38086f089
d3686a04fe6d109cd4293f2f1c20fdfc7c9b2745
refs/heads/master
2020-08-30T10:33:05.321074
2017-05-26T01:28:20
2017-05-26T01:28:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,652
cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 3000 + 5; int n, m; int a[MAXN]; bool visit[MAXN]; struct Loop { set<int> s; bool operator <(const Loop &loop) const { return *s.begin() < *loop.s.begin(); } }; Loop getLoop(int p) { Loop loop; while (!visit[p]) { visit[p] = true; loop.s.insert(p); p = a[p]; } return loop; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); } scanf("%d", &m); set<Loop> loops; for (int i = 1; i <= n; ++i) { if (!visit[i]) { loops.insert(getLoop(i)); } } int num = n - loops.size(); vector<pair<int, int>> ans; if (num < m) { auto first = loops.begin(); auto it = loops.begin(); for (int i = 0; i < m - num; ++i) { ans.push_back({*(first->s.begin()), *((++it)->s.begin())}); } } else if (num > m) { for (int i = 0; i < num - m; ++i) { while (loops.begin()->s.size() <= 1) { loops.erase(loops.begin()); } auto loop = loops.begin(); int p = *(loop->s.begin()); int s = *(++loop->s.begin()); ans.push_back({p, s}); swap(a[p], a[s]); for (auto c : loop->s) { visit[c] = false; } loops.erase(loops.begin()); loops.insert(getLoop(p)); loops.insert(getLoop(s)); } } printf("%d\n", (int)ans.size()); for (auto a : ans) { printf("%d %d\n", a.first, a.second); } return 0; }
[ "cyberzhg@gmail.com" ]
cyberzhg@gmail.com
a8f769d531dfeba32cfaa6cd6d2b8a809c6b766a
216dce839ba13869d8d6e23b3f55accf050beb9f
/Robot/Robot.ino
208d6d7368ebb569e691907b0a7f699edb94594e
[]
no_license
navidadelpour/Microprocessor-Lab
c6ccbe7a64978ac8135339018294395036777375
9987a0c12375bf1ec9d9ed4684d250271af844b4
refs/heads/master
2020-09-06T12:52:56.295787
2020-01-08T17:40:28
2020-01-08T17:40:28
220,428,889
4
0
null
null
null
null
UTF-8
C++
false
false
1,423
ino
// ============================================== SETTINGS ///////////////// const int THRESHOLD = 512; const int SENSORS_COUNT = 5; const int SENSOR_PINS[SENSORS_COUNT] = {A0, A1, A2, A3, A4}; const int ERRORS[4] = {0, 1, 2, 3}; const int MAX_SPEED = 255; const int NORMAL_SPEED = 205; const int MIN_SPEED = 0; const int LEFT_IN1 = 6; const int LEFT_IN2 = 7; const int LEFT_EN = 5; const int RIGHT_IN1 = 8; const int RIGHT_IN2 = 9; const int RIGHT_EN = 10; const float KP = 80; const float KI = 0; const float KD = 50; const bool DEBUG = false; const int DELAY_TIME = 1000; // ============================================== ///////////////// #include "Sensors.h" #include "Motors.h" #include "PID.h" Sensors sensors(THRESHOLD, SENSORS_COUNT, SENSOR_PINS, ERRORS); Motors motors( NORMAL_SPEED, MIN_SPEED, MAX_SPEED, LEFT_IN1, LEFT_IN2, LEFT_EN, RIGHT_IN1, RIGHT_IN2, RIGHT_EN ); PID pid(KP, KI, KD); void setup() { Serial.begin(9600); motors.initialize(); } void loop() { int error = sensors.calculate_error(); int speed_difference = pid.calculate_speed_difference(error); motors.drive(speed_difference, DEBUG); if(DEBUG) { Serial.print("error: "); Serial.println(error); Serial.print("speed_difference: "); Serial.println(speed_difference); Serial.println("--------------------------------------"); delay(DELAY_TIME); } }
[ "navidadelpour@gmail.com" ]
navidadelpour@gmail.com
49aa75e66f9813a62b579525f8327effafeb8482
210f014d443b5cd3193033f1a26e8d638533bf01
/5.5.1/android_arm64-v8a/include/Qt3DRenderer/sphere.h
8d01b477182861bdca8db72c568c580d562e95b1
[]
no_license
LightZam/Qt-Library
427106c56e6570846a24a5f6049e4af8468d8590
c006b881904ccce88c533fdcd6ca16989e4db7e6
refs/heads/master
2021-09-06T20:59:56.066435
2018-02-11T09:43:51
2018-02-11T09:48:35
107,560,674
11
1
null
null
null
null
UTF-8
C++
false
false
4,178
h
/**************************************************************************** ** ** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL3$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or later as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information to ** ensure the GNU General Public License version 2.0 requirements will be ** met: http://www.gnu.org/licenses/gpl-2.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef SPHERE_H #define SPHERE_H #include <Qt3DRenderer/qt3drenderer_global.h> #include <Qt3DCore/qnodeid.h> #include <Qt3DCore/qboundingsphere.h> #include <QMatrix4x4> #include <QVector3D> QT_BEGIN_NAMESPACE namespace Qt3D { class QT3DRENDERERSHARED_EXPORT Sphere : public QBoundingSphere { public: inline Sphere(const QNodeId &i = QNodeId()) : m_center() , m_radius(0.0f) , m_id(i) {} inline Sphere(const QVector3D &c, float r, const QNodeId &i = QNodeId()) : m_center(c) , m_radius(r) , m_id(i) {} void setCenter(const QVector3D &c); QVector3D center() const; inline bool isNull() { return m_center == QVector3D() && m_radius == 0.0f; } void setRadius(float r); float radius() const; void clear(); void initializeFromPoints(const QVector<QVector3D> &points); void expandToContain(const QVector3D &point); inline void expandToContain(const QVector<QVector3D> &points) { Q_FOREACH (const QVector3D &p, points) expandToContain(p); } void expandToContain(const Sphere &sphere); Sphere transformed(const QMatrix4x4 &mat); inline Sphere &transform(const QMatrix4x4 &mat) { *this = transformed(mat); return *this; } QNodeId id() const Q_DECL_FINAL; bool intersects(const QRay3D &ray, QVector3D *q) const Q_DECL_FINAL; Type type() const Q_DECL_FINAL; static Sphere fromPoints(const QVector<QVector3D> &points); private: QVector3D m_center; float m_radius; QNodeId m_id; static const float ms_epsilon; }; inline void Sphere::setCenter(const QVector3D &c) { m_center = c; } inline QVector3D Sphere::center() const { return m_center; } inline void Sphere::setRadius(float r) { m_radius = r; } inline float Sphere::radius() const { return m_radius; } inline void Sphere::clear() { m_center = QVector3D(); m_radius = 0.0f; } inline bool intersects(const Sphere &a, const Sphere &b) { // Calculate squared distance between sphere centers const QVector3D d = a.center() - b.center(); const float distSq = QVector3D::dotProduct(d, d); // Spheres intersect if squared distance is less than squared // sum of radii const float sumRadii = a.radius() + b.radius(); return distSq <= sumRadii * sumRadii; } } QT_END_NAMESPACE Q_DECLARE_METATYPE(Qt3D::Sphere) #endif // SPHERE_H
[ "love8879201@gmail.com" ]
love8879201@gmail.com
d016f3abca84a3f155e716906b26b17e6c8cb879
bb10dba077acb492b13e6274cfc2c645790b68c7
/src/Game/Game/Map/BattleEffect/BattleEffectP008_1.cpp
8e6e3f4446a3d96228d0dfd44640275d7b269c2a
[]
no_license
pocarich/RPG
177225228f40459e56a57e151ec2fc4ee4257791
24c437d9e6b158d3d6e3a16a6ad462840d1ee60d
refs/heads/main
2023-08-31T09:59:52.318258
2021-10-31T19:11:45
2021-10-31T19:11:45
423,229,445
0
0
null
null
null
null
UTF-8
C++
false
false
5,567
cpp
#include"../header/BattleEffectP008_1.h" #include"../header/PlayerMap.h" #include"../header/EnemyMap.h" #include"../header/BattleEffectP008_2.h" #include"../header/ObjectMap.h" #include"../header/BossMap.h" const double BattleEffectP008_1::speed = 8.0; const int BattleEffectP008_1::existTime = 40; BattleEffectP008_1::BattleEffectP008_1(PlayerMap* playerMap, list<BossMapPtr>& bossMapList, list<ObjectMapPtr>& objectMapList, list<BattleEffectPtr>& battleEffectList, list<EnemyMapPtr>& enemyMapList, int sourceID, Vector2<int> masuPosition, Direction direction, Vector2<double>&camera, int& mapNum,bool SPMAX) :BattleEffect(playerMap, bossMapList, objectMapList, battleEffectList, enemyMapList, ObjectType::PLAYER, sourceID, masuPosition, direction, camera, mapNum, TargetType::ENEMY),SPMAX(SPMAX) { position = Vector2<double>(this->masuPosition.x*Define::MASU_SIZE + Define::MASU_SIZE / 2, this->masuPosition.y*Define::MASU_SIZE + Define::MASU_SIZE / 2); this->direction = playerMap->GetDirection(); switch (playerMap->GetDirection()) { case Direction::DOWN: velocity = Vector2<double>::DOWN*speed; break; case Direction::LEFT: velocity = Vector2<double>::LEFT*speed; break; case Direction::RIGHT: velocity = Vector2<double>::RIGHT*speed; break; case Direction::UP: velocity = Vector2<double>::UP*speed; break; } } BattleEffectP008_1::~BattleEffectP008_1() { } void BattleEffectP008_1::Update() { position += velocity; effectTimer++; if (effectTimer % (Define::MASU_SIZE / (int)speed) == 2) { Vector2<int> next; switch (direction) { case Direction::DOWN: next = masuPosition + Vector2<int>((int)Vector2<double>::DOWN.x, (int)Vector2<double>::DOWN.y); break; case Direction::LEFT: next = masuPosition + Vector2<int>((int)Vector2<double>::LEFT.x, (int)Vector2<double>::LEFT.y); break; case Direction::RIGHT: next = masuPosition + Vector2<int>((int)Vector2<double>::RIGHT.x, (int)Vector2<double>::RIGHT.y); break; case Direction::UP: next = masuPosition + Vector2<int>((int)Vector2<double>::UP.x, (int)Vector2<double>::UP.y); break; } if (CanMoveToNextPosition(next,direction)) { masuPosition = next; } else { disappearFlag = true; return; } } for (auto& obj : enemyMapList) { if (abs(obj->GetPosition().x - position.x) < ((double)Define::MASU_SIZE - 2.0) && abs(obj->GetPosition().y - position.y) < ((double)Define::MASU_SIZE - 2.0)) { Vector2<int> next; switch (direction) { case Direction::DOWN: next = masuPosition + Vector2<int>((int)Vector2<double>::DOWN.x, (int)Vector2<double>::DOWN.y); break; case Direction::LEFT: next = masuPosition + Vector2<int>((int)Vector2<double>::LEFT.x, (int)Vector2<double>::LEFT.y); break; case Direction::RIGHT: next = masuPosition + Vector2<int>((int)Vector2<double>::RIGHT.x, (int)Vector2<double>::RIGHT.y); break; case Direction::UP: next = masuPosition + Vector2<int>((int)Vector2<double>::UP.x, (int)Vector2<double>::UP.y); break; } masuPosition = next; battleEffectList.push_back(make_shared<BattleEffectP008_2>(playerMap, bossMapList, objectMapList, battleEffectList, enemyMapList, sourceID, masuPosition, direction, camera, mapNum,SPMAX)); disappearFlag = true; } } for (auto& obj : objectMapList) { if (obj->GetCanDestroy() && masuPosition == obj->GetMasuPosition()) { Vector2<int> next; switch (direction) { case Direction::DOWN: next = masuPosition + Vector2<int>((int)Vector2<double>::DOWN.x, (int)Vector2<double>::DOWN.y); break; case Direction::LEFT: next = masuPosition + Vector2<int>((int)Vector2<double>::LEFT.x, (int)Vector2<double>::LEFT.y); break; case Direction::RIGHT: next = masuPosition + Vector2<int>((int)Vector2<double>::RIGHT.x, (int)Vector2<double>::RIGHT.y); break; case Direction::UP: next = masuPosition + Vector2<int>((int)Vector2<double>::UP.x, (int)Vector2<double>::UP.y); break; } masuPosition = next; battleEffectList.push_back(make_shared<BattleEffectP008_2>(playerMap, bossMapList, objectMapList, battleEffectList, enemyMapList, sourceID, masuPosition, direction, camera, mapNum,SPMAX)); disappearFlag = true; } } for (auto& obj : bossMapList) { if (abs(obj->GetPosition().x - position.x) < ((double)Define::MASU_SIZE*2 - 2.0) && abs(obj->GetPosition().y - position.y) < ((double)Define::MASU_SIZE*2 - 2.0)) { Vector2<int> next; switch (direction) { case Direction::DOWN: next = masuPosition + Vector2<int>((int)Vector2<double>::DOWN.x, (int)Vector2<double>::DOWN.y); break; case Direction::LEFT: next = masuPosition + Vector2<int>((int)Vector2<double>::LEFT.x, (int)Vector2<double>::LEFT.y); break; case Direction::RIGHT: next = masuPosition + Vector2<int>((int)Vector2<double>::RIGHT.x, (int)Vector2<double>::RIGHT.y); break; case Direction::UP: next = masuPosition + Vector2<int>((int)Vector2<double>::UP.x, (int)Vector2<double>::UP.y); break; } masuPosition = next; battleEffectList.push_back(make_shared<BattleEffectP008_2>(playerMap, bossMapList, objectMapList, battleEffectList, enemyMapList, sourceID, masuPosition, direction, camera, mapNum,SPMAX)); disappearFlag = true; } } if (effectTimer == existTime) { disappearFlag = true; } } void BattleEffectP008_1::Draw() { static const int graphKind[] = { 2,3,4,5 }; DrawRotaGraphF((float)position.x - camera.x, (float)position.y - camera.y, 1.0, 0.0, graph[13][graphKind[(effectTimer / 3) % 4]], TRUE); }
[ "pocarich@gmail.com" ]
pocarich@gmail.com
736c4785c9256c07d1c0a6d5a07c03d9c028ef79
79487524fd7a6fbbe32e3e57b8aa5f150668ccfc
/Source/vtkDICOMFile.cxx
7ac3e715d385afaff34e502c409621c973838f2c
[]
no_license
lorensen/vtk-dicom
067be771c2047c062123b2f2ad6848be19e32106
8664858b456607543e611c1e3ff7d3558e063134
refs/heads/master
2021-01-17T16:07:21.506708
2015-07-07T23:29:01
2015-07-07T23:29:01
38,824,130
1
0
null
2015-07-09T14:08:04
2015-07-09T14:08:04
null
UTF-8
C++
false
false
10,124
cxx
/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2015 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDICOMFile.h" #if defined(VTK_DICOM_POSIX_IO) #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #elif defined(VTK_DICOM_WIN32_IO) #include <windows.h> #else #ifdef _WIN32 #include <io.h> #include <direct.h> #define _unlink unlink #else #include <unistd.h> #endif #include <stdio.h> #include <errno.h> #endif //---------------------------------------------------------------------------- vtkDICOMFile::vtkDICOMFile(const char *filename, Mode mode) { #if defined(VTK_DICOM_POSIX_IO) this->Handle = -1; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = open(filename, O_RDONLY); } else if (mode == Out) { this->Handle = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 000666); } if (this->Handle == -1) { int errorCode = errno; if (errorCode == EACCES) { this->Error = AccessDenied; } else if (errorCode == EISDIR) { this->Error = IsDirectory; } else if (errorCode == ENOTDIR) { this->Error = DirectoryNotFound; } else if (errorCode == ENOENT) { this->Error = FileNotFound; } else if (errorCode == ENOSPC) { // some systems also have EDQUOT for "quota exceeded" this->Error = OutOfSpace; } else { this->Error = Bad; } } #elif defined(VTK_DICOM_WIN32_IO) this->Handle = INVALID_HANDLE_VALUE; this->Error = 0; this->Eof = false; WCHAR *wideFilename = 0; int n = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, filename, -1, NULL, 0); if (n > 0) { wideFilename = new WCHAR[n]; n = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, filename, -1, wideFilename, n); if (mode == In) { this->Handle = CreateFileW(wideFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); } else if (mode == Out) { this->Handle = CreateFileW(wideFilename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } } if (this->Handle == INVALID_HANDLE_VALUE) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_ACCESS_DENIED || errorCode == ERROR_SHARING_VIOLATION) { this->Error = AccessDenied; if (wideFilename) { DWORD attr = GetFileAttributesW(wideFilename); if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { this->Error = IsDirectory; } } } else if (errorCode == ERROR_DIRECTORY) { this->Error = DirectoryNotFound; } else if (errorCode == ERROR_FILE_NOT_FOUND) { this->Error = FileNotFound; } else if (errorCode == ERROR_DISK_FULL) { this->Error = OutOfSpace; } else { this->Error = Bad; } } delete [] wideFilename; #else this->Handle = 0; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = fopen(filename, "rb"); } else if (mode == Out) { this->Handle = fopen(filename, "wb"); } if (this->Handle == 0) { this->Error = Bad; } #endif } //---------------------------------------------------------------------------- vtkDICOMFile::~vtkDICOMFile() { this->Close(); } //---------------------------------------------------------------------------- void vtkDICOMFile::Close() { #if defined(VTK_DICOM_POSIX_IO) if (this->Handle) { if (close(this->Handle) == 0) { this->Error = 0; } else if (errno != EINTR) { this->Error = Bad; } this->Handle = 0; } #elif defined(VTK_DICOM_WIN32_IO) CloseHandle(this->Handle); this->Handle = INVALID_HANDLE_VALUE; #else if (this->Handle) { fclose(static_cast<FILE *>(this->Handle)); } this->Handle = 0; #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Read(unsigned char *data, size_t len) { #if defined(VTK_DICOM_POSIX_IO) ssize_t n; while ((n = read(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } errno = 0; } if (n == 0) { this->Eof = true; } else if (n == -1) { this->Error = Bad; n = 0; } return n; #elif defined(VTK_DICOM_WIN32_IO) // handle large requests in 1GB chunks const size_t chunksize = 1024*1024*1024; size_t n = 0; while (n < len) { DWORD l = static_cast<DWORD>(len - n < chunksize ? len - n : chunksize); DWORD r = 0; if (ReadFile(this->Handle, &data[n], l, &r, NULL) == FALSE) { this->Error = Bad; break; } else if (r == 0) { this->Eof = true; break; } n += r; } return n; #else size_t n = fread(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Eof = (feof(static_cast<FILE *>(this->Handle)) != 0); this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Write(const unsigned char *data, size_t len) { #if defined(VTK_DICOM_POSIX_IO) ssize_t n; while ((n = write(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } errno = 0; } if (n == -1) { this->Error = Bad; n = 0; } return n; #elif defined(VTK_DICOM_WIN32_IO) // handle large requests in 1GB chunks const size_t chunksize = 1024*1024*1024; size_t n = 0; while (n < len) { DWORD l = static_cast<DWORD>(len - n < chunksize ? len - n : chunksize); DWORD r = 0; if (WriteFile(this->Handle, &data[n], l, &r, NULL) == FALSE) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_HANDLE_DISK_FULL) { this->Error = OutOfSpace; } else { this->Error = Bad; } break; } n += r; } return n; #else size_t n = fwrite(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- bool vtkDICOMFile::SetPosition(Size offset) { #if defined(VTK_DICOM_POSIX_IO) #if defined(__linux__) && defined(_LARGEFILE64_SOURCE) off64_t pos = lseek64(this->Handle, offset, SEEK_SET); #else off_t pos = lseek(this->Handle, offset, SEEK_SET); #endif if (pos == -1) { this->Error = Bad; return false; } return true; #elif defined(VTK_DICOM_WIN32_IO) LONG lowerBits = static_cast<LONG>(offset); LONG upperBits = static_cast<LONG>(offset >> 32); DWORD pos = SetFilePointer(this->Handle, lowerBits, &upperBits, FILE_BEGIN); if (pos == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) { this->Error = Bad; return false; } return true; #else return (fseek(static_cast<FILE *>(this->Handle), offset, SEEK_SET) == 0); #endif } //---------------------------------------------------------------------------- vtkDICOMFile::Size vtkDICOMFile::GetSize() { #if defined(VTK_DICOM_POSIX_IO) struct stat fs; if (fstat(this->Handle, &fs) != 0) { this->Error = Bad; return static_cast<long long>(-1); } return fs.st_size; #elif defined(VTK_DICOM_WIN32_IO) DWORD upperBits = 0; DWORD lowerBits = GetFileSize(this->Handle, &upperBits); if (lowerBits == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) { this->Error = Bad; return static_cast<long long>(-1); } return lowerBits | (static_cast<Size>(upperBits) << 32); #else FILE *fp = static_cast<FILE *>(this->Handle); long long size = -1; fpos_t pos; if (fgetpos(fp, &pos) == 0) { if (fseek(fp, 0, SEEK_END) == 0) { size = ftell(fp); } if (fsetpos(fp, &pos) != 0) { this->Error = Bad; } } if (size == -1) { this->Error = Bad; } return size; #endif } //---------------------------------------------------------------------------- int vtkDICOMFile::Remove(const char *filename) { #if defined(VTK_DICOM_WIN32_IO) int errorCode = 0; WCHAR *wideFilename = 0; int n = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, filename, -1, NULL, 0); if (n > 0) { wideFilename = new WCHAR[n]; n = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, filename, -1, wideFilename, n); if (!DeleteFileW(wideFilename)) { DWORD lastError = GetLastError(); if (lastError == ERROR_ACCESS_DENIED || lastError == ERROR_SHARING_VIOLATION) { errorCode = AccessDenied; } else if (lastError == ERROR_FILE_NOT_FOUND) { errorCode = FileNotFound; } else if (lastError == ERROR_DIRECTORY) { errorCode = DirectoryNotFound; } else { errorCode = Bad; } } delete [] wideFilename; } return errorCode; #else int errorCode = 0; if (unlink(filename) != 0) { int e = errno; if (e == EACCES || e == EPERM) { errorCode = AccessDenied; } else if (e == ENOENT) { errorCode = FileNotFound; } else if (e == ENOTDIR) { errorCode = DirectoryNotFound; } else { errorCode = Bad; } } return errorCode; #endif }
[ "david.gobbi@gmail.com" ]
david.gobbi@gmail.com
23b6a75159807bc81b03736910675f8a66e69aed
7ed441ee237f2738a79bfb5b705e3e7dbfda4ec9
/client/UserInterface/PythonNetworkStreamPhaseLogin.cpp
0449835fcad40db68c644b83448e2b981d6162e3
[]
no_license
ASIKOO/Metin-Refresh-Client-Src
82cab756bca20b7703b0478e29798e6c8ea3b5f1
c9d825b71037197696050cde10c8292dda07d9a9
refs/heads/master
2021-09-22T01:17:04.630661
2018-09-04T13:55:19
2018-09-04T13:55:19
null
0
0
null
null
null
null
UHC
C++
false
false
11,000
cpp
#include "StdAfx.h" #include "PythonNetworkStream.h" #include "Packet.h" #include "Test.h" #include "AccountConnector.h" #include "Hackshield.h" #include "WiseLogicXTrap.h" // Login --------------------------------------------------------------------------- void CPythonNetworkStream::LoginPhase() { TPacketHeader header; if (!CheckPacket(&header)) return; switch (header) { case HEADER_GC_PHASE: if (RecvPhasePacket()) return; break; case HEADER_GC_LOGIN_SUCCESS3: if (__RecvLoginSuccessPacket3()) return; break; /*case HEADER_GC_LOGIN_SUCCESS4: if (__RecvLoginSuccessPacket4()) return; break;*/ case HEADER_GC_LOGIN_FAILURE: if (__RecvLoginFailurePacket()) return; break; case HEADER_GC_EMPIRE: if (__RecvEmpirePacket()) return; break; case HEADER_GC_CHINA_MATRIX_CARD: if (__RecvChinaMatrixCardPacket()) return; break; /*case HEADER_GC_RUNUP_MATRIX_QUIZ: if (__RecvRunupMatrixQuizPacket()) return; break;*/ case HEADER_GC_NEWCIBN_PASSPOD_REQUEST: if (__RecvNEWCIBNPasspodRequestPacket()) return; break; case HEADER_GC_NEWCIBN_PASSPOD_FAILURE: if (__RecvNEWCIBNPasspodFailurePacket()) return; break; case HEADER_GC_LOGIN_KEY: if (__RecvLoginKeyPacket()) return; break; case HEADER_GC_PING: if (RecvPingPacket()) return; break; case HEADER_GC_HYBRIDCRYPT_KEYS: RecvHybridCryptKeyPacket(); return; break; case HEADER_GC_HYBRIDCRYPT_SDB: RecvHybridCryptSDBPacket(); return; break; default: if (RecvDefaultPacket(header)) return; break; } RecvErrorPacket(header); } void CPythonNetworkStream::SetLoginPhase() { const char* key = LocaleService_GetSecurityKey(); #ifndef _IMPROVED_PACKET_ENCRYPTION_ SetSecurityMode(true, key); #endif if ("Login" != m_strPhase) m_phaseLeaveFunc.Run(); Tracen(""); Tracen("## Network - Login Phase ##"); Tracen(""); m_strPhase = "Login"; m_phaseProcessFunc.Set(this, &CPythonNetworkStream::LoginPhase); m_phaseLeaveFunc.Set(this, &CPythonNetworkStream::__LeaveLoginPhase); m_dwChangingPhaseTime = ELTimer_GetMSec(); if (__DirectEnterMode_IsSet()) { if (0 != m_dwLoginKey) SendLoginPacketNew(m_stID.c_str(), m_stPassword.c_str(), m_stHwid.c_str()); else SendLoginPacket(m_stID.c_str(), m_stPassword.c_str(), m_stHwid.c_str()); // 비밀번호를 메모리에 계속 갖고 있는 문제가 있어서, 사용 즉시 날리는 것으로 변경 ClearLoginInfo(); CAccountConnector & rkAccountConnector = CAccountConnector::Instance(); rkAccountConnector.ClearLoginInfo(); } else { if (0 != m_dwLoginKey) SendLoginPacketNew(m_stID.c_str(), m_stPassword.c_str(), m_stHwid.c_str()); else SendLoginPacket(m_stID.c_str(), m_stPassword.c_str(), m_stHwid.c_str()); // 비밀번호를 메모리에 계속 갖고 있는 문제가 있어서, 사용 즉시 날리는 것으로 변경 ClearLoginInfo(); CAccountConnector & rkAccountConnector = CAccountConnector::Instance(); rkAccountConnector.ClearLoginInfo(); PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "OnLoginStart", Py_BuildValue("()")); __ClearSelectCharacterData(); } } bool CPythonNetworkStream::__RecvEmpirePacket() { TPacketGCEmpire kPacketEmpire; if (!Recv(sizeof(kPacketEmpire), &kPacketEmpire)) return false; m_dwEmpireID=kPacketEmpire.bEmpire; return true; } bool CPythonNetworkStream::__RecvLoginSuccessPacket3() { TPacketGCLoginSuccess3 kPacketLoginSuccess; if (!Recv(sizeof(kPacketLoginSuccess), &kPacketLoginSuccess)) return false; for (int i = 0; i<PLAYER_PER_ACCOUNT3; ++i) { m_akSimplePlayerInfo[i]=kPacketLoginSuccess.akSimplePlayerInformation[i]; m_adwGuildID[i]=kPacketLoginSuccess.guild_id[i]; m_astrGuildName[i]=kPacketLoginSuccess.guild_name[i]; } m_kMarkAuth.m_dwHandle=kPacketLoginSuccess.handle; m_kMarkAuth.m_dwRandomKey=kPacketLoginSuccess.random_key; if (__DirectEnterMode_IsSet()) { } else { PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_SELECT], "Refresh", Py_BuildValue("()")); } return true; } bool CPythonNetworkStream::__RecvLoginSuccessPacket4() { TPacketGCLoginSuccess4 kPacketLoginSuccess; if (!Recv(sizeof(kPacketLoginSuccess), &kPacketLoginSuccess)) return false; for (int i = 0; i<PLAYER_PER_ACCOUNT4; ++i) { m_akSimplePlayerInfo[i]=kPacketLoginSuccess.akSimplePlayerInformation[i]; m_adwGuildID[i]=kPacketLoginSuccess.guild_id[i]; m_astrGuildName[i]=kPacketLoginSuccess.guild_name[i]; } m_kMarkAuth.m_dwHandle=kPacketLoginSuccess.handle; m_kMarkAuth.m_dwRandomKey=kPacketLoginSuccess.random_key; if (__DirectEnterMode_IsSet()) { } else { PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_SELECT], "Refresh", Py_BuildValue("()")); } return true; } void CPythonNetworkStream::OnConnectFailure() { if (__DirectEnterMode_IsSet()) { ClosePhase(); } else { PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "OnConnectFailure", Py_BuildValue("()")); } } bool CPythonNetworkStream::__RecvLoginFailurePacket() { TPacketGCLoginFailure packet_failure; if (!Recv(sizeof(TPacketGCLoginFailure), &packet_failure)) return false; PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "OnLoginFailure", Py_BuildValue("(s)", packet_failure.szStatus)); #if !_RELEASE Tracef(" RecvLoginFailurePacket : [%s]\n", packet_failure.szStatus); #endif return true; } bool CPythonNetworkStream::SendDirectEnterPacket(const char* c_szID, const char* c_szPassword, const char* c_szHwid, UINT uChrSlot) { TPacketCGDirectEnter kPacketDirectEnter; kPacketDirectEnter.bHeader=HEADER_CG_DIRECT_ENTER; kPacketDirectEnter.index=uChrSlot; strncpy(kPacketDirectEnter.login, c_szID, ID_MAX_NUM); strncpy(kPacketDirectEnter.passwd, c_szPassword, PASS_MAX_NUM); strncpy(kPacketDirectEnter.Hwid, c_szHwid, HWID_MAX_NUM); if (!Send(sizeof(kPacketDirectEnter), &kPacketDirectEnter)) { Tracen("SendDirectEnter"); return false; } return SendSequence(); } bool CPythonNetworkStream::SendLoginPacket(const char* c_szName, const char* c_szPassword, const char* c_szHwid) { TPacketCGLogin LoginPacket; LoginPacket.header = HEADER_CG_LOGIN; strncpy(LoginPacket.name, c_szName, sizeof(LoginPacket.name)-1); strncpy(LoginPacket.pwd, c_szPassword, sizeof(LoginPacket.pwd)-1); strncpy(LoginPacket.Hwid, c_szHwid, sizeof(LoginPacket.Hwid) - 1); LoginPacket.name[ID_MAX_NUM]='\0'; LoginPacket.pwd[PASS_MAX_NUM]='\0'; LoginPacket.Hwid[HWID_MAX_NUM] = '\0'; if (!Send(sizeof(LoginPacket), &LoginPacket)) { Tracen("SendLogin Error"); return false; } return SendSequence(); } bool CPythonNetworkStream::SendLoginPacketNew(const char * c_szName, const char * c_szPassword, const char * c_szHwid) { TPacketCGLogin2 LoginPacket; LoginPacket.header = HEADER_CG_LOGIN2; LoginPacket.login_key = m_dwLoginKey; strncpy(LoginPacket.name, c_szName, sizeof(LoginPacket.name)-1); LoginPacket.name[ID_MAX_NUM]='\0'; extern DWORD g_adwEncryptKey[4]; extern DWORD g_adwDecryptKey[4]; for (DWORD i = 0; i < 4; ++i) LoginPacket.adwClientKey[i] = g_adwEncryptKey[i]; if (!Send(sizeof(LoginPacket), &LoginPacket)) { Tracen("SendLogin Error"); return false; } if (!SendSequence()) { Tracen("SendLogin Error"); return false; } __SendInternalBuffer(); #ifndef _IMPROVED_PACKET_ENCRYPTION_ SetSecurityMode(true, (const char *) g_adwEncryptKey, (const char *) g_adwDecryptKey); #endif return true; } bool CPythonNetworkStream::__RecvRunupMatrixQuizPacket() { TPacketGCRunupMatrixQuiz kMatrixQuizPacket; if (!Recv(sizeof(TPacketGCRunupMatrixQuiz), &kMatrixQuizPacket)) return false; PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "BINARY_OnRunupMatrixQuiz", Py_BuildValue("(s)", kMatrixQuizPacket.szQuiz)); return true; } bool CPythonNetworkStream::SendRunupMatrixAnswerPacket(const char * c_szMatrixCardString) { TPacketCGRunupMatrixAnswer answerPacket; //answerPacket.bHeader = HEADER_CG_RUNUP_MATRIX_ANSWER; strncpy(answerPacket.szAnswer, c_szMatrixCardString, RUNUP_MATRIX_ANSWER_MAX_LEN); answerPacket.szAnswer[RUNUP_MATRIX_ANSWER_MAX_LEN] = '\0'; if (!Send(sizeof(answerPacket), &answerPacket)) { TraceError("SendRunupMatrixCardPacketError"); return false; } return SendSequence(); } bool CPythonNetworkStream::__RecvNEWCIBNPasspodRequestPacket() { TPacketGCNEWCIBNPasspodRequest kRequestPacket; if (!Recv(sizeof(kRequestPacket), &kRequestPacket)) return false; PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "BINARY_OnNEWCIBNPasspodRequest", Py_BuildValue("()")); return true; } bool CPythonNetworkStream::__RecvNEWCIBNPasspodFailurePacket() { TPacketGCNEWCIBNPasspodFailure kFailurePacket; if (!Recv(sizeof(kFailurePacket), &kFailurePacket)) return false; PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "BINARY_OnNEWCIBNPasspodFailure", Py_BuildValue("()")); return true; } bool CPythonNetworkStream::SendNEWCIBNPasspodAnswerPacket(const char * answer) { TPacketCGNEWCIBNPasspodAnswer answerPacket; answerPacket.bHeader = HEADER_CG_NEWCIBN_PASSPOD_ANSWER; strncpy(answerPacket.szAnswer, answer, NEWCIBN_PASSPOD_ANSWER_MAX_LEN); answerPacket.szAnswer[NEWCIBN_PASSPOD_ANSWER_MAX_LEN] = '\0'; if (!Send(sizeof(answerPacket), &answerPacket)) { TraceError("SendNEWCIBNPasspodAnswerPacket"); return false; } return SendSequence(); } bool CPythonNetworkStream::SendChinaMatrixCardPacket(const char * c_szMatrixCardString) { TPacketCGChinaMatrixCard MatrixCardPacket; //MatrixCardPacket.bHeader = HEADER_CG_CHINA_MATRIX_CARD; strncpy(MatrixCardPacket.szAnswer, c_szMatrixCardString, CHINA_MATRIX_ANSWER_MAX_LEN); MatrixCardPacket.szAnswer[CHINA_MATRIX_ANSWER_MAX_LEN]='\0'; if (!Send(sizeof(MatrixCardPacket), &MatrixCardPacket)) { Tracen("SendLogin Error"); return false; } m_isWaitLoginKey = TRUE; return SendSequence(); } #define ROW(rows, i) ((rows >> ((4 - i - 1) * 8)) & 0x000000FF) #define COL(cols, i) ((cols >> ((4 - i - 1) * 8)) & 0x000000FF) bool CPythonNetworkStream::__RecvChinaMatrixCardPacket() { TPacketGCChinaMatrixCard kMatrixCardPacket; if (!Recv(sizeof(TPacketGCChinaMatrixCard), &kMatrixCardPacket)) return false; PyObject * pyValue = Py_BuildValue("(iiiiiiii)", ROW(kMatrixCardPacket.dwRows, 0), ROW(kMatrixCardPacket.dwRows, 1), ROW(kMatrixCardPacket.dwRows, 2), ROW(kMatrixCardPacket.dwRows, 3), COL(kMatrixCardPacket.dwCols, 0), COL(kMatrixCardPacket.dwCols, 1), COL(kMatrixCardPacket.dwCols, 2), COL(kMatrixCardPacket.dwCols, 3)); PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_LOGIN], "OnMatrixCard", pyValue); return true; } bool CPythonNetworkStream::__RecvLoginKeyPacket() { TPacketGCLoginKey kLoginKeyPacket; if (!Recv(sizeof(TPacketGCLoginKey), &kLoginKeyPacket)) return false; m_dwLoginKey = kLoginKeyPacket.dwLoginKey; m_isWaitLoginKey = FALSE; return true; }
[ "42899943+MetinRefresh@users.noreply.github.com" ]
42899943+MetinRefresh@users.noreply.github.com
c3e24d4760f169ffa9a1f0bf94e315cbdce2c422
f4b38a2eb5d262a87093252cc0958076ea8857db
/DataStructurePractice/Next.cpp
0e1f6a5b31de4456b325d301429469f5234dc3dd
[]
no_license
zhxhxlzt/DataStructurePractice
0383fa6216bdc77d2c751f72c8e4544f249aa963
276115d4ab92034663aee386b6586e1f930675db
refs/heads/master
2020-03-30T12:20:13.933283
2018-11-01T13:41:21
2018-11-01T13:41:21
151,219,716
0
0
null
2018-11-01T13:41:22
2018-10-02T07:54:47
null
UTF-8
C++
false
false
446
cpp
#include<string.h> #include<iostream> using namespace std; int * buildNext( const char * P ) { size_t m = strlen( P ), j = 0; int * N = new int[m]; int t = N[0] = -1; while( j < m - 1 ) { if( 0 > t || P[j] == P[t] ) N[++j] = ++t; else t = N[t]; } return N; } int main() { const char * P = "abcnabdi"; int *N = buildNext( P ); for( int i = 0; i < strlen( P ); i++ ) { cout << N[i] << endl; } getchar(); return 0; }
[ "2284174996@qq.com" ]
2284174996@qq.com
be79ddf98251d8c6bba8d51170fa2c06e0db8776
2d96f94e59a9e26c6b3e438151765da826f16247
/include/eathread/internal/eathread_atomic_standalone_gcc.h
6e1e2e6f554d6c96a13abe4a63e7a10e7b0cbddf
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
questor/eathread
8e52e830bce1234bee06f437a4e84b4fa0b761b2
5767f201c78b41002fee155c4e85c13d9d1adfe4
refs/heads/master
2022-12-29T20:19:00.420481
2020-10-16T12:15:43
2020-10-16T12:15:43
304,617,022
0
0
null
null
null
null
UTF-8
C++
false
false
18,200
h
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. /////////////////////////////////////////////////////////////////////////////// #if defined(EASTL_PRAGMA_ONCE_SUPPORTED) #pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result. #endif namespace EA { namespace Thread { // TODO(rparolin): Consider use of clang builtin __sync_swap. // https://clang.llvm.org/docs/LanguageExtensions.html#sync-swap // TODO(rparolin): Consider use of C11 atomics // https://clang.llvm.org/docs/LanguageExtensions.html#c11-atomic-builtins namespace detail { template<class T> inline T AtomicGetValue(volatile T* ptr); } // namespace detail // int inline int AtomicGetValue(volatile int* ptr) { return detail::AtomicGetValue(ptr); } inline int AtomicGetValue(const volatile int* ptr) { return AtomicGetValue(const_cast<volatile int*>(ptr)); } inline int AtomicSetValue(volatile int* dest, int value) { return __sync_lock_test_and_set(dest, value); } inline int AtomicFetchIncrement(volatile int* dest) { return __sync_fetch_and_add(dest, int(1)); } inline int AtomicFetchDecrement(volatile int* dest) { return __sync_fetch_and_add(dest, int(-1)); } inline int AtomicFetchAdd(volatile int* dest, int value) { return __sync_fetch_and_add(dest, value); } inline int AtomicFetchSub(volatile int* dest, int value) { return __sync_fetch_and_sub(dest, value); } inline int AtomicFetchOr(volatile int* dest, int value) { return __sync_fetch_and_or(dest, value); } inline int AtomicFetchAnd(volatile int* dest, int value) { return __sync_fetch_and_and(dest, value); } inline int AtomicFetchXor(volatile int* dest, int value) { return __sync_fetch_and_xor(dest, value); } inline int AtomicFetchSwap(volatile int* dest, int value) { return __sync_lock_test_and_set(dest, value); } inline int AtomicFetchSwapConditional(volatile int* dest, int value, int condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile int* dest, int value, int condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // unsigned int inline unsigned int AtomicGetValue(volatile unsigned int* ptr) { return detail::AtomicGetValue(ptr); } inline unsigned int AtomicGetValue(const volatile unsigned int* ptr) { return AtomicGetValue(const_cast<volatile unsigned int*>(ptr)); } inline unsigned int AtomicSetValue(volatile unsigned int* dest, unsigned int value) { return __sync_lock_test_and_set(dest, value); } inline unsigned int AtomicFetchIncrement(volatile unsigned int* dest) { return __sync_fetch_and_add(dest, (unsigned int)(1)); } inline unsigned int AtomicFetchDecrement(volatile unsigned int* dest) { return __sync_fetch_and_add(dest, (unsigned int)(-1)); } inline unsigned int AtomicFetchAdd(volatile unsigned int* dest, unsigned int value) { return __sync_fetch_and_add(dest, value); } inline unsigned int AtomicFetchSub(volatile unsigned int* dest, unsigned int value) { return __sync_fetch_and_sub(dest, value); } inline unsigned int AtomicFetchOr(volatile unsigned int* dest, unsigned int value) { return __sync_fetch_and_or(dest, value); } inline unsigned int AtomicFetchAnd(volatile unsigned int* dest, unsigned int value) { return __sync_fetch_and_and(dest, value); } inline unsigned int AtomicFetchXor(volatile unsigned int* dest, unsigned int value) { return __sync_fetch_and_xor(dest, value); } inline unsigned int AtomicFetchSwap(volatile unsigned int* dest, unsigned int value) { return __sync_lock_test_and_set(dest, value); } inline unsigned int AtomicFetchSwapConditional(volatile unsigned int* dest, unsigned int value, unsigned int condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile unsigned int* dest, unsigned int value, unsigned int condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // short inline short AtomicGetValue(volatile short* ptr) { return detail::AtomicGetValue(ptr); } inline short AtomicGetValue(const volatile short* ptr) { return AtomicGetValue(const_cast<volatile short*>(ptr)); } inline short AtomicSetValue(volatile short* dest, short value) { return __sync_lock_test_and_set(dest, value); } inline short AtomicFetchIncrement(volatile short* dest) { return __sync_fetch_and_add(dest, short(1)); } inline short AtomicFetchDecrement(volatile short* dest) { return __sync_fetch_and_add(dest, short(-1)); } inline short AtomicFetchAdd(volatile short* dest, short value) { return __sync_fetch_and_add(dest, value); } inline short AtomicFetchSub(volatile short* dest, short value) { return __sync_fetch_and_sub(dest, value); } inline short AtomicFetchOr(volatile short* dest, short value) { return __sync_fetch_and_or(dest, value); } inline short AtomicFetchAnd(volatile short* dest, short value) { return __sync_fetch_and_and(dest, value); } inline short AtomicFetchXor(volatile short* dest, short value) { return __sync_fetch_and_xor(dest, value); } inline short AtomicFetchSwap(volatile short* dest, short value) { return __sync_lock_test_and_set(dest, value); } inline short AtomicFetchSwapConditional(volatile short* dest, short value, short condition) { return __sync_val_compare_and_swap(reinterpret_cast<volatile unsigned short*>(dest), static_cast<unsigned short>(condition), static_cast<unsigned short>(value)); } inline bool AtomicSetValueConditional(volatile short* dest, short value, short condition) { return __sync_bool_compare_and_swap(reinterpret_cast<volatile unsigned short*>(dest), static_cast<unsigned short>(condition), static_cast<unsigned short>(value)); } // unsigned short inline unsigned short AtomicGetValue(volatile unsigned short* ptr) { return detail::AtomicGetValue(ptr); } inline unsigned short AtomicGetValue(const volatile unsigned short* ptr) { return AtomicGetValue(const_cast<volatile unsigned short*>(ptr)); } inline unsigned short AtomicSetValue(volatile unsigned short* dest, unsigned short value) { return __sync_lock_test_and_set(dest, value); } inline unsigned short AtomicFetchIncrement(volatile unsigned short* dest) { return __sync_fetch_and_add(dest, (unsigned short)(1)); } inline unsigned short AtomicFetchDecrement(volatile unsigned short* dest) { return __sync_fetch_and_add(dest, (unsigned short)(-1)); } inline unsigned short AtomicFetchAdd(volatile unsigned short* dest, unsigned short value) { return __sync_fetch_and_add(dest, value); } inline unsigned short AtomicFetchSub(volatile unsigned short* dest, unsigned short value) { return __sync_fetch_and_sub(dest, value); } inline unsigned short AtomicFetchOr(volatile unsigned short* dest, unsigned short value) { return __sync_fetch_and_or(dest, value); } inline unsigned short AtomicFetchAnd(volatile unsigned short* dest, unsigned short value) { return __sync_fetch_and_and(dest, value); } inline unsigned short AtomicFetchXor(volatile unsigned short* dest, unsigned short value) { return __sync_fetch_and_xor(dest, value); } inline unsigned short AtomicFetchSwap(volatile unsigned short* dest, unsigned short value) { return __sync_lock_test_and_set(dest, value); } inline unsigned short AtomicFetchSwapConditional(volatile unsigned short* dest, unsigned short value, unsigned short condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile unsigned short* dest, unsigned short value, unsigned short condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // long inline long AtomicGetValue(volatile long* ptr) { return detail::AtomicGetValue(ptr); } inline long AtomicGetValue(const volatile long* ptr) { return AtomicGetValue(const_cast<volatile long*>(ptr)); } inline long AtomicSetValue(volatile long* dest, long value) { return __sync_lock_test_and_set(dest, value); } inline long AtomicFetchIncrement(volatile long* dest) { return __sync_fetch_and_add(dest, long(1)); } inline long AtomicFetchDecrement(volatile long* dest) { return __sync_fetch_and_add(dest, long(-1)); } inline long AtomicFetchAdd(volatile long* dest, long value) { return __sync_fetch_and_add(dest, value); } inline long AtomicFetchSub(volatile long* dest, long value) { return __sync_fetch_and_sub(dest, value); } inline long AtomicFetchOr(volatile long* dest, long value) { return __sync_fetch_and_or(dest, value); } inline long AtomicFetchAnd(volatile long* dest, long value) { return __sync_fetch_and_and(dest, value); } inline long AtomicFetchXor(volatile long* dest, long value) { return __sync_fetch_and_xor(dest, value); } inline long AtomicFetchSwap(volatile long* dest, long value) { return __sync_lock_test_and_set(dest, value); } inline long AtomicFetchSwapConditional(volatile long* dest, long value, long condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile long* dest, long value, long condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // unsigned long inline unsigned long AtomicGetValue(volatile unsigned long* ptr) { return detail::AtomicGetValue(ptr); } inline unsigned long AtomicGetValue(const volatile unsigned long* ptr) { return AtomicGetValue(const_cast<volatile unsigned long*>(ptr)); } inline unsigned long AtomicSetValue(volatile unsigned long* dest, unsigned long value) { return __sync_lock_test_and_set(dest, value); } inline unsigned long AtomicFetchIncrement(volatile unsigned long* dest) { return __sync_fetch_and_add(dest, (unsigned long)(1)); } inline unsigned long AtomicFetchDecrement(volatile unsigned long* dest) { return __sync_fetch_and_add(dest, (unsigned long)(-1)); } inline unsigned long AtomicFetchAdd(volatile unsigned long* dest, unsigned long value) { return __sync_fetch_and_add(dest, value); } inline unsigned long AtomicFetchSub(volatile unsigned long* dest, unsigned long value) { return __sync_fetch_and_sub(dest, value); } inline unsigned long AtomicFetchOr(volatile unsigned long* dest, unsigned long value) { return __sync_fetch_and_or(dest, value); } inline unsigned long AtomicFetchAnd(volatile unsigned long* dest, unsigned long value) { return __sync_fetch_and_and(dest, value); } inline unsigned long AtomicFetchXor(volatile unsigned long* dest, unsigned long value) { return __sync_fetch_and_xor(dest, value); } inline unsigned long AtomicFetchSwap(volatile unsigned long* dest, unsigned long value) { return __sync_lock_test_and_set(dest, value); } inline unsigned long AtomicFetchSwapConditional(volatile unsigned long* dest, unsigned long value, unsigned long condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile unsigned long* dest, unsigned long value, unsigned long condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // char32_t #if EASTL_CHAR32_NATIVE inline char32_t AtomicGetValue(volatile char32_t* ptr) { return detail::AtomicGetValue(ptr); } inline char32_t AtomicGetValue(const volatile char32_t* ptr) { return AtomicGetValue(const_cast<volatile char32_t*>(ptr)); } inline char32_t AtomicSetValue(volatile char32_t* dest, char32_t value) { return __sync_lock_test_and_set(dest, value); } inline char32_t AtomicFetchIncrement(volatile char32_t* dest) { return __sync_fetch_and_add(dest, char32_t(1)); } inline char32_t AtomicFetchDecrement(volatile char32_t* dest) { return __sync_fetch_and_add(dest, char32_t(-1)); } inline char32_t AtomicFetchAdd(volatile char32_t* dest, char32_t value) { return __sync_fetch_and_add(dest, value); } inline char32_t AtomicFetchSub(volatile char32_t* dest, char32_t value) { return __sync_fetch_and_sub(dest, value); } inline char32_t AtomicFetchOr(volatile char32_t* dest, char32_t value) { return __sync_fetch_and_or(dest, value); } inline char32_t AtomicFetchAnd(volatile char32_t* dest, char32_t value) { return __sync_fetch_and_and(dest, value); } inline char32_t AtomicFetchXor(volatile char32_t* dest, char32_t value) { return __sync_fetch_and_xor(dest, value); } inline char32_t AtomicFetchSwap(volatile char32_t* dest, char32_t value) { return __sync_lock_test_and_set(dest, value); } inline char32_t AtomicFetchSwapConditional(volatile char32_t* dest, char32_t value, char32_t condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile char32_t* dest, char32_t value, char32_t condition) { return __sync_bool_compare_and_swap(dest, condition, value); } #endif // long long inline long long AtomicGetValue(volatile long long* ptr) { return detail::AtomicGetValue(ptr); } inline long long AtomicGetValue(const volatile long long* ptr) { return AtomicGetValue(const_cast<volatile long long*>(ptr)); } inline long long AtomicSetValue(volatile long long* dest, long long value) { return __sync_lock_test_and_set(dest, value); } inline long long AtomicFetchIncrement(volatile long long* dest) { return __sync_fetch_and_add(dest, (long long)(1)); } inline long long AtomicFetchDecrement(volatile long long* dest) { return __sync_fetch_and_add(dest, (long long)(-1)); } inline long long AtomicFetchAdd(volatile long long* dest, long long value) { return __sync_fetch_and_add(dest, value); } inline long long AtomicFetchSub(volatile long long* dest, long long value) { return __sync_fetch_and_sub(dest, value); } inline long long AtomicFetchOr(volatile long long* dest, long long value) { return __sync_fetch_and_or(dest, value); } inline long long AtomicFetchAnd(volatile long long* dest, long long value) { return __sync_fetch_and_and(dest, value); } inline long long AtomicFetchXor(volatile long long* dest, long long value) { return __sync_fetch_and_xor(dest, value); } inline long long AtomicFetchSwap(volatile long long* dest, long long value) { return __sync_lock_test_and_set(dest, value); } inline long long AtomicFetchSwapConditional(volatile long long* dest, long long value, long long condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile long long* dest, long long value, long long condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // unsigned long long inline unsigned long long AtomicGetValue(volatile unsigned long long* ptr) { return detail::AtomicGetValue(ptr); } inline unsigned long long AtomicGetValue(const volatile unsigned long long* ptr) { return AtomicGetValue(const_cast<volatile unsigned long long*>(ptr)); } inline unsigned long long AtomicSetValue(volatile unsigned long long* dest, unsigned long long value) { return __sync_lock_test_and_set(dest, value); } inline unsigned long long AtomicFetchIncrement(volatile unsigned long long* dest) { return __sync_fetch_and_add(dest, (unsigned long long)(1)); } inline unsigned long long AtomicFetchDecrement(volatile unsigned long long* dest) { return __sync_fetch_and_add(dest, (unsigned long long)(-1)); } inline unsigned long long AtomicFetchAdd(volatile unsigned long long* dest, unsigned long long value) { return __sync_fetch_and_add(dest, value); } inline unsigned long long AtomicFetchSub(volatile unsigned long long* dest, unsigned long long value) { return __sync_fetch_and_sub(dest, value); } inline unsigned long long AtomicFetchOr(volatile unsigned long long* dest, unsigned long long value) { return __sync_fetch_and_or(dest, value); } inline unsigned long long AtomicFetchAnd(volatile unsigned long long* dest, unsigned long long value) { return __sync_fetch_and_and(dest, value); } inline unsigned long long AtomicFetchXor(volatile unsigned long long* dest, unsigned long long value) { return __sync_fetch_and_xor(dest, value); } inline unsigned long long AtomicFetchSwap(volatile unsigned long long* dest, unsigned long long value) { return __sync_lock_test_and_set(dest, value); } inline unsigned long long AtomicFetchSwapConditional(volatile unsigned long long* dest, unsigned long long value, unsigned long long condition) { return __sync_val_compare_and_swap(dest, condition, value); } inline bool AtomicSetValueConditional(volatile unsigned long long* dest, unsigned long long value, unsigned long long condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // // You can not simply define a template for the above atomics due to the explicit 128bit overloads // below. The compiler will prefer those overloads during overload resolution and attempt to convert // temporaries as they are more specialized than a template. // // template<typename T> inline T AtomicGetValue(volatile T* source) { return __sync_fetch_and_add(source, (T)(0)); } // template<typename T> inline void AtomicSetValue(volatile T* dest, T value) { __sync_lock_test_and_set(dest, value); } // template<typename T> inline T AtomicFetchIncrement(volatile T* dest) { return __sync_fetch_and_add(dest, (T)(1)); } // template<typename T> inline T AtomicFetchDecrement(volatile T* dest) { return __sync_fetch_and_add(dest, (T)(-1)); } // template<typename T> inline T AtomicFetchAdd(volatile T* dest, T value) { return __sync_fetch_and_add(dest, value); } // template<typename T> inline T AtomicFetchOr(volatile T* dest, T value) { return __sync_fetch_and_or(dest, value); } // template<typename T> inline T AtomicFetchAnd(volatile T* dest, T value) { return __sync_fetch_and_and(dest, value); } // template<typename T> inline T AtomicFetchXor(volatile T* dest, T value) { return __sync_fetch_and_xor(dest, value); } // template<typename T> inline T AtomicFetchSwap(volatile T* dest, T value) { return __sync_lock_test_and_set(dest, value); } // template<typename T> inline bool AtomicSetValueConditional(volatile T* dest, T value, T condition) { return __sync_bool_compare_and_swap(dest, condition, value); } // namespace detail { template<class T> inline T AtomicGetValue(volatile T* ptr) { #if EA_PLATFORM_WORD_SIZE >= 8 && defined(EA_PROCESSOR_X86_64) EATHREAD_ALIGNMENT_CHECK(ptr); EACompilerMemoryBarrier(); T value = *ptr; EACompilerMemoryBarrier(); return value; #else return AtomicFetchAdd(ptr, T(0)); #endif } } // namespace detail } // namespace Thread } // namespace EA
[ "questor@inter" ]
questor@inter
cc26703913b140b51718f3d409680f007f307906
e272a9c0b27f445a21c007723b821a262a43531a
/SimplePhotoViewer/Win2D/winrt/impl/Microsoft.Graphics.Canvas.Geometry.2.h
0a420389dfb3b44a0dc4fa05de760a394611e617
[ "MIT" ]
permissive
Hearwindsaying/SimplePhotoViewer
777facb3b6c18e0747da2f70b02fff6c481a2168
12d9cd383d379ebce6696263af58c93a2769073b
refs/heads/master
2021-11-05T17:41:29.288860
2021-10-31T11:04:36
2021-10-31T11:04:36
176,699,093
3
2
null
null
null
null
UTF-8
C++
false
false
10,610
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v1.0.180821.2 #pragma once #include "Microsoft.Graphics.Canvas.1.h" #include "Microsoft.Graphics.Canvas.Text.1.h" #include "winrt/impl/Windows.UI.Input.Inking.1.h" #include "winrt/impl/Windows.Foundation.1.h" #include "winrt/impl/Windows.Graphics.1.h" #include "Microsoft.Graphics.Canvas.Geometry.1.h" WINRT_EXPORT namespace winrt::Microsoft::Graphics::Canvas::Geometry { struct CanvasGradientMeshPatch { Windows::Foundation::Numerics::float2 Point00; Windows::Foundation::Numerics::float2 Point01; Windows::Foundation::Numerics::float2 Point02; Windows::Foundation::Numerics::float2 Point03; Windows::Foundation::Numerics::float2 Point10; Windows::Foundation::Numerics::float2 Point11; Windows::Foundation::Numerics::float2 Point12; Windows::Foundation::Numerics::float2 Point13; Windows::Foundation::Numerics::float2 Point20; Windows::Foundation::Numerics::float2 Point21; Windows::Foundation::Numerics::float2 Point22; Windows::Foundation::Numerics::float2 Point23; Windows::Foundation::Numerics::float2 Point30; Windows::Foundation::Numerics::float2 Point31; Windows::Foundation::Numerics::float2 Point32; Windows::Foundation::Numerics::float2 Point33; Windows::Foundation::Numerics::float4 Color00; Windows::Foundation::Numerics::float4 Color03; Windows::Foundation::Numerics::float4 Color30; Windows::Foundation::Numerics::float4 Color33; Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge Edge00To03; Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge Edge03To33; Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge Edge33To30; Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge Edge30To00; }; inline bool operator==(CanvasGradientMeshPatch const& left, CanvasGradientMeshPatch const& right) noexcept { return left.Point00 == right.Point00 && left.Point01 == right.Point01 && left.Point02 == right.Point02 && left.Point03 == right.Point03 && left.Point10 == right.Point10 && left.Point11 == right.Point11 && left.Point12 == right.Point12 && left.Point13 == right.Point13 && left.Point20 == right.Point20 && left.Point21 == right.Point21 && left.Point22 == right.Point22 && left.Point23 == right.Point23 && left.Point30 == right.Point30 && left.Point31 == right.Point31 && left.Point32 == right.Point32 && left.Point33 == right.Point33 && left.Color00 == right.Color00 && left.Color03 == right.Color03 && left.Color30 == right.Color30 && left.Color33 == right.Color33 && left.Edge00To03 == right.Edge00To03 && left.Edge03To33 == right.Edge03To33 && left.Edge33To30 == right.Edge33To30 && left.Edge30To00 == right.Edge30To00; } inline bool operator!=(CanvasGradientMeshPatch const& left, CanvasGradientMeshPatch const& right) noexcept { return !(left == right); } struct CanvasTriangleVertices { Windows::Foundation::Numerics::float2 Vertex1; Windows::Foundation::Numerics::float2 Vertex2; Windows::Foundation::Numerics::float2 Vertex3; }; inline bool operator==(CanvasTriangleVertices const& left, CanvasTriangleVertices const& right) noexcept { return left.Vertex1 == right.Vertex1 && left.Vertex2 == right.Vertex2 && left.Vertex3 == right.Vertex3; } inline bool operator!=(CanvasTriangleVertices const& left, CanvasTriangleVertices const& right) noexcept { return !(left == right); } } namespace winrt::impl { } WINRT_EXPORT namespace winrt::Microsoft::Graphics::Canvas::Geometry { struct WINRT_EBO CanvasCachedGeometry : Microsoft::Graphics::Canvas::Geometry::ICanvasCachedGeometry { CanvasCachedGeometry(std::nullptr_t) noexcept {} static Microsoft::Graphics::Canvas::Geometry::CanvasCachedGeometry CreateFill(Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const& geometry); static Microsoft::Graphics::Canvas::Geometry::CanvasCachedGeometry CreateFill(Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const& geometry, float flatteningTolerance); static Microsoft::Graphics::Canvas::Geometry::CanvasCachedGeometry CreateStroke(Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const& geometry, float strokeWidth); static Microsoft::Graphics::Canvas::Geometry::CanvasCachedGeometry CreateStroke(Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const& geometry, float strokeWidth, Microsoft::Graphics::Canvas::Geometry::CanvasStrokeStyle const& strokeStyle); static Microsoft::Graphics::Canvas::Geometry::CanvasCachedGeometry CreateStroke(Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const& geometry, float strokeWidth, Microsoft::Graphics::Canvas::Geometry::CanvasStrokeStyle const& strokeStyle, float flatteningTolerance); }; struct WINRT_EBO CanvasGeometry : Microsoft::Graphics::Canvas::Geometry::ICanvasGeometry, impl::require<CanvasGeometry, Windows::Graphics::IGeometrySource2D> { CanvasGeometry(std::nullptr_t) noexcept {} static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateRectangle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, Windows::Foundation::Rect const& rect); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateRectangle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, float x, float y, float w, float h); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateRoundedRectangle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, Windows::Foundation::Rect const& rect, float radiusX, float radiusY); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateRoundedRectangle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, float x, float y, float w, float h, float radiusX, float radiusY); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateEllipse(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, Windows::Foundation::Numerics::float2 const& centerPoint, float radiusX, float radiusY); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateEllipse(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, float x, float y, float radiusX, float radiusY); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateCircle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, Windows::Foundation::Numerics::float2 const& centerPoint, float radius); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateCircle(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, float x, float y, float radius); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreatePath(Microsoft::Graphics::Canvas::Geometry::CanvasPathBuilder const& pathBuilder); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreatePolygon(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, array_view<Windows::Foundation::Numerics::float2 const> points); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateGroup(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, array_view<Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const> geometries); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateGroup(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, array_view<Microsoft::Graphics::Canvas::Geometry::CanvasGeometry const> geometries, Microsoft::Graphics::Canvas::Geometry::CanvasFilledRegionDetermination const& filledRegionDetermination); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateText(Microsoft::Graphics::Canvas::Text::CanvasTextLayout const& textLayout); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateGlyphRun(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, Windows::Foundation::Numerics::float2 const& point, Microsoft::Graphics::Canvas::Text::CanvasFontFace const& fontFace, float fontSize, array_view<Microsoft::Graphics::Canvas::Text::CanvasGlyph const> glyphs, bool isSideways, uint32_t bidiLevel, Microsoft::Graphics::Canvas::Text::CanvasTextMeasuringMode const& measuringMode, Microsoft::Graphics::Canvas::Text::CanvasGlyphOrientation const& glyphOrientation); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateInk(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, param::iterable<Windows::UI::Input::Inking::InkStroke> const& inkStrokes); static Microsoft::Graphics::Canvas::Geometry::CanvasGeometry CreateInk(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, param::iterable<Windows::UI::Input::Inking::InkStroke> const& inkStrokes, Windows::Foundation::Numerics::float3x2 const& transform, float flatteningTolerance); static float ComputeFlatteningTolerance(float dpi, float maximumZoomFactor); static float ComputeFlatteningTolerance(float dpi, float maximumZoomFactor, Windows::Foundation::Numerics::float3x2 const& expectedGeometryTransform); static float DefaultFlatteningTolerance(); }; struct WINRT_EBO CanvasGradientMesh : Microsoft::Graphics::Canvas::Geometry::ICanvasGradientMesh { CanvasGradientMesh(std::nullptr_t) noexcept {} CanvasGradientMesh(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator, array_view<Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatch const> patchElements); static Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatch CreateCoonsPatch(array_view<Windows::Foundation::Numerics::float2 const> points, array_view<Windows::Foundation::Numerics::float4 const> colors, array_view<Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge const> edges); static Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatch CreateTensorPatch(array_view<Windows::Foundation::Numerics::float2 const> points, array_view<Windows::Foundation::Numerics::float4 const> colors, array_view<Microsoft::Graphics::Canvas::Geometry::CanvasGradientMeshPatchEdge const> edges); }; struct WINRT_EBO CanvasPathBuilder : Microsoft::Graphics::Canvas::Geometry::ICanvasPathBuilder { CanvasPathBuilder(std::nullptr_t) noexcept {} CanvasPathBuilder(Microsoft::Graphics::Canvas::ICanvasResourceCreator const& resourceCreator); }; struct WINRT_EBO CanvasStrokeStyle : Microsoft::Graphics::Canvas::Geometry::ICanvasStrokeStyle { CanvasStrokeStyle(std::nullptr_t) noexcept {} CanvasStrokeStyle(); }; }
[ "hearwindsaying@gmail.com" ]
hearwindsaying@gmail.com
e7cd7ede4f8cd22123702d19a653545bf4635d43
71ffbf8cec50696a720fcabcd8b0d9df4fffd4a1
/masstree/query_masstree.cc
26f0211ab8a2f64a22ba5219202172b75a28f007
[ "MIT", "W3C", "LicenseRef-scancode-click-license" ]
permissive
huanchenz/masstree_lib_test
84e523225c85ab0e2a7932c11ec451b126c84d1f
7bd441cf54c9252c45770624abef810e7e9065f6
refs/heads/master
2020-04-06T06:40:57.693354
2014-08-13T16:04:36
2014-08-13T16:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,001
cc
/* Masstree * Eddie Kohler, Yandong Mao, Robert Morris * Copyright (c) 2012-2014 President and Fellows of Harvard College * Copyright (c) 2012-2014 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Masstree LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Masstree LICENSE file; the license in that file * is legally binding. */ #include "masstree.hh" #include "masstree_key.hh" #include "masstree_struct.hh" #include "masstree_tcursor.hh" #include "masstree_get.hh" #include "masstree_insert.hh" #include "masstree_split.hh" #include "masstree_remove.hh" #include "masstree_scan.hh" #include "masstree_print.hh" #include "query_masstree.hh" #include "string_slice.hh" #include "kpermuter.hh" #include "ksearch.hh" #include "stringbag.hh" #include "json.hh" #include "kvrow.hh" namespace Masstree { static uint64_t heightcounts[300], fillcounts[100]; template <typename P> static void treestats1(node_base<P>* n, unsigned height) { if (!n) return; if (n->isleaf()) { assert(height < arraysize(heightcounts)); if (n->deleted()) return; leaf<P> *lf = (leaf<P> *)n; typename leaf<P>::permuter_type perm = lf->permutation_; for (int idx = 0; idx < perm.size(); ++idx) { int p = perm[idx]; typename leaf<P>::leafvalue_type lv = lf->lv_[p]; if (!lv || !lf->value_is_layer(p)) heightcounts[height] ++; else { node_base<P> *in = lv.layer()->unsplit_ancestor(); treestats1(in, height + 1); } } } else { internode<P> *in = (internode<P> *) n; for (int i = 0; i <= n->size(); ++i) if (in->child_[i]) treestats1(in->child_[i], height + 1); } assert((size_t) n->size() < arraysize(fillcounts)); fillcounts[n->size()] += 1; } template <typename P> void query_table<P>::stats(FILE* f) { memset(heightcounts, 0, sizeof(heightcounts)); memset(fillcounts, 0, sizeof(fillcounts)); treestats1(table_.root(), 0); fprintf(f, " heights:"); for (unsigned i = 0; i < arraysize(heightcounts); ++i) if (heightcounts[i]) fprintf(f, " %d=%" PRIu64, i, heightcounts[i]); fprintf(f, "\n node counts:"); for (unsigned i = 0; i < arraysize(fillcounts); ++i) if (fillcounts[i]) fprintf(f, " %d=%" PRIu64, i, fillcounts[i]); fprintf(f, "\n"); } template <typename P> static void json_stats1(node_base<P>* n, lcdf::Json& j, int layer, int depth, threadinfo& ti) { if (!n) return; else if (n->isleaf()) { leaf<P>* lf = static_cast<leaf<P>*>(n); // track number of leaves by depth and size j[&"l1_node_by_depth"[!layer * 3]][depth] += 1; j[&"l1_leaf_by_depth"[!layer * 3]][depth] += 1; j[&"l1_leaf_by_size"[!layer * 3]][lf->size()] += 1; // per-key information typename leaf<P>::permuter_type perm(lf->permutation_); int n = 0, nksuf = 0; size_t active_ksuf_len = 0; for (int i = 0; i < perm.size(); ++i) if (lf->value_is_layer(perm[i])) { lcdf::Json x = j["l1_size"]; j["l1_size"] = 0; json_stats1(lf->lv_[perm[i]].layer(), j, layer + 1, 0, ti); j["l1_size_sum"] += j["l1_size"].to_i(); j["l1_size"] = x; j["l1_count"] += 1; } else { ++n; int l = sizeof(typename P::ikey_type) * layer + lf->keylenx_[perm[i]]; if (lf->has_ksuf(perm[i])) { size_t ksuf_len = lf->ksuf(perm[i]).len; l += ksuf_len - 1; active_ksuf_len += ksuf_len; ++nksuf; } j["key_by_length"][l] += 1; } assert(lf->nksuf_ == nksuf); j["size"] += n; j["l1_size"] += n; j["key_by_layer"][layer] += n; // key suffix information if (lf->allocated_size() != lf->min_allocated_size() && lf->ksuf_external()) { j["overridden_ksuf"] += 1; j["overridden_ksuf_capacity"] += lf->allocated_size() - lf->min_allocated_size(); } if (lf->ksuf_capacity()) { j["ksuf"] += 1; j["ksuf_capacity"] += lf->ksuf_capacity(); j["ksuf_len"] += active_ksuf_len; j["ksuf_by_layer"][layer] += 1; if (!active_ksuf_len) { j["unused_ksuf_capacity"] += lf->ksuf_capacity(); j["unused_ksuf_by_layer"][layer] += 1; if (lf->ksuf_external()) j["unused_ksuf_external"] += 1; } else j["used_ksuf_by_layer"][layer] += 1; } } else { internode<P> *in = static_cast<internode<P> *>(n); for (int i = 0; i <= n->size(); ++i) if (in->child_[i]) json_stats1(in->child_[i], j, layer, depth + 1, ti); j[&"l1_node_by_depth"[!layer * 3]][depth] += 1; } } template <typename P> void query_table<P>::json_stats(lcdf::Json& j, threadinfo& ti) { using lcdf::Json; j["size"] = 0.0; j["l1_count"] = 0; j["l1_size"] = 0; const char* jarrays[] = { "node_by_depth", "leaf_by_depth", "leaf_by_size", "l1_node_by_depth", "l1_leaf_by_depth", "l1_leaf_by_size", "key_by_layer", "key_by_length", "ksuf_by_layer", "unused_ksuf_by_layer", "used_ksuf_by_layer" }; for (const char** x = jarrays; x != jarrays + sizeof(jarrays) / sizeof(*jarrays); ++x) j[*x] = Json::make_array(); json_stats1(table_.root(), j, 0, 0, ti); j.unset("l1_size"); for (const char** x = jarrays; x != jarrays + sizeof(jarrays) / sizeof(*jarrays); ++x) { Json& a = j[*x]; for (Json* it = a.array_data(); it != a.end_array_data(); ++it) if (!*it) *it = Json((size_t) 0); if (a.empty()) j.unset(*x); } } template <typename N> static Str findpv(N *n, int pvi, int npv) { // XXX assumes that most keys differ in the low bytes // XXX will fail badly if all keys have the same prefix // XXX not clear what to do then int nbranch = 1, branchid = 0; typedef typename N::internode_type internode_type; typedef typename N::leaf_type leaf_type; n = n->unsplit_ancestor(); while (1) { typename N::nodeversion_type v = n->stable(); int size = n->size() + !n->isleaf(); if (size == 0) return Str(); int total_nkeys_estimate = nbranch * size; int first_pv_in_node = branchid * size; int pv_offset = pvi * total_nkeys_estimate / npv - first_pv_in_node; if (!n->isleaf() && total_nkeys_estimate < npv) { internode_type *in = static_cast<internode_type *>(n); pv_offset = std::min(std::max(pv_offset, 0), size - 1); N *next = in->child_[pv_offset]; if (!n->has_changed(v)) { nbranch = total_nkeys_estimate; branchid = first_pv_in_node + pv_offset; n = next; } continue; } pv_offset = std::min(std::max(pv_offset, 0), size - 1 - !n->isleaf()); typename N::ikey_type ikey0; if (n->isleaf()) { leaf_type *l = static_cast<leaf_type *>(n); typename leaf_type::permuter_type perm = l->permutation(); ikey0 = l->ikey0_[perm[pv_offset]]; } else { internode_type *in = static_cast<internode_type *>(n); ikey0 = in->ikey0_[pv_offset]; } if (!n->has_changed(v)) { char *x = (char *) malloc(sizeof(ikey0)); int len = string_slice<typename N::ikey_type>::unparse_comparable(x, sizeof(ikey0), ikey0); return Str(x, len); } } } // findpivots should allocate memory for pv[i]->s, which will be // freed by the caller. template <typename P> void query_table<P>::findpivots(Str *pv, int npv) const { pv[0].assign(NULL, 0); char *cmaxk = (char *)malloc(MASSTREE_MAXKEYLEN); memset(cmaxk, 255, MASSTREE_MAXKEYLEN); pv[npv - 1].assign(cmaxk, MASSTREE_MAXKEYLEN); for (int i = 1; i < npv - 1; i++) pv[i] = findpv(table_.root(), i, npv - 1); } namespace { struct scan_tester { const char * const *vbegin_, * const *vend_; char key_[32]; int keylen_; bool reverse_; bool first_; scan_tester(const char * const *vbegin, const char * const *vend, bool reverse = false) : vbegin_(vbegin), vend_(vend), keylen_(0), reverse_(reverse), first_(true) { if (reverse_) { memset(key_, 255, sizeof(key_)); keylen_ = sizeof(key_); } } template <typename SS, typename K> void visit_leaf(const SS&, const K&, threadinfo&) { } bool visit_value(Str key, row_type*, threadinfo&) { memcpy(key_, key.s, key.len); keylen_ = key.len; const char *pos = (reverse_ ? vend_[-1] : vbegin_[0]); if ((int) strlen(pos) != key.len || memcmp(pos, key.s, key.len) != 0) { fprintf(stderr, "%sscan encountered %.*s, expected %s\n", reverse_ ? "r" : "", key.len, key.s, pos); assert((int) strlen(pos) == key.len && memcmp(pos, key.s, key.len) == 0); } fprintf(stderr, "%sscan %.*s\n", reverse_ ? "r" : "", key.len, key.s); (reverse_ ? --vend_ : ++vbegin_); first_ = false; return vbegin_ != vend_; } template <typename T> int scan(T& table, threadinfo& ti) { return table.table().scan(Str(key_, keylen_), first_, *this, ti); } template <typename T> int rscan(T& table, threadinfo& ti) { return table.table().rscan(Str(key_, keylen_), first_, *this, ti); } }; } template <typename P> void query_table<P>::test(threadinfo& ti) { query_table<P> t; t.initialize(ti); query<row_type> q; const char * const values[] = { "", "0", "1", "10", "100000000", // 0-4 "1000000001", "1000000002", "2", "20", "200000000", // 5-9 "aaaaaaaaaaaaaaaaaaaaaaaaaa", // 10 "aaaaaaaaaaaaaaabbbb", "aaaaaaaaaaaaaaabbbc", "aaaaaaaaaxaaaaabbbc", "b", "c", "d", "e", "f", "g", "h", "i", "j", "kkkkkkkk\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "a", "kkkkkkkk\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "b", "xxxxxxxxy" }; const char * const *end_values = values + arraysize(values); const char *values_copy[arraysize(values)]; memcpy(values_copy, values, sizeof(values)); for (int i = arraysize(values); i > 0; --i) { int x = rand() % i; q.run_replace(t.table(), Str(values_copy[x]), Str(values_copy[x]), ti); values_copy[x] = values_copy[i - 1]; } t.table_.print(); printf("\n"); scan_tester scanner(values, values + 3); while (scanner.scan(t, ti)) { scanner.vend_ = std::min(scanner.vend_ + 3, end_values); fprintf(stderr, "-scanbreak-\n"); } scanner = scan_tester(values, values + 8); while (scanner.scan(t, ti)) { scanner.vend_ = std::min(scanner.vend_ + 8, end_values); fprintf(stderr, "-scanbreak-\n"); } scanner = scan_tester(values + 10, values + 11); int r = t.table_.scan(Str(values[10]), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 10, values + 11); r = t.table_.scan(Str(values[10] + 1), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 11, values + 12); r = t.table_.scan(Str(values[10]), false, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 10, values + 11); r = t.table_.scan(Str("aaaaaaaaaaaaaaaaaaaaaaaaaZ"), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 11, values + 12); r = t.table_.scan(Str(values[11]), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 12, values + 13); r = t.table_.scan(Str(values[11]), false, scanner, ti); always_assert(r == 1); scanner = scan_tester(end_values - 3, end_values, true); while (scanner.rscan(t, ti)) { scanner.vbegin_ = std::max(scanner.vbegin_ - 3, (const char * const *) values); fprintf(stderr, "-scanbreak-\n"); } scanner = scan_tester(end_values - 2, end_values, true); r = scanner.rscan(t, ti); always_assert(r == 2); scanner.vbegin_ = std::max(scanner.vbegin_ - 2, (const char * const *) values); fprintf(stderr, "-scanbreak-\n"); r = scanner.rscan(t, ti); always_assert(r == 2); scanner = scan_tester(end_values - 8, end_values, true); while (scanner.rscan(t, ti)) { scanner.vbegin_ = std::max(scanner.vbegin_ - 8, (const char * const *) values); fprintf(stderr, "-scanbreak-\n"); } scanner = scan_tester(values + 10, values + 11); r = t.table_.rscan(Str(values[10]), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 10, values + 11); r = t.table_.rscan(Str("aaaaaaaaaaaaaaaaaaaaaaaaab"), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 9, values + 10); r = t.table_.rscan(Str(values[10]), false, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 10, values + 11); r = t.table_.rscan(Str("aaaaaaaaaaaaaaaaaaaaaaaaab"), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 11, values + 12); r = t.table_.rscan(Str(values[11]), true, scanner, ti); always_assert(r == 1); scanner = scan_tester(values + 10, values + 11); r = t.table_.rscan(Str(values[11]), false, scanner, ti); always_assert(r == 1); Str pv[10]; t.findpivots(pv, 10); for (int i = 0; i < 10; ++i) { fprintf(stderr, "%d >%.*s<\n", i, std::min(pv[i].len, 10), pv[i].s); free((char *)pv[i].s); } t.findpivots(pv, 4); for (int i = 0; i < 4; ++i) { fprintf(stderr, "%d >%.*s<\n", i, std::min(pv[i].len, 10), pv[i].s); free((char *)pv[i].s); } // XXX destroy tree } template <typename P> void query_table<P>::print(FILE *f, int indent) const { table_.print(f, indent); } template class basic_table<default_table::param_type>; template class query_table<default_table::param_type>; }
[ "huanchenzhang.cs@gmail.com" ]
huanchenzhang.cs@gmail.com
b417b13550213e044344ca7617dfe7ff0cfb89fc
bda9007e163ef35ea8d736660adfb540c31c2007
/src/TelloDrone.h
0c3e53593a08c9b42ce731c4ab1711f529071455
[]
no_license
ThanosKand/ESP32-TelloDrone
65953ca01242edc00174a17f7def427bda64da76
92791fb62d35898d91d1c706e971e34d20438ca0
refs/heads/master
2020-08-18T17:02:43.830228
2019-09-10T13:26:34
2019-09-10T13:26:34
215,813,262
1
0
null
null
null
null
UTF-8
C++
false
false
733
h
#include <WiFi.h> #include <WiFiUdp.h> #include <string.h> using namespace std; class TelloDrone { public: boolean connected; TelloDrone(); string sendMessage(string message); void printWifiStatus(); void connect(const char* ssid, const char* password); void sendCommand(string message); string getResponse(); const char* networkName; const char* networkPswd; private: //const char * networkName = "tello2"; //const char * networkPswd = "";' void WiFiEvent(WiFiEvent_t event, system_event_info_t info); WiFiUDP udp; const char * udpAddress = "192.168.10.1"; const int udpPort = 8889; };
[ "ev@evang.dk" ]
ev@evang.dk
92b00fe9540587f631c8cad45a67d004e44c91fb
afec113dcac49a1f341d42be821973755051e103
/sedata/CDataFieldList.h
da7028079971ad11b7e3da0798c508b3e15c65c3
[]
no_license
radtek/earnsmart
e080bafa824bf2728fbf8603d46c11430d77cfb6
df3983366a993d1e5ba0167d2483c3eb799b25be
refs/heads/master
2020-06-22T06:14:04.646933
2019-02-15T13:32:59
2019-02-15T13:32:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,845
h
/* * File: CDataFieldList.h * Author: santony * * Created on December 4, 2012, 7:16 AM */ #ifndef CDATAFIELDLIST_H #define CDATAFIELDLIST_H #include <map> #include <tuple> #include <string> #include "../seglobal/CObjectRoot.h" #include "../seglobaltypedefs.h" using namespace std; namespace se { namespace data { class CDataTable; typedef std::tuple<string, DATATYPES> FIELDINFO; class CDataFieldList : public CObjectRoot { public: CDataFieldList(ISession*); // only datatable can create this instance. CDataFieldList(CDataFieldList&&); public: CDataFieldList(const CDataFieldList& orig); virtual ~CDataFieldList(); U32 AddField(string fieldName, DATATYPES dataType); void RemoveField(const string& fieldName); void RemoveField(U32 fieldId); DATATYPES get_Type(const string& fieldName); CDataFieldList& operator=(CDataFieldList&&); CDataFieldList& operator=(const CDataFieldList&); const string& get_FieldName(U32 ) const; U32 get_FieldId(const string&) const; bool TryGetFieldId(const string&, U32* fieldId); bool get_HasField(const string&) const; SIZE get_Size() const { return _fields.size() ; } private: friend class CDataTable; typedef string FIELDNAME; typedef map<U32, FIELDINFO> FIELDSINFO; typedef map<string, U32> FIELDINDEXNAMEMAP; FIELDSINFO _fields; FIELDINDEXNAMEMAP _fieldMap; string _empty; }; } } #endif /* CDATAFIELDLIST_H */
[ "sajiantony@hotmail.com" ]
sajiantony@hotmail.com
00e56fc431ea371ad7b045d127b9ebb89bf8c097
2adefd33aecc07419d8d7f970a805f441bd1171d
/20160429/for_each.cc
e6e82c20615603ae28a9146cf85511fc52d5281d
[]
no_license
lcybelieveme/26042016
c077a55007d7fdd00d5df97f7bbb297642fb4661
8db21b58336ea285eb0d7b4a556f9f18dc549747
refs/heads/master
2021-01-01T05:19:47.718107
2016-05-01T03:12:38
2016-05-01T03:12:38
57,113,111
0
0
null
null
null
null
UTF-8
C++
false
false
611
cc
/// ///@date 2016-04-29 22:33:52 /// #include <iostream> #include <map> #include <utility> #include <string> #include <algorithm> using std::string; using std::cin; using std::cout; using std::endl; using std::map; using std::pair; void add(pair<const string,int> &p) { p.second+=2; } int main(void) { map<string,int> mpInt{ {"hello",1}, {"world",1}, {"how",1}, {"are",1}, {"you",1} }; for_each(mpInt.begin(),mpInt.end(),add); for(map<string,int>::iterator it=mpInt.begin();it!=mpInt.end();++it) { cout<<it->second<<" "<<it->first<<endl; } return 0; }
[ "857929453@qq.com" ]
857929453@qq.com
06504f1f9a49fef6e4795712784cf0f63c4c1be3
4dda7dd52854561a27832f8006dd847a7347aa68
/simulation/robotModel.h
d171e8d85f9cebd0945b79a30996feaa80fb5078
[ "Apache-2.0" ]
permissive
Evolutionary-Intelligence/Tensoft-G21
dce58317468e54610f7a86fa5b662dba43011b6c
7a83c5dabc12906c0a6bd1da0a28a131e9d5e144
refs/heads/main
2023-04-22T10:35:02.390381
2021-05-17T14:12:18
2021-05-17T14:12:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,521
h
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ #ifndef ROBOT_MODEL_H #define ROBOT_MODEL_H #ifndef SIM_MODEL_H #define SIM_MODEL_H // The C++ Standard Library #include <map> #include <set> #include <string> #include <vector> #include <Eigen/Dense> // The Bullet Physics library #include "btBulletDynamicsCommon.h" // NTRT libraries #include "ntrt/core/tgModel.h" #include "ntrt/core/tgSubject.h" #include "ntrt/core/tgCast.h" #include "ntrt/core/abstractMarker.h" #include "ntrt/core/tgBasicActuator.h" #include "ntrt/tgcreator/tgBasicContactCableInfo.h" #include "ntrt/core/tgSpringCableActuator.h" #include "ntrt/core/tgRod.h" #include "ntrt/core/tgBox.h" #include "ntrt/core/tgString.h" #include "ntrt/tgcreator/tgBuildSpec.h" #include "ntrt/tgcreator/tgBasicActuatorInfo.h" #include "ntrt/tgcreator/tgRigidAutoCompound.h" #include "ntrt/tgcreator/tgRodInfo.h" #include "ntrt/tgcreator/tgSphereInfo.h" #include "ntrt/tgcreator/tgBoxInfo.h" #include "ntrt/tgcreator/tgStructure.h" #include "ntrt/tgcreator/tgStructureInfo.h" #include "ntrt/tgcreator/tgUtil.h" #endif // Forward declarations class tgBasicActuator; struct Module { int order; std::vector<int> connected_modules; std::vector<int> connected_faces; int parent_face; btVector3 position; double frequency; double amplitude; double phase; int rotation; double stiffness; btVector3 e1; btVector3 e2; btVector3 e3; std::vector<btVector3> rotation_directions; }; class robotModel: public tgSubject<robotModel>, public tgModel { public: /** * Used within this function to map segments to string keys */ typedef std::map<std::string, std::vector<tgBasicActuator*> > ActuatorMap; /** * The only constructor. The model details are instantiated once * setup is called typically when the model is added to a simulation. * @param[in] segments, a positive integer dictating how many * rigid segments will be constructed. */ robotModel(); robotModel(int argc, char *argv[]); robotModel(int argc, char *argv[], std::vector<double>& activePreStretches); /** * Nothing to do. Most functions already handled by tgModel::teardown */ virtual ~robotModel() {} /** * Create the model. Place the rods and strings into the world * that is passed into the simulation. This is triggered * automatically when the model is added to the simulation, when * tgModel::setup(world) is called (if this model is a child), * and when reset is called. Also notifies controllers of setup. * @param[in] world - the world we're building into */ virtual void setup(tgWorld& world); /** * Step the model, its children. Notifies controllers of step. * @param[in] dt, the timestep. Must be positive. */ virtual void step(const double dt); /** * Get a group of actuators according to the provided key. Groups are * populated during setup. * @param[in] key - a std:string* used as a key to a std::map from * a string to a vector of actuators * @return a std::vector of pointers to the actuators found by the key */ const std::vector<tgBasicActuator*>& getActuators(const std::string& key) const; /** * Returns the module's size. * @return module's size. */ double getModuleSize(); /** * Returns the length of the robot * @param num_modules number of robot's modules (used only in case the model has not been added to the simulation yet) * @return robot's length */ double getLength(int num_modules); /** * Returns the movement direction of the robot * @return movement direction (-1 = backward, 1 = forward) */ int getMovDir(); /** * Sets the movement direction parameter (used to determine the front face) * @param moving_direction movement direction (-1 = backward, 1 = forward) */ void setMovDir(int moving_direction); /** * Sets the rotation angle w.r.t. the z axis * @param rot_angle rotation angle in radiants */ void setRotationAngle(double rot_angle); /** * Computes the coordinates of the robot front face * @param position vector that will contain the result */ void getCurrentPosition(btVector3& position); /** * Computes the coordinates of the robot front face and the one parallel to it */ void getFirstModulePosition(btVector3& f_position, btVector3& p_position); /** * Computes target coordinates from distance and bearing * @param distance distance from the frontFace CoM * @param bearing bearing wrt the axis of the first module * @param target btVector3 that will contain the result */ void getCoordinatesFromDistAndBearing(double distance, double bearing, btVector3& target); /** * Compute the distance and the bearing to a given target * @param target btVector3 instance containing the coordinates of the target to reach * @param distance the computed distance value * @param bearing the computed bearing value */ void getDistAndBearingToGoal(btVector3 target, double& distance, double& bearing); /** * Receives a tgModelVisitor and dispatches itself into the * visitor's "render" function. This model will go to the default * tgModel function, which does nothing. * @param[in] r - a tgModelVisitor which will pass this model back * to itself */ virtual void onVisit(tgModelVisitor& r); /** * Undoes setup */ virtual void teardown(); /** * Return a std::size_t indicating the number of segments in the * tetraSpine. * @return a std::size_t with the value of m_segments */ std::vector<Module> m_moduleData; #ifdef MEASURE_CABLES tgStructure finalStruct; #endif private: /** * A std::vector containing all of the tgBasicActuators amongst * the children of this model. Populated during setup */ std::vector<tgBasicActuator*> allActuators; /** * A typedef of std::map from std::string to tgBasicActuator*. Contains * mapped actuators, populated during setup. */ ActuatorMap actuatorMap; /** * A std::vector containing the rods related to the robot's front * face. Populated during setup */ std::vector<tgRod*> frontFace; /** * A std::vector containing the rods related to the robot's face * parallel to the front one. Populated during setup */ std::vector<tgRod*> frontFaceParallel; int m_argc; char **m_argv; int m_initPos; /** * Active cables pre-stretch modifiers */ std::vector<double> activePreStretches; /** * Movement direction: -1 = backward, 1 = forward */ int mov_dir; double rotation_angle; double module_size = 11.11260546; }; #endif
[ "enrico.zardini@studenti.unitn.it" ]
enrico.zardini@studenti.unitn.it
b005e83e284d88a77ddd4194176739dc88d08f6d
b66a0c1eb7ecb2d77512610f751be9c7cfbef931
/Strings/reverse_the_string.cpp
ab78efb85c6d8d1b9a51aacf6f3b60bc9b457c9b
[ "MIT" ]
permissive
zerocod3r/InterviewQuestions
f1c188c009b7599fde068e1cc8eecdf0b2c63137
92dc9d6b1c71ebe4318f1e206e2598a657ee0ad3
refs/heads/master
2023-09-01T17:47:58.928433
2023-08-30T07:17:04
2023-08-30T07:17:04
99,483,334
1
2
MIT
2019-04-19T07:35:06
2017-08-06T11:55:40
C++
UTF-8
C++
false
false
1,167
cpp
/*Given a string A. Return the string A after reversing the string word by word. NOTE: A sequence of non-space characters constitutes a word. Your reversed string should not contain leading or trailing spaces, even if it is present in the input string. If there are multiple spaces between words, reduce them to a single space in the reversed string. Input 1: A = "the sky is blue" Output 1: "blue is sky the" Input 2: A = "this is ib" Output 2: "ib is this" */ string Solution::solve(string A) { int i=0; string ans=""; string temp=""; vector<string> slist{}; int n = A.length(); for(i=0;i<n;i++){ if (i == n-1){ if (A[i] != ' '){ temp += A[i]; slist.push_back(temp); } } if ((A[i] == ' ')&&(temp.length() > 0)){ slist.push_back(temp); temp = ""; } else if (A[i] != ' '){ temp += A[i]; } } for(i=slist.size()-1;i>=0;i--){ ans += slist[i]; if (i != 0) ans += ' '; } return ans; }
[ "sarthakrohilla03@gmail.com" ]
sarthakrohilla03@gmail.com
b56888141cc1a8f2aca356811d13485b09022802
3f8b288711bb5adc2394171507f54c62dc60c601
/atcoder/abc/145c.cpp
9cb68927de647796639d8d9ab070a0aa67f39aa8
[]
no_license
pontsuyo/procon
65df6356f0ea1cfb619898d9e8cc6e326c0586e7
804aaeb526946172a8f41e0619712f5989b6b613
refs/heads/master
2021-06-15T15:13:04.441761
2021-03-20T05:26:54
2021-03-20T05:26:54
175,234,672
1
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> P; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define chmin(x, y) x = min(x, y) #define chmax(x, y) x = max(x, y) #define MOD (int) (1e9+7) #define INF (int) 2e9 #define LLINF (ll) 2e18 int main(){ int n; cin >> n; double x[n], y[n]; rep(i, n){ cin >> x[i] >> y[i]; } double s = 0; rep(i, n){ rep(j, n){ if(i<j){ s += sqrt(pow(x[i]-x[j], 2) + pow(y[i]-y[j], 2)); } } } // cout << s*2/n << endl; printf("%.10lf\n", s*2/n); return 0; }
[ "tsuyopon9221@gmail.com" ]
tsuyopon9221@gmail.com
0aeac30a706910455b263825047117827cae2303
fe19410e2c7c1ebb72c3b1b2812dec728e016b41
/owlqn-mpi/include/worker.h
f19d89c36d3175acf2bf4d7d2954fbd65ba4608b
[]
no_license
upton1919/owlqn-mpi
897a18d59a49321dfed3541b23f455a89a63f643
7df8b44789083205e0caf4217ab711acd6b5a42a
refs/heads/master
2020-07-23T05:47:53.992677
2017-06-16T06:57:00
2017-06-16T06:57:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
h
#ifndef WORKER_H_ #define WORKER_H_ #include <iostream> #include <string> #include <vector> #include <math.h> #include "server.h" #include "utility.h" #include "mpi.h" namespace Optimizer { class Worker{ friend class server_run_Test; public: Worker(int iters, std::string file, int feat_nums, MPI_Comm comm) :_iters(iters), _train_file(file), _feat_nums(feat_nums), _communicator(comm) {} int run(); DBvec getter_f_deriv(){return _fo_deriv;} const double& getter_loss(){return _loss;} ~Worker(){ delptr(_x); delptr(_fo_deriv); delptr(_train_labels); delptr(_h_sita_vec); } private: int _load_train_data(); int _init_interal_parameter(); int _compute_loss_and_grad(); int _compute_f_deriv(); bool _go_bts_condition(); int _send_loss_and_grad(); private: double _loss; int _sample_nums, _feat_nums , _iters; DBvec _fo_deriv, _x; std::string _train_file; Sparsematrix _train_set; std::vector<int>* _train_labels; std::vector<double>* _h_sita_vec; MPI_Comm _communicator; }; } #endif
[ "guochao01@internal.baidu.com" ]
guochao01@internal.baidu.com
f501cf4409f8f74160b3860415b75eda651827a7
db46cf6a36cb0d97389bdc8e93c5b7a72799772e
/HardwareTimer.h
50cf068b8bf0f4a78e88e2306f426a4044edd50a
[]
no_license
tinytiny123/autolabAlu
67b5d3cbda2266fe7a4ed562af524c988adfa196
f37ad2b0eb95555f7ad679dacf42f21311f1a834
refs/heads/master
2022-11-06T15:26:28.390494
2020-06-26T09:32:51
2020-06-26T09:32:51
273,466,745
0
0
null
null
null
null
UTF-8
C++
false
false
700
h
// // Created by jonas on 27.05.20. // #include <stdint.h> #ifndef AUTOSYSLAB_CALCULATOR_HARDWARETIMER_H #define AUTOSYSLAB_CALCULATOR_HARDWARETIMER_H class HardwareTimer { public: static volatile uint8_t newCycle; // void ISR(TIMER0_COMP_VECT); /** * frequency set-up as follows: * base Timer ((frequency / prescaler) * (1/interrupts per second)) -1 * so currently there should be 10 Cycles per second * tool for timerFrequency calc * https://timer-interrupt-calculator.simsso.de/ */ int hardwareTimerFrequency = ((16000000 / 1024) * 0.1) - 1; public: void init(); bool checkNewCycle(); }; #endif // AUTOSYSLAB_CALCULATOR_HARDWARETIMER_H
[ "florian4grunbach@hotmail.de" ]
florian4grunbach@hotmail.de
f804484f2baac716eca717a58189f6eb2231f315
82c8e98f00999f3fca2759a7595ac54b833f777b
/HW6/Parse.cpp
1e7901847fa19d5ed91e7467d1d45a45a6e91791
[]
no_license
devrimakinci/CSE241-HOMEWORKS
636245023fa51b198cc42bbecb5829e4eee4608b
0520b8f2d87155491b4507dde22e7f71dcce58a0
refs/heads/master
2021-07-15T16:57:36.336657
2017-10-21T10:31:55
2017-10-21T10:31:55
107,770,942
0
0
null
null
null
null
UTF-8
C++
false
false
6,341
cpp
/* * Dosya Ismi: Parse.cpp * Yazan: Devrim AKINCI * Numarasi: 141044052 * Tarih: 26 Kasim 2016 */ #include "Parse.h" void Parse::removeFirstSpaces(string &str){ int numberOfSpaces=0; //Bosluk sayisi //Bosluk ve tab karakterinin sayisinin bulunmasi while (str[numberOfSpaces] == ' ' || str[numberOfSpaces] == '\t') numberOfSpaces++; str.erase(0,numberOfSpaces); //Bosluklarin silinmesi } string Parse::findInstructions(string &str){ int idx,i=0,numberOfSpaces=0;//Bosluk sayisi idx = str.find_first_of(' '); //İlk boslugun indeksi while (str[i] != '\0') {//Bosluk sayisinin bulunmasi if (str[i] == ' ' || str[i] == '\t') numberOfSpaces++; i++; } if (str.size() == numberOfSpaces+INS_SIZE){ instruction = str.substr(0,idx); return instruction; } if (idx == -1){ idx = str.find_first_of('\t'); //İlk tab karakterinin bulunamasi if (idx == -1){ if (str.size() == INS_SIZE) return instruction = str; /*----------------Stringin icindeki yorumlarin silinmesi----------------------*/ for (i=0; str[i]!=';'; i++){ ; } instruction = str.erase(i); return instruction; } instruction = str.substr(0,idx); //Instructionin ayiklanmasi return instruction; /*----------------------------------------------------------------------------*/ } instruction = str.substr(0,idx); //Instructionin ayiklanmasi return instruction; } string Parse::upperCaseSensitivity (string &str){ for (int j=0; j<str.size(); j++){ //Kucuk harfleri buyuk harfe cevirmesi if (str[j] >= 'a' && str[j] <= 'z') str[j] += 'A' - 'a'; } return str; } string Parse::findRegister(string &str){ int i=0,indexOfSpace,indexOfR,indexOfSharp; indexOfSpace = str.find_first_of(' '); //İlk boslugun indeksi reg1 = str.substr (indexOfSpace); removeFirstSpaces (reg1); //Bosluklarin silinmesi /*---------------Stringin icindeki yorumlarin ayiklanmasi---------------------*/ for (i=0; ((reg1[i]!= ' ' && reg1[i]!= ',') &&reg1[i]!=';'); i++){ ; } /*----------------------------------------------------------------------------*/ reg1 = reg1.substr(0,i); indexOfR = reg1.find_first_of('R');//ilk R harfinin indeksi if (indexOfR == -1){ indexOfR = reg1.find_first_of('r');//ilk r harfinin indeksi if (indexOfR == -1){ indexOfSharp = reg1.find_first_of('#');//ilk # karakterinin indeksi if (indexOfSharp == -1){ //Integer tipine cevrilmesi constant = convertFromStringToInt (reg1); return reg1; } else{ reg1 = reg1.substr(1); //Integer tipine cevrilmesi indexAdres = convertFromStringToInt (reg1); reg1.insert(0,1,'#');//Stringe # karakteri eklenmesi return reg1; } } else{ reg1 = reg1.substr(1); //Integer tipine cevrilmesi index = convertFromStringToInt (reg1); reg1.insert(0,1,'R'); //Stringe R harfinin eklenmesi return reg1; } } reg1 = reg1.substr(1); //Integer tipine cevrilmesi index = convertFromStringToInt (reg1); reg1.insert(0,1,'R');//Stringe R harfinin eklenmesi return reg1; } string Parse::findRegisterTwo(string &str){ int i=0,indexOfSpace,indexOfR,indexOfSharp;//Bosluk sayisi indexOfSpace = str.find_first_of(' ');//İlk boslugun indeksi reg2 = str.substr (indexOfSpace); removeFirstSpaces (reg2); //Bosluklarin silinmesi indexOfSpace= reg2.find_first_of(' '); //İlk boslugun indeksi if (indexOfSpace == -1) return reg2; reg2 = reg2.substr (indexOfSpace); removeFirstSpaces (reg2); //Bosluklarin silinmesi /*---------------Stringin icindeki yorumlarin ayiklanmasi---------------------*/ for (i=0; (reg2[i]== ' ' || reg2[i]== ','); i++){ ; } reg2 = reg2.substr(i); /*----------------------------------------------------------------------------*/ indexOfSpace = reg2.find_first_of(' '); //İlk boslugun indeksi reg2 = reg2.substr(0,indexOfSpace); indexOfR = reg2.find_first_of('R');//ilk R harfinin indeksi if (indexOfR == -1){ indexOfR = reg2.find_first_of('r');//ilk r harfinin indeksi if (indexOfR == -1){ indexOfSharp = reg2.find_first_of('#');//ilk # karakterinin indeksi if (indexOfSharp == -1){ //Integer tipine cevrilmesi constant2 = convertFromStringToInt (reg2); return reg2; } else{ reg2 = reg2.substr(1); //Integer tipine cevrilmesi indexAdres = convertFromStringToInt (reg2); reg2.insert(0,1,'#');//Stringe # karakterinin eklenmesi return reg2; } } else{ reg2 = reg2.substr(1); //Integer tipine cevrilmesi index2 = convertFromStringToInt (reg2); reg2.insert(0,1,'R');//Stringe R harfinin eklenmesi return reg2; } } reg2 = reg2.substr(1); //Integer tipine cevrilmesi index2 = convertFromStringToInt (reg2); reg2.insert(0,1,'R');//Stringe R harfinin eklenmesi return reg2; } int Parse::convertFromStringToInt(string str) { int i=0,sum=0; if (str[i] == '\0') return NOT_NUMBER; else{ for (i=0; str[i]!='\0'; i++){ //Stringi integer tipine cevirme if (str[i] >= '0' && str[i] <= '9') sum = (sum * DECIMAL) + str[i] - ASCII_ZERO_CH; else return NOT_NUMBER; } } return sum; } string Parse::getInstruction() const { return instruction; } string Parse::getRegister() const { return reg1; } string Parse::getRegister2() const { return reg2; } int Parse::getIndex() const { return index-1; } int Parse::getIndex2() const { return index2-1; } int Parse::getConstant() const { return constant; } int Parse::getConstant2() const { return constant2; } int Parse::getAdres() const { return indexAdres; }
[ "devrimakinci103@gmail.com" ]
devrimakinci103@gmail.com
f52619771e0d4945b7eb7499673dbaa56ce4f987
8f7a2efc606e5cc7cb15c2b986f694e128b071af
/teclado/teclado.ino
137712ad96642bf46d6e1c53ac24b84921bb0885
[]
no_license
mateollano1/ArduinoProyects
154af82cc832c5dba89186b30067b0e1eac513d4
f8e6530f739bb41cbfe63698ae9b57d6f5b8cd7b
refs/heads/master
2020-09-28T09:19:14.118975
2019-12-08T23:16:22
2019-12-08T23:16:22
226,745,835
0
0
null
null
null
null
UTF-8
C++
false
false
4,141
ino
//Librerias necesarias #include<Keypad.h> #include<EEPROM.h> //Declaración de variables y constantes int ledPresion = A1; int ledClave = A0; int buzzer = A2; char tecla; bool cambio = false; char cambioClave[4] = { '*', '9', '9', '#' }; char claveDigitada[4]; int contadorDigitos = 0; char claveGuardada[4]; bool cambioAutorizado; bool IngresoAutorizado; // Código necesario para matriz de teclado---- const byte filas = 4; const byte columnas = 3; byte pinsFilas[filas] = {8, 7, 6, 5}; byte pinsColumnas[columnas] = {4, 3, 2}; char teclas[filas][columnas] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'}, }; Keypad teclado = Keypad(makeKeymap(teclas), pinsFilas, pinsColumnas, filas, columnas); //-------------------------------------------- void setup() { // put your setup code here, to run once: pinMode(ledPresion, OUTPUT); pinMode(ledClave, OUTPUT); pinMode(buzzer, OUTPUT); Serial.begin(9600); claveGuardada[ 0 ] = EEPROM.read( 0 ); // Asigna el primer digito de la clave claveGuardada[ 1 ] = EEPROM.read( 1 ); // Asigna el segundo digito de la clave claveGuardada[ 2 ] = EEPROM.read( 2 ); // Asigna el tercer digito de la clave claveGuardada[ 3 ] = EEPROM.read( 3 ); /*Serial.print("claveGuardada: "); Serial.print(claveGuardada[0]); Serial.print(claveGuardada[1]); Serial.print(claveGuardada[2]); Serial.println(claveGuardada[3]);*/ } void loop() { // put your main code here, to run repeatedly: tecla = teclado.getKey(); if (tecla != NO_KEY) { //claveDigitada = claveDigitada + tecla; claveDigitada[contadorDigitos] = tecla; contadorDigitos = contadorDigitos + 1; if (contadorDigitos == 4) { contadorDigitos = 0; revisarClave(); } else { presionTecla(); } } } void presionTecla() { digitalWrite(ledPresion, HIGH); tone (buzzer, 30); delay(80); noTone (buzzer); digitalWrite(ledPresion, LOW); } void revisarClave() { if (cambio) { //Serial.println("Clave guardada "); EEPROM.write( 0, claveDigitada[ 0 ] ); // Almacena el primer digito de la clave maestra claveGuardada[0] = claveDigitada[ 0 ]; EEPROM.write( 1, claveDigitada[ 1 ] ); // Almacena el segundo digito de la clave maestra claveGuardada[1] = claveDigitada[ 1 ]; EEPROM.write( 2, claveDigitada[ 2 ] ); // Almacena el tercer digito de la clave maestra claveGuardada[2] = claveDigitada[ 2 ]; EEPROM.write( 3, claveDigitada[ 3 ] ); // Almacena el cuarto digito de la clave maestra claveGuardada[3] = claveDigitada[ 3 ]; EEPROM.write( 4, 0x55 ); /* Serial.print("claveGuardada: "); Serial.print(EEPROM.read( 0 )); Serial.print(EEPROM.read( 1 )); Serial.print(EEPROM.read( 2 )); Serial.println(EEPROM.read( 3 )); */ digitalWrite(ledClave, LOW); //guarda en eeprom cambio = false; return; } // comprueba clave cambioAutorizado = true; for ( int DigitNum = 0; DigitNum < 4; DigitNum++ ) { if ( cambioClave[ DigitNum ] != claveDigitada[ DigitNum ] ) cambioAutorizado = false; } if (cambioAutorizado) { cambioAutorizado = false; //cambiarclave(); Serial.println("ingresar nueva clave: "); cambio = true; digitalWrite(ledClave, HIGH); // claveDigitada = ""; return; } IngresoAutorizado = true; for ( int DigitNum = 0; DigitNum < 4; DigitNum++ ) { if ( claveGuardada[ DigitNum ] != claveDigitada[ DigitNum ] ) IngresoAutorizado = false; } //obtener clave eeprom // Serial.println("clave ingresada: "+ claveDigitada); //EEPROM.get(0,claveGuardada); // Serial.println("clave guardada: " + claveGuardada); if (IngresoAutorizado) { digitalWrite(ledPresion, HIGH); //encender electroiman delay(3000); digitalWrite(ledPresion, LOW); } else { digitalWrite(ledClave, HIGH); tone (buzzer, 261); delay(1000); digitalWrite(ledClave, LOW); noTone(buzzer); } //claveDigitada = ""; // si es igual abra, y sonido }
[ "mateo.llano1@gmail.com" ]
mateo.llano1@gmail.com
ab0ab5e76fa0de164db28d589a7ba588fa559075
41498afc0ff63320ed321a8d0601313c162d92fd
/MouseMover/MouseMover.ino
9034b406882647dff7399bdaa9e37314dae1520a
[]
no_license
KobiTashbini/Eric
0a145d93db92174ee3930cd3af582d2e2eccab66
20bb56156f4101337c7c7754ed3772ce23ef1e9f
refs/heads/master
2022-12-26T13:47:43.937295
2020-10-03T11:12:18
2020-10-03T11:12:18
200,721,626
1
1
null
null
null
null
UTF-8
C++
false
false
14,745
ino
#include <AbsMouse.h> enum ShotState{ oneShot, mulShot, emulatorEventsHooker }; ShotState shotState = emulatorEventsHooker; int data; int last_analogX = 0; int last_analogY = 0; unsigned long currentMillis = millis(); int buttonPin = 13; int buttonPin3 = 3; int buttonPin4 = 4; int buttonPin2 = 2; //int buttonPin2 = 8; long shotCounter = 0; bool mulShotButtonState = false; bool oneShotButtonState = false; int swichModePin = 9; int oneShotButton = 2; int mulShotButton = 8; int celenoidOutput = 10; bool isCelenoidOutputOn_OMAME = false; unsigned long currentMillisMAME = false; unsigned long startShotMillisMAME = 0; bool isCelenoidOutputOn_M = false; bool isCelenoidOutputOn_O = false; const long oneShotinterval = 40; const long oneShotintervalMAME = 40; const long mulShotIntervalToAvoid = 105; unsigned long startShotMillis = 0; unsigned long lastMulShot = 0; bool isMouseShouldMove = false; bool buttonState = false; bool buttonState2 = false; bool buttonState3 = false; bool buttonState4 = false; float XAxis_ = 0; float YAxis_ = 0; int const C_xBorderLimitA = 787; int const C_xBorderLimitB = 143; int const C_yBorderLimitA = 920; int const C_yBorderLimitB = 195; int const C_xScaleValue = 143; int const C_yScaleValue = 230; int xBorderLimitA = C_xBorderLimitA; int xBorderLimitB = C_xBorderLimitB; int yBorderLimitA = C_yBorderLimitA; int yBorderLimitB = C_yBorderLimitB; int xScaleValue = C_xScaleValue; int yScaleValue = C_yScaleValue; void setup() { Serial.begin(9600); AbsMouse.init(1024, 720); pinMode(buttonPin, INPUT); // pinMode(buttonPin2, INPUT_PULLUP); // digitalWrite(buttonPin2,HIGH); pinMode(buttonPin3, INPUT_PULLUP); pinMode(buttonPin4, INPUT_PULLUP); pinMode(oneShotButton, INPUT); //digitalWrite(oneShotButton,HIGH); pinMode(mulShotButton, INPUT); // digitalWrite(mulShotButton,HIGH); pinMode(celenoidOutput, OUTPUT); AbsMouse.report(); } void loop() { //////Serial.println(digitalRead(oneShotButton)); if(shotState == emulatorEventsHooker) { if (Serial.available()) { data = Serial.read(); if (data == 'A' && !isCelenoidOutputOn_OMAME) { //Serial.println(" digitalWrite(celenoidOutput, HIGH);"); digitalWrite(celenoidOutput, HIGH); isCelenoidOutputOn_OMAME = true; startShotMillisMAME = millis(); // delay(40); // digitalWrite(celenoidOutput, LOW); } else if (data == 'B') { digitalWrite(5, HIGH); } else if(data == 'b'){ digitalWrite(5, LOW); } else if (data == 'C') { digitalWrite(6, HIGH); } else if(data == 'c'){ digitalWrite(6, LOW); } else if (data == 'D') { digitalWrite(7, HIGH); } else if(data == 'd'){ digitalWrite(7, LOW); } else if (data == 'E') { digitalWrite(8, HIGH); } else if(data == 'e'){ digitalWrite(8, LOW); } else if (data == 'F') { digitalWrite(11, HIGH); } else if(data == 'f'){ digitalWrite(11, LOW); } else if (data == 'G') { digitalWrite(12, HIGH); } else if(data == 'g'){ digitalWrite(12, LOW); } } currentMillisMAME = millis(); /////////////////////////// if ((currentMillisMAME - startShotMillisMAME >= oneShotintervalMAME) && isCelenoidOutputOn_OMAME) { //Serial.print("++++++++++++++++++++CELENOID DOWN++++++++++++++++++++"); //Serial.print("currentMillisMAME"); //Serial.println(currentMillisMAME); //Serial.print("startShotMillisMAME"); //Serial.println(startShotMillisMAME); //Serial.print("oneShotinterval"); //Serial.println(oneShotinterval); digitalWrite(celenoidOutput, LOW); //Serial.println("digitalWrite(celenoidOutput, LOW);"); isCelenoidOutputOn_OMAME = false; ////Serial.println("digitalWrite(celenoidOutput, LOW)"); //Serial.println("currentMillis:"); ////Serial.println(currentMillis); //Serial.println("startShotMillis:"); ////Serial.println(startShotMillis); //Serial.println("oneShotinterval:"); ////Serial.println(oneShotinterval); } else { //Serial.print("CELENOID NOT DOWN"); //Serial.print("currentMillisMAME"); //Serial.println(currentMillisMAME); //Serial.print("startShotMillisMAME"); //Serial.println(startShotMillisMAME); //Serial.print("oneShotinterval"); //Serial.println(oneShotinterval); } } else { if ( digitalRead(oneShotButton) == HIGH && !isCelenoidOutputOn_O && !oneShotButtonState) { oneShotButtonState = true; Serial.println("digitalRead(oneShotButton) == HIGH"); digitalWrite(celenoidOutput, HIGH); Serial.println("digitalWrite(celenoidOutput, HIGH);"); // AbsMouse.press(MOUSE_LEFT ); isCelenoidOutputOn_O = true; Serial.println("digitalWrite(celenoidOutput, HIGH)"); // digitalWrite(celenoidOutput, LOW); Serial.println("digitalWrite(celenoidOutput, LOW)"); // isCelenoidOutputOn = false; startShotMillis = millis(); Serial.println( shotCounter); shotCounter++; } else if (digitalRead(oneShotButton) == LOW) { // //Serial.print("!digitalRead(oneShotButton) == LOW"); oneShotButtonState = false; // AbsMouse.release(MOUSE_LEFT ); } currentMillis = millis(); if ( digitalRead(mulShotButton) == HIGH && !isCelenoidOutputOn_M && ( (currentMillis - lastMulShot >= mulShotIntervalToAvoid) || lastMulShot == 0) ) { // //Serial.print("igitalRead(mulShotButton) : "); digitalWrite(celenoidOutput, HIGH); ////Serial.println("digitalWrite(celenoidOutput, HIGH)"); ////Serial.println(millis()); isCelenoidOutputOn_M = true; mulShotButtonState = true; lastMulShot = millis(); ////Serial.println( shotCounter); shotCounter++; } else if (digitalRead(mulShotButton) == LOW) { mulShotButtonState = false; } //////Serial.println("SSSSSSS"); // Serial.write("A"); if (Serial.available()) { data = Serial.read(); //////Serial.println("dataReaded" ); //////Serial.println(data); // Serial.write("Z"); if (data == 'X') { xBorderLimitA = xBorderLimitA + 1; //////Serial.println("xBorderLimit : "); // ////Serial.println(xBorderLimit); // ////Serial.println("A"); // Serial.write("A"); //Serial.println(xBorderLimitA); } else if (data == 'x') { xBorderLimitA = xBorderLimitA - 1; //////Serial.println("xBorderLimit : "); // ////Serial.println(xBorderLimit); //Serial.println(xBorderLimitA); } if (data == 'W') { xBorderLimitB = xBorderLimitB + 1; //Serial.println(xBorderLimitB); } else if (data == 'w') { xBorderLimitB = xBorderLimitB - 1; //Serial.println(xBorderLimitB); } else if (data == 'Y') { yBorderLimitA = yBorderLimitA - 1; //////Serial.println("yBorderLimitA : "); //////Serial.println(yBorderLimitA); //Serial.println(yBorderLimitA); } else if (data == 'y') { yBorderLimitA = yBorderLimitA + 1; // ////Serial.println("yBorderLimitA : "); //////Serial.println(yBorderLimitA); //Serial.println(yBorderLimitA); } else if (data == 'Z') { yBorderLimitB = yBorderLimitB + 1; // ////Serial.println("yBorderLimitB : "); // ////Serial.println(yBorderLimitB); //Serial.println(yBorderLimitB); } else if (data == 'z') { yBorderLimitB = yBorderLimitB - 1; // ////Serial.println("yBorderLimitB : "); // ////Serial.println(yBorderLimitB); //Serial.println(yBorderLimitB); } else if (data == 'H') { yScaleValue = yScaleValue + 1; //////Serial.println("yScaleValue : "); // ////Serial.println(yScaleValue); //Serial.println(yScaleValue); } else if (data == 'h') { yScaleValue = yScaleValue - 1; // ////Serial.println("yScaleValue : "); // // ////Serial.println(yScaleValue); //Serial.println(yScaleValue); } else if (data == 'R') { xScaleValue = xScaleValue + 1; //////Serial.println("xScaleValue : "); // ////Serial.println(xScaleValue); //Serial.println(xScaleValue); } else if (data == 'r') { xScaleValue = xScaleValue - 1; // ////Serial.println("xScaleValue : "); // ////Serial.println(xScaleValue); //Serial.println(xScaleValue); } else if (data == 'P') { xBorderLimitA = C_xBorderLimitA; xBorderLimitB = C_xBorderLimitB; yBorderLimitA = C_yBorderLimitA; yBorderLimitB = C_yBorderLimitB; xScaleValue = C_xScaleValue; yScaleValue = C_yScaleValue; //Serial.println("RestoreSuccess"); } else { // ////Serial.println('M'); } } // ////Serial.println("isMouseShouldMove - "); // ////Serial.println(isMouseShouldMove); currentMillis = millis(); if((currentMillis - lastMulShot >= oneShotinterval) && isCelenoidOutputOn_M) { digitalWrite(celenoidOutput, LOW); isCelenoidOutputOn_M = false; } /////////////////////////// if ((currentMillis - startShotMillis >= oneShotinterval) && isCelenoidOutputOn_O) { digitalWrite(celenoidOutput, LOW); isCelenoidOutputOn_O = false; Serial.println(currentMillis - startShotMillis); Serial.println("OFF CELENOID OUTPUT"); //Serial.print("currentMillis:"); ////Serial.println(currentMillis); //Serial.print("startShotMillis:"); ////Serial.println(startShotMillis); //Serial.print("oneShotinterval:"); ////Serial.println(oneShotinterval); } else { ////Serial.print("ERROR:"); ////Serial.print("currentMillis:"); // ////Serial.println(currentMillis); // //Serial.print("startShotMillis:"); // ////Serial.println(startShotMillis); // //Serial.print("oneShotinterval:"); // ////Serial.println(oneShotinterval); /// //Serial.print("isCelenoidOutputOn:"); // ////Serial.println(isCelenoidOutputOn); //////Serial.println("(currentMillis - startShotMillis >= oneShotinterval) && isCelenoidOutputOn"); //////Serial.println((currentMillis - startShotMillis >= oneShotinterval) && isCelenoidOutputOn); } } //--------------------BEGIN MOUCE EVENTS SECTION ----------------------------- if (digitalRead(buttonPin) == HIGH ) { isMouseShouldMove = !isMouseShouldMove; // ////Serial.println("isMouseShouldMove - "); // ////Serial.println(isMouseShouldMove); if (!isMouseShouldMove) { AbsMouse.move(500, 500 ); // //Serial.print("STOPPPPPPPPPPPP - "); //delay(20000000000); } Serial.println("delay(200"); delay(200); } int currentAnalogX = analogRead(A0); int currentAnalogY = analogRead(A1); // ////Serial.println("currentAnalogX - "); // ////Serial.println(currentAnalogX); // ////Serial.println("currentAnalogY - "); // ////Serial.println(currentAnalogY); if (isMouseShouldMove == true && (last_analogX != currentAnalogX || last_analogY != currentAnalogY )) { last_analogX = currentAnalogX; last_analogY = currentAnalogY; XAxis_ = 1023 - analogRead(A0); YAxis_ = 1023 - analogRead(A1); //////Serial.println("XAxis_ - "); // ////Serial.println(XAxis_); if (XAxis_ > xBorderLimitA) { XAxis_ = xBorderLimitA; } if (XAxis_ < xBorderLimitB) { XAxis_ = xBorderLimitB; } if (YAxis_ > yBorderLimitA) { YAxis_ = yBorderLimitA; } else if (YAxis_ < yBorderLimitB) { YAxis_ = yBorderLimitB; } // int nYAxis_ = ((YAxis_ - yScaleValue) / (yBorderLimitA - yScaleValue)) * 720; // int nXAxis_ = ((XAxis_ - xScaleValue) / ((xBorderLimit - 1) - xScaleValue)) * 1023; int nYAxis_ = ((YAxis_ - yScaleValue) / (yBorderLimitA - yScaleValue)) * 720; int nXAxis_ = ((XAxis_ - xScaleValue) / (xBorderLimitA - xScaleValue)) * 1023; AbsMouse.move(nXAxis_, nYAxis_ ); // ////Serial.println("nXAxis_"); // ////Serial.println(nXAxis_); // //Serial.print("XAxis_"); // ////Serial.println(XAxis_); // //Serial.print("nYAxis_"); // ////Serial.println(nYAxis_); // //Serial.print("YAxis_"); // ////Serial.println(YAxis_); // //Serial.print("isMouseShouldMove-"); // ////Serial.println("WIRKING ABS"); } else { //////Serial.println("NOT WORKING ABS"); } //////////////////////// if (digitalRead(buttonPin2) == HIGH ) { if (!buttonState2) { buttonState2 = true; ////Serial.println("buttonPin2 clicked and press MOUSE_LEFT"); // ////Serial.println(buttonState2); AbsMouse.press(MOUSE_LEFT ); } } else { if (buttonState2) { buttonState2 = false; AbsMouse.release(MOUSE_LEFT); ////Serial.println("buttonState2 releaseed"); } // AbsMouse.release(MOUSE_LEFT ); } if (digitalRead(buttonPin3) == HIGH ) { if (!buttonState3) { buttonState3 = true; ////Serial.println("buttonPin3 clicked and press MOUSE_RIGHT"); // ////Serial.println(buttonState3); AbsMouse.press(MOUSE_RIGHT ); } } else { if (buttonState3) { buttonState3 = false; AbsMouse.release(MOUSE_RIGHT); ////Serial.println("buttonState3 releaseed"); } // AbsMouse.release(MOUSE_LEFT ); } /////////////////////////// if (digitalRead(buttonPin4) == HIGH ) { if (!buttonState4) { buttonState4 = true; ////Serial.println("buttonPin4 clicked and press MOUSE_MIDDLE"); // ////Serial.println(buttonState4); AbsMouse.press(MOUSE_MIDDLE ); } } else { if (buttonState4) { buttonState4 = false; AbsMouse.release(MOUSE_MIDDLE); ////Serial.println("buttonState4 releaseed"); } } //--------------------END MOUCE EVENTS SECTION ----------------------------- if (digitalRead(swichModePin) == HIGH ) { if(shotState == oneShot) { shotState = mulShot; Serial.println("mulShot"); mulShotButton = 2; oneShotButton = 7; } else if(shotState == mulShot ) { shotState = emulatorEventsHooker; Serial.println("emulatorEventsHooker"); } else { shotState = oneShot; Serial.println("oneShot"); oneShotButton = 2; mulShotButton = 7; } //Serial.print("mulShot|"); Serial.println("delay(200"); delay(200); } //delay(50); } //////////////////////
[ "kobits6@gmail.com" ]
kobits6@gmail.com
00b3ad642d9c67fba2e757cebd736454db11d145
ff30fec1eae2ae49cfe46ef4d240ff25d7211d25
/Contact/person.h
f1f9f8d1cc0f1499f9c715e93fc67158a6912812
[]
no_license
zhuxiang555111/c-courese-design
d2a4104fca88493076e9518977e6a453de3d52d5
cd5bacc1e9206aa148243f917014f48600263233
refs/heads/master
2021-01-20T01:57:11.789222
2017-05-16T14:04:19
2017-05-16T14:04:19
89,350,361
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
#pragma once #include<iostream> #include <string> using namespace std; class person { public: string name; string sex; string phoneNumber; string address; string postCode; string email; string qqNumber; string relationType; };
[ "zhuxiang555111@hotmail.com" ]
zhuxiang555111@hotmail.com
ab66644b40696a129a1ab0694878d05a1a782b22
80b49b50194cadf0a7a18cc16fa138f89cb083fc
/kernel/init.cpp
e71381184bd37d64304527ba9389e826a37825ab
[]
no_license
sm5ve/OS
03078da366b090eca2137ea3e3b28e0b5126c8ce
967b2022e5a6319e695114ab5fa959499576a852
refs/heads/master
2021-01-01T01:14:40.964142
2020-08-04T22:11:05
2020-08-04T22:11:05
239,115,488
2
0
null
null
null
null
UTF-8
C++
false
false
3,632
cpp
#include <Scheduler.h> #include <acpi/tables.h> #include <arch/i386/proc.h> #include <arch/i386/smp.h> #include <assert.h> #include <debug.h> #include <devices/SerialDevice.h> #include <devices/ahci/ahci.h> #include <devices/apic.h> #include <devices/pci.h> #include <devices/pcie.h> #include <devices/pit.h> #include <ds/Intervals.h> #include <ds/String.h> #include <elf/dwarf.h> #include <elf/elf.h> #include <interrupts.h> #include <loader.h> #include <mem.h> #include <multiboot/multiboot.h> #include <paging.h> #include <devices/ahci/AHCIDevice.h> #include <ds/smart_pointers.h> // Since kernel_init has a lot of testing code, we sometimes get used variables // for older tests that are commented out Hence, while the kernel's still // largely in flux, we'll disable unused variable warnings for now #pragma GCC diagnostic ignored "-Wunused-variable" extern uint32_t _kend; ELF* ksyms_elf = NULL; ELF* test_program_elf = NULL; void load_modules(mboot_module* modules, uint32_t count) { for (uint32_t i = 0; i < count; i++) { String modName((char*)(modules[i].name_ptr + 0xC0000000)); if (modName == "kernel.sym") { SD::the() << "Found the kernel symbols!" << "\n"; void* kstart = (void*)(modules[i].start_addr + 0xC0000000); ksyms_elf = new ELF(kstart); ksyms = new DWARF(ksyms_elf); } if (modName == "test") { SD::the() << "Found the test program\n"; void* pstart = (void*)(modules[i].start_addr + 0xC0000000); test_program_elf = new ELF(pstart); } } } class AllocTester{ public: AllocTester(){ SD::the() << "Constructed!\n"; } ~AllocTester(){ SD::the() << "Destructed!\n"; } }; void init_scheduled(); extern "C" [[noreturn]] void kernel_init(unsigned int multiboot_magic, mboot_info* mboot) { SD::init(); assert(multiboot_magic == MULTIBOOT_BOOTLOADER_MAGIC, "Error: Multiboot magic does not match. Aborting boot."); SD::the() << "\n"; SD::the() << "Multiboot magic verified\n"; initKalloc(); SD::the() << "Memory allocators initialized\n"; SD::the() << "Installing the GDT\n"; installGDT(); SD::the() << "GDT installed!\n"; SD::the() << "Installing the IDT\n"; IDT::install(); SD::the() << "IDT installed!\n"; mboot_mmap_entry* entries = (mboot_mmap_entry*)((uint32_t)(mboot->mmap_ptr) + 0xC0000000); load_modules((mboot_module*)(mboot->mods_ptr + 0xC0000000), mboot->mods_count); SD::the() << "Initializing memory manager\n"; MemoryManager::init(entries, mboot->mmap_len); SD::the() << "Done!\n"; SD::the() << "Free bytes " << MemoryManager::getFreeBytes() << "\n"; Scheduler::init(); PIT::initOneshot(); ACPI::init(); PCI::init(); PCIe::init(); APIC::init(); sti(); AHCI::init(); AHCI::getPrimaryDisk() -> test(); //sti(); //SMP::init(); //for (uint32_t i = 0; i < PCI::devices->size(); i++) { //auto& device = *(*PCI::devices)[i]; for(auto& device : *PCI::devices){ SD::the() << "PCI device type " << (void*)(device -> getDeviceType()) << "\n"; } //SD::the() << AHCI::getPrimaryDisk() << "\n"; // sti(); /*Task* utask = Loader::load(*test_program_elf); Scheduler::addTask(*utask); Task* utask2 = Loader::load(*test_program_elf); Scheduler::addTask(*utask2); Scheduler::pickNext();*/ auto stage2 = new Task(true); stage2 -> setEntrypoint((void*)init_scheduled); Scheduler::addTask(*stage2); Scheduler::pickNext(); Scheduler::exec(); //SD::the() << "Free bytes " << MemoryManager::getFreeBytes() << "\n"; outw(0x604, 0x2000); //shutdown qemu for (;;) { __asm__("hlt"); } } void init_scheduled(){ SD::the() << "Hello ktask world!\n"; outw(0x604, 0x2000); for(;;); } #pragma GCC diagnostic pop
[ "sm5ve@virginia.edu" ]
sm5ve@virginia.edu
075e16139a57604f2b3946b8aa24e19bda7052be
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/235/431/CWE190_Integer_Overflow__int64_t_fscanf_square_43.cpp
9e1f61b581b6ad2779cc53ad8bf67027d3b5e694
[]
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
3,117
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int64_t_fscanf_square_43.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-43.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: square * GoodSink: Ensure there will not be an overflow before squaring data * BadSink : Square data, which can lead to overflow * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file * * */ #include "std_testcase.h" #include <math.h> #include <inttypes.h> namespace CWE190_Integer_Overflow__int64_t_fscanf_square_43 { #ifndef OMITBAD static void badSource(int64_t &data) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%" SCNd64, &data); } void bad() { int64_t data; data = 0LL; badSource(data); { /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */ int64_t result = data * data; printLongLongLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(int64_t &data) { /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; } static void goodG2B() { int64_t data; data = 0LL; goodG2BSource(data); { /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */ int64_t result = data * data; printLongLongLine(result); } } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2GSource(int64_t &data) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%" SCNd64, &data); } static void goodB2G() { int64_t data; data = 0LL; goodB2GSource(data); /* FIX: Add a check to prevent an overflow from occurring */ if (imaxabs((intmax_t)data) <= sqrtl(LLONG_MAX)) { int64_t result = data * data; printLongLongLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE190_Integer_Overflow__int64_t_fscanf_square_43; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
c61b7dd7e7fb474d2d9040ae42c3f9f8fe17af39
1be913dcc06fed297346e736f836dcbf8a33022d
/managesystem.cpp
2dd71e3e86912e619eac424fcf9ef28f1c57781b
[]
no_license
2063436123/CSAPP-
19129a02c6cd1393e8afa3006d416c0902b45202
6326a6f10576847fb3aa2891d2fc5c6da6fd246b
refs/heads/master
2022-11-11T02:11:20.423720
2020-06-29T13:01:50
2020-06-29T13:01:50
275,697,562
0
0
null
null
null
null
GB18030
C++
false
false
7,820
cpp
#include "managesystem.h" int main() { StuManSystem system; system.start(); return 0; } // 构造对象时设置存放数据的文件名 StuManSystem::StuManSystem() { FileName = "data.txt"; } void StuManSystem::loadData() { fstream fin(FileName, ios::in); if (fin.is_open()) { stuData data; while (fin.peek() != EOF) { fin >> data.id >> data.student_name >> data.date >> data.class_name >> data.message; if (fin.eof()) break; stuDataLists.push_back(data); } fin.close(); } } void StuManSystem::saveData() { fstream fout(FileName, ios::out); if (fout.is_open()) { stuData data; list<stuData>::const_iterator iter = stuDataLists.begin(); for (; iter != stuDataLists.end(); iter++) { data = *iter; fout << data.id <<" " << data.student_name << " " <<data.date << " " << data.class_name << " " << data.message << endl; } fout.close(); } } // 首先尝试从data.dat中加载数据,之后展示菜单 void StuManSystem::start() { loadData(); int select = 0; while (true) { //打印界面 cout << ("\n***********学生考勤管理系统************\n"); cout << ("\t1: 添加学生缺课记录\n"); cout << ("\t2: 查询学生缺课记录\n"); cout << ("\t3: 修改学生缺课记录\n"); cout << ("\t4: 删除学生缺课记录\n"); cout << ("\t0: 退出系统\n"); cout << ("请选择(0-5):"); cin >> select; cin.get(); switch (select) { case 1: inputData(); break; case 2: showAllData(); break; case 3: changeData(); break; case 4: removeData(); break; default: exit(EXIT_SUCCESS); } } } // 给出列表中缺课信息的ID,返回指向它的迭代器retIter,属于辅助方法 list<stuData>::iterator StuManSystem::findDataById(int id) { list<stuData>::iterator retIter = stuDataLists.end(); list<stuData>::iterator iter = stuDataLists.begin(); for (; iter != stuDataLists.end(); iter++) { if (id == iter->id) { retIter = iter; break; } } return retIter; } // 这个方法实现从键盘录入缺课信息到data,并保存data到文件的功能 void StuManSystem::inputData() { cout << ("\n************录入缺课记录***************\n"); stuData data; cout << "请输入缺课日期(yyyy-mm-dd):"; cin >> data.date; cout << "请输入课程名(不能含有空格):"; cin >> data.class_name; cout << "请输入学生名(不能含有空格):"; cin >> data.student_name; cout << "请输入缺课信息(不能含有空格):"; cin >> data.message; stuDataLists.push_back(data); stuDataLists.back().id = stuDataLists.size(); saveData(); } // 按顺序列出所有学生的记录,输入记录编号然后修改记录 void StuManSystem::changeData() { list<stuData> lists = findData(); cout << ("\n************修改缺课记录**************\n"); if (lists.size() > 0) { cout << "请输入要修改的记录序号:"; int order; cin >> order; cin.get(); list<stuData>::iterator iter = findDataById(order); if (iter != stuDataLists.end()) { stuData data = *iter; cout << "请输入缺课日期(yyyy-mm-dd): "; cin >> data.date; cout << "请输入学生名称(不能含有空格): "; cin >> data.student_name; cout << "请输入课程名(不能含有空格): "; cin >> data.class_name; cout << "请输入缺课信息 (不能含有空格): "; cin >> data.message; *iter = data; saveData(); } else { cout << "输入错误!" << endl; } } else { cout << "暂未查询到缺课记录!" << endl; } } // 展示所有记录,输入要删除的记录序号,调用list::remove删除之 void StuManSystem::removeData() { list<stuData> lists = findData(); if (lists.size() > 0) { cout << "请输入要删除的记录序号:"; int order; cin >> order; list<stuData>::iterator iter = findDataById(order); if (iter != stuDataLists.end()) { stuDataLists.remove(*iter); saveData(); } else { cout << "输入错误!" << endl; } } else { cout << "暂未查询到缺课记录!" << endl; } } // 按顺序打印所有的缺课记录,以遍历lists的方式 void StuManSystem::showAllData() { cout << "选择记录的排序方式(1:按记录ID顺序 2:按学生名称顺序 3:按缺课时间顺序 4:按课程名称顺序): "; int order; cin >> order; if (order < 1 || order > 4) { cout << "请正确选择" << endl; return; } // 因为list不能用sort,所以通过一个vector存储信息并排序输出 vector<stuData> vec(stuDataLists.begin(), stuDataLists.end()); // 下面使用lambda表达式代替了comp函数 if (order == 1) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.id < s2.id; }); else if (order == 2) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.student_name < s2.student_name; }); else if (order == 3) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.date < s2.date; }); else if (order == 4) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.class_name < s2.class_name; }); cout << endl << "*************所有的缺课记录如下:************" << endl; vector<stuData>::const_iterator constIter = vec.cbegin(); cout << "*编号***日期******学生名****课程名****备注*\n"; for (; constIter != vec.cend(); constIter++) { cout << " " << constIter->id << " \t " << constIter->date << "\t" << constIter->student_name << "\t" << constIter->class_name << "\t" << constIter->message << endl; } } // 将保存信息的链表stuDataLists排序,并返回该链表;同时起到printAllData的功能,按顺序输出所有信息 list<stuData> StuManSystem::findData() { vector<stuData> vec(stuDataLists.begin(), stuDataLists.end()); cout << "选择记录的排序方式(1:按记录ID顺序 2:按学生名称顺序 3:按缺课时间顺序 4:按课程名称顺序): "; int order; while (cin >> order && order < 1 || order > 4) { cout << "请正确选择!" << endl; } if (order == 1) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.id < s2.id; }); else if (order == 2) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.student_name < s2.student_name; }); else if (order == 3) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.date < s2.date; }); else if (order == 4) sort(vec.begin(), vec.end(), [](stuData &s1, stuData &s2) { return s1.class_name < s2.class_name; }); list<stuData> result; vector<stuData>::const_iterator iter = vec.begin(); cout << "*编号***日期******学生名****课程名****备注*\n"; for (; iter != vec.end(); iter++) { result.push_back(*iter); cout << " " << iter->id << " \t " << iter->date << "\t" << iter->student_name << "\t" << iter->class_name << "\t" << iter->message << endl; } return result; }
[ "2063436123@qq.com" ]
2063436123@qq.com
6344581c871e84bcd5abf416fdf7d2d22656ea5b
969435924f8285d397c06340c5382eb313895e71
/src/osg/DisplaySettings.cpp
89a8ec192d4bfe78b2c71a76de65f7072395e512
[]
no_license
whztt07/osg-specialWindows
f6f4bc0bca39501055b33987c5a9361332882cde
ea637645ec3bd37ec840de123a36a0309eceb442
refs/heads/master
2021-01-18T05:49:57.268566
2015-02-26T03:50:47
2015-02-26T03:50:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,772
cpp
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/DisplaySettings> #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <osg/Math> #include <osg/Notify> #include <osg/ref_ptr> #include <algorithm> #include <string.h> using namespace osg; using namespace std; ref_ptr<DisplaySettings>& DisplaySettings::instance() { static ref_ptr<DisplaySettings> s_displaySettings = new DisplaySettings; return s_displaySettings; } DisplaySettings::DisplaySettings(const DisplaySettings& vs):Referenced(true) { setDisplaySettings(vs); } DisplaySettings::~DisplaySettings() { } DisplaySettings& DisplaySettings::operator = (const DisplaySettings& vs) { if (this==&vs) return *this; setDisplaySettings(vs); return *this; } void DisplaySettings::setDisplaySettings(const DisplaySettings& vs) { _displayType = vs._displayType; _stereo = vs._stereo; _stereoMode = vs._stereoMode; _eyeSeparation = vs._eyeSeparation; _screenWidth = vs._screenWidth; _screenHeight = vs._screenHeight; _screenDistance = vs._screenDistance; _splitStereoHorizontalEyeMapping = vs._splitStereoHorizontalEyeMapping; _splitStereoHorizontalSeparation = vs._splitStereoHorizontalSeparation; _splitStereoVerticalEyeMapping = vs._splitStereoVerticalEyeMapping; _splitStereoVerticalSeparation = vs._splitStereoVerticalSeparation; _splitStereoAutoAdjustAspectRatio = vs._splitStereoAutoAdjustAspectRatio; _doubleBuffer = vs._doubleBuffer; _RGB = vs._RGB; _depthBuffer = vs._depthBuffer; _minimumNumberAlphaBits = vs._minimumNumberAlphaBits; _minimumNumberStencilBits = vs._minimumNumberStencilBits; _minimumNumberAccumRedBits = vs._minimumNumberAccumRedBits; _minimumNumberAccumGreenBits = vs._minimumNumberAccumGreenBits; _minimumNumberAccumBlueBits = vs._minimumNumberAccumBlueBits; _minimumNumberAccumAlphaBits = vs._minimumNumberAccumAlphaBits; _maxNumOfGraphicsContexts = vs._maxNumOfGraphicsContexts; _numMultiSamples = vs._numMultiSamples; _compileContextsHint = vs._compileContextsHint; _serializeDrawDispatch = vs._serializeDrawDispatch; _useSceneViewForStereoHint = vs._useSceneViewForStereoHint; _numDatabaseThreadsHint = vs._numDatabaseThreadsHint; _numHttpDatabaseThreadsHint = vs._numHttpDatabaseThreadsHint; _application = vs._application; _maxTexturePoolSize = vs._maxTexturePoolSize; _maxBufferObjectPoolSize = vs._maxBufferObjectPoolSize; _implicitBufferAttachmentRenderMask = vs._implicitBufferAttachmentRenderMask; _implicitBufferAttachmentResolveMask = vs._implicitBufferAttachmentResolveMask; _glContextVersion = vs._glContextVersion; _glContextFlags = vs._glContextFlags; _glContextProfileMask = vs._glContextProfileMask; _swapMethod = vs._swapMethod; _keystoneHint = vs._keystoneHint; _keystoneFileNames = vs._keystoneFileNames; _keystones = vs._keystones; } void DisplaySettings::merge(const DisplaySettings& vs) { if (_stereo || vs._stereo) _stereo = true; // need to think what to do about merging the stereo mode. if (_doubleBuffer || vs._doubleBuffer) _doubleBuffer = true; if (_RGB || vs._RGB) _RGB = true; if (_depthBuffer || vs._depthBuffer) _depthBuffer = true; if (vs._minimumNumberAlphaBits>_minimumNumberAlphaBits) _minimumNumberAlphaBits = vs._minimumNumberAlphaBits; if (vs._minimumNumberStencilBits>_minimumNumberStencilBits) _minimumNumberStencilBits = vs._minimumNumberStencilBits; if (vs._numMultiSamples>_numMultiSamples) _numMultiSamples = vs._numMultiSamples; if (vs._compileContextsHint) _compileContextsHint = vs._compileContextsHint; if (vs._serializeDrawDispatch) _serializeDrawDispatch = vs._serializeDrawDispatch; if (vs._useSceneViewForStereoHint) _useSceneViewForStereoHint = vs._useSceneViewForStereoHint; if (vs._numDatabaseThreadsHint>_numDatabaseThreadsHint) _numDatabaseThreadsHint = vs._numDatabaseThreadsHint; if (vs._numHttpDatabaseThreadsHint>_numHttpDatabaseThreadsHint) _numHttpDatabaseThreadsHint = vs._numHttpDatabaseThreadsHint; if (_application.empty()) _application = vs._application; if (vs._maxTexturePoolSize>_maxTexturePoolSize) _maxTexturePoolSize = vs._maxTexturePoolSize; if (vs._maxBufferObjectPoolSize>_maxBufferObjectPoolSize) _maxBufferObjectPoolSize = vs._maxBufferObjectPoolSize; // these are bit masks so merging them is like logical or _implicitBufferAttachmentRenderMask |= vs._implicitBufferAttachmentRenderMask; _implicitBufferAttachmentResolveMask |= vs._implicitBufferAttachmentResolveMask; // merge swap method to higher value if( vs._swapMethod > _swapMethod ) _swapMethod = vs._swapMethod; _keystoneHint = _keystoneHint | vs._keystoneHint; // insert any unique filenames into the local list for(FileNames::const_iterator itr = vs._keystoneFileNames.begin(); itr != vs._keystoneFileNames.end(); ++itr) { const std::string& filename = *itr; FileNames::iterator found_itr = std::find(_keystoneFileNames.begin(), _keystoneFileNames.end(), filename); if (found_itr == _keystoneFileNames.end()) _keystoneFileNames.push_back(filename); } // insert unique Keystone object into local list for(Objects::const_iterator itr = vs._keystones.begin(); itr != vs._keystones.end(); ++itr) { const osg::Object* object = itr->get(); Objects::iterator found_itr = std::find(_keystones.begin(), _keystones.end(), object); if (found_itr == _keystones.end()) _keystones.push_back(const_cast<osg::Object*>(object)); } } void DisplaySettings::setDefaults() { _displayType = MONITOR; _stereo = false; _stereoMode = ANAGLYPHIC; _eyeSeparation = 0.05f; _screenWidth = 0.325f; _screenHeight = 0.26f; _screenDistance = 0.5f; _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT; _splitStereoHorizontalSeparation = 0; _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT; _splitStereoVerticalSeparation = 0; _splitStereoAutoAdjustAspectRatio = false; _doubleBuffer = true; _RGB = true; _depthBuffer = true; _minimumNumberAlphaBits = 8; _minimumNumberStencilBits = 0; _minimumNumberAccumRedBits = 0; _minimumNumberAccumGreenBits = 0; _minimumNumberAccumBlueBits = 0; _minimumNumberAccumAlphaBits = 0; _maxNumOfGraphicsContexts = 32; _numMultiSamples = 0; #ifdef __sgi // switch on anti-aliasing by default, just in case we have an Onyx :-) _numMultiSamples = 4; #endif _compileContextsHint = false; _serializeDrawDispatch = false; _useSceneViewForStereoHint = true; _numDatabaseThreadsHint = 2; _numHttpDatabaseThreadsHint = 1; _maxTexturePoolSize = 0; _maxBufferObjectPoolSize = 0; _implicitBufferAttachmentRenderMask = DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; _implicitBufferAttachmentResolveMask = DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; _glContextVersion = "4.4"; // XXX blf: Boosting OpenGL interface level. _glContextFlags = 0; _glContextProfileMask = 0; _swapMethod = SWAP_DEFAULT; _keystoneHint = false; } void DisplaySettings::setMaxNumberOfGraphicsContexts(unsigned int num) { _maxNumOfGraphicsContexts = num; } unsigned int DisplaySettings::getMaxNumberOfGraphicsContexts() const { // OSG_NOTICE<<"getMaxNumberOfGraphicsContexts()="<<_maxNumOfGraphicsContexts<<std::endl; return _maxNumOfGraphicsContexts; } void DisplaySettings::setMinimumNumAccumBits(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha) { _minimumNumberAccumRedBits = red; _minimumNumberAccumGreenBits = green; _minimumNumberAccumBlueBits = blue; _minimumNumberAccumAlphaBits = alpha; } static ApplicationUsageProxy DisplaySetting_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_DISPLAY_TYPE <type>", "MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY"); static ApplicationUsageProxy DisplaySetting_e1(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_STEREO_MODE <mode>", "QUAD_BUFFER | ANAGLYPHIC | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE | VERTICAL_INTERLACE | HORIZONTAL_INTERLACE"); static ApplicationUsageProxy DisplaySetting_e2(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_STEREO <mode>", "OFF | ON"); static ApplicationUsageProxy DisplaySetting_e3(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_EYE_SEPARATION <float>", "Physical distance between eyes."); static ApplicationUsageProxy DisplaySetting_e4(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SCREEN_DISTANCE <float>", "Physical distance between eyes and screen."); static ApplicationUsageProxy DisplaySetting_e5(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SCREEN_HEIGHT <float>", "Physical screen height."); static ApplicationUsageProxy DisplaySetting_e6(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SCREEN_WIDTH <float>", "Physical screen width."); static ApplicationUsageProxy DisplaySetting_e7(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING <mode>", "LEFT_EYE_LEFT_VIEWPORT | LEFT_EYE_RIGHT_VIEWPORT"); static ApplicationUsageProxy DisplaySetting_e8(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION <float>", "Number of pixels between viewports."); static ApplicationUsageProxy DisplaySetting_e9(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING <mode>", "LEFT_EYE_TOP_VIEWPORT | LEFT_EYE_BOTTOM_VIEWPORT"); static ApplicationUsageProxy DisplaySetting_e10(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO <mode>", "OFF | ON Default to OFF to compenstate for the compression of the aspect ratio when viewing in split screen stereo. Note, if you are setting fovx and fovy explicityly OFF should be used."); static ApplicationUsageProxy DisplaySetting_e11(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SPLIT_STEREO_VERTICAL_SEPARATION <float>", "Number of pixels between viewports."); static ApplicationUsageProxy DisplaySetting_e12(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS <int>", "Maximum number of graphics contexts to be used with applications."); static ApplicationUsageProxy DisplaySetting_e13(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_COMPILE_CONTEXTS <mode>", "OFF | ON Disable/enable the use of background compiled contexts and threads."); static ApplicationUsageProxy DisplaySetting_e14(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SERIALIZE_DRAW_DISPATCH <mode>", "OFF | ON Disable/enable the use of a mutex to serialize the draw dispatch when there are multiple graphics threads."); static ApplicationUsageProxy DisplaySetting_e15(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_USE_SCENEVIEW_FOR_STEREO <mode>", "OFF | ON Disable/enable the hint to use osgUtil::SceneView to implement stereo when required.."); static ApplicationUsageProxy DisplaySetting_e16(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_NUM_DATABASE_THREADS <int>", "Set the hint for the total number of threads to set up in the DatabasePager."); static ApplicationUsageProxy DisplaySetting_e17(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_NUM_HTTP_DATABASE_THREADS <int>", "Set the hint for the total number of threads dedicated to http requests to set up in the DatabasePager."); static ApplicationUsageProxy DisplaySetting_e18(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_MULTI_SAMPLES <int>", "Set the hint for the number of samples to use when multi-sampling."); static ApplicationUsageProxy DisplaySetting_e19(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_TEXTURE_POOL_SIZE <int>", "Set the hint for the size of the texture pool to manage."); static ApplicationUsageProxy DisplaySetting_e20(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_BUFFER_OBJECT_POOL_SIZE <int>", "Set the hint for the size of the vertex buffer object pool to manage."); static ApplicationUsageProxy DisplaySetting_e21(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_FBO_POOL_SIZE <int>", "Set the hint for the size of the frame buffer object pool to manage."); static ApplicationUsageProxy DisplaySetting_e22(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_IMPLICIT_BUFFER_ATTACHMENT_RENDER_MASK", "OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for render FBO."); static ApplicationUsageProxy DisplaySetting_e23(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_IMPLICIT_BUFFER_ATTACHMENT_RESOLVE_MASK", "OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for resolve FBO."); static ApplicationUsageProxy DisplaySetting_e24(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_GL_CONTEXT_VERSION <major.minor>", "Set the hint for the GL version to create contexts for."); static ApplicationUsageProxy DisplaySetting_e25(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_GL_CONTEXT_FLAGS <uint>", "Set the hint for the GL context flags to use when creating contexts."); static ApplicationUsageProxy DisplaySetting_e26(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_GL_CONTEXT_PROFILE_MASK <uint>", "Set the hint for the GL context profile mask to use when creating contexts."); static ApplicationUsageProxy DisplaySetting_e27(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_SWAP_METHOD <method>", "DEFAULT | EXCHANGE | COPY | UNDEFINED. Select preferred swap method."); static ApplicationUsageProxy DisplaySetting_e28(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_KEYSTONE ON | OFF", "Specify the hint to whether the viewer should set up keystone correction."); static ApplicationUsageProxy DisplaySetting_e29(ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_KEYSTONE_FILES <filename>[:filename]..", "Specify filenames of keystone parameter files. Under Windows use ; to deliminate files, otherwise use :"); void DisplaySettings::readEnvironmentalVariables() { const char* ptr = 0; if ((ptr = getenv("OSG_DISPLAY_TYPE")) != 0) { if (strcmp(ptr,"MONITOR")==0) { _displayType = MONITOR; } else if (strcmp(ptr,"POWERWALL")==0) { _displayType = POWERWALL; } else if (strcmp(ptr,"REALITY_CENTER")==0) { _displayType = REALITY_CENTER; } else if (strcmp(ptr,"HEAD_MOUNTED_DISPLAY")==0) { _displayType = HEAD_MOUNTED_DISPLAY; } } if( (ptr = getenv("OSG_STEREO_MODE")) != 0) { if (strcmp(ptr,"QUAD_BUFFER")==0) { _stereoMode = QUAD_BUFFER; } else if (strcmp(ptr,"ANAGLYPHIC")==0) { _stereoMode = ANAGLYPHIC; } else if (strcmp(ptr,"HORIZONTAL_SPLIT")==0) { _stereoMode = HORIZONTAL_SPLIT; } else if (strcmp(ptr,"VERTICAL_SPLIT")==0) { _stereoMode = VERTICAL_SPLIT; } else if (strcmp(ptr,"LEFT_EYE")==0) { _stereoMode = LEFT_EYE; } else if (strcmp(ptr,"RIGHT_EYE")==0) { _stereoMode = RIGHT_EYE; } else if (strcmp(ptr,"HORIZONTAL_INTERLACE")==0) { _stereoMode = HORIZONTAL_INTERLACE; } else if (strcmp(ptr,"VERTICAL_INTERLACE")==0) { _stereoMode = VERTICAL_INTERLACE; } else if (strcmp(ptr,"CHECKERBOARD")==0) { _stereoMode = CHECKERBOARD; } } if( (ptr = getenv("OSG_STEREO")) != 0) { if (strcmp(ptr,"OFF")==0) { _stereo = false; } else if (strcmp(ptr,"ON")==0) { _stereo = true; } } if( (ptr = getenv("OSG_EYE_SEPARATION")) != 0) { _eyeSeparation = osg::asciiToFloat(ptr); } if( (ptr = getenv("OSG_SCREEN_WIDTH")) != 0) { _screenWidth = osg::asciiToFloat(ptr); } if( (ptr = getenv("OSG_SCREEN_HEIGHT")) != 0) { _screenHeight = osg::asciiToFloat(ptr); } if( (ptr = getenv("OSG_SCREEN_DISTANCE")) != 0) { _screenDistance = osg::asciiToFloat(ptr); } if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_EYE_MAPPING")) != 0) { if (strcmp(ptr,"LEFT_EYE_LEFT_VIEWPORT")==0) { _splitStereoHorizontalEyeMapping = LEFT_EYE_LEFT_VIEWPORT; } else if (strcmp(ptr,"LEFT_EYE_RIGHT_VIEWPORT")==0) { _splitStereoHorizontalEyeMapping = LEFT_EYE_RIGHT_VIEWPORT; } } if( (ptr = getenv("OSG_SPLIT_STEREO_HORIZONTAL_SEPARATION")) != 0) { _splitStereoHorizontalSeparation = atoi(ptr); } if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_EYE_MAPPING")) != 0) { if (strcmp(ptr,"LEFT_EYE_TOP_VIEWPORT")==0) { _splitStereoVerticalEyeMapping = LEFT_EYE_TOP_VIEWPORT; } else if (strcmp(ptr,"LEFT_EYE_BOTTOM_VIEWPORT")==0) { _splitStereoVerticalEyeMapping = LEFT_EYE_BOTTOM_VIEWPORT; } } if( (ptr = getenv("OSG_SPLIT_STEREO_AUTO_ADJUST_ASPECT_RATIO")) != 0) { if (strcmp(ptr,"OFF")==0) { _splitStereoAutoAdjustAspectRatio = false; } else if (strcmp(ptr,"ON")==0) { _splitStereoAutoAdjustAspectRatio = true; } } if( (ptr = getenv("OSG_SPLIT_STEREO_VERTICAL_SEPARATION")) != 0) { _splitStereoVerticalSeparation = atoi(ptr); } if( (ptr = getenv("OSG_MAX_NUMBER_OF_GRAPHICS_CONTEXTS")) != 0) { _maxNumOfGraphicsContexts = atoi(ptr); } if( (ptr = getenv("OSG_COMPIlE_CONTEXTS")) != 0) { if (strcmp(ptr,"OFF")==0) { _compileContextsHint = false; } else if (strcmp(ptr,"ON")==0) { _compileContextsHint = true; } } if( (ptr = getenv("OSG_SERIALIZE_DRAW_DISPATCH")) != 0) { if (strcmp(ptr,"OFF")==0) { _serializeDrawDispatch = false; } else if (strcmp(ptr,"ON")==0) { _serializeDrawDispatch = true; } } if( (ptr = getenv("OSG_USE_SCENEVIEW_FOR_STEREO")) != 0) { if (strcmp(ptr,"OFF")==0) { _useSceneViewForStereoHint = false; } else if (strcmp(ptr,"ON")==0) { _useSceneViewForStereoHint = true; } } if( (ptr = getenv("OSG_NUM_DATABASE_THREADS")) != 0) { _numDatabaseThreadsHint = atoi(ptr); } if( (ptr = getenv("OSG_NUM_HTTP_DATABASE_THREADS")) != 0) { _numHttpDatabaseThreadsHint = atoi(ptr); } if( (ptr = getenv("OSG_MULTI_SAMPLES")) != 0) { _numMultiSamples = atoi(ptr); } if( (ptr = getenv("OSG_TEXTURE_POOL_SIZE")) != 0) { _maxTexturePoolSize = atoi(ptr); } if( (ptr = getenv("OSG_BUFFER_OBJECT_POOL_SIZE")) != 0) { _maxBufferObjectPoolSize = atoi(ptr); } { // Read implicit buffer attachments combinations for both render and resolve mask const char * variable[] = { "OSG_IMPLICIT_BUFFER_ATTACHMENT_RENDER_MASK", "OSG_IMPLICIT_BUFFER_ATTACHMENT_RESOLVE_MASK", }; int * mask[] = { &_implicitBufferAttachmentRenderMask, &_implicitBufferAttachmentResolveMask, }; for( unsigned int n = 0; n < sizeof( variable ) / sizeof( variable[0] ); n++ ) { const char* env = getenv( variable[n] ); if ( !env ) continue; std::string str(env); if(str.find("OFF")!=std::string::npos) *mask[n] = 0; if(str.find("~DEFAULT")!=std::string::npos) *mask[n] ^= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; else if(str.find("DEFAULT")!=std::string::npos) *mask[n] |= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; if(str.find("~COLOR")!=std::string::npos) *mask[n] ^= IMPLICIT_COLOR_BUFFER_ATTACHMENT; else if(str.find("COLOR")!=std::string::npos) *mask[n] |= IMPLICIT_COLOR_BUFFER_ATTACHMENT; if(str.find("~DEPTH")!=std::string::npos) *mask[n] ^= IMPLICIT_DEPTH_BUFFER_ATTACHMENT; else if(str.find("DEPTH")!=std::string::npos) *mask[n] |= (int)IMPLICIT_DEPTH_BUFFER_ATTACHMENT; if(str.find("~STENCIL")!=std::string::npos) *mask[n] ^= (int)IMPLICIT_STENCIL_BUFFER_ATTACHMENT; else if(str.find("STENCIL")!=std::string::npos) *mask[n] |= (int)IMPLICIT_STENCIL_BUFFER_ATTACHMENT; } } if( (ptr = getenv("OSG_GL_VERSION")) != 0 || (ptr = getenv("OSG_GL_CONTEXT_VERSION")) != 0) { _glContextVersion = ptr; } if( (ptr = getenv("OSG_GL_CONTEXT_FLAGS")) != 0) { _glContextFlags = atoi(ptr); } if( (ptr = getenv("OSG_GL_CONTEXT_PROFILE_MASK")) != 0) { _glContextProfileMask = atoi(ptr); } if ((ptr = getenv("OSG_SWAP_METHOD")) != 0) { if (strcmp(ptr,"DEFAULT")==0) { _swapMethod = SWAP_DEFAULT; } else if (strcmp(ptr,"EXCHANGE")==0) { _swapMethod = SWAP_EXCHANGE; } else if (strcmp(ptr,"COPY")==0) { _swapMethod = SWAP_COPY; } else if (strcmp(ptr,"UNDEFINED")==0) { _swapMethod = SWAP_UNDEFINED; } } if( (ptr = getenv("OSG_KEYSTONE")) != 0) { if (strcmp(ptr,"OFF")==0) { _keystoneHint = false; } else if (strcmp(ptr,"ON")==0) { _keystoneHint = true; } } if ((ptr = getenv("OSG_KEYSTONE_FILES")) != 0) { #if defined(WIN32) && !defined(__CYGWIN__) char delimitor = ';'; #else char delimitor = ':'; #endif std::string paths(ptr); if (!paths.empty()) { std::string::size_type start = 0; std::string::size_type end; while ((end = paths.find_first_of(delimitor,start))!=std::string::npos) { _keystoneFileNames.push_back(std::string(paths,start,end-start)); start = end+1; } std::string lastPath(paths,start,std::string::npos); if (!lastPath.empty()) _keystoneFileNames.push_back(lastPath); } } } void DisplaySettings::readCommandLine(ArgumentParser& arguments) { if (_application.empty()) _application = arguments[0]; // report the usage options. if (arguments.getApplicationUsage()) { arguments.getApplicationUsage()->addCommandLineOption("--display <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY"); arguments.getApplicationUsage()->addCommandLineOption("--stereo","Use default stereo mode which is ANAGLYPHIC if not overriden by environmental variable"); arguments.getApplicationUsage()->addCommandLineOption("--stereo <mode>","ANAGLYPHIC | QUAD_BUFFER | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE | HORIZONTAL_INTERLACE | VERTICAL_INTERLACE | CHECKERBOARD | ON | OFF "); arguments.getApplicationUsage()->addCommandLineOption("--rgba","Request a RGBA color buffer visual"); arguments.getApplicationUsage()->addCommandLineOption("--stencil","Request a stencil buffer visual"); arguments.getApplicationUsage()->addCommandLineOption("--accum-rgb","Request a rgb accumulator buffer visual"); arguments.getApplicationUsage()->addCommandLineOption("--accum-rgba","Request a rgb accumulator buffer visual"); arguments.getApplicationUsage()->addCommandLineOption("--samples <num>","Request a multisample visual"); arguments.getApplicationUsage()->addCommandLineOption("--cc","Request use of compile contexts and threads"); arguments.getApplicationUsage()->addCommandLineOption("--serialize-draw <mode>","OFF | ON - set the serialization of draw dispatch"); arguments.getApplicationUsage()->addCommandLineOption("--implicit-buffer-attachment-render-mask","OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for render FBO"); arguments.getApplicationUsage()->addCommandLineOption("--implicit-buffer-attachment-resolve-mask","OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for resolve FBO"); arguments.getApplicationUsage()->addCommandLineOption("--gl-version <major.minor>","Set the hint of which GL version to use when creating graphics contexts."); arguments.getApplicationUsage()->addCommandLineOption("--gl-flags <mask>","Set the hint of which GL flags projfile mask to use when creating graphics contexts."); arguments.getApplicationUsage()->addCommandLineOption("--gl-profile-mask <mask>","Set the hint of which GL context profile mask to use when creating graphics contexts."); arguments.getApplicationUsage()->addCommandLineOption("--swap-method <method>","DEFAULT | EXCHANGE | COPY | UNDEFINED. Select preferred swap method."); arguments.getApplicationUsage()->addCommandLineOption("--keystone <filename>","Specify a keystone file to be used by the viewer for keystone correction."); arguments.getApplicationUsage()->addCommandLineOption("--keystone-on","Set the keystone hint to true to tell the viewer to do keystone correction."); arguments.getApplicationUsage()->addCommandLineOption("--keystone-off","Set the keystone hint to false."); } std::string str; while(arguments.read("--display",str)) { if (str=="MONITOR") _displayType = MONITOR; else if (str=="POWERWALL") _displayType = POWERWALL; else if (str=="REALITY_CENTER") _displayType = REALITY_CENTER; else if (str=="HEAD_MOUNTED_DISPLAY") _displayType = HEAD_MOUNTED_DISPLAY; } int pos; while ((pos=arguments.find("--stereo"))>0) { if (arguments.match(pos+1,"ANAGLYPHIC")) { arguments.remove(pos,2); _stereo = true;_stereoMode = ANAGLYPHIC; } else if (arguments.match(pos+1,"QUAD_BUFFER")) { arguments.remove(pos,2); _stereo = true;_stereoMode = QUAD_BUFFER; } else if (arguments.match(pos+1,"HORIZONTAL_SPLIT")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_SPLIT; } else if (arguments.match(pos+1,"VERTICAL_SPLIT")) { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_SPLIT; } else if (arguments.match(pos+1,"HORIZONTAL_INTERLACE")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_INTERLACE; } else if (arguments.match(pos+1,"VERTICAL_INTERLACE")) { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_INTERLACE; } else if (arguments.match(pos+1,"CHECKERBOARD")) { arguments.remove(pos,2); _stereo = true;_stereoMode = CHECKERBOARD; } else if (arguments.match(pos+1,"LEFT_EYE")) { arguments.remove(pos,2); _stereo = true;_stereoMode = LEFT_EYE; } else if (arguments.match(pos+1,"RIGHT_EYE")) { arguments.remove(pos,2); _stereo = true;_stereoMode = RIGHT_EYE; } else if (arguments.match(pos+1,"ON")) { arguments.remove(pos,2); _stereo = true; } else if (arguments.match(pos+1,"OFF")) { arguments.remove(pos,2); _stereo = false; } else { arguments.remove(pos); _stereo = true; } } while (arguments.read("--rgba")) { _RGB = true; _minimumNumberAlphaBits = 1; } while (arguments.read("--stencil")) { _minimumNumberStencilBits = 1; } while (arguments.read("--accum-rgb")) { setMinimumNumAccumBits(8,8,8,0); } while (arguments.read("--accum-rgba")) { setMinimumNumAccumBits(8,8,8,8); } while(arguments.read("--samples",str)) { _numMultiSamples = atoi(str.c_str()); } if (arguments.read("--keystone",str)) { _keystoneHint = true; if (!_keystoneFileNames.empty()) _keystoneFileNames.clear(); _keystoneFileNames.push_back(str); while(arguments.read("--keystone",str)) { _keystoneFileNames.push_back(str); } } if (arguments.read("--keystone-on")) { _keystoneHint = true; } if (arguments.read("--keystone-off")) { _keystoneHint = false; } while(arguments.read("--cc")) { _compileContextsHint = true; } while(arguments.read("--serialize-draw",str)) { if (str=="ON") _serializeDrawDispatch = true; else if (str=="OFF") _serializeDrawDispatch = false; } while(arguments.read("--num-db-threads",_numDatabaseThreadsHint)) {} while(arguments.read("--num-http-threads",_numHttpDatabaseThreadsHint)) {} while(arguments.read("--texture-pool-size",_maxTexturePoolSize)) {} while(arguments.read("--buffer-object-pool-size",_maxBufferObjectPoolSize)) {} { // Read implicit buffer attachments combinations for both render and resolve mask const char* option[] = { "--implicit-buffer-attachment-render-mask", "--implicit-buffer-attachment-resolve-mask", }; int * mask[] = { &_implicitBufferAttachmentRenderMask, &_implicitBufferAttachmentResolveMask, }; for( unsigned int n = 0; n < sizeof( option ) / sizeof( option[0]); n++ ) { while(arguments.read( option[n],str)) { if(str.find("OFF")!=std::string::npos) *mask[n] = 0; if(str.find("~DEFAULT")!=std::string::npos) *mask[n] ^= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; else if(str.find("DEFAULT")!=std::string::npos) *mask[n] |= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT; if(str.find("~COLOR")!=std::string::npos) *mask[n] ^= IMPLICIT_COLOR_BUFFER_ATTACHMENT; else if(str.find("COLOR")!=std::string::npos) *mask[n] |= IMPLICIT_COLOR_BUFFER_ATTACHMENT; if(str.find("~DEPTH")!=std::string::npos) *mask[n] ^= IMPLICIT_DEPTH_BUFFER_ATTACHMENT; else if(str.find("DEPTH")!=std::string::npos) *mask[n] |= IMPLICIT_DEPTH_BUFFER_ATTACHMENT; if(str.find("~STENCIL")!=std::string::npos) *mask[n] ^= IMPLICIT_STENCIL_BUFFER_ATTACHMENT; else if(str.find("STENCIL")!=std::string::npos) *mask[n] |= IMPLICIT_STENCIL_BUFFER_ATTACHMENT; } } } while (arguments.read("--gl-version", _glContextVersion)) {} while (arguments.read("--gl-flags", _glContextFlags)) {} while (arguments.read("--gl-profile-mask", _glContextProfileMask)) {} while(arguments.read("--swap-method",str)) { if (str=="DEFAULT") _swapMethod = SWAP_DEFAULT; else if (str=="EXCHANGE") _swapMethod = SWAP_EXCHANGE; else if (str=="COPY") _swapMethod = SWAP_COPY; else if (str=="UNDEFINED") _swapMethod = SWAP_UNDEFINED; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Helper funciotns for computing projection and view matrices of left and right eyes // osg::Matrixd DisplaySettings::computeLeftEyeProjectionImplementation(const osg::Matrixd& projection) const { double iod = getEyeSeparation(); double sd = getScreenDistance(); double scale_x = 1.0; double scale_y = 1.0; if (getSplitStereoAutoAdjustAspectRatio()) { switch(getStereoMode()) { case(HORIZONTAL_SPLIT): scale_x = 2.0; break; case(VERTICAL_SPLIT): scale_y = 2.0; break; default: break; } } if (getDisplayType()==HEAD_MOUNTED_DISPLAY) { // head mounted display has the same projection matrix for left and right eyes. return osg::Matrixd::scale(scale_x,scale_y,1.0) * projection; } else { // all other display types assume working like a projected power wall // need to shjear projection matrix to account for asymetric frustum due to eye offset. return osg::Matrixd(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, iod/(2.0*sd),0.0,1.0,0.0, 0.0,0.0,0.0,1.0) * osg::Matrixd::scale(scale_x,scale_y,1.0) * projection; } } osg::Matrixd DisplaySettings::computeLeftEyeViewImplementation(const osg::Matrixd& view, double eyeSeperationScale) const { double iod = getEyeSeparation(); double es = 0.5f*iod*eyeSeperationScale; return view * osg::Matrixd(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, es,0.0,0.0,1.0); } osg::Matrixd DisplaySettings::computeRightEyeProjectionImplementation(const osg::Matrixd& projection) const { double iod = getEyeSeparation(); double sd = getScreenDistance(); double scale_x = 1.0; double scale_y = 1.0; if (getSplitStereoAutoAdjustAspectRatio()) { switch(getStereoMode()) { case(HORIZONTAL_SPLIT): scale_x = 2.0; break; case(VERTICAL_SPLIT): scale_y = 2.0; break; default: break; } } if (getDisplayType()==HEAD_MOUNTED_DISPLAY) { // head mounted display has the same projection matrix for left and right eyes. return osg::Matrixd::scale(scale_x,scale_y,1.0) * projection; } else { // all other display types assume working like a projected power wall // need to shjear projection matrix to account for asymetric frustum due to eye offset. return osg::Matrixd(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, -iod/(2.0*sd),0.0,1.0,0.0, 0.0,0.0,0.0,1.0) * osg::Matrixd::scale(scale_x,scale_y,1.0) * projection; } } osg::Matrixd DisplaySettings::computeRightEyeViewImplementation(const osg::Matrixd& view, double eyeSeperationScale) const { double iod = getEyeSeparation(); double es = 0.5*iod*eyeSeperationScale; return view * osg::Matrixd(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, -es,0.0,0.0,1.0); }
[ "bfurtaw@csc.com" ]
bfurtaw@csc.com
ef717ca61bba9f28f19415b04a41fe286e78a9fc
0c384a65fb670fbc0a2dde7d33054cb18429634e
/SocketAnnotator/source/CAnnotation.h
b79ba734341dbbbaa54aca6e77c07f0f8341c018
[]
no_license
DURAARK/elecdetect
c204347a24ecb025a3f712d5f31ed845d0385516
fb711de94893905e1e26be65924600ff4b188895
refs/heads/master
2016-09-03T07:09:09.205956
2015-04-24T13:00:23
2015-04-24T13:00:23
34,518,807
1
0
null
null
null
null
UTF-8
C++
false
false
2,491
h
/* * CAnnotation.h * * Created on: Jun 13, 2014 * Author: test */ #ifndef CANNOTATION_H_ #define CANNOTATION_H_ #include <string> #include <vector> #include <iomanip> #include <sstream> #include <opencv2/opencv.hpp> #include "tinyxml2.h" #include "Utils.h" #define SMP_FULL_SIZE_MM 128.0 // how big is the whole sample incl. context #define SOCKET_DIAMETER_MM 38.0 // socket diameter that will be matched for socket annotations #define PIXEL_PER_SQ_MM 1.0 // spatial resolution of the samples #define SWITCH_SIZE_MM 55.0 // reference switch size #define SWITCH_SIZE_MM_FROM 50.0 // generate different sizes of switches (FROM-TO) #define SWITCH_SIZE_MM_TO 60.0 #define POS_SMP_PER_ANNO 5 // how many random samples are generated from one annotation #define NEG_SMP_PER_IMG 10 // how many negative examples are extracted from one image #define IMG_VIEW_SIZE 1024 #define IMG_ZOOM_REGION 300 using namespace std; using namespace cv; using namespace tinyxml2; void onMouse(int event, int x, int y, int flag, void* gui_ptr_arg); class CAnnotation { private: CAnnotation() : img_filename_(""), exit_annotation_(false), rescale_view_factor_(0) { } string img_filename_; Mat img_; vector<vector<Point> > sockets_; vector<vector<Point> > switches_; vector<Point> rect_plane_; vector<Point> cur_annotation_; bool exit_annotation_; double rescale_view_factor_; static int crop_socket_cnt_; static int crop_switch_cnt_; static int crop_neg_cnt_; public: // constructor that reads the image CAnnotation(string img_filename); // copy constructor CAnnotation(const CAnnotation& other); virtual ~CAnnotation(); bool isImageLoaded(); // annotate: user interaction method (automatically resets previous annotations) bool annotate(); // returns false if the programm needs to be aborted // refine existing annotations void refine(); // show: shows image with annotations void show(); // zooming window method void zoomRegion(int x, int y); // reset annotations void reset(); // write annotations as XML string void addXMLString(XMLDocument& doc); // load annotations from an XML Element void loadFromXMLElement(XMLElement* xml_el); // crop image void saveAnnotatedImages(const string& prefix = ""); void mouseInputHandler(int event, int flag, int x, int y); }; #endif /* CANNOTATION_H_ */
[ "robert.viehauser@student.tugraz.at" ]
robert.viehauser@student.tugraz.at
8b89a878edb775063674caea6507ec53f8f3c8bf
90a50773ad9d10f586aa92a7be7e8dc88d392a15
/atcoder/abc138/F/main.cpp
bbbb08173307bfc2084114c6c5a8a98e3cdea3d2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yukirin/coder
e0eebc55886fd4a4a62bab80ae6bd980bb0e8409
3a04e9d19011b126bf4b3b0e6d089e6746fb58d5
refs/heads/master
2022-09-27T05:06:34.144714
2022-09-19T14:10:37
2022-09-19T14:10:37
86,316,125
1
1
null
null
null
null
UTF-8
C++
false
false
2,252
cpp
#include <bits/stdc++.h> #ifdef _DEBUG #define debug(x) cerr << "line: " << __LINE__ << ", func: " << __func__ << " -> " << #x << " = " << x << endl #define INFILE freopen("input.txt", "r", stdin) #else #define debug(x) #define INFILE #endif #define ALL(s) begin(s), end(s) #define RALL(s) rbegin(s), rend(s) #define REP(i, a, b) for (int i = (a); i < (b); i++) #define RREP(i, a, b) for (int i = (a); i >= (b); i--) using namespace std; using ll = long long; using ull = unsigned long long; using i_i = pair<int, int>; using ll_ll = pair<ll, ll>; using d_ll = pair<double, ll>; using ll_d = pair<ll, double>; using d_d = pair<double, double>; static constexpr ll INF = 1LL << 60; static constexpr double PI = static_cast<double>(3.14159265358979323846264338327950288); static constexpr double EPS = numeric_limits<double>::epsilon(); static constexpr ll MOD = 1000000007; static map<type_index, const char* const> scanType = { {typeid(int), "%d"}, {typeid(ll), "%lld"}, {typeid(double), "%lf"}, {typeid(char), "%c"}}; template <class T> static void scan(vector<T>& v); [[maybe_unused]] static void scan(vector<string>& v, bool isWord = true); template <class T> static inline bool chmax(T& a, T b); template <class T> static inline bool chmin(T& a, T b); template <class A, size_t N, class T> static void Fill(A (&arr)[N], const T& val); int main(int argc, char* argv[]) { long long L; scanf("%lld",&L); long long R; scanf("%lld",&R); return 0; } template <class T> static void scan(vector<T>& v) { auto tFormat = scanType[typeid(T)]; for (T& n : v) { scanf(tFormat, &n); } } static void scan(vector<string>& v, bool isWord) { if (isWord) { for (auto& n : v) { cin >> n; } return; } int i = 0, size = v.size(); string s; getline(cin, s); if (s.size() != 0) { i++; v[0] = s; } for (; i < size; ++i) { getline(cin, v[i]); } } template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template <class A, size_t N, class T> void Fill(A (&arr)[N], const T& val) { std::fill((T*)arr, (T*)(arr + N), val); }
[ "standupdown@gmail.com" ]
standupdown@gmail.com
2a95836d74d1b91923e1d73656d8905cca400cfc
06fd941971c623ea194a45b1ad457ca4ee7da3b7
/src/rrt.cpp
bd90e3c50cc24dcdc28de3e3ca46be15ec3e635f
[]
no_license
wenzhong1/path_planning
eda4d112962c01be0ec6d23d41659431daffdfbc
270463b22a12d2497d96360c455c055b65639150
refs/heads/master
2020-09-08T13:16:57.437403
2019-08-20T15:40:51
2019-08-20T15:40:51
221,144,679
2
0
null
2019-11-12T06:19:33
2019-11-12T06:19:33
null
UTF-8
C++
false
false
6,462
cpp
/** * @file rrt.cpp * @author vss2sn * @brief Contains the RRT class */ #include "rrt.hpp" Node RRT::FindNearestPoint(Node& new_node){ Node nearest_node(-1,-1,-1,-1,-1,-1); std::vector<Node>::iterator it_v; std::vector<Node>::iterator it_v_store; //use just distance not total cost double dist = (double)(n*n); double new_dist = dist; for(it_v = point_list_.begin(); it_v != point_list_.end(); ++it_v){ new_dist = (double)sqrt((double)(it_v->x_-new_node.x_)*(double)(it_v->x_-new_node.x_)+ (double)(it_v->y_-new_node.y_)*(double)(it_v->y_-new_node.y_)); if(new_dist > threshold_) continue; if(CheckObstacle(*it_v, new_node)) continue; if(it_v->id_==new_node.id_) continue; if(it_v->pid_==new_node.id_) continue; if(new_dist >= dist) continue; dist = new_dist; it_v_store = it_v; } if(dist!=n*n){ nearest_node = *it_v_store; new_node.pid_ = nearest_node.id_; new_node.cost_ = nearest_node.cost_ + dist; } return nearest_node; } bool RRT::CheckObstacle(Node& n_1, Node& n_2){ if (n_2.y_ - n_1.y_ == 0){ double c = n_2.y_; for(auto it_v = obstacle_list_.begin(); it_v!=obstacle_list_.end(); ++it_v){ if(!(((n_1.x_>=it_v->x_) && (it_v->x_>= n_2.x_)) || ((n_1.x_<=it_v->x_) && (it_v->x_<= n_2.x_)))) continue; if ((double)it_v->y_ == c) return true; } } else { double slope = (double)(n_2.x_ - n_1.x_)/(double)(n_2.y_ - n_1.y_); std::vector<Node>::iterator it_v; double c = (double)n_2.x_ - slope * (double)n_2.y_; for(auto it_v = obstacle_list_.begin(); it_v!=obstacle_list_.end(); ++it_v){ if(!(((n_1.y_>=it_v->y_) && (it_v->y_>= n_2.y_)) || ((n_1.y_<=it_v->y_) && (it_v->y_<= n_2.y_)))) continue; if(!(((n_1.x_>=it_v->x_) && (it_v->x_>= n_2.x_)) || ((n_1.x_<=it_v->x_) && (it_v->x_<= n_2.x_)))) continue; double arr[4]; // Using properties of a point and a line here. // If the obtacle lies on one side of a line, substituting its edge points // (all obstacles are grid sqaures in this example) into the equation of // the line passing through the coordinated of the two nodes under // consideration will lead to all four resulting values having the same // sign. Hence if their sum of the value/abs(value) is 4 the obstacle is // not in the way. If a single point is touched ie the substitution leads // ot a value under 10^-7, it is set to 0. Hence the obstacle has // 1 point on side 1, 3 points on side 2, the sum is 2 (-1+3) // 2 point on side 1, 2 points on side 2, the sum is 0 (-2+2) // 0 point on side 1, 3 points on side 2, (1 point on the line, ie, // grazes the obstacle) the sum is 3 (0+3) // Hence the condition < 3 arr[0] = (double)it_v->x_+0.5 - slope*((double)it_v->y_+0.5) - c; arr[1] = (double)it_v->x_+0.5 - slope*((double)it_v->y_-0.5) - c; arr[2] = (double)it_v->x_-0.5 - slope*((double)it_v->y_+0.5) - c; arr[3] = (double)it_v->x_-0.5 - slope*((double)it_v->y_-0.5) - c; double count = 0; for (int i=0;i<4;i++){ if(fabs(arr[i]) <= 0.000001) arr[i] = 0; else count +=arr[i]/fabs(arr[i]); } if(abs(count) < 3) return true; } } return false; } Node RRT::GenerateRandomNode(int n){ std::random_device rd; // obtain a random number from hardware std::mt19937 eng(rd()); // seed the generator std::uniform_int_distribution<int> distr(0,n-1); // define the range int x = distr(eng); int y = distr(eng); Node new_node(x, y, 0, 0, n*x+y, 0); return new_node; } std::vector<Node> RRT::rrt(std::vector<std::vector<int> > &grid, Node start_in, Node goal_in, int max_iter_x_factor, double threshold_in){ start_ = start_in; goal_ = goal_in; n = grid.size(); threshold_ = threshold_in; int max_iter = max_iter_x_factor * n * n; CreateObstacleList(grid); point_list_.push_back(start_); Node new_node = start_; grid[start_.x_][start_.y_]=2; if (CheckGoalVisible(new_node)) return this->point_list_; int iter = 0; while(iter <= max_iter){ iter++; new_node = GenerateRandomNode(n); if (grid[new_node.x_][new_node.y_]!=0) continue; Node nearest_node = FindNearestPoint(new_node); if(nearest_node.id_ == -1) continue; grid[new_node.x_][new_node.y_]=2; point_list_.push_back(new_node); if (CheckGoalVisible(new_node)) return this->point_list_; } Node no_path_node(-1,-1,-1,-1,-1,-1); point_list_.clear(); point_list_.push_back(no_path_node); return point_list_; } bool RRT::CheckGoalVisible(Node new_node){ if(!CheckObstacle(new_node, goal_)){ double new_dist = (double)sqrt((double)(goal_.x_-new_node.x_)*(double)(goal_.x_-new_node.x_) + (double)(goal_.y_-new_node.y_)*(double)(goal_.y_-new_node.y_)); if(new_dist <= threshold_){ goal_.pid_ = new_node.id_; goal_.cost_ = new_dist + new_node.cost_; point_list_.push_back(goal_); return true; } } return false; } void RRT::CreateObstacleList(std::vector<std::vector<int> > &grid){ for(int i=0; i < n; i++){ for(int j=0;j < n; j++){ if(grid[i][j]==1){ Node obs(i,j,0,0,i*n+j,0); obstacle_list_.push_back(obs); } } } } #ifdef BUILD_INDIVIDUAL /** * @brief Script main function. Generates start and end nodes as well as grid, then creates the algorithm object and calls the main algorithm function. * @return 0 */ int main(){ int n = 11; std::vector<std::vector<int>> grid(n); std::vector<int> tmp(n); for (int i = 0; i < n; i++){ grid[i] = tmp; } MakeGrid(grid); std::random_device rd; // obtain a random number from hardware std::mt19937 eng(rd()); // seed the generator std::uniform_int_distribution<int> distr(0,n-1); // define the range Node start(distr(eng),distr(eng),0,0,0,0); Node goal(distr(eng),distr(eng),0,0,0,0); start.id_ = start.x_ * n + start.y_; start.pid_ = start.x_ * n + start.y_; goal.id_ = goal.x_ * n + goal.y_; start.h_cost_ = abs(start.x_ - goal.x_) + abs(start.y_ - goal.y_); //Make sure start and goal are not obstacles and their ids are correctly assigned. grid[start.x_][start.y_] = 0; grid[goal.x_][goal.y_] = 0; PrintGrid(grid); RRT new_rrt; double threshold = 2; int max_iter_x_factor = 20; std::vector<Node> path_vector = new_rrt.rrt(grid, start, goal, max_iter_x_factor, threshold); PrintPath(path_vector, start, goal, grid); return 0; } #endif
[ "28676655+vss2sn@users.noreply.github.com" ]
28676655+vss2sn@users.noreply.github.com
3f629692f17f58b8126604c22bd49b862f8f508d
767419ca9e6a899d84db512e165c07c5842b6b27
/aurobotservers/trunk/plugin/auavoid/uresavoid.h
f8b9bfde533a4556525aee852ee614a213fd708d
[]
no_license
savnik/LaserNavigation
3bf7a95519456a96b34488cd821d4da4bee3ceed
614fce06425c79e1d7e783aad4bbc97479798a7c
refs/heads/master
2021-01-16T20:55:33.441230
2014-06-26T21:55:19
2014-06-26T21:55:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,702
h
/*************************************************************************** * Copyright (C) 2006 by DTU (Christian Andersen) * * jca@elektro.dtu.dk * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef URESAVOID_H #define URESAVOID_H #include <cstdlib> #include <urob4/uresbase.h> #include <urob4/uresvarpool.h> #include <urob4/uresposehist.h> #include <urob4/uobstacle.h> #include "ureactivepath.h" /** This is the shared resource class. It must enherit from the resource base class (or one of its decendent) as shown. @author Christian Andersen */ class UResAvoid : public UResVarPool { // NAMING convention recommend that a resource class // starts with URes (as in UResAvoid) followed by // a descriptive extension for this specific resource public: /** Constructor */ UResAvoid() { // set name and version setResID(getResClassID(), 200); UResAvoidInit(); }; /** Destructor */ virtual ~UResAvoid(); /** * Initialize class */ void UResAvoidInit(); /** Fixed name of this resource type */ static const char * getResClassID() { return "avoid"; }; /** Fixed varsion number for this resource type. Should follow release version, i.e. version 1.28 gives number 128. Should be incremented only when there is change to this class definition, i.e new or changed functions or variables. */ /* static int getResVersion() { return 169; };*/ /** print status to a string buffer */ virtual const char * print(const char * preString, char * buff, int buffCnt); /** print status to a string buffer */ inline virtual const char * snprint(const char * preString, char * buff, int buffCnt) { return print(preString, buff, buffCnt); }; /** The server will offer a resource pointer by this call. If the resource is used, please return true. */ bool setResource(UResBase * resource, bool remove); /** Open logfile - the name is always avoid.log and is placed in the dataPath. The full name is available in 'logAvoidName'. */ bool openLogAvoid(); /** Is the logfile open */ inline bool isLogAvoidOpen() { if (paths->par.logAvoid != NULL) return paths->par.logAvoid->isOpen(); else return false; }; /** Close the logfile */ void closeLogAvoid(); /** Get the logfile name */ const char * getLogAvoidFileName() { return logAvoidName; }; // the above methods are udes be the server core and should be present // the print function is not strictly needed, but is nice. public: /** * Find path to this destination - and this desired (maximum) end velocity. * Return the time of calculation (pose time) in 'tod'. * NB! remember to call result->unlock() when no manoeuvre is longer needed. * \param directTestOnly to test direct path * \returns man sequence if path is available and usable */ UManSeq * findPathToHere(UPose exitPose, double endVel, bool exitPoseRel, UTime * tod, bool directTestOnly); /** Get pointer to path pool */ inline UAvoidPathPool * getPathPool() { return paths; }; /** * The varPool has methods, and a call to one of these are needed. * Do the call now and return (a double sized) result in 'value'. * Return true if the method call is allowed. * "getAvoidPath", "ddd": Find path to exit position. The found route is returned in the 'returnStruct' pointer array. The pointers in the array will be redirected to the static set of manoeuvre buffers in the avoid function, i.e. the result should be used before the next call to 'getAvoidPath'. */ virtual bool methodCall(const char * name, const char * paramOrder, char ** strings, const double * doubles, double * value, UDataBase ** returnStruct = NULL, int * returnStructCnt = NULL); /** * The varPool has methods, and a call to one of these are requested. The parameters * hold the requested method name, parameter list, parameters, and an array of pointers for the result. All parameters and results are of type UVariable. * \param name is the method name (within this variable pool) * \param paramOrder is the parameter sequence d=double structure or array * \param params is the array of UVariable pointers with the values * \param returnStruct is an array of pointers (to UDataBase structures, * either UVariable or another class based on UDataBase), may be NULL pointers * or pointers to actual result variables or classes - as specified in the method definition. * \param returnStructCnt is the actual number of returned structure pointers. * \return true if the method is handled (recognized) */ virtual bool methodCallV(const char * name, const char * paramOrder, UVariable * params[], UDataBase ** returnStruct, int * returnStructCnt); /** Is the obstacle avoidance a rev1 or rev 2 calculation */ bool useRev2(); /** Get current pose from pose-history */ inline UPose getCurrentPose() { UPose pose; if (poseHist != NULL) pose = poseHist->getNewest(NULL); return pose; } /** code front-left and front-right points as an xmlPose \param buff is the buffer to deliver result into. \param buffCnt is the size of the bugger in bytes. \returns a pointer to the buffer. */ const char * codeXmlRobotFront(char * buff, const int buffCnt); /** * Get last avoidance calculation time */ UTime getCalcTime() { return varCalcTime->getTime(); }; protected: // Locally used methods /** Create the smrif related variables */ void createBaseVar(); private: /** Copy footprint polygons to the polygon resource for debug purposes. \param resAP is the path definition with the footprint polygons. \param oldCnt is the prevoius number of polygons (that are to be deleted) */ void copyFootprintPolys(UAvoidPath2 * resAP, int oldCnt); /** Copy cell decomposition cells as polygons in the polygon plugin using the name cellPoly.XXX \param svcg is the cell decomposition structure */ void copyCellPolys(UAvoidCellGraph * avcg); /** Copy all grouped and added obstacles to polygon plugin, that is all obstacles in resAp.aogs with a point count > 2. */ void copyAvoidObstacles(UAvoidPath2 * resAP); protected: /** * Road lines to respect */ UReacRoadLines roadLines; /** * Obstacles to avoid */ UReacObstGrps obsts; /** Pool of alternative paths generated in responce to the obstacles and road lines */ UAvoidPathPool * paths; /** Pose history */ UResPoseHist * poseHist; /** Pose history */ UResPoseHist * mapPose; /** Global variables to access obstacles and road lines */ UResVarPool * globVar; /** Filename for obstacle avoidance logging */ char logAvoidName[MAX_FILENAME_LENGTH]; protected: /** Index to variable with manoeuvre count */ UVariable * varManCnt; /** Index to variable most problematic front left position */ UVariable * varFrontLeft; /** Index to variable most problematic front right position */ UVariable * varFrontRight; /** Index to boolean flag selecting wich obstacle avoidance method to use */ UVariable * varRev2; /** Index to boolean flag selecting wich cell decomposition method */ UVariable * varRev2cell; /** Index to boolean flag selecting wich obstacle avoidance method to use */ UVariable * varSerial; /// (old method - (desired) minimum distance to obstacle UVariable * varObstMinDist; /// (old method - absolute minimum distance to obstacle UVariable * varObstMinMinDist; /// maximum lateral acceleration UVariable * varMaxAcc; // maximum lateral acceleration /// maximum acceleration in turns UVariable * varMaxTurnAcc; /// minimum allowed turn radius UVariable * varMinTurnRadius; /// number of nested levels UVariable * varMaxNestedSpawns; /// maximum number of loops for midPose search UVariable * varMaxAvoidLoops; /// maximum spawn count limit UVariable * varMaxSpawnCount; /// minimum allowed clearence to obstacles (new method) UVariable * varClearenceMinimum; /// desired clearence to obstacles (new method) UVariable * varClearenceDesired; /// flag to set if obstacles (all) are to be ignored - path to bosition only) UVariable * varIgnoreObstacles; /// When set to true more debug info is returned to client and logged UVariable * varCrashTest; /// Use drivon manoeuver planning UVariable * varUseDriveon; /// drivon angle gain parameter UVariable * varDriveonGA; /// driveon distance gain parameter UVariable * varDriveonGD; /// allow forward solutions only - positive or negative (radians) UVariable * varForwardAngle; /// number of obstacle groups used for obstacle avoidance UVariable * varMaxOG; /// maximumber of tantents to search for the visibility graph UVariable * varMaxTangentDepth; /// Maximum number of tangent sequences testes, if first sequences fails in manoeuvre generation. UVariable * varMaxTangentToMan; /// debug maximum of allowed close obstacles that are to be ignored UVariable * varIgnoreCloseObst; /// accept mid-point solution after this number of calculations. UVariable * varAcceptSolution; /// should destination pose line be used in a line drive as soon as possible UVariable * varFollowLineOnLastPose; /// debug flag - use any solution UVariable * varUseAnyResult; /// debug flag - makeCellPolygon - 0 = no cells, 1= all cells 2=traversed cells UVariable * varMakeCellPolygon; /// debug limit of polygon size (for display only) UVariable * varMakeCellPolygonMaxY; /// debug flag - makeCellPolygon - boolean UVariable * varMakeFootprintPolygon; /// debug make also generated obstacles to polygons UVariable * varMakeAvoidObstPolygon; /// debug flag - make polyline from the cell path cost lines UVariable * varMakeCellCostLine; /// debug flag - make polyline from vertex-points from current to target position UVariable * varMakeCellVertexLine; /// debugDump flag, when true a full data dump (or as much as planned in code) is dumped to logfile. UVariable * varDebugDump; /// debugDump flag, when true a full data dump (or as much as planned in code) is dumped to logfile. UVariable * varCalcTime; private: /** a common string buffer for logging */ static const int MSL = 10000; char sBuff[MSL]; }; #endif
[ "ex25@localhost.(none)" ]
ex25@localhost.(none)
8cfd6480a925321fbf6f53c9ea78cfa6378d2beb
4f33e8501ce0ad3c3ff7bb831a43680dbf560a41
/hackerrank/project_euler/018.cpp
09a3c4598dce4b3a43248b4241b2e446161cf252
[]
no_license
vpatel95/online_programming
5d8ee1baac81a1c0f80743c22b949823b181705c
4d1bf26575e0715988828d84b9db39dc5cf31326
refs/heads/master
2022-11-21T03:34:26.391464
2020-07-15T01:39:41
2020-07-15T01:39:41
273,396,198
0
0
null
null
null
null
UTF-8
C++
false
false
734
cpp
// Project Euler #18 - https://www.hackerrank.com/contests/projecteuler/challenges/euler018/problem #include <bits/stdc++.h> using namespace std; int solve(int n) { int i, j; int a[n][n], dp[n][n]; for (i = 0; i < n; i++) { for (j = 0; j <= i; j++) { cin >> a[i][j]; } } for (i = n - 1; i >= 0; i--) { for (j = 0; j <= i; j++) { if (i == n - 1) { dp[i][j] = a[i][j]; } else { dp[i][j] = a[i][j] + max(dp[i+1][j], dp[i+1][j+1]); } } } return dp[0][0]; } int main() { int t; cin >> t; while (t--) { int i, j, n; cin >> n; cout << solve(n) << endl; } return 0; }
[ "vedmpatel@gmail.com" ]
vedmpatel@gmail.com
6e7b8ad9c19e45978fa4382c2ed082baee4ed1d3
4faa288f6d1fb100ee4e455c79bee74bf7daa5c2
/grow-unit-control/module-firmwares/firmware-ph-atlas-scientific-ezo/src/DeviceEzoPh.h
e9d2b9db09d15d71d0d8196cabfdf3d57a4f695c
[]
no_license
Nextfood/grow-system
a4e99bb0395128727e57c23158f14f9c256344c7
df8660342acd09cff99aebc05872bc03c9e18f98
refs/heads/master
2021-01-18T09:55:51.433085
2017-08-15T09:02:25
2017-08-15T09:02:25
100,359,306
1
0
null
null
null
null
UTF-8
C++
false
false
2,312
h
#ifndef _DeviceEzoPh_H_ #define _DeviceEzoPh_H_ #include <SPI.h> #include <math.h> #include "Arduino.h" #include <SoftwareSerial.h> #include "Device.h" #include "SetupEzoPh.h" #include "DataEzoPh.h" #include "InfoEzoPh.h" #include "ConfigureEzoPh.h" #define DEVICE_RCV_BUFFER_SIZE 41 class DeviceEzoPh : public Device<SetupEzoPh, DataEzoPh, InfoEzoPh, ConfigureEzoPh> { public: virtual void setup(SetupEzoPh& setup) { m_setup = setup; pinMode(setup.pin_rx, INPUT); pinMode(setup.pin_tx, OUTPUT); delay(1); _queryDeviceOk("C,0\r"); // Disable continous reading } virtual void initiateUpdateData() { } virtual bool isUpdatedDataReady() { return true; } virtual DataEzoPh& updateData(DataEzoPh& data) { String recv = _queryDevice("R\r"); data.ph = recv.toFloat(); return data; } virtual InfoEzoPh& updateInfo(InfoEzoPh& info) { return info; } virtual bool configure(ConfigureEzoPh& conf) { switch (conf.calPoint) { case ConfigureEzoPh::CAL_LOWPOINT: _queryDeviceOk(String("Cal,low,") + String(conf.calTarget, 2) + "\r"); break; case ConfigureEzoPh::CAL_MIDPOINT: _queryDeviceOk(String("Cal,mid,") + String(conf.calTarget, 2) + "\r"); break; case ConfigureEzoPh::CAL_HIGHPOINT: _queryDeviceOk(String("Cal,high,") + String(conf.calTarget, 2) + "\r"); break; default: return false; }; return true; } private: String _readDevice(SoftwareSerial& serDev) { char buf[DEVICE_RCV_BUFFER_SIZE]; buf[0] = '\0'; size_t bytes = serDev.readBytesUntil('\r', buf, DEVICE_RCV_BUFFER_SIZE); if (bytes > 0) buf[bytes - 1] = '\0'; return String(buf); } String _queryDevice(const String& msg) { SoftwareSerial serDev(m_setup.pin_rx, m_setup.pin_tx); serDev.begin(9600); serDev.setTimeout(1000); serDev.print(msg); return _readDevice(serDev); } bool _queryDeviceOk(const String& msg) { SoftwareSerial serDev(m_setup.pin_rx, m_setup.pin_tx); serDev.begin(9600); serDev.setTimeout(1000); serDev.print(msg); for (int i = 3; i; --i) { String recv = _readDevice(serDev); if (recv.startsWith("*OK")) return true; } return false; } SetupEzoPh m_setup; }; #endif
[ "hl@nextfood.co" ]
hl@nextfood.co
eccfd241e2f4023d707feb7f47a021b292a8d544
0e9394230899fd0df0c891a83131883f4451bcb9
/include/boost/simd/meta/as_logical.hpp
d1302c4f76b0992b664d236674300d0a51ee9dfd
[ "BSL-1.0" ]
permissive
WillowOfTheBorder/boost.simd
f75764485424490302291fbe9856d10eb55cdbf6
561316cc54bdc6353ca78f3b6d7e9120acd11144
refs/heads/master
2022-05-02T07:07:29.560118
2016-04-21T12:53:10
2016-04-21T12:53:10
59,155,554
1
0
null
null
null
null
UTF-8
C++
false
false
1,909
hpp
//================================================================================================== /*! @file Defines the as_logical meta-function @copyright 2012 - 2015 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_SDK_AS_LOGICAL_HPP_INCLUDED #define BOOST_SIMD_SDK_AS_LOGICAL_HPP_INCLUDED #include <boost/simd/config.hpp> #include <boost/simd/logical.hpp> #include <boost/simd/meta/real_of.hpp> #include <boost/simd/detail/brigand.hpp> #include <boost/dispatch/meta/factory_of.hpp> #include <boost/dispatch/meta/scalar_of.hpp> namespace boost { namespace simd { namespace details { template<typename T, typename F> struct as_logical { using type = brigand::apply<F, logical<T> >; }; template<typename T, typename F> struct as_logical< logical<T>, F > { using type = brigand::apply<F, logical<T> >; }; template<typename F> struct as_logical<bool, F> { using type = brigand::apply<F, bool >; }; } /*! @ingroup group-api @brief COnvert types to a logical type For a given type @c T , provides a type of same structure but able to fit a logical value. Provisions are taken so that conversion of logical and bool types is idempotent. @tparam T Type to convert **/ template<typename T> struct as_logical : details::as_logical < real_of_t<T> , dispatch::factory_of<T,dispatch::scalar_of_t<T>> > { }; /*! @ingroup group-api @brief Eager short-cut to as_logical meta-function **/ template<typename T> using as_logical_t = typename as_logical<T>::type; } } #endif
[ "charly.chevalier@numscale.com" ]
charly.chevalier@numscale.com
b60bb519cbe3240eeff7a49e3adae8c84843bbd6
432f7de15055ea14bb50e41f15cd7734a990259c
/sources/migrate-5.0.3a/haru/PdfExceptions.cc
b317e6796f8c673e97f1e04d5abf42aa527ef6bb
[ "MIT", "Zlib" ]
permissive
pbeerli/fractional-coalescent-material
f7d6a0b1b8db1a4a9c157a4566a9465103ca2a6a
d3487fb0869f6aa2e712cef980406229fd761885
refs/heads/master
2020-04-04T17:10:07.422471
2019-03-01T13:16:41
2019-03-01T13:16:41
156,109,793
2
1
null
null
null
null
UTF-8
C++
false
false
980
cc
/* * << H a r u --free pdf library >> -- PdfStreams.cpp * * Copyright (c) 1999-2003 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. * It is provided "as is" without express or implied warranty. * */ #include <stdarg.h> #include <stdio.h> #include "libharu.h" PdfException::PdfException(int code, const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef __WIN32__ _vsnprintf(fErrorBuf, 512, fmt, args); #else vsnprintf(fErrorBuf, 512, fmt, args); #endif va_end(args); fCode = code; } const char* #ifdef _NO_EXCEPT_LIST PdfException::what() const #else PdfException::what() const throw() #endif { return fErrorBuf; }
[ "beerli@me.com" ]
beerli@me.com
486e1e94af608ff217e07188d4a634855f179c04
808b3a49735d93a33802b86e122df29ffb61209e
/programmers/키패드 누르기.c++
f0f2eb9f4920fb7d1e5a2b91d882badcb0525ecc
[]
no_license
KingJoo/programmers
0deb1a9c5c615d0583f8142cd395d33186c3c255
e51b2dadebdc75d10b07ea567775784e2ffa3cb8
refs/heads/master
2023-08-12T03:40:43.243599
2021-09-28T11:20:25
2021-09-28T11:20:25
410,730,410
0
0
null
null
null
null
UTF-8
C++
false
false
785
#include <string> #include <vector> #include <cstdlib> using namespace std; typedef struct{int y,x;}P; P pad[]={{4,2},{1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3}},l={4,1},r={4,3}; string answer = ""; inline void select(int n,char c){ if(c=='l'){answer+="L";l=pad[n];} else{answer+="R";r=pad[n];} return; } string solution(vector<int> numbers, string hand) { int ll,rl; for(int n:numbers){ if(n==1||n==4||n==7) select(n,'l'); else if(n==3||n==6||n==9) select(n,'r'); else{ ll=pad[n].x-l.x+abs(pad[n].y-l.y); rl=r.x-pad[n].x+abs(r.y-pad[n].y); if(ll==rl) hand=="left"?select(n,'l'):select(n,'r'); else rl>ll?select(n,'l'):select(n,'r'); } } return answer; }
[ "jkangju@gmail.com" ]
jkangju@gmail.com
cb860eb5f9625e556efb7a539228c6d6b6f7e11b
fb6b653d2f1676b40ab75443edc2a3187cf00606
/Chapter15/exercises/15.12/ex_1512.cpp
9a911b9863afe2171bb6bb96c6dde6fe62243ab3
[]
no_license
wenjing219/Cpp-How-To-Program-9E
4cd923de658a90f3d3bfd0e4c0b3e8505d3a8472
8a6e2d1bc84e94fc598e258b9b151aa40895b21e
refs/heads/master
2021-01-22T22:16:24.824817
2017-03-14T22:14:40
2017-03-14T22:14:40
85,525,193
2
0
null
2017-03-20T02:04:41
2017-03-20T02:04:41
null
UTF-8
C++
false
false
984
cpp
/* * ===================================================================================== * * Filename: ex_1512.cpp * * Description: Exercise 15.12 - Converting Farenheit to Celsuis * * Version: 1.0 * Created: 13/10/16 17:58:23 * Revision: none * Compiler: g++ * * Author: Siidney Watson - siidney.watson.work@gmail.com * Organization: LolaDog Studio * * ===================================================================================== */ #include <iostream> #include <iomanip> int main(int argc, const char *argv[]){ std::cout << std::right << std::setw(12) << "Farenheit" << std::setw(12) << "Celsuis" << std::endl; for(int i=0; i<=212; ++i){ std::cout << std::right << std::setw(12) << i << std::right << std::setw(12) << std::setprecision(3) << std::showpos << std::fixed << ((5.0 / 9.0) * (i - 32)) << std::endl; } return 0; }
[ "siidney.watson.work@gmail.com" ]
siidney.watson.work@gmail.com
7e25b5815d30b58515dded844a6485061028fce6
7b4bac7cd798cfbf3a8c018c01a6ad60a1b34c25
/src/backend/networking/rpc_utils.h
5e9c71d580415d45e34c04a58eca97e6d6882060
[ "Apache-2.0" ]
permissive
larryxiao/peloton
0698b3394aa16cc7befd896220831a87e8ea3995
9a02fcacae6f5c5c9a7966cddf1c9e275c9b67c9
refs/heads/memcached
2020-04-10T13:28:32.674686
2016-05-11T23:09:02
2016-05-11T23:09:02
51,320,148
4
1
null
2016-05-11T16:47:37
2016-02-08T19:14:33
C++
UTF-8
C++
false
false
1,177
h
//===----------------------------------------------------------------------===// // // PelotonDB // // rpc_utils.h // // Identification: /peloton/src/backend/networking/rpc_utils.h // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include "abstract_service.pb.h" #include "postgres/include/c.h" #include "postgres/include/access/transam.h" #include "postgres/include/access/tupdesc.h" #include <memory> namespace peloton { namespace networking { //===----------------------------------------------------------------------===// // Message Creation Functions //===----------------------------------------------------------------------===// /* * CreateTupleDescMsg is used when a node sends query plan */ void SetTupleDescMsg(TupleDesc tuple_desc, TupleDescMsg& tuple_desc_msg); /* * When executing the query plan, a node must parse the received msg and convert it * to Postgres's TupleDesc */ std::unique_ptr<tupleDesc> ParseTupleDescMsg(const TupleDescMsg& tuple_desc_msg); } // namespace message } // namespace peloton
[ "tieyingz@cs.cmu.edu" ]
tieyingz@cs.cmu.edu
03880db7b5a4d4830fb63b69e670fae11f12f82f
899e293884d1ed1896414d46e3b46a1a9bfdc490
/ACM/Codes/Vjudge/20150718/E.cpp
2cf1630364318c883804ac3c0e080fc87063b103
[]
no_license
py100/University
d936dd071cca6c7db83551f15a952ffce2f4764c
45906ae95c22597b834aaf153730196541b45e06
refs/heads/master
2021-06-09T05:49:23.656824
2016-10-27T08:22:52
2016-10-27T08:22:52
53,556,979
1
1
null
null
null
null
UTF-8
C++
false
false
729
cpp
#include<bits/stdc++.h> using namespace std; int a[100020][32]; int topbit[32] = {0}; int len[100020]; int tobit(int n, int x){ int i = 0; while(x > 0){ a[n][i++] = x % 2; x /= 2; } return i; } int main(){ int n; scanf("%d", &n); minlen = 32; for(int i = 0; i < n; i++){ scanf("%d", &a[i]); len[i] = tobit(i, a); minlen = min(minlen, len[i]); for(int j = len[i] - 1, k = 31; j >= 0; j--, k--){ topbit[k] += a[i][j]; } } int top = 31; int head = 0; while((topbit[top] == n || topbit[top] == 0) && head <= len) {top--;head++;} return 0; }
[ "py100@live.cn" ]
py100@live.cn
c3c689a9a3611d87cc32e357307702709434efa5
6dfdb80e485bf74bf4f62080e801c80cbc3e9a99
/boostTest/boostIntger/static_log2_test.cpp
5b0a745d22cde7b1b127a5fba6ef4b7094e5c147
[]
no_license
hjw21century/boostTest
ecba566a55c01f55fd0cb81f89694b900bbe02f1
e92c18235c409dc97d7e6aea33ab2b33de518463
refs/heads/master
2020-12-03T03:46:22.916531
2017-06-29T16:33:26
2017-06-29T16:33:26
95,772,982
0
0
null
null
null
null
UTF-8
C++
false
false
3,662
cpp
// Boost static_log2.hpp test program --------------------------------------// // (C) Copyright Daryle Walker 2001. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version including documentation. // Revision History // 01 Oct 2001 Initial version (Daryle Walker) #include <boost/detail/lightweight_test.hpp> // for main #include <boost/cstdlib.hpp> // for boost::exit_success #include <boost/integer/static_log2.hpp> // for boost::static_log2 #include <iostream> // for std::cout (std::endl indirectly) // Macros to compact code #define PRIVATE_LB_TEST( v, e ) BOOST_TEST( ::boost::static_log2<v>::value == e ) #define PRIVATE_PRINT_LB( v ) ::std::cout << "boost::static_log2<" << (v) \ << "> = " << ::boost::static_log2< (v) >::value << '.' << ::std::endl // Control to check for a compile-time error #ifndef CONTROL_LB_0_TEST #define PRIVATE_LB_0_TEST #else #define PRIVATE_LB_0_TEST PRIVATE_PRINT_LB( 0 ) #endif // Main testing function int static_log2_test ( int , // "argc" is unused char * [] // "argv" is unused ) { std::cout << "Doing tests on static_log2." << std::endl; PRIVATE_LB_0_TEST; PRIVATE_LB_TEST( 1, 0 ); PRIVATE_LB_TEST( 2, 1 ); PRIVATE_LB_TEST( 3, 1 ); PRIVATE_LB_TEST( 4, 2 ); PRIVATE_LB_TEST( 5, 2 ); PRIVATE_LB_TEST( 6, 2 ); PRIVATE_LB_TEST( 7, 2 ); PRIVATE_LB_TEST( 8, 3 ); PRIVATE_LB_TEST( 9, 3 ); PRIVATE_LB_TEST( 10, 3 ); PRIVATE_LB_TEST( 11, 3 ); PRIVATE_LB_TEST( 12, 3 ); PRIVATE_LB_TEST( 13, 3 ); PRIVATE_LB_TEST( 14, 3 ); PRIVATE_LB_TEST( 15, 3 ); PRIVATE_LB_TEST( 16, 4 ); PRIVATE_LB_TEST( 17, 4 ); PRIVATE_LB_TEST( 18, 4 ); PRIVATE_LB_TEST( 19, 4 ); PRIVATE_LB_TEST( 20, 4 ); PRIVATE_LB_TEST( 21, 4 ); PRIVATE_LB_TEST( 22, 4 ); PRIVATE_LB_TEST( 23, 4 ); PRIVATE_LB_TEST( 24, 4 ); PRIVATE_LB_TEST( 25, 4 ); PRIVATE_LB_TEST( 26, 4 ); PRIVATE_LB_TEST( 27, 4 ); PRIVATE_LB_TEST( 28, 4 ); PRIVATE_LB_TEST( 29, 4 ); PRIVATE_LB_TEST( 30, 4 ); PRIVATE_LB_TEST( 31, 4 ); PRIVATE_LB_TEST( 32, 5 ); PRIVATE_LB_TEST( 33, 5 ); PRIVATE_LB_TEST( 34, 5 ); PRIVATE_LB_TEST( 35, 5 ); PRIVATE_LB_TEST( 36, 5 ); PRIVATE_LB_TEST( 37, 5 ); PRIVATE_LB_TEST( 38, 5 ); PRIVATE_LB_TEST( 39, 5 ); PRIVATE_LB_TEST( 40, 5 ); PRIVATE_LB_TEST( 63, 5 ); PRIVATE_LB_TEST( 64, 6 ); PRIVATE_LB_TEST( 65, 6 ); PRIVATE_LB_TEST( 127, 6 ); PRIVATE_LB_TEST( 128, 7 ); PRIVATE_LB_TEST( 129, 7 ); PRIVATE_LB_TEST( 255, 7 ); PRIVATE_LB_TEST( 256, 8 ); PRIVATE_LB_TEST( 257, 8 ); PRIVATE_LB_TEST( 511, 8 ); PRIVATE_LB_TEST( 512, 9 ); PRIVATE_LB_TEST( 513, 9 ); PRIVATE_LB_TEST( 1023, 9 ); PRIVATE_LB_TEST( 1024, 10 ); PRIVATE_LB_TEST( 1025, 10 ); PRIVATE_LB_TEST( 2047, 10 ); PRIVATE_LB_TEST( 2048, 11 ); PRIVATE_LB_TEST( 2049, 11 ); PRIVATE_LB_TEST( 4095, 11 ); PRIVATE_LB_TEST( 4096, 12 ); PRIVATE_LB_TEST( 4097, 12 ); PRIVATE_LB_TEST( 8191, 12 ); PRIVATE_LB_TEST( 8192, 13 ); PRIVATE_LB_TEST( 8193, 13 ); PRIVATE_LB_TEST( 16383, 13 ); PRIVATE_LB_TEST( 16384, 14 ); PRIVATE_LB_TEST( 16385, 14 ); PRIVATE_LB_TEST( 32767, 14 ); PRIVATE_LB_TEST( 32768, 15 ); PRIVATE_LB_TEST( 32769, 15 ); PRIVATE_LB_TEST( 65535, 15 ); PRIVATE_LB_TEST( 65536, 16 ); PRIVATE_LB_TEST( 65537, 16 ); return boost::report_errors(); }
[ "hjw21century@163.com" ]
hjw21century@163.com
fbb941af33ad70c3006c00390f4ec0dab0605314
9d2bafb07baf657c447d09a6bc5a6e551ba1806d
/ros2_ws/install/include/cartographer_ros_msgs/srv/start_trajectory__response__struct.hpp
d010c60d5e003557c09bb7258422b799759dfd7c
[]
no_license
weidafan/ros2_dds
f65c4352899a72e1ade662b4106e822d80a99403
c0d9e6ff97cb7cc822fe25a62c0b1d56f7d12c59
refs/heads/master
2021-09-05T20:47:49.088161
2018-01-30T21:03:59
2018-01-30T21:03:59
119,592,597
1
0
null
null
null
null
UTF-8
C++
false
false
4,125
hpp
// generated from rosidl_generator_cpp/resource/msg__struct.hpp.em // generated code does not contain a copyright notice #ifndef CARTOGRAPHER_ROS_MSGS__SRV__START_TRAJECTORY__RESPONSE__STRUCT_HPP_ #define CARTOGRAPHER_ROS_MSGS__SRV__START_TRAJECTORY__RESPONSE__STRUCT_HPP_ // Protect against ERROR being predefined on Windows, in case somebody defines a // constant by that name. #if defined(_WIN32) && defined(ERROR) #undef ERROR #endif #include <rosidl_generator_cpp/bounded_vector.hpp> #include <array> #include <memory> #include <string> #include <vector> // include message dependencies #ifndef _WIN32 # define DEPRECATED_cartographer_ros_msgs_srv_StartTrajectory_Response __attribute__((deprecated)) #else # define DEPRECATED_cartographer_ros_msgs_srv_StartTrajectory_Response __declspec(deprecated) #endif namespace cartographer_ros_msgs { namespace srv { // message struct template<class ContainerAllocator> struct StartTrajectory_Response_ { using Type = StartTrajectory_Response_<ContainerAllocator>; StartTrajectory_Response_() { } explicit StartTrajectory_Response_(const ContainerAllocator & _alloc) // *INDENT-OFF* (prevent uncrustify from making unnecessary indents here) // *INDENT-ON* { (void)_alloc; } // field types and members using _trajectory_id_type = int32_t; _trajectory_id_type trajectory_id; // setters for named parameter idiom Type * set__trajectory_id( const int32_t & _arg) { this->trajectory_id = _arg; return this; } // constants // pointer types using RawPtr = cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> *; using ConstRawPtr = const cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED_cartographer_ros_msgs_srv_StartTrajectory_Response std::shared_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator>> Ptr; typedef DEPRECATED_cartographer_ros_msgs_srv_StartTrajectory_Response std::shared_ptr<cartographer_ros_msgs::srv::StartTrajectory_Response_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const StartTrajectory_Response_ & other) const { if (this->trajectory_id != other.trajectory_id) { return false; } return true; } bool operator!=(const StartTrajectory_Response_ & other) const { return !this->operator==(other); } }; // struct StartTrajectory_Response_ // alias to use template instance with default allocator using StartTrajectory_Response = cartographer_ros_msgs::srv::StartTrajectory_Response_<std::allocator<void>>; // constants requiring out of line definition } // namespace srv } // namespace cartographer_ros_msgs #endif // CARTOGRAPHER_ROS_MSGS__SRV__START_TRAJECTORY__RESPONSE__STRUCT_HPP_
[ "austin.tisdale.15@cnu.edu" ]
austin.tisdale.15@cnu.edu
fb1172835c0132945486adf5119d8c4b8c3c4791
c76480c7d7b2410839c8d71242d698750f929428
/datastructures/hackerrank/linked_list/reverse_doubly_list.cc
daa492d10061eabd86be7a387f57562de2aa5de9
[ "MIT" ]
permissive
AravindVasudev/datastructures-and-algorithms
c234ec83768a18a4b184012a0b670e059f64842f
42a3089c044846d7b0adf311ec816bd736f2eb06
refs/heads/master
2023-04-15T15:22:49.544556
2023-04-03T07:48:08
2023-04-03T07:48:08
85,127,389
1
0
null
null
null
null
UTF-8
C++
false
false
492
cc
/* Reverse a doubly linked list, input list may also be empty Node is defined as struct Node { int data; Node *next; Node *prev; } */ Node* Reverse(Node* head) { // Complete this function // Do not write the main method. Node *cur, *next, *prev; if (head == NULL) return NULL; cur = head; prev = NULL; while (cur != NULL) { next = cur->next; cur->next = prev; cur->prev = next; prev = cur; cur = next; } return prev; }
[ "aravindv96@yahoo.com" ]
aravindv96@yahoo.com
610519855644de60a7bdaddd670913619cf44eec
ca5f51c4fecdb3cca7ffc0544c17de0c412086f8
/Strings/compress-a-string(run length encoding).cpp
6e81e34984d0e0dc91359a5d99ada666854e89c3
[]
no_license
avinashw50w/ds_algo
f517bbb326a922258e6ef7816e6c06593a2d06aa
bc73bd617486ab8fcbbdd8a076cacd3761c6c954
refs/heads/master
2023-07-22T17:44:44.815336
2023-07-13T07:38:22
2023-07-13T07:38:22
193,303,550
0
3
null
null
null
null
UTF-8
C++
false
false
608
cpp
/*compress a string such that if the consecutive characters are equal then, replace then with a single character followed by the no of times it appeared. eg. aabbbcdddd => a2b3c1d4 */ string runLengthEncode(string s) { int n = s.size(); int k = 0; for (int i = 0; i < n; ++i) { int len = 1; while (i + len < n and s[i] == s[i + len]) len++; string len_str = to_string(len); s[k++] = s[i]; for (char c : len_str) s[k++] = c; } return s.substr(0, k); } int main() { char c[] = "aaabbcccc"; cout << encode(c); }
[ "avinash.kumar@seenit.in" ]
avinash.kumar@seenit.in
cca9de70ad7bb15105cee705cf29b2f70063d51d
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/Sexy_Jeans_Shorts_04_classes.h
eedc6afbd770c3174a1573a10458ddfce7fdcb3c
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
653
h
#pragma once // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Sexy_Jeans_Shorts_04.Sexy_Jeans_Shorts_04_C // 0x0000 (0x0928 - 0x0928) class ASexy_Jeans_Shorts_04_C : public AClothesItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Sexy_Jeans_Shorts_04.Sexy_Jeans_Shorts_04_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
52077ea87162eebf02ede68b300a1560585f38a3
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/21/266.c
369926bcfad91673d63e3d6c1f712c566ccf9d55
[]
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
650
c
void main() { int n,a[300],b[300],i,p,k,j=1,q; double s=0,m=0,t; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); s=s+a[i]; } s=s/n; for(i=0;i<n;i++) { t=fabs(a[i]-s); if(t>m) { m=t; k=i; p=1; } else if(fabs(t-m)<=1e-6) p++; } b[0]=a[k]; if(p==1) printf("%d",a[k]); else { for(i=k+1;i<n;i++) if(fabs(fabs(a[i]-s)-m)<=1e-6) { b[j]=a[i]; j++; } for(j=0;j<p;j++) { q=j; for(i=j+1;i<p;i++) if(b[q]>b[j]) q=i; b[j]=b[q]; } for(j=0;j<p;j++) { printf("%d",b[j]); if(j<p-1) printf(","); } } }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
a29b3d7065f649692bfec8fccc53c562ff8c1329
c747cfbe51cc24d15e49a888072d34635833d90a
/273_IntegerToEnglishWords.cpp
23af270f421cbd466f9f3323beabf3ed235a7ad9
[]
no_license
bigship/leetcode_solutions
18921508a8acba25013ae65864168c4c084bef37
45edfab5f1696fa9b3b59b63663aa9524de209cd
refs/heads/master
2022-08-22T05:42:37.462263
2022-08-02T20:14:50
2022-08-02T20:14:50
13,472,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
// 273. Integer to English Words /* * Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Example 4: Input: num = 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" Constraints: 0 <= num <= 2^31 - 1 */ class Solution { public: vector<string> in_twenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; vector<string> in_hundred = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; vector<string> over_thousand = {"","Thousand", "Million", "Billion"}; string numberToWords(int num) { if (num == 0) return "Zero"; int i = 0; string ans; while (num) { string pre = helper(num % 1000); if (pre != "") ans = pre + " " + over_thousand[i] + " " + ans; num /= 1000; ++i; } return trim(ans); } string helper(int num) { if (num < 20) return trim(in_twenty[num]); if (num < 100) return trim(in_hundred[num / 10] + " " + in_twenty[num % 10]); return trim(in_twenty[num / 100] + " " + "Hundred " + helper(num % 100)); } string trim(string s) { if (s == "") return s; int first = s.find_first_not_of(' '); int last = s.find_last_not_of(' '); return s.substr(first, (last-first+1)); } };
[ "colinchen1984@gmail.com" ]
colinchen1984@gmail.com
d580a43ba00f1f832301b62b6e2bfb951b19c2fc
7013a3d3cfd4883a0cdcbd1667a675d03e0475f7
/src/celula_t.cpp
82f14e115c220f1a424e88d29c469ca1f6edcc51
[]
no_license
DarwinGonzalez/juego_de_la_vida
daf1d9fdac2650172760eb18e6043d8c626b2ecb
ab69bd740efbbba9dd3e977c4ef682f0fdecc197
refs/heads/master
2020-03-11T02:46:13.628819
2018-04-16T11:01:40
2018-04-16T11:01:40
129,728,213
0
0
null
null
null
null
UTF-8
C++
false
false
938
cpp
//Algoritmos y Estructuras de Datos Avanzados //Práctica: Juego de la Vida C++ //AUTOR: Darwin González Suárez //Archivo donde se implementan los metodos necesarios para el funcionamiento de la clase celula #include "celula_t.hpp" cel_t::cel_t(){ state_ = false; num_vecinos_ = 0; symbol_ = ' '; } cel_t::~cel_t(){ state_ = false; num_vecinos_ = 0; symbol_ = ' '; } int cel_t::get_num_vecinos(){ return num_vecinos_; } void cel_t::set_num_vecinos(int x){ num_vecinos_ = x; } void cel_t::set_state(bool x){ state_ = x; } bool cel_t::get_state(){ return state_; } void cel_t::cambiar(){ if(state_){ set_state(false); set_symbol(' '); }else{ set_state(true); set_symbol('X'); } } char cel_t::get_symbol(){ return symbol_; } void cel_t::set_symbol(char symbol){ symbol_ = symbol; } void cel_t::reiniciar(){ num_vecinos_ = 0; }
[ "alu0100812794@ull.edu.es" ]
alu0100812794@ull.edu.es
b4904bf313ff4b140f205770ab356d4b0cacce32
504ee37878baab25cf338f9588ec1e4b463e13f1
/interphone.ino
1040177f67a46deefcf29226abe6c4a4c267e3ba
[]
no_license
valentintintin/esp8266-interphone-connected
dbb95d509a8895e2d4883066af238f144c06925c
ba226e391c0b91fefc80e3f88e1780f29d2ee860
refs/heads/master
2020-03-11T18:29:50.839536
2019-07-16T15:23:53
2019-07-16T15:23:53
130,178,477
1
0
null
null
null
null
UTF-8
C++
false
false
7,323
ino
#include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #include <ESPAsyncWebServer.h> #include "Timer.h" #define DIRECT_CO //#define VOICE //#define MP3 #ifndef DIRECT_CO #include <WiFiManager.h> // Conflict with WebServer #endif #if defined(VOICE) || defined(MP3) #include <AudioOutputI2SNoDAC.h> AudioOutputI2SNoDAC *out; #endif #ifdef VOICE #include <ESP8266SAM.h> ESP8266SAM *sam = new ESP8266SAM; #endif #ifdef MP3 #include "message.h" #include <AudioFileSourcePROGMEM.h> #include <AudioGeneratorMP3.h> AudioGeneratorWAV *wav; AudioFileSourcePROGMEM *file; #endif #define DEBUG #define TIME_ON 5000 #define RELAY 2 const char pageHTML[] PROGMEM = {"<!DOCTYPE html><title>Interphone - CURIOUS</title><meta content=\"width=device-width,initial-scale=1\"name=viewport><script crossorigin=anonymous integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\"src=https://code.jquery.com/jquery-3.3.1.min.js></script><script>$(function() { const ESP = \"/\"; const interphoneElement = $(\"#interphone\"); interphoneElement.click(function() { $.post(ESP + \"open\", function(state) { refreshHtml(state); }, \"json\").fail(function() { error(); }); }); function getStatus() { $.post(ESP + \"\", function(state) { refreshHtml(state); }, \"json\").fail(function() { error(); }); } function refreshHtml(state) { if (state) { interphoneElement.removeClass(\"off\"); interphoneElement.addClass(\"on\"); interphoneElement.html(\"Ouvert !\"); interphoneElement.attr(\"disabled\", true); } else { interphoneElement.removeClass(\"on\"); interphoneElement.addClass(\"off\"); interphoneElement.text(\"Ouvrir\"); interphoneElement.removeAttr(\"disabled\"); } } function error() { interphoneElement.removeClass(\"on\"); interphoneElement.removeClass(\"off\"); interphoneElement.html(\"Erreur !\"); interphoneElement.attr(\"disabled\", true); } getStatus(); setInterval(function() { getStatus() }, 2000); });</script><style>body{text-align:center;margin:auto}.on{background:green!important}.off{background:red!important}#interphone{margin:auto;display:flex;align-items:center;justify-content:center;width:150px;height:150px;border-radius:35%;color:#fff;font-weight:700;font-size:20px;background:gray;border:0}#interphone:hover:enabled{font-size:25px;cursor:pointer}#infos{margin-top:200px}#infos a{display:block}</style><h1>Interphone - CURIOUS</h1><button autofocus id=interphone type=button></button><details id=infos><summary>Autres commandes</summary><a href=/open>Ouvrir (GET et POST)</a> <a href=/infos>Memoire + Uptime en JSON (GET)</a> <a href=/reset>Reset l'ESP (POST)</a>"}; const char trueStr[] PROGMEM = {"true"}; const char falseStr[] PROGMEM = {"false"}; char page[2048] = ""; char mimeHtml[] = "text/html"; char mimeJson[] = "application/json"; bool isDoorOpen = false; bool mustOpenDoor = false; #ifndef RELAY char serialRelayOn[4] = {0xA0, 0x01, 0x01, 0xA2}; char serialRelayOff[4] = {0xA0, 0x01, 0x00, 0xA1}; #endif AsyncWebServer server(80); Timer timer(TIME_ON); void setup() { #ifdef RELAY Serial.begin(115200); #else Serial.begin(9600); #endif Serial.println(F("\nStart, connection to curious")); #if defined(VOICE) || defined(MP3) out = new AudioOutputI2SNoDAC(); out->begin(); #endif #ifdef MP3 file = new AudioFileSourcePROGMEM(message, sizeof(message)); out = new AudioOutputI2SNoDAC(); wav = new AudioGeneratorWAV(); wav->begin(file, out); #endif #ifdef RELAY pinMode(RELAY, OUTPUT); closeRelay(); #endif #ifndef DIRECT_CO WiFiManager wifiManager; if(!wifiManager.autoConnect("CURIOUS-INTERPHONE")) { Serial.println("No connection, reset !"); ESP.restart(); } #else WiFi.mode(WIFI_STA); WiFi.begin("curieux_wifi", "curious7ruesaintjoseph"); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(F("No connection curious, try Valentin !")); WiFi.begin ( "Valentin", "0613979414" ); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(F("No connection, reset !")); ESP.restart(); } } #endif Serial.println (WiFi.localIP()); server.onNotFound(handleRequest); server.on("/open", HTTP_ANY, handleRequestOpen); server.on("/infos", HTTP_GET, handleRequestInfos); server.on("/reset", HTTP_POST, handleRequestReset); //server.on("/update", HTTP_POST, handleRequestReset, handleRequestUploadProgram); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); server.begin(); timer.setExpired(); Serial.println(F("OK")); } void loop() { if (ESP.getFreeHeap() < 1000) { Serial.println(F("No more memory, reset !")); ESP.restart(); } checkDoor(); } void handleRequest(AsyncWebServerRequest *request) { if (request->method() == HTTP_POST) { request->send_P(200, mimeJson, mustOpenDoor || isDoorOpen ? trueStr : falseStr); } else { request->send_P(200, mimeHtml, pageHTML); } } void handleRequestOpen(AsyncWebServerRequest *request) { mustOpenDoor = true; handleRequest(request); } void handleRequestInfos(AsyncWebServerRequest *request) { sprintf_P(page, PSTR("{\"mem\":%d,\"uptime\":%lu}"), ESP.getFreeHeap(), millis() / 1000); request->send(200, mimeJson, page); } void checkDoor() { if (mustOpenDoor && !isDoorOpen) { Serial.println(F("Open")); isDoorOpen = true; mustOpenDoor = false; #ifdef VOICE sam->SetPhonetic(false); sam->Say(out, "bonjour"); delay(500); sam->Say(out, "porte de gauche"); delay(500); sam->Say(out, "troixième étage"); /*sam->SetPhonetic(true); //ɡʁup kyʁju tʁwaksjɛm etaʒ sam->Say(out, "GRUH4PEH KUXRIH3UHS");*/ #endif #ifdef MP3 if (wav->isRunning()) { if (!wav->loop()) wav->stop(); } #endif timer.restart(); openRelay(); } if (mustCloseDoor() && isDoorOpen) { Serial.println(F("Close")); isDoorOpen = false; closeRelay(); } } void openRelay() { #ifdef RELAY digitalWrite(RELAY, HIGH); #else for(byte i = 0; i < 4; i++) { Serial.write(serialRelayOn[i]); } #endif } void closeRelay() { #ifdef RELAY digitalWrite(RELAY, LOW); #else for(byte i = 0; i < 4; i++) { Serial.write(serialRelayOff[i]); } #endif } bool mustCloseDoor() { return timer.hasExpired(); } /* void handleRequestUploadProgram(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { if (!index){ Serial.println(F("UploadStart")); Serial.setDebugOutput(true); uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if(!Update.begin(maxSketchSpace)){ //start with max available size Update.printError(Serial); } } if(Update.write(data, len) != len){ Update.printError(Serial); } if (final){ Serial.println(F("UploadEnd")); if(Update.end(true)){ // true to set the size to the current progress Serial.println(F("Update Success")); } else { Update.printError(Serial); } Serial.setDebugOutput(false); } } */ void handleRequestReset(AsyncWebServerRequest *request) { Serial.println(F("Reset")); request->send_P(200, mimeJson, Update.hasError() ? falseStr : trueStr); delay(1000); ESP.restart(); }
[ "valentin.s.10@gmail.com" ]
valentin.s.10@gmail.com
7f5c7fbd15ea8584f0aece0b4737951363dd34dc
c36206501cd121bd80e83890afa895c47512cff6
/p5/comand.cpp
ae91d11a8d9472d9aabe184569bcfec091572566
[]
no_license
ninatu/multithread
35db9c2047e12f5754d309994234ddfd6a34cba3
dedf8dd6648bcd1372db59c9e94ba10773c2e597
refs/heads/master
2021-01-19T04:06:57.545118
2016-06-15T14:23:10
2016-06-15T14:23:10
52,672,422
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include "comand.h" Comand::Comand( const std::vector<std::string> &parts, const std::string &_infile, const std::string &_outfile) { infile = _infile; outfile = _outfile; cmd = (char*) calloc(parts[0].size() + 1, sizeof(*cmd)); params = (char **) calloc(parts.size() + 1, sizeof(*params)); memcpy(cmd, parts[0].c_str(), parts[0].size()+1); for(size_t i = 0; i < parts.size(); i++) { params[i] = (char*) calloc(parts[i].size() + 1, sizeof(**params)); memcpy(params[i], parts[i].c_str(), parts[i].size()+1); } params[parts.size()] = NULL; count_params = parts.size(); } Comand::~Comand() { free(cmd); for(size_t i = 0; i < count_params; i++) free(params[i]); free(params); } const std::string & Comand::who_is() { return name_class; } const std::string & Delimeter::who_is() { return name_class; }
[ "p.pin.p@yandex.ru" ]
p.pin.p@yandex.ru
124cbdb9f93569a1375cbe83cf647c05e3e12e9a
f2ed8aa89c705fab1ea8b8328c5ce92497ee276a
/task4/pollard_lambda.cpp
5150c5435d19358f7e75fbccb0f7a526eba712b3
[]
no_license
radekwlsk/pwr-high-performace-computing
b2b8b9986b038ff46a2f9b0e5042023c256d3b59
fb90802ce055ede55e3c90f4ae2eff898d6fec7b
refs/heads/master
2021-04-03T04:56:08.495614
2018-06-05T14:38:38
2018-06-05T14:38:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,534
cpp
#include <iostream> #include <omp.h> #include <NTL/ZZ.h> #include <NTL/ZZ_p.h> #include <NTL/vector.h> #include <assert.h> #include <functional> #include <string> #include <sstream> #include <tuple> #include <unordered_map> #include <map> #define DIST_BITS 8 #define WILD_KANGAROO false #define TAME_KANGAROO true #define WILD_THREADS 2 #define TAME_THREADS 3 #define NUM_THREADS 5 using namespace std; using namespace NTL; string ZZToString(const ZZ &z) { stringstream buffer; buffer << z; return buffer.str(); } unsigned long MaxJumps(ZZ beta) { unsigned long r = 1; ZZ res; res = r; do { /* res = (2^r - 1) / r */ power(res, ZZ(2), r); res -= 1; res /= r; ++r; } while (res < beta); return r - 2; } ZZ pollard_lambda(ZZ alpha, ZZ beta, ZZ P, ZZ a, ZZ b) { int tid; Vec<ZZ> dists; Vec<ZZ> jumps; unsigned long r; int index; string str; ZZ Q = (P - ZZ(1)) / ZZ(2); ZZ res, beta_min; bool quit = false; map<ZZ, tuple<ZZ, bool, int>> distinguished_values; // beta_min = NUM_THREADS * sqrt(b - a) / 4 beta_min = MulMod(ZZ(NUM_THREADS), SqrRoot(b - a), P) / ZZ(4); // r - max jumps r = MaxJumps(beta_min); // cout << "max jumps: " << r << endl; dists.SetLength(r); jumps.SetLength(r); for (int i = 0; i < r; ++i) { dists[i] = MulMod(PowerMod(ZZ(2), ZZ(i), Q), ZZ(WILD_THREADS * TAME_THREADS), Q); jumps[i] = PowerMod(alpha, dists[i], P); } bool kangaroo_type; ZZ dist, pos, x, step; #pragma omp parallel \ num_threads(NUM_THREADS) \ shared(res, quit, distinguished_values) \ private(tid, dist, pos, kangaroo_type, x, step, index, str) \ firstprivate(a, b, alpha, beta, P, Q, jumps, dists, r) { tid = omp_get_thread_num(); #pragma omp critical { dist = 0; if (tid < TAME_THREADS) { kangaroo_type = TAME_KANGAROO; ZZ i; i = tid; // dist = i*vi // dist = MulMod(i, vi, Q); // pos = g^((a + b) / 2 + iv) pos = PowerMod(alpha, ((a + b) / ZZ(2)) + i*ZZ(WILD_THREADS), P); } else { kangaroo_type = WILD_KANGAROO; ZZ j; j = tid - TAME_THREADS; // dist = j*vi // dist = MulMod(j, vi, Q); // pos = h * g^ju pos = PowerMod(alpha, MulMod(j, ZZ(TAME_THREADS), P), P); pos = MulMod(beta, pos, P); } // cout << "start pos:" << tid << ": " << pos << endl; } #pragma omp barrier do { str = ZZToString(pos); index = (int)(hash<string>{}(str) % r); pos = MulMod(pos, jumps[index], P); dist += dists[index]; if ((pos & ZZ((1 << DIST_BITS) - 1)) == 0) { #pragma omp critical if (!quit) { // cout << "distinguished:" << tid << ": " << pos << endl; pair<map<ZZ, tuple<ZZ, bool, int>>::iterator, bool> ret = distinguished_values.insert( pair<ZZ, tuple<ZZ, bool, int>>(pos, make_tuple(dist, kangaroo_type, tid))); if (!ret.second) { quit = true; // cout << "collision:" << get<2>(ret.first->second) << ": " << ret.first->first << endl; // x = (a + b) / 2 + iv - ju + dist_TAME - dist_WILD x = ZZ(a + b) / ZZ(2); ZZ i, j, dist_tame, dist_wild; if (kangaroo_type == TAME_KANGAROO) { i = tid; j = get<2>(ret.first->second) - TAME_THREADS; dist_tame = dist % Q; dist_wild = get<0>(ret.first->second) % Q; } else { i = get<2>(ret.first->second); j = tid - TAME_THREADS; dist_tame = get<0>(ret.first->second) % Q; dist_wild = dist % Q; } AddMod(x, x, dist_tame, Q); SubMod(x, x, dist_wild, Q); AddMod(x, x, i * WILD_THREADS, Q); SubMod(x, x, j * TAME_THREADS, Q); res = x; } } } } while (!quit); } return res; } int main(int argc, char **argv) { ZZ Q, P; ZZ alpha; ZZ beta; ZZ a, b; // 40 bits P = 971579802563; // P alpha = 310118604200; // generator g beta = 93968352314; // // // 45 bits // P = 30034629688907; // P // alpha = 15963176245506; // generator g // beta = 13006361946477; // y = alpha^{x} = beta (mod P) // // 50 bits // P = 1869034281506423; // P // alpha = 834224574754024; // generator g // beta = 889899983492440; // y = alpha^{x} = beta (mod P) if (argc == 4) { P = ZZ(atoi(argv[1])); alpha = ZZ(atoi(argv[2])); beta = ZZ(atoi(argv[3])); } else if (argc == 2) { cout << "Using random " << argv[1] << " bits P and random values.\n"; Q = GenGermainPrime_ZZ(atoi(argv[1])-1); P = (ZZ(2) * Q) + ZZ(1); do { alpha = RandomBnd(P - ZZ(1)) + ZZ(1); PowerMod(alpha, alpha, ZZ(2), P); } while (alpha == 1); // range [0, (pi / 8) * ord g] // ord g = Q for P = (2 * Q) + 1 a = 0; b = (ZZ(314 / 8) * Q) / 100; ZZ r; r = RandomBnd(b - ZZ(1)) + ZZ(1); r += a; cout << "[a, b] = [" << a << ", " << b << "]" << endl; // cout << "x = " << r << endl; PowerMod(beta, alpha, r, P); } else { cout << "Using default values.\n" "You can provide your own as commandline arguments: hpc_pollard [P alpha beta]\n"; } cout << "beta = alpha^x mod P\n" << beta << " = " << alpha << "^x mod " << P << "\n\n"; ZZ x, real_beta; x = pollard_lambda(alpha, beta, P, a, b); if (x < 0) { cout << "failure\n"; } else { PowerMod(real_beta, alpha, x, P); cout << "x = " << x << endl; cout << real_beta << " = " << alpha << "^" << x << " mod " << P << '\n'; assert(real_beta == beta); } return 0; }
[ "radek.kwlsk@gmail.com" ]
radek.kwlsk@gmail.com
4158eef34638b5a3d6168c67806b7a43be808d21
a6d6768f0cb3cf60ead4861f3d0956542647e2be
/src/include/mclTimer.h
5411e11ce1f808f33ee5d2a07ffd4a82c294e25c
[]
no_license
mclumd/MCL
d8707e7b85476a6f926757980b1f7313915cbe60
90c6a70187ab13e8ba664038eb2205f9667f8607
refs/heads/master
2020-04-12T05:46:15.173170
2014-02-06T23:35:57
2014-02-06T23:35:57
16,597,476
1
0
null
null
null
null
UTF-8
C++
false
false
1,738
h
#ifndef MCL_TIMER_H #define MCL_TIMER_H /** \file mclTimer.h * \brief A real-time timer. */ #ifdef WIN32 #include <Winsock2.h> #else #include <sys/time.h> #endif #include <time.h> #define usec_per_sec 1000000 //! class of timer objects. class mclTimer { public: //! constructs a timer that has already expired mclTimer(); /** constructs a timer that will expire at the specified time from now * the expiration time on the constructed timer will be seconds+useconds * from the current time. * \param seconds expiration time from now, in seconds * \param useconds expiration time from now, in microseconds */ mclTimer(int seconds, int useconds); static double getTimeDouble(); //! true if the timer has expired. bool expired(); /** resets the timer so that it will expire at the specified time from now * the expiration time on the timer will be seconds+useconds * from the current time. * \param seconds expiration time from now, in seconds * \param useconds expiration time from now, in microseconds */ void restart(int seconds, int useconds); /** resets the timer so that it will expire in 1/Hz seconds * the expiration time will allow the timer to fire at the specified * frequency if it is continuously reset. * \param Hz the timer frequency in Hertz */ void restartHz(float Hz); /** computes the time to expiration in microseconds and seconds * \param sleft writes the number of seconds left to this memory location * \param usleft writes the number of microseconds left to this memory location * \return true if the timer is not expired */ bool timeRemaining(int *sleft,int *usleft); private: struct timeval current,target; }; #endif
[ "e.hand@live.com" ]
e.hand@live.com
d2abc726a136cf22955faf17f5b6ecff38803076
8947812c9c0be1f0bb6c30d1bb225d4d6aafb488
/03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch5_ShadowedLabels.cpp
395429e2b429fcded731bef7d2d20a0f5b3ea431
[ "MIT" ]
permissive
alissastanderwick/OpenKODE-Framework
cbb298974e7464d736a21b760c22721281b9c7ec
d4382d781da7f488a0e7667362a89e8e389468dd
refs/heads/master
2021-10-25T01:33:37.821493
2016-07-12T01:29:35
2016-07-12T01:29:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,502
cpp
/* -------------------------------------------------------------------------- * * File Ch5_ShadowedLabels.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * Created By Nate Burba * Contact Cocos2dCookbook@gmail.com * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. * Copyright (c) 2011 COCOS2D COOKBOOK. All rights reserved. * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "Ch5_ShadowedLabels.h" #include "Libraries/ShadowLabel.h" KDbool Ch5_ShadowedLabels::init ( KDvoid ) { if ( !Recipe::init ( ) ) { return KD_FALSE; } m_pMessage->setString ( "" ); // Draw four different shadowed labels using 4 different fonts CCMenuItemFont::setFontSize ( 47 ); CCMenuItemFont::setFontName ( "Georgia.ttf" ); this->label ( "Label 1", ccp ( -120, 50 ), ccc3 ( 0, 50, 255 ), ccc3 ( 0, 200, 255 ), menu_selector ( Ch5_ShadowedLabels::labelTouched ), 1 ); CCMenuItemFont::setFontSize ( 40 ); CCMenuItemFont::setFontName ( "Marker Felt.ttf" ); this->label ( "Label 2", ccp ( 120, 50 ), ccc3 ( 255, 128, 0 ), ccc3 ( 255, 255, 0 ), menu_selector ( Ch5_ShadowedLabels::labelTouched ), 2 ); CCMenuItemFont::setFontSize ( 45 ); CCMenuItemFont::setFontName ( "Arial.ttf" ); this->label ( "Label 3", ccp ( -120, -50 ), ccc3 ( 0, 128, 0 ), ccc3 ( 0, 255, 0 ), menu_selector ( Ch5_ShadowedLabels::labelTouched ), 3 ); CCMenuItemFont::setFontSize ( 50 ); CCMenuItemFont::setFontName ( "Courier New.ttf" ); this->label ( "Label 4", ccp ( 120, -50 ), ccc3 ( 255, 0, 0 ), ccc3 ( 255, 255, 0 ), menu_selector ( Ch5_ShadowedLabels::labelTouched ), 4 ); return KD_TRUE; } // Label creation helper method KDvoid Ch5_ShadowedLabels::label ( const KDchar* szStr, const CCPoint& tPoint, const ccColor3B& tColor, const ccColor3B& tActiveColor, SEL_MenuHandler pSelector, KDint nTag ) { ShadowLabel* pLabel = ShadowLabel::create ( szStr, this, pSelector ); pLabel->setPosition ( tPoint ); pLabel->setColor ( tColor ); pLabel->setActiveColor ( tActiveColor ); pLabel->setTag ( nTag ); CCMenu* pMenu = CCMenu::create ( pLabel->getShadow ( ), pLabel, KD_NULL ); pMenu->setPosition ( ccp ( 240, 160 ) ); this->addChild ( pMenu ); } // Label touch callback KDvoid Ch5_ShadowedLabels::labelTouched ( CCObject* pSender ) { ShadowLabel* pLabel = (ShadowLabel*) pSender; this->showMessage ( ccszf ( "Pressed label %d", pLabel->getTag ( ) ) ); }
[ "mcodegeeks@gmail.com" ]
mcodegeeks@gmail.com
d7508c74726376f5fb448e086d1bbc7f69a5efe3
60d350fd266a95a9898bced9f9f98d499949d7db
/testdata/test_binary.cc
59fe51881ee4fe584a2702d53d78f33af41bab96
[ "Apache-2.0" ]
permissive
isabella232/lldb-eval
e9af865cd927835d6184f6f9a3f4bf34a08dd292
68cdc845b53ce9193564c2a9ba82ed2fc8f34a2b
refs/heads/master
2023-01-01T23:13:25.350036
2020-09-23T16:27:24
2020-09-23T16:27:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,695
cc
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <limits> #include <string> static void TestArithmetic() { int a = 1; int int_max = std::numeric_limits<int>::max(); int int_min = std::numeric_limits<int>::min(); unsigned int uint_max = std::numeric_limits<unsigned int>::max(); unsigned int uint_zero = 0; long long ll_max = std::numeric_limits<long long>::max(); long long ll_min = std::numeric_limits<long long>::min(); unsigned long long ull_max = std::numeric_limits<unsigned long long>::max(); unsigned long long ull_zero = 0; // BREAK(TestArithmetic) } static void TestPointerArithmetic() { const char* p_char1 = "hello"; int offset = 5; int array[10]; array[0] = 0; array[offset] = offset; int* p_int0 = &array[0]; const int* cp_int0 = &array[0]; const int* cp_int5 = &array[offset]; typedef int* td_int_ptr_t; td_int_ptr_t td_int_ptr0 = &array[0]; void* p_void = (void*)p_char1; void** pp_void0 = &p_void; void** pp_void1 = pp_void0 + 1; // BREAK(TestPointerArithmetic) } static void TestLogicalOperators() { bool trueVar = true; bool falseVar = false; const char* p_ptr = "🦊"; const char* p_nullptr = nullptr; struct S { } s; // BREAK(TestLogicalOperators) } static void TestLocalVariables() { int a = 1; int b = 2; char c = -3; unsigned short s = 4; // BREAK(TestLocalVariables) } static void TestIndirection() { int val = 1; int* p = &val; // BREAK(TestIndirection) } // Referenced by TestInstanceVariables class C { public: int field_ = 1337; }; // Referenced by TestAddressOf int globalVar = 0xDEADBEEF; extern int externGlobalVar; class TestMethods { public: void TestInstanceVariables() { C c; c.field_ = -1; C& c_ref = c; C* c_ptr = &c; // BREAK(TestInstanceVariables) } void TestAddressOf(int param) { std::string s = "hello"; const char* s_str = s.c_str(); // BREAK(TestAddressOf) } private: int field_ = 1; }; static void TestSubscript() { const char* char_ptr = "lorem"; const char char_arr[] = "ipsum"; int int_arr[] = {1, 2, 3}; C c_arr[2]; c_arr[0].field_ = 0; c_arr[1].field_ = 1; C(&c_arr_ref)[2] = c_arr; int idx_1 = 1; const int& idx_1_ref = idx_1; typedef int td_int_t; typedef td_int_t td_td_int_t; typedef int* td_int_ptr_t; typedef int& td_int_ref_t; td_int_t td_int_idx_1 = 1; td_td_int_t td_td_int_idx_2 = 2; td_int_t td_int_arr[3] = {1, 2, 3}; td_int_ptr_t td_int_ptr = td_int_arr; td_int_ref_t td_int_idx_1_ref = td_int_idx_1; td_int_t(&td_int_arr_ref)[3] = td_int_arr; unsigned char uchar_idx = std::numeric_limits<unsigned char>::max(); uint8_t uint8_arr[256]; uint8_arr[255] = 0xAB; // BREAK(TestSubscript) } // Referenced by TestCStyleCast namespace ns { typedef int myint; class Foo {}; namespace inner { using mydouble = double; class Foo {}; } // namespace inner } // namespace ns static void TestCStyleCast() { int a = 1; int* ap = &a; void* vp = &a; int na = -1; float f = 1.1; typedef int myint; myint myint_ = 1; ns::myint ns_myint_ = 2; ns::Foo ns_foo_; ns::Foo* ns_foo_ptr_ = &ns_foo_; ns::inner::mydouble ns_inner_mydouble_ = 1.2; ns::inner::Foo ns_inner_foo_; ns::inner::Foo* ns_inner_foo_ptr_ = &ns_inner_foo_; // BREAK(TestCStyleCastBasicType) // BREAK(TestCStyleCastPointer) } // Referenced by TestQualifiedId. namespace ns { int i = 1; namespace ns { int i = 2; } // namespace ns } // namespace ns class Foo { public: static const int x = 42; static const int y; }; const int Foo::y = 42; static void TestQualifiedId() { // BREAK(TestQualifiedId) } // Referenced by TestTemplateTypes. template <typename T> struct T_1 { static const int cx; typedef double myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 42; template <> const int T_1<int>::cx = 24; template <typename T1, typename T2> struct T_2 { typedef float myint; T_2() {} T1 x; T2 y; }; namespace ns { template <typename T> struct T_1 { static const int cx; typedef int myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 46; template <> const int T_1<int>::cx = 64; } // namespace ns static void TestTemplateTypes() { int i; int* p = &i; { T_1<int> _; } { T_1<int*> _; } { T_1<int**> _; } { T_1<int&> _(i); } { T_1<int*&> _(p); } { T_1<double> _; } { T_2<int, char> _; } { T_2<char, int> _; } { T_2<T_1<int>, T_1<char>> _; } { T_2<T_1<T_1<int>>, T_1<char>> _; } { ns::T_1<int> _; } { ns::T_1<ns::T_1<int>> _; } { T_1<int>::myint _ = 0; } { T_1<int*>::myint _ = 0; } { T_1<int**>::myint _ = 0; } { T_1<int&>::myint _ = 0; } { T_1<int*&>::myint _ = 0; } { T_1<T_1<int>>::myint _ = 0; } { T_1<T_1<int*>>::myint _ = 0; } { T_1<T_1<int**>>::myint _ = 0; } { T_1<T_1<int&>>::myint _ = 0; } { T_1<T_1<int*&>>::myint _ = 0; } { T_2<int, char>::myint _ = 0; } { T_2<int*, char&>::myint _ = 0; } { T_2<int&, char*>::myint _ = 0; } { T_2<T_1<T_1<int>>, T_1<char>>::myint _ = 0; } { ns::T_1<int>::myint _ = 0; } { ns::T_1<int*>::myint _ = 0; } { ns::T_1<int**>::myint _ = 0; } { ns::T_1<int&>::myint _ = 0; } { ns::T_1<int*&>::myint _ = 0; } { ns::T_1<T_1<int>>::myint _ = 0; } { ns::T_1<T_1<int*>>::myint _ = 0; } { ns::T_1<T_1<int**>>::myint _ = 0; } { ns::T_1<T_1<int&>>::myint _ = 0; } { ns::T_1<T_1<int*&>>::myint _ = 0; } { ns::T_1<ns::T_1<int>>::myint _ = 0; } { ns::T_1<ns::T_1<int*>>::myint _ = 0; } { ns::T_1<ns::T_1<int**>>::myint _ = 0; } { ns::T_1<ns::T_1<int&>>::myint _ = 0; } { ns::T_1<ns::T_1<int*&>>::myint _ = 0; } (void)T_1<double>::cx; (void)ns::T_1<double>::cx; (void)ns::T_1<ns::T_1<int>>::cx; // BREAK(TestTemplateTypes) } int main() { TestMethods tm; TestArithmetic(); TestPointerArithmetic(); TestLogicalOperators(); TestLocalVariables(); tm.TestInstanceVariables(); TestIndirection(); tm.TestAddressOf(42); TestSubscript(); TestCStyleCast(); TestQualifiedId(); TestTemplateTypes(); // break here }
[ "werat@google.com" ]
werat@google.com
1969158571a3f9ea9c862289f9137607269a4756
67941601affc289defc19f5dcc7d21ebe8ae2ea5
/ExpressionConversion-InfixPrefix.cpp
88613ea4baba192a4276a4d764859d7300f52ffb
[]
no_license
Gaurav-Gaikwad-1/Data-Structures-Programs-in-C-
c07f178f0f9c12672b371d986a042ec08108af1a
002fe377b5afe5fd407e98b33087a59a3cc37b42
refs/heads/master
2022-05-25T09:07:39.391960
2020-04-27T08:11:29
2020-04-27T08:11:29
259,247,265
0
0
null
null
null
null
UTF-8
C++
false
false
2,519
cpp
/* Implement C/C++ program for expression conversion- a) infix to prefix, b)prefix to postfix, c) prefix to infix, d) postfix to infix and e) postfix to prefix. */ #include <iostream> using namespace std; class post { char expr[20]="",out[20]="",stack[15]; int stack1[15]; int top=-1,j=0; public: void getData(); int getPrecedence(char); void push(char); char pop(); void push_int(int); int pop_int(); void evaluate(); int stEmpty(); void convert(); }; void post::getData() { cout<<"\nEnter Infix Expression:"; cin>>expr; } int post::getPrecedence(char ch) { if(ch=='+' || ch=='-') return 1; if(ch=='*' || ch=='/') return 2; else return 0; } void post::push(char ch) { stack[++top]=ch; } char post::pop() { return stack[top--]; } int post::stEmpty() { if(top==-1) return 1; else return 0; } void post::convert() { int i=0; char tmp; while(expr[i]!='\0') { if(expr[i]=='(' || expr[i]=='[' || expr[i]=='{') { push(expr[i]); } else if(expr[i]==')' || expr[i]==']' || expr[i]=='}') { if(expr[i]==')') { while(stack[top]!='(') { out[j++]=pop(); } } if(expr[i]==']') { while(stack[top]!='[') { out[j++]=pop(); } } if(expr[i]=='}') { while(stack[top]!='{') { out[j++]=pop(); } } tmp=pop(); } else if(expr[i]=='+' || expr[i]=='-' || expr[i]=='*' || expr[i]=='/') { if(getPrecedence(stack[top]) >= getPrecedence(expr[i])) { out[j++]=pop(); push(expr[i]); } else { push(expr[i]); } } else { out[j++]=expr[i]; } i++; } if(top!=-1) { while(top>=-1) { out[j++]=pop(); } } out[j]='\0'; cout<<"\nPostfix expression is:"; for(i=0;out[i]!='\0';i++) cout<<out[i]; } void post::push_int(int ch) { stack1[++top]=ch; } int post::pop_int() { return stack1[top--]; } void post::evaluate() { int i=0; int op1=0,op2=0; while(out[i]!='\0') { if(out[i]=='+') { op2=pop_int(); op1=pop_int(); push_int(op1+op2); } else if(out[i]=='-') { op2=pop_int(); op1=pop_int(); push_int(op1 - op2); } else if(out[i]=='*') { op2=pop_int(); op1=pop_int(); push_int(op1 * op2); } else if(out[i]=='/') { op2=pop_int(); op1=pop_int(); push_int(op1 / op2); } else { push_int((int)out[i]-48); } i++; } cout<<"\n\nEvaluation is:"<<pop_int()<<"\n"; } int main() { post p; p.getData(); p.convert(); p.evaluate(); return 0; }
[ "gauraevg1234@gmail.com" ]
gauraevg1234@gmail.com
d0fe4ccd4e7513105c9e22ebcdb269d8c064e790
29b91fafb820e5513c7284072dca5bd77c189b22
/array_row_max_ones.cpp
d68f9c2543bf7375b8631ba619c691e2c3569939
[]
no_license
rishirajsurti/gfg
c1d542ebb59790d529be7be2a107a67f4fae2b35
f7205bec70c39e085bf8a45b527f7464c8bcef8e
refs/heads/master
2021-03-27T19:13:06.466708
2016-11-15T11:43:31
2016-11-15T11:43:31
61,434,826
0
0
null
null
null
null
UTF-8
C++
false
false
430
cpp
#include <bits/stdc++.h> using namespace std; int a[53][53]; int main(){ int t; scanf("%d", &t); while(t--){ int n, m; scanf("%d %d", &n, &m); int cur_sum=0, max_sum=INT_MIN, ans= -1; for(int i = 0; i < n; i++){ cur_sum = 0; int u; for(int j = 0; j < m; j++){ scanf("%d", &u); cur_sum+= u; } if(cur_sum > max_sum){ max_sum = cur_sum; ans = i; } } printf("%d\n", ans); } return 0; }
[ "rishirajsurti.iitm@gmail.com" ]
rishirajsurti.iitm@gmail.com
b58820cdb91fc35c044ea1ae7dc949e4085e31a7
c66c4318725ed89310423c4f8f34d1206a787cf6
/Math/segmentedSieve.cpp
297207adf219705a956c2a6351a315a734d09031
[ "Apache-2.0" ]
permissive
rsd511/CP-Library
6b96f7f321b0718ee7cd432576459ff542ca7190
85460629097436f494f51a4f89b097559567f71c
refs/heads/master
2021-07-18T00:28:40.611917
2020-10-22T11:54:53
2020-10-22T11:54:53
222,041,697
3
0
null
null
null
null
UTF-8
C++
false
false
741
cpp
// OUTSIDE MAIN // Calculates till MAX #define MAX 1000000 ll isPrime[MAX + 1]; void sieve() { isPrime[0] = isPrime[1] = 0; f(i,2,MAX) isPrime[i] = 1; for(ll i = 2; i*i <= MAX; i++) if(isPrime[i]) { for(ll j = i*i; j <= MAX; j += i) isPrime[j] = 0; } } vector <ll> segmentedSieve(ll low, ll high) { low = max(low,(ll)2); vector <ll> ret; ret.clear(); ll limit = (ll)sqrt(high) + 1; ll n = high - low + 1; ll mark[n + 1] = {0}; f(i,2,limit) if(isPrime[i]) { ll lowerLimit = (low / i) * i; if(lowerLimit < low) lowerLimit += i; if(lowerLimit == i) lowerLimit += i; for(ll j = lowerLimit; j <= high; j += i) mark[j-low] = 1; } f(i,low,high) if(!mark[i-low]) ret.pb(i); return ret; } // INSIDE MAIN sieve();
[ "rahul.rsd511@gmail.com" ]
rahul.rsd511@gmail.com
88a0854b69859c1f0197546464a72a9e60aa8884
7a2e4fb0ef75367e88112160713f94b1eee06eea
/src/Common/ConsoleTools.h
28707798729957eaaf22557a320cee24fc124cd3
[]
no_license
rainmanp7/digitalnote45
0ba02600369f19c729841c736f5809893bc45034
c64310a220f12b6d4e7f4820c8014026a4266a02
refs/heads/master
2020-03-17T16:02:22.867091
2018-05-17T01:33:53
2018-05-17T01:33:53
133,733,725
0
0
null
null
null
null
UTF-8
C++
false
false
624
h
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2014-2017 XDN-project developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <cstdint> namespace Common { namespace Console { enum class Color : uint8_t { Default, Blue, Green, Red, Yellow, White, Cyan, Magenta, BrightBlue, BrightGreen, BrightRed, BrightYellow, BrightWhite, BrightCyan, BrightMagenta }; void setTextColor(Color color); bool isConsoleTty(); }}
[ "muslimsoap@gmail.com" ]
muslimsoap@gmail.com
e25e5b50b273e8f2492fbdd04895498216a8d3e0
724cb73a1a93b9a4b78ac8ff0fc249854e8154ae
/297/solution.cpp
4d954a5a8a7d8cac690473b7bd29272ee803cb66
[]
no_license
nikitaunity/project_euler
9d68cd83fb160e259be4893719c018ca65cbf291
9ef1279abb670bbba4fbc5438801b008ac788af0
refs/heads/main
2023-02-18T14:45:01.087050
2021-01-23T22:34:14
2021-01-23T22:34:14
325,356,193
0
0
null
null
null
null
UTF-8
C++
false
false
3,205
cpp
#include <iostream> #include <vector> #include <cstdlib> #include <chrono> std::vector<uint64_t> generateFibonacchiSequence(uint64_t max_value) { std::vector<uint64_t> fibonacchi_numbers = {1, 2}; uint64_t last_two_sum = 3; size_t count = 2; while (last_two_sum < max_value) { fibonacchi_numbers.push_back(last_two_sum); ++count; last_two_sum = fibonacchi_numbers[count - 2] + fibonacchi_numbers[count - 1]; } return fibonacchi_numbers; } std::vector<std::vector<uint64_t> > calculateNumberOfSequenceWithFixedFibonacciNumbers( size_t max_length) { std::vector<std::vector<uint64_t>> number_of_sequence( ((max_length + 1) >> 1) + 1, std::vector<uint64_t>(max_length, 0)); for (size_t i = 0; i < max_length; ++i) { number_of_sequence[0][i] = 1; } for (size_t ones_number = 1; ones_number <= ((max_length + 1) >> 1); ++ones_number) { size_t min_length = (ones_number << 1) - 1; number_of_sequence[ones_number][min_length] = 1; for (size_t length = min_length + 1; length < max_length; ++length) { number_of_sequence[ones_number][length] = number_of_sequence[ones_number - 1][length - 2] + number_of_sequence[ones_number][length - 1]; } } return number_of_sequence; } uint64_t calculateNumberOfOnesWithFixedLength( const std::vector<std::vector<uint64_t> >& number_of_sequence, const std::vector<uint64_t>& fibonacci_sequence, size_t length, size_t number_of_ones_defined) { uint64_t answer = 0; for (size_t ones_number = 0; ones_number <= ((length + 1) >> 1); ++ones_number) { answer += number_of_sequence[ones_number][length] * ones_number; } answer += number_of_ones_defined * fibonacci_sequence[length]; return answer; } int main(int argc, char** argv) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); if (argc != 2) { std::cout << "Please provide only 1 parameter (max N)...\n"; return 1; } uint64_t max_value = static_cast<uint64_t>(std::atoll(argv[1])); auto fibonacci_sequence = generateFibonacchiSequence(max_value); auto number_of_sequences = calculateNumberOfSequenceWithFixedFibonacciNumbers(fibonacci_sequence.size()); uint64_t pos = static_cast<uint64_t>(fibonacci_sequence.size()) - 1; uint64_t current_value = max_value; uint64_t number_of_ones = 0; uint64_t answer = 0; while (current_value > 0) { if (fibonacci_sequence[pos] <= current_value) { answer += calculateNumberOfOnesWithFixedLength( number_of_sequences, fibonacci_sequence, pos, number_of_ones); current_value -= fibonacci_sequence[pos]; ++number_of_ones; pos -= 2; } else { --pos; } } std::cout << answer << '\n'; std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::cout << std::fixed << "Time difference = " << static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.0 << "[s]" << '\n'; return 0; }
[ "nikitaalexandrov@unity3d.com" ]
nikitaalexandrov@unity3d.com
3cd1653372b3a81060a775b630a8e5c3b934f5f4
b38c5eb548636af44b4c82fc2b57e3103114f2e0
/test/PoE-test/spacedeur-asis-2017/spacedeur-asis-2017.ino
4bc03daeaea1efd052d7702156c72176e035e1ff
[ "LicenseRef-scancode-other-permissive", "MIT", "NTP", "LicenseRef-scancode-rsa-1990", "LicenseRef-scancode-rsa-md4", "Beerware", "RSA-MD", "HPND-sell-variant", "Spencer-94", "LicenseRef-scancode-zeusbench", "metamail", "Apache-2.0" ]
permissive
MakerSpaceLeiden/AccesSystem
e652a343c86ac904de8a1a08adc13bbc3ee6de7d
5e39572f51fafca71750660fcf5f737670f17d54
refs/heads/master
2023-05-27T01:44:57.893580
2023-05-16T11:27:48
2023-05-16T11:27:48
54,308,309
4
4
Apache-2.0
2022-02-21T22:37:34
2016-03-20T08:46:08
C++
UTF-8
C++
false
false
18,873
ino
/* Spacedeur 2-'as is' configuration which should be near identical to the existing setup late 2017. */ #include "/Users/dirkx/.passwd.h" // Wired ethernet. // #define ETH_PHY_ADDR 1 #define ETH_PHY_MDC 23 #define ETH_PHY_MDIO 18 #define ETH_PHY_POWER 17 #define ETH_PHY_TYPE ETH_PHY_LAN8720 // Labelling as per `blue' RFID MFRC522-MSL 1471 'fixed' // #define MFRC522_SDA (15) #define MFRC522_SCK (14) #define MFRC522_MOSI (13) #define MFRC522_MISO (12) #define MFRC522_IRQ (33) #define MFRC522_GND /* gnd pin */ #define MFRC522_RSTO (32) #define MFRC522_3V3 /* 3v3 */ // Stepper motor-Pololu / A4988 // #define STEPPER_DIR (2) #define STEPPER_ENABLE (4) #define STEPPER_STEP (5) #define STEPPER_MAXSPEED (1250) #define STEPPER_ACCELL (750) #define LED_AART (16) #define DOOR_CLOSED (0) #define DOOR_OPEN (1100) #define DOOR_OPEN_DELAY (10*1000) #define REPORTING_PERIOD (300*1000) typedef enum doorstates { CLOSED, CHECKINGCARD, OPENING, OPEN, CLOSING } doorstate_t; doorstate_t doorstate; unsigned long long last_doorstatechange = 0; long cnt_cards = 0, cnt_opens = 0, cnt_closes = 0, cnt_fails = 0, cnt_misreads = 0, cnt_minutes = 0, cnt_reconnects = 0, cnt_mqttfails = 0; #include <ETH.h> #include <SPI.h> #include <SPIFFS.h> #include <FS.h> #include <ArduinoOTA.h> #include <AccelStepper.h> #include <PubSubClient.h> #include <MFRC522.h> // Requires modifed MFRC522 (see pull rq) or the -master branch as of late DEC 2017. // https://github.com/miguelbalboa/rfid.git SPIClass spirfid = SPIClass(VSPI); const SPISettings spiSettings = SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0); MFRC522 mfrc522(MFRC522_SDA, MFRC522_RSTO, &spirfid, spiSettings); // Simple overlay of the AccelStepper that configures for the A4988 // driver of a 4 wire stepper-including the additional enable wire. // class PololuStepper : public AccelStepper { public: PololuStepper(uint8_t step_pin = 0xFF, uint8_t dir_pin = 0xFF, uint8_t enable_pin = 0xFF); }; PololuStepper::PololuStepper(uint8_t step_pin, uint8_t dir_pin, uint8_t enable_pin) : AccelStepper(AccelStepper::DRIVER, step_pin, dir_pin) { pinMode(STEPPER_ENABLE, OUTPUT); digitalWrite(STEPPER_ENABLE, LOW); // dis-able stepper first. setPinsInverted(false, false, true); // The enable pin is NOT inverted. Kind of unusual. setEnablePin(enable_pin); } PololuStepper stepper = PololuStepper(STEPPER_STEP, STEPPER_DIR, STEPPER_ENABLE); #ifdef LOCALMQTT const IPAddress mqtt_host = LOCALMQTT; #else const char mqtt_host[] = "space.vijn.org"; #endif const unsigned short mqtt_port = 1883; extern void callback(char* topic, byte * payload, unsigned int length); bool caching = false; #ifdef LOCALMQTT #define PREFIX "" #else #define PREFIX "test" #endif const char rfid_topic[] = PREFIX "deur/space2/rfid"; const char door_topic[] = PREFIX "deur/space2/open"; const char log_topic[] = PREFIX "log"; WiFiClient wifiClient; PubSubClient client(wifiClient); static bool eth_connected = false; char pname[128] = "some-unconfigured-door"; static bool ota = false; void enableOTA() { if (ota) return; ArduinoOTA.setPort(3232); ArduinoOTA.setHostname(pname); #ifdef LOCALOTA ArduinoOTA.setPasswordHash(LOCALOTA); #endif ArduinoOTA.onStart([]() { String type; switch (ArduinoOTA.getCommand()) { case U_FLASH: type = "Firmware"; break; case U_SPIFFS: type = "SPIFFS"; break; default: { const char buff[] = "Unknown type of reprogramming attempt. Rejecting."; Serial.println(buff); client.publish(log_topic, buff); client.loop(); ESP.restart(); } break; }; char buff[256]; snprintf(buff, sizeof(buff), "[%s] %s OTA reprogramming started.", pname, type.c_str()); Serial.println(buff); client.publish(log_topic, buff); client.loop(); closeDoor(); while (stepper.isRunning()) { stepper.run(); }; stepper.disableOutputs(); SPIFFS.end(); }); ArduinoOTA.onEnd([]() { char buff[256]; snprintf(buff, sizeof(buff), "[%s] OTA re-programming completed. Rebooting.", pname); Serial.println(buff); client.publish(log_topic, buff); client.loop(); client.disconnect(); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { static int lp = -1 ; int p = progress / (total / 10); if (p != lp) Serial.printf("Progress: %u %%\n", p * 10); lp = p; digitalWrite(LED_AART, ((millis() >> 7) & 3) == 0); }); // Unfortunately-deep in OTA it auto defaults to Wifi. So we // force it to ETH -- requires pull RQ https://github.com/espressif/arduino-esp32/issues/944 // and https://github.com/espressif/esp-idf/issues/1431. // ArduinoOTA.begin(TCPIP_ADAPTER_IF_ETH); Serial.println("OTA enabled."); ota = true; } String DisplayIP4Address(IPAddress address) { return String(address[0]) + "." + String(address[1]) + "." + String(address[2]) + "." + String(address[3]); } String connectionDetailsString() { return "Wired Ethernet: " + ETH.macAddress() + ", IPv4: " + DisplayIP4Address(ETH.localIP()) + ", " + ((ETH.fullDuplex()) ? "full" : "half") + "-duplex, " + String(ETH.linkSpeed()) + " Mbps, Build: " + String(__DATE__) + " " + String(__TIME__); } void WiFiEvent(WiFiEvent_t event) { switch (event) { case SYSTEM_EVENT_ETH_START: Serial.println("ETH Started"); ETH.setHostname(pname); break; case SYSTEM_EVENT_ETH_CONNECTED: Serial.println("ETH Connected"); break; case SYSTEM_EVENT_ETH_GOT_IP: case SYSTEM_EVENT_STA_GOT_IP: Serial.println(connectionDetailsString()); eth_connected = true; break; case SYSTEM_EVENT_ETH_DISCONNECTED: Serial.printf("ETH Disconnected (event %d)\n", event); eth_connected = false; break; case SYSTEM_EVENT_ETH_STOP: Serial.println("ETH Stopped"); eth_connected = false; break; default: Serial.printf("Unknown event %d\n", event); break; } } volatile boolean irqCardSeen = false; void readCard() { irqCardSeen = true; } /* The function sending to the MFRC522 the needed commands to activate the reception */ void activateRec(MFRC522 mfrc522) { mfrc522.PCD_WriteRegister(mfrc522.FIFODataReg, mfrc522.PICC_CMD_REQA); mfrc522.PCD_WriteRegister(mfrc522.CommandReg, mfrc522.PCD_Transceive); mfrc522.PCD_WriteRegister(mfrc522.BitFramingReg, 0x87); } /* The function to clear the pending interrupt bits after interrupt serving routine */ void clearInt(MFRC522 mfrc522) { mfrc522.PCD_WriteRegister(mfrc522.ComIrqReg, 0x7F); } static long lastReconnectAttempt = 0; boolean reconnect() { if (!client.connect(pname)) { // Do not log this to the MQTT bus-as it may have been us posting too much // or some other loop-ish thing that triggered our disconnect. // Serial.println("Failed to reconnect to MQTT bus."); return false; } char buff[256]; snprintf(buff, sizeof(buff), "[%s] %sconnected, %s", pname, cnt_reconnects ? "re" : "", connectionDetailsString().c_str()); client.publish(log_topic, buff); client.subscribe(door_topic); Serial.println(buff); cnt_reconnects++; return client.connected(); } void setup() { const char * f = __FILE__; char * p = rindex(f, '/'); if (p) strncpy(pname, p + 1, sizeof(pname)); p = index(pname, '.'); if (p) *p = 0; #ifndef LOCALMQTT // Alert us to safe, non production versions. strncat(pname, "-test", sizeof(pname)); #endif Serial.begin(115200); Serial.print("\n\n\n\nStart "); Serial.print(pname); Serial.println(" -- buuld: " __DATE__ " " __TIME__ ); pinMode(LED_AART, OUTPUT); digitalWrite(LED_AART, 1); WiFi.onEvent(WiFiEvent); ETH.begin(); Serial.println("SPI init"); spirfid.begin(MFRC522_SCK, MFRC522_MISO, MFRC522_MOSI, MFRC522_SDA); Serial.println("MFRC522 IRQ and callback setup."); mfrc522.PCD_Init(); // Init MFRC522 mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD-MFRC522 Card Reader details pinMode(MFRC522_IRQ, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(MFRC522_IRQ), readCard, FALLING); byte regVal = 0xA0; //rx irq mfrc522.PCD_WriteRegister(mfrc522.ComIEnReg, regVal); Serial.println("Setting up MQTT"); client.setServer(mqtt_host, mqtt_port); client.setCallback(callback); Serial.println("Setup of Stepper motor"); stepper.setMaxSpeed(STEPPER_MAXSPEED); // divide by 3 to get rpm stepper.setAcceleration(STEPPER_ACCELL); stepper.moveTo(DOOR_CLOSED); stepper.run(); doorstate = CLOSED; last_doorstatechange = millis(); Serial.println("SPIFF setup"); if (!SPIFFS.begin()) { Serial.println("SPIFFS Mount Failed-reformatting"); wipeCache(); } else { caching = true; listDir(SPIFFS, "/", ""); }; Serial.println("setup() done.\n\n"); } // This function is taken from the SPIFFS_Test example. Under the expressif ESP32 license. // void listDir(fs::FS &fs, const char * dirname, String prefix) { Serial.print(prefix); Serial.println(dirname); File root = fs.open(dirname); if (!root) { Serial.println("Failed to open directory"); return; } if (!root.isDirectory()) { Serial.println("Not a directory"); return; } File file = root.openNextFile(); while (file) { if (file.isDirectory()) { listDir(fs, file.name(), prefix + " "); } else { Serial.print(prefix + " "); Serial.println(file.name()); } file = root.openNextFile(); } root.close(); } void wipeCache() { caching = false; if (!SPIFFS.format()) { Serial.println("SPIFFS formatting failed."); return; } Serial.println("Formatted."); if (!SPIFFS.begin()) { Serial.println("SPIFFS mount after formatting failed."); return; }; for (int i = 0; i < 255; i++) SPIFFS.mkdir(String(i)); Serial.println("Directory structure created."); listDir(SPIFFS, "/", ""); caching = true; }; String uid2path(MFRC522::Uid uid) { String path = "/uid-"; for (int i = 0; i < uid.size; i++) { path += String(uid.uidByte[i], DEC); if (i == 0) path += "/"; else path += "."; }; return path; } bool checkCache(MFRC522::Uid uid) { String path = uid2path(uid) + ".lastOK"; return SPIFFS.exists(path); } void setCache(MFRC522::Uid uid, bool ok) { String path = uid2path(uid) + ".lastOK"; if (ok) { File f = SPIFFS.open(path, "w"); f.println(cnt_minutes); f.close(); } else { SPIFFS.remove(path); } } void openDoor() { doorstate = OPENING; stepper.enableOutputs(); stepper.moveTo(DOOR_OPEN); }; bool isOpen() { return stepper.currentPosition() == DOOR_OPEN; // no sensors. } void closeDoor() { stepper.moveTo(DOOR_CLOSED); doorstate = CLOSING; } bool isClosed() { return stepper.currentPosition() == DOOR_CLOSED; // no sensors. } MFRC522::Uid uid; String uidToString(MFRC522::Uid uid) { String uidStr = ""; for (int i = 0; i < uid.size; i++) { if (i) uidStr += "-"; uidStr += String(uid.uidByte[i], DEC); }; return uidStr; } void callback(char* topic, byte * payload, unsigned int length) { char buff[256]; if (strcmp(topic, door_topic)) { Serial.printf("Received an unexepcted %d byte message on topic <%s>, ignoring.", length, topic); // We intentinally do not log this message to a MQTT channel-as to reduce the // risk of (amplification) loops due to a misconfiguration. We do increase the counter // so indirectly this does show up in the MQTT log. // cnt_mqttfails ++; return; }; int l = 0; for (int i = 0; l < sizeof(buff) - 1 && i < length; i++) { char c = payload[i]; if (c >= 32 && c < 128) buff[l++] = c; }; buff[l] = 0; Serial.println(buff); if (!strcmp(buff, "reboot")) { ESP.restart(); return; } if (!strcmp(buff, "report")) { reportStats(); return; } if (!strcmp(buff, "purge")) { char msg[255]; wipeCache(); snprintf(msg, sizeof(msg), "[%s] Purged cache.", pname); client.publish(log_topic, msg); Serial.println(msg); return; } if (!strncmp(buff, "purge ", 6)) { char msg[255]; char * ptag = buff + 6; char * p = ptag; for (uid.size = 0; uid.size < sizeof(uid.uidByte) && *p;) { while (*p && !isdigit(*p)) p++; errno = 0; byte b = (byte) strtol(p, NULL, 10); if (b == 0 && (errno || *p != '0')) // it seems ESP32 does not set errno ?! break; uid.uidByte[uid.size++] = b; while (*p && isdigit(*p)) p++; } if (uid.size) { snprintf(msg, sizeof(msg), "[%s] Purged cache of UID <%s> (payload %s)", pname, uidToString(uid).c_str(), ptag); setCache(uid, false); } else { snprintf(msg, sizeof(msg), "[%s] Ignored purge request for uid-payload <%s> ", pname, ptag); cnt_mqttfails ++; } client.publish(log_topic, msg); Serial.println(msg); return; } if (!strcmp(buff, "open")) { Serial.println("Opening door."); openDoor(); if (caching && uid.size) setCache(uid, true); uid.size = 0; return; }; if (caching) setCache(uid, false); uid.size = 0; char msg[256]; snprintf(msg, sizeof(msg), "[%s] Cannot parse reply <%s> [len=%d, payload len=%d] or denied access.", pname, buff, l, length); client.publish(log_topic, msg); Serial.println(msg); cnt_mqttfails ++; } #ifdef __cplusplus extern "C" { #endif uint8_t temprature_sens_read(); #ifdef __cplusplus } #endif double coreTemp() { double temp_farenheit= temprature_sens_read(); return ( temp_farenheit - 32 ) / 1.8; } void reportStats() { char buff[255]; snprintf(buff, sizeof(buff), "[%s] alive-uptime %02ld:%02ld :" "swipes %ld, opens %ld, closes %ld, fails %ld, mis-swipes %ld, mqtt reconnects %ld, mqtt fails %ld, " "stepper %s at %ld (target %ld), temperature %.1f", pname, cnt_minutes / 60, (cnt_minutes % 60), cnt_cards, cnt_opens, cnt_closes, cnt_fails, cnt_misreads, cnt_reconnects, cnt_mqttfails, stepper.run() ? "running" : "halted", stepper.currentPosition(), stepper.targetPosition(), coreTemp() ); client.publish(log_topic, buff); Serial.println(buff); } void loop() { stepper.run(); { static unsigned long aart = 0; unsigned long del = 1000; if (!eth_connected or !client.connected()) del = 100; else if (doorstate != CLOSED) del = 300; if (millis() - aart > del) { digitalWrite(LED_AART, !digitalRead(LED_AART)); aart = millis(); } } if (eth_connected) { if (ota) ArduinoOTA.handle(); else enableOTA(); if (!client.connected()) { long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; if (reconnect()) { lastReconnectAttempt = 0; } } } else { client.loop(); } } else { if (client.connected()) client.disconnect(); } { static doorstate_t lastdoorstate = CLOSED; switch (doorstate) { case CHECKINGCARD: if (millis() - last_doorstatechange > 1500 && caching && checkCache(uid)) { char msg[255]; snprintf(msg, sizeof(msg), "[%s] Allowing door to open based on cached information.", pname); Serial.println(msg); client.publish(log_topic, msg); openDoor(); } break; case OPENING: if (isOpen()) { char msg[256]; snprintf(msg, sizeof(msg), "[%s] Door is open.", pname); Serial.println(msg); client.publish(log_topic, msg); doorstate = OPEN; cnt_opens++; }; break; case OPEN: if (millis() - last_doorstatechange > DOOR_OPEN_DELAY) { Serial.println("Closing door."); closeDoor(); }; case CLOSING: if (isClosed()) { char msg[256]; snprintf(msg, sizeof(msg), "[%s] Door is closed.", pname); Serial.println(msg); client.publish(log_topic, msg); doorstate = CLOSED; cnt_closes++; }; break; case CLOSED: stepper.disableOutputs(); if (!isClosed()) { /// some alerting ? clearly a bug ? } default: break; }; if (lastdoorstate != doorstate) { lastdoorstate = doorstate; last_doorstatechange = millis(); } } // catch any logic errors or strange cases where the door is open while we think // we are not doing anything. // if ((millis() - last_doorstatechange > 10 * DOOR_OPEN_DELAY) && ((doorstate != CLOSED) || (!isClosed()))) { closeDoor(); char msg[256]; snprintf(msg, sizeof(msg), "[%s] Door in an odd state-forcing close.", pname); Serial.println(msg); client.publish(log_topic, msg); cnt_fails ++; } { static unsigned long tock = 0; if (millis() - tock > REPORTING_PERIOD) { cnt_minutes += ((millis() - tock) + 500) / 1000 / 60; reportStats(); tock = millis(); } } if (irqCardSeen) { if (mfrc522.PICC_ReadCardSerial()) { uid = mfrc522.uid; String uidStr = uidToString(uid); String pyStr = "["; for (int i = 0; i < uid.size; i++) { if (i) pyStr += ", "; pyStr += String(uid.uidByte[i], DEC); }; pyStr += "]"; cnt_cards++; client.publish(rfid_topic, pyStr.c_str()); char msg[256]; #ifndef LOCALMQTT snprintf(msg, sizeof(msg), "[%s] Tag <%s> (len=%d) swiped", pname, uidStr.c_str(), uid.size); #else snprintf(msg, sizeof(msg), "[%s] Tag swiped", pname); #endif client.publish(log_topic, msg); Serial.println(msg); doorstate = CHECKINGCARD; } else { Serial.println("Misread."); cnt_misreads++; } mfrc522.PICC_HaltA(); // Stop reading clearInt(mfrc522); irqCardSeen = false; }; // Re-arm/retrigger the scanning regularly. { static unsigned long reminderToRead = 0; if (millis() - reminderToRead > 100) { activateRec(mfrc522); reminderToRead = millis(); } } }
[ "dirkx@webweaving.org" ]
dirkx@webweaving.org
8fb549fcdc53a159b2a47cd04f2df39cc6f42df5
d64bb70a14246e8da868887a67b8a45af061745c
/boost_tst/GraphvizSubgraph/subdot.cc
b9039090154a64b5579c7b0b587c84d5429deaed
[]
no_license
rcoscali/cpad_tool
176fcc20005bff1dcac6045f539abe96ff72602a
4addc1223b32068d72ca1e4d2df21d5b098f9945
refs/heads/master
2021-03-22T04:52:28.258861
2017-06-08T08:51:02
2017-06-08T08:51:02
85,364,407
0
0
null
null
null
null
UTF-8
C++
false
false
3,538
cc
#include <boost/graph/graphviz.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/subgraph.hpp> #include <iostream> #include <boost/graph/random.hpp> // in case you comment out the random graph creation code #include <random> using namespace boost; template <typename SubGraph> SubGraph generate_random() { std::mt19937 prng(std::random_device{}()); SubGraph randomized(uniform_int<int>(10,20)(prng)); auto subs = uniform_int<int>(1,5)(prng); while (subs--) randomized.create_subgraph(); subs = boost::size(randomized.children()); int offset = 0; for (auto& sub : make_iterator_range(randomized.children())) { for (size_t i = offset; i < num_vertices(randomized); i += subs) add_vertex(i, sub); ++offset; } auto random_edges = [&](SubGraph& g) { uniform_int<typename SubGraph::vertex_descriptor> v(0, num_vertices(g) -1); for (size_t i = 1; i < 4; ++i) add_edge(v(prng), v(prng), g); }; for (auto& sub : make_iterator_range(randomized.children())) random_edges(sub); random_edges(randomized); // setting some graph viz attributes get_property(randomized, graph_name) = "G0"; offset = 0; for (auto& sub : make_iterator_range(randomized.children())) { ++offset; get_property(sub, graph_name) = "cluster" + std::to_string(offset); get_property(sub, graph_graph_attribute)["label"] = "G" + std::to_string(offset); } return randomized; } template <typename SubGraph> SubGraph create_data() { enum { A,B,C,D,E,F,N }; // main edges SubGraph main(N); SubGraph& sub1 = main.create_subgraph(); SubGraph& sub2 = main.create_subgraph(); auto A1 = add_vertex(A, sub1); auto B1 = add_vertex(B, sub1); auto E2 = add_vertex(E, sub2); auto C2 = add_vertex(C, sub2); auto F2 = add_vertex(F, sub2); add_edge(A1, B1, sub1); add_edge(E2, F2, sub2); add_edge(C2, F2, sub2); add_edge(E, B, main); add_edge(B, C, main); add_edge(B, D, main); add_edge(F, D, main); // setting some graph viz attributes get_property(main, graph_name) = "G0"; get_property(sub1, graph_name) = "clusterG1"; get_property(sub2, graph_name) = "clusterG2"; get_property(sub1, graph_graph_attribute)["label"] = "G1"; /*extra*/get_property(sub1, graph_vertex_attribute)["shape"] = "Mrecord"; get_property(sub2, graph_graph_attribute)["label"] = "G2"; /*extra*/get_property(sub1, graph_vertex_attribute)["color"] = "red"; /*extra*/get_property(sub2, graph_graph_attribute)["fillcolor"] = "lightgray"; /*extra*/get_property(sub2, graph_graph_attribute)["style"] = "filled"; /*extra*/get_property(sub2, graph_vertex_attribute)["shape"] = "circle"; return main; } using GraphvizAttributes = std::map<std::string, std::string>; using Graph = adjacency_list<vecS, vecS, directedS, property<vertex_attribute_t, GraphvizAttributes>, property<edge_index_t, int, property<edge_attribute_t, GraphvizAttributes> >, property<graph_name_t, std::string, property<graph_graph_attribute_t, GraphvizAttributes, property<graph_vertex_attribute_t, GraphvizAttributes, property<graph_edge_attribute_t, GraphvizAttributes> > > > >; int main() { #ifdef GENERATE_RANDOM_GRAPHS write_graphviz(std::cout, generate_random<subgraph<Graph> >()); #else char names[] = {"ABCDEFGH"}; write_graphviz(std::cout, create_data<subgraph<Graph> >(), make_iterator_vertex_map(names)); #endif }
[ "remi.cohen-scali@nagra.com" ]
remi.cohen-scali@nagra.com
fd047e69a116ec13b13f27d966985ad02136076d
58a84aa609537561c1c06828efc273c59cd9ace5
/5.Arduino IDE course/4.Breathing light/Breathing_light/Breathing_light.ino
ac3e5c4f660f178961dd39b5c0674a8447261f34
[]
no_license
YahboomTechnology/Omibox-Robot
b66afab6f8e881938cf94955f0f5177aa8feb763
80c508e1109e41f2fcc517613c8c337a78a720c3
refs/heads/master
2021-06-27T04:39:26.593311
2021-04-12T04:28:01
2021-04-12T04:28:01
206,752,390
3
2
null
null
null
null
UTF-8
C++
false
false
1,500
ino
/* * @par Copyright (C): 2010-2019, Shenzhen Yahboom Tech * @file Breathing_light.c * @author xiaozhen * @version V1.0 * @date 2018.10.19 * @brief Breathing_ligh * @details * @par History * */ #include <Adafruit_NeoPixel.h> //Library file #define PIN 5 //Define the pins of the RGB lamp #define MAX_LED 8 //8 RGB lights in the robot car Adafruit_NeoPixel strip = Adafruit_NeoPixel( MAX_LED, PIN, NEO_RGB + NEO_KHZ800 ); uint8_t brightness = 0; //Brightness of RGB light uint8_t fadeAmount = 1; //Increment in brightness change uint8_t i=0; //"i" indicates the serial number of the RGB lamp /*Initialization settings*/ void setup() { strip.begin(); strip.show(); pinMode(4,OUTPUT); digitalWrite(4,0); //Pin 4 is the pin of the color recognition sensor searchlight /* In order to reduce the load of the power supply, * we initialize the searchlight of the color recognition sensor when it is initialized * (this is not necessary when the color recognition sensor is used) */ } /*Main function*/ void loop() { for(i=0;i<MAX_LED;i++) { strip.setPixelColor(i, brightness, 0, 0); //All RGB light is green strip.show(); } brightness = brightness + fadeAmount; if (brightness <= 0 || brightness >=100) //The brightness of RGB lamps varies from 1 to 100. fadeAmount = -fadeAmount ; delay(20); }
[ "2448532184@qq.com" ]
2448532184@qq.com
3d15b4a56d4d240b26053972135e110a0fdc84d1
09b3c2e3ca8ef51c0d66d7ecc18009d31e5e38b1
/path_manager.cpp
6cb7a252e5b49778c69a55e1d498f17167aa406d
[]
no_license
alisomay/wavecrush
ae8b0922ea4ce7d0f14124c0366297f0e91095b1
683cfbf5843405a697a8d2b917d45287e03e582d
refs/heads/master
2020-05-04T04:47:39.669489
2019-04-05T11:23:51
2019-04-05T11:23:51
178,974,095
0
0
null
null
null
null
UTF-8
C++
false
false
420
cpp
#include "path_manager.hpp" fs::path Path_Manager::get_in_path(){ return in_path; }; fs::path Path_Manager::get_crushed_path(){ return crushed_path; }; fs::path Path_Manager::set_crushed_path(std::string path){ crushed_path = path; return crushed_path; }; fs::path Path_Manager::set_crushed_path(char* path){ crushed_path = path; return crushed_path; };
[ "alisomay@gmail.com" ]
alisomay@gmail.com
4459c3924aa52bf8be8a7ee1c19bb9f0fe1e8b32
5c9eb0c093d36ece2cc158cb5020ea46177f67e4
/CPP04/ex03/Character.cpp
a354d66a0b2f49d418cb44414767474e8a98dad1
[]
no_license
cquiana/CPP_pisc
651a082dfd05415aa801cab791bea651010ddf30
96cf6a74076af7389e860c9ee1284abb9770a1f4
refs/heads/master
2023-03-14T20:57:38.045063
2021-03-30T10:39:49
2021-03-30T10:39:49
345,763,811
0
0
null
null
null
null
UTF-8
C++
false
false
2,552
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cquiana <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/22 14:26:22 by cquiana #+# #+# */ /* Updated: 2021/03/22 17:50:29 by cquiana ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" Character::Character() : _name("Noname") { for (int i = 0; i < 4; i++) _bag[i] = 0; } Character::~Character() { for (int i = 0; i < 4; i++) { if (_bag[i]) delete _bag[i]; _bag[i] = 0; } } Character::Character(std::string const &name) : _name(name) { for (int i = 0; i < 4; i++) _bag[i] = 0; } Character::Character(Character const &old) { *this = old; } Character &Character::operator=(Character const &old) { if (this != &old) { for (int i = 0; i < 4; i++) { if (_bag[i]) delete _bag[i]; } for (int i = 0; i < 4; i++) { _bag[i] = old._bag[i]->clone(); } _name = old._name; } return (*this); } std::string const &Character::getName() const { return (_name); } void Character::equip(AMateria* m) { if (m == 0) return; for (int i = 0; i < 4; i++) { if (_bag[i] == 0) { _bag[i] = m; std::cout << "New materia " << m->getType() << " in bag!" << std::endl; return; } } std::cout << "Bag is full!" << std::endl; } void Character::unequip(int idx) { if (idx < 0 || idx > 3) { std::cout << "Wrong index #" << idx << std::endl; return; } if (_bag[idx] == 0) { std::cout << "Materia with index " << idx << " already not in bag!" << std::endl; return; } if (_bag[idx] != 0) { _bag[idx] = 0; std::cout << "Materia with index " << idx << " unequiped!" << std::endl; } } void Character::use(int idx, ICharacter& target) { if (idx < 0 || idx > 3) { std::cout << "Wrong index #" << idx << std::endl; return; } if (_bag[idx] != 0) _bag[idx]->use(target); else std::cout << "Materia with index " << idx << " not found in bag!" << std::endl; }
[ "atulyakov@gmail.com" ]
atulyakov@gmail.com
20b861638c51910208ca64eab4bafcc7739ebd15
3c5c1e3836edf3e9627a64600785503d1814df51
/build/Android/Debug/app/src/main/include/OpenGL.GLFramebufferStatus.h
d98b60427b541b48d74bb30184dd4a7a00d0cd8c
[]
no_license
fypwyt/wytcarpool
70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4
4fbdeedf261ee8ecd563260816991741ec701432
refs/heads/master
2021-09-08T10:32:17.612628
2018-03-09T05:24:54
2018-03-09T05:24:54
124,490,692
0
0
null
null
null
null
UTF-8
C++
false
false
366
h
// This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/UnoCore/1.6.0/Source/OpenGL/GLEnums.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace OpenGL{ // public extern enum GLFramebufferStatus :271 uEnumType* GLFramebufferStatus_typeof(); }} // ::g::OpenGL
[ "s1141120@studentdmn.ouhk.edu.hk" ]
s1141120@studentdmn.ouhk.edu.hk
abb4392d0f6d3c0cd9d4b5ce0c49ca820b4b49b5
191126328427ffb1d2cebcc5d3ccb670a7f4f8be
/brazilicpc1.cpp
990b3cb87c02526120c1559a6506d113548d8574
[]
no_license
drviruses/CP
090ca7db998f7f113d85ab96a91a73fd9d5892ac
69294c62218fda3453daf4b69251ab98bb24cccb
refs/heads/master
2023-03-14T06:09:15.174975
2021-03-01T05:04:26
2021-03-01T05:04:26
305,608,273
1
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
#include<bits/stdc++.h> #define ll long long #define ld long double using namespace std; int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll n,sum=0,val; cin>>n; while (n--) { cin>>val; if(val==2 || val==3) sum+=1; /* code */ } cout<<sum; return 0; }
[ "amitkumarhero28@gmail.com" ]
amitkumarhero28@gmail.com
43fd11ab3c6ef8a01662fe0bc387499ad5c67584
957038eaa58a9e05aa0b0d62cbe91361a181c299
/playerDeMusica/Origem.cpp
c559a376ef6a0a5e1cf40c637caddd9fb0253f24
[ "MIT" ]
permissive
antonioagontijo/PlayerDeMusica
ee62c9c396ffa7674a2beef2c6ccde928bb31079
b5be0baea22bcfadb43908e85ae738434fc5a1a4
refs/heads/main
2023-02-11T21:16:57.808926
2021-01-19T22:42:59
2021-01-19T22:42:59
331,126,958
0
0
null
null
null
null
ISO-8859-1
C++
false
false
10,892
cpp
#include <stdlib.h> #include <stdio.h> #include <string.h>//necessário para o strcpy #include <locale.h>//biblioteca que permite o uso de acentuação #include <time.h>//biblioteca de tempo, usada para gerar números aleatórios #define TAMANHO 100 //definir tamanho dos vetores #define LIMITE 1000 //definir tamanho dos códigos que serão gerados para as músicas struct dadoDaMusica {//criação de struct char nomeMusica[TAMANHO]; char nomeAlbum[TAMANHO]; char nomeArtista[TAMANHO]; char genero[TAMANHO]; int ano, code; float duracao; dadoDaMusica* prox; } *Head; //escopo das variaveis void inserirMusica(char nome[TAMANHO], char album[TAMANHO], char artista[TAMANHO], char genero[TAMANHO], int ano, float duracao, int code); int menu(); void Listar(); int removerMusica(int nome); int geraCodigo(int guardaCodigo[], int limite, int cont); bool existe(int valores[], int tam, int valor); dadoDaMusica* busca(int ID); int main() { setlocale(LC_ALL, "portuguese");//código para habilitar a acentuação. float aux_duracao;//variáveis com 'aux' são usadas para receber os dados informados pelo usuário, para posteriormente serem armazenadas na lista int op, aux_ano, c, excluir, aux_code, cont = 0, guardaCodigo[1000], conf; //'op' usado pelo menu, 'c' usado para limpeza do buffer do teclado, //'excluir' usado para armazenar o valor que o usuário informar, e que será usa pela função de remover. //a variável 'cont' e o vetor 'guardaCodigo' são usadas pela função de criar números aleatórios. //E a variável 'conf' é usado pelo while de confirmação de exclusão da musica char aux_nomeMusica[TAMANHO], aux_nomeAlbum[TAMANHO], aux_nomeArtista[TAMANHO], aux_genero[TAMANHO]; dadoDaMusica* ElementoBusca; ElementoBusca = (dadoDaMusica*)malloc(sizeof(dadoDaMusica)); while (1) { op = menu(); switch (op) { case 1://INSERÇÃO DE DADOS printf("Digite o nome da música:\n"); gets_s(aux_nomeMusica); system("Cls"); printf("Digite o nome do álbum:\n"); gets_s(aux_nomeAlbum); system("Cls"); printf("Digite o nome do artista:\n"); gets_s(aux_nomeArtista); system("Cls"); printf("Informe o gênero:\n"); gets_s(aux_genero); system("Cls"); printf("Digite o ano:\n"); scanf_s("%d", &aux_ano); system("Cls"); printf("Digite a duração da música:\n"); scanf_s("%f", &aux_duracao); while ((c = getchar()) != '\n' && c != EOF) {} //limpeza do buffer do teclado. aux_code = geraCodigo(guardaCodigo, LIMITE, cont);//chamada da função que gera códigos de identificação para cada música inserirMusica(aux_nomeMusica, aux_nomeAlbum, aux_nomeArtista, aux_genero, aux_ano, aux_duracao, aux_code);// Chamada da função que salva os dados na lista break; case 2://LISTAR TODAS AS MUSICAS Listar(); break; case 3://BUSCAR MUSICA printf("Digite o ID da música: "); scanf_s("%d", &aux_code); while ((c = getchar()) != '\n' && c != EOF) {} ElementoBusca = busca(aux_code);//chamada da função de busca, ela retorna o valor que foi buscado, e os dados são exibidos na tela para o usuário nas linha abaixo if (ElementoBusca != 0) { system("Cls"); printf("--------MÚSICA--------\n"); printf("%s\n", ElementoBusca->nomeMusica); printf("Álbum: %s\n", ElementoBusca->nomeAlbum); printf("Artista: %s\n", ElementoBusca->nomeArtista); printf("Gênero: %s\n", ElementoBusca->genero); printf("Ano: %d\n", ElementoBusca->ano); printf("Duração: %0.2fmin\n", ElementoBusca->duracao); printf("ID: %d\n", ElementoBusca->code); printf("----------------------\n"); } else { system("Cls");//caso a musica não seja encontrada printf("---------OPS!---------\n"); printf("Música não encontrada.\n"); printf("----------------------\n"); } system("pause"); break; case 4://REMOVE MUSICA int res; /*No parte de remoção, primeiramente reutilizei a função de busca para exibir na tela o nome da música, e uma pergunta de confirmação se o usuário realmente deseja remover a música. Se sim, chama a função de remoção, se não, retorna para tela inicial.*/ printf("--------REMOVER-------\n"); printf("Digite o ID da música:"); scanf_s("%d", &excluir); while ((c = getchar()) != '\n' && c != EOF) {} ElementoBusca = busca(excluir); if (ElementoBusca != 0) { conf = 0; while (conf < 1 || conf > 2)//While para garantir que o usuário digite umas das opções pedidas { system("Cls"); printf("--------MÚSICA--------\n"); printf("\"%s\"\n", ElementoBusca->nomeMusica); printf("Deseja mesmo excluir?\n"); printf("[1]SIM\n"); printf("[2]NÂO\n"); printf("----------------------\n"); scanf_s("%d", &conf); while ((c = getchar()) != '\n' && c != EOF) {} } if (conf == 1) { res = removerMusica(excluir); //mensagem de confirmação de remoção system("Cls"); printf("----SUCESSO!----\n"); printf("Música removida.\n"); printf("----------------\n"); } else break; } else {//caso a música não seja encontrada system("Cls"); printf("---------OPS!---------\n"); printf("Música não encontrada.\n"); printf("----------------------\n"); } system("pause"); break; case 5://SAIR return 0;//encerra o programa default: //mensagem que pede para o usuário digitar apenas uma das opções informadas system("Cls"); printf("---------------INVÁLIDO--------------\nFavor digitar um dos valor informados\n-------------------------------------\n"); system("pause"); } } system("pause"); return 0; }//FIM DA MAIN int menu() //FUNÇÃO MENU { int op, c; system("Cls"); printf("---------------MENU---------------\n"); printf("[1]Adicionar uma música à playlist\n"); printf("[2]Exibir playlist\n"); printf("[3]Buscar música\n"); printf("[4]Remover música\n"); printf("[5]Sair\n"); printf("Digite sua escolha: "); printf("\n----------------------------------\n"); scanf_s("%d", &op); while ((c = getchar()) != '\n' && c != EOF) {} system("Cls"); return op; } //FUNÇÃO DE INSERÇÃO void inserirMusica(char nome[TAMANHO], char album[TAMANHO], char artista[TAMANHO], char genero[TAMANHO], int ano, float duracao, int code) //Recebe como parâmetro todos os dados das músicas informados pelo usuário, e salvos temporariamente nas variáveis com 'aux' { dadoDaMusica* NovoElemento; NovoElemento = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); dadoDaMusica* ElementoVarredura; ElementoVarredura = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); //aqui os dados que foram passados pelo usuário, são armazenados na struct NovoElemento->ano = ano; NovoElemento->duracao = duracao; NovoElemento->code = code; strcpy_s(NovoElemento->nomeMusica, nome); strcpy_s(NovoElemento->nomeAlbum, album); strcpy_s(NovoElemento->nomeArtista, artista); strcpy_s(NovoElemento->genero, genero); if (Head == NULL) { Head = NovoElemento; Head->prox = NULL; } else { ElementoVarredura = Head; while (ElementoVarredura->prox != NULL) ElementoVarredura = ElementoVarredura->prox; ElementoVarredura->prox = NovoElemento; NovoElemento->prox = NULL; } } /*As funções de remoções e de busca utilizam um código de identificação para fazer as buscas. Esse código é único e é gerado e atrelado em cada música automaticamente, toda vez que o usuário insere uma música nova*/ //FUNÇÃO DE REMOÇÃO int removerMusica(int ID) //Recebe como parâmetro o valor salvo na variável excluir, { dadoDaMusica* ElementoVarredura; ElementoVarredura = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); dadoDaMusica* Anterior; Anterior = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); ElementoVarredura = Head; while (ElementoVarredura != NULL) { if (ElementoVarredura->code == ID) { if (ElementoVarredura == Head) { Head = ElementoVarredura->prox; free(ElementoVarredura); return 1; } else { Anterior->prox = ElementoVarredura->prox; free(ElementoVarredura); return 1; } } else { Anterior = ElementoVarredura; ElementoVarredura = ElementoVarredura->prox; } } return 0; } void Listar()//FUNÇÃO DE LISTAGEM { dadoDaMusica* ElementoVarredura; ElementoVarredura = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); ElementoVarredura = Head; if (ElementoVarredura == NULL) { //caso o usuário tente listar as músicas, mas a lista estiver vazia, essa mensagem será exibida. system("Cls"); printf("--------------LISTA VAZIA!--------------\n"); printf("Ainda não foi adicionado nenhuma música.\n"); printf("----------------------------------------\n"); system("pause"); return; } printf("---------------Playlist---------------\n"); printf("(Para ver as informações completas de \n"); printf("cada música, utilize a opção de BUSCA)\n"); printf("--------------------------------------\n"); while (ElementoVarredura != NULL) { printf("\"%s\" - %s\n", ElementoVarredura->nomeMusica, ElementoVarredura->nomeArtista); printf("ID: %d\n\n", ElementoVarredura->code); ElementoVarredura = ElementoVarredura->prox; } printf("--------------------------------------\n"); system("pause"); return; } //FUNÇÃO QUE GERA O CÓDIGOS ALETATÓRIOS int geraCodigo(int numeros[], int limite, int cont) //Recebe como parâmetro o vetor 'gardaCodigo', para guarda os código que foram gerados pela função, recebe também um valor limite dos números que podem ser gerados, //e um contador para acessar os espaços do vetor { srand(time(NULL)); int v;//armazena temporariamente o número gerado v = rand() % limite;// gerador valores aleatória com base no relógio do sistema while (existe(numeros, cont, v)) { v = rand() % limite; } numeros[cont] = v; return numeros[cont]; cont++; } //FUNÇÃO DE CHECAGEM bool existe(int valores[], int tam, int valor) //Recebe como parâmetro, o vetor 'guardaCodigo', o valor salvo na variável contador, e o valor salvo na variável 'v' que contém o número gerado em 'geraCodigo()' //Essa função checa se o código que foi gerado aleatoriamente já existe ou não, //e assim garantir que cada música tem um número de identificação único. { for (int i = 0; i < tam; i++) { if (valores[i] == valor) return true; }return false; } //FUNÇÃO DE BUSCA dadoDaMusica* busca(int ID) //Recebe como parâmetro o valor salvo na variável aux_code, que são os códigos de identificação de cada musica { dadoDaMusica* ElementoVarredura; ElementoVarredura = (struct dadoDaMusica*)malloc(sizeof(struct dadoDaMusica)); ElementoVarredura = Head; while (ElementoVarredura != NULL) { if (ElementoVarredura->code == ID) return ElementoVarredura; else ElementoVarredura = ElementoVarredura->prox; } return 0; }
[ "antonioasgontijo@outlook.com" ]
antonioasgontijo@outlook.com
cdf8b24e6b8d373ab9fde78efb0b91245d812ce3
809bbbddf5f4abdf8f85a6591df61fcf11f52ce0
/06_04_engine/src/libs/libserver/regist_to_factory.h
65a47cbea758147078ad9edeed532ddcb209f73e
[ "MIT" ]
permissive
KMUS1997/GameBookServer
542df52ac3f7cb1443584394e3d8033dbb2d29e3
6f32333cf464088a155f0637f188acd452b631b7
refs/heads/master
2023-03-15T18:52:23.253198
2020-06-09T01:58:36
2020-06-09T01:58:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
417
h
#pragma once #include <typeinfo> #include "component_factory.h" #include "object_pool.h" template<typename T, typename...Targs> class RegistToFactory { public: RegistToFactory() { ComponentFactory<Targs...>::GetInstance()->Regist(typeid(T).name(), CreateComponent); } static T* CreateComponent(Targs... args) { return DynamicObjectPool<T>::GetInstance()->MallocObject(std::forward<Targs>(args)...); } };
[ "setup_pf@hotmail.com" ]
setup_pf@hotmail.com
c6b3c68c164c14240509009b22f4723de0cda9f3
05086f53556fe759e28f94f58a608136072fd884
/FileTypeData/Prog_Data_train/cpp/InputClass.cpp
cf8a730a82b8bb0394a19b021785370701203999
[]
no_license
P79N6A/tensorflow-language-classification
969597f50738638bc5d017c951a5911089337d02
94cd65f84db6b02dbafac887f32077eeff16d8ad
refs/heads/master
2020-04-24T21:18:19.406205
2019-02-23T20:08:00
2019-02-23T20:08:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
#include "InputClass.h" InputClass::InputClass() { } InputClass::~InputClass() { } void InputClass::Initialize() { for (int i = 0; i < 256; i++) { keys[i] = false; } } void InputClass::KeyDown(unsigned int input) { keys[input] = true; } void InputClass::KeyUp(unsigned int input) { keys[input] = false; } bool InputClass::IsKeyDown(unsigned int key) { return keys[key]; }
[ "the.rahul.pal@gmail.com" ]
the.rahul.pal@gmail.com
45cbcb3858500e51c9e3bf687bcdd1739885c3a0
f112f9745d7c916c68ee2b8ec05e93e74d7d3004
/vod/include/tencentcloud/vod/v20180717/model/MediaSourceData.h
76bb9d7d2363f487fd5102f8a2d3747aa7d282ea
[ "Apache-2.0" ]
permissive
datalliance88/tencentcloud-sdk-cpp
d5ca9454e2692ac21a08394bf7a4ba98982640da
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
refs/heads/master
2020-09-04T20:59:42.950346
2019-11-18T07:40:56
2019-11-18T07:40:56
219,890,597
0
0
Apache-2.0
2019-11-06T02:02:01
2019-11-06T02:02:00
null
UTF-8
C++
false
false
5,785
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_VOD_V20180717_MODEL_MEDIASOURCEDATA_H_ #define TENCENTCLOUD_VOD_V20180717_MODEL_MEDIASOURCEDATA_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Vod { namespace V20180717 { namespace Model { /** * 来源文件信息 */ class MediaSourceData : public AbstractModel { public: MediaSourceData(); ~MediaSourceData() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取媒体文件的来源类别: <li>Record:来自录制。如直播录制、直播时移录制等。</li> <li>Upload:来自上传。如拉取上传、服务端上传、客户端 UGC 上传等。</li> <li>VideoProcessing:来自视频处理。如视频拼接、视频剪辑等。</li> <li>Unknown:未知来源。</li> 注意:此字段可能返回 null,表示取不到有效值。 * @return SourceType 媒体文件的来源类别: <li>Record:来自录制。如直播录制、直播时移录制等。</li> <li>Upload:来自上传。如拉取上传、服务端上传、客户端 UGC 上传等。</li> <li>VideoProcessing:来自视频处理。如视频拼接、视频剪辑等。</li> <li>Unknown:未知来源。</li> 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetSourceType() const; /** * 设置媒体文件的来源类别: <li>Record:来自录制。如直播录制、直播时移录制等。</li> <li>Upload:来自上传。如拉取上传、服务端上传、客户端 UGC 上传等。</li> <li>VideoProcessing:来自视频处理。如视频拼接、视频剪辑等。</li> <li>Unknown:未知来源。</li> 注意:此字段可能返回 null,表示取不到有效值。 * @param SourceType 媒体文件的来源类别: <li>Record:来自录制。如直播录制、直播时移录制等。</li> <li>Upload:来自上传。如拉取上传、服务端上传、客户端 UGC 上传等。</li> <li>VideoProcessing:来自视频处理。如视频拼接、视频剪辑等。</li> <li>Unknown:未知来源。</li> 注意:此字段可能返回 null,表示取不到有效值。 */ void SetSourceType(const std::string& _sourceType); /** * 判断参数 SourceType 是否已赋值 * @return SourceType 是否已赋值 */ bool SourceTypeHasBeenSet() const; /** * 获取用户创建文件时透传的字段 注意:此字段可能返回 null,表示取不到有效值。 * @return SourceContext 用户创建文件时透传的字段 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetSourceContext() const; /** * 设置用户创建文件时透传的字段 注意:此字段可能返回 null,表示取不到有效值。 * @param SourceContext 用户创建文件时透传的字段 注意:此字段可能返回 null,表示取不到有效值。 */ void SetSourceContext(const std::string& _sourceContext); /** * 判断参数 SourceContext 是否已赋值 * @return SourceContext 是否已赋值 */ bool SourceContextHasBeenSet() const; private: /** * 媒体文件的来源类别: <li>Record:来自录制。如直播录制、直播时移录制等。</li> <li>Upload:来自上传。如拉取上传、服务端上传、客户端 UGC 上传等。</li> <li>VideoProcessing:来自视频处理。如视频拼接、视频剪辑等。</li> <li>Unknown:未知来源。</li> 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_sourceType; bool m_sourceTypeHasBeenSet; /** * 用户创建文件时透传的字段 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_sourceContext; bool m_sourceContextHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_VOD_V20180717_MODEL_MEDIASOURCEDATA_H_
[ "jimmyzhuang@tencent.com" ]
jimmyzhuang@tencent.com