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 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
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 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2fcb85b902726b94e9c45453433b40ae19645729
|
e933cbc6697a5ff43988ce206ea7d66d9688dd62
|
/build-102022111_final_project_angry_jump-Desktop_Qt_5_4_1_MinGW_32bit-Debug/debug/moc_thank_you.cpp
|
f46acd9162551cd6ea74d5bcbd72ab7da6fd0532
|
[
"Apache-2.0"
] |
permissive
|
zelzhang/qt-game-project-angry-jump
|
c4bf75b3727363928baa96d17061b73e19801d12
|
9a029baa797c5a033e6e67a7eeef48b0b9bdc223
|
refs/heads/master
| 2021-01-21T02:11:28.655964
| 2016-06-08T15:41:39
| 2016-06-08T15:41:39
| 60,707,779
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,594
|
cpp
|
/****************************************************************************
** Meta object code from reading C++ file 'thank_you.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../thank_you.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'thank_you.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.1. 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
struct qt_meta_stringdata_THANK_YOU_t {
QByteArrayData data[1];
char stringdata[10];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_THANK_YOU_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_THANK_YOU_t qt_meta_stringdata_THANK_YOU = {
{
QT_MOC_LITERAL(0, 0, 9) // "THANK_YOU"
},
"THANK_YOU"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_THANK_YOU[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void THANK_YOU::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject THANK_YOU::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_THANK_YOU.data,
qt_meta_data_THANK_YOU, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *THANK_YOU::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *THANK_YOU::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_THANK_YOU.stringdata))
return static_cast<void*>(const_cast< THANK_YOU*>(this));
return QWidget::qt_metacast(_clname);
}
int THANK_YOU::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
|
[
"chaomin.ryan@gmail.com"
] |
chaomin.ryan@gmail.com
|
7259b6751fe2ae1d3ca9d9f4b3fd311629a88a0a
|
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
|
/app/src/main/cpp/dir521/dir3871/dir5864/dir6285/dir6632/file7235.cpp
|
6c8170267516a44fe33109ab09144727e441c272
|
[] |
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
| 111
|
cpp
|
#ifndef file7235
#error "macro file7235 must be defined"
#endif
static const char* file7235String = "file7235";
|
[
"tgeng@google.com"
] |
tgeng@google.com
|
66488fec2528a710940126ee1e9037eedef09c57
|
44f47684236454cf7bb0bb15f27ceaae22022b40
|
/gklib/otd_proto_medium.cpp
|
1f34b5cb8bedd1f38ace278afa8f0cdf204eff8a
|
[] |
no_license
|
icprog/cpc152
|
4313b4714b124682ef335d7d6e2619ea1d727ae1
|
b6a4063c044349e438f77491d4f600d2046069ab
|
refs/heads/master
| 2020-04-04T15:46:13.041474
| 2018-08-29T15:47:02
| 2018-08-29T15:47:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,178
|
cpp
|
#ifdef __WIN32__
#include <ke_defs.h>
#include <otd_addr.h>
#include <otdm_proto.h>
#else
#include <gklib/otdm_proto.h>
#endif
union multi_ptr
{
LPVOID v_ptr;
LPBYTE b_ptr;
LPWORD w_ptr;
LPDWORD dw_ptr;
float * float_ptr;
__int64 * int64_ptr;
lpotd_param_addr addr_ptr;
};
DWORD WINAPI otdm_pack_record(LPVOID buff,DWORD bsz,DWORD mask, LPMDB_RECORD rec)
{
DWORD ret = 0;
if(rec && bsz>=sizeof(*rec))
{
multi_ptr ptr;
ptr.v_ptr = buff;
*ptr.dw_ptr = rec->rec_id;
++ptr.dw_ptr;
ret+=sizeof(DWORD);
if(!(mask & MDBR_RECORD_REMOVED))
{
if(mask & MDBR_FIELD_VALUE)
{
*ptr.float_ptr = rec->value ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_DIAG)
{
*ptr.w_ptr = rec->diag ;
++ptr.w_ptr ;
ret+=sizeof(*ptr.w_ptr);
}
if(mask & MDBR_FIELD_STATE)
{
*ptr.w_ptr = rec->state ;
++ptr.w_ptr ;
ret+=sizeof(*ptr.w_ptr);
}
if(mask & MDBR_FIELD_TIME)
{
*ptr.int64_ptr = rec->time ;
++ptr.int64_ptr;
ret+=sizeof(*ptr.int64_ptr);
}
if(mask & MDBR_FIELD_KVANTS)
{
*ptr.dw_ptr = rec->kvants ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_MIN_VALUE)
{
*ptr.float_ptr = rec->min_value ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_VALUE)
{
*ptr.float_ptr = rec->max_value ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_NAME)
{
*ptr.dw_ptr = rec->name;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_SNAME)
{
*ptr.dw_ptr = rec->sname;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_MIN_DANGER)
{
*ptr.float_ptr = rec->min_danger;
++ptr.float_ptr;
ret+=(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_DANGER)
{
*ptr.float_ptr = rec->max_danger;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MIN_ALARM)
{
*ptr.float_ptr = rec->min_alarm;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_ALARM)
{
*ptr.float_ptr = rec->max_alarm;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_ADDR)
{
*ptr.addr_ptr = rec->addr;
++ptr.addr_ptr ;
ret+=sizeof(*ptr.addr_ptr);
}
if(mask & MDBR_FIELD_OTDVALUE)
{
*ptr.dw_ptr = rec->otd_val;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_OTDPD)
{
*ptr.dw_ptr = rec->otd_pd;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_OPTIONS)
{
*ptr.dw_ptr = rec->options;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_SCALEID)
{
*ptr.dw_ptr = rec->scale_id;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_PERCENT)
{
*ptr.dw_ptr = rec->percent;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_LASTVALUE)
{
*ptr.float_ptr = rec->last_value;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
*ptr.int64_ptr = rec->last_time;
++ptr.int64_ptr ;
ret+=sizeof(*ptr.int64_ptr);
}
if(mask & MDBR_FIELD_SECURITY)
{
*ptr.dw_ptr = rec->security;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
}
}
return ret;
}
DWORD WINAPI otdm_unpack_record(LPVOID buff,DWORD bsz,DWORD mask, LPMDB_RECORD rec)
{
DWORD ret = 0;
if(rec)
{
multi_ptr ptr;
ptr.v_ptr = buff;
rec->rec_id = *ptr.dw_ptr ;
++ptr.dw_ptr;
ret+=sizeof(DWORD);
if(!(mask & MDBR_RECORD_REMOVED))
{
if(mask & MDBR_FIELD_VALUE)
{
rec->value = *ptr.float_ptr ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_DIAG)
{
rec->diag = *ptr.w_ptr ;
++ptr.w_ptr ;
ret+=sizeof(*ptr.w_ptr);
}
if(mask & MDBR_FIELD_STATE)
{
rec->state = *ptr.w_ptr ;
++ptr.w_ptr ;
ret+=sizeof(*ptr.w_ptr);
}
if(mask & MDBR_FIELD_TIME)
{
rec->time = *ptr.int64_ptr ;
++ptr.int64_ptr;
ret+=sizeof(*ptr.int64_ptr);
}
if(mask & MDBR_FIELD_KVANTS)
{
rec->kvants = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_MIN_VALUE)
{
rec->min_value =*ptr.float_ptr ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_VALUE)
{
rec->max_value = *ptr.float_ptr ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_NAME)
{
rec->name = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_SNAME)
{
rec->sname = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_MIN_DANGER)
{
rec->min_danger = *ptr.float_ptr ;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_DANGER)
{
rec->max_danger = *ptr.float_ptr ;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MIN_ALARM)
{
rec->min_alarm = *ptr.float_ptr ;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_MAX_ALARM)
{
rec->max_alarm = *ptr.float_ptr ;
++ptr.float_ptr;
ret+=sizeof(*ptr.float_ptr);
}
if(mask & MDBR_FIELD_ADDR)
{
rec->addr = *ptr.addr_ptr ;
++ptr.addr_ptr ;
ret+=sizeof(*ptr.addr_ptr);
}
if(mask & MDBR_FIELD_OTDVALUE)
{
rec->otd_val = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_OTDPD)
{
rec->otd_pd = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_OPTIONS)
{
rec->options = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_SCALEID)
{
rec->scale_id = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_PERCENT)
{
rec->percent = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask & MDBR_FIELD_LASTVALUE)
{
rec->last_value = *ptr.float_ptr ;
++ptr.float_ptr ;
ret+=sizeof(*ptr.float_ptr);
rec->last_time = *ptr.int64_ptr ;
++ptr.int64_ptr ;
ret+=sizeof(*ptr.int64_ptr);
}
if(mask & MDBR_FIELD_SECURITY)
{
rec->security = *ptr.dw_ptr ;
++ptr.dw_ptr ;
ret+=sizeof(*ptr.dw_ptr);
}
}
}
return ret;
}
DWORD WINAPI _otdm_pack_kadr(LPVOID data,DWORD data_size,DWORD mask,LPMDB_KADR kadr,bool unpack )
{
DWORD ret = 0;
multi_ptr ptr;
ptr.v_ptr = data;
if(unpack) kadr->kadr_id = *ptr.dw_ptr;
else *ptr.dw_ptr = kadr->kadr_id;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
if(mask&MDB_KADR_FIELD_DIAG )
{
if(unpack)
kadr->kadr_diag = *ptr.w_ptr;
else
*ptr.w_ptr = kadr->kadr_diag ;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_STATE )
{
if(unpack) kadr->kadr_state = *ptr.w_ptr;
else *ptr.w_ptr = kadr->kadr_state;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_CHANGES )
{
if(unpack) kadr->kadr_changes = *ptr.w_ptr;
else *ptr.w_ptr = kadr->kadr_changes;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_DISCRETE_CHANGES )
{
if(unpack) kadr->discrete_changes = *ptr.w_ptr;
else *ptr.w_ptr = kadr->discrete_changes;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_ALARM_CHANGES )
{
if(unpack) kadr->alarm_changes = *ptr.w_ptr;
else *ptr.w_ptr = kadr->alarm_changes;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_ENTRY_COUNT )
{
if(unpack) kadr->entry_count = *ptr.w_ptr;
else *ptr.w_ptr = kadr->entry_count;
++ptr.w_ptr;
ret+=sizeof(*ptr.w_ptr);
}
if(mask&MDB_KADR_FIELD_NAME )
{
if(unpack) kadr->name_id = *ptr.dw_ptr;
else *ptr.dw_ptr = kadr->name_id;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask&MDB_KADR_FIELD_SNAME )
{
if(unpack) kadr->name_id = *ptr.dw_ptr;
else *ptr.dw_ptr = kadr->name_id;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask&MDB_KADR_FIELD_IMAGE )
{
if(unpack) kadr->image_id = *ptr.dw_ptr;
else *ptr.dw_ptr = kadr->image_id;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask&MDB_KADR_FIELD_FLAGS )
{
if(unpack) kadr->kadr_flags = *ptr.dw_ptr;
else *ptr.dw_ptr = kadr->kadr_flags;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask&MDB_KADR_FIELD_SIZE )
{
if(unpack)
{
kadr->kadr_size.cx = *ptr.dw_ptr;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
kadr->kadr_size.cy = *ptr.dw_ptr;
}
else
{
*ptr.dw_ptr = kadr->kadr_size.cx;
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
*ptr.dw_ptr = kadr->kadr_size.cy;
}
++ptr.dw_ptr;
ret+=sizeof(*ptr.dw_ptr);
}
if(mask&MDB_KADR_FIELD_TIMES )
{
if(unpack)
{
kadr->image_time = *ptr.int64_ptr;
++ptr.int64_ptr;
ret +=sizeof(*ptr.int64_ptr);
kadr->content_time = *ptr.int64_ptr;
}
else
{
*ptr.int64_ptr = kadr->image_time;
++ptr.int64_ptr;
ret +=sizeof(*ptr.int64_ptr);
*ptr.int64_ptr = kadr->content_time ;
}
++ptr.int64_ptr;
ret +=sizeof(*ptr.int64_ptr);
}
return ret;
}
DWORD WINAPI otdm_pack_kadr(LPVOID data,DWORD data_size,DWORD mask,LPMDB_KADR kadr )
{
return _otdm_pack_kadr(data,data_size,mask,kadr,false);
}
DWORD WINAPI otdm_unpack_kadr(LPVOID data,DWORD data_size,DWORD mask,LPMDB_KADR kadr )
{
return _otdm_pack_kadr(data,data_size,mask,kadr,true);
}
|
[
"dostap@debian"
] |
dostap@debian
|
18f136e6c8ab5061ffd2a1af5aaf946ebd36a2f1
|
94a1ae89fa4fac16b3d2a6c56ca678d6c8af668a
|
/include/ircd/fs/aio.h
|
033a2f7f69ae1945d02a52e2c6aaa0c201a88772
|
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
matrix-construct/construct
|
99d677d0c2254cac2176d80690bbfd02b18a8658
|
0624b69246878da592d3f5c2c3737ad0b5ff6277
|
refs/heads/master
| 2023-05-28T12:16:23.661446
| 2023-04-28T05:33:46
| 2023-05-01T19:45:37
| 147,328,703
| 356
| 41
|
NOASSERTION
| 2022-07-22T03:45:21
| 2018-09-04T10:26:23
|
C++
|
UTF-8
|
C++
| false
| false
| 3,289
|
h
|
// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2018 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_FS_AIO_H
// Public and unconditional interface for AIO. This file is part of the
// standard include stack and available whether or not this platform is Linux
// with AIO, and whether or not it's enabled, etc. If it is not most of this
// stuff does nothing and will have null values.
/// Asynchronous filesystem Input/Output
///
namespace ircd::fs::aio
{
struct init;
struct stats;
struct system;
struct request;
extern const size_t MAX_EVENTS;
extern const size_t MAX_REQPRIO;
extern conf::item<bool> enable;
extern conf::item<size_t> max_events;
extern conf::item<size_t> max_submit;
extern conf::item<bool> submit_coalesce;
extern struct stats stats;
extern struct system *system;
bool for_each_completed(const std::function<bool (const request &)> &);
bool for_each_queued(const std::function<bool (const request &)> &);
size_t count_queued(const op &);
}
/// Statistics structure.
///
struct ircd::fs::aio::stats
{
using item = ircd::stats::item<uint64_t *>;
uint64_t value[32];
size_t items;
item requests; ///< count of requests created
item complete; ///< count of requests completed
item submits; ///< count of io_submit calls
item chases; ///< count of chase calls
item handles; ///< count of event_fd callbacks
item events; ///< count of events from io_getevents
item cancel; ///< count of requests canceled
item errors; ///< count of response errcodes
item reads; ///< count of read complete
item writes; ///< count of write complete
item stalls; ///< count of io_submit's blocking.
item bytes_requests; ///< total bytes for requests created
item bytes_complete; ///< total bytes for requests completed
item bytes_errors; ///< total bytes for completed w/ errc
item bytes_cancel; ///< total bytes for cancels
item bytes_read; ///< total bytes for read completed
item bytes_write; ///< total bytes for write completed
item cur_bytes_write; ///< pending write bytes
item cur_reads; ///< pending reads
item cur_writes; ///< pending write
item cur_queued; ///< nr of requests in userspace queue
item cur_submits; ///< nr requests in flight with kernel
item max_requests; ///< maximum observed pending requests
item max_reads; ///< maximum observed pending reads
item max_writes; ///< maximum observed pending write
item max_queued; ///< maximum observed in queue.
item max_submits; ///< maximum observed in flight.
stats();
};
struct [[gnu::visibility("hidden")]]
ircd::fs::aio::init
{
static size_t query_max_events();
init();
~init() noexcept;
};
|
[
"jason@zemos.net"
] |
jason@zemos.net
|
06ee5020a38290f989557f50c2aaa30e32774ef5
|
df055d97526e69b8e455a19b99edf0fa7e73457f
|
/bin/engines/stockfish/stockfish-11-linux/stockfish-11-linux/src/endgame.h
|
4642e44857b4ac7500652941f57243ea736e5260
|
[
"GPL-3.0-only",
"MIT"
] |
permissive
|
coelho-faminto/chess-cheater
|
f2ae55f02f33fb67847f29bd7ae67aac290243fb
|
98b520a73f2d2b78079fdd1a2ca3e92b31947d82
|
refs/heads/master
| 2022-12-25T05:20:40.598916
| 2020-07-26T20:51:38
| 2020-07-26T20:51:38
| 281,398,122
| 0
| 0
|
MIT
| 2022-12-13T08:34:36
| 2020-07-21T12:56:38
|
C++
|
UTF-8
|
C++
| false
| false
| 3,601
|
h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2015-2020 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ENDGAME_H_INCLUDED
#define ENDGAME_H_INCLUDED
#include <unordered_map>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "position.h"
#include "types.h"
/// EndgameCode lists all supported endgame functions by corresponding codes
enum EndgameCode {
EVALUATION_FUNCTIONS,
KNNK, // KNN vs K
KNNKP, // KNN vs KP
KXK, // Generic "mate lone king" eval
KBNK, // KBN vs K
KPK, // KP vs K
KRKP, // KR vs KP
KRKB, // KR vs KB
KRKN, // KR vs KN
KQKP, // KQ vs KP
KQKR, // KQ vs KR
SCALING_FUNCTIONS,
KBPsK, // KB and pawns vs K
KQKRPs, // KQ vs KR and pawns
KRPKR, // KRP vs KR
KRPKB, // KRP vs KB
KRPPKRP, // KRPP vs KRP
KPsK, // K and pawns vs K
KBPKB, // KBP vs KB
KBPPKB, // KBPP vs KB
KBPKN, // KBP vs KN
KNPK, // KNP vs K
KNPKB, // KNP vs KB
KPKP // KP vs KP
};
/// Endgame functions can be of two types depending on whether they return a
/// Value or a ScaleFactor.
template<EndgameCode E> using
eg_type = typename std::conditional<(E < SCALING_FUNCTIONS), Value, ScaleFactor>::type;
/// Base and derived functors for endgame evaluation and scaling functions
template<typename T>
struct EndgameBase {
explicit EndgameBase(Color c) : strongSide(c), weakSide(~c) {}
virtual ~EndgameBase() = default;
virtual T operator()(const Position&) const = 0;
const Color strongSide, weakSide;
};
template<EndgameCode E, typename T = eg_type<E>>
struct Endgame : public EndgameBase<T> {
explicit Endgame(Color c) : EndgameBase<T>(c) {}
T operator()(const Position&) const override;
};
/// The Endgames namespace handles the pointers to endgame evaluation and scaling
/// base objects in two std::map. We use polymorphism to invoke the actual
/// endgame function by calling its virtual operator().
namespace Endgames {
template<typename T> using Ptr = std::unique_ptr<EndgameBase<T>>;
template<typename T> using Map = std::unordered_map<Key, Ptr<T>>;
extern std::pair<Map<Value>, Map<ScaleFactor>> maps;
void init();
template<typename T>
Map<T>& map() {
return std::get<std::is_same<T, ScaleFactor>::value>(maps);
}
template<EndgameCode E, typename T = eg_type<E>>
void add(const std::string& code) {
StateInfo st;
map<T>()[Position().set(code, WHITE, &st).material_key()] = Ptr<T>(new Endgame<E>(WHITE));
map<T>()[Position().set(code, BLACK, &st).material_key()] = Ptr<T>(new Endgame<E>(BLACK));
}
template<typename T>
const EndgameBase<T>* probe(Key key) {
auto it = map<T>().find(key);
return it != map<T>().end() ? it->second.get() : nullptr;
}
}
#endif // #ifndef ENDGAME_H_INCLUDED
|
[
"coelho@nostracasa.org"
] |
coelho@nostracasa.org
|
bc1fab7378d3d70db4de4c4312a365892cd7b5b2
|
23e4759cfb7507477f78c5c68373748e85eebf97
|
/class_notes/w4_servo/w4_servo.ino
|
102c1b2cea53c9cb4a644efbb95f62231cedf08d
|
[] |
no_license
|
abhimanyuvasishth/intro-to-im
|
85388f121452c070776bcb474d743ebbc17af50a
|
9bacdb528fbe0e2bb2a0cac09e7b6389a46254fc
|
refs/heads/master
| 2021-01-16T00:05:07.509423
| 2016-12-15T10:26:33
| 2016-12-15T10:26:33
| 68,454,361
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 309
|
ino
|
#include <Servo.h>
Servo myServo;
int potPin = 0;
int val;
void setup() {
// put your setup code here, to run once:
myServo.attach(9);
}
void loop() {
// put your main code here, to run repeatedly:
val = analogRead(potPin);
val = map(val, 0, 1023, 0, 180);
myServo.write(val);
delay(15);
}
|
[
"abhimanyu.vasishth@gmail.com"
] |
abhimanyu.vasishth@gmail.com
|
6636e238f26737a8f0657872e554e7c25db2477e
|
678588dc03828db3b00306469940e6b86a41c4eb
|
/src/OptFlowCpp/cpu_backend/sb_linearsystem/SunBakerLinearOp.h
|
aa5c26bd90d74c5922f7e0fa5e7180aada9b868a
|
[] |
no_license
|
Arnizack/opticalFlow
|
d3d815161d18422a99ce737a7135b06e49774a09
|
14d3f79abfd81e2b8ce360773384494b211003a4
|
refs/heads/master
| 2021-05-26T09:27:09.247343
| 2020-12-29T16:41:12
| 2020-12-29T16:41:12
| 254,075,717
| 1
| 0
| null | 2020-11-29T19:10:41
| 2020-04-08T12:02:18
|
Python
|
UTF-8
|
C++
| false
| false
| 1,446
|
h
|
#pragma once
#include"core/linalg/ILinearOperator.h"
#include"core/IArray.h"
#include<memory>
#include"../Array.h"
namespace cpu_backend
{
class SunBakerLinearOp final: public core::ILinearOperator<
std::shared_ptr<core::IArray<double, 1>>,
std::shared_ptr<core::IArray<double, 1>>>
{
using PtrGrayImg = std::shared_ptr<core::IArray<double, 1 >> ;
/*
Matrix representation:
|K+A C |
A = |C K+B|
Shape of A (width*height*2,width*height*2)
with:
K * x = - 2 lambda_kernel * mat(ker(x))
| 1 2 1 |
kernel = | 2 -12 2 | / 12
| 1 2 1 |
ker(x) uses width, height
C = diag_matrix(c_diags)
A = diag_matrix(a_diags)
B = diag_matrix(b_diags)
*/
public:
SunBakerLinearOp(
size_t width,
size_t height,
std::shared_ptr<Array<double, 1>> a_diags,
std::shared_ptr<Array<double, 1>> b_diags,
std::shared_ptr<Array<double, 1>> c_diags,
double lambda_kernel);
virtual PtrGrayImg Apply(const PtrGrayImg vec) override;
virtual void ApplyTo(PtrGrayImg dst, const PtrGrayImg vec) override;
virtual std::shared_ptr<core::ILinearOperator<PtrGrayImg, PtrGrayImg>> Transpose() override;
virtual bool IsSymetric() override;
private:
size_t _width;
size_t _height;
std::shared_ptr<Array<double, 1>> _a_diags;
std::shared_ptr<Array<double, 1>> _b_diags;
std::shared_ptr<Array<double, 1>> _c_diags;
double _lambda_kernel;
};
}
|
[
"42911677+Arnizack@users.noreply.github.com"
] |
42911677+Arnizack@users.noreply.github.com
|
d1b3d38e66d4c40eddb83d22b9a83ea1e8db93fe
|
447be6d71898f33ebbf3b71db8c4fdaaf670bc0b
|
/source/application/commands/CmdCut.cpp
|
1e22c0515f2cfb3ecd438e787d57104be5c4a5b4
|
[] |
no_license
|
CST-Modelling-Tools/TonatiuhPP
|
35bc1b6f4067364875471a5be99053df01df5883
|
664250e8ef38e7d6dab3ed35d6fab7f732edec19
|
refs/heads/master
| 2023-04-13T03:12:14.843634
| 2022-08-26T12:09:02
| 2022-08-26T12:09:02
| 380,948,961
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 867
|
cpp
|
#include "CmdCut.h"
#include <Inventor/nodekits/SoBaseKit.h>
#include "tree/SceneTreeModel.h"
#include "kernel/run/InstanceNode.h"
CmdCut::CmdCut(const QModelIndex& index, SoNode*& clipboard, SceneTreeModel* model, QUndoCommand* parent):
QUndoCommand("Cut", parent),
m_clipboard(clipboard),
m_model(model)
{
m_nodeOld = clipboard;
InstanceNode* instance = m_model->getInstance(index);
m_node = instance->getNode();
m_node->ref();
InstanceNode* instanceP = instance->getParent();
m_parent = static_cast<SoBaseKit*>(instanceP->getNode());
m_row = instanceP->children.indexOf(instance);
}
CmdCut::~CmdCut()
{
m_node->unref();
}
void CmdCut::undo()
{
m_clipboard = m_nodeOld;
m_model->Paste(m_parent, m_node, m_row, true);
}
void CmdCut::redo()
{
m_clipboard = m_node;
m_model->Cut(m_parent, m_row);
}
|
[
"v.grigoriev@cyi.ac.cy"
] |
v.grigoriev@cyi.ac.cy
|
5ac659c5524c139293ea88b61145ab2d25c26964
|
da7c499625123f5d1a28e3d75b037523df11ccb5
|
/devel/clon/src/clonutil/main/SCCS/s.run_number.cc
|
5262550660e7d9910521dca7fb991ccf811c021b
|
[] |
no_license
|
emuikernel/BDXDaq
|
84d947b0a4c0c1799a855dbe6c59e9560a8fc4e2
|
cf678d3b71bdfb95996e8b7e97ad3657ef98262f
|
refs/heads/master
| 2021-01-18T07:26:38.855967
| 2015-06-08T15:45:58
| 2015-06-08T15:45:58
| 48,211,085
| 3
| 2
| null | 2015-12-18T02:56:53
| 2015-12-18T02:56:52
| null |
UTF-8
|
C++
| false
| false
| 1,849
|
cc
|
h65393
s 00003/00003/00068
d D 1.2 00/08/29 16:39:15 wolin 3 1
c New CC
e
s 00000/00000/00000
d R 1.2 97/11/25 13:37:16 Codemgr 2 1
c SunPro Code Manager data about conflicts, renames, etc...
c Name history : 1 0 libutil/test/run_number.cc
e
s 00071/00000/00000
d D 1.1 97/11/25 13:37:15 wolin 1 0
c
e
u
U
f b
f e 0
t
T
I 1
// run_number
// prints run number
// ejw, 20-may-97
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
char *session = getenv("DD_NAME");
D 3
char *msql_database = "clasrun";
E 3
I 3
char *msql_database = (char *)"clasrun";
E 3
extern "C"{
void get_run_config(char *msql_database, char *session, int *run, char **config);
}
void decode_command_line(int argc, char **argv);
//----------------------------------------------------------------
main(int argc, char **argv){
int run;
char *config;
decode_command_line(argc,argv);
D 3
if(session==NULL)session="clasprod";
E 3
I 3
if(session==NULL)session=(char *)"clasprod";
E 3
// get run number
get_run_config(msql_database,session,&run,&config);
cout << run << endl;
}
//----------------------------------------------------------------
void decode_command_line(int argc, char **argv)
{
int i=1;
D 3
char *help="\nusage:\n\n run_number [-s session] [-m msql_database] \n\n\n";
E 3
I 3
const char *help="\nusage:\n\n run_number [-s session] [-m msql_database] \n\n\n";
E 3
while(i<argc) {
if(strncasecmp(argv[i],"-h",2)==0){
cout << help;
exit(EXIT_SUCCESS);
}
else if (strncasecmp(argv[i],"-s",2)==0){
session=strdup(argv[i+1]);
i=i+2;
}
else if (strncasecmp(argv[i],"-m",2)==0){
msql_database=strdup(argv[i+1]);
i=i+2;
}
}
}
/*---------------------------------------------------------------------*/
E 1
|
[
"andrea.celentano@ge.infn.it"
] |
andrea.celentano@ge.infn.it
|
b961713c6931b7fdf13f15225c24b138d0b84177
|
333b58a211c39f7142959040c2d60b69e6b20b47
|
/Odyssey/Oos/DdmCpu.cpp
|
b43e53c9d66be63e4158e3ccc36c10b2a89eb4dd
|
[] |
no_license
|
JoeAltmaier/Odyssey
|
d6ef505ade8be3adafa3740f81ed8d03fba3dc1a
|
121ea748881526b7787f9106133589c7bd4a9b6d
|
refs/heads/master
| 2020-04-11T08:05:34.474250
| 2015-09-09T20:03:29
| 2015-09-09T20:03:29
| 42,187,845
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,588
|
cpp
|
#include "DdmCpu.h"
#ifndef WIN32
#include "tc_defs.h"
#endif
#include "BuildSys.h"
#include "Critical.h"
#define ONESEC 1000000
CLASSNAME(DdmCpu, SINGLE);
DEVICENAME(CpuStatistics, DdmCpu::DeviceInitialize);
SERVELOCAL(DdmCpu, REQ_OS_CPU_STATS);
extern "C" int TCD_IDLE_COUNTER;
extern "C" int TCD_HISR_COUNTER;
extern "C" int TCD_TASK_COUNTER;
DdmCpu::DdmCpu(DID did): Ddm(did) {
DispatchRequest(REQ_OS_CPU_STATS, REQUESTCALLBACK( DdmCpu, Stats ));
}
Ddm *DdmCpu::Ctor(DID did) {
return new DdmCpu(did);
}
void DdmCpu::DeviceInitialize() {
TCD_IDLE_COUNTER = 0;
TCD_HISR_COUNTER = 0;
TCD_TASK_COUNTER = 0;
}
Status DdmCpu::Initialize(Message *pMsg) {
#ifndef WIN32
(new TimerStatic(TimerTick, this))->Enable(ONESEC, ONESEC);
#endif
Reply(pMsg, OK);
return OK;
}
Status DdmCpu::Stats(Message *pMsg) {
pMsg->AddPayload(&payload, sizeof(payload));
Reply(pMsg, OK);
return OK;
}
void DdmCpu::TimerTick(void *pThis) {
#ifndef WIN32
((DdmCpu*)pThis)->ProcessTimerTick();
#endif
}
void DdmCpu::ProcessTimerTick() {
Critical section;
payload.cIdleLast=TCD_IDLE_COUNTER;
TCD_IDLE_COUNTER=0;
payload.cHisrLast=TCD_HISR_COUNTER;
TCD_HISR_COUNTER=0;
payload.cTaskLast=TCD_TASK_COUNTER;
TCD_TASK_COUNTER=0;
payload.cIdleAvg = ( payload.cIdleAvg >> 1 ) + ( payload.cIdleLast >> 1 );
payload.cHisrAvg = ( payload.cHisrAvg >> 1 ) + ( payload.cHisrLast >> 1 );
payload.cTaskAvg = ( payload.cTaskAvg >> 1 ) + ( payload.cTaskLast >> 1 );
}
|
[
"joe.altmaier@sococo.com"
] |
joe.altmaier@sococo.com
|
db9bde019f9686cdd53948caa77fa7a208aa8aa8
|
fb39f72c5325704dc04a13594b7938125569a8f3
|
/lib-rdm/src/rdmidentify.cpp
|
0c6c7ec14f9560145767286d7ec182c1cc612af5
|
[] |
no_license
|
hippyau/rpidmx512
|
3699ec5d1a299876b22f60c2f87ebb98b441c347
|
449eb386281b142dbee7d65c9eecb5a4eb1ce01a
|
refs/heads/master
| 2021-09-10T23:32:13.804337
| 2020-10-09T15:54:21
| 2020-10-09T15:54:21
| 287,152,580
| 1
| 0
| null | 2020-11-08T01:57:46
| 2020-08-13T01:32:01
| null |
UTF-8
|
C++
| false
| false
| 1,709
|
cpp
|
/**
* @file rdmidentify.cpp
*
*/
/* Copyright (C) 2018-2020 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <cassert>
#include "rdmidentify.h"
#include "ledblink.h"
#include "debug.h"
RDMIdentify *RDMIdentify::s_pThis = nullptr;
RDMIdentify::RDMIdentify() :
m_bIsEnabled(false),
m_nMode(IDENTIFY_MODE_QUIET)
{
assert(s_pThis == nullptr);
s_pThis = this;
}
void RDMIdentify::On() {
m_bIsEnabled = true;
LedBlink::Get()->SetMode(LEDBLINK_MODE_FAST);
}
void RDMIdentify::Off() {
m_bIsEnabled = false;
LedBlink::Get()->SetMode(LEDBLINK_MODE_NORMAL);
}
bool RDMIdentify::IsEnabled() {
return m_bIsEnabled;
}
|
[
"Arjan.van.Vught@gmail.com"
] |
Arjan.van.Vught@gmail.com
|
6a8f5d1d2179525fc277b6449a6f7abac8154cd8
|
f121b18f179642a792967baa4f7d6a7e8b1a61cd
|
/hid/juce_hid.cpp
|
aaaf2790c94b35033607abbc8fa112765e573c26
|
[
"MIT"
] |
permissive
|
martinpavlas/juce_hid
|
6670e6ac35340ddadd5ccdab63e37335833d0136
|
8c396e2c79e5bf6ed5543cba9ac7f231e30a3511
|
refs/heads/master
| 2021-05-24T13:28:06.928807
| 2021-02-18T19:44:04
| 2021-02-18T19:44:04
| 253,583,677
| 0
| 0
|
MIT
| 2020-04-06T18:32:43
| 2020-04-06T18:32:43
| null |
UTF-8
|
C++
| false
| false
| 19,980
|
cpp
|
/*
==============================================================================
juce_hid.cpp
Created: 7 Dec 2017 3:16:59pm
Author: Chris Penny
==============================================================================
*/
#define HID_ERROR -1
#ifndef DEFAULT_SIZE
#define DEFAULT_SIZE 2048
#endif
using namespace juce;
Result hid::init()
{
int res = hid_init();
return res == HID_ERROR
? Result::fail(TRANS("could not initialize hidapi"))
: Result::ok();
}
Result hid::exit()
{
int res = hid_exit();
return res == HID_ERROR
? Result::fail(TRANS("could not exit hidapi"))
: Result::ok();
}
hid::DeviceInfo::DeviceInfo()
: vendorId(0)
, productId(0)
, releaseNumber(0)
, usagePage(0)
, usage(0)
, interfaceNumber (0) {};
hid::DeviceInfo::DeviceInfo (const hid_device_info& info)
: path (info.path)
, vendorId (info.vendor_id)
, productId (info.product_id)
, serialNumber (info.serial_number)
, releaseNumber (info.release_number)
, manufacturerString (info.manufacturer_string)
, productString (info.product_string)
, usagePage (info.usage_page)
, usage (info.usage)
, interfaceNumber (info.interface_number) {}
hid::DeviceInfo::DeviceInfo (const DeviceInfo& other)
: path (other.path)
, vendorId (other.vendorId)
, productId (other.productId)
, serialNumber (other.serialNumber)
, releaseNumber (other.releaseNumber)
, manufacturerString (other.manufacturerString)
, productString (other.productString)
, usagePage (other.usagePage)
, usage (other.usage)
, interfaceNumber (other.interfaceNumber) {}
hid::DeviceInfo::DeviceInfo (const MutableDeviceInfo& other)
: path (other.getPath())
, vendorId (other.getVendorId())
, productId (other.getProductId())
, serialNumber (other.getSerialNumber())
, releaseNumber (other.getReleaseNumber())
, manufacturerString (other.getManufacturerString())
, productString (other.getProductString())
, usagePage (other.getUsagePage())
, usage (other.getUsage())
, interfaceNumber (other.getInterfaceNumber()) {}
bool hid::DeviceInfo::operator== (const DeviceInfo& other) const
{
return
this->path == other.path
&& this->vendorId == other.vendorId
&& this->productId == other.productId
&& this->serialNumber == other.serialNumber
&& this->releaseNumber == other.releaseNumber
&& this->manufacturerString == other.manufacturerString
&& this->productString == other.productString
&& this->usagePage == other.usagePage
&& this->usage == other.usage
&& this->interfaceNumber == other.interfaceNumber;
}
bool hid::DeviceInfo::operator== (const MutableDeviceInfo& other) const
{
return
this->path == other.path
&& this->vendorId == other.vendorId
&& this->productId == other.productId
&& this->serialNumber == other.serialNumber
&& this->releaseNumber == other.releaseNumber
&& this->manufacturerString == other.manufacturerString
&& this->productString == other.productString
&& this->usagePage == other.usagePage
&& this->usage == other.usage
&& this->interfaceNumber == other.interfaceNumber;
}
bool hid::DeviceInfo::operator== (const DeviceIO& other) const
{
return *this == other.getInfo();
}
const String& hid::DeviceInfo::getPath() const { return path; }
const unsigned short hid::DeviceInfo::getVendorId() const { return vendorId; };
const unsigned short hid::DeviceInfo::getProductId() const { return productId; };
const String& hid::DeviceInfo::getSerialNumber() const { return serialNumber; };
const unsigned short hid::DeviceInfo::getReleaseNumber() const { return releaseNumber; };
const String& hid::DeviceInfo::getManufacturerString() const { return manufacturerString; };
const String& hid::DeviceInfo::getProductString() const { return productString; };
const unsigned short hid::DeviceInfo::getUsagePage() const { return usagePage; };
const unsigned short hid::DeviceInfo::getUsage() const { return usage; };
const int hid::DeviceInfo::getInterfaceNumber() const { return interfaceNumber; };
const String hid::DeviceInfo::getName() const {
return manufacturerString + " " + productString;
}
const hid::DeviceIO hid::DeviceInfo::connect() const
{
return hid::connect(*this);
}
void hid::DeviceInfo::disconnect() const
{
hid::disconnect();
}
hid::MutableDeviceInfo::MutableDeviceInfo() {}
hid::MutableDeviceInfo::MutableDeviceInfo (const hid_device_info& info)
{
path = info.path;
vendorId = info.vendor_id;
productId = info.product_id;
serialNumber = info.serial_number;
releaseNumber = info.release_number;
manufacturerString = info.manufacturer_string;
productString = info.product_string;
usagePage = info.usage_page;
usage = info.usage;
interfaceNumber = info.interface_number;
}
hid::MutableDeviceInfo::MutableDeviceInfo (const hid::DeviceInfo& other)
{
path = other.getPath();
vendorId = other.getVendorId();
productId = other.getProductId();
serialNumber = other.getSerialNumber();
releaseNumber = other.getReleaseNumber();
manufacturerString = other.getManufacturerString();
productString = other.getProductString();
usagePage = other.getUsagePage();
usage = other.getUsage();
interfaceNumber = other.getInterfaceNumber();
}
hid::MutableDeviceInfo::MutableDeviceInfo (const hid::MutableDeviceInfo& other)
{
path = other.getPath();
vendorId = other.getVendorId();
productId = other.getProductId();
serialNumber = other.getSerialNumber();
releaseNumber = other.getReleaseNumber();
manufacturerString = other.getManufacturerString();
productString = other.getProductString();
usagePage = other.getUsagePage();
usage = other.getUsage();
interfaceNumber = other.getInterfaceNumber();
}
bool hid::MutableDeviceInfo::operator== (const DeviceInfo& other) const
{
return
this->path == other.path
&& this->vendorId == other.vendorId
&& this->productId == other.productId
&& this->serialNumber == other.serialNumber
&& this->releaseNumber == other.releaseNumber
&& this->manufacturerString == other.manufacturerString
&& this->productString == other.productString
&& this->usagePage == other.usagePage
&& this->usage == other.usage
&& this->interfaceNumber == other.interfaceNumber;
}
bool hid::MutableDeviceInfo::operator== (const MutableDeviceInfo& other) const
{
return
this->path == other.path
&& this->vendorId == other.vendorId
&& this->productId == other.productId
&& this->serialNumber == other.serialNumber
&& this->releaseNumber == other.releaseNumber
&& this->manufacturerString == other.manufacturerString
&& this->productString == other.productString
&& this->usagePage == other.usagePage
&& this->usage == other.usage
&& this->interfaceNumber == other.interfaceNumber;
}
bool hid::MutableDeviceInfo::operator== (const DeviceIO& other) const
{
return *this == other.getInfo();
}
const String& hid::MutableDeviceInfo::getPath() const { return path; }
const unsigned short hid::MutableDeviceInfo::getVendorId() const { return vendorId; };
const unsigned short hid::MutableDeviceInfo::getProductId() const { return productId; };
const String& hid::MutableDeviceInfo::getSerialNumber() const { return serialNumber; };
const unsigned short hid::MutableDeviceInfo::getReleaseNumber() const { return releaseNumber; };
const String& hid::MutableDeviceInfo::getManufacturerString() const { return manufacturerString; };
const String& hid::MutableDeviceInfo::getProductString() const { return productString; };
const unsigned short hid::MutableDeviceInfo::getUsagePage() const { return usagePage; };
const unsigned short hid::MutableDeviceInfo::getUsage() const { return usage; };
const int hid::MutableDeviceInfo::getInterfaceNumber() const { return interfaceNumber; };
const String hid::MutableDeviceInfo::getName() const {
return manufacturerString + " " + productString;
}
hid::DeviceIO hid::MutableDeviceInfo::connect() const
{
return hid::connect(*this);
}
void hid::MutableDeviceInfo::disconnect() const
{
hid::disconnect();
}
hid::DeviceIterator::DeviceIterator (unsigned short vid, unsigned short pid)
: current(hid_enumerate(vid, pid))
{
DeleteThis = current;
}
hid::DeviceIterator::~DeviceIterator()
{
hid_free_enumeration(DeleteThis);
}
bool hid::DeviceIterator::hasNext()
{
return current != nullptr;
}
hid::DeviceInfo hid::DeviceIterator::getNext()
{
// You must call hasNext() first to see if there is one available!
// Program will crash if you try to getNext() when there are none.
jassert(current != nullptr);
hid_device_info* deviceToReturn = current;
current = current->next;
return *deviceToReturn;
}
hid::DeviceIO::DeviceIO (Device deviceToUse, const DeviceInfo& deviceInfo)
: device(deviceToUse), info(deviceInfo) {}
hid::DeviceIO::DeviceIO (const DeviceIO& other) : device(other.device), info(other.info) {}
bool hid::DeviceIO::operator==(const DeviceIO& other) const
{
return
this->device == other.device
&& DeviceInfo(this->info) == DeviceInfo(other.info);
}
bool hid::DeviceIO::operator==(const DeviceInfo& other) const
{
return getInfo() == other;
}
bool hid::DeviceIO::operator==(const MutableDeviceInfo& other) const
{
return getInfo() == other;
}
Result hid::DeviceIO::setNonblocking(bool shouldBeNonblocking)
{
int r = hid_set_nonblocking(device, shouldBeNonblocking);
return r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::write(const unsigned char *data, size_t length, size_t* bytesWritten)
{
int r = hid_write(device, data, length);
if (bytesWritten != nullptr) {
*bytesWritten = (size_t) r;
}
return r == 0
? Result::fail(TRANS("no bytes written"))
: r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::read(unsigned char *data, size_t length, size_t* bytesRead)
{
int r = hid_read(device, data, length);
if (bytesRead != nullptr) {
*bytesRead = (size_t) r;
}
return r == 0
? Result::fail(TRANS("no bytes read"))
: r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::readTimeout(unsigned char *data, size_t length, int milliseconds, size_t* bytesRead)
{
int r = hid_read_timeout (device, data, length, milliseconds);
if (bytesRead != nullptr) {
*bytesRead = (size_t) r;
}
return r == 0
? Result::fail(TRANS("no bytes read"))
: r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::sendFeatureReport(const unsigned char *data, size_t length, size_t* bytesWritten)
{
int r = hid_send_feature_report(device, data, length);
if (bytesWritten != nullptr) {
*bytesWritten = (size_t) r;
}
return r == 0
? Result::fail(TRANS("no bytes written"))
: r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::getFeatureReport(unsigned char *data, size_t length, size_t* bytesRead)
{
int r = hid_get_feature_report(device, data, length);
if (bytesRead != nullptr) {
*bytesRead = (size_t) r;
}
return r == 0 || r == 1
? Result::fail(TRANS("no bytes read"))
: r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::getManufacturerString(wchar_t* string, size_t maxLength)
{
int r = hid_get_manufacturer_string(device, string, maxLength);
return r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::getProductString(wchar_t* string, size_t maxLength)
{
int r = hid_get_product_string(device, string, maxLength);
return r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::getSerialNumberString(wchar_t* string, size_t maxLength)
{
int r = hid_get_serial_number_string(device, string, maxLength);
return r == HID_ERROR
? Result::fail(TRANS(hid_error(device)))
: Result::ok();
}
Result hid::DeviceIO::getIndexedString(int index, wchar_t* string, size_t maxLength)
{
int r = hid_get_indexed_string(device, index, string, maxLength);
return r == HID_ERROR
? Result::fail(TRANS("hid_get_indexed_string not implemented on macOS"))
: Result::ok();
}
void hid::DeviceIO::disconnect()
{
if (device == nullptr || ! hid::isConnected()) {
DBG(" Warning: disconnecting device when none are connected.");
}
hid_close(device);
device = nullptr;
}
Result hid::DeviceIO::connect()
{
if (device != nullptr || hid::isConnected()) {
return Result::fail(TRANS("Already connected to device"));
}
*this = info.connect();
if (device == nullptr) {
return Result::fail(TRANS("failed to connect to device"));
}
return Result::ok();
}
const hid::DeviceInfo hid::DeviceIO::getInfo() const
{
return info;
}
hid::DeviceScanner::DeviceScanner() : DeviceScanner (nullptr) {}
hid::DeviceScanner::DeviceScanner(ChangeListener* listener, int intervalInMilliseconds)
{
if (listener != nullptr) {
addChangeListener(listener);
}
startTimer(intervalInMilliseconds);
}
hid::DeviceScanner::~DeviceScanner()
{
removeAllChangeListeners();
stopTimer();
}
void hid::DeviceScanner::timerCallback()
{
scanNow();
}
const Array<hid::DeviceInfo>& hid::DeviceScanner::getCurrentDevices() const
{
return devices;
}
void hid::DeviceScanner::scanNow()
{
Array<DeviceInfo> newDevices = hid::getAllDevicesAvailable();
// Device removed or connected
if (newDevices.size() != devices.size()) {
devices = newDevices;
sendChangeMessage();
}
}
bool hid::isDeviceAvailable (unsigned short vid, unsigned short pid)
{
hid::DeviceIterator iterator (vid, pid);
return iterator.hasNext();
}
hid::DeviceInfo hid::getDeviceInfo(unsigned short vid, unsigned short pid)
{
hid::DeviceIterator iterator (vid, pid);
// Can't get the next device when there are none! Check if it's availiable with
// isDeviceAvailable (unsigned short vid, unsigned short pid).
jassert(iterator.hasNext());
return iterator.getNext();
}
Array<hid::DeviceInfo> hid::getAllDevicesAvailable()
{
Array<DeviceInfo> allDevices;
hid::DeviceIterator iterator;
while (iterator.hasNext()) {
allDevices.add(iterator.getNext());
}
return allDevices;
}
void hid::printAllDevices()
{
hid::DeviceIterator iterator;
while (iterator.hasNext())
{
DeviceInfo currentDevice (iterator.getNext());
String s;
String usage_str;
s += "0x" + String::toHexString (currentDevice.getVendorId()).paddedLeft('0', 4) + ":";
s += "0x" + String::toHexString (currentDevice.getProductId()).paddedLeft('0', 4);
s += String(" ") + currentDevice.getManufacturerString();
s += String(" ") + currentDevice.getProductString();
usage_str += "0x" + String::toHexString (currentDevice.getUsagePage()).paddedLeft('0', 4);
usage_str += ":0x" + String::toHexString (currentDevice.getUsage()).paddedLeft('0', 4);
s += " " + usage_str;
std::cout << s << "\n";
std::cout << currentDevice.getPath() << "\n\n";
}
}
hid::DeviceIO hid::getConnectedDevice()
{
// Don't call this function if no device is connected!!!!!!!
jassert(isConnected());
return changeConnection(false, DeviceInfo(hid_device_info()), true);
}
const hid::DeviceInfo hid::getConnectedDeviceInfo()
{
// Don't call this function if no device is connected!!!!!!!
jassert(isConnected());
return getConnectedDevice().getInfo();
}
bool hid::isConnected()
{
return connectionStatus(false);
}
hid::DeviceIO hid::connect (const DeviceInfo& device)
{
return changeConnection(true, device);
}
void hid::disconnect()
{
changeConnection(false);
}
const unsigned int hid::reportID()
{
static unsigned int idCounter = 0;
return idCounter++;
}
// Why use a class when you could use a function
// Don't worry it's a rhetorical question — this approach worked for my
// specific use case, but this could easily be replaced with something
// a little more clear.
//
// These functions maintain an internal static device representation and
// are the single point of entry for all connection/disconnection related things.
// Note that this only supports one connection at a time.
bool hid::connectionStatus (bool shouldSet, bool shouldBeConnected)
{
static bool isConnected = false;
if (shouldSet) {
isConnected = shouldBeConnected;
}
return isConnected;
}
hid::DeviceIO hid::changeConnection(bool shouldConnect, const DeviceInfo& deviceInfo, bool get)
{
static MutableDeviceInfo connectedDeviceInfo;
static Device connectedDevice = nullptr;
if (get) {
return DeviceIO(connectedDevice, connectedDeviceInfo);
}
connectionStatus(true, false);
if (shouldConnect) {
if ((connectedDevice = hid_open_path(deviceInfo.getPath().toRawUTF8())) != nullptr) {
// Connection Success
connectedDeviceInfo = deviceInfo;
DBG(" HID Device Connected: " << deviceInfo.getName());
connectionStatus(true, true);
}
else {
DBG(" HID Device Failed To Connect: " << deviceInfo.getName());
}
}
else if (connectedDevice != nullptr) {
hid_close(connectedDevice);
connectedDevice = nullptr;
DBG(" HID Device Disconnected: " << connectedDeviceInfo.getName());
}
else {
DBG(" Could not disconnect HID Device - none connected.");
}
return DeviceIO(connectedDevice, connectedDeviceInfo);
}
|
[
"cpennny@gmail.com"
] |
cpennny@gmail.com
|
f48fb48ac055bb507b59fa869294ffc6275c7f6e
|
201ff54232a3eab6f160e256d575d6644bf32d72
|
/src/tests/ScriptInterpTCLTest.h
|
ac3bf8856eb469f4222a5e0f1fe34e45089a17e5
|
[
"BSD-2-Clause"
] |
permissive
|
bdrewery/bdlib
|
c421a52fb820e276cb393b7c6cd3c28df4a1d87c
|
33b6871ccdd677925471beb0229b2e7cb2f89eed
|
refs/heads/master
| 2021-01-18T21:56:47.189036
| 2020-03-25T04:15:33
| 2020-03-25T04:18:19
| 73,997
| 3
| 5
| null | 2017-02-24T23:17:10
| 2008-11-10T19:24:50
|
C++
|
UTF-8
|
C++
| false
| false
| 1,261
|
h
|
/* ScriptInterpTCLTest.h
*
*/
#ifndef _SCRIPTINTERPTCLTEST_H
#define _SCRIPTINTERPTCLTEST_H 1
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "String.h"
#include "Array.h"
#include "Stream.h"
#include "ScriptInterp.h"
#include "ScriptInterpTCL.h"
using namespace BDLIB_NS;
#ifdef USE_SCRIPT_TCL
class ScriptInterpTCLTest : public CPPUNIT_NS :: TestFixture
{
CPPUNIT_TEST_SUITE (ScriptInterpTCLTest);
CPPUNIT_TEST (evalTest);
CPPUNIT_TEST (loadScriptTest);
// CPPUNIT_TEST (operatorEqualsTest);
CPPUNIT_TEST (linkVarTest);
CPPUNIT_TEST (unlinkVarTest);
CPPUNIT_TEST (createCommandTest);
CPPUNIT_TEST (createCommandEventTest);
CPPUNIT_TEST (deleteCommandTest);
CPPUNIT_TEST_SUITE_END ();
public:
void setUp (void);
void tearDown (void);
protected:
void evalTest(void);
void loadScriptTest(void);
// void operatorEqualsTest(void);
void linkVarTest(void);
void unlinkVarTest(void);
void createCommandTest(void);
void createCommandEventTest(void);
void deleteCommandTest(void);
private:
};
#endif /* USE_SCRIPT_TCL */
#endif /* !_SCRIPTINTERPTCLTEST_H */
/* vim: set sts=2 sw=2 ts=8 et: */
|
[
"bryan@shatow.net"
] |
bryan@shatow.net
|
54c9e7d40a49271240b12de5b0052b95eb460213
|
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
|
/cmake-build-debug/programs_tiling/function14057/function14057_schedule_7/function14057_schedule_7.cpp
|
60d55b9c480a4e4cbcf475b63be73869a4b0d3bf
|
[] |
no_license
|
IsraMekki/tiramisu_code_generator
|
8b3f1d63cff62ba9f5242c019058d5a3119184a3
|
5a259d8e244af452e5301126683fa4320c2047a3
|
refs/heads/master
| 2020-04-29T17:27:57.987172
| 2019-04-23T16:50:32
| 2019-04-23T16:50:32
| 176,297,755
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,849
|
cpp
|
#include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14057_schedule_7");
constant c0("c0", 262144), c1("c1", 256);
var i0("i0", 0, c0), i1("i1", 0, c1), i01("i01"), i02("i02"), i03("i03"), i04("i04");
input input00("input00", {i1}, p_int32);
input input01("input01", {i1}, p_int32);
input input02("input02", {i0}, p_int32);
input input03("input03", {i0}, p_int32);
input input04("input04", {i0}, p_int32);
input input05("input05", {i1}, p_int32);
input input06("input06", {i1}, p_int32);
input input07("input07", {i0}, p_int32);
computation comp0("comp0", {i0, i1}, input00(i1) * input01(i1) * input02(i0) * input03(i0) + input04(i0) * input05(i1) - input06(i1) + input07(i0));
comp0.tile(i0, i1, 128, 64, i01, i02, i03, i04);
comp0.parallelize(i01);
buffer buf00("buf00", {256}, p_int32, a_input);
buffer buf01("buf01", {256}, p_int32, a_input);
buffer buf02("buf02", {262144}, p_int32, a_input);
buffer buf03("buf03", {262144}, p_int32, a_input);
buffer buf04("buf04", {262144}, p_int32, a_input);
buffer buf05("buf05", {256}, p_int32, a_input);
buffer buf06("buf06", {256}, p_int32, a_input);
buffer buf07("buf07", {262144}, p_int32, a_input);
buffer buf0("buf0", {262144, 256}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
input05.store_in(&buf05);
input06.store_in(&buf06);
input07.store_in(&buf07);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf07, &buf0}, "../data/programs/function14057/function14057_schedule_7/function14057_schedule_7.o");
return 0;
}
|
[
"ei_mekki@esi.dz"
] |
ei_mekki@esi.dz
|
6968d4d98b44dc72e5571983349922bd0d0eea5a
|
923a4858ca40e3b2a60a27c03f93ea362b11d870
|
/C++/Task6_Part2_C++Code/PayOffBridge.h
|
7d952db62eeaeb0fce408568ee3c33c03433f954
|
[] |
no_license
|
himanshu199391/DerivativePricing-DesignPatterns
|
97a4db4823403bc2bf642662ce2dd1edd8e120eb
|
69ab4ee574d6ef72ecd207528fec91567a8d8ef5
|
refs/heads/master
| 2022-02-04T12:22:34.923691
| 2019-08-27T17:53:02
| 2019-08-27T17:53:02
| 204,757,407
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 749
|
h
|
//
// PayOffBridge.h
// ch10_factory_pattern
//
// Created by cheerzzh on 24/6/14.
// Copyright (c) 2014年 Jared Zhou. All rights reserved.
//
#ifndef __ch10_factory_pattern__PayOffBridge__
#define __ch10_factory_pattern__PayOffBridge__
#include "PayOff3.h"
class PayOffBridge
{
public:
PayOffBridge(const PayOffBridge& original);
PayOffBridge(const PayOff& innerPayOff);
inline double operator()(double Spot) const;
~PayOffBridge();
PayOffBridge& operator=(const PayOffBridge& original);
private:
PayOff* ThePayOffPtr;
};
inline double PayOffBridge::operator()(double Spot) const
{
return ThePayOffPtr->operator ()(Spot);
}
#endif /* defined(__ch10_factory_pattern__PayOffBridge__) */
|
[
"himanshu@HIMANSHUs-Air.fios-router.home"
] |
himanshu@HIMANSHUs-Air.fios-router.home
|
a6507210592cf8ef21140d9b722928d9b30221bd
|
f1bd16b70c982ac75bf5b6b5ec4cb4e99a207896
|
/Algorithm/Recursive/樓梯階層走法(遞迴演算法).cpp
|
5082d2a34bdf815b8c4c538f49af6dc29f3a55df
|
[] |
no_license
|
ChouJustice/C-Language_exercise
|
92b33515b8d0c7cfcd59c523905b1a00079067cf
|
8d44e16a22f50ec684d6cb63758bbdff4d0c2fb2
|
refs/heads/master
| 2021-04-12T04:26:16.917913
| 2018-06-07T14:12:12
| 2018-06-07T14:12:12
| 125,950,714
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,047
|
cpp
|
#include <iostream>
using namespace std;
void startWalk(int ) ;
void printHow();
int len = 0, n = 0, total = 0, *step;
int main(void)
{
cout << "Input stairs of n = ";
cin >> n;
cout << endl;
if (n!=0 && n>0)
{
step = new int [n];
startWalk(n);
cout << endl << "Total Path : " << total << endl << endl;
}
else return main();
system("pause");
return 0;
}
void printHow()
{
cout << "Path "<< total << " ¡÷ " ;
for (int i = 0; i < len; i++)
{
cout << step[i] << " ";
}
cout <<endl;
return;
}
void startWalk(int s)
{
//cout << s << endl;
if (s < 0)
{
return;
}
else if (s == 0)
{
total++;
printHow();
return;
}
else
for (int i = 1; i <= 2; i++)
{
step[len] = i;
len++;
//cout << "$" << len << endl;
startWalk(s - i);
len--;
//cout << "*" << len << endl;
//cout << i << endl;
}
}
|
[
"noreply@github.com"
] |
ChouJustice.noreply@github.com
|
edb7d2f108d065f9e1012c0f28d8347f10ed5ae5
|
2e8a39b275cf368da752bc7a6fad39f9968bdb2a
|
/输出一组整数中的最小整数.cpp
|
b3ffdd1a896c96450816d8b9d49d48f003af1ab2
|
[] |
no_license
|
15831944/Cplusplus-1
|
9e77161b9df8df610f16432503f9e52ffff4eb68
|
16c74deec56829fd2141a98284145984cd555735
|
refs/heads/master
| 2023-04-09T22:19:07.092358
| 2016-09-30T03:40:35
| 2016-09-30T03:40:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 197
|
cpp
|
#include <iostream>
using namespace std;
int main()
{
int n,a,ans;
cin>>n;
ans=0;
while(n--)
{
cin>>a;
if(ans<=a) ans=a;
}cout<<"Answer = "<<ans<<endl;
}
|
[
"lixuat2014@gmail.com"
] |
lixuat2014@gmail.com
|
faae5f02168d44a4eb8aca0f6ea44a11be0b796f
|
94c3272a6fa6884c258cdbe27fc6e96b0d1f364b
|
/include/relay.hpp
|
c5ae434dbed57d7cd551237d1ad4dba0ccbf3030
|
[] |
no_license
|
CentraleFitness/ESP32-relay
|
bc4e6853a67ead1e7049791461aa3d18076d3e78
|
6dd68a3fe326e91260401d6d1de8d0cc45f71643
|
refs/heads/master
| 2021-07-25T00:21:49.622681
| 2019-01-13T20:49:40
| 2019-01-13T20:49:40
| 147,251,894
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 761
|
hpp
|
#pragma once
#ifndef ARDUINO_H_
#define ARDUINO_H_
#include <Arduino.h>
#endif
class Relay
{
private:
uint8_t mPin;
bool mStatus;
public:
void turn_on(void) {
digitalWrite(this->mPin, HIGH);
this->mStatus = true;
delay(10);
};
void turn_off(void) {
digitalWrite(this->mPin, LOW);
this->mStatus = false;
delay(10);
};
bool status(void) {
return (this->mStatus);
}
Relay(uint8_t pin) {
this->mStatus = false;
this->mPin = pin;
pinMode(this->mPin, OUTPUT);
};
~Relay() {
this->turn_off();
};
};
|
[
"leoraphael.poulin@epitech.eu"
] |
leoraphael.poulin@epitech.eu
|
58d0650d3c465b54e474cd7f2bbe469a442a571c
|
48ebb9aa139b70ed9d8411168c9bd073741393f5
|
/Classes/Native/System_Xml_System_Xml_Serialization_XmlTypeMapping315595419.h
|
b34f05b98b51708d2663b47acef3734845533951
|
[] |
no_license
|
JasonRy/0.9.1
|
36cae42b24faa025659252293d8c7f8bfa8ee529
|
b72ec7b76d3e26eb055574712a5150b1123beaa5
|
refs/heads/master
| 2021-07-22T12:25:04.214322
| 2017-11-02T07:42:18
| 2017-11-02T07:42:18
| 109,232,088
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,134
|
h
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "System_Xml_System_Xml_Serialization_XmlMapping1597064667.h"
// System.String
struct String_t;
// System.Xml.Serialization.TypeData
struct TypeData_t3979356678;
// System.Xml.Serialization.XmlTypeMapping
struct XmlTypeMapping_t315595419;
// System.Collections.ArrayList
struct ArrayList_t4252133567;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Xml.Serialization.XmlTypeMapping
struct XmlTypeMapping_t315595419 : public XmlMapping_t1597064667
{
public:
// System.String System.Xml.Serialization.XmlTypeMapping::xmlType
String_t* ___xmlType_7;
// System.String System.Xml.Serialization.XmlTypeMapping::xmlTypeNamespace
String_t* ___xmlTypeNamespace_8;
// System.Xml.Serialization.TypeData System.Xml.Serialization.XmlTypeMapping::type
TypeData_t3979356678 * ___type_9;
// System.Xml.Serialization.XmlTypeMapping System.Xml.Serialization.XmlTypeMapping::baseMap
XmlTypeMapping_t315595419 * ___baseMap_10;
// System.Boolean System.Xml.Serialization.XmlTypeMapping::multiReferenceType
bool ___multiReferenceType_11;
// System.Boolean System.Xml.Serialization.XmlTypeMapping::includeInSchema
bool ___includeInSchema_12;
// System.Boolean System.Xml.Serialization.XmlTypeMapping::isNullable
bool ___isNullable_13;
// System.Collections.ArrayList System.Xml.Serialization.XmlTypeMapping::_derivedTypes
ArrayList_t4252133567 * ____derivedTypes_14;
public:
inline static int32_t get_offset_of_xmlType_7() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___xmlType_7)); }
inline String_t* get_xmlType_7() const { return ___xmlType_7; }
inline String_t** get_address_of_xmlType_7() { return &___xmlType_7; }
inline void set_xmlType_7(String_t* value)
{
___xmlType_7 = value;
Il2CppCodeGenWriteBarrier(&___xmlType_7, value);
}
inline static int32_t get_offset_of_xmlTypeNamespace_8() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___xmlTypeNamespace_8)); }
inline String_t* get_xmlTypeNamespace_8() const { return ___xmlTypeNamespace_8; }
inline String_t** get_address_of_xmlTypeNamespace_8() { return &___xmlTypeNamespace_8; }
inline void set_xmlTypeNamespace_8(String_t* value)
{
___xmlTypeNamespace_8 = value;
Il2CppCodeGenWriteBarrier(&___xmlTypeNamespace_8, value);
}
inline static int32_t get_offset_of_type_9() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___type_9)); }
inline TypeData_t3979356678 * get_type_9() const { return ___type_9; }
inline TypeData_t3979356678 ** get_address_of_type_9() { return &___type_9; }
inline void set_type_9(TypeData_t3979356678 * value)
{
___type_9 = value;
Il2CppCodeGenWriteBarrier(&___type_9, value);
}
inline static int32_t get_offset_of_baseMap_10() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___baseMap_10)); }
inline XmlTypeMapping_t315595419 * get_baseMap_10() const { return ___baseMap_10; }
inline XmlTypeMapping_t315595419 ** get_address_of_baseMap_10() { return &___baseMap_10; }
inline void set_baseMap_10(XmlTypeMapping_t315595419 * value)
{
___baseMap_10 = value;
Il2CppCodeGenWriteBarrier(&___baseMap_10, value);
}
inline static int32_t get_offset_of_multiReferenceType_11() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___multiReferenceType_11)); }
inline bool get_multiReferenceType_11() const { return ___multiReferenceType_11; }
inline bool* get_address_of_multiReferenceType_11() { return &___multiReferenceType_11; }
inline void set_multiReferenceType_11(bool value)
{
___multiReferenceType_11 = value;
}
inline static int32_t get_offset_of_includeInSchema_12() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___includeInSchema_12)); }
inline bool get_includeInSchema_12() const { return ___includeInSchema_12; }
inline bool* get_address_of_includeInSchema_12() { return &___includeInSchema_12; }
inline void set_includeInSchema_12(bool value)
{
___includeInSchema_12 = value;
}
inline static int32_t get_offset_of_isNullable_13() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ___isNullable_13)); }
inline bool get_isNullable_13() const { return ___isNullable_13; }
inline bool* get_address_of_isNullable_13() { return &___isNullable_13; }
inline void set_isNullable_13(bool value)
{
___isNullable_13 = value;
}
inline static int32_t get_offset_of__derivedTypes_14() { return static_cast<int32_t>(offsetof(XmlTypeMapping_t315595419, ____derivedTypes_14)); }
inline ArrayList_t4252133567 * get__derivedTypes_14() const { return ____derivedTypes_14; }
inline ArrayList_t4252133567 ** get_address_of__derivedTypes_14() { return &____derivedTypes_14; }
inline void set__derivedTypes_14(ArrayList_t4252133567 * value)
{
____derivedTypes_14 = value;
Il2CppCodeGenWriteBarrier(&____derivedTypes_14, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
[
"renxiaoyi@me.com"
] |
renxiaoyi@me.com
|
26f4f8e809d9198c84e6934f2828a612dff85d1b
|
5c026ae62a2677038f85dec3682393841a6b8de0
|
/include/recarray.h
|
2fbfe084fd826aa5de81bdae4354cdcd049180c7
|
[] |
no_license
|
gravit0/server-cpp
|
8f10d31ae8832504eb0f9bdb18b00261f7bd54ba
|
e3d824971910e88f3aec8cbce55e8ec7a82e32bd
|
refs/heads/master
| 2020-03-22T01:39:05.091829
| 2017-02-18T08:37:35
| 2017-02-18T08:37:35
| 139,319,999
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 619
|
h
|
#ifndef RECARRAY_H
#define RECARRAY_H
#include <boost/property_tree/ptree.hpp>
typedef boost::property_tree::ptree RecursionArray;
namespace RecArrUtils
{
void printTree(const RecursionArray& tree, const std::string& prefix="");
char SlashReplaceEx(std::string* str, const unsigned int frist_pos);
RecursionArray fromArcan(const std::string& str);
std::string toArcan(const RecursionArray& tree);
//std::string toCfg(const RecursionArray& tree, const std::string& prefix="");
std::string printTreeEx(const RecursionArray& tree, const std::string& prefix="");
std::string IntToByte(int integer);
}
#endif // RECARRAY_H
|
[
"xellgf2013@ya.ru"
] |
xellgf2013@ya.ru
|
f6476ff0a8ad890f42e1efd892b9e2d86caa5f1d
|
e4d61a174008740024a537f18270d1e69c9d31f7
|
/day13a.cpp
|
f09e5d081d053f2d656114d689ee2dbd99b867f2
|
[
"MIT"
] |
permissive
|
Fossegrimen/advent-of-code-2020
|
0cf06326c9e792274584bddb08cf587c147f2eb5
|
d9323346c167435fe461214e9eae990a1940c78e
|
refs/heads/master
| 2023-02-04T23:29:08.250014
| 2020-12-26T15:54:25
| 2020-12-26T15:54:25
| 318,574,008
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,009
|
cpp
|
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
typedef std::vector<size_t> Vector;
int main()
{
Vector busIds;
std::string line;
std::getline(std::cin, line);
const size_t timeToLeave(stol(line));
std::getline(std::cin, line);
std::replace(line.begin(), line.end(), ',', ' ');
std::replace(line.begin(), line.end(), 'x', ' ');
std::stringstream _line(line);
size_t busId;
while (_line >> busId)
{
busIds.push_back(busId);
}
size_t value = 0;
size_t minDepartment = std::numeric_limits<size_t>::max();
for (size_t busId : busIds)
{
const size_t department = ceil((double)timeToLeave / busId) * busId;
if (department < minDepartment )
{
minDepartment = department;
value = (department - timeToLeave) * busId;
}
}
std::cout << value << std::endl;
return 0;
}
|
[
"68206123+Fossegrimen@users.noreply.github.com"
] |
68206123+Fossegrimen@users.noreply.github.com
|
b74f7d1df2b8a123851a36f3b654d85dccd7ec16
|
3a395f2afb3b7ba014665e3b43b62eb366e2ba27
|
/PapilioVCA.h
|
4b84e1412c334e6fba567d13f6e3b65711b777b6
|
[] |
no_license
|
Gaetino/PapilioGroovuino
|
e6c5f702131bee16ad30863a23281e7b6ad29270
|
0d7f2ea4187c98fcfa234da58e1e7c7f045a9e06
|
refs/heads/master
| 2021-01-22T03:05:18.118486
| 2014-01-17T13:10:55
| 2014-01-17T13:10:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 91
|
h
|
class VCA
{
public:
VCA();
long input_volume;
long output(long input_audio);
};
|
[
"gaith26740@yahoo.fr"
] |
gaith26740@yahoo.fr
|
6993b54a5f2be84e11896bf681c5e6d1b4b488bd
|
85ec0860a0a9f5c0c0f0d81ce3cc0baf4b2a812e
|
/sngcm/cmlexer/CmajorTokens.hpp
|
6589c53d65b15970c16bc1f9eb7923ff1a3e9b5f
|
[] |
no_license
|
slaakko/soulng
|
3218185dc808fba63e2574b3a158fa1a9f0b2661
|
a128a1190ccf71794f1bcbd420357f2c85fd75f1
|
refs/heads/master
| 2022-07-27T07:30:20.813581
| 2022-04-30T14:22:44
| 2022-04-30T14:22:44
| 197,632,580
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,852
|
hpp
|
#ifndef CmajorTokens_HPP
#define CmajorTokens_HPP
// this file has been automatically generated from 'D:/work/soulng-project/sngcm/cmlexer/CmajorLexer.lexer' using soulng lexer generator slg version 3.0.0
#include <sngcm/cmlexer/TokenValueParsers.hpp>
#include <sngcm/cmlexer/CmajorLexerApi.hpp>
#include <string>
namespace CmajorTokens
{
const int END = 0;
const int ASSERT = 1;
const int ELIF = 2;
const int ENDIF = 3;
const int BOOL = 4;
const int TRUE = 5;
const int FALSE = 6;
const int SBYTE = 7;
const int BYTE = 8;
const int SHORT = 9;
const int USHORT = 10;
const int INT = 11;
const int UINT = 12;
const int LONG = 13;
const int ULONG = 14;
const int FLOAT = 15;
const int DOUBLE = 16;
const int CHAR = 17;
const int WCHAR = 18;
const int UCHAR = 19;
const int VOID = 20;
const int ENUM = 21;
const int CAST = 22;
const int INTERFACE = 23;
const int NAMESPACE = 24;
const int USING = 25;
const int STATIC = 26;
const int EXTERN = 27;
const int AS = 28;
const int IS = 29;
const int EXPLICIT = 30;
const int DELEGATE = 31;
const int INLINE = 32;
const int CDECL = 33;
const int NOTHROW = 34;
const int PUBLIC = 35;
const int PROTECTED = 36;
const int PRIVATE = 37;
const int INTERNAL = 38;
const int VIRTUAL = 39;
const int ABSTRACT = 40;
const int OVERRIDE = 41;
const int SUPPRESS = 42;
const int WINAPI = 43;
const int OPERATOR = 44;
const int CLASS = 45;
const int RETURN = 46;
const int IF = 47;
const int ELSE = 48;
const int SWITCH = 49;
const int CASE = 50;
const int DEFAULT = 51;
const int WHILE = 52;
const int DO = 53;
const int FOR = 54;
const int BREAK = 55;
const int CONTINUE = 56;
const int GOTO = 57;
const int TYPEDEF = 58;
const int TYPENAME = 59;
const int TYPEID = 60;
const int CONST = 61;
const int CONSTEXPR = 62;
const int NULLLIT = 63;
const int THIS = 64;
const int BASE = 65;
const int CONSTRUCT = 66;
const int DESTROY = 67;
const int NEW = 68;
const int DELETE = 69;
const int SIZEOF = 70;
const int TRY = 71;
const int CATCH = 72;
const int THROW = 73;
const int CONCEPT = 74;
const int WHERE = 75;
const int AXIOM = 76;
const int AND = 77;
const int OR = 78;
const int EXCLAMATION = 79;
const int UNIT_TEST = 80;
const int ID = 81;
const int FLOATINGLIT = 82;
const int INTLIT = 83;
const int CHARLIT = 84;
const int STRINGLIT = 85;
const int EQUIVALENCE = 86;
const int IMPLICATION = 87;
const int DISJUNCTION = 88;
const int AMPAMP = 89;
const int BITOR = 90;
const int BITXOR = 91;
const int AMP = 92;
const int EQ = 93;
const int NEQ = 94;
const int LEQ = 95;
const int GEQ = 96;
const int SHIFTLEFT = 97;
const int SHIFTRIGHT = 98;
const int PLUS = 99;
const int MINUS = 100;
const int STAR = 101;
const int DIV = 102;
const int REM = 103;
const int PLUSPLUS = 104;
const int MINUSMINUS = 105;
const int CPL = 106;
const int DOT = 107;
const int ARROW = 108;
const int LBRACKET = 109;
const int RBRACKET = 110;
const int LPAREN = 111;
const int RPAREN = 112;
const int LANGLE = 113;
const int RANGLE = 114;
const int LBRACE = 115;
const int RBRACE = 116;
const int COMMA = 117;
const int ASSIGN = 118;
const int COLON = 119;
const int SEMICOLON = 120;
const int HASH = 121;
SNGCM_LEXER_API void InitTokenIdMap();
SNGCM_LEXER_API int GetTokenId(const std::u32string& tokenName);
SNGCM_LEXER_API const char* GetTokenName(int tokenId);
SNGCM_LEXER_API const char* GetTokenInfo(int tokenId);
}
#endif
|
[
"slaakko@gmail.com"
] |
slaakko@gmail.com
|
2fb0294571cff34146e0758e7faf68a769789c25
|
d071e6156cf23ddee37a612f71d71a650c27fcfe
|
/pojpass/poj1511_invitation.cpp
|
1606f42ae6e9582e7df1318a36cd2d633b93a44e
|
[] |
no_license
|
tsstss123/code
|
57f1f7d1a1bf68c47712897e2d8945a28e3e9862
|
e10795c35aac442345f84a58845ada9544a9c748
|
refs/heads/master
| 2021-01-24T23:00:08.749712
| 2013-04-30T12:33:24
| 2013-04-30T12:33:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,856
|
cpp
|
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LLONG;
const int NN = 1000000 + 5;
struct Edge {
int v, w;
Edge * next;
};
int nE, nAE;
Edge *head[NN], * Ahead[NN];
Edge E[NN], AE[NN];
void addEdge(int u, int v, int w)
{
Edge *e = E + nE++;
e->v = v;
e->w = w;
e->next = head[u];
head[u] = e;
e = AE + nAE++;
e->v = u;
e->w = w;
e->next = Ahead[v];
Ahead[v] = e;
}
bool vis[NN];
struct PVex {
int v;
LLONG w;
bool operator < (const PVex &B) const {
return w > B.w;
}
} pri_ord[NN];
void dijkstra(int n, int s, Edge *head[], LLONG len[])
{
memset(len, -1, sizeof(len[0]) * (n + 1));
memset(vis, 0, sizeof(vis[0]) * (n + 1));
len[s] = 0;
int cnt = 1;
pri_ord[0].v = s;
pri_ord[0].w = 0;
for (int i = 0; i < n; ++i) {
if (cnt <= 0) {
break;
}
int u = pri_ord[0].v;
pop_heap(pri_ord, pri_ord + cnt);
--cnt;
vis[u] = true;
for (Edge *e = head[u]; e; e = e->next) {
int v = e->v;
LLONG w = e->w;
if (!vis[v] && (len[v] == -1 || len[v] > len[u] + w)) {
len[v] = len[u] + w;
pri_ord[cnt].v = v;
pri_ord[cnt].w = len[v];
++cnt;
push_heap(pri_ord, pri_ord + cnt);
}
}
while (cnt > 0 && vis[pri_ord[0].v]) {
pop_heap(pri_ord, pri_ord + cnt);
--cnt;
}
}
}
LLONG len[NN], Alen[NN];
int main()
{
int nTest;
scanf("%d", &nTest);
while (nTest--) {
int n, q;
scanf("%d %d", &n, &q);
nE = nAE = 0;
memset(head, 0, sizeof(head[0]) * (n + 1));
memset(Ahead, 0, sizeof(Ahead[0]) * (n + 1));
for (int i = 0; i < q; ++i) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
addEdge(u, v, w);
}
dijkstra(n, 1, head, len);
dijkstra(n, 1, Ahead, Alen);
LLONG ans = 0;
for (int i = 1; i <= n; ++i) {
ans += len[i] + Alen[i];
}
printf("%lld\n", ans);
}
return 0;
}
|
[
"leon.acwa@gmail.com"
] |
leon.acwa@gmail.com
|
9ac5ae85d4d37e2c47799286278398a7a909ddda
|
6a2d869e34aad0a967beb7e2c2f30a74c4fbc596
|
/stmp/StmpTransInitiative.cpp
|
eba416a3420746fbb0052a573de162a830eaab18
|
[] |
no_license
|
ongbe/libfsc
|
6337cb7342acad46d6b48f266d4fddf12ea79067
|
96fc22bebbb1a568748f9c6656c2a6b7b784c4a6
|
refs/heads/master
| 2020-03-18T20:05:10.122882
| 2018-04-18T10:12:44
| 2018-04-18T10:12:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 301
|
cpp
|
/*
* StmpTransInitiative.cpp
*
* Created on: Jan 15, 2018
* Author: root
*/
#include "StmpTransInitiative.h"
StmpTransInitiative::StmpTransInitiative()
{
// TODO Auto-generated constructor stub
}
StmpTransInitiative::~StmpTransInitiative()
{
// TODO Auto-generated destructor stub
}
|
[
"zewenxu@fintend.com"
] |
zewenxu@fintend.com
|
bd24d93f07b0f9572a4b946cd67ded574e8e5555
|
d24cd235387eace08c7c61f5ef86f062192de5e0
|
/Source/SUB20HwModuleCtrlADCUnitDrv.cpp
|
6e93fe37303af31140805fddffb7bfe8b577ecba
|
[] |
no_license
|
asafl1976/MVTerminal
|
e02b149e32b1927e281167c20a20f15422762714
|
019fd753b704d21b1f3787395d1e61b9a1075dfe
|
refs/heads/master
| 2021-01-02T08:58:14.191737
| 2017-08-02T10:31:35
| 2017-08-02T10:31:35
| 99,104,278
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 623
|
cpp
|
#include "StdAfx.h"
#include ".\sub20hwmodulectrladcunitdrv.h"
CSUB20HwModuleCtrlADCUnitDrv::CSUB20HwModuleCtrlADCUnitDrv(CSUB20HwModuleCtrlDrv *pDrv)
{
m_pDrv = pDrv;
}
CSUB20HwModuleCtrlADCUnitDrv::~CSUB20HwModuleCtrlADCUnitDrv(void)
{
}
BOOL CSUB20HwModuleCtrlADCUnitDrv::Init()
{
return m_pDrv->ADCInit();
}
BOOL CSUB20HwModuleCtrlADCUnitDrv::GetVoltage(int nIndex, int* pVoltage)
{
return m_pDrv->GetVoltage(nIndex,pVoltage);
}
BOOL CSUB20HwModuleCtrlADCUnitDrv::GetCurrent(int nIndex,float nResistorVal, int* pCurrent)
{
return m_pDrv->GetCurrent(nIndex,nResistorVal,pCurrent);
}
|
[
"asafl1976@gmail.com"
] |
asafl1976@gmail.com
|
686f75a31f962310ee5c28b998bf0d0482888f3e
|
62d33fa0eca8c0145611cd0efe6e9c4d8bb8b378
|
/LeetCode/48.Rotate_Image.cpp
|
73114d3da15e44c2d520a44f429622d49bde8106
|
[
"MIT"
] |
permissive
|
yousefalaa2021/OJ
|
da085e3eba1c80b7998c471bd3aed71d774985f2
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
refs/heads/master
| 2023-03-15T20:16:56.439701
| 2019-05-01T11:29:10
| 2019-05-01T11:29:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 363
|
cpp
|
// 先對角線翻轉,再水平對稱
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
for(int i = 0; i < matrix.size(); ++i)
for(int j = 0; j < i; j++)
swap(matrix[i][j], matrix[j][i]);
for(int i = 0; i < matrix.size(); ++i)
reverse(matrix[i].begin(), matrix[i].end());
}
};
|
[
"w181496@gmail.com"
] |
w181496@gmail.com
|
3732a1418fe2268ab0c2c6e9c07d279a3a5b2284
|
32c71980153a2fa9e40329aafd9efff97ec7def1
|
/BT_Master_and_MPU6050.ino
|
42445f3ceac9db9f14bcff1087d4c7e73a439dc3
|
[] |
no_license
|
tunzbaby/Vong_deo_co_phat_hien_nga
|
89448d90f97f0a8cf18779cb7590723e3c2a36c3
|
a130c7a93bab3342081c73439a7cf0a363d7a7e4
|
refs/heads/main
| 2023-01-03T13:12:52.458304
| 2020-10-28T16:17:23
| 2020-10-28T16:17:23
| 308,072,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,362
|
ino
|
#include <SoftwareSerial.h>
SoftwareSerial BTserial(10, 11);
#include "I2Cdev.h"
#include "MPU6050.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
int state = 0;
MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;
uint32_t lastTime;
#define OUTPUT_READABLE_ACCELGYRO
#define ledbao 7
#define nutnhan 12
bool blinkState = false;
void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
BTserial.begin(38400);
Serial.begin(19200);
accelgyro.initialize();
//Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
pinMode(ledbao, OUTPUT);
pinMode(nutnhan, INPUT_PULLUP);
digitalWrite(ledbao, LOW);
}
void loop() {
// read raw accel/gyro measurements from device
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);
#ifdef OUTPUT_READABLE_ACCELGYRO
// Serial.print("a/g:\t");
/*
Serial.print(ax); Serial.print("\t");
Serial.print(ay); Serial.print("\t");
Serial.print(az); Serial.print("\t");
Serial.print(gx); Serial.print("\t");
Serial.print(gy); Serial.print("\t");
Serial.println(gz);
Serial.println(millis());
*/
#endif
#ifdef OUTPUT_BINARY_ACCELGYRO
Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
#endif
// Chuong trinh kiem tra nga
// Nga sang trai - 2019.12.21 - 8:08 PM | 3 gia tri x, y, z khi nga khao sat duoc 32767 11436 -25912
if(abs(ax) > 32000 && abs(ax) < 45000 && abs(ay) > 15000 && abs(ay) < 33000 && abs(az) > 16000 && abs(az) < 33000 ) // Khi de truc Y qua nho se lam canh bao de nhieu hon
{
BTserial.write('1');
Serial.println("Phat hien nga xay ra");
int button_val = 1;
lastTime = millis();
button_val = digitalRead(nutnhan);
while(millis() - lastTime < 5000)
{
digitalWrite(ledbao, HIGH);
button_val = digitalRead(nutnhan);
delay(50);
Serial.println(button_val);
if(!button_val) break;
}
if(!button_val){
Serial.println("Khong lam gi ca, nut da duoc nhan");
digitalWrite(ledbao, LOW);
delay(200);
}
else{
digitalWrite(ledbao, HIGH);
Serial.println("Canh bao da duoc gui");
// xem lai code phan nay de gui du lieu qua bluetooth
digitalWrite(ledbao, LOW);
}
}
delay(1);
}
|
[
"noreply@github.com"
] |
tunzbaby.noreply@github.com
|
3013cdc4d0829959b9169264c18916670dd831e3
|
d7f774ff0067abf6fccf37003afb47642b044120
|
/ui/AppWindow/MainWindowClient.h
|
47c4c460be0e84946ef628e9e09034c56b00cbe5
|
[] |
no_license
|
GitaiQAQ/cptf
|
25efbd79b076ddde4a034526d8af3436ef44ac62
|
6a3a956142703c9501045fcf18792d9ce9412f39
|
refs/heads/master
| 2021-01-18T16:56:21.944203
| 2014-01-23T06:36:14
| 2014-01-23T06:36:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 529
|
h
|
#pragma once
#include "include/cef_app.h"
#include "include/cef_client.h"
class MainWindowClient : public CefClient
, public CefLifeSpanHandler
{
public:
MainWindowClient(void);
~MainWindowClient(void);
public:
CefRefPtr<CefBrowser> getBrowser();
public://override
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler(){return this;}
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser);
public:
IMPLEMENT_REFCOUNTING(MainWindowClient);
private:
CefRefPtr<CefBrowser> browser_;
};
|
[
"s666666"
] |
s666666
|
eb05b7114a1b185cf8a55300ad7fed851b834430
|
d72c11581e23ac6141d2419d86d71a1d634dced5
|
/src/net.cpp
|
d55d90fd3ed405baebaf8552ed6e241244265caa
|
[
"MIT"
] |
permissive
|
OFCoin/OFCCoin
|
837e86d6def9044d67d6f83fcb6ac8c16f6ad11a
|
c95abc3dec6bf091e057326be149e1d5b3685124
|
refs/heads/master
| 2020-03-27T04:30:31.581715
| 2016-06-28T15:24:55
| 2016-06-28T15:24:55
| 61,849,632
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 60,820
|
cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The OFCCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "OFCCoin-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "core.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
//
// Global state variables
//
bool fDiscover = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
static CNode* pnodeSync = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore *semOutbound = NULL;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true)
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
boost::this_thread::interruption_point();
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
LogPrint("net", "socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
while (true)
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
LogPrintf("GetMyExternalIP() received [%s] %s\n", strLine, addr.ToString());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 1; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP()
{
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %s\n", NetworkErrorString(WSAGetLastError()));
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %s\n", NetworkErrorString(errno));
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
LogPrint("net", "disconnecting node %s\n", addrName);
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = NULL;
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), addr.ToString());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
}
std::map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Ban(const CNetAddr &addr) {
int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
return true;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
stats.fSyncNode = (this == pnodeSync);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (OFCCoin users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
vRecv.resize(hdr.nMessageSize);
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true)
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if(vNodes.size() != nPrevNodeCount) {
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (
pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
closesocket(hSocket);
}
else if (CNode::IsBanned(addr))
{
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
closesocket(hSocket);
}
else
{
LogPrint("net", "accepted connection %s\n", addr.ToString());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
LogPrint("net", "socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
LogPrintf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
LogPrintf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "OFCCoin " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");;
MilliSleep(20*60*1000); // Refresh every 20 minutes
}
}
catch (boost::thread_interrupted)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
vector<CNetAddr> vIPs;
vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs))
{
BOOST_FOREACH(CNetAddr& ip, vIPs)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64_t nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true)
{
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true)
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while(true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH(string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++)
{
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, lAddresses)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
{
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
CNode* pnode = ConnectNode(addrConnect, strDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
// for now, use a very simple selection metric: the node from which we received
// most recently
static int64_t NodeSyncScore(const CNode *pnode) {
return pnode->nLastRecv;
}
void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
int64_t nBestScore = 0;
int nBestHeight = g_signals.GetHeight().get_value_or(0);
// Iterate over all nodes
BOOST_FOREACH(CNode* pnode, vNodes) {
// check preconditions for allowing a sync
if (!pnode->fClient && !pnode->fOneShot &&
!pnode->fDisconnect && pnode->fSuccessfullyConnected &&
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
int64_t nScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || nScore > nBestScore) {
pnodeNewSync = pnode;
nBestScore = nScore;
}
}
}
// if a new sync candidate was found, start sync!
if (pnodeNewSync) {
pnodeNewSync->fStartSync = true;
pnodeSync = pnodeNewSync;
}
}
void ThreadMessageHandler()
{
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true)
{
bool fHaveSyncNode = false;
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy) {
pnode->AddRef();
if (pnode == pnodeSync)
fHaveSyncNode = true;
}
}
if (!fHaveSyncNode)
StartSync(vNodesCopy);
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize())
{
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
{
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
MilliSleep(100);
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. OFCCoin Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString());
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "ext-ip", &ThreadGetMyExternalIP));
}
void StartNode(boost::thread_group& threadGroup)
{
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
#ifdef USE_UPNP
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", USE_UPNP));
#endif
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
LogPrintf("closesocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
BOOST_FOREACH(CNode *pnode, vNodes)
delete pnode;
BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter)
{
if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3))
{
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin()+pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin()+pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
RAND_bytes((unsigned char *)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open temp output file, and associate with CAutoFile
boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
FILE *file = fopen(pathTmp.string().c_str(), "wb");
CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("%s : Failed to open file %s", __func__, pathTmp.string());
// Write and commit header, data
try {
fileout << ssPeers;
}
catch (std::exception &e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout);
fileout.fclose();
// replace existing peers.dat, if any, with new peers.dat.XXXX
if (!RenameOver(pathTmp, pathAddr))
return error("%s : Rename-into-place failed", __func__);
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE *file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
if (!filein)
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathAddr);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
}
catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
|
[
"2069422310@qq.com"
] |
2069422310@qq.com
|
3ba4d78d125662170afa27fa84f21f685878fd0d
|
96e96a73920734376fd5c90eb8979509a2da25c0
|
/C3DE/GuiCon.cpp
|
c4cbd3cb09a1d855503b85b607267aa62c697bf1
|
[] |
no_license
|
lianlab/c3de
|
9be416cfbf44f106e2393f60a32c1bcd22aa852d
|
a2a6625549552806562901a9fdc083c2cacc19de
|
refs/heads/master
| 2020-04-29T18:07:16.973449
| 2009-11-15T10:49:36
| 2009-11-15T10:49:36
| 32,124,547
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,667
|
cpp
|
#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#ifndef _USE_OLD_IOSTREAMS
using namespace std;
#endif
// maximum mumber of lines the output console should have
static const WORD MAX_CONSOLE_LINES = 500;
#ifdef _DEBUG
void RedirectIOToConsole()
{
int hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
&coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
coninfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
ios::sync_with_stdio();
}
#endif
//End of File
|
[
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
] |
caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158
|
6648078b9a58550ba20398baa88bcc79aac0d5e6
|
6afeef38988aec261b5f73e195f1a4335613825e
|
/代码/L12 终版本/GameMode.h
|
7b2b58c64efece4b0cc422a75d95a991ee23e353
|
[
"MIT"
] |
permissive
|
ConsoleTank/ConsoleTank
|
ed7c338af1cdc9e66ca2728833dabecf57cc1e4e
|
d488532ce8d9b14013d3ab124598abb2f7e67014
|
refs/heads/master
| 2020-12-10T07:42:32.794815
| 2020-01-17T10:24:43
| 2020-01-17T10:24:43
| 233,537,229
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 943
|
h
|
#ifndef __GAMEMODE_HPP__
#define __GAMEMODE_HPP__
#include "Common.h"
#include "tools.hpp"
#include "Map.hpp"
#include <time.h>
class Tank;
class BaseCamp;
class GameMode
{
private:
static GameMode s_instance;
public:
static GameMode& instance();
void welcome();
bool Init();
bool finish();
void Tick();
void Mode_editor();
void Mode_editor_paint_info();
void single_player();
void double_player();
void OnMouse(INPUT_RECORD mouseRec);
void OnKeyBoard_Editor(INPUT_RECORD mouseRec);
void ReturnToMainMenu();
void OnKeyBoard_Menu(char ch);
void OnMouseClick(int x, int y);
private:
void _battle();
public:
Map* m_pmap;
int cur_sel = 0;
bool if_in_game = false;
int draw_type = Common::WALL;
bool running = true;
Tank *tank01;
Tank *tank02;
BaseCamp * camp;
list<Tank*> tanks;
bool gameOver = false;
clock_t nt_back;
};
#endif // __GAMEMODE_HPP__
|
[
"fyc@time-vr.com"
] |
fyc@time-vr.com
|
7d83b6cc4d33ed82b0b9fdff3af057c02720ee25
|
341ababeb44bdffbf693663bda06de566e393594
|
/tests/gt_ble.cc
|
cb3832be9ed19b93019ec54d768a4a57b8b6b2aa
|
[] |
no_license
|
pabigot/pabigot-cxx
|
bce52719997f22f40961f08b4a4694e76721a47a
|
2f9b1940d07aa832be64939dd03f3b25a34288eb
|
refs/heads/master
| 2020-04-28T11:37:48.180418
| 2019-03-13T10:41:52
| 2019-03-13T10:43:45
| 175,248,825
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,303
|
cc
|
// SPDX-License-Identifier: CC-BY-SA-4.0
// Copyright 2018-2019 Peter A. Bigot
#include <algorithm>
#include <gtest/gtest.h>
#include <pabigot/ble.hpp>
std::string operator"" _s (const char* p, size_t n)
{
return std::string(p, n);
}
#define BLE_GAP_ADV_MAX_SIZE 31
#define UUID16_BRACE_INITIALIZER {0x34, 0x12}
#define UUID32_BRACE_INITIALIZER {0x78, 0x56, 0x34, 0x12}
#define UUID128_BRACE_INITIALIZER { \
0x56, 0x55, 0x54, 0x53, \
0x52, 0x51, 0x42, 0x41, \
0x32, 0x31, 0x22, 0x21, \
0x14, 0x13, 0x12, 0x11, \
}
namespace {
TEST(clkType, count)
{
using namespace pabigot::ble;
using namespace std::literals::chrono_literals;
ASSERT_EQ(std::chrono::duration_cast<clk1_type>(625us).count(), 1U);
ASSERT_EQ(std::chrono::duration_cast<clk1_type>(1250us).count(), 2U);
ASSERT_EQ(std::chrono::duration_cast<clk2_type>(1250us).count(), 1U);
ASSERT_EQ(std::chrono::duration_cast<clk2_type>(10ms).count(), 8U);
ASSERT_EQ(std::chrono::duration_cast<clk5_type>(10ms).count(), 1U);
ASSERT_EQ(std::chrono::duration_cast<clk5_type>(200ms).count(), 20U);
}
// Expect little-endian storage of 0x1234
void match16_1234 (const pabigot::ble::uuid16_type& u16)
{
ASSERT_EQ(u16[0], 0x34);
ASSERT_EQ(u16[1], 0x12);
}
TEST(BLE, uuid16)
{
using namespace pabigot::ble;
SCOPED_TRACE("uuid16_type ctors");
#define BRACE_INITIALIZER UUID16_BRACE_INITIALIZER
{ // default
uuid16_type u16;
ASSERT_EQ(u16[0], 0x00);
ASSERT_EQ(u16[1], 0x00);
}
{ // from const built-in array
const uint8_t raw[] = BRACE_INITIALIZER;
uuid16_type u16{raw};
}
{ // from mutable built-in array
uint8_t raw[] = BRACE_INITIALIZER;
match16_1234(uuid16_type{raw});
}
{ // from const std::array instance
const std::array<uint8_t, 2> arr = BRACE_INITIALIZER;
match16_1234(uuid16_type{arr});
}
{ // from mutable std::array instance
std::array<uint8_t, 2> arr = BRACE_INITIALIZER;
match16_1234(uuid16_type{arr});
}
{ // from/to compatible integer literal
uint16_t v16{0x1234};
uuid16_type u16{v16};
match16_1234(u16);
ASSERT_EQ(v16, u16.as_integer());
auto u16b = u16;
ASSERT_TRUE(std::equal(u16b.begin(), u16b.end(), u16.begin()));
}
{ // from/to text
uint16_t v16{0x1AB2};
uuid16_type u16{v16};
ASSERT_EQ(u16.as_string(), "1ab2"_s);
}
#if (WILL_ERROR - 0)
{ // from incompatible integer literal (narrowing)
uuid16_type u16{0x123456};
ASSERT_EQ(u16[0], 0x56);
ASSERT_EQ(u16[1], 0x34);
auto u16b = u16;
ASSERT_TRUE(std::equal(u16b.begin(), u16b.end(), u16.begin()));
}
#endif
#undef BRACE_INITIALIZER
}
// Expect little-endian storage of 0x12345678
void match32_1234 (const pabigot::ble::uuid32_type& u32)
{
ASSERT_EQ(u32[0], 0x78);
ASSERT_EQ(u32[1], 0x56);
ASSERT_EQ(u32[2], 0x34);
ASSERT_EQ(u32[3], 0x12);
}
TEST(BLE, uuid32)
{
using namespace pabigot::ble;
SCOPED_TRACE("uuid32_type ctors");
#define BRACE_INITIALIZER UUID32_BRACE_INITIALIZER
{ // default
uuid32_type u32;
ASSERT_EQ(u32[0], 0x00);
ASSERT_EQ(u32[1], 0x00);
ASSERT_EQ(u32[2], 0x00);
ASSERT_EQ(u32[3], 0x00);
}
{ // from const built-in array
const uint8_t raw[] = BRACE_INITIALIZER;
match32_1234(raw);
}
{ // from mutable built-in array
uint8_t raw[] = BRACE_INITIALIZER;
match32_1234(raw);
}
{ // from const std::array instance
const std::array<uint8_t, 4> arr = BRACE_INITIALIZER;
match32_1234(arr);
}
{ // from mutable std::array instance
std::array<uint8_t, 4> arr = BRACE_INITIALIZER;
match32_1234(arr);
}
{ // from compatible integer literal
const uint32_t lit = 0x12345678;
uuid32_type u32{lit};
match32_1234(u32);
ASSERT_EQ(lit, u32.as_integer());
auto u32b = u32;
ASSERT_TRUE(std::equal(u32b.begin(), u32b.end(), u32.begin()));
}
{ // from/to text
uint32_t v32{0x1ABCDEF4};
uuid32_type u32{v32};
ASSERT_EQ(u32.as_string(), "1abcdef4"_s);
}
#undef BRACE_INITIALIZER
}
TEST(BLE, uuid128)
{
using namespace pabigot::ble;
ASSERT_STREQ("00000000-0000-1000-8000-00805f9b34fb", uuid128_type::BLUETOOTH_BASE.as_string().c_str());
#define BRACE_INITIALIZER UUID128_BRACE_INITIALIZER
{ // default
const uint8_t zeroed[16] = {};
uuid128_type u128;
ASSERT_TRUE(std::equal(u128.begin(), u128.end(), zeroed));
}
{ // from const built-in array
const uint8_t raw[] = BRACE_INITIALIZER;
uuid128_type u128{raw};
ASSERT_TRUE(std::equal(u128.begin(), u128.end(), raw));
ASSERT_STREQ("11121314-2122-3132-4142-515253545556", u128.as_string().c_str());
}
{ // from mutable built-in array
uint8_t raw[] = BRACE_INITIALIZER;
uuid128_type u128{raw};
ASSERT_TRUE(std::equal(u128.begin(), u128.end(), raw));
}
{ // from const std::array instance
const std::array<uint8_t, 16> arr = BRACE_INITIALIZER;
uuid128_type u128{arr};
ASSERT_TRUE(std::equal(u128.begin(), u128.end(), arr.data()));
}
{ // from mutable std::array instance
std::array<uint8_t, 16> arr = BRACE_INITIALIZER;
uuid128_type u128{arr};
ASSERT_TRUE(std::equal(u128.begin(), u128.end(), arr.data()));
}
{ // Derived 16-bit UUIDs and base match */
uuid128_type u128{BRACE_INITIALIZER};
ASSERT_STREQ("11121314-2122-3132-4142-515253545556", u128.as_string().c_str());
uint16_t uuid{0xABCD};
auto u16 = u128.from_uuid16(uuid);
ASSERT_STREQ("1112abcd-2122-3132-4142-515253545556", u16.as_string().c_str());
ASSERT_EQ(uuid, u16.uuid16());
ASSERT_TRUE(u128.base_match(u16));
ASSERT_TRUE(u16.base_match(u128));
u16[14] = 0x00;
ASSERT_STREQ("1100abcd-2122-3132-4142-515253545556", u16.as_string().c_str());
ASSERT_FALSE(u128.base_match(u16));
u16[14] = 0x12;
u16[11] = 0x00;
ASSERT_STREQ("1112abcd-0022-3132-4142-515253545556", u16.as_string().c_str());
ASSERT_FALSE(u128.base_match(u16));
}
{ // Reversing the UUID
uuid128_type u128{BRACE_INITIALIZER};
ASSERT_STREQ("11121314-2122-3132-4142-515253545556", u128.as_string().c_str());
auto r128 = u128.swap_endian();
ASSERT_STREQ("56555453-5251-4241-3231-222114131211", r128.as_string().c_str());
}
#undef BRACE_INITIALIZER
}
} // ns anonymous
|
[
"pab@pabigot.com"
] |
pab@pabigot.com
|
7bec824c131f6d4b78ca709c665fa7a87b9d0db1
|
0a3e06930e0a9889b6de7974581fbda24f538624
|
/tb_base_driver/src/iRobot/OpenInterface.cpp
|
b4e1e4ce65e242672eab227d805bb126a127c5d2
|
[] |
no_license
|
robofit/turtlebut
|
e054f26b0be94814602ecc11be9d6f411d0ce53d
|
24fc33eed23eb45c587ce19d2929ceb826ad41f7
|
refs/heads/master
| 2021-01-19T07:03:24.602212
| 2014-05-05T09:41:59
| 2014-05-05T09:41:59
| 9,325,522
| 2
| 1
| null | 2014-05-05T09:42:00
| 2013-04-09T16:11:45
|
C++
|
UTF-8
|
C++
| false
| false
| 41,779
|
cpp
|
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, ISR University of Coimbra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the ISR University of Coimbra nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Gonçalo Cabrita on 19/05/2010
*********************************************************************/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <string>
#include <netinet/in.h>
#include <sys/types.h>
#include "tb_base_driver/OpenInterface.h"
// *****************************************************************************
// Constructor
irobot::OpenInterface::OpenInterface(const char * new_serial_port)
{
port_name_ = new_serial_port;
OImode_ = OI_MODE_OFF;
this->resetOdometry();
encoder_counts_[LEFT] = -1;
encoder_counts_[RIGHT] = -1;
last_encoder_counts_[LEFT] = 0;
last_encoder_counts_[RIGHT] = 0;
num_of_packets_ = 0;
sensor_packets_ = NULL;
packets_size_ = 0;
// Default packets
OI_Packet_ID default_packets[2] = {OI_PACKET_RIGHT_ENCODER, OI_PACKET_LEFT_ENCODER};
this->setSensorPackets(default_packets, 2, OI_PACKET_RIGHT_ENCODER_SIZE + OI_PACKET_LEFT_ENCODER_SIZE);
serial_port_ = new cereal::CerealPort();
}
// *****************************************************************************
// Destructor
irobot::OpenInterface::~OpenInterface()
{
// Clean up!
delete serial_port_;
}
// *****************************************************************************
// Open the serial port
int irobot::OpenInterface::openSerialPort(bool full_control)
{
try{ serial_port_->open(port_name_.c_str(), 115200); }
catch(cereal::Exception& e){ return(-1); }
this->startOI(full_control);
return(0);
}
// *****************************************************************************
// Set the mode
int irobot::OpenInterface::startOI(bool full_control)
{
char buffer[1];
usleep(OI_DELAY_MODECHANGE_MS * 1e3);
buffer[0] = (char)OI_OPCODE_START;
try{ serial_port_->write(buffer, 1); }
catch(cereal::Exception& e){ return(-1); }
OImode_ = OI_MODE_PASSIVE;
usleep(OI_DELAY_MODECHANGE_MS * 1e3);
buffer[0] = (char)OI_OPCODE_CONTROL;
try{ serial_port_->write(buffer, 1); }
catch(cereal::Exception& e){ return(-1); }
OImode_ = OI_MODE_SAFE;
if(full_control)
{
usleep(OI_DELAY_MODECHANGE_MS * 1e3);
buffer[0] = (char)OI_OPCODE_FULL;
try{ serial_port_->write(buffer, 1); }
catch(cereal::Exception& e){ return(-1); }
OImode_ = OI_MODE_FULL;
}
return(0);
}
// *****************************************************************************
// Close the serial port
int irobot::OpenInterface::closeSerialPort()
{
this->drive(0.0, 0.0);
usleep(OI_DELAY_MODECHANGE_MS * 1e3);
try{ serial_port_->close(); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Send an OP code to the roomba
int irobot::OpenInterface::sendOpcode(OI_Opcode code)
{
char to_send = code;
try{ serial_port_->write(&to_send, 1); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Power down the roomba
int irobot::OpenInterface::powerDown()
{
return sendOpcode(OI_OPCODE_POWER);
}
// *****************************************************************************
// Set the speeds
int irobot::OpenInterface::drive(double linear_speed, double angular_speed)
{
int left_speed_mm_s = (int)((linear_speed-ROOMBA_AXLE_LENGTH*angular_speed/2)*1e3); // Left wheel velocity in mm/s
int right_speed_mm_s = (int)((linear_speed+ROOMBA_AXLE_LENGTH*angular_speed/2)*1e3); // Right wheel velocity in mm/s
return this->driveDirect(left_speed_mm_s, right_speed_mm_s);
}
// *****************************************************************************
// Set the motor speeds
int irobot::OpenInterface::driveDirect(int left_speed, int right_speed)
{
// Limit velocity
int16_t left_speed_mm_s = MAX(left_speed, -ROOMBA_MAX_LIN_VEL_MM_S);
left_speed_mm_s = MIN(left_speed, ROOMBA_MAX_LIN_VEL_MM_S);
int16_t right_speed_mm_s = MAX(right_speed, -ROOMBA_MAX_LIN_VEL_MM_S);
right_speed_mm_s = MIN(right_speed, ROOMBA_MAX_LIN_VEL_MM_S);
// Compose comand
char cmd_buffer[5];
cmd_buffer[0] = (char)OI_OPCODE_DRIVE_DIRECT;
cmd_buffer[1] = (char)(right_speed_mm_s >> 8);
cmd_buffer[2] = (char)(right_speed_mm_s & 0xFF);
cmd_buffer[3] = (char)(left_speed_mm_s >> 8);
cmd_buffer[4] = (char)(left_speed_mm_s & 0xFF);
try{ serial_port_->write(cmd_buffer, 5); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the motor PWMs
int irobot::OpenInterface::drivePWM(int left_pwm, int right_pwm)
{
// TODO: Not yet implemented... Doesnt really matter.
return(-1);
}
// *****************************************************************************
// Set the brushes motors status
int irobot::OpenInterface::brushes(unsigned char side_brush, unsigned char vacuum, unsigned char main_brush, unsigned char side_brush_clockwise, unsigned char main_brush_dir)
{
unsigned char cmd_buffer[2];
cmd_buffer[0] = OI_OPCODE_MOTORS;
cmd_buffer[1] = side_brush | vacuum<<1 | main_brush<<2 | side_brush_clockwise<<3 | main_brush_dir<<4;
try{ serial_port_->write((char*)cmd_buffer, 2); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the brushes motors PWMs
int irobot::OpenInterface::brushesPWM(char main_brush, char side_brush, char vacuum)
{
char cmd_buffer[4];
cmd_buffer[0] = (char)OI_OPCODE_PWM_MOTORS;
cmd_buffer[1] = main_brush;
cmd_buffer[2] = side_brush;
cmd_buffer[3] = vacuum<0 ? 0 : vacuum;
try{ serial_port_->write(cmd_buffer, 4); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the sensors to read
int irobot::OpenInterface::setSensorPackets(OI_Packet_ID * new_sensor_packets, int new_num_of_packets, size_t new_buffer_size)
{
if(sensor_packets_ == NULL)
{
delete [] sensor_packets_;
}
num_of_packets_ = new_num_of_packets;
sensor_packets_ = new OI_Packet_ID[num_of_packets_];
for(int i=0 ; i<num_of_packets_ ; i++)
{
sensor_packets_[i] = new_sensor_packets[i];
}
stream_defined_ = false;
packets_size_ = new_buffer_size;
return(0);
}
// *****************************************************************************
// Read the sensors
int irobot::OpenInterface::getSensorPackets(int timeout)
{
char cmd_buffer[num_of_packets_+2];
char data_buffer[packets_size_];
// Fill in the command buffer to send to the robot
cmd_buffer[0] = (char)OI_OPCODE_QUERY; // Query
cmd_buffer[1] = num_of_packets_; // Number of packets
for(int i=0 ; i<num_of_packets_ ; i++)
{
cmd_buffer[i+2] = sensor_packets_[i]; // The packet IDs
}
try{ serial_port_->write(cmd_buffer, num_of_packets_+2); }
catch(cereal::Exception& e){ return(-1); }
try{ serial_port_->readBytes(data_buffer, packets_size_, timeout); }
catch(cereal::Exception& e){ return(-1); }
return this->parseSensorPackets((unsigned char*)data_buffer, packets_size_);
}
// *****************************************************************************
// Read the sensors stream
int irobot::OpenInterface::streamSensorPackets()
{
char data_buffer[packets_size_];
if(!stream_defined_)
{
char cmd_buffer[num_of_packets_+2];
// Fill in the command buffer to send to the robot
cmd_buffer[0] = (char)OI_OPCODE_STREAM; // Stream
cmd_buffer[1] = num_of_packets_; // Number of packets
for(int i=0 ; i<num_of_packets_ ; i++)
{
cmd_buffer[i+2] = sensor_packets_[i]; // The packet IDs
}
try{ serial_port_->write(cmd_buffer, num_of_packets_+2); }
catch(cereal::Exception& e){ return(-1); }
stream_defined_ = true;
}
try{ serial_port_->readBytes(data_buffer, packets_size_, 100); }
catch(cereal::Exception& e){ return(-1); }
return this->parseSensorPackets((unsigned char*)data_buffer, packets_size_);
}
int irobot::OpenInterface::startStream()
{
char data_buffer[2];
data_buffer[0] = OI_OPCODE_PAUSE_RESUME_STREAM;
data_buffer[1] = 1;
try{ serial_port_->write(data_buffer, 2); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
int irobot::OpenInterface::stopStream()
{
char data_buffer[2];
data_buffer[0] = OI_OPCODE_PAUSE_RESUME_STREAM;
data_buffer[1] = 0;
try{ serial_port_->write(data_buffer, 2); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Parse sensor data
int irobot::OpenInterface::parseSensorPackets(unsigned char * buffer , size_t buffer_lenght)
{
if(buffer_lenght != packets_size_)
{
// Error wrong packet size
return(-1);
}
int i = 0;
unsigned int index = 0;
while(index < packets_size_)
{
if(sensor_packets_[i]==OI_PACKET_GROUP_0) // PACKETS 7-26
{
index += parseBumpersAndWheeldrops(buffer, index);
index += parseWall(buffer, index);
index += parseLeftCliff(buffer, index);
index += parseFrontLeftCliff(buffer, index);
index += parseFrontRightCliff(buffer, index);
index += parseRightCliff(buffer, index);
index += parseVirtualWall(buffer, index);
index += parseOvercurrents(buffer, index);
index += parseDirtDetector(buffer, index);
index ++; // Unused byte
index += parseIrOmniChar(buffer, index);
index += parseButtons(buffer, index);
index += parseDistance(buffer, index);
index += parseAngle(buffer, index);
index += parseChargingState(buffer, index);
index += parseVoltage(buffer, index);
index += parseCurrent(buffer, index);
index += parseTemperature(buffer, index);
index += parseBatteryCharge(buffer, index);
index += parseBatteryCapacity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_1) // PACKETS 7-16
{
index += parseBumpersAndWheeldrops(buffer, index);
index += parseWall(buffer, index);
index += parseLeftCliff(buffer, index);
index += parseFrontLeftCliff(buffer, index);
index += parseFrontRightCliff(buffer, index);
index += parseRightCliff(buffer, index);
index += parseVirtualWall(buffer, index);
index += parseOvercurrents(buffer, index);
index += parseDirtDetector(buffer, index);
index ++; // Unused byte
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_2) // PACKETS 17-20
{
index += parseIrOmniChar(buffer, index);
index += parseButtons(buffer, index);
index += parseDistance(buffer, index);
index += parseAngle(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_3) // PACKETS 21-26
{
index += parseChargingState(buffer, index);
index += parseVoltage(buffer, index);
index += parseCurrent(buffer, index);
index += parseTemperature(buffer, index);
index += parseBatteryCharge(buffer, index);
index += parseBatteryCapacity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_4) // PACKETS 27-34
{
index += parseWallSignal(buffer, index);
index += parseLeftCliffSignal(buffer, index);
index += parseFrontLeftCliffSignal(buffer, index);
index += parseFontRightCliffSignal(buffer, index);
index += parseRightCliffSignal(buffer, index);
index += 3; // Unused bytes
index += parseChargingSource(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_5) // PACKETS 35-42
{
index += parseOiMode(buffer, index);
index += parseSongNumber(buffer, index);
index += parseSongPlaying(buffer, index);
index += parseNumberOfStreamPackets(buffer, index);
index += parseRequestedVelocity(buffer, index);
index += parseRequestedRadius(buffer, index);
index += parseRequestedRightVelocity(buffer, index);
index += parseRequestedLeftVelocity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_6) // PACKETS 7-42
{
index += parseBumpersAndWheeldrops(buffer, index);
index += parseWall(buffer, index);
index += parseLeftCliff(buffer, index);
index += parseFrontLeftCliff(buffer, index);
index += parseFrontRightCliff(buffer, index);
index += parseRightCliff(buffer, index);
index += parseVirtualWall(buffer, index);
index += parseOvercurrents(buffer, index);
index += parseDirtDetector(buffer, index);
index ++; // Unused byte
index += parseIrOmniChar(buffer, index);
index += parseButtons(buffer, index);
index += parseDistance(buffer, index);
index += parseAngle(buffer, index);
index += parseChargingState(buffer, index);
index += parseVoltage(buffer, index);
index += parseCurrent(buffer, index);
index += parseTemperature(buffer, index);
index += parseBatteryCharge(buffer, index);
index += parseBatteryCapacity(buffer, index);
index += parseWallSignal(buffer, index);
index += parseLeftCliffSignal(buffer, index);
index += parseFrontLeftCliffSignal(buffer, index);
index += parseFontRightCliffSignal(buffer, index);
index += parseRightCliffSignal(buffer, index);
index += 3; // Unused bytes
index += parseChargingSource(buffer, index);
index += parseOiMode(buffer, index);
index += parseSongNumber(buffer, index);
index += parseSongPlaying(buffer, index);
index += parseNumberOfStreamPackets(buffer, index);
index += parseRequestedVelocity(buffer, index);
index += parseRequestedRadius(buffer, index);
index += parseRequestedRightVelocity(buffer, index);
index += parseRequestedLeftVelocity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_BUMPS_DROPS)
{
index += parseBumpersAndWheeldrops(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_WALL)
{
index += parseWall(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_LEFT)
{
index += parseLeftCliff(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_FRONT_LEFT)
{
index += parseFrontLeftCliff(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_FRONT_RIGHT)
{
index += parseFrontRightCliff(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_RIGHT)
{
index += parseRightCliff(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_VIRTUAL_WALL)
{
index += parseVirtualWall(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_WHEEL_OVERCURRENTS)
{
index += parseOvercurrents(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_DIRT_DETECT)
{
index += parseDirtDetector(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_IR_CHAR_OMNI)
{
index += parseIrOmniChar(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_BUTTONS)
{
index += parseButtons(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_DISTANCE)
{
index += parseDistance(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_ANGLE)
{
index += parseAngle(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CHARGING_STATE)
{
index += parseChargingState(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_VOLTAGE)
{
index += parseVoltage(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CURRENT)
{
index += parseCurrent(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_TEMPERATURE)
{
index += parseTemperature(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_BATTERY_CHARGE)
{
index += parseBatteryCharge(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_BATTERY_CAPACITY)
{
index += parseBatteryCapacity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_WALL_SIGNAL)
{
index += parseWallSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_LEFT_SIGNAL)
{
index += parseLeftCliffSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_FRONT_LEFT_SIGNAL)
{
index += parseFrontLeftCliffSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_FRONT_RIGHT_SIGNAL)
{
index += parseFontRightCliffSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CLIFF_RIGHT_SIGNAL)
{
index += parseRightCliffSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_CHARGE_SOURCES)
{
index += parseChargingSource(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_OI_MODE)
{
index += parseOiMode(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_SONG_NUMBER)
{
index += parseSongNumber(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_SONG_PLAYING)
{
index += parseSongPlaying(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_STREAM_PACKETS)
{
index += parseNumberOfStreamPackets(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_REQ_VELOCITY)
{
index += parseRequestedVelocity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_REQ_RADIUS)
{
index += parseRequestedRadius(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_REQ_RIGHT_VELOCITY)
{
index += parseRequestedRightVelocity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_REQ_LEFT_VELOCITY)
{
index += parseRequestedLeftVelocity(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_RIGHT_ENCODER)
{
index += parseRightEncoderCounts(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LEFT_ENCODER)
{
index += parseLeftEncoderCounts(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER)
{
index += parseLightBumper(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_LEFT)
{
index += parseLightBumperLeftSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_FRONT_LEFT)
{
index += parseLightBumperFrontLeftSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_CENTER_LEFT)
{
index += parseLightBumperCenterLeftSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_CENTER_RIGHT)
{
index += parseLightBumperCenterRightSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_FRONT_RIGHT)
{
index += parseLightBumperFrontRightSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LIGHT_BUMPER_RIGHT)
{
index += parseLightBumperRightSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_IR_CHAR_LEFT)
{
index += parseIrCharLeft(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_IR_CHAR_RIGHT)
{
index += parseIrCharRight(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_LEFT_MOTOR_CURRENT)
{
index += parseLeftMotorCurrent(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_RIGHT_MOTOR_CURRENT)
{
index += parseRightMotorCurrent(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_BRUSH_MOTOR_CURRENT)
{
index += parseMainBrushMotorCurrent(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_SIDE_BRUSH_MOTOR_CURRENT)
{
index += parseSideBrushMotorCurrent(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_STASIS)
{
index += parseStasis(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_100) // PACKETS 7-58
{
index += parseBumpersAndWheeldrops(buffer, index);
index += parseWall(buffer, index);
index += parseLeftCliff(buffer, index);
index += parseFrontLeftCliff(buffer, index);
index += parseFrontRightCliff(buffer, index);
index += parseRightCliff(buffer, index);
index += parseVirtualWall(buffer, index);
index += parseOvercurrents(buffer, index);
index += parseDirtDetector(buffer, index);
index ++; // Unused byte
index += parseIrOmniChar(buffer, index);
index += parseButtons(buffer, index);
index += parseDistance(buffer, index);
index += parseAngle(buffer, index);
index += parseChargingState(buffer, index);
index += parseVoltage(buffer, index);
index += parseCurrent(buffer, index);
index += parseTemperature(buffer, index);
index += parseBatteryCharge(buffer, index);
index += parseBatteryCapacity(buffer, index);
index += parseWallSignal(buffer, index);
index += parseLeftCliffSignal(buffer, index);
index += parseFrontLeftCliffSignal(buffer, index);
index += parseFontRightCliffSignal(buffer, index);
index += parseRightCliffSignal(buffer, index);
index += 3; // Unused bytes
index += parseChargingSource(buffer, index);
index += parseOiMode(buffer, index);
index += parseSongNumber(buffer, index);
index += parseSongPlaying(buffer, index);
index += parseNumberOfStreamPackets(buffer, index);
index += parseRequestedVelocity(buffer, index);
index += parseRequestedRadius(buffer, index);
index += parseRequestedRightVelocity(buffer, index);
index += parseRequestedLeftVelocity(buffer, index);
index += parseRightEncoderCounts(buffer, index);
index += parseLeftEncoderCounts(buffer, index);
index += parseLightBumper(buffer, index);
index += parseLightBumperLeftSignal(buffer, index);
index += parseLightBumperFrontLeftSignal(buffer, index);
index += parseLightBumperCenterLeftSignal(buffer, index);
index += parseLightBumperCenterRightSignal(buffer, index);
index += parseLightBumperFrontRightSignal(buffer, index);
index += parseLightBumperRightSignal(buffer, index);
index += parseIrCharLeft(buffer, index);
index += parseIrCharRight(buffer, index);
index += parseLeftMotorCurrent(buffer, index);
index += parseRightMotorCurrent(buffer, index);
index += parseMainBrushMotorCurrent(buffer, index);
index += parseSideBrushMotorCurrent(buffer, index);
index += parseStasis(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_101) // PACKETS 43-58
{
index += parseRightEncoderCounts(buffer, index);
index += parseLeftEncoderCounts(buffer, index);
index += parseLightBumper(buffer, index);
index += parseLightBumperLeftSignal(buffer, index);
index += parseLightBumperFrontLeftSignal(buffer, index);
index += parseLightBumperCenterLeftSignal(buffer, index);
index += parseLightBumperCenterRightSignal(buffer, index);
index += parseLightBumperFrontRightSignal(buffer, index);
index += parseLightBumperRightSignal(buffer, index);
index += parseIrCharLeft(buffer, index);
index += parseIrCharRight(buffer, index);
index += parseLeftMotorCurrent(buffer, index);
index += parseRightMotorCurrent(buffer, index);
index += parseMainBrushMotorCurrent(buffer, index);
index += parseSideBrushMotorCurrent(buffer, index);
index += parseStasis(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_106) // PACKETS 46-51
{
index += parseLightBumperLeftSignal(buffer, index);
index += parseLightBumperFrontLeftSignal(buffer, index);
index += parseLightBumperCenterLeftSignal(buffer, index);
index += parseLightBumperCenterRightSignal(buffer, index);
index += parseLightBumperFrontRightSignal(buffer, index);
index += parseLightBumperRightSignal(buffer, index);
i++;
}
if(sensor_packets_[i]==OI_PACKET_GROUP_107) // PACKETS 54-58
{
index += parseLeftMotorCurrent(buffer, index);
index += parseRightMotorCurrent(buffer, index);
index += parseMainBrushMotorCurrent(buffer, index);
index += parseSideBrushMotorCurrent(buffer, index);
index += parseStasis(buffer, index);
i++;
}
}
return(0);
}
int irobot::OpenInterface::parseBumpersAndWheeldrops(unsigned char * buffer, int index)
{
// Bumps, wheeldrops
this->bumper_[RIGHT] = (buffer[index]) & 0x01;
this->bumper_[LEFT] = (buffer[index] >> 1) & 0x01;
this->wheel_drop_[RIGHT] = (buffer[index] >> 2) & 0x01;
this->wheel_drop_[LEFT] = (buffer[index] >> 3) & 0x01;
return OI_PACKET_BUMPS_DROPS_SIZE;
}
int irobot::OpenInterface::parseWall(unsigned char * buffer, int index)
{
// Wall
this->wall_ = buffer[index] & 0x01;
return OI_PACKET_WALL_SIZE;
}
int irobot::OpenInterface::parseLeftCliff(unsigned char * buffer, int index)
{
// Cliffs
this->cliff_[LEFT] = buffer[index] & 0x01;
return OI_PACKET_CLIFF_LEFT_SIZE;
}
int irobot::OpenInterface::parseFrontLeftCliff(unsigned char * buffer, int index)
{
// Cliffs
this->cliff_[FRONT_LEFT] = buffer[index] & 0x01;
return OI_PACKET_CLIFF_FRONT_LEFT_SIZE;
}
int irobot::OpenInterface::parseFrontRightCliff(unsigned char * buffer, int index)
{
// Cliffs
this->cliff_[FRONT_RIGHT] = buffer[index] & 0x01;
return OI_PACKET_CLIFF_FRONT_RIGHT_SIZE;
}
int irobot::OpenInterface::parseRightCliff(unsigned char * buffer, int index)
{
// Cliffs
this->cliff_[RIGHT] = buffer[index] & 0x01;
return OI_PACKET_CLIFF_RIGHT_SIZE;
}
int irobot::OpenInterface::parseVirtualWall(unsigned char * buffer, int index)
{
// Virtual Wall
this->virtual_wall_ = buffer[index] & 0x01;
return OI_PACKET_VIRTUAL_WALL_SIZE;
}
int irobot::OpenInterface::parseOvercurrents(unsigned char * buffer, int index)
{
// Overcurrent
unsigned char byte = buffer[index];
this->overcurrent_[SIDE_BRUSH] = (byte >> 0) & 0x01;
this->overcurrent_[MAIN_BRUSH] = (byte >> 2) & 0x01;
this->overcurrent_[RIGHT] = (byte >> 3) & 0x01;
this->overcurrent_[LEFT] = (byte >> 4) & 0x01;
return OI_PACKET_WHEEL_OVERCURRENTS_SIZE;
}
int irobot::OpenInterface::parseDirtDetector(unsigned char * buffer, int index)
{
// Dirt Detector
this->dirt_detect_ = buffer[index];
return OI_PACKET_DIRT_DETECT_SIZE;
}
int irobot::OpenInterface::parseIrOmniChar(unsigned char * buffer, int index)
{
// Infrared Character Omni
this->ir_char_[OMNI] = buffer[index];
return OI_PACKET_IR_CHAR_OMNI_SIZE;
}
int irobot::OpenInterface::parseButtons(unsigned char * buffer, int index)
{
// Buttons
for(int i=0 ; i<8 ; i++) this->buttons_[i] = (buffer[index] >> i) & 0x01;
return OI_PACKET_BUTTONS_SIZE;
}
int irobot::OpenInterface::parseDistance(unsigned char * buffer, int index)
{
// Distance
this->distance_ = buffer2signed_int(buffer, index);
return OI_PACKET_DISTANCE_SIZE;
}
int irobot::OpenInterface::parseAngle(unsigned char * buffer, int index)
{
// Angle
this->angle_ = buffer2signed_int(buffer, index);
return OI_PACKET_ANGLE_SIZE;
}
int irobot::OpenInterface::parseChargingState(unsigned char * buffer, int index)
{
// Charging State
unsigned char byte = buffer[index];
this->power_cord_ = (byte >> 0) & 0x01;
this->dock_ = (byte >> 1) & 0x01;
return OI_PACKET_CHARGING_STATE_SIZE;
}
int irobot::OpenInterface::parseVoltage(unsigned char * buffer, int index)
{
// Voltage
this->voltage_ = (float)(buffer2unsigned_int(buffer, index) / 1000.0);
return OI_PACKET_VOLTAGE_SIZE;
}
int irobot::OpenInterface::parseCurrent(unsigned char * buffer, int index)
{
// Current
this->current_ = (float)(buffer2signed_int(buffer, index) / 1000.0);
return OI_PACKET_CURRENT_SIZE;
}
int irobot::OpenInterface::parseTemperature(unsigned char * buffer, int index)
{
// Temperature
this->temperature_ = (char)(buffer[index]);
return OI_PACKET_TEMPERATURE_SIZE;
}
int irobot::OpenInterface::parseBatteryCharge(unsigned char * buffer, int index)
{
// Charge
this->charge_ = (float)(buffer2unsigned_int(buffer, index) / 1000.0);
return OI_PACKET_BATTERY_CHARGE_SIZE;
}
int irobot::OpenInterface::parseBatteryCapacity(unsigned char * buffer, int index)
{
// Capacity
this->capacity_ = (float)(buffer2unsigned_int(buffer, index) / 1000.0);
return OI_PACKET_BATTERY_CAPACITY_SIZE;
}
int irobot::OpenInterface::parseWallSignal(unsigned char * buffer, int index)
{
// Wall signal
this->wall_signal_ = buffer2unsigned_int(buffer, index);
return OI_PACKET_WALL_SIGNAL_SIZE;
}
int irobot::OpenInterface::parseLeftCliffSignal(unsigned char * buffer, int index)
{
// Cliff signals
this->cliff_signal_[LEFT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_CLIFF_LEFT_SIGNAL_SIZE;
}
int irobot::OpenInterface::parseFrontLeftCliffSignal(unsigned char * buffer, int index)
{
// Cliff signals
this->cliff_signal_[FRONT_LEFT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_CLIFF_FRONT_LEFT_SIGNAL_SIZE;
}
int irobot::OpenInterface::parseFontRightCliffSignal(unsigned char * buffer, int index)
{
// Cliff signals
this->cliff_signal_[FRONT_RIGHT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_CLIFF_FRONT_RIGHT_SIGNAL_SIZE;
}
int irobot::OpenInterface::parseRightCliffSignal(unsigned char * buffer, int index)
{
// Cliff signals
this->cliff_signal_[RIGHT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_CLIFF_RIGHT_SIGNAL_SIZE;
}
int irobot::OpenInterface::parseChargingSource(unsigned char * buffer, int index)
{
// Charging soruces available
this->power_cord_ = (buffer[index] >> 0) & 0x01;
this->dock_ = (buffer[index] >> 1) & 0x01;
return OI_PACKET_CHARGE_SOURCES_SIZE;
}
int irobot::OpenInterface::parseOiMode(unsigned char * buffer, int index)
{
this->OImode_ = buffer[index];
return OI_PACKET_OI_MODE_SIZE;
}
int irobot::OpenInterface::parseSongNumber(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_SONG_NUMBER_SIZE;
}
int irobot::OpenInterface::parseSongPlaying(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_SONG_PLAYING_SIZE;
}
int irobot::OpenInterface::parseNumberOfStreamPackets(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_STREAM_PACKETS_SIZE;
}
int irobot::OpenInterface::parseRequestedVelocity(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_REQ_VELOCITY_SIZE;
}
int irobot::OpenInterface::parseRequestedRadius(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_REQ_RADIUS_SIZE;
}
int irobot::OpenInterface::parseRequestedRightVelocity(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_REQ_RIGHT_VELOCITY_SIZE;
}
int irobot::OpenInterface::parseRequestedLeftVelocity(unsigned char * buffer, int index)
{
// TODO
return OI_PACKET_REQ_LEFT_VELOCITY_SIZE;
}
int irobot::OpenInterface::parseRightEncoderCounts(unsigned char * buffer, int index)
{
// Right encoder counts
uint16_t right_encoder_counts = buffer2unsigned_int(buffer, index);
//printf("Right Encoder: %d\n", rightEncoderCounts);
if(encoder_counts_[RIGHT] == -1 || right_encoder_counts == last_encoder_counts_[RIGHT]) // First time, we need 2 to make it work!
{
encoder_counts_[RIGHT] = 0;
}
else
{
encoder_counts_[RIGHT] = (int)(right_encoder_counts - last_encoder_counts_[RIGHT]);
if(encoder_counts_[RIGHT] > ROOMBA_MAX_ENCODER_COUNTS/10) encoder_counts_[RIGHT] = encoder_counts_[RIGHT] - ROOMBA_MAX_ENCODER_COUNTS;
if(encoder_counts_[RIGHT] < -ROOMBA_MAX_ENCODER_COUNTS/10) encoder_counts_[RIGHT] = ROOMBA_MAX_ENCODER_COUNTS + encoder_counts_[RIGHT];
}
last_encoder_counts_[RIGHT] = right_encoder_counts;
return OI_PACKET_RIGHT_ENCODER_SIZE;
}
int irobot::OpenInterface::parseLeftEncoderCounts(unsigned char * buffer, int index)
{
// Left encoder counts
uint16_t left_encoder_counts = buffer2unsigned_int(buffer, index);
//printf("Left Encoder: %d\n", leftEncoderCounts);
if(encoder_counts_[LEFT] == -1 || left_encoder_counts == last_encoder_counts_[LEFT]) // First time, we need 2 to make it work!
{
encoder_counts_[LEFT] = 0;
}
else
{
encoder_counts_[LEFT] = (int)(left_encoder_counts - last_encoder_counts_[LEFT]);
if(encoder_counts_[LEFT] > ROOMBA_MAX_ENCODER_COUNTS/10) encoder_counts_[LEFT] = encoder_counts_[LEFT] - ROOMBA_MAX_ENCODER_COUNTS;
if(encoder_counts_[LEFT] < -ROOMBA_MAX_ENCODER_COUNTS/10) encoder_counts_[LEFT] = ROOMBA_MAX_ENCODER_COUNTS + encoder_counts_[LEFT];
}
last_encoder_counts_[LEFT] = left_encoder_counts;
return OI_PACKET_LEFT_ENCODER_SIZE;
}
int irobot::OpenInterface::parseLightBumper(unsigned char * buffer, int index)
{
// Light bumper
this->ir_bumper_[LEFT] = (buffer[index]) & 0x01;
this->ir_bumper_[FRONT_LEFT] = (buffer[index] >> 1) & 0x01;
this->ir_bumper_[CENTER_LEFT] = (buffer[index] >> 2) & 0x01;
this->ir_bumper_[CENTER_RIGHT] = (buffer[index] >> 3) & 0x01;
this->ir_bumper_[FRONT_RIGHT] = (buffer[index] >> 4) & 0x01;
this->ir_bumper_[RIGHT] = (buffer[index] >> 5) & 0x01;
return OI_PACKET_LIGHT_BUMPER_SIZE;
}
int irobot::OpenInterface::parseLightBumperLeftSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[LEFT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_LEFT_SIZE;
}
int irobot::OpenInterface::parseLightBumperFrontLeftSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[FRONT_LEFT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_FRONT_LEFT_SIZE;
}
int irobot::OpenInterface::parseLightBumperCenterLeftSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[CENTER_LEFT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_CENTER_LEFT_SIZE;
}
int irobot::OpenInterface::parseLightBumperCenterRightSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[CENTER_RIGHT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_CENTER_RIGHT_SIZE;
}
int irobot::OpenInterface::parseLightBumperFrontRightSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[FRONT_RIGHT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_FRONT_RIGHT_SIZE;
}
int irobot::OpenInterface::parseLightBumperRightSignal(unsigned char * buffer, int index)
{
// Light bumper signal
this->ir_bumper_signal_[RIGHT] = buffer2unsigned_int(buffer, index);
return OI_PACKET_LIGHT_BUMPER_RIGHT_SIZE;
}
int irobot::OpenInterface::parseIrCharLeft(unsigned char * buffer, int index)
{
// Infrared character left
this->ir_char_[LEFT] = buffer[index];
return OI_PACKET_IR_CHAR_LEFT_SIZE;
}
int irobot::OpenInterface::parseIrCharRight(unsigned char * buffer, int index)
{
// Infrared character left
this->ir_char_[RIGHT] = buffer[index];
return OI_PACKET_IR_CHAR_RIGHT_SIZE;
}
int irobot::OpenInterface::parseLeftMotorCurrent(unsigned char * buffer, int index)
{
// Left motor current
this->motor_current_[LEFT] = buffer2signed_int(buffer, index);
return OI_PACKET_LEFT_MOTOR_CURRENT_SIZE;
}
int irobot::OpenInterface::parseRightMotorCurrent(unsigned char * buffer, int index)
{
// Left motor current
this->motor_current_[RIGHT] = buffer2signed_int(buffer, index);
return OI_PACKET_RIGHT_MOTOR_CURRENT_SIZE;
}
int irobot::OpenInterface::parseMainBrushMotorCurrent(unsigned char * buffer, int index)
{
// Main brush motor current
this->motor_current_[MAIN_BRUSH] = buffer2signed_int(buffer, index);
return OI_PACKET_BRUSH_MOTOR_CURRENT_SIZE;
}
int irobot::OpenInterface::parseSideBrushMotorCurrent(unsigned char * buffer, int index)
{
// Main brush motor current
this->motor_current_[SIDE_BRUSH] = buffer2signed_int(buffer, index);
return OI_PACKET_SIDE_BRUSH_MOTOR_CURRENT_SIZE;
}
int irobot::OpenInterface::parseStasis(unsigned char * buffer, int index)
{
// Stasis
this->stasis_ = (buffer[index] >> 0) & 0x01;
return OI_PACKET_STASIS_SIZE;
}
int irobot::OpenInterface::buffer2signed_int(unsigned char * buffer, int index)
{
int16_t signed_int;
memcpy(&signed_int, buffer+index, 2);
signed_int = ntohs(signed_int);
return (int)signed_int;
}
int irobot::OpenInterface::buffer2unsigned_int(unsigned char * buffer, int index)
{
uint16_t unsigned_int;
memcpy(&unsigned_int, buffer+index, 2);
unsigned_int = ntohs(unsigned_int);
return (int)unsigned_int;
}
// *****************************************************************************
// Calculate Roomba odometry
void irobot::OpenInterface::calculateOdometry()
{
double dist = (encoder_counts_[RIGHT]*ROOMBA_PULSES_TO_M + encoder_counts_[LEFT]*ROOMBA_PULSES_TO_M) / 2.0;
double ang = (encoder_counts_[RIGHT]*ROOMBA_PULSES_TO_M - encoder_counts_[LEFT]*ROOMBA_PULSES_TO_M) / -ROOMBA_AXLE_LENGTH;
// Update odometry
this->odometry_yaw_ = NORMALIZE(this->odometry_yaw_ + ang); // rad
this->odometry_x_ = this->odometry_x_ + dist*cos(odometry_yaw_); // m
this->odometry_y_ = this->odometry_y_ + dist*sin(odometry_yaw_); // m
}
// *****************************************************************************
// Reset Roomba odometry
void irobot::OpenInterface::resetOdometry()
{
this->setOdometry(0.0, 0.0, 0.0);
}
// *****************************************************************************
// Set Roomba odometry
void irobot::OpenInterface::setOdometry(double new_x, double new_y, double new_yaw)
{
this->odometry_x_ = new_x;
this->odometry_y_ = new_y;
this->odometry_yaw_ = new_yaw;
}
// *****************************************************************************
// Clean
int irobot::OpenInterface::clean()
{
return sendOpcode(OI_OPCODE_CLEAN);
}
// *****************************************************************************
// Max
int irobot::OpenInterface::max()
{
return sendOpcode(OI_OPCODE_MAX);
}
// *****************************************************************************
// Spot
int irobot::OpenInterface::spot()
{
return sendOpcode(OI_OPCODE_SPOT);
}
// *****************************************************************************
// Go to the dock
int irobot::OpenInterface::goDock()
{
return sendOpcode(OI_OPCODE_FORCE_DOCK);
}
// *****************************************************************************
// Compose a song
int irobot::OpenInterface::setSong(unsigned char song_number, unsigned char song_length, unsigned char *notes, unsigned char *note_lengths)
{
int size = 2*song_length+3;
unsigned char cmd_buffer[size];
unsigned char i;
cmd_buffer[0] = (unsigned char)OI_OPCODE_SONG;
cmd_buffer[1] = song_number;
cmd_buffer[2] = song_length;
for(i=0 ; i < song_length ; i++)
{
cmd_buffer[3+(2*i)] = notes[i];
cmd_buffer[3+(2*i)+1] = note_lengths[i];
}
try{ serial_port_->write((char*)cmd_buffer, size); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Play a song from the list
int irobot::OpenInterface::playSong(unsigned char song_number)
{
unsigned char cmd_buffer[2];
cmd_buffer[0] = (unsigned char)OI_OPCODE_PLAY;
cmd_buffer[1] = song_number;
try{ serial_port_->write((char*)cmd_buffer, 2); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the LEDs
int irobot::OpenInterface::setLeds(unsigned char check_robot, unsigned char dock, unsigned char spot, unsigned char debris, unsigned char power_color, unsigned char power_intensity)
{
unsigned char cmd_buffer[4];
cmd_buffer[0] = (unsigned char)OI_OPCODE_LEDS;
cmd_buffer[1] = debris | spot<<1 | dock<<2 | check_robot<<3;
cmd_buffer[2] = power_color;
cmd_buffer[3] = power_intensity;
try{ serial_port_->write((char*)cmd_buffer, 4); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the scheduling LEDs
int irobot::OpenInterface::setSchedulingLeds(unsigned char sun, unsigned char mon, unsigned char tue, unsigned char wed, unsigned char thu, unsigned char fri, unsigned char sat, unsigned char colon, unsigned char pm, unsigned char am, unsigned char clock, unsigned char schedule)
{
unsigned char cmd_buffer[3];
cmd_buffer[0] = OI_OPCODE_SCHEDULE_LEDS;
cmd_buffer[1] = sun | mon<<1 | tue<<2 | wed<<3 | thu<<4 | fri<<5 | sat<<6;
cmd_buffer[2] = colon | pm<<1 | am<<2 | clock<<3 | schedule<<4;
try{ serial_port_->write((char*)cmd_buffer, 3); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// *****************************************************************************
// Set the digit LEDs
int irobot::OpenInterface::setDigitLeds(unsigned char digit3, unsigned char digit2, unsigned char digit1, unsigned char digit0)
{
unsigned char cmd_buffer[5];
cmd_buffer[0] = (unsigned char)OI_OPCODE_DIGIT_LEDS_ASCII;
cmd_buffer[1] = digit3;
cmd_buffer[2] = digit2;
cmd_buffer[3] = digit1;
cmd_buffer[4] = digit0;
try{ serial_port_->write((char*)cmd_buffer, 5); }
catch(cereal::Exception& e){ return(-1); }
return(0);
}
// EOF
|
[
"imaterna@fit.vutbr.cz"
] |
imaterna@fit.vutbr.cz
|
a67d5f7e59460d5bf007345b95174c847a0411be
|
4c8f8d7d4fa4a486267427c9cf12c3c246dae9d4
|
/cplusplus/chapter12/test1/strngbad.h
|
ad8baa8c4ab521fb038e24d83fbf047ceada8b4e
|
[] |
no_license
|
shuwentao/learn
|
3f8b1a15d2b440820e4804e20e42f821ae872a92
|
a07b1fc1f47e0657b4d985f3a1a29b6a43bd5ec7
|
refs/heads/master
| 2020-09-23T19:18:55.715984
| 2019-12-26T08:52:10
| 2019-12-26T08:52:10
| 225,566,386
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 284
|
h
|
#include <iostream>
#ifndef STRNGBAD_H_
#define STRNGBAD_H_
class StringBad
{
private:
char * str;
int len;
static int num_strings;
public:
StringBad(const char *s);
StringBad();
~StringBad();
friend std::ostream & operator<<(std::ostream & os,const StringBad & st);
};
#endif
|
[
"418674879@qq.com"
] |
418674879@qq.com
|
9382dfc1fab4e592a635607257cf353511963c95
|
5531d676864880b890630f462cfc6d05defd1d79
|
/include/boost/gil/extension/io/pnm/detail/reader_backend.hpp
|
5aba7ace05d76921444f7a42b7c0ddbb2415a4b5
|
[] |
no_license
|
BeamMW/boost-android
|
2cd0ec609462e72ac41bdcf02ded82f954652dde
|
60cc7878e44e898cf44fb04a1f10372eceaa9b02
|
refs/heads/master
| 2020-04-27T11:13:33.402189
| 2019-04-01T10:04:55
| 2019-04-01T10:04:55
| 174,288,040
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,687
|
hpp
|
/*
Copyright 2012 Christian Henning
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
*/
/*************************************************************************************************/
#ifndef BOOST_GIL_EXTENSION_IO_PNM_DETAIL_READER_BACKEND_HPP
#define BOOST_GIL_EXTENSION_IO_PNM_DETAIL_READER_BACKEND_HPP
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief
/// \author Christian Henning \n
///
/// \date 2012 \n
///
////////////////////////////////////////////////////////////////////////////////////////
#include <boost/gil/extension/io/pnm/tags.hpp>
namespace boost { namespace gil {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable:4512) //assignment operator could not be generated
#endif
///
/// PNM Backend
///
template< typename Device >
struct reader_backend< Device
, pnm_tag
>
{
public:
typedef pnm_tag format_tag_t;
public:
reader_backend( const Device& io_dev
, const image_read_settings< pnm_tag >& settings
)
: _io_dev ( io_dev )
, _settings( settings )
, _info()
, _scanline_length( 0 )
{
read_header();
if( _settings._dim.x == 0 )
{
_settings._dim.x = _info._width;
}
if( _settings._dim.y == 0 )
{
_settings._dim.y = _info._height;
}
}
void read_header()
{
// read signature
io_error_if( read_char() != 'P', "Invalid PNM signature" );
_info._type = read_char() - '0';
io_error_if( _info._type < pnm_image_type::mono_asc_t::value || _info._type > pnm_image_type::color_bin_t::value
, "Invalid PNM file (supports P1 to P6)"
);
_info._width = read_int();
_info._height = read_int();
if( _info._type == pnm_image_type::mono_asc_t::value || _info._type == pnm_image_type::mono_bin_t::value )
{
_info._max_value = 1;
}
else
{
_info._max_value = read_int();
io_error_if( _info._max_value > 255
, "Unsupported PNM format (supports maximum value 255)"
);
}
}
/// Check if image is large enough.
void check_image_size( const point_t& img_dim )
{
if( _settings._dim.x > 0 )
{
if( img_dim.x < _settings._dim.x ) { io_error( "Supplied image is too small" ); }
}
else
{
if( img_dim.x < _info._width ) { io_error( "Supplied image is too small" ); }
}
if( _settings._dim.y > 0 )
{
if( img_dim.y < _settings._dim.y ) { io_error( "Supplied image is too small" ); }
}
else
{
if( img_dim.y < _info._height ) { io_error( "Supplied image is too small" ); }
}
}
private:
// Read a character and skip a comment if necessary.
char read_char()
{
char ch;
if(( ch = _io_dev.getc() ) == '#' )
{
// skip comment to EOL
do
{
ch = _io_dev.getc();
}
while (ch != '\n' && ch != '\r');
}
return ch;
}
unsigned int read_int()
{
char ch;
// skip whitespaces, tabs, and new lines
do
{
ch = read_char();
}
while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if( ch < '0' || ch > '9' )
{
io_error( "Unexpected characters reading decimal digits" );
}
unsigned val = 0;
do
{
unsigned dig = ch - '0';
if( val > INT_MAX / 10 - dig )
{
io_error( "Integer too large" );
}
val = val * 10 + dig;
ch = read_char();
}
while( '0' <= ch && ch <= '9' );
return val;
}
public:
Device _io_dev;
image_read_settings< pnm_tag > _settings;
image_read_info< pnm_tag > _info;
std::size_t _scanline_length;
};
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
} // namespace gil
} // namespace boost
#endif
|
[
"strylets@gmail.com"
] |
strylets@gmail.com
|
3f377aa376fcd4f4c6e00273ac842047ce605cda
|
2bb5ffa26516d667a3116d1f772f21b5abad1dcc
|
/ppd/lab3/main.cpp
|
8e36942c30040b0dc98b3132db09ea1e7bc13fef
|
[] |
no_license
|
Demon000/uni
|
71a0c8d26ae1a6024f2215f4105dc8daee3c1bb5
|
7735fc90b17f452879bfca4b0e4e8c2c4e80831f
|
refs/heads/master
| 2022-08-14T03:08:51.029670
| 2021-12-15T16:50:06
| 2021-12-15T16:51:09
| 154,342,332
| 0
| 4
| null | 2022-07-21T08:25:57
| 2018-10-23T14:26:35
|
Jupyter Notebook
|
UTF-8
|
C++
| false
| false
| 2,909
|
cpp
|
#include <cstdio>
#include <mpi.h>
#include <chrono>
void sum(int *a, int *b, int *c, int size) {
for (int i = 0; i < size; i++) {
c[i] = a[i] + b[i];
}
}
void printArray(int *v, int size) {
for (int i = 0; i < size; i++) {
std::cout << v[i] << " ";
}
std::cout << std::endl;
}
int main(int argc, char** argv) {
int n = 100000;
int m = 10;
int a[n];
int b[n];
int c[n];
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// Get the rank of the process
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Status status;
int p = world_size - 1;
int chunk = n / p;
int rest = n % p;
auto startTime = std::chrono::high_resolution_clock::now();
if (world_rank == 0) {
for (int i = 0; i < n; i++) {
a[i] = rand() % m;
b[i] = rand() % m;
}
int start;
int end = 0;
for (int i = 1; i < world_size; i++) {
start = end;
end = start + chunk;
if (end > n) {
end = n;
}
if (rest > 0) {
end += 1;
rest--;
}
MPI_Send(&start, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
MPI_Send(&end, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
MPI_Send(a + start, end - start, MPI_INT, i, 0, MPI_COMM_WORLD);
MPI_Send(b + start, end - start, MPI_INT, i, 0, MPI_COMM_WORLD);
}
for (int i = 1; i < world_size; i++) {
MPI_Recv(&start, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
MPI_Recv(&end, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
MPI_Recv(c + start, end - start, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
}
auto endTime = std::chrono::high_resolution_clock::now();
std::cout << "time threads: " << duration_cast<std::chrono::microseconds>(endTime - startTime).count() << "\n";
// printArray(a, n);
// printArray(b, n);
// printArray(c, n);
} else {
int start;
int end;
MPI_Recv(&start, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
MPI_Recv(&end, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
MPI_Recv(a + start, end - start, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
MPI_Recv(b + start, end - start, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
sum(a + start, b + start, c + start, end - start);
MPI_Send(&start, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
MPI_Send(&end, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
MPI_Send(c + start, end - start, MPI_INT, 0, 0, MPI_COMM_WORLD);
// std::cout << start << " " << end << " " << world_rank << std::endl;
}
// Finalize the MPI environment.
MPI_Finalize();
}
|
[
"demonsingur@gmail.com"
] |
demonsingur@gmail.com
|
130b694cb1df52a777853244fe8a4c3c6b0d9773
|
776572b92dfca09c7657f6f58e4c3a4796efe4b4
|
/c++/dbobjects.h
|
5786e71a8f5a211bbd58c3079b813d53355d6645
|
[] |
no_license
|
sowbhagyasuvi/aquarium_notes
|
f8a653b270abf5079ebfc942cf288706079a7fbf
|
af6b1ee4c56851b11ab3eeabe41c7ce3ff436a2f
|
refs/heads/master
| 2022-07-06T10:54:27.736547
| 2020-05-20T15:01:10
| 2020-05-20T15:01:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,398
|
h
|
#ifndef DBOBJECTS_H
#define DBOBJECTS_H
#include <QObject>
#include <QString>
#include <QSql>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QVariant>
typedef enum
{
Reef_Fish = 0,
Reef_SoftCoral = 1,
Reef_MixedCoral = 2,
Reef_SPSCoral = 3,
Fresh_Cihlids = 4,
Fresh_Discus = 5,
Fresh_LowScape = 6,
Fresh_FullScape = 7,
EndOfList = Fresh_FullScape + 1
} AquariumType;
class LastDataParamRecObj : public QObject
{
Q_OBJECT
Q_PROPERTY(char paramId READ paramId WRITE setParamId NOTIFY paramIdChanged)
Q_PROPERTY(int smpIdNow READ smpIdNow WRITE setSmpIdNow NOTIFY smpIdNowChanged)
Q_PROPERTY(int smpIdPrev READ smpIdPrev WRITE setSmpIdPrev NOTIFY smpIdPrevChanged)
Q_PROPERTY(float valueNow READ valueNow WRITE setValueNow NOTIFY valueNowChanged)
Q_PROPERTY(float valuePrev READ valuePrev WRITE setValuePrev NOTIFY valuePrevChanged)
Q_PROPERTY(unsigned int dtNow READ dtNow WRITE setDtNow NOTIFY dtNowChanged)
Q_PROPERTY(unsigned int dtPrev READ dtPrev WRITE setDtPrev NOTIFY dtPrevChanged)
Q_PROPERTY(QString note READ note WRITE setNote NOTIFY noteChanged)
Q_PROPERTY(QString imgLink READ imgLink WRITE setImgLink NOTIFY imgLinkChanged)
public:
LastDataParamRecObj(char paramId, int idNow, int idPrev, float now, float prev, unsigned int dtNow, unsigned int dtPrev, QString note, QString img)
{
_paramId = paramId;
_smpIdNow = idNow;
_smpIdPrev = idPrev;
_valueNow = now;
_valuePrev = prev;
_dtNow = dtNow;
_dtPrev = dtPrev;
_note = note;
_imgLink = img;
}
char paramId() { return _paramId; }
int smpIdNow() { return _smpIdNow; }
int smpIdPrev() { return _smpIdPrev; }
float valueNow() { return _valueNow; }
float valuePrev() { return _valuePrev; }
unsigned int dtNow() { return _dtNow; }
unsigned int dtPrev() { return _dtPrev; }
QString note() { return _note; }
QString imgLink() { return _imgLink; }
void setParamId(char paramId) { _paramId = paramId; }
void setSmpIdNow(int smpIdNow) { _smpIdNow = smpIdNow; }
void setSmpIdPrev(int smpIdPrev) { _smpIdPrev = smpIdPrev; }
void setValueNow(float valueNow) { _valueNow = valueNow; }
void setValuePrev(float valuePrev) { _valuePrev = valuePrev; }
void setDtNow(unsigned int dt) { _dtNow = dt; }
void setDtPrev(unsigned int dt) { _dtPrev = dt; }
void setNote(QString note) { _note = note; }
void setImgLink(QString link) { _imgLink = link; }
signals:
void paramIdChanged();
void smpIdNowChanged();
void smpIdPrevChanged();
void valueNowChanged();
void valuePrevChanged();
void dtNowChanged();
void dtPrevChanged();
void noteChanged();
void imgLinkChanged();
protected:
char _paramId;
int _smpIdNow;
int _smpIdPrev;
float _valueNow;
float _valuePrev;
unsigned int _dtNow;
unsigned int _dtPrev;
QString _note;
QString _imgLink;
};
class ParamObj : public QObject
{
Q_OBJECT
Q_PROPERTY(char paramId READ paramId WRITE setParamId NOTIFY paramIdChanged)
Q_PROPERTY(QString shortName READ shortName WRITE setShortName NOTIFY shortNameChanged)
Q_PROPERTY(QString fullName READ fullName WRITE setFullName NOTIFY fullNameChanged)
Q_PROPERTY(QString unitName READ unitName WRITE setUnitName NOTIFY unitNameChanged)
Q_PROPERTY(bool en READ en WRITE setEn NOTIFY enChanged)
Q_PROPERTY(float value READ value WRITE setValue NOTIFY valueChanged)
Q_PROPERTY(float min READ min WRITE setMin NOTIFY minChanged)
Q_PROPERTY(float max READ max WRITE setMax NOTIFY maxChanged)
Q_PROPERTY(float max READ max WRITE setMax NOTIFY maxChanged)
public:
ParamObj(QSqlQuery *query, AquariumType type)
{
QString min = "MIN_" + QString::number(type);
QString max = "MAX_" + QString::number(type);
if (query != nullptr)
{
_paramId = (char) query->value(query->record().indexOf("PARAM_ID")).toInt();
_shortName = query->value(query->record().indexOf("SHORT_NAME")).toString();
_fullName = query->value(query->record().indexOf("FULL_NAME")).toString();
_unitName = query->value(query->record().indexOf("UNIT_NAME")).toString();
_min = query->value(query->record().indexOf(min)).toFloat();
_max = query->value(query->record().indexOf(max)).toFloat();
_value = -1;
_en = true;
}
}
char paramId() { return _paramId; }
QString shortName() { return _shortName; }
QString fullName() { return _fullName; }
QString unitName() { return _unitName; }
float value() { return _value; }
float min() { return _min; }
float max() { return _max; }
bool en() { return _en; }
void setParamId(char paramId) { _paramId = paramId; }
void setShortName(QString name) { _shortName = name; }
void setFullName(QString name) { _fullName = name; }
void setUnitName(QString name) { _unitName = name; }
void setValue(float value) { _value = value; }
void setMin(float min) { _min = min; }
void setMax(float max) { _max = max; }
void setEn(bool en) { _en = en; }
signals:
void paramIdChanged();
void shortNameChanged();
void fullNameChanged();
void unitNameChanged();
void valueChanged();
void minChanged();
void maxChanged();
void enChanged();
protected:
char _paramId;
QString _shortName;
QString _fullName;
QString _unitName;
float _value;
float _min;
float _max;
bool _en;
};
class UserObj
{
public:
UserObj() {}
UserObj(QSqlQuery *query)
{
if (query != nullptr)
{
man_id = query->value(query->record().indexOf("MAN_ID")).toString();
uname = query->value(query->record().indexOf("UNAME")).toString();
email = query->value(query->record().indexOf("EMAIL")).toString();
phone = query->value(query->record().indexOf("PHONE")).toString();
avatar_img = query->value(query->record().indexOf("AVATAR_IMG")).toString();
status = query->value(query->record().indexOf("STATUS")).toInt();
selected = query->value(query->record().indexOf("SELECTED")).toInt();
date_create = query->value(query->record().indexOf("DATE_CREATE")).toInt();
date_edit = query->value(query->record().indexOf("DATE_EDIT")).toInt();
}
}
~UserObj() {}
QString man_id = "";
QString uname = "";
QString email = "";
QString phone = "";
QString avatar_img = "";
int status = 0;
int selected = 0;
int date_create = 0;
int date_edit = 0;
};
class TankTypeObj : public QObject
{
Q_OBJECT
Q_PROPERTY(int type READ type WRITE setType NOTIFY typeChanged)
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
public:
TankTypeObj(int type, QString name)
{
_type = type;
_name = name;
}
public:
int type() { return _type; }
QString name() { return _name; }
void setType(int type) { _type = type; }
void setName(QString name) { _name = name; }
signals:
void typeChanged();
void nameChanged();
protected:
int _type;
QString _name;
};
class TankObj : public QObject
{
Q_OBJECT
Q_PROPERTY(QString tankId READ tankId WRITE setTankId NOTIFY tankIdChanged)
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(QString desc READ desc WRITE setDesc NOTIFY descChanged)
Q_PROPERTY(float volume READ volume WRITE setVolume NOTIFY volumeChanged)
Q_PROPERTY(int type READ type WRITE setType NOTIFY typeChanged)
Q_PROPERTY(QString typeName READ typeName WRITE setTypeName NOTIFY typeNameChanged)
Q_PROPERTY(QString img READ img WRITE setImg NOTIFY imgChanged)
public:
TankObj(QSqlQuery *query)
{
if (query != nullptr)
{
_tank_id = query->value(query->record().indexOf("TANK_ID")).toString();
_man_id = query->value(query->record().indexOf("MAN_ID")).toString();
_type = query->value(query->record().indexOf("TYPE")).toInt();
_name = query->value(query->record().indexOf("NAME")).toString();
_desc = query->value(query->record().indexOf("DESC")).toString();
_img = query->value(query->record().indexOf("IMG")).toString();
_status = query->value(query->record().indexOf("STATUS")).toInt();
_l = query->value(query->record().indexOf("L")).toFloat();
_w = query->value(query->record().indexOf("W")).toFloat();
_h = query->value(query->record().indexOf("H")).toFloat();
_date_create = query->value(query->record().indexOf("DATE_CREATE")).toInt();
_date_edit = query->value(query->record().indexOf("DATE_EDIT")).toInt();
}
}
public:
float tankVolume() { return (_l * _w * _h) / 1000; }
public:
QString tankId() { return _tank_id; }
QString name() { return _name; }
QString desc() { return _desc; }
float volume() { return tankVolume(); }
int type() { return _type; }
QString img() { return _img; }
QString typeName() { return _typeName; }
void setTankId(QString tankId) { _tank_id = tankId; }
void setName(QString name) { _name = name; }
void setDesc(QString desc) { _desc = desc; }
void setVolume(float vol) { _l = _w; }
void setType(int type) { _type = type; }
void setImg(QString img) { _img = img; }
void setTypeName(QString name) { _typeName = name; }
signals:
void tankIdChanged();
void nameChanged();
void descChanged();
void volumeChanged();
void typeChanged();
void imgChanged();
void typeNameChanged();
protected:
QString _tank_id;
QString _man_id;
int _type;
QString _typeName;
QString _name;
QString _desc;
QString _img;
int _status;
float _l;
float _w;
float _h;
int _date_create;
int _date_edit;
};
#endif // DBOBJECTS_H
|
[
"webmaster@aquabox.by"
] |
webmaster@aquabox.by
|
d074a4222925f16f075948341b7922f869452e11
|
ec0a8e179459bfa15b3abfd21df2ea33d201f0bd
|
/Codigo/Versao Minibau/states/testeVisao.cpp
|
950e11cecdac9a8335c74b7741f0ca3ad9479905
|
[] |
no_license
|
UnbDroid/Festo2017
|
b32fbf61e6a703feb1d04e47b765186f2ecca376
|
eb4afb447bbb6cb1016a289231071471c6228e6e
|
refs/heads/master
| 2021-01-20T02:47:59.381718
| 2017-11-11T07:48:35
| 2017-11-11T07:48:35
| 101,334,390
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,190
|
cpp
|
#include "control.hpp"
#include "robotino.hpp"
#include "classificadores.hpp"
#include "maquinainferencia.hpp"
#include "defuzzyficador.hpp"
#include "irparaponto.hpp"
#include "controleposicao.hpp"
#include "coordenadas.hpp"
#include "girar.hpp"
#include "identificarcor.hpp"
#include "procurarcor.hpp"
#include "seguircor.hpp"
#include "irparaparede.hpp"
#include "irparalinha.hpp"
#include "modulo3testar.hpp"
#include "testeVisao.hpp"
#include "ajustarnaslinhas.hpp"
#include "ajustarnaslinhasortogonais.hpp"
#include "andarpelaparedeatelinha.hpp"
#include "andarpelaparedeatelinhasensor.hpp"
#include "contarlinhas.hpp"
#include "percorrerprocurandodiscos.hpp"
#include "irparedepelaparede.hpp"
#include "irparedepelaparedeprocurandodisco.hpp"
#include "nobusca.hpp"
#include "navegarentreareas.hpp"
#include "navegarentreareas2.hpp"
#include "navegarentreareas3.hpp"
#include "alinhartraseiro.hpp"
#include <unistd.h>
#include <vector>
#include <cmath>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <algorithm>
#define PI 3.14159265
#define R 0
#define Y 1
#define B 2
#define INDEFINIDO -1
#define VAZIO 4
#define AREA_D1 20
#define AREA_D2 21
#define AREA_D3 22
#define AREA_D4 23
#define AREA_D5 24
#define AREA_D6 25
#define AREA_INTERMEDIARIA 34
#define VOLTARINICIO 50
#define RE 10// era 30
//*****************************************************************************************************************
// teste003Locomocao
//*****************************************************************************************************************
testeVisao *testeVisao::instance()
{
static testeVisao testeVisaoStateInstance;
return &testeVisaoStateInstance;
}
testeVisao::testeVisao() {}
testeVisao::~testeVisao() {}
void testeVisao::enter(Robotino *robotino)
{
std::cout << "Entrando no estado testeVisao...\n";
}
void testeVisao::execute(Robotino *robotino)
{
static int objetivo_completo = 0;
static int discos_entregues = 0;
static int numPassosFazer = 0;
static int numPassosFeitos = 0;
static int deixarDiscos = 0;
static int pegar = 0;
static bool deixando = false;
static vector<int> ordemAtualDiscos = {INDEFINIDO, INDEFINIDO, INDEFINIDO, INDEFINIDO, INDEFINIDO, INDEFINIDO}; //mudei para 6
static vector<int> ordemCorreta = {B,B,R,R,Y,Y};
static NoBusca noFinal(ordemCorreta,0);
static NoBusca melhorResultado;
std::cout << "objetivo_completo: " << objetivo_completo << std::endl;
// Saindo da area de inicio e indo para a area de deposito 6------------------------------------------------------------------------------------------
//ANDA NAS 4 paredes da arena seguindo parede no sentido horário
if (objetivo_completo == 0)
{
robotino->change_state(IdentificarCor::instance());
}
else if(objetivo_completo == 99999)
{
std::cout << "TERMINOU" << endl;
robotino->~Robotino();
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
void testeVisao::exit(Robotino *robotino) {}
|
[
"leticiahelenasp@hotmail.com"
] |
leticiahelenasp@hotmail.com
|
16845ec7e19bcba2103cd8781aba8d1be6d4870f
|
ba4db75b9d1f08c6334bf7b621783759cd3209c7
|
/src_main/game/shared/props_shared.cpp
|
3bc71c1be5745036d409669521c5140059b7366d
|
[] |
no_license
|
equalent/source-2007
|
a27326c6eb1e63899e3b77da57f23b79637060c0
|
d07be8d02519ff5c902e1eb6430e028e1b302c8b
|
refs/heads/master
| 2020-03-28T22:46:44.606988
| 2017-03-27T18:05:57
| 2017-03-27T18:05:57
| 149,257,460
| 2
| 0
| null | 2018-09-18T08:52:10
| 2018-09-18T08:52:09
| null |
WINDOWS-1252
|
C++
| false
| false
| 50,331
|
cpp
|
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: static_prop - don't move, don't animate, don't do anything.
// physics_prop - move, take damage, but don't animate
//
//=============================================================================//
#include "cbase.h"
#include "props_shared.h"
#include "filesystem.h"
#include "animation.h"
#include <vcollide_parse.h>
#include <bone_setup.h>
#ifdef CLIENT_DLL
#include "gamestringpool.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar sv_pushaway_clientside_size( "sv_pushaway_clientside_size", "15", FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Minimum size of pushback objects" );
ConVar props_break_max_pieces( "props_break_max_pieces", "-1", 0, "Maximum prop breakable piece count (-1 = model default)" );
ConVar props_break_max_pieces_perframe( "props_break_max_pieces_perframe", "-1", FCVAR_REPLICATED, "Maximum prop breakable piece count per frame (-1 = model default)" );
#ifdef GAME_DLL
extern ConVar breakable_multiplayer;
#endif // GAME_DLL
extern bool PropBreakableCapEdictsOnCreateAll(int modelindex, IPhysicsObject *pPhysics, const breakablepropparams_t ¶ms, CBaseEntity *pEntity, int iPrecomputedBreakableCount = -1 );
extern CBaseEntity *BreakModelCreateSingle( CBaseEntity *pOwner, breakmodel_t *pModel, const Vector &position,
const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, int nSkin, const breakablepropparams_t ¶ms );
static int nPropBreakablesPerFrameCount = 0;
static int nFrameNumber = 0;
//=============================================================================================================
// UTILITY FUNCS
//=============================================================================================================
//-----------------------------------------------------------------------------
// Purpose: returns the axis index with the greatest size
// Input : &vec -
// Output : static int
//-----------------------------------------------------------------------------
static int GreatestAxis( const Vector &vec )
{
if ( vec.x > vec.y )
{
if ( vec.x > vec.z )
return 0;
return 2;
}
if ( vec.y > vec.z )
return 1;
return 2;
}
//-----------------------------------------------------------------------------
// Purpose: returns the axis index with the smallest size
// Input : &vec -
// Output : static int
//-----------------------------------------------------------------------------
static int SmallestAxis( const Vector &vec )
{
if ( vec.x < vec.y )
{
if ( vec.x < vec.z )
return 0;
return 2;
}
if ( vec.y < vec.z )
return 1;
return 2;
}
//-----------------------------------------------------------------------------
// Purpose: Rotates a matrix by 90 degrees in the plane of axis0/axis1
// Input : &matrix -
// axis0 -
// axis1 -
// Output : static void
//-----------------------------------------------------------------------------
static void MatrixRot90( matrix3x4_t &matrix, int axis0, int axis1 )
{
Vector col0, col1;
MatrixGetColumn( matrix, axis0, col0 );
MatrixGetColumn( matrix, axis1, col1 );
MatrixSetColumn( col1, axis0, matrix );
MatrixSetColumn( -col0, axis1, matrix );
}
//-----------------------------------------------------------------------------
// Purpose: Given two symmetric boxes, rotate the coordinate frame by the necessary
// 90 degree rotations to approximately align them
// Input : *pInOutMatrix -
// &boxExtents1 -
// &boxExtents2 -
//-----------------------------------------------------------------------------
static void AlignBoxes( matrix3x4_t *pInOutMatrix, const Vector &boxExtents1, const Vector &boxExtents2 )
{
int rotCount = 0;
struct
{
int axis0;
int axis1;
} rotations[2];
Vector ext1 = boxExtents1;
Vector ext2 = boxExtents2;
int axis0 = GreatestAxis( ext1 );
int axis1 = GreatestAxis( ext2 );
if ( axis0 != axis1 )
{
rotations[rotCount].axis0 = axis0;
rotations[rotCount].axis1 = axis1;
rotCount++;
ext2[axis1] = ext2[axis0];
}
ext1[axis0] = 0;
ext2[axis0] = 0;
axis0 = GreatestAxis(ext1);
axis1 = GreatestAxis(ext2);
if ( axis0 != axis1 )
{
rotations[rotCount].axis0 = axis0;
rotations[rotCount].axis1 = axis1;
rotCount++;
}
while ( rotCount > 0 )
{
rotCount--;
MatrixRot90( *pInOutMatrix, rotations[rotCount].axis0, rotations[rotCount].axis1 );
}
}
//=============================================================================================================
// PROP DATA
//=============================================================================================================
CPropData g_PropDataSystem;
// Parsing details for each of the propdata interactions
struct propdata_interaction_s
{
const char *pszSectionName;
const char *pszKeyName;
const char *pszValue;
};
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
propdata_interaction_s sPropdataInteractionSections[PROPINTER_NUM_INTERACTIONS] =
{
{ "physgun_interactions", "onworldimpact", "stick" }, // PROPINTER_PHYSGUN_WORLD_STICK,
{ "physgun_interactions", "onfirstimpact", "break" }, // PROPINTER_PHYSGUN_FIRST_BREAK,
{ "physgun_interactions", "onfirstimpact", "paintsplat" }, // PROPINTER_PHYSGUN_FIRST_PAINT,
{ "physgun_interactions", "onfirstimpact", "impale" }, // PROPINTER_PHYSGUN_FIRST_IMPALE,
{ "physgun_interactions", "onlaunch", "spin_none" }, // PROPINTER_PHYSGUN_LAUNCH_SPIN_NONE,
{ "physgun_interactions", "onlaunch", "spin_zaxis" }, // PROPINTER_PHYSGUN_LAUNCH_SPIN_Z,
{ "physgun_interactions", "onbreak", "explode_fire" }, // PROPINTER_PHYSGUN_BREAK_EXPLODE,
{ "physgun_interactions", "damage", "none" }, // PROPINTER_PHYSGUN_DAMAGE_NONE,
{ "fire_interactions", "flammable", "yes" }, // PROPINTER_FIRE_FLAMMABLE,
{ "fire_interactions", "explosive_resist", "yes" }, // PROPINTER_FIRE_EXPLOSIVE_RESIST,
{ "fire_interactions", "ignite", "halfhealth" }, // PROPINTER_FIRE_IGNITE_HALFHEALTH,
{ "physgun_interactions", "onpickup", "create_flare" }, // PROPINTER_PHYSGUN_CREATE_FLARE,
{ "physgun_interactions", "allow_overhead", "yes" }, // PROPINTER_PHYSGUN_ALLOW_OVERHEAD,
{ "world_interactions", "onworldimpact", "bloodsplat" }, // PROPINTER_WORLD_BLOODSPLAT,
};
#else
extern propdata_interaction_s sPropdataInteractionSections[PROPINTER_NUM_INTERACTIONS];
#endif
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CPropData::CPropData( void ) :
CAutoGameSystem( "CPropData" )
{
m_bPropDataLoaded = false;
m_pKVPropData = NULL;
}
//-----------------------------------------------------------------------------
// Inherited from IAutoServerSystem
//-----------------------------------------------------------------------------
void CPropData::LevelInitPreEntity( void )
{
m_BreakableChunks.RemoveAll();
ParsePropDataFile();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropData::LevelShutdownPostEntity( void )
{
if ( m_pKVPropData )
{
m_pKVPropData->deleteThis();
m_pKVPropData = NULL;
}
}
//-----------------------------------------------------------------------------
// Clear out the stats + their history
//-----------------------------------------------------------------------------
void CPropData::ParsePropDataFile( void )
{
m_pKVPropData = new KeyValues( "PropDatafile" );
if ( !m_pKVPropData->LoadFromFile( filesystem, "scripts/propdata.txt" ) )
{
m_pKVPropData->deleteThis();
m_pKVPropData = NULL;
return;
}
m_bPropDataLoaded = true;
// Now try and parse out the breakable section
KeyValues *pBreakableSection = m_pKVPropData->FindKey( "BreakableModels" );
if ( pBreakableSection )
{
KeyValues *pChunkSection = pBreakableSection->GetFirstSubKey();
while ( pChunkSection )
{
// Create a new chunk section and add it to our list
int index = m_BreakableChunks.AddToTail();
propdata_breakablechunk_t *pBreakableChunk = &m_BreakableChunks[index];
pBreakableChunk->iszChunkType = AllocPooledString( pChunkSection->GetName() );
// Read in all the model names
KeyValues *pModelName = pChunkSection->GetFirstSubKey();
while ( pModelName )
{
const char *pModel = pModelName->GetName();
string_t pooledName = AllocPooledString( pModel );
pBreakableChunk->iszChunkModels.AddToTail( pooledName );
CBaseEntity::PrecacheModel( STRING( pooledName ) );
pModelName = pModelName->GetNextKey();
}
pChunkSection = pChunkSection->GetNextKey();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Parse a keyvalues section into the prop
//
// pInteractionSection is a bit of jiggery-pokery to get around the unfortunate
// fact that the interaction KV sections ("physgun_interactions", "fire_interactions", etc)
// are OUTSIDE the "prop_data" KV section in the model, but may be contained WITHIN the
// specified Base's "prop_data" section (i.e. in propdata.txt)
//-----------------------------------------------------------------------------
int CPropData::ParsePropFromKV( CBaseEntity *pProp, KeyValues *pSection, KeyValues *pInteractionSection )
{
IBreakableWithPropData *pBreakableInterface = dynamic_cast<IBreakableWithPropData*>(pProp);
if ( !pBreakableInterface )
return PARSE_FAILED_BAD_DATA;
if ( !pBreakableInterface )
return PARSE_FAILED_BAD_DATA;
int iBaseResult = PARSE_SUCCEEDED;
// Do we have a base?
char const *pszBase = pSection->GetString( "base" );
if ( pszBase && pszBase[0] )
{
iBaseResult = ParsePropFromBase( pProp, pszBase );
if ( (iBaseResult != PARSE_SUCCEEDED) && (iBaseResult != PARSE_SUCCEEDED_ALLOWED_STATIC) )
return iBaseResult;
}
// Allow overriding of Block LOS
int iBlockLOS = pSection->GetFloat( "blockLOS", -1 );
if ( iBlockLOS != -1 )
{
pBreakableInterface->SetPropDataBlocksLOS( iBlockLOS != 0 );
}
// Set whether AI can walk on this prop
int iIsWalkable = pSection->GetFloat( "AIWalkable", -1 );
if ( iIsWalkable != -1 )
{
pBreakableInterface->SetPropDataIsAIWalkable( iIsWalkable != 0 );
}
// Set custom damage table
const char *pszTableName;
if ( pBreakableInterface->GetPhysicsDamageTable() == NULL_STRING )
{
pszTableName = pSection->GetString( "damage_table", NULL );
}
else
{
pszTableName = pSection->GetString( "damage_table", STRING(pBreakableInterface->GetPhysicsDamageTable()) );
}
if ( pszTableName && pszTableName[0] )
{
pBreakableInterface->SetPhysicsDamageTable( AllocPooledString( pszTableName ) );
}
else
{
pBreakableInterface->SetPhysicsDamageTable( NULL_STRING );
}
// Get multiplayer physics mode if not set by map
pBreakableInterface->SetPhysicsMode( pSection->GetInt( "physicsmode",
pBreakableInterface->GetPhysicsMode() ) );
const char *multiplayer_break = pSection->GetString( "multiplayer_break", NULL );
if ( multiplayer_break )
{
mp_break_t mode = MULTIPLAYER_BREAK_DEFAULT;
if ( FStrEq( multiplayer_break, "server" ) )
{
mode = MULTIPLAYER_BREAK_SERVERSIDE;
}
else if ( FStrEq( multiplayer_break, "client" ) )
{
mode = MULTIPLAYER_BREAK_CLIENTSIDE;
}
else if ( FStrEq( multiplayer_break, "both" ) )
{
mode = MULTIPLAYER_BREAK_BOTH;
}
pBreakableInterface->SetMultiplayerBreakMode( mode );
}
// Get damage modifiers, but only if they're specified, because our base may have already overridden them.
pBreakableInterface->SetDmgModBullet( pSection->GetFloat( "dmg.bullets", pBreakableInterface->GetDmgModBullet() ) );
pBreakableInterface->SetDmgModClub( pSection->GetFloat( "dmg.club", pBreakableInterface->GetDmgModClub() ) );
pBreakableInterface->SetDmgModExplosive( pSection->GetFloat( "dmg.explosive", pBreakableInterface->GetDmgModExplosive() ) );
// Get the health (unless this is an override prop)
if ( !FClassnameIs( pProp, "prop_physics_override" ) && !FClassnameIs( pProp, "prop_dynamic_override" ) )
{
pProp->SetHealth( pSection->GetInt( "health", pProp->GetHealth() ) );
// Explosive?
pBreakableInterface->SetExplosiveDamage( pSection->GetFloat( "explosive_damage", pBreakableInterface->GetExplosiveDamage() ) );
pBreakableInterface->SetExplosiveRadius( pSection->GetFloat( "explosive_radius", pBreakableInterface->GetExplosiveRadius() ) );
#ifdef GAME_DLL
// If we now have health, we're not allowed to ignore physics damage
if ( pProp->GetHealth() )
{
pProp->RemoveSpawnFlags( SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE );
}
#endif
}
const char *pszBreakableModel;
if ( pBreakableInterface->GetBreakableModel() == NULL_STRING )
{
pszBreakableModel = pSection->GetString( "breakable_model", NULL );
}
else
{
pszBreakableModel = pSection->GetString( "breakable_model", STRING(pBreakableInterface->GetBreakableModel()) );
}
if ( pszBreakableModel && pszBreakableModel[0] )
{
pBreakableInterface->SetBreakableModel( AllocPooledString( pszBreakableModel ) );
}
else
{
pBreakableInterface->SetBreakableModel( NULL_STRING );
}
pBreakableInterface->SetBreakableSkin( pSection->GetInt( "breakable_skin", pBreakableInterface->GetBreakableSkin() ) );
pBreakableInterface->SetBreakableCount( pSection->GetInt( "breakable_count", pBreakableInterface->GetBreakableCount() ) );
// Calculate the maximum size of the breakables this breakable will produce
Vector vecSize = pProp->CollisionProp()->OBBSize();
// Throw away the smallest coord
int iSmallest = SmallestAxis(vecSize);
vecSize[iSmallest] = 1;
float flVolume = vecSize.x * vecSize.y * vecSize.z;
int iMaxSize = floor( flVolume / (32.0*32.0) );
pBreakableInterface->SetMaxBreakableSize( iMaxSize );
// Now parse our interactions
for ( int i = 0; i < PROPINTER_NUM_INTERACTIONS; i++ )
{
// If we hit this assert, we have too many interactions for our current storage solution to handle
Assert( i < 32 );
propdata_interaction_s *pInteraction = &sPropdataInteractionSections[i];
KeyValues *pkvCurrentInter = pInteractionSection->FindKey( pInteraction->pszSectionName );
if ( pkvCurrentInter )
{
char const *pszInterBase = pkvCurrentInter->GetString( pInteraction->pszKeyName );
if ( pszInterBase && pszInterBase[0] && !stricmp( pszInterBase, pInteraction->pszValue ) )
{
pBreakableInterface->SetInteraction( (propdata_interactions_t)i );
}
}
}
// If the base said we're allowed to be static, return that
if ( iBaseResult == PARSE_SUCCEEDED_ALLOWED_STATIC )
return PARSE_SUCCEEDED_ALLOWED_STATIC;
// Otherwise, see if our propdata says we are allowed to be static
if ( pSection->GetInt( "allowstatic", 0 ) )
return PARSE_SUCCEEDED_ALLOWED_STATIC;
return PARSE_SUCCEEDED;
}
//-----------------------------------------------------------------------------
// Purpose: Fill out a prop's with base data parsed from the propdata file
//-----------------------------------------------------------------------------
int CPropData::ParsePropFromBase( CBaseEntity *pProp, const char *pszPropData )
{
if ( !m_bPropDataLoaded )
return PARSE_FAILED_NO_DATA;
IBreakableWithPropData *pBreakableInterface = dynamic_cast<IBreakableWithPropData*>(pProp);
if ( !pBreakableInterface )
{
return PARSE_FAILED_BAD_DATA;
}
if ( !m_pKVPropData )
{
return PARSE_FAILED_BAD_DATA;
}
// Find the specified propdata
KeyValues *pSection = m_pKVPropData->FindKey( pszPropData );
if ( !pSection )
{
Warning("%s '%s' has a base specified as '%s', but there is no matching entry in propdata.txt.\n", pProp->GetClassname(), STRING( pProp->GetModelName() ), pszPropData );
return PARSE_FAILED_BAD_DATA;
}
// Store off the first base data for debugging
if ( pBreakableInterface->GetBasePropData() == NULL_STRING )
{
pBreakableInterface->SetBasePropData( AllocPooledString( pszPropData ) );
}
return ParsePropFromKV( pProp, pSection, pSection );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CPropData::GetRandomChunkModel( const char *pszBreakableSection, int iMaxSize )
{
if ( !m_bPropDataLoaded )
return NULL;
// Find the right section
int iCount = m_BreakableChunks.Count();
int i;
for ( i = 0; i < iCount; i++ )
{
if ( !Q_strncmp( STRING(m_BreakableChunks[i].iszChunkType), pszBreakableSection, strlen(pszBreakableSection) ) )
break;
}
if ( i == iCount )
return NULL;
// Now pick a random one and return it
int iRandom;
if ( iMaxSize == -1 )
{
iRandom = RandomInt( 0, m_BreakableChunks[i].iszChunkModels.Count()-1 );
}
else
{
// Don't pick anything over the specified size
iRandom = RandomInt( 0, min(iMaxSize, m_BreakableChunks[i].iszChunkModels.Count()-1) );
}
return STRING(m_BreakableChunks[i].iszChunkModels[iRandom]);
}
// ensure that a model name from a qc file is properly formatted
static const char *FixupModelName( char *pOut, int sizeOut, const char *pModelNameIn )
{
char tmp[1024];
Q_strncpy( tmp, pModelNameIn, sizeof(tmp) );
if ( Q_strnicmp( tmp, "models/", 7 ) )
{
Q_snprintf( pOut, sizeOut, "models/%s" , tmp );
}
else
{
Q_strncpy( pOut, tmp, sizeOut);
}
int len = Q_strlen(pOut);
if ( len < 4 || Q_stricmp( pOut + (len-4), ".mdl" ) )
{
Q_strncat( pOut, ".mdl", sizeOut, COPY_ALL_CHARACTERS );
}
return pOut;
}
//-----------------------------------------------------------------------------
// breakable prop functions
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
// list of models to break into
class CBreakParser : public IVPhysicsKeyHandler
{
public:
CBreakParser( float defaultBurstScale, int defaultCollisionGroup )
: m_defaultBurstScale(defaultBurstScale), m_defaultCollisionGroup(defaultCollisionGroup) {}
void ParseModelName( breakmodel_t *pModel, const char *pValue )
{
FixupModelName( pModel->modelName, sizeof(pModel->modelName), pValue );
}
virtual void ParseKeyValue( void *pData, const char *pKey, const char *pValue )
{
breakmodel_t *pModel = (breakmodel_t *)pData;
if ( !strcmpi( pKey, "model" ) )
{
ParseModelName( pModel, pValue );
}
else if (!strcmpi( pKey, "ragdoll" ) )
{
ParseModelName( pModel, pValue );
pModel->isRagdoll = true;
}
else if (!strcmpi( pKey, "motiondisabled" ) )
{
pModel->isMotionDisabled = true;
}
else if ( !strcmpi( pKey, "offset" ) )
{
UTIL_StringToVector( pModel->offset.Base(), pValue );
}
else if ( !strcmpi( pKey, "health" ) )
{
pModel->health = atof(pValue);
}
else if ( !strcmpi( pKey, "fadetime" ) )
{
pModel->fadeTime = atof(pValue);
if ( !m_wroteCollisionGroup )
{
pModel->collisionGroup = COLLISION_GROUP_DEBRIS;
}
}
else if ( !strcmpi( pKey, "fademindist" ) )
{
pModel->fadeMinDist = atof(pValue);
}
else if ( !strcmpi( pKey, "fademaxdist" ) )
{
pModel->fadeMaxDist = atof(pValue);
}
else if ( !strcmpi( pKey, "debris" ) )
{
pModel->collisionGroup = atoi(pValue) > 0 ? COLLISION_GROUP_DEBRIS : COLLISION_GROUP_INTERACTIVE;
m_wroteCollisionGroup = true;
}
else if ( !strcmpi( pKey, "burst" ) )
{
pModel->burstScale = atof( pValue );
}
else if ( !strcmpi( pKey, "placementbone" ) )
{
Q_strncpy( pModel->placementName, pValue, sizeof(pModel->placementName) );
pModel->placementIsBone = true;
}
else if ( !strcmpi( pKey, "placementattachment" ) )
{
Q_strncpy( pModel->placementName, pValue, sizeof(pModel->placementName) );
pModel->placementIsBone = false;
}
else if ( !strcmpi( pKey, "multiplayer_break" ) )
{
if ( FStrEq( pValue, "server" ) )
{
pModel->mpBreakMode = MULTIPLAYER_BREAK_SERVERSIDE;
}
else if ( FStrEq( pValue, "client" ) )
{
pModel->mpBreakMode = MULTIPLAYER_BREAK_CLIENTSIDE;
}
}
}
virtual void SetDefaults( void *pData )
{
breakmodel_t *pModel = (breakmodel_t *)pData;
pModel->modelName[0] = 0;
pModel->offset = vec3_origin;
pModel->health = 1;
pModel->fadeTime = 20.0f;
pModel->fadeMinDist = 0.0f;
pModel->fadeMaxDist = 0.0f;
pModel->burstScale = m_defaultBurstScale;
pModel->collisionGroup = m_defaultCollisionGroup;
pModel->isRagdoll = false;
pModel->isMotionDisabled = false;
pModel->placementName[0] = 0;
pModel->placementIsBone = false;
pModel->mpBreakMode = MULTIPLAYER_BREAK_DEFAULT;
m_wroteCollisionGroup = false;
}
private:
int m_defaultCollisionGroup;
float m_defaultBurstScale;
bool m_wroteCollisionGroup;
};
void BreakModelList( CUtlVector<breakmodel_t> &list, int modelindex, float defBurstScale, int defCollisionGroup )
{
vcollide_t *pCollide = modelinfo->GetVCollide( modelindex );
if ( !pCollide )
return;
IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide->pKeyValues );
while ( !pParse->Finished() )
{
CBreakParser breakParser( defBurstScale, defCollisionGroup );
const char *pBlock = pParse->GetCurrentBlockName();
if ( !strcmpi( pBlock, "break" ) )
{
int index = list.AddToTail();
breakmodel_t &breakModel = list[index];
pParse->ParseCustom( &breakModel, &breakParser );
}
else
{
pParse->SkipBlock();
}
}
physcollision->VPhysicsKeyParserDestroy( pParse );
}
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
int GetAutoMultiplayerPhysicsMode( Vector size, float mass )
{
float volume = size.x * size.y * size.z;
float minsize = sv_pushaway_clientside_size.GetFloat();
// if it's too small, client side only
if ( volume < (minsize*minsize*minsize) )
return PHYSICS_MULTIPLAYER_CLIENTSIDE;
// if it's too light, no player pushback
if ( mass < 8.0 )
return PHYSICS_MULTIPLAYER_NON_SOLID;
// full pushbackmode
return PHYSICS_MULTIPLAYER_SOLID;
}
#else
extern int GetAutoMultiplayerPhysicsMode( Vector size, float mass );
#endif
//-----------------------------------------------------------------------------
// Purpose: Returns a string describing a real-world equivalent mass.
// Input : flMass - mass in kg
//-----------------------------------------------------------------------------
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
const char *GetMassEquivalent(float flMass)
{
static struct
{
float flMass;
char *sz;
} masstext[] =
{
{ 5e-6, "snowflake" },
{ 2.5e-3, "ping-pong ball" },
{ 5e-3, "penny" },
{ 0.05, "golf ball" },
{ 0.17, "billard ball" },
{ 2, "bag of sugar" },
{ 7, "male cat" },
{ 10, "bowling ball" },
{ 30, "dog" },
{ 60, "cheetah" },
{ 90, "adult male human" },
{ 250, "refrigerator" },
{ 600, "race horse" },
{ 1000, "small car" },
{ 1650, "medium car" },
{ 2500, "large car" },
{ 6000, "t-rex" },
{ 7200, "elephant" },
{ 8e4, "space shuttle" },
{ 7e5, "locomotive" },
{ 9.2e6, "Eiffel tower" },
{ 6e24, "the Earth" },
{ 7e24, "really freaking heavy" },
};
for (int i = 0; i < sizeof(masstext) / sizeof(masstext[0]) - 1; i++)
{
if (flMass < masstext[i].flMass)
{
return masstext[i].sz;
}
}
return masstext[ sizeof(masstext) / sizeof(masstext[0]) - 1 ].sz;
}
#else
extern const char *GetMassEquivalent(float flMass);
#endif
#ifdef GAME_DLL
//=========================================================
//=========================================================
class CGameGibManager : public CBaseEntity
{
DECLARE_CLASS( CGameGibManager, CBaseEntity );
DECLARE_DATADESC();
public:
CGameGibManager() : m_iCurrentMaxPieces(-1), m_iMaxPieces(-1), m_iMaxPiecesDX8(-1) {}
void Activate( void );
void AddGibToLRU( CBaseAnimating *pEntity );
inline bool AllowedToSpawnGib( void );
private:
void UpdateMaxPieces();
void InputSetMaxPieces( inputdata_t &inputdata );
void InputSetMaxPiecesDX8( inputdata_t &inputdata );
typedef CHandle<CBaseAnimating> CGibHandle;
CUtlLinkedList< CGibHandle > m_LRU;
bool m_bAllowNewGibs;
int m_iDXLevel;
int m_iCurrentMaxPieces;
int m_iMaxPieces;
int m_iMaxPiecesDX8;
int m_iLastFrame;
};
BEGIN_DATADESC( CGameGibManager )
// Silence perfidous classcheck!
//DEFINE_FIELD( m_iCurrentMaxPieces, FIELD_INTEGER ),
//DEFINE_FIELD( m_iLastFrame, FIELD_INTEGER ),
//DEFINE_FIELD( m_iDXLevel, FIELD_INTEGER ),
DEFINE_KEYFIELD( m_iMaxPieces, FIELD_INTEGER, "maxpieces" ),
DEFINE_KEYFIELD( m_iMaxPiecesDX8, FIELD_INTEGER, "maxpiecesdx8" ),
DEFINE_KEYFIELD( m_bAllowNewGibs, FIELD_BOOLEAN, "allownewgibs" ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetMaxPieces", InputSetMaxPieces ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetMaxPiecesDX8", InputSetMaxPiecesDX8 ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( game_gib_manager, CGameGibManager );
void CGameGibManager::Activate( void )
{
m_LRU.Purge();
// Cache off the DX level for use later.
ConVarRef mat_dxlevel( "mat_dxlevel" );
m_iDXLevel = mat_dxlevel.GetInt();
UpdateMaxPieces();
BaseClass::Activate();
}
void CGameGibManager::UpdateMaxPieces()
{
// If we're running DX8, use the DX8 gib limit if set.
if ( ( m_iDXLevel < 90 ) && ( m_iMaxPiecesDX8 >= 0 ) )
{
m_iCurrentMaxPieces = m_iMaxPiecesDX8;
}
else
{
m_iCurrentMaxPieces = m_iMaxPieces;
}
}
bool CGameGibManager::AllowedToSpawnGib( void )
{
if ( m_bAllowNewGibs )
return true;
// We're not tracking gibs at the moment
if ( m_iCurrentMaxPieces < 0 )
return true;
if ( m_iCurrentMaxPieces == 0 )
return false;
if ( m_iLastFrame == gpGlobals->framecount )
{
if ( m_LRU.Count() >= m_iCurrentMaxPieces )
{
return false;
}
}
return true;
}
void CGameGibManager::InputSetMaxPieces( inputdata_t &inputdata )
{
m_iMaxPieces = inputdata.value.Int();
UpdateMaxPieces();
}
void CGameGibManager::InputSetMaxPiecesDX8( inputdata_t &inputdata )
{
m_iMaxPiecesDX8 = inputdata.value.Int();
UpdateMaxPieces();
}
void CGameGibManager::AddGibToLRU( CBaseAnimating *pEntity )
{
int i, next;
if ( pEntity == NULL )
return;
//Find stale gibs.
for ( i = m_LRU.Head(); i < m_LRU.InvalidIndex(); i = next )
{
next = m_LRU.Next(i);
if ( m_LRU[i].Get() == NULL )
{
m_LRU.Remove(i);
}
}
// We're not tracking gibs at the moment
if ( m_iCurrentMaxPieces <= 0 )
return;
while ( m_LRU.Count() >= m_iCurrentMaxPieces )
{
i = m_LRU.Head();
//TODO: Make this fade out instead of pop.
UTIL_Remove( m_LRU[i] );
m_LRU.Remove(i);
}
m_LRU.AddToTail( pEntity );
m_iLastFrame = gpGlobals->framecount;
}
EHANDLE g_hGameGibManager;
CGameGibManager *GetGibManager( void )
{
#ifndef HL2_EPISODIC
return NULL;
#endif
if ( g_hGameGibManager == NULL )
{
g_hGameGibManager = (CGameGibManager *)gEntList.FindEntityByClassname( NULL, "game_gib_manager" );
}
return (CGameGibManager *)g_hGameGibManager.Get();
}
#endif
void PropBreakableCreateAll( int modelindex, IPhysicsObject *pPhysics, const breakablepropparams_t ¶ms, CBaseEntity *pEntity, int iPrecomputedBreakableCount, bool bIgnoreGibLimit, bool defaultLocation )
{
// Check for prop breakable count reset.
int nPropCount = props_break_max_pieces_perframe.GetInt();
if ( nPropCount != -1 )
{
if ( nFrameNumber != gpGlobals->framecount )
{
nPropBreakablesPerFrameCount = 0;
nFrameNumber = gpGlobals->framecount;
}
// Check for max breakable count for the frame.
if ( nPropBreakablesPerFrameCount >= nPropCount )
return;
}
int iMaxBreakCount = bIgnoreGibLimit ? -1 : props_break_max_pieces.GetInt();
if ( iMaxBreakCount != -1 )
{
if ( iPrecomputedBreakableCount != -1 )
{
iPrecomputedBreakableCount = min( iMaxBreakCount, iPrecomputedBreakableCount );
}
else
{
iPrecomputedBreakableCount = iMaxBreakCount;
}
}
#ifdef GAME_DLL
// On server limit break model creation
if ( !PropBreakableCapEdictsOnCreateAll(modelindex, pPhysics, params, pEntity, iPrecomputedBreakableCount ) )
{
DevMsg( "Failed to create PropBreakable: would exceed MAX_EDICTS\n" );
return;
}
#endif
vcollide_t *pCollide = modelinfo->GetVCollide( modelindex );
if ( !pCollide )
return;
int nSkin = 0;
CBaseEntity *pOwnerEntity = pEntity;
CBaseAnimating *pOwnerAnim = NULL;
if ( pPhysics )
{
pOwnerEntity = static_cast<CBaseEntity *>(pPhysics->GetGameData());
}
if ( pOwnerEntity )
{
pOwnerAnim = pOwnerEntity->GetBaseAnimating();
if ( pOwnerAnim )
{
nSkin = pOwnerAnim->m_nSkin;
}
}
matrix3x4_t localToWorld;
CStudioHdr studioHdr;
const model_t *model = modelinfo->GetModel( modelindex );
if ( model )
{
studioHdr.Init( modelinfo->GetStudiomodel( model ) );
}
Vector parentOrigin = vec3_origin;
int parentAttachment = Studio_FindAttachment( &studioHdr, "placementOrigin" ) + 1;
if ( parentAttachment > 0 )
{
GetAttachmentLocalSpace( &studioHdr, parentAttachment-1, localToWorld );
MatrixGetColumn( localToWorld, 3, parentOrigin );
}
else
{
AngleMatrix( vec3_angle, localToWorld );
}
CUtlVector<breakmodel_t> list;
BreakModelList( list, modelindex, params.defBurstScale, params.defCollisionGroup );
if ( list.Count() )
{
for ( int i = 0; i < list.Count(); i++ )
{
int modelIndex = modelinfo->GetModelIndex( list[i].modelName );
if ( modelIndex <= 0 )
continue;
// Skip multiplayer pieces that should be spawning on the other dll
#ifdef GAME_DLL
if ( gpGlobals->maxClients > 1 && breakable_multiplayer.GetBool() )
#else
if ( gpGlobals->maxClients > 1 )
#endif
{
#ifdef GAME_DLL
if ( list[i].mpBreakMode == MULTIPLAYER_BREAK_CLIENTSIDE )
continue;
#else
if ( list[i].mpBreakMode == MULTIPLAYER_BREAK_SERVERSIDE )
continue;
#endif
if ( !defaultLocation && list[i].mpBreakMode == MULTIPLAYER_BREAK_DEFAULT )
continue;
}
if ( ( nPropCount != -1 ) && ( nPropBreakablesPerFrameCount > nPropCount ) )
break;
if ( ( iPrecomputedBreakableCount != -1 ) && ( i >= iPrecomputedBreakableCount ) )
break;
matrix3x4_t matrix;
AngleMatrix( params.angles, params.origin, matrix );
CStudioHdr studioHdr;
const model_t *model = modelinfo->GetModel( modelIndex );
if ( model )
{
studioHdr.Init( modelinfo->GetStudiomodel( model ) );
}
// Increment the number of breakable props this frame.
++nPropBreakablesPerFrameCount;
Vector position = vec3_origin;
QAngle angles = params.angles;
if ( pOwnerAnim && list[i].placementName[0] )
{
if ( list[i].placementIsBone )
{
int boneIndex = pOwnerAnim->LookupBone( list[i].placementName );
if ( boneIndex >= 0 )
{
pOwnerAnim->GetBonePosition( boneIndex, position, angles );
AngleMatrix( angles, position, matrix );
}
}
else
{
int attachmentIndex = Studio_FindAttachment( &studioHdr, list[i].placementName ) + 1;
if ( attachmentIndex > 0 )
{
pOwnerAnim->GetAttachment( attachmentIndex, matrix );
MatrixAngles( matrix, angles );
}
}
}
else
{
int placementIndex = Studio_FindAttachment( &studioHdr, "placementOrigin" ) + 1;
Vector placementOrigin = parentOrigin;
if ( placementIndex > 0 )
{
GetAttachmentLocalSpace( &studioHdr, placementIndex-1, localToWorld );
MatrixGetColumn( localToWorld, 3, placementOrigin );
placementOrigin -= parentOrigin;
}
VectorTransform( list[i].offset - placementOrigin, matrix, position );
}
Vector objectVelocity = params.velocity;
if (pPhysics)
{
pPhysics->GetVelocityAtPoint( position, &objectVelocity );
}
int nActualSkin = nSkin;
if ( nActualSkin > studioHdr.numskinfamilies() )
nActualSkin = 0;
CBaseEntity *pBreakable = NULL;
#ifdef GAME_DLL
if ( GetGibManager() == NULL || GetGibManager()->AllowedToSpawnGib() )
#endif
{
pBreakable = BreakModelCreateSingle( pOwnerEntity, &list[i], position, angles, objectVelocity, params.angularVelocity, nActualSkin, params );
}
if ( pBreakable )
{
#ifdef GAME_DLL
if ( GetGibManager() )
{
GetGibManager()->AddGibToLRU( pBreakable->GetBaseAnimating() );
}
#endif
if ( pOwnerEntity && pOwnerEntity->IsEffectActive( EF_NOSHADOW ) )
{
pBreakable->AddEffects( EF_NOSHADOW );
}
// If burst scale is set, this piece should 'burst' away from
// the origin in addition to travelling in the wished velocity.
if ( list[i].burstScale != 0.0 )
{
Vector vecBurstDir = position - params.origin;
// If $autocenter wasn't used, try the center of the piece
if ( vecBurstDir == vec3_origin )
{
vecBurstDir = pBreakable->WorldSpaceCenter() - params.origin;
}
VectorNormalize( vecBurstDir );
pBreakable->ApplyAbsVelocityImpulse( vecBurstDir * list[i].burstScale );
}
// If this piece is supposed to be motion disabled, disable it
if ( list[i].isMotionDisabled )
{
IPhysicsObject *pPhysicsObject = pBreakable->VPhysicsGetObject();
if ( pPhysicsObject != NULL )
{
pPhysicsObject->EnableMotion( false );
}
}
}
}
}
// Then see if the propdata specifies any breakable pieces
else if ( pEntity )
{
IBreakableWithPropData *pBreakableInterface = dynamic_cast<IBreakableWithPropData*>(pEntity);
if ( pBreakableInterface && pBreakableInterface->GetBreakableModel() != NULL_STRING && pBreakableInterface->GetBreakableCount() )
{
breakmodel_t breakModel;
for ( int i = 0; i < pBreakableInterface->GetBreakableCount(); i++ )
{
if ( ( iPrecomputedBreakableCount != -1 ) && ( i >= iPrecomputedBreakableCount ) )
break;
Q_strncpy( breakModel.modelName, g_PropDataSystem.GetRandomChunkModel(STRING(pBreakableInterface->GetBreakableModel()), pBreakableInterface->GetMaxBreakableSize()), sizeof(breakModel.modelName) );
breakModel.health = 1;
breakModel.fadeTime = RandomFloat(5,10);
breakModel.fadeMinDist = 0.0f;
breakModel.fadeMaxDist = 0.0f;
breakModel.burstScale = params.defBurstScale;
breakModel.collisionGroup = COLLISION_GROUP_DEBRIS;
breakModel.isRagdoll = false;
breakModel.isMotionDisabled = false;
breakModel.placementName[0] = 0;
breakModel.placementIsBone = false;
Vector vecObbSize = pEntity->CollisionProp()->OBBSize();
// Find a random point on the plane of the original's two largest axis
int smallestAxis = SmallestAxis( vecObbSize );
Vector vecMins(0,0,0);
Vector vecMaxs(1,1,1);
vecMins[smallestAxis] = 0.5;
vecMaxs[smallestAxis] = 0.5;
pEntity->CollisionProp()->RandomPointInBounds( vecMins, vecMaxs, &breakModel.offset );
// Push all chunks away from the center
Vector vecBurstDir = breakModel.offset - params.origin;
VectorNormalize( vecBurstDir );
Vector vecVelocity = vecBurstDir * params.defBurstScale;
QAngle vecAngles = pEntity->GetAbsAngles();
int iSkin = pBreakableInterface->GetBreakableSkin();
CBaseEntity *pBreakable = NULL;
#ifdef GAME_DLL
if ( GetGibManager() == NULL || GetGibManager()->AllowedToSpawnGib() )
#endif
{
pBreakable = BreakModelCreateSingle( pOwnerEntity, &breakModel, breakModel.offset, vecAngles, vecVelocity, vec3_origin/*params.angularVelocity*/, iSkin, params );
if ( !pBreakable )
{
DevWarning( "PropBreakableCreateAll: Could not create model %s\n", breakModel.modelName );
}
}
if ( pBreakable )
{
#ifdef GAME_DLL
if ( GetGibManager() )
{
GetGibManager()->AddGibToLRU( pBreakable->GetBaseAnimating() );
}
#endif
Vector vecBreakableObbSize = pBreakable->CollisionProp()->OBBSize();
// Try to align the gibs along the original axis
matrix3x4_t matrix;
AngleMatrix( vecAngles, matrix );
AlignBoxes( &matrix, vecObbSize, vecBreakableObbSize );
MatrixAngles( matrix, vecAngles );
if ( pBreakable->VPhysicsGetObject() )
{
Vector pos;
pBreakable->VPhysicsGetObject()->GetPosition( &pos, NULL );
pBreakable->VPhysicsGetObject()->SetPosition( pos, vecAngles, true );
}
pBreakable->SetAbsAngles( vecAngles );
if ( pOwnerEntity->IsEffectActive( EF_NOSHADOW ) )
{
pBreakable->AddEffects( EF_NOSHADOW );
}
}
}
}
}
}
void PropBreakableCreateAll( int modelindex, IPhysicsObject *pPhysics, const Vector &origin, const QAngle &angles, const Vector &velocity, const AngularImpulse &angularVelocity, float impactEnergyScale, float defBurstScale, int defCollisionGroup, CBaseEntity *pEntity, bool defaultLocation )
{
breakablepropparams_t params( origin, angles, velocity, angularVelocity );
params.impactEnergyScale = impactEnergyScale;
params.defBurstScale = defBurstScale;
params.defCollisionGroup = defCollisionGroup;
PropBreakableCreateAll( modelindex, pPhysics, params, pEntity, -1, false, defaultLocation );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : modelindex -
//-----------------------------------------------------------------------------
void PrecacheGibsForModel( int iModel )
{
vcollide_t *pCollide = modelinfo->GetVCollide( iModel );
if ( !pCollide )
return;
// The scale and group doesn't really matter at the moment, we are just using the parser to get the model name to cache.
CBreakParser breakParser( 1.0, COLLISION_GROUP_NONE );
// Create a parser.
IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide->pKeyValues );
while ( !pParse->Finished() )
{
const char *pBlock = pParse->GetCurrentBlockName();
if ( !strcmpi( pBlock, "break" ) )
{
breakmodel_t breakModel;
pParse->ParseCustom( &breakModel, &breakParser );
CBaseEntity::PrecacheModel( breakModel.modelName );
}
else
{
pParse->SkipBlock();
}
}
// Destroy the parser.
physcollision->VPhysicsKeyParserDestroy( pParse );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &list -
// modelindex -
// defBurstScale -
// defCollisionGroup -
//-----------------------------------------------------------------------------
void BuildGibList( CUtlVector<breakmodel_t> &list, int modelindex, float defBurstScale, int defCollisionGroup )
{
BreakModelList( list, modelindex, defBurstScale, defCollisionGroup );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &list -
// modelindex -
// *pPhysics -
// ¶ms -
// *pEntity -
// iPrecomputedBreakableCount -
// bIgnoreGibLImit -
// defaultLocation -
//-----------------------------------------------------------------------------
CBaseEntity *CreateGibsFromList( CUtlVector<breakmodel_t> &list, int modelindex, IPhysicsObject *pPhysics, const breakablepropparams_t ¶ms, CBaseEntity *pEntity, int iPrecomputedBreakableCount, bool bIgnoreGibLimit, bool defaultLocation, CUtlVector<EHANDLE> *pGibList )
{
// Check for prop breakable count reset.
int nPropCount = props_break_max_pieces_perframe.GetInt();
if ( nPropCount != -1 )
{
if ( nFrameNumber != gpGlobals->framecount )
{
nPropBreakablesPerFrameCount = 0;
nFrameNumber = gpGlobals->framecount;
}
// Check for max breakable count for the frame.
if ( nPropBreakablesPerFrameCount >= nPropCount )
return NULL;
}
int iMaxBreakCount = bIgnoreGibLimit ? -1 : props_break_max_pieces.GetInt();
if ( iMaxBreakCount != -1 )
{
if ( iPrecomputedBreakableCount != -1 )
{
iPrecomputedBreakableCount = min( iMaxBreakCount, iPrecomputedBreakableCount );
}
else
{
iPrecomputedBreakableCount = iMaxBreakCount;
}
}
#ifdef GAME_DLL
// On server limit break model creation
if ( !PropBreakableCapEdictsOnCreateAll(modelindex, pPhysics, params, pEntity, iPrecomputedBreakableCount ) )
{
DevMsg( "Failed to create PropBreakable: would exceed MAX_EDICTS\n" );
return NULL;
}
#endif
vcollide_t *pCollide = modelinfo->GetVCollide( modelindex );
if ( !pCollide )
return NULL;
int nSkin = 0;
CBaseEntity *pOwnerEntity = pEntity;
CBaseAnimating *pOwnerAnim = NULL;
if ( pPhysics )
{
pOwnerEntity = static_cast<CBaseEntity *>(pPhysics->GetGameData());
}
if ( pOwnerEntity )
{
pOwnerAnim = dynamic_cast<CBaseAnimating*>(pOwnerEntity);
if ( pOwnerAnim )
{
nSkin = pOwnerAnim->m_nSkin;
}
}
matrix3x4_t localToWorld;
CStudioHdr studioHdr;
const model_t *model = modelinfo->GetModel( modelindex );
if ( model )
{
studioHdr.Init( modelinfo->GetStudiomodel( model ) );
}
Vector parentOrigin = vec3_origin;
int parentAttachment = Studio_FindAttachment( &studioHdr, "placementOrigin" ) + 1;
if ( parentAttachment > 0 )
{
GetAttachmentLocalSpace( &studioHdr, parentAttachment-1, localToWorld );
MatrixGetColumn( localToWorld, 3, parentOrigin );
}
else
{
AngleMatrix( vec3_angle, localToWorld );
}
// CUtlVector<breakmodel_t> list;
// BreakModelList( list, modelindex, params.defBurstScale, params.defCollisionGroup );
CBaseEntity *pFirstBreakable = NULL;
if ( list.Count() )
{
for ( int i = 0; i < list.Count(); i++ )
{
int modelIndex = modelinfo->GetModelIndex( list[i].modelName );
if ( modelIndex <= 0 )
continue;
// Skip multiplayer pieces that should be spawning on the other dll
#ifdef GAME_DLL
if ( gpGlobals->maxClients > 1 && breakable_multiplayer.GetBool() )
#else
if ( gpGlobals->maxClients > 1 )
#endif
{
#ifdef GAME_DLL
if ( list[i].mpBreakMode == MULTIPLAYER_BREAK_CLIENTSIDE )
continue;
#else
if ( list[i].mpBreakMode == MULTIPLAYER_BREAK_SERVERSIDE )
continue;
#endif
if ( !defaultLocation && list[i].mpBreakMode == MULTIPLAYER_BREAK_DEFAULT )
continue;
}
if ( ( nPropCount != -1 ) && ( nPropBreakablesPerFrameCount > nPropCount ) )
break;
if ( ( iPrecomputedBreakableCount != -1 ) && ( i >= iPrecomputedBreakableCount ) )
break;
matrix3x4_t matrix;
AngleMatrix( params.angles, params.origin, matrix );
CStudioHdr studioHdr;
const model_t *model = modelinfo->GetModel( modelIndex );
if ( model )
{
studioHdr.Init( modelinfo->GetStudiomodel( model ) );
}
// Increment the number of breakable props this frame.
++nPropBreakablesPerFrameCount;
Vector position = vec3_origin;
QAngle angles = params.angles;
if ( pOwnerAnim && list[i].placementName[0] )
{
if ( list[i].placementIsBone )
{
int boneIndex = pOwnerAnim->LookupBone( list[i].placementName );
if ( boneIndex >= 0 )
{
pOwnerAnim->GetBonePosition( boneIndex, position, angles );
AngleMatrix( angles, position, matrix );
}
}
else
{
int attachmentIndex = Studio_FindAttachment( &studioHdr, list[i].placementName ) + 1;
if ( attachmentIndex > 0 )
{
pOwnerAnim->GetAttachment( attachmentIndex, matrix );
MatrixAngles( matrix, angles );
}
}
}
else
{
int placementIndex = Studio_FindAttachment( &studioHdr, "placementOrigin" ) + 1;
Vector placementOrigin = parentOrigin;
if ( placementIndex > 0 )
{
GetAttachmentLocalSpace( &studioHdr, placementIndex-1, localToWorld );
MatrixGetColumn( localToWorld, 3, placementOrigin );
placementOrigin -= parentOrigin;
}
VectorTransform( list[i].offset - placementOrigin, matrix, position );
}
Vector objectVelocity = params.velocity;
float flScale = VectorNormalize( objectVelocity );
objectVelocity.x += RandomFloat( -1.f, 1.0f );
objectVelocity.y += RandomFloat( -1.0f, 1.0f );
objectVelocity.z += RandomFloat( 0.0f, 1.0f );
VectorNormalize( objectVelocity );
objectVelocity *= flScale;
if (pPhysics)
{
pPhysics->GetVelocityAtPoint( position, &objectVelocity );
}
int nActualSkin = nSkin;
if ( nActualSkin > studioHdr.numskinfamilies() )
nActualSkin = 0;
CBaseEntity *pBreakable = NULL;
#ifdef GAME_DLL
if ( GetGibManager() == NULL || GetGibManager()->AllowedToSpawnGib() )
#endif
{
pBreakable = BreakModelCreateSingle( pOwnerEntity, &list[i], position, angles, objectVelocity, params.angularVelocity, nActualSkin, params );
}
if ( pBreakable )
{
#ifdef GAME_DLL
if ( GetGibManager() )
{
GetGibManager()->AddGibToLRU( pBreakable->GetBaseAnimating() );
}
#endif
if ( pOwnerEntity && pOwnerEntity->IsEffectActive( EF_NOSHADOW ) )
{
pBreakable->AddEffects( EF_NOSHADOW );
}
// If burst scale is set, this piece should 'burst' away from
// the origin in addition to travelling in the wished velocity.
if ( list[i].burstScale != 0.0 )
{
Vector vecBurstDir = position - params.origin;
// If $autocenter wasn't used, try the center of the piece
if ( vecBurstDir == vec3_origin )
{
vecBurstDir = pBreakable->WorldSpaceCenter() - params.origin;
}
VectorNormalize( vecBurstDir );
pBreakable->ApplyAbsVelocityImpulse( vecBurstDir * list[i].burstScale );
}
// If this piece is supposed to be motion disabled, disable it
if ( list[i].isMotionDisabled )
{
IPhysicsObject *pPhysicsObject = pBreakable->VPhysicsGetObject();
if ( pPhysicsObject != NULL )
{
pPhysicsObject->EnableMotion( false );
}
}
if ( !pFirstBreakable )
{
pFirstBreakable = pBreakable;
}
if ( pGibList )
{
pGibList->AddToTail( pBreakable );
}
}
}
}
// Then see if the propdata specifies any breakable pieces
else if ( pEntity )
{
IBreakableWithPropData *pBreakableInterface = dynamic_cast<IBreakableWithPropData*>(pEntity);
if ( pBreakableInterface && pBreakableInterface->GetBreakableModel() != NULL_STRING && pBreakableInterface->GetBreakableCount() )
{
breakmodel_t breakModel;
for ( int i = 0; i < pBreakableInterface->GetBreakableCount(); i++ )
{
if ( ( iPrecomputedBreakableCount != -1 ) && ( i >= iPrecomputedBreakableCount ) )
break;
Q_strncpy( breakModel.modelName, g_PropDataSystem.GetRandomChunkModel(STRING(pBreakableInterface->GetBreakableModel()), pBreakableInterface->GetMaxBreakableSize()), sizeof(breakModel.modelName) );
breakModel.health = 1;
breakModel.fadeTime = RandomFloat(5,10);
breakModel.fadeMinDist = 0.0f;
breakModel.fadeMaxDist = 0.0f;
breakModel.burstScale = params.defBurstScale;
breakModel.collisionGroup = COLLISION_GROUP_DEBRIS;
breakModel.isRagdoll = false;
breakModel.isMotionDisabled = false;
breakModel.placementName[0] = 0;
breakModel.placementIsBone = false;
Vector vecObbSize = pEntity->CollisionProp()->OBBSize();
// Find a random point on the plane of the original's two largest axis
int smallestAxis = SmallestAxis( vecObbSize );
Vector vecMins(0,0,0);
Vector vecMaxs(1,1,1);
vecMins[smallestAxis] = 0.5;
vecMaxs[smallestAxis] = 0.5;
pEntity->CollisionProp()->RandomPointInBounds( vecMins, vecMaxs, &breakModel.offset );
// Push all chunks away from the center
Vector vecBurstDir = breakModel.offset - params.origin;
VectorNormalize( vecBurstDir );
Vector vecVelocity = vecBurstDir * params.defBurstScale;
QAngle vecAngles = pEntity->GetAbsAngles();
int iSkin = pBreakableInterface->GetBreakableSkin();
CBaseEntity *pBreakable = NULL;
#ifdef GAME_DLL
if ( GetGibManager() == NULL || GetGibManager()->AllowedToSpawnGib() )
#endif
{
pBreakable = BreakModelCreateSingle( pOwnerEntity, &breakModel, breakModel.offset, vecAngles, vecVelocity, vec3_origin/*params.angularVelocity*/, iSkin, params );
}
if( pBreakable )
{
#ifdef GAME_DLL
if ( GetGibManager() )
{
GetGibManager()->AddGibToLRU( pBreakable->GetBaseAnimating() );
}
#endif
Vector vecBreakableObbSize = pBreakable->CollisionProp()->OBBSize();
// Try to align the gibs along the original axis
matrix3x4_t matrix;
AngleMatrix( vecAngles, matrix );
AlignBoxes( &matrix, vecObbSize, vecBreakableObbSize );
MatrixAngles( matrix, vecAngles );
if ( pBreakable->VPhysicsGetObject() )
{
Vector pos;
pBreakable->VPhysicsGetObject()->GetPosition( &pos, NULL );
pBreakable->VPhysicsGetObject()->SetPosition( pos, vecAngles, true );
}
pBreakable->SetAbsAngles( vecAngles );
if ( pOwnerEntity->IsEffectActive( EF_NOSHADOW ) )
{
pBreakable->AddEffects( EF_NOSHADOW );
}
if ( !pFirstBreakable )
{
pFirstBreakable = pBreakable;
}
if ( pGibList )
{
pGibList->AddToTail( pBreakable );
}
}
else
{
DevWarning( "PropBreakableCreateAll: Could not create model %s\n", breakModel.modelName );
}
}
}
}
return pFirstBreakable;
}
|
[
"sean@csnxs.uk"
] |
sean@csnxs.uk
|
5004dc883504cd280f7e544c8724c20624c2d6f6
|
cb0e7d6493b23e870aa625eb362384a10f5ee657
|
/solutions/cpp/0712.cpp
|
bcc20e90c873e8a4830b003de17074309196aba5
|
[] |
no_license
|
sweetpand/LeetCode-1
|
0acfa603af254a3350d457803449a91322f2d1a7
|
65f4ef26cb8b2db0b4bf8c42bfdc76421b479f94
|
refs/heads/master
| 2022-11-14T07:01:42.502172
| 2020-07-12T12:25:56
| 2020-07-12T12:25:56
| 279,088,171
| 1
| 0
| null | 2020-07-12T15:03:20
| 2020-07-12T15:03:19
| null |
UTF-8
|
C++
| false
| false
| 672
|
cpp
|
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
const int m = s1.length();
const int n = s2.length();
// dp[i][j] := min cost to make s1[0..i) and s2[0..j) equal
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; ++i)
dp[i][0] = dp[i - 1][0] + s1[i - 1];
for (int j = 1; j <= n; ++j)
dp[0][j] = dp[0][j - 1] + s2[j - 1];
for (int i = 1; i <= m; ++i)
for (int j = 1; j <= n; ++j)
if (s1[i - 1] == s2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]);
return dp[m][n];
}
};
|
[
"walkccray@gmail.com"
] |
walkccray@gmail.com
|
c1048c06106d3a3922a0e6a2f780ebda2c7e87cb
|
573a091f6782bf04a73d12a39ea12e860ec3dddb
|
/hw2/strLiteral.cpp
|
efd58bb317053d6ec41e970c03005e040e37152f
|
[] |
no_license
|
askoulwassim/Software-Design
|
e61f4e7ff78021925c7d0ae6cd511971992b32b0
|
61e606a97532c188c636e0dc7206d3f4d2e4c4d5
|
refs/heads/master
| 2020-04-08T01:21:41.694341
| 2018-11-24T01:31:51
| 2018-11-24T01:31:51
| 158,890,732
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 627
|
cpp
|
#include <iostream>
using namespace std;
int main()
{
cout << "How old are you \? \n I am 20 years old..\b " << endl;
cout << "Name \t\t Surname \v " << endl;
cout << "Elif Ilaria \t Yurtseven " << endl;
cout << "So I am trying to figure \r out whether this will create a new line or not" << endl; /*I have not understood what the carriage return does */
cout << "I think this sentence will be in \\ two lines" << endl;
char a = 'a';
cout << a << endl;
cout << "I will try to make the \f key work" << endl;
cout << "this supposively " "shouldn't look like " "separate pieces of a sentence" "." << endl;
}
|
[
"noreply@github.com"
] |
askoulwassim.noreply@github.com
|
32f3a140f2c31349018e3dfc9ed0acf32adbdf5c
|
9c079c10fb9f90ff15181b3bdd50ea0435fbc0cd
|
/hw/Dynamic Programming/coinchnge.cpp
|
cd6fda63d5d057e2262fcc0c95f81dd6584a5291
|
[] |
no_license
|
shihab122/Competitive-Programming
|
73d5bd89a97f28c8358796367277c9234caaa9a4
|
37b94d267fa03edf02110fd930fb9d80fbbe6552
|
refs/heads/master
| 2023-04-02T20:57:50.685625
| 2023-03-25T09:47:13
| 2023-03-25T09:47:13
| 148,019,792
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 517
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int no_ofcoin;
cin>>no_ofcoin;
int coin[no_ofcoin];
for(int i=0;i<no_ofcoin;i++) cin>>coin[i];
int amount;
cin>>amount;
int taka[amount+1];
memset(taka,INT_MAX,sizeof(taka));
taka[0]=0;
for(int i=0;i<no_ofcoin;i++){
for(int j=1;j<=amount;j++){
if(j<coin[i]) continue;
int x=j-coin[i];
taka[j]=min(taka[j],x+1);
}
}
cout<<taka[amount]<<endl;
return 0;
}
|
[
"shihabhossain611@gmail.com"
] |
shihabhossain611@gmail.com
|
fdbe89fba09f1e639cfa3878db14dab28731d9fc
|
47104268ae7603b55c70422364288867b7bc75b8
|
/leetcode/leet836.cpp
|
172f7f6346ae5fcb5497fc1357d7d3ec3a29ad38
|
[
"Apache-2.0"
] |
permissive
|
LABZHG/AlgorithmsTraining-
|
d6ca8bd1d038a9131521730868dcdc5cac073b7d
|
cf56591927cc3e664a7d96363dcce880009c2c31
|
refs/heads/master
| 2020-12-30T08:40:13.724728
| 2020-04-23T15:53:58
| 2020-04-23T15:53:58
| 238,933,511
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,431
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
int judge=(rec1[2]<=rec2[0] || rec1[0]>=rec2[2] || rec1[1]>=rec2[3] || rec1[3]<=rec2[1]);
return !judge;
}
};
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
char delim = ',';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
string boolToString(bool input) {
return input ? "True" : "False";
}
int main() {
string line;
while (getline(cin, line)) {
vector<int> rec1 = stringToIntegerVector(line);
getline(cin, line);
vector<int> rec2 = stringToIntegerVector(line);
bool ret = Solution().isRectangleOverlap(rec1, rec2);
string out = boolToString(ret);
cout << out << endl;
}
return 0;
}
|
[
"hg250250@126.com"
] |
hg250250@126.com
|
93fd7de52836185f240197436de93b1deb615e6e
|
285b4638f208afcb523feeea18bc5c6ad1ff0adc
|
/Backjoon/Line Sweeping/(2836)수상 택시.cpp
|
42cfcc17773dfeec64fe266fc7826e01b7203d85
|
[] |
no_license
|
Kuril951/ICPC_Study
|
8941b8b86e3c12eef3858e2cbf880f84523bac7a
|
78cd99b50fe05983e459672ae2f1c5ec6011cd17
|
refs/heads/master
| 2018-10-21T12:42:44.542883
| 2018-10-04T07:05:18
| 2018-10-04T07:05:18
| 116,656,800
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 683
|
cpp
|
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
vector<pair<int, int>> v;
int main()
{
int N, M;
scanf("%d %d", &N, &M);
for(int i=0; i<N; i++){
int a, b;
scanf("%d %d",&a, &b);
if(a > b)
v.emplace_back(make_pair(b, a));
}
sort(v.begin(), v.end());
int s = 0, e = 0;
long long res = 0;
for(int i=0; i<v.size(); i++){
if(e < v[i].first){
res += (e - s) * 2;
s = v[i].first;
e = v[i].second;
}
else if(e < v[i].second)
e = v[i].second;
}
res += (e - s) * 2 + M;
printf("%lld", res);
return 0;
}
|
[
"viodle238@naver.com"
] |
viodle238@naver.com
|
f4cf52354c0c1642a2fd69558c2f30e9e3b45f09
|
9674fd13f6559ac24e92489c257e57ca11b4c49c
|
/src/function pointer/functionPointer3.cpp
|
abab2624969cb0179886ced12d7fa4c61f94a0a7
|
[] |
no_license
|
superrabbit11223344/c--Tutorial
|
f8a68f7d2eb2f30aeaf07b627b87977be5c78661
|
10d09bbe49b123be44eea637961459358db8f139
|
refs/heads/master
| 2023-03-24T20:02:58.896679
| 2021-03-17T03:10:11
| 2021-03-17T03:10:11
| 348,564,275
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 359
|
cpp
|
#include <iostream>
#include <vector>
void PrintValue(int value)
{
std::cout << "Value:" << value << std::endl;
}
void ForEach(std::vector<int>& values, void(*func)(int))
{
for (int value : values)
{
func(value);
}
}
int main()
{
std::vector<int> values = {1, 2, 6, 1, 5};
ForEach(values, PrintValue);
std::cin.get();
}
|
[
"gongwei808@hotmail.com"
] |
gongwei808@hotmail.com
|
efa12f0f5a735cd5b2e69203a8b30d91397254f7
|
5c7f4f28c817d03b93ca25b5bd1c4ecddb38134a
|
/src/core/arithmetical.cpp
|
194e10bc759908b0ccf92c33ec093e4558d870ab
|
[] |
no_license
|
xiserre/eXodusino
|
cd2d5cd71bef9eda98e999f380ffbb1367bea1a4
|
102eee441c49dc821beb53aece15c76e47c4fd95
|
refs/heads/master
| 2021-01-18T08:49:27.679154
| 2012-11-21T13:13:19
| 2012-11-21T13:13:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,079
|
cpp
|
#include <libmary.h>
#include <arithmetical.h>
unsigned int random_seed;
void randomSeed(unsigned int seed)
{
random_seed = seed;
return;
}
// random algorithm using linear congruential method
unsigned int random(void)
{
int hi,lo,x;
x = random_seed;
if(x == 0)x = 123459876L;
hi = x / 127773L;
lo = x % 127773L;
x = 16807L * lo - 2836L * hi;
if(x < 0)x += 0x7FFFFFFFL;
random_seed = x;
return (x % ((unsigned long int)0x7FFFFFFFL + 1));
}
// random algorithm using Fibonacci-LFSR
unsigned int random_LFSR(void)
{
unsigned int shift_bit;
shift_bit = (random_seed & 0x0001) ^
((random_seed & 0x0004) >> 2) ^
((random_seed & 0x0008) >> 3) ^
((random_seed & 0x0020) >> 5);
random_seed = (random_seed >> 1) | (shift_bit << 15);
return random_seed;
}
long random(long max_num)
{
if(max_num ==0) return 0;
return random() % max_num;
}
long random(long min_num, long max_num)
{
if(min_num >= max_num)return 0;
if(max_num == 0) return 0;
return random( max_num - min_num ) + min_num;
}
|
[
"lynxeyed@xj9.so-net.ne.jp"
] |
lynxeyed@xj9.so-net.ne.jp
|
f96f48dbddd7e9091a35883564a9467921586a73
|
2d211fc1d33b5031efbfaeb039191192acee0769
|
/Main.cpp
|
e0138f98bc9ddca25a9f5ab7ce8ec0fb5c1cc804
|
[] |
no_license
|
LightWaveEmpire/Piecewise-Interpolation
|
20f403f935f797ed86a60d90d8e3881bd2aad2d4
|
e3aca51f76f837681544065ddfd308f0d2756554
|
refs/heads/main
| 2023-03-13T21:32:41.135027
| 2021-03-11T05:10:29
| 2021-03-11T05:10:29
| 346,585,021
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,088
|
cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include "Core.h"
using namespace std;
void corelist(string filename);
int main (int argc, char* argv[])
{
if (argc != 2)
{
cout << "Insufficent information"<< endl;
cout << "Usage: " <<argv[0] << " <filename>"<< endl;
return 1;
}
string filename = argv[1];
corelist(filename);
return 0;
}
void corelist(string filename)
{
ifstream ins;
double v_c1, v_c2, v_c3, v_c4;
Core c1, c2, c3, c4, temp;
int i=0;
ins.open(filename);
if(!(ins.is_open()))
{
cout<< "File unable to open"<<endl;
}
while (!ins.eof())
{
ins>> v_c1>>v_c2>>v_c3>>v_c4;
c1.addVal(v_c1);
c1.addTime(i*30);
c2.addVal(v_c2);
c2.addTime(i*30);
c3.addVal(v_c3);
c3.addTime(i*30);
c4.addVal(v_c4);
c4.addTime(i*30);
i++;
}
ins.close();
c1.interpolate(filename, "0");
c1.LinearInterp(filename, "0");
c2.interpolate(filename, "1");
c2.LinearInterp(filename, "1");
c3.interpolate(filename, "2");
c3.LinearInterp(filename, "2");
c4.interpolate(filename, "3");
c4.LinearInterp(filename, "3");
}
|
[
"noreply@github.com"
] |
LightWaveEmpire.noreply@github.com
|
c35b0e7176b1c7940384b0050ff86c0cc20ba956
|
e17c7cf738ee8c59789e9bef6aca875715545912
|
/tests/testplugin.cpp
|
56300077bca572f4ac53802992aa3f4871330f4b
|
[] |
no_license
|
KDE/libkcw
|
e279b1336b2228716853e3bc9465a1424adacd75
|
810b71cc946d7fa0625d481d4245cfb6d3f2a04c
|
refs/heads/master
| 2016-09-08T01:32:43.445800
| 2014-01-17T21:07:48
| 2014-01-17T21:08:45
| 42,731,774
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,485
|
cpp
|
/* Copyright 2013-2014 Patrick Spendrin <ps_ml@gmx.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "kcwpluginloader.h"
#include "testplugin.h"
TestPlugin::TestPlugin() : m_int(5) {
}
int TestPlugin::getInt() const {
return m_int;
}
KCW_ADD_PLUGIN(TestPlugin)
|
[
"ps_ml@gmx.de"
] |
ps_ml@gmx.de
|
050db5b5909865db2655f9a978dd36b7b58daf5b
|
8ca9dbc82b523c9dfadd2273c32c606a0bfee57f
|
/JsonGenerator/JsonGenerator/read.cpp
|
178532b259c9aa96bcafef8fcce30ad5ee711ebf
|
[] |
no_license
|
RainingQ/student_department_match
|
19203960f1093cbb7bfcfaa61d0bca8dad8afecd
|
9d11481ef0e372e24bab761b4e30df0ec4fcd527
|
refs/heads/master
| 2021-04-26T05:29:19.720265
| 2017-10-16T09:42:13
| 2017-10-16T09:42:13
| 107,097,242
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,248
|
cpp
|
#include<iostream>
#include<ostream>
#include<fstream>
#include"json.hpp"
#include"read.h"
#include"student.h"
#include"department.h"
using namespace std;
using json = nlohmann::json;
extern Student student[5000];//存储从json读入的student信息
extern Department department[100];//存储从json读入的department信息
int i = 0;
/*从json读取student信息*/
void student_from_json(const json& j)
{
student[i].student_no = j.at("student_no").get<int>();
student[i].student_name = j.at("student_name").get<string>();
student[i].student_score = j.at("student_score").get<float>();
student[i].student_cur = j.at("student_cur").get<int>();
for (int k = 0; k < j.at("student_tag").size(); k++)
student[i].student_tag[k] = j.at("student_tag")[k].get<string>();
for (int k = 0; k < j.at("student_schedule").size(); k++)
student[i].student_schedule[k] = j.at("student_schedule")[k].get<string>();
for (int k = 0; k < j.at("student_wish").size(); k++)
student[i].student_wish[k] = j.at("student_wish")[k].get<int>();
}
/*存储从json读取department信息*/
void department_from_json(const json& j)
{
department[i].department_no = j.at("department_no").get<int>();
department[i].department_name = j.at("department_name").get<string>();
department[i].department_score_limit = j.at("department_score_limit").get<float>();
department[i].department_member_limit = j.at("department_member_limit").get<int>();
department[i].chosen_num = j.at("chosen_num").get<int>();
for (int k = 0; k < j.at("department_tag").size(); k++)
department[i].department_tag[k] = j.at("department_tag")[k].get<string>();
for (int k = 0; k < j.at("department_schedule").size(); k++)
department[i].department_schedule[k] = j.at("department_schedule")[k].get<string>();
}
/*读取.json文件*/
void read(string file_name)
{
json jset;
fstream json_input(file_name);
json_input >> jset;
if (jset.find("department") != jset.end())
{
int size = jset.at("department").size();
for (i = 0; i < size; i++)
department_from_json(jset.at("department")[i].get<json>());
}
if (jset.find("student") != jset.end())
{
int size = jset.at("student").size();
for (i = 0; i < size; i++)
student_from_json(jset.at("student")[i].get<json>());
}
}
|
[
"275922122@qq.com"
] |
275922122@qq.com
|
f381b808dda4297ca32c7e968f46980cb0585137
|
a31e3f4a7980fdcd029cddbd075e0b910dafd009
|
/swamm_new/nazc/src/utility/getFile.cpp
|
7ed34ff06f3278ddda8c03f31b73632286f9b312
|
[] |
no_license
|
dongdong-2009/new_swamm
|
a49221cdb7fe21f1c70a394f09cb489b9c49b2fb
|
0ecef056138af4b92d3bc8e52235699803782823
|
refs/heads/master
| 2021-05-30T01:50:56.587102
| 2015-11-10T00:15:02
| 2015-11-10T00:15:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,639
|
cpp
|
/** Nuritelecom AiMiR Project.
*
* Put File
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/stat.h>
#include <dirent.h>
#include "aimir.h"
#include "typedef.h"
#include "version.h"
#include "config.h"
#include "if4api.h"
#include "varapi.h"
#include "mcudef.h"
#include "Utils.h"
#include "Variable.h"
#include "CommandHandler.h"
extern VAROBJECT m_Root_node[];
unsigned int getfile(char * ipaddr, int port, char * remote, char * local)
{
CIF4Invoke invoke(ipaddr, port, 600);
int nError;
int i,ncnt;
unsigned int size=0, mode;
FILE * fp;
invoke.AddParamFormat("1.11", VARSMI_STRING, remote, strlen(remote));
nError = Call(invoke.GetHandle(), "198.1");
if(nError) {
fprintf(stderr, " error=[%d %s]\n", nError, IF4API_GetErrorMessage(nError));
return -nError;
}
ncnt = invoke.GetHandle()->nResultCount;
size = invoke.GetHandle()->pResult[0]->stream.u32;
mode = invoke.GetHandle()->pResult[1]->stream.u32;
if((fp=fopen(local,"w")) == NULL) return 0;
for(i=3;i<ncnt;i++) {
fwrite(invoke.GetHandle()->pResult[i]->stream.p, invoke.GetHandle()->pResult[i]->len, 1, fp);
}
fclose(fp);
return size;
}
void usage(char * name)
{
fprintf(stderr,"%s [-p] ipaddr remote local\n", name);
fprintf(stderr," -p port : connection port(default 8000)\n");
exit(1);
}
int main(int argc, char * argv[])
{
char *ipaddr = NULL;
char *remote = NULL;
char *local = NULL;
int nPort = 8000;
int opt;
while((opt=getopt(argc, argv, "p:")) != -1) {
switch(opt) {
case 'p': nPort = (int)strtol(optarg, (char **)NULL, 10);
break;
default :
usage(argv[0]);
}
}
if(argc - optind < 3) {
usage(argv[0]);
}
ipaddr = strdup(argv[optind]);
remote = strdup(argv[optind+1]);
local = strdup(argv[optind+2]);
VARAPI_Initialize(NULL, m_Root_node, FALSE);
IF4API_Initialize(IF4_DEFAULT_PORT, NULL);
fprintf(stdout,"get file : target=%s, port=%d, remote=%s, local=%s ",
ipaddr, nPort, remote, local);
fflush(stdout);
fprintf(stdout,"length=%d\n", getfile(ipaddr, nPort, remote, local));
IF4API_Destroy();
VARAPI_Destroy();
return 0;
}
|
[
"locap001@nuritelecom.com"
] |
locap001@nuritelecom.com
|
2ba914fcfe2bf6bfea1563054bc2795878ec7d09
|
815d65edea087796ea5c5a05c33e79abfb0ab980
|
/pigLatin.cpp
|
280cb3c41f9408fde2eb20605431f8cd9f6c9d01
|
[] |
no_license
|
nanquim/PigLatin
|
83418be35be98ab5cef2983670084cef2b734ec1
|
cebef3993c9b1b8ad4ddaac7d38d24c21efc273f
|
refs/heads/master
| 2021-04-30T17:51:03.299789
| 2017-02-10T00:17:46
| 2017-02-10T00:17:46
| 80,265,077
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,966
|
cpp
|
#include <iostream>
#include <string>
#include <algorithm>
/*RULES:
1. If a word starts with a consonant and a vowel, put the first letter of the word at the end of the word and add "ay."
2. If a word starts with two consonants move the two consonants to the end of the word and add "ay."
3. If a word starts with a vowel add the word "way" at the end of the word. */
bool isConsonant(std::string str, char pos);
bool isVowel(std::string str, char pos);
void formatOutput(std::string& str);
int main(){
std::string str;
std::cout << "\nEnter any WORD: " << std::endl;
getline(std::cin, str);
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
if(str.empty()){
std::cerr << "ERROR - Empty String" << std::endl;
}else if(isConsonant(str, str.at(0)) == true){
if(isConsonant(str, str.at(1)) == true){
str += str.at(0);
str += "ay";
str.erase(0, 1);
formatOutput(str);
std::cout << "\nString Translation to Pig Latin: " << str << std::endl;
}else if(isVowel(str, str.at(1)) == true){
str += str.at(0);
str += str.at(1);
str += "ay";
str.erase(0, 1);
formatOutput(str);
std::cout << "\nString Translation to Pig Latin: " << str << std::endl;
}
}else if(isVowel(str, str.at(0)) == true){
str += "way";
formatOutput(str);
std::cout << "\nString Translation to Pig Latin: " << str << std::endl;
}
}
bool isConsonant(std::string str, char pos){
std::string consonants = "BCDFGHJKLMNPQRSTVWXYZ";
for(int i=0; i<consonants.length(); ++i){
if(str.at(0) == consonants[i]){
return true;
}
}
return false;
}
bool isVowel(std::string str, char pos){
std::string vowels = "AEIOU";
for(int i=0; i<vowels.length(); ++i){
if(str.at(0) == vowels[i]){
return true;
}
}
return false;
}
void formatOutput(std::string& str){
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
str[0] = toupper(str[0]);
}
|
[
"noreply@github.com"
] |
nanquim.noreply@github.com
|
cc39ce606992365a7a0cb72294ec7eac6c7abc35
|
b7c6c9237a0a65ade0bae30503f54fcf03dbac6d
|
/2-4/Maze Movement (Incomplete).cpp
|
9a1ee8e5896059283bba51831fc5267e2c71ade4
|
[] |
no_license
|
Yizue/Programming-Exercises-2017
|
4f8a97cb44feb12586fd21f4ef86d76c6c494362
|
8711cf0236c8bc5c52d23e9bf14796f90d54145c
|
refs/heads/master
| 2021-01-09T06:22:04.187236
| 2017-02-05T06:37:58
| 2017-02-05T06:37:58
| 80,972,873
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,651
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int INF = std::numeric_limits<int>::max()/3;
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
#define forn(i,n) for(int (i) = 0; (i) < (n); (i)++)
#define fornm(i,n,m) for(int (i) = (n); (i) < (m); (i)++)
#define formn(i,m,n) for(int (i) = (m); (i) > (n); (i)--)
#define DEBUG if(debugging)
#define FASTER ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<int,ii> iii;
typedef pair<int,char> ic;
typedef pair<long,char> lc;
typedef pair<double,double> dd;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<dd> vdd;
int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);}
int lcm(int a,int b){return a*(b/gcd(a,b));}
int cmp(const void *a, const void *b) {return *(int*)a - *(int*)b;}
const int debugging = 1;
/*
__builtin_popcount(int d) // count bits
__builtin_popcountll(long long d)
strtol(s, &end, base); // convert base number
*/
//----------------------------------------------------------------------//
class Edge{
public:
int u,v,cap,f;
Edge(int _u, int _v, int _cap) : u(_u),v(_v),cap(_cap){
f = 0;
}
int other(int vertex){
if(vertex == u)return v;
else if(vertex == v)return u;
return -1;
}
int residualTo(int vertex){
if(vertex == u)return f;
return cap - f;
}
void addFlowTo(int vertex, int ff){
if(vertex == u){
f -= ff;
}else if(vertex == v){
f += ff;
}
}
};
typedef vector<Edge*> edgeList;
map<int, int> M;
#define MAX_V 1000
#define MAX_E 1000
int SRC;
int SINK;
int Flow;
edgeList parent;
vi visited;
vector<edgeList> adj;
void addEdge(int u, int v, int cap){
Edge* e = new Edge(u,v,cap);
adj[u].push_back(e);
adj[v].push_back(e);
}
bool augmentingPath(){
queue<int> q;
parent.assign(MAX_V, NULL);
visited.assign(MAX_V, 0);
q.push(SRC);
visited[SRC] = 1;
while(!q.empty()){
int u = q.front();
q.pop();
if(u == SINK)
break;
for (int i = 0; i < (int)adj[u].size(); ++i) {
Edge* e = adj[u][i];
int v = e->other(u);
if(!visited[v] && e->residualTo(v) > 0){
visited[v] = 1;
parent[v] = e;
q.push(v);
}
}
}
return visited[SINK];
}
// Ford Fulkerson
int maxFlow(){
int mf = 0;
while(augmentingPath()){
Flow = 1e9;
for(int v = SINK; v != SRC ; v = parent[v]->other(v)){
Flow = min(Flow, parent[v]->residualTo(v));
}
for(int v = SINK; v != SRC ; v = parent[v]->other(v)){
parent[v]->addFlowTo(v,Flow);
}
mf += Flow;
}
return mf;
}
int main() {
FASTER;
int V, SRC = INF, SINK = -1, n;
cin >> V;
adj.assign(V, edgeList());
forn(i, V)
{
cin >> n; M[i] = n;
//cout << i << ": " << M[i] << endl;
if (n < SRC) SRC = i;
if (n > SINK) SINK = i;
}
//cout << "S: " << s << " T: " << t << endl;
forn(j, V)
{
forn(k, V)
{
int cd = gcd(M[j], M[k]);
if(cd > 1 && j != k)
{
//cout << "gcd of " << M[j] << ", " << M[k] << ": " << cd << endl;
addEdge(j,k,cd);
}
}
}
/*forn(z, V)
{
cout << z << ": ";
forn(x, G[z].size())
cout << G[z][x].first << ", " << G[z][x].second << endl;
}*/
cout << maxFlow();
return 0;
}
|
[
"noreply@github.com"
] |
Yizue.noreply@github.com
|
2039aea27b6291e45ea983d80e7288ee17df4b8b
|
6c77cf237697f252d48b287ae60ccf61b3220044
|
/aws-cpp-sdk-workspaces/include/aws/workspaces/model/DisassociateIpGroupsRequest.h
|
68e9aa7b875606a84a9abb42455e9504b89bb519
|
[
"MIT",
"Apache-2.0",
"JSON"
] |
permissive
|
Gohan/aws-sdk-cpp
|
9a9672de05a96b89d82180a217ccb280537b9e8e
|
51aa785289d9a76ac27f026d169ddf71ec2d0686
|
refs/heads/master
| 2020-03-26T18:48:43.043121
| 2018-11-09T08:44:41
| 2018-11-09T08:44:41
| 145,232,234
| 1
| 0
|
Apache-2.0
| 2018-08-30T13:42:27
| 2018-08-18T15:42:39
|
C++
|
UTF-8
|
C++
| false
| false
| 4,701
|
h
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/workspaces/WorkSpaces_EXPORTS.h>
#include <aws/workspaces/WorkSpacesRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
namespace WorkSpaces
{
namespace Model
{
/**
*/
class AWS_WORKSPACES_API DisassociateIpGroupsRequest : public WorkSpacesRequest
{
public:
DisassociateIpGroupsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DisassociateIpGroups"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The ID of the directory.</p>
*/
inline const Aws::String& GetDirectoryId() const{ return m_directoryId; }
/**
* <p>The ID of the directory.</p>
*/
inline void SetDirectoryId(const Aws::String& value) { m_directoryIdHasBeenSet = true; m_directoryId = value; }
/**
* <p>The ID of the directory.</p>
*/
inline void SetDirectoryId(Aws::String&& value) { m_directoryIdHasBeenSet = true; m_directoryId = std::move(value); }
/**
* <p>The ID of the directory.</p>
*/
inline void SetDirectoryId(const char* value) { m_directoryIdHasBeenSet = true; m_directoryId.assign(value); }
/**
* <p>The ID of the directory.</p>
*/
inline DisassociateIpGroupsRequest& WithDirectoryId(const Aws::String& value) { SetDirectoryId(value); return *this;}
/**
* <p>The ID of the directory.</p>
*/
inline DisassociateIpGroupsRequest& WithDirectoryId(Aws::String&& value) { SetDirectoryId(std::move(value)); return *this;}
/**
* <p>The ID of the directory.</p>
*/
inline DisassociateIpGroupsRequest& WithDirectoryId(const char* value) { SetDirectoryId(value); return *this;}
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline const Aws::Vector<Aws::String>& GetGroupIds() const{ return m_groupIds; }
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline void SetGroupIds(const Aws::Vector<Aws::String>& value) { m_groupIdsHasBeenSet = true; m_groupIds = value; }
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline void SetGroupIds(Aws::Vector<Aws::String>&& value) { m_groupIdsHasBeenSet = true; m_groupIds = std::move(value); }
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline DisassociateIpGroupsRequest& WithGroupIds(const Aws::Vector<Aws::String>& value) { SetGroupIds(value); return *this;}
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline DisassociateIpGroupsRequest& WithGroupIds(Aws::Vector<Aws::String>&& value) { SetGroupIds(std::move(value)); return *this;}
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline DisassociateIpGroupsRequest& AddGroupIds(const Aws::String& value) { m_groupIdsHasBeenSet = true; m_groupIds.push_back(value); return *this; }
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline DisassociateIpGroupsRequest& AddGroupIds(Aws::String&& value) { m_groupIdsHasBeenSet = true; m_groupIds.push_back(std::move(value)); return *this; }
/**
* <p>The IDs of one or more IP access control groups.</p>
*/
inline DisassociateIpGroupsRequest& AddGroupIds(const char* value) { m_groupIdsHasBeenSet = true; m_groupIds.push_back(value); return *this; }
private:
Aws::String m_directoryId;
bool m_directoryIdHasBeenSet;
Aws::Vector<Aws::String> m_groupIds;
bool m_groupIdsHasBeenSet;
};
} // namespace Model
} // namespace WorkSpaces
} // namespace Aws
|
[
"henso@amazon.com"
] |
henso@amazon.com
|
15d9afd299e31fec11d95cd4457dada5f37543c0
|
4235966c1b5cb0ec1c8ff7da99bb7bfe178af84a
|
/lw3/Shapes/CircleParser.cpp
|
9b5a9207671f32bd9250339f0aa38fff7233cb2c
|
[] |
no_license
|
term96/OOD
|
8d6f1a3792ffb8d337cb2780e5ef1167cf48490a
|
1056e62544a795661af4156c939becbbfbcdf6d2
|
refs/heads/master
| 2021-04-29T17:48:17.362000
| 2018-03-23T07:46:12
| 2018-03-23T07:46:12
| 121,677,738
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 612
|
cpp
|
#include "stdafx.h"
#include "CircleParser.h"
CCircleParser & CCircleParser::getInstance()
{
static CCircleParser instance;
return instance;
}
IShape * CCircleParser::parseShape(std::string const & inputLine) const
{
std::smatch match;
std::regex regex("[0-9]+");
std::string matchSuffix = inputLine;
int params[3];
int currentParam = 0;
while (std::regex_search(matchSuffix, match, regex))
{
params[currentParam] = std::stoi(match.str(0));
currentParam++;
matchSuffix = match.suffix().str();
}
return new CCircle(CShapePoint(params[0], params[1]), params[2]);
}
|
[
"term96@yandex.com"
] |
term96@yandex.com
|
c96afe0cb0f9396e852823b8517b5fedbeec5548
|
06e712f56339aa950853be843222b7abfe7212d3
|
/preparation/SelectServer/SelectServer.h
|
2fb556c84feb1684600672e8395a4875d378a48c
|
[] |
no_license
|
SalvationN/WebServer
|
feb84412e4d56fbce8d77d0f986e75da5dcb4d3d
|
4946534299a6d4545de5f6a55d52b6c29879f44d
|
refs/heads/master
| 2023-07-10T00:13:56.563994
| 2021-08-08T10:37:33
| 2021-08-08T10:37:33
| 378,905,043
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,541
|
h
|
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <stdio.h>
#include "TcpServer.h"
#include <vector>
using std::vector;
class SelectServer {
public:
SelectServer() {
_maxfd = -1;
FD_ZERO(&_readfds);
}
void addfd(int fd) {
FD_SET(fd,&_readfds);
if(fd > _maxfd){
_maxfd = fd;
}
}
void deletefd(int fd) {
FD_CLR(fd,&_readfds);
printf("delete fd: %d\n", fd);
for(int i=_maxfd; i>=0; i--) {
if(FD_ISSET(fd,&_readfds)) {
_maxfd = i;
break;
}
}
}
bool Select(std::vector<TcpServer>& vec) {
struct timeval tv;
tv.tv_sec = 20;
tv.tv_usec = 0;
fd_set tmp = _readfds;
printf("start select.\n");
int ret = select(_maxfd+1, &tmp, NULL, NULL, &tv);
if(ret < 0) {
perror("select error: ");
return false;
}
else if(ret == 0) {
printf("timeout!\n");
return false;
}
for(int i=0; i<= _maxfd; i++) {
if(FD_ISSET(i, &tmp)) {
TcpServer ts;
ts.setfd(i);
vec.push_back(ts);
}
}
return true;
}
private:
int _maxfd;
fd_set _readfds;
};
|
[
"salvation@localhost.localdomain"
] |
salvation@localhost.localdomain
|
47020bcb054611d22896dd406b45bbcd0fc4edc6
|
6e5aca8a2d93092dbb8ad130d4bc904b49b938f9
|
/algorithm/daiziguizhong/trailing-zeros.cc
|
b42c5d46f34afae4c2d98e2be98fe6a02da6869b
|
[] |
no_license
|
ljshou/workspace
|
6a1b79f0b222cefee8d751fe5c32c726466fa38e
|
7cc1067f22cca9e56511f89be7e24420fe894090
|
refs/heads/master
| 2016-09-05T13:30:42.402922
| 2016-02-28T15:35:40
| 2016-02-28T15:35:40
| 26,074,693
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 465
|
cc
|
/**
* @file trailing-zeros.cc
* @brief determine trailing zeros of n!
* @author L.J.SHOU, shoulinjun@126.com
* @version 0.1.00
* @date 2014-12-30
*/
#include <iostream>
#include <cassert>
using namespace std;
int TrailingZeros(int n)
{
assert(n >= 0);
int count(0);
while(n) {
n /= 5;
count += n;
}
return count;
}
int main(void)
{
assert(2 == TrailingZeros(10));
assert(4 == TrailingZeros(22));
return 0;
}
|
[
"shoulinjun@126.com"
] |
shoulinjun@126.com
|
1fe6d800394137297c1a368e94eebb9eab421013
|
94e924b108177223d5b431ba1a0312e7aa1e6ee3
|
/src/Dialog/ColorDialog.h
|
b4f72c8c434b36100914722a3bf70258ef13dd74
|
[
"MIT"
] |
permissive
|
TheReincarnator/glaziery
|
baae34f244c02974cd1247537baad627c409b0c0
|
f688943163b73cea7034e929539fff8aa39d63e5
|
refs/heads/master
| 2020-06-05T18:43:32.175577
| 2019-06-18T10:05:02
| 2019-06-18T10:05:02
| 192,514,605
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 618
|
h
|
/*
* This file is part of the Glaziery.
* Copyright Thomas Jacob.
*
* READ README.TXT BEFORE USE!!
*/
#ifndef __GLAZIERY_COLORDIALOG_H
#define __GLAZIERY_COLORDIALOG_H
namespace glaziery
{
/**
* TODO
*/
class ColorDialog : public Dialog
{
protected:
/**
* Creates a new message window.
*/
ColorDialog();
/**
* Destroys the message dialog.
*/
virtual ~ColorDialog();
// Runtime class macros require their own public section.
public:
#if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL))
DECLARE_DYNAMIC(ColorDialog);
#endif
public:
};
}
#endif
|
[
"git@thomasjacob.de"
] |
git@thomasjacob.de
|
b5dd9a19b4050e74e9f79fcc1f2f3ed2fcf3af72
|
0d1bb8aa3f469d4dffbfc3441b2951e260b2d156
|
/src/apps/DEL_DOT_VEC_2D.hpp
|
8f7110af9c00bcfb62188dd58e9e10c65aebd55a
|
[] |
no_license
|
wcohen/RAJAPerf
|
62013dace3806eaa40f6f72d35b6b6e9ac68418b
|
a7b6f63e4fef2d0146932eff409788da51ab0cb3
|
refs/heads/master
| 2020-06-03T01:41:13.555308
| 2019-04-12T21:21:40
| 2019-04-12T21:21:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,525
|
hpp
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-19, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-738930
//
// All rights reserved.
//
// This file is part of the RAJA Performance Suite.
//
// For details about use and distribution, please read RAJAPerf/LICENSE.
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
///
/// DEL_DOT_VEC_2D kernel reference implementation:
///
/// for (Index_type ii = ibegin; ii < iend; ++ii ) {
/// Index_type i = real_zones[ii];
///
/// Real_type xi = half * ( x1[i] + x2[i] - x3[i] - x4[i] ) ;
/// Real_type xj = half * ( x2[i] + x3[i] - x4[i] - x1[i] ) ;
///
/// Real_type yi = half * ( y1[i] + y2[i] - y3[i] - y4[i] ) ;
/// Real_type yj = half * ( y2[i] + y3[i] - y4[i] - y1[i] ) ;
///
/// Real_type fxi = half * ( fx1[i] + fx2[i] - fx3[i] - fx4[i] ) ;
/// Real_type fxj = half * ( fx2[i] + fx3[i] - fx4[i] - fx1[i] ) ;
///
/// Real_type fyi = half * ( fy1[i] + fy2[i] - fy3[i] - fy4[i] ) ;
/// Real_type fyj = half * ( fy2[i] + fy3[i] - fy4[i] - fy1[i] ) ;
///
/// Real_type rarea = 1.0 / ( xi * yj - xj * yi + ptiny ) ;
///
/// Real_type dfxdx = rarea * ( fxi * yj - fxj * yi ) ;
///
/// Real_type dfydy = rarea * ( fyj * xi - fyi * xj ) ;
///
/// Real_type affine = ( fy1[i] + fy2[i] + fy3[i] + fy4[i] ) /
/// ( y1[i] + y2[i] + y3[i] + y4[i] ) ;
///
/// div[i] = dfxdx + dfydy + affine ;
/// }
///
#ifndef RAJAPerf_Apps_DEL_DOT_VEC_2D_HPP
#define RAJAPerf_Apps_DEL_DOT_VEC_2D_HPP
#define DEL_DOT_VEC_2D_DATA_INDEX \
Index_ptr real_zones = m_domain->real_zones;
#define DEL_DOT_VEC_2D_BODY_INDEX \
Index_type i = real_zones[ii];
#define DEL_DOT_VEC_2D_BODY \
\
Real_type xi = half * ( x1[i] + x2[i] - x3[i] - x4[i] ) ; \
Real_type xj = half * ( x2[i] + x3[i] - x4[i] - x1[i] ) ; \
\
Real_type yi = half * ( y1[i] + y2[i] - y3[i] - y4[i] ) ; \
Real_type yj = half * ( y2[i] + y3[i] - y4[i] - y1[i] ) ; \
\
Real_type fxi = half * ( fx1[i] + fx2[i] - fx3[i] - fx4[i] ) ; \
Real_type fxj = half * ( fx2[i] + fx3[i] - fx4[i] - fx1[i] ) ; \
\
Real_type fyi = half * ( fy1[i] + fy2[i] - fy3[i] - fy4[i] ) ; \
Real_type fyj = half * ( fy2[i] + fy3[i] - fy4[i] - fy1[i] ) ; \
\
Real_type rarea = 1.0 / ( xi * yj - xj * yi + ptiny ) ; \
\
Real_type dfxdx = rarea * ( fxi * yj - fxj * yi ) ; \
\
Real_type dfydy = rarea * ( fyj * xi - fyi * xj ) ; \
\
Real_type affine = ( fy1[i] + fy2[i] + fy3[i] + fy4[i] ) / \
( y1[i] + y2[i] + y3[i] + y4[i] ) ; \
\
div[i] = dfxdx + dfydy + affine ;
#include "common/KernelBase.hpp"
namespace rajaperf
{
class RunParams;
namespace apps
{
class ADomain;
class DEL_DOT_VEC_2D : public KernelBase
{
public:
DEL_DOT_VEC_2D(const RunParams& params);
~DEL_DOT_VEC_2D();
Index_type getItsPerRep() const;
void setUp(VariantID vid);
void runKernel(VariantID vid);
void updateChecksum(VariantID vid);
void tearDown(VariantID vid);
void runCudaVariant(VariantID vid);
void runOpenMPTargetVariant(VariantID vid);
private:
Real_ptr m_x;
Real_ptr m_y;
Real_ptr m_xdot;
Real_ptr m_ydot;
Real_ptr m_div;
Real_type m_ptiny;
Real_type m_half;
ADomain* m_domain;
Index_type m_array_length;
};
} // end namespace apps
} // end namespace rajaperf
#endif // closing endif for header file include guard
|
[
"hornung1@llnl.gov"
] |
hornung1@llnl.gov
|
6751b81f333a2663013bfb55168cd9796abc5ce6
|
af69e335fc0ff9632964d061833713b672abad01
|
/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Runtime_CompilerServices_RuntimeHe1447613860.h
|
c7467b2b0906a3cf3122656c1ff5c5135c5c3a66
|
[] |
no_license
|
PruthvishMShirur/Solar-System
|
ca143ab38cef582705f0beb76f7fef8b28e25ef9
|
5cf3eaa66949801aa9a34cd3cf80eeefa64d2342
|
refs/heads/master
| 2023-05-26T17:53:37.489349
| 2021-06-16T19:56:48
| 2021-06-16T19:56:48
| 377,611,177
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 536
|
h
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object3080106164.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.CompilerServices.RuntimeHelpers
struct RuntimeHelpers_t1447613860 : public Il2CppObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
[
"42893637+PruthvishMShirur@users.noreply.github.com"
] |
42893637+PruthvishMShirur@users.noreply.github.com
|
5e18b1c747f27e05d2c10614ebf938c0ad11e406
|
e1a6af52111a1dfa0ae053183e2b3d0180d1e9ec
|
/src/test/script_standard_tests.cpp
|
3f0ccbab2b0707e364df8d3d449dc75885959c0c
|
[
"MIT"
] |
permissive
|
UFO-ETL/ufo
|
df392b66b3f528a3442c2a26304e061fb6e1a631
|
e85dde0c8b12c1bf3357003afb77ea85b1476d6b
|
refs/heads/main
| 2023-03-12T04:27:35.910420
| 2021-03-05T06:54:21
| 2021-03-05T06:54:21
| 344,399,934
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,205
|
cpp
|
// Copyright (c) 2017-2020 The UFO Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <script/script.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(script_standard_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(dest_default_is_no_dest)
{
CTxDestination dest;
BOOST_CHECK(!IsValidDestination(dest));
}
BOOST_AUTO_TEST_CASE(script_standard_Solver_success)
{
CKey keys[3];
CPubKey pubkeys[3];
for (int i = 0; i < 3; i++) {
keys[i].MakeNewKey(true);
pubkeys[i] = keys[i].GetPubKey();
}
CScript s;
std::vector<std::vector<unsigned char> > solutions;
// TxoutType::PUBKEY
s.clear();
s << ToByteVector(pubkeys[0]) << OP_CHECKSIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::PUBKEY);
BOOST_CHECK_EQUAL(solutions.size(), 1U);
BOOST_CHECK(solutions[0] == ToByteVector(pubkeys[0]));
// TxoutType::PUBKEYHASH
s.clear();
s << OP_DUP << OP_HASH160 << ToByteVector(pubkeys[0].GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::PUBKEYHASH);
BOOST_CHECK_EQUAL(solutions.size(), 1U);
BOOST_CHECK(solutions[0] == ToByteVector(pubkeys[0].GetID()));
// TxoutType::SCRIPTHASH
CScript redeemScript(s); // initialize with leftover P2PKH script
s.clear();
s << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::SCRIPTHASH);
BOOST_CHECK_EQUAL(solutions.size(), 1U);
BOOST_CHECK(solutions[0] == ToByteVector(CScriptID(redeemScript)));
// TxoutType::MULTISIG
s.clear();
s << OP_1 <<
ToByteVector(pubkeys[0]) <<
ToByteVector(pubkeys[1]) <<
OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::MULTISIG);
BOOST_CHECK_EQUAL(solutions.size(), 4U);
BOOST_CHECK(solutions[0] == std::vector<unsigned char>({1}));
BOOST_CHECK(solutions[1] == ToByteVector(pubkeys[0]));
BOOST_CHECK(solutions[2] == ToByteVector(pubkeys[1]));
BOOST_CHECK(solutions[3] == std::vector<unsigned char>({2}));
s.clear();
s << OP_2 <<
ToByteVector(pubkeys[0]) <<
ToByteVector(pubkeys[1]) <<
ToByteVector(pubkeys[2]) <<
OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::MULTISIG);
BOOST_CHECK_EQUAL(solutions.size(), 5U);
BOOST_CHECK(solutions[0] == std::vector<unsigned char>({2}));
BOOST_CHECK(solutions[1] == ToByteVector(pubkeys[0]));
BOOST_CHECK(solutions[2] == ToByteVector(pubkeys[1]));
BOOST_CHECK(solutions[3] == ToByteVector(pubkeys[2]));
BOOST_CHECK(solutions[4] == std::vector<unsigned char>({3}));
// TxoutType::NULL_DATA
s.clear();
s << OP_RETURN <<
std::vector<unsigned char>({0}) <<
std::vector<unsigned char>({75}) <<
std::vector<unsigned char>({255});
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NULL_DATA);
BOOST_CHECK_EQUAL(solutions.size(), 0U);
// TxoutType::WITNESS_V0_KEYHASH
s.clear();
s << OP_0 << ToByteVector(pubkeys[0].GetID());
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::WITNESS_V0_KEYHASH);
BOOST_CHECK_EQUAL(solutions.size(), 1U);
BOOST_CHECK(solutions[0] == ToByteVector(pubkeys[0].GetID()));
// TxoutType::WITNESS_V0_SCRIPTHASH
uint256 scriptHash;
CSHA256().Write(&redeemScript[0], redeemScript.size())
.Finalize(scriptHash.begin());
s.clear();
s << OP_0 << ToByteVector(scriptHash);
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::WITNESS_V0_SCRIPTHASH);
BOOST_CHECK_EQUAL(solutions.size(), 1U);
BOOST_CHECK(solutions[0] == ToByteVector(scriptHash));
// TxoutType::WITNESS_V1_TAPROOT
s.clear();
s << OP_1 << ToByteVector(uint256::ZERO);
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::WITNESS_V1_TAPROOT);
BOOST_CHECK_EQUAL(solutions.size(), 2U);
BOOST_CHECK(solutions[0] == std::vector<unsigned char>{1});
BOOST_CHECK(solutions[1] == ToByteVector(uint256::ZERO));
// TxoutType::WITNESS_UNKNOWN
s.clear();
s << OP_16 << ToByteVector(uint256::ONE);
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::WITNESS_UNKNOWN);
BOOST_CHECK_EQUAL(solutions.size(), 2U);
BOOST_CHECK(solutions[0] == std::vector<unsigned char>{16});
BOOST_CHECK(solutions[1] == ToByteVector(uint256::ONE));
// TxoutType::NONSTANDARD
s.clear();
s << OP_9 << OP_ADD << OP_11 << OP_EQUAL;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
}
BOOST_AUTO_TEST_CASE(script_standard_Solver_failure)
{
CKey key;
CPubKey pubkey;
key.MakeNewKey(true);
pubkey = key.GetPubKey();
CScript s;
std::vector<std::vector<unsigned char> > solutions;
// TxoutType::PUBKEY with incorrectly sized pubkey
s.clear();
s << std::vector<unsigned char>(30, 0x01) << OP_CHECKSIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::PUBKEYHASH with incorrectly sized key hash
s.clear();
s << OP_DUP << OP_HASH160 << ToByteVector(pubkey) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::SCRIPTHASH with incorrectly sized script hash
s.clear();
s << OP_HASH160 << std::vector<unsigned char>(21, 0x01) << OP_EQUAL;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::MULTISIG 0/2
s.clear();
s << OP_0 << ToByteVector(pubkey) << OP_1 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::MULTISIG 2/1
s.clear();
s << OP_2 << ToByteVector(pubkey) << OP_1 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::MULTISIG n = 2 with 1 pubkey
s.clear();
s << OP_1 << ToByteVector(pubkey) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::MULTISIG n = 1 with 0 pubkeys
s.clear();
s << OP_1 << OP_1 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::NULL_DATA with other opcodes
s.clear();
s << OP_RETURN << std::vector<unsigned char>({75}) << OP_ADD;
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
// TxoutType::WITNESS_UNKNOWN with incorrect program size
s.clear();
s << OP_0 << std::vector<unsigned char>(19, 0x01);
BOOST_CHECK_EQUAL(Solver(s, solutions), TxoutType::NONSTANDARD);
}
BOOST_AUTO_TEST_CASE(script_standard_ExtractDestination)
{
CKey key;
CPubKey pubkey;
key.MakeNewKey(true);
pubkey = key.GetPubKey();
CScript s;
CTxDestination address;
// TxoutType::PUBKEY
s.clear();
s << ToByteVector(pubkey) << OP_CHECKSIG;
BOOST_CHECK(ExtractDestination(s, address));
BOOST_CHECK(std::get_if<PKHash>(&address) &&
*std::get_if<PKHash>(&address) == PKHash(pubkey));
// TxoutType::PUBKEYHASH
s.clear();
s << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(ExtractDestination(s, address));
BOOST_CHECK(std::get_if<PKHash>(&address) &&
*std::get_if<PKHash>(&address) == PKHash(pubkey));
// TxoutType::SCRIPTHASH
CScript redeemScript(s); // initialize with leftover P2PKH script
s.clear();
s << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
BOOST_CHECK(ExtractDestination(s, address));
BOOST_CHECK(std::get_if<ScriptHash>(&address) &&
*std::get_if<ScriptHash>(&address) == ScriptHash(redeemScript));
// TxoutType::MULTISIG
s.clear();
s << OP_1 << ToByteVector(pubkey) << OP_1 << OP_CHECKMULTISIG;
BOOST_CHECK(!ExtractDestination(s, address));
// TxoutType::NULL_DATA
s.clear();
s << OP_RETURN << std::vector<unsigned char>({75});
BOOST_CHECK(!ExtractDestination(s, address));
// TxoutType::WITNESS_V0_KEYHASH
s.clear();
s << OP_0 << ToByteVector(pubkey.GetID());
BOOST_CHECK(ExtractDestination(s, address));
WitnessV0KeyHash keyhash;
CHash160().Write(pubkey).Finalize(keyhash);
BOOST_CHECK(std::get_if<WitnessV0KeyHash>(&address) && *std::get_if<WitnessV0KeyHash>(&address) == keyhash);
// TxoutType::WITNESS_V0_SCRIPTHASH
s.clear();
WitnessV0ScriptHash scripthash;
CSHA256().Write(redeemScript.data(), redeemScript.size()).Finalize(scripthash.begin());
s << OP_0 << ToByteVector(scripthash);
BOOST_CHECK(ExtractDestination(s, address));
BOOST_CHECK(std::get_if<WitnessV0ScriptHash>(&address) && *std::get_if<WitnessV0ScriptHash>(&address) == scripthash);
// TxoutType::WITNESS_UNKNOWN with unknown version
s.clear();
s << OP_1 << ToByteVector(pubkey);
BOOST_CHECK(ExtractDestination(s, address));
WitnessUnknown unk;
unk.length = 33;
unk.version = 1;
std::copy(pubkey.begin(), pubkey.end(), unk.program);
BOOST_CHECK(std::get_if<WitnessUnknown>(&address) && *std::get_if<WitnessUnknown>(&address) == unk);
}
BOOST_AUTO_TEST_CASE(script_standard_ExtractDestinations)
{
CKey keys[3];
CPubKey pubkeys[3];
for (int i = 0; i < 3; i++) {
keys[i].MakeNewKey(true);
pubkeys[i] = keys[i].GetPubKey();
}
CScript s;
TxoutType whichType;
std::vector<CTxDestination> addresses;
int nRequired;
// TxoutType::PUBKEY
s.clear();
s << ToByteVector(pubkeys[0]) << OP_CHECKSIG;
BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
BOOST_CHECK_EQUAL(whichType, TxoutType::PUBKEY);
BOOST_CHECK_EQUAL(addresses.size(), 1U);
BOOST_CHECK_EQUAL(nRequired, 1);
BOOST_CHECK(std::get_if<PKHash>(&addresses[0]) &&
*std::get_if<PKHash>(&addresses[0]) == PKHash(pubkeys[0]));
// TxoutType::PUBKEYHASH
s.clear();
s << OP_DUP << OP_HASH160 << ToByteVector(pubkeys[0].GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
BOOST_CHECK_EQUAL(whichType, TxoutType::PUBKEYHASH);
BOOST_CHECK_EQUAL(addresses.size(), 1U);
BOOST_CHECK_EQUAL(nRequired, 1);
BOOST_CHECK(std::get_if<PKHash>(&addresses[0]) &&
*std::get_if<PKHash>(&addresses[0]) == PKHash(pubkeys[0]));
// TxoutType::SCRIPTHASH
CScript redeemScript(s); // initialize with leftover P2PKH script
s.clear();
s << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
BOOST_CHECK_EQUAL(whichType, TxoutType::SCRIPTHASH);
BOOST_CHECK_EQUAL(addresses.size(), 1U);
BOOST_CHECK_EQUAL(nRequired, 1);
BOOST_CHECK(std::get_if<ScriptHash>(&addresses[0]) &&
*std::get_if<ScriptHash>(&addresses[0]) == ScriptHash(redeemScript));
// TxoutType::MULTISIG
s.clear();
s << OP_2 <<
ToByteVector(pubkeys[0]) <<
ToByteVector(pubkeys[1]) <<
OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
BOOST_CHECK_EQUAL(whichType, TxoutType::MULTISIG);
BOOST_CHECK_EQUAL(addresses.size(), 2U);
BOOST_CHECK_EQUAL(nRequired, 2);
BOOST_CHECK(std::get_if<PKHash>(&addresses[0]) &&
*std::get_if<PKHash>(&addresses[0]) == PKHash(pubkeys[0]));
BOOST_CHECK(std::get_if<PKHash>(&addresses[1]) &&
*std::get_if<PKHash>(&addresses[1]) == PKHash(pubkeys[1]));
// TxoutType::NULL_DATA
s.clear();
s << OP_RETURN << std::vector<unsigned char>({75});
BOOST_CHECK(!ExtractDestinations(s, whichType, addresses, nRequired));
}
BOOST_AUTO_TEST_CASE(script_standard_GetScriptFor_)
{
CKey keys[3];
CPubKey pubkeys[3];
for (int i = 0; i < 3; i++) {
keys[i].MakeNewKey(true);
pubkeys[i] = keys[i].GetPubKey();
}
CScript expected, result;
// PKHash
expected.clear();
expected << OP_DUP << OP_HASH160 << ToByteVector(pubkeys[0].GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
result = GetScriptForDestination(PKHash(pubkeys[0]));
BOOST_CHECK(result == expected);
// CScriptID
CScript redeemScript(result);
expected.clear();
expected << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
result = GetScriptForDestination(ScriptHash(redeemScript));
BOOST_CHECK(result == expected);
// CNoDestination
expected.clear();
result = GetScriptForDestination(CNoDestination());
BOOST_CHECK(result == expected);
// GetScriptForRawPubKey
expected.clear();
expected << ToByteVector(pubkeys[0]) << OP_CHECKSIG;
result = GetScriptForRawPubKey(pubkeys[0]);
BOOST_CHECK(result == expected);
// GetScriptForMultisig
expected.clear();
expected << OP_2 <<
ToByteVector(pubkeys[0]) <<
ToByteVector(pubkeys[1]) <<
ToByteVector(pubkeys[2]) <<
OP_3 << OP_CHECKMULTISIG;
result = GetScriptForMultisig(2, std::vector<CPubKey>(pubkeys, pubkeys + 3));
BOOST_CHECK(result == expected);
// WitnessV0KeyHash
expected.clear();
expected << OP_0 << ToByteVector(pubkeys[0].GetID());
result = GetScriptForDestination(WitnessV0KeyHash(Hash160(ToByteVector(pubkeys[0]))));
BOOST_CHECK(result == expected);
result = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0].GetID()));
BOOST_CHECK(result == expected);
// WitnessV0ScriptHash (multisig)
CScript witnessScript;
witnessScript << OP_1 << ToByteVector(pubkeys[0]) << OP_1 << OP_CHECKMULTISIG;
uint256 scriptHash;
CSHA256().Write(&witnessScript[0], witnessScript.size())
.Finalize(scriptHash.begin());
expected.clear();
expected << OP_0 << ToByteVector(scriptHash);
result = GetScriptForDestination(WitnessV0ScriptHash(witnessScript));
BOOST_CHECK(result == expected);
}
BOOST_AUTO_TEST_SUITE_END()
|
[
"xiaka53@vip.qq.com"
] |
xiaka53@vip.qq.com
|
54adcb0a4e4ede6d0b32234f211cb6a5c0e96bf1
|
a2424f0c80a06446c8c9c32ac1e2d63bd7aa1d6b
|
/Source/SprueEngine/Libs/nvmesh/param/Util.h
|
0ed6b36ffb9d37b4c8fbf910f5ea90b9c2ae8b54
|
[
"MIT"
] |
permissive
|
caniouff/TexGraph
|
6a30852866c7c3a4a278f94bbd65195951badd64
|
8fe72cea1afcf5e235c810003bf4ee062bb3fc13
|
refs/heads/master
| 2020-06-26T01:28:15.637110
| 2019-01-27T01:00:43
| 2019-01-27T01:00:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 833
|
h
|
// This code is in the public domain -- castano@gmail.com
#pragma once
#include <SprueEngine/MathGeoLib/AllMath.h>
#include <stdint.h>
namespace nv {
namespace HalfEdge { class Mesh; class Vertex; }
bool isQuadMesh(const HalfEdge::Mesh * mesh);
bool isTriangularMesh(const HalfEdge::Mesh * mesh);
uint32_t countMeshTriangles(const HalfEdge::Mesh * mesh);
const HalfEdge::Vertex * findBoundaryVertex(const HalfEdge::Mesh * mesh);
HalfEdge::Mesh * unifyVertices(const HalfEdge::Mesh * inputMesh);
HalfEdge::Mesh * triangulate(const HalfEdge::Mesh * inputMesh);
float triangleArea(const SprueEngine::Vec2& v0, const SprueEngine::Vec2& v1, const SprueEngine::Vec2& v2);
float triangleArea(const SprueEngine::Vec2& v0, const SprueEngine::Vec2& v1);
} // nv namespace
|
[
"jonathan@jsandusky.com"
] |
jonathan@jsandusky.com
|
b1996b73caac59474ab97e252dcd806265378889
|
ba8e87b98e591e02c4a94434315271947d57fdcd
|
/baekjoon_study_won/string/9935_jw.cpp
|
930f6878465c49d20320221a130b3c1618188bee
|
[] |
no_license
|
ji-one/algorithm-study
|
f0e66af8748a2772796b18574586e45ff66d4db8
|
8931faa7a2893c19c150c61dedf0ea3c88965b69
|
refs/heads/main
| 2023-08-02T12:26:33.667856
| 2021-08-23T07:42:55
| 2021-08-23T07:42:55
| 326,375,577
| 2
| 1
| null | 2021-08-23T07:42:55
| 2021-01-03T10:00:37
|
C++
|
UTF-8
|
C++
| false
| false
| 857
|
cpp
|
#include <iostream>
#include <string>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;
int main()
{
string s, e;
cin >> s >> e;
stack<char> st;
for (int i = 0; i < s.length(); i++)
{
st.push(s[i]);
int idx = e.length() - 1;
stack<char> tmp;
while (!st.empty() && idx >= 0 && st.top() == e[idx])
{
--idx;
tmp.push(st.top());
st.pop();
}
if (tmp.size() != e.length())
{
while (!tmp.empty())
{
st.push(tmp.top());
tmp.pop();
}
}
}
string res = "";
while (!st.empty())
{
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
res == "" ? cout << "FRULA" : cout << res;
return 0;
}
|
[
"rlawldnjs8@gmail.com"
] |
rlawldnjs8@gmail.com
|
194e799230d435e1e2c0147ecac0ebbd1423425c
|
7902ad865f181e3bdc7f4445c988fb5cc64cf18d
|
/libsax/test/t_cru.cpp
|
9aad51c61039dab2798fb10e4361bb5fb4bf5cf9
|
[] |
no_license
|
zjx20/xlibsax
|
fa2fcc708eac19f9918be48233be2a9b4e2a921c
|
7889eea8122b6f8ae4f954476aa6bb07d31f3cf2
|
refs/heads/master
| 2021-01-13T02:22:45.294209
| 2014-11-04T12:15:17
| 2014-11-04T12:15:17
| 32,296,550
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 540
|
cpp
|
#include <stdio.h>
#include <string>
#include <sax/c++/crumb.h>
int main( int argc, char *argv[] )
{
typedef int TYPE;
sax::crumb<char, TYPE> x;
x.init(2, 100);
x.add(1, 100);
x.add(2, 200);
x.add(3, 300);
x.purge();
printf("size()=%u\n", x.size());
getchar();
x.purge();
printf("size()=%u\n", x.size());
TYPE z;
if (x.sub(1, &z)) printf("got: %d\n", z);
x.purge();
printf("size()=%d\n", x.size());
getchar();
x.purge();
printf("size()=%d\n", x.size());
return 0;
}
|
[
"zhoujianxiong2@gmail.com"
] |
zhoujianxiong2@gmail.com
|
313e6242deb94de49d6cccd1eb49cc2c43d65607
|
54f62e14405fb25bae9c88e4767944a1d75dec2e
|
/files/asobiba/filer/RfileNetResourceBigIcon.cpp
|
28fd3890b9be5185bc0702a2bdad544e9be52920
|
[] |
no_license
|
Susuo/rtilabs
|
408975914dde59f44c1670ce3db663ed785d00b2
|
822a39d1605de7ea2639bdffdc016d8cc46b0875
|
refs/heads/master
| 2020-12-11T01:48:08.562065
| 2012-04-10T14:22:37
| 2012-04-10T14:22:37
| null | 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 2,017
|
cpp
|
// RfileNetResourceBigIcon.cpp: RfileNetResourceBigIcon クラスのインプリメンテーション
//
//////////////////////////////////////////////////////////////////////
#include "comm.h"
#include "RfileNetResourceBigIcon.h"
//////////////////////////////////////////////////////////////////////
// 構築/消滅
//////////////////////////////////////////////////////////////////////
//登録します。
void RfileNetResourceBigIcon::Attach(const char* inName,const char* inComment,DWORD inDisplayType )
{
this->Name = inName;
if (inComment) this->Comment = inComment;
FileModifyChacheLargeWin32* fmc = FileModifyChacheLargeWin32::getInstance();
switch ( inDisplayType )
{
case RESOURCEDISPLAYTYPE_DOMAIN: //ドメイン.
case RESOURCEDISPLAYTYPE_NETWORK:
case RESOURCEDISPLAYTYPE_SHAREADMIN:
this->FileModify = fmc->SearchSystem( FileModifyChacheLargeWin32::Modifty::__SYSTEMICON_NETRESOURCE_DOMAIN );
break;
case RESOURCEDISPLAYTYPE_SERVER: //サーバ.
this->FileModify = fmc->SearchSystem( FileModifyChacheLargeWin32::Modifty::__SYSTEMICON_NETRESOURCE_SERVER );
break;
case RESOURCEDISPLAYTYPE_SHARE: //共有.
this->FileModify = fmc->SearchSystem( FileModifyChacheLargeWin32::Modifty::__SYSTEMICON_NETRESOURCE_SHAREPOINT_DISK );
break;
case RESOURCEDISPLAYTYPE_GROUP: //ワークグループ.
this->FileModify = fmc->SearchSystem( FileModifyChacheLargeWin32::Modifty::__SYSTEMICON_NETRESOURCE_WORKGROUP );
break;
default: //不明.
this->FileModify = fmc->SearchSystem( FileModifyChacheLargeWin32::Modifty::__SYSTEMICON_NORMALFILE );
break;
}
ASSERT(this->FileModify);
}
//値の取得.
const string RfileNetResourceBigIcon::getVars(__FILECOLUMN_TYPE inType) const
{
switch(inType)
{
case __FILECOLUMN_TYPE_NAME: //名前
return Name;
case __FILECOLUMN_TYPE_COMMENT: //コメント
return Comment;
}
return "";
}
//イメージの取得.
const int RfileNetResourceBigIcon::getImageIndex() const
{
return FileModify->getIndex();
}
|
[
"super.rti@gmail.com"
] |
super.rti@gmail.com
|
c6b786e71d31d4c791d6b7a4b729385043220224
|
3b7510e0b11f33d3d311c73cfe7786828c406095
|
/04/ex01/SuperMutant.cpp
|
9c592fe6f5de51540d65544e9c3128d6154f8347
|
[] |
no_license
|
Nimon77/Piscine_CPP
|
3ae7f747a92018a39d79b91e9f15947e453037e9
|
2a3f745764d4bed60522f0af04aa30cbd24ec7cd
|
refs/heads/main
| 2023-04-14T00:27:58.686490
| 2021-04-17T18:02:22
| 2021-04-17T18:02:22
| 336,347,602
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,285
|
cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* SuperMutant.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nsimon <nsimon@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 16:48:44 by nsimon #+# #+# */
/* Updated: 2021/03/17 23:52:13 by nsimon ### ########.fr */
/* */
/* ************************************************************************** */
#include "SuperMutant.hpp"
SuperMutant::SuperMutant(): Enemy(170, "Super Mutant")
{
std::cout << "Gaaah. Me want smash heads!" << std::endl;
}
SuperMutant::SuperMutant(SuperMutant const & copy): Enemy(copy) {}
SuperMutant::~SuperMutant()
{
std::cout << "Aaargh..." << std::endl;
}
void SuperMutant::takeDamage(int amount)
{
if (amount <= 3)
return ;
Enemy::takeDamage(amount - 3);
}
|
[
"nsimon@student.42.fr"
] |
nsimon@student.42.fr
|
3e35d5695c9dfde233de8b63ea756759da1f086f
|
142492ea1a6d7278856ca04b9945f2a3a017c53c
|
/src/c_cpp/c++11/atomic.cpp
|
e3804ad160a81a29e860c4465c16ed2342c98d50
|
[] |
no_license
|
henrytien/henry-notes
|
4884a19bc10507fe2fcca2bef49dd6050995cb25
|
8bceddea32e0aaffc46feade0a5131d057efd7bf
|
refs/heads/master
| 2023-08-05T04:22:48.982591
| 2021-09-28T04:23:27
| 2021-09-28T04:23:27
| 68,274,996
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 793
|
cpp
|
//
// Created by Henry on 2020-08-26.
//
#include "ac.h"
#include <atomic>
#include <thread>
struct AtomicCounter {
std::atomic<int> value;
AtomicCounter() : value(0) {}
void increment(){
++value;
}
void decrement(){
--value;
}
int get(){
return value.load();
}
};
int main() {
AtomicCounter counter;
counter.increment();
cout << counter.get() << endl;
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread([&counter](){
for (int i = 0; i < 500; ++i) {
counter.increment();
}
}));
}
for(auto& thread : threads) {
thread.join();
}
std::cout << counter.get() << std::endl;
return 0;
}
|
[
"tianhangyu8886@gmail.com"
] |
tianhangyu8886@gmail.com
|
80f99896f6787d9b5107cb474782b7d574b5d33b
|
544a465731b44638ad61a4afa4f341aecf66f3cd
|
/src/ivkapp/SampleComputation.cpp
|
5e430683812ef3cd6773de8ddc91b08e9f74d608
|
[] |
no_license
|
skempken/interverdikom
|
e13cbe592aa6dc5b67d8b2fbb4182bcb2b8bc15b
|
dde091ee71dc1d88bbedb5162771623f3ab8a6f4
|
refs/heads/master
| 2020-05-29T15:29:18.076702
| 2014-01-03T10:10:03
| 2014-01-03T10:10:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,177
|
cpp
|
#include "SampleComputation.h"
#if 0
#include <sstream>
#include <iostream>
#include "rvector.hpp"
using namespace std;
using namespace cxsc;
SampleComputation::~SampleComputation() {}
QDomElement SampleComputation::exportXml(QDomDocument document)
{
/*
// Create test rvector (1, 2, 3, 4)
rvector rvtest; // Test rvector
Resize(rvtest, 4);
for (int i = 1; i <= 4; i++)
rvtest[i] = i;
// Create test ivector ((1,2), (2,3), (3,4), (4,5))
ivector ivtest; // Test rvector
Resize(ivtest, 4);
for (int i = 1; i <= 4; i++)
ivtest[i] = interval(i, i+1);
// Create test rmatrix
rmatrix rmtest;
Resize(rmtest,3,5);
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 5; j++)
rmtest[i][j] = i * j;
// Create test imatrix
imatrix imtest;
Resize(imtest,3,5);
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 5; j++)
imtest[i][j] = interval(i,i + j);
elements["TestRVector"] = xml.rvectorToXml(rvtest);
elements["TestRMatrix"] = xml.rmatrixToXml(rmtest);
elements["TestIVector"] = xml.ivectorToXml(ivtest);
elements["TestIMatrix"] = xml.imatrixToXml(imtest);
// Utility typedef, collection of DOM elements
XMLTools::ElementMap elements;
// Generate XML and assign to element collection
elements["Result"] = xml.realToXml(resultValue);
// Return XML generated from joining the collection
return xml.joinDomElements(elements);
*/
return QDomElement();
}
void SampleComputation::importXml(QDomElement domElement)
{
/*
// Unserialize element collection
XMLTools::ElementMap elements = XMLTools::splitDomElements(domElement);
// Read in serialized values
resultValue = xml.xmlToReal(elements["Result"]);
rvector rvtest = xml.xmlToRvector(elements["TestRVector"]);
rmatrix rmtest = xml.xmlToRmatrix(elements["TestRMatrix"]);
ivector ivtest = xml.xmlToIvector(elements["TestIVector"]);
imatrix imtest = xml.xmlToImatrix(elements["TestIMatrix"]);
// TODO DEBUG REMOVEME test of rvector serialization
cout << "SampleComputation: Unsserialized rvector (size " << VecLen(rvtest) << "): " << endl << rvtest;
cout << "SampleComputation: Unsserialized rmatrix (size " << ColLen(rmtest) << " x " << RowLen(rmtest) << "): " << endl << rmtest;
cout << "SampleComputation: Unsserialized ivector (size " << VecLen(ivtest) << "): " << endl << ivtest;
cout << "SampleComputation: Unsserialized imatrix (size " << ColLen(imtest) << " x " << RowLen(imtest) << "): " << endl << imtest;
*/
}
bool* SampleComputation::compute()
{
/*
// We've got 100000000 operations to count and are computing stuff
setProgressMax(100000000);
setProgressText("Computing stuff.");
// Let's do some bogus calculations
int i = 1;
for (int j = 1; j <= 100000000; j++)
{
// Random operations to waste some CPU power
i *= j;
i += j;
i *= j;
// Update task text after 20000 operations
if ((j % 1000000) == 0)
{
std::stringstream msgStream;
setProgressValue(j);
msgStream << "Computing stuff step " << j / 1000000 << ".";
setProgressText(msgStream.str());
}
}
setProgressText("Finished.");
// Increase result by one each time
resultValue += 1;
*/
return new bool(true);
}
#endif
|
[
"sebastian@ivk-virtualbox.(none)"
] |
sebastian@ivk-virtualbox.(none)
|
789e25afeebc416e566ae515c5dcc29834a5aeba
|
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
|
/3rdParty/boost/1.78.0/boost/mpl/aux_/na_fwd.hpp
|
43882419397ee792f8c05adde94dc9345f50871f
|
[
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode-public-domain",
"JSON",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
arangodb/arangodb
|
0980625e76c56a2449d90dcb8d8f2c485e28a83b
|
43c40535cee37fc7349a21793dc33b1833735af5
|
refs/heads/devel
| 2023-08-31T09:34:47.451950
| 2023-08-31T07:25:02
| 2023-08-31T07:25:02
| 2,649,214
| 13,385
| 982
|
Apache-2.0
| 2023-09-14T17:02:16
| 2011-10-26T06:42:00
|
C++
|
UTF-8
|
C++
| false
| false
| 673
|
hpp
|
#ifndef BOOST_MPL_AUX_NA_FWD_HPP_INCLUDED
#define BOOST_MPL_AUX_NA_FWD_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// 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/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/aux_/adl_barrier.hpp>
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
// n.a. == not available
struct na
{
typedef na type;
enum { value = 0 };
};
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
BOOST_MPL_AUX_ADL_BARRIER_DECL(na)
#endif // BOOST_MPL_AUX_NA_FWD_HPP_INCLUDED
|
[
"jan@arangodb.com"
] |
jan@arangodb.com
|
67481365b4fd35b1dd1c034eff2b69b7338ff1be
|
71b405ad15c691a6517eb3a02f2bef256dfc40b0
|
/trees/print_pre_given_post.cpp
|
909175ae18fb391d5b5c519f35f74d1963fa7efe
|
[] |
no_license
|
shantand/practice
|
22b1b00f32e3b4a1abc9c0ea97df5d9c2e49db33
|
998ca8a0fcc8d19af266c6f4ce9816becf7176b2
|
refs/heads/master
| 2021-01-18T17:45:42.134231
| 2016-04-06T19:46:53
| 2016-04-06T19:46:53
| 14,297,258
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 434
|
cpp
|
#include<iostream>
#include<cstdio>
using namespace std;
void create_pre(int post[],int start,int end)
{
if (start>end) return;
else if(start==end) printf("%d ",post[start]);
else
{
int node1 = post[end];
int i=end-1;
while(post[i]>node1) i--;
printf("%d ",node1);
create_pre(post,start,i);
create_pre(post,i+1,end-1);
}
}
int main()
{
int post[3] = {20,40,30};
create_pre( post,0,2 );
printf("\n");
}
|
[
"shantanu@shantanu-Lenovo-G580.(none)"
] |
shantanu@shantanu-Lenovo-G580.(none)
|
cab75e1d2e9e3e169e8c72f3ab65d2899085c1a4
|
d1baa2026feb1ef8fe58366ffedfb838f3715918
|
/Nella oscura e pronda caverna/Nella oscura e pronda caverna/Scrigno.h
|
aa00c060c64972860f803b144770134634d42f6d
|
[] |
no_license
|
ElMustacho/Nella-oscura-e-profonda-caverna
|
916285aa9a3939b201d7fbe6e0665d269ff1f519
|
da49e881830d03164ee8ff83ae9616fa93956f6c
|
refs/heads/master
| 2018-09-28T08:21:11.669741
| 2018-05-24T15:44:16
| 2018-05-24T15:44:16
| 92,165,746
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 435
|
h
|
#pragma once
#include <list>
#include "Oggetto.h"
class Scrigno : public Oggetto
{
public:
Scrigno(double peso, std::string nome, std::string descrizione, long valore, int unlock, std::list<Oggetto> loot);
~Scrigno();
void open();
std::list<Oggetto> prendiOggetto(Oggetto* scelta = nullptr);
void inserisciOggetto(Oggetto* obj);
private:
std::list<Oggetto> loot;
int unlock; // 0 = aperto, >0 = metodi apertura/chiuso
};
|
[
"fabiopolonia00@gmail.com"
] |
fabiopolonia00@gmail.com
|
8b59fa75114aa247a1488857b3e8391dce90916d
|
38616fa53a78f61d866ad4f2d3251ef471366229
|
/3rdparty/GPSTk/ext/lib/Math/BaseDistribution.hpp
|
d227afb3fb850f86e06f5f182db17489358e7bdf
|
[
"GPL-3.0-only",
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"MIT"
] |
permissive
|
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
|
3b467fa6d3f34cabbd5ee59596ac1950aabf2522
|
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
|
refs/heads/master
| 2020-06-08T12:42:31.977541
| 2019-06-10T15:04:33
| 2019-06-10T15:04:33
| 193,229,646
| 1
| 0
|
MIT
| 2019-06-22T12:07:29
| 2019-06-22T12:07:29
| null |
UTF-8
|
C++
| false
| false
| 2,392
|
hpp
|
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
// Dagoberto Salazar - gAGE ( http://www.gage.es ). 2008
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file BaseDistribution.hpp
* This is a base class for statistical distributions.
*/
#ifndef BASEDISTRIBUTION_HPP
#define BASEDISTRIBUTION_HPP
#include <cmath>
#include "SpecialFunctions.hpp"
#include "Exception.hpp"
namespace gpstk
{
/// @ingroup math
//@{
/// This is a base class for statistical distributions.
class BaseDistribution
{
public:
/// Computes the probability density function
virtual double pdf(double x) = 0;
/// Computes the cumulative distribution function
virtual double cdf(double x) = 0;
}; // End of class "BaseDistribution"
//@}
} // End of namespace gpstk
#endif // BASEDISTRIBUTION_HPP
|
[
"rwatso12@gmail.com"
] |
rwatso12@gmail.com
|
7616de91942d6b90b5623c2c571832afaf31b7cc
|
4e1190455394bb008b9299082cdbd236477e293a
|
/CodeForces/Rounds/271 Div2/b.cpp
|
b2f1e5c92128c633d51150013f75678729945a5d
|
[] |
no_license
|
Leonardosu/competitive_programming
|
64b62fc5a1731763a1bee0f99f9a9d7df15e9e8a
|
01ce1e4f3cb4dc3c5973774287f2e32f92418987
|
refs/heads/master
| 2023-08-04T06:27:26.384700
| 2023-07-24T19:47:57
| 2023-07-24T19:47:57
| 202,539,762
| 4
| 6
| null | 2022-10-25T00:24:54
| 2019-08-15T12:46:33
|
C++
|
UTF-8
|
C++
| false
| false
| 333
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,q,x;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;++i) {
cin>>v[i];
if(i)
v[i] += v[i-1];
}
cin>>q;
while(q--) {
cin>>x;
cout<<(lower_bound(v.begin(),v.end(),x)-v.begin())+1<<"\n";
}
}
|
[
"leonardo.su@ccc.ufcg.edu.br"
] |
leonardo.su@ccc.ufcg.edu.br
|
8fa7dea5da62754d9033a61f7d9afca5015b766c
|
1fb60732828ab4b26dee5c1a6c09192b3e72605b
|
/galaxy-game/SettingMenu.cpp
|
3a941e8ce89db9d7d35ae23a1f19195951bf61e3
|
[] |
no_license
|
phatnm-student-hcmus/ProjectOOP
|
e24a01135607cddbfdbcb7e38c741743d57946b8
|
d1d63f873990506b8cdb2df37a5dd11d297fbaa4
|
refs/heads/master
| 2023-06-18T01:26:48.123211
| 2021-05-09T12:29:10
| 2021-05-09T12:29:10
| 365,736,903
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,923
|
cpp
|
#include "SettingMenu.h"
const int SettingMenu::s_max_volume[6] = { 128,64,15,128,128,128 };
int SettingMenu::s_prev_volume[6] = { 128,64,15,128,128,128 };
SettingMenu::SettingMenu() {
m_event_ = SDL_Event();
ptr_screen_ = NULL;
for (int i = 0; i < 4; i++) {
sound_[i] = NULL;
icons[i] = NULL;
percent_volume_[i] = NULL;
line_rect_[i] = SDL_Rect();
sound_mark_rect_[i] = SDL_Rect();
line_color_[i] = 0;
sound_mark_color_[i] = 0;
}
sound_[4] = NULL;
sound_[5] = NULL;
dragging_ = -1;
open_from_ = OPEN_FROM::START_MENU;
}
SettingMenu::SettingMenu(SDL_Surface* screen) {
ptr_screen_ = screen;
loadImage(s_setting_menu_in_game_img_file_path, 1);
font_ = TTF_OpenFont(s_alberto_font_file_path, s_font_size_start_menu);
for (int i = 0; i < 4; i++) {
sound_[i] = NULL;
icons[i] = new AudioIcon;
percent_volume_[i] = new TextObject("100% ", TextObject::TEXTCOLOR::WHITE_TEXT, font_);
sound_mark_rect_[i].x = 490 + LINE_WIDTH_1 - SOUND_MARK_WIDTH/2;
//cout << "rect 0: " << sound_mark_rect_[i].x << endl;
sound_mark_rect_[i].w = SOUND_MARK_WIDTH;
sound_mark_rect_[i].h = SOUND_MARK_HEIGHT;
//blue
//green
}
sound_[4] = NULL;
sound_[5] = NULL;
line_rect_[0].x = 490;
line_rect_[0].y = 265 - LINE_HEIGHT/2;
line_rect_[0].w = LINE_WIDTH_1;
line_rect_[0].h = LINE_HEIGHT;
line_color_[0] = SDL_MapRGB(screen->format, 109, 207, 246);
line_rect_[1].x = 680;
line_rect_[1].y = 340 - LINE_HEIGHT / 2;
line_rect_[1].w = LINE_WIDTH_2;
line_rect_[1].h = LINE_HEIGHT;
line_color_[1] = SDL_MapRGB(screen->format, 109, 207, 246);
line_rect_[2].x = 680;
line_rect_[2].y = 400 - LINE_HEIGHT / 2;
line_rect_[2].w = LINE_WIDTH_2;
line_rect_[2].h = LINE_HEIGHT;
line_color_[2] = SDL_MapRGB(screen->format, 109, 207, 246);
line_rect_[3].x = 680;
line_rect_[3].y = 460 - LINE_HEIGHT / 2;
line_rect_[3].w = LINE_WIDTH_2;
line_rect_[3].h = LINE_HEIGHT;
line_color_[3] = SDL_MapRGB(screen->format, 109, 207, 246);
sound_mark_rect_[0].y = 265 - LINE_HEIGHT / 2 - SOUND_MARK_HEIGHT / 2;
sound_mark_rect_[1].y = 340 - LINE_HEIGHT / 2 - SOUND_MARK_HEIGHT / 2;
sound_mark_rect_[2].y = 400 - LINE_HEIGHT / 2 - SOUND_MARK_HEIGHT / 2;
sound_mark_rect_[3].y = 460 - LINE_HEIGHT / 2 - SOUND_MARK_HEIGHT / 2;
sound_mark_color_[0] = SDL_MapRGB(screen->format, 109, 207, 246);
sound_mark_color_[1] = SDL_MapRGB(screen->format, 140, 200, 96);
sound_mark_color_[2] = SDL_MapRGB(screen->format, 140, 200, 96);
sound_mark_color_[3] = SDL_MapRGB(screen->format, 140, 200, 96);
icons[0]->setRect(930, 265 - LINE_HEIGHT / 2 - icons[0]->getRect().h / 2);
icons[1]->setRect(930, 340 - LINE_HEIGHT / 2 - icons[1]->getRect().h / 2);
icons[2]->setRect(930, 400 - LINE_HEIGHT / 2 - icons[2]->getRect().h / 2);
icons[3]->setRect(930, 460 - LINE_HEIGHT / 2 - icons[3]->getRect().h / 2);
percent_volume_[0]->setRect(1000, 265 - LINE_HEIGHT / 2 - 72 / 2);
percent_volume_[1]->setRect(1000, 340 - LINE_HEIGHT / 2 - 72 / 2);
percent_volume_[2]->setRect(1000, 400 - LINE_HEIGHT / 2 - 72 / 2);
percent_volume_[3]->setRect(1000, 460 - LINE_HEIGHT / 2 - 72 / 2);
dragging_ = -1;
resume_ = TextObject("RESUME", TextObject::TEXTCOLOR::WHITE_TEXT, font_);
resume_.setRect(SCREEN_WIDTH/2 - 112/2, 150);
exit_game_ = TextObject("EXIT GAME", TextObject::TEXTCOLOR::WHITE_TEXT, font_);
exit_game_.setRect(100, 500);
open_from_ = OPEN_FROM::START_MENU;
}
SettingMenu::~SettingMenu() {
ptr_screen_ = NULL;
for (int i = 0; i < 6; i++) {
sound_[i] = NULL;
}
for (int i = 0; i < 4; i++) {
delete percent_volume_[i];
}
}
int SettingMenu::showMenu(SDL_Surface* screen) {
int ret_val = -1;
int x_mouse, y_mouse;
while (true) {
changeSoundVolume();
show(screen);
showAllText(screen);
//show rectangle
for (int i = 0; i < 4; i++) {
icons[i]->show(screen);
SDL_FillRect(screen, &line_rect_[i], line_color_[i]);
SDL_FillRect(screen, &sound_mark_rect_[i], sound_mark_color_[i]);
}
while (SDL_PollEvent(&m_event_)) {
switch (m_event_.type) {
case SDL_QUIT:
ret_val = RETURN_VALUE::EXIT_GAME;
return ret_val;
case SDL_MOUSEMOTION:
x_mouse = m_event_.motion.x;
y_mouse = m_event_.motion.y;
mouseMotionCheck(x_mouse, y_mouse);
break;
case SDL_MOUSEBUTTONDOWN:
x_mouse = m_event_.motion.x;
y_mouse = m_event_.motion.y;
ret_val = mouseButtonDown(x_mouse, y_mouse);
switch (ret_val) {
case MOUSE_BTN_DOWN_RET::NOTHING:
break;
case MOUSE_BTN_DOWN_RET::RESUME:
return RETURN_VALUE::RESUME_GAME;
case MOUSE_BTN_DOWN_RET::CHANGE_VOLUME:
break;
case MOUSE_BTN_DOWN_RET::EXIT:
return RETURN_VALUE::EXIT_GAME;
case MOUSE_BTN_DOWN_RET::DRAG:
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONUP:
x_mouse = m_event_.motion.x;
y_mouse = m_event_.motion.y;
ret_val = mouseButtonDown(x_mouse, y_mouse);
dragging_ = -1;
changeSoundVolume();
break;
case SDL_KEYDOWN:
if (m_event_.key.keysym.sym == SDLK_ESCAPE) {
return RETURN_VALUE::RESUME_GAME;
}
break;
default:
ret_val = -1;
break;
}
}
SDL_Flip(screen);
}
return -1;
}
void SettingMenu::showAllText(SDL_Surface* screen) {
int percent_volume[4] = { 0 };
//music
if (sound_[0]) {
if (open_from_ == OPEN_FROM::START_MENU) {
percent_volume[0] = sound_[0]->volume * 100 / s_max_volume[0];
}
}
if (sound_[1]) {
if (open_from_ == OPEN_FROM::IN_GAME) {
percent_volume[0] = sound_[1]->volume * 100 / s_max_volume[1];
}
}
if (sound_[2]) {
percent_volume[1] = sound_[2]->volume * 100 / s_max_volume[2];
}
if (sound_[3]) {
percent_volume[2] = sound_[3]->volume * 100 / s_max_volume[3];
}
if (sound_[4]) {
percent_volume[2] = sound_[4]->volume * 100 / s_max_volume[4];
}
if (sound_[5]) {
percent_volume[3] = sound_[5]->volume * 100 / s_max_volume[5];
}
for (int i = 0; i < 4; i++) {
percent_volume_[i]->setTextContent(to_string(percent_volume[i]) + "%");
percent_volume_[i]->show(screen);
}
resume_.show(screen);
exit_game_.show(screen);
}
void SettingMenu::mouseMotionCheck(const int& x_mouse, const int& y_mouse){
if (dragging_ == -1) {
for (int i = 0; i < 4; i++) {
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, sound_mark_rect_[i]))
{
//red
sound_mark_color_[i] = SDL_MapRGB(ptr_screen_->format, 0xff, 0, 0);
}
else {
//blue
sound_mark_color_[i] = SDL_MapRGB(ptr_screen_->format, 0, 0xff, 0);
}
}
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, resume_.getRect()))
{
resume_.setTextColor(TextObject::TEXTCOLOR::YELLOW_TEXT);
}
else {
resume_.setTextColor(TextObject::TEXTCOLOR::WHITE_TEXT);
}
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, exit_game_.getRect())) {
exit_game_.setTextColor(TextObject::TEXTCOLOR::YELLOW_TEXT);
}
else {
exit_game_.setTextColor(TextObject::TEXTCOLOR::WHITE_TEXT);
}
}
else {
sound_mark_color_[dragging_] = SDL_MapRGB(ptr_screen_->format, 0xff, 0, 0);
}
}
int SettingMenu::mouseButtonDown(const int& x_mouse, const int& y_mouse) {
int ret = -1;
if (dragging_ == -1) {
for (int i = 0; i < 4; i++) {
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, sound_mark_rect_[i]))
{
dragging_ = i;
cout << dragging_ << endl;
return DRAG;
}
else if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, icons[i]->getRect()) && m_event_.type != SDL_MOUSEBUTTONDOWN) {
if (icons[i]->get_is_mute() == false) {
icons[i]->set_is_mute(true);
sound_mark_rect_[i].x = line_rect_[i].x;
}
else {
icons[i]->set_is_mute(false);
sound_mark_rect_[i].x = line_rect_[i].x + line_rect_[i].w - sound_mark_rect_[i].w / 2;
}
}
}
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, resume_.getRect())) {
ret = MOUSE_BTN_DOWN_RET::RESUME;
}
if (CommonFunction::checkMouseFocusWithRect(x_mouse, y_mouse, exit_game_.getRect())) {
ret = MOUSE_BTN_DOWN_RET::EXIT;
}
}
else {
//p: index of sound mark
int p = dragging_;
sound_mark_rect_[p].x = MAX(line_rect_[p].x, MIN(x_mouse, line_rect_[p].x + line_rect_[p].w - sound_mark_rect_[p].w / 2));
if (sound_mark_rect_[p].x == line_rect_[p].x) {
icons[p]->set_is_mute(true);
sound_mark_rect_[p].x = line_rect_[p].x;
}
else {
icons[p]->set_is_mute(false);
}
ret = 1;
}
return ret;
}
void SettingMenu::setSound(Mix_Chunk* s1, Mix_Chunk* s2, Mix_Chunk* s3, Mix_Chunk* s4, Mix_Chunk* s5, Mix_Chunk* s6) {
sound_[0] = s1;
sound_[1] = s2;
sound_[2] = s3;
sound_[3] = s4;
sound_[4] = s5;
sound_[5] = s6;
}
void SettingMenu::changeSoundVolume() {
int percent_volume[4] = { 0 };
for (int i = 0; i < 4; i++) {
percent_volume[i] = 100 * (sound_mark_rect_[i].x - line_rect_[i].x) / (line_rect_[i].w - sound_mark_rect_[i].w/2);
}
//music
if (sound_[0] && sound_[1]) {
if (open_from_ == OPEN_FROM::START_MENU) {
sound_[0]->volume = percent_volume[0] * MAX_VOLUME::MAX_VOL_0 / 100;
sound_[1]->volume = 0;
}
else if (open_from_ == OPEN_FROM::IN_GAME) {
sound_[0]->volume = 0;
sound_[1]->volume = percent_volume[0] * MAX_VOLUME::MAX_VOL_1 / 100;
}
}
if (sound_[2]) {
sound_[2]->volume = percent_volume[1] * 15 / 100;
}
if (sound_[3]) {
sound_[3]->volume = percent_volume[2] * 128 / 100;
}
if (sound_[4]) {
sound_[4]->volume = percent_volume[2] * 128 / 100;
}
if (sound_[5]) {
sound_[5]->volume = percent_volume[3] * 128 / 100;
}
}
bool SettingMenu::getOpenFrom() {
return open_from_;
}
void SettingMenu::setOpenFrom(const bool& state) {
open_from_ = state;
if (state == OPEN_FROM::IN_GAME) {
if (sound_[0])
sound_[0]->volume = 0;
if (sound_[1])
Mix_VolumeChunk(sound_[1], MAX_VOLUME::MAX_VOL_1);
}
else {
if (sound_[0])
Mix_VolumeChunk(sound_[0], MAX_VOLUME::MAX_VOL_0);
if(sound_[1])
sound_[1]->volume = 0;
}
}
|
[
"74006956+phatnguqqq-2428@users.noreply.github.com"
] |
74006956+phatnguqqq-2428@users.noreply.github.com
|
9ecbb2de600ce9d8ec347f62ec25a8d69710bf86
|
e25f25a77af3e9eae0a714f9d2b572e12e049d08
|
/include/template.hpp
|
4633f777c3bccdc6b613b0f2b8ded604f14d8c9e
|
[] |
no_license
|
liyunwei-3558/Template_Learner
|
fedb0be07b9b5e6f1daa1481f7efc4a70ff7041a
|
9a5ca00e9b5b0ef1bc5e70a27d6cfd26a03da60c
|
refs/heads/master
| 2021-05-22T17:40:22.440374
| 2020-04-04T15:27:59
| 2020-04-04T15:27:59
| 253,025,223
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,574
|
hpp
|
/*
Formula Student Driverless Project (FSD-Project).
Copyright (c) 2019:
- chentairan <killasipilin@gmail.com>
FSD-Project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FSD-Project is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FSD-Project. If not, see <https://www.gnu.org/licenses/>.
*/
//.hpp这是类的声明文件
#ifndef TEMPLATE_HPP //防止重复定义 TEMPLATE_HPP
#define TEMPLATE_HPP
#include "fsd_common_msgs/ConeDetections.h" //包含了这两种消息类型
#include "std_msgs/String.h"
namespace ns_template {
class Template {
public:
// Constructor
Template(ros::NodeHandle& nh);//构造函数,与类同名, 传引用参数是一个句柄
// Getters
fsd_common_msgs::ConeDetections getConeDetections();//一个获取成员变量具体值的函数,返回类型是公用消息包中的ConeDetections类型
// Setters
void setConeDetections(fsd_common_msgs::ConeDetections cones);
void runAlgorithm();
private:
ros::NodeHandle& nh_;//句柄类型成员变量nh_
fsd_common_msgs::ConeDetections cone_current;
};
}
#endif //TEMPLATE_HPP
|
[
"1084087910@qq.com"
] |
1084087910@qq.com
|
d86a51a88075316b53a7502e80fc004e6fcfd712
|
195e3b6d1468df2a8aa7b9300f8ef61103fceff2
|
/Object.h
|
b7da8c28984ce6f9f2730e3d63f22c5ec5b21d6c
|
[
"MIT"
] |
permissive
|
adrianlacour/Bell-LaPadula-Security-Monitor
|
6495c9abc61573557406dcaa1ebd0912ff48cb17
|
2d6a46d9c66bde1c8b4cbf339b1c2c716befcebf
|
refs/heads/master
| 2020-04-16T00:12:13.854052
| 2019-01-10T21:04:33
| 2019-01-10T21:04:33
| 165,130,360
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 594
|
h
|
/*
Author : Adrian LaCour
Course : CSCE 4550
Description: This header file holdes the Object class, which will hold the name and
value of the object that is stored with the object.
*/
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Object{
public:
string name; //Holds the name of the object
//The current value of an object, which doesn't change unless a WRITE command is initiated
int value = 0;
Object(string name1)//Constructor
{
name = name1;
}
};
|
[
"noreply@github.com"
] |
adrianlacour.noreply@github.com
|
a0af246ff9cc2e7bac0b2a737429894455ee5532
|
7f0c143c141c6803f5ef8da55c3c8d49ec7898e8
|
/Ultrasonix.Amplio/Ultrasonix.Amplio.cpp
|
e7879c3d2f7f3aca5b823e6dc228581521c79fdc
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
loselvisos/Ultrasonix-.NET-SDK-1
|
d585799e4bc21d45806a43d22846e4803f80ceea
|
a4fddd775fe0b068c7d8b20c053e44a8b9a0d5cb
|
refs/heads/master
| 2021-01-23T20:18:03.505781
| 2012-08-15T07:44:01
| 2012-08-15T07:44:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 84
|
cpp
|
// This is the main DLL file.
#include "stdafx.h"
#include "Ultrasonix.Amplio.h"
|
[
"eddinsw@gmail.com"
] |
eddinsw@gmail.com
|
6016ba593e02abc45f43bcc749eba1ea5f9f19f9
|
545b3638c12f5af3157533e2c4b096d5b4dc1e57
|
/ook/ast/index_node.h
|
d60e08284f2638569b234299f3a6cfb433837c54
|
[] |
no_license
|
Pedrolindeza/OOK
|
88d8cd01625c0ee82b7fa02fd782bc0eb01c2e9d
|
bac0d83654c60137d080535c71274f490a89a02f
|
refs/heads/master
| 2020-12-30T10:36:24.345404
| 2017-08-02T19:34:27
| 2017-08-02T19:34:27
| 99,149,853
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 726
|
h
|
#ifndef __CDK_INDEXNODE_H__
#define __CDK_INDEXNODE_H__
#include <cdk/ast/expression_node.h>
namespace ook {
/**
* Class for describing index nodes.
*/
class index_node: public cdk::lvalue_node {
cdk::expression_node *_base;
cdk::expression_node *_offset;
public:
inline index_node(int lineno, cdk::expression_node *base, cdk::expression_node *offset) :
cdk::lvalue_node(lineno), _base(base), _offset(offset){
}
public:
inline cdk::expression_node *base() {
return _base;
}
inline cdk::expression_node *offset() {
return _offset;
}
void accept(basic_ast_visitor *sp, int level) {
sp->do_index_node(this, level);
}
};
} // ook
#endif
|
[
"pedro.lindeza@tecnico.ulisboa.pt"
] |
pedro.lindeza@tecnico.ulisboa.pt
|
8438df2ec2b29b28c959b39e5fd3ce57a9339106
|
3b9b4049a8e7d38b49e07bb752780b2f1d792851
|
/src/third_party/pdfium/xfa/fwl/basewidget/ifwl_picturebox.h
|
8ff4981e11cc54debad1c5945ded9cf3aa58cc4d
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
webosce/chromium53
|
f8e745e91363586aee9620c609aacf15b3261540
|
9171447efcf0bb393d41d1dc877c7c13c46d8e38
|
refs/heads/webosce
| 2020-03-26T23:08:14.416858
| 2018-08-23T08:35:17
| 2018-09-20T14:25:18
| 145,513,343
| 0
| 2
|
Apache-2.0
| 2019-08-21T22:44:55
| 2018-08-21T05:52:31
| null |
UTF-8
|
C++
| false
| false
| 1,936
|
h
|
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef XFA_FWL_BASEWIDGET_IFWL_PICTUREBOX_H_
#define XFA_FWL_BASEWIDGET_IFWL_PICTUREBOX_H_
#include "xfa/fwl/core/fwl_widgetimp.h"
#include "xfa/fwl/core/ifwl_dataprovider.h"
#include "xfa/fwl/core/ifwl_widget.h"
#include "xfa/fwl/core/cfwl_widgetimpproperties.h"
#include "xfa/fwl/core/fwl_error.h"
#define FWL_CLASS_PictureBox L"FWL_PICTUREBOX"
#define FWL_STYLEEXT_PTB_Left 0L << 0
#define FWL_STYLEEXT_PTB_Center 1L << 0
#define FWL_STYLEEXT_PTB_Right 2L << 0
#define FWL_STYLEEXT_PTB_Top 0L << 2
#define FWL_STYLEEXT_PTB_Vcenter 1L << 2
#define FWL_STYLEEXT_PTB_Bottom 2L << 2
#define FWL_STYLEEXT_PTB_Normal 0L << 4
#define FWL_STYLEEXT_PTB_AutoSize 1L << 4
#define FWL_STYLEEXT_PTB_StretchImage 2L << 4
#define FWL_STYLEEXT_PTB_StretchHImage 3L << 4
#define FWL_STYLEEXT_PTB_StretchVImage 4L << 4
#define FWL_STYLEEXT_PTB_HAlignMask 3L << 0
#define FWL_STYLEEXT_PTB_VAlignMask 3L << 2
#define FWL_STYLEEXT_PTB_StretchAlignMask 7L << 4
class CFX_DIBitmap;
class IFWL_PictureBoxDP : public IFWL_DataProvider {
public:
virtual CFX_DIBitmap* GetPicture(IFWL_Widget* pWidget) = 0;
virtual CFX_DIBitmap* GetErrorPicture(IFWL_Widget* pWidget) = 0;
virtual CFX_DIBitmap* GetInitialPicture(IFWL_Widget* pWidget) = 0;
virtual int32_t GetOpacity(IFWL_Widget* pWidget) = 0;
virtual int32_t GetFlipMode(IFWL_Widget* pWidget) = 0;
virtual FWL_Error GetMatrix(IFWL_Widget* pWidget, CFX_Matrix& matrix) = 0;
};
class IFWL_PictureBox : public IFWL_Widget {
public:
static IFWL_PictureBox* Create(const CFWL_WidgetImpProperties& properties,
IFWL_Widget* pOuter);
protected:
IFWL_PictureBox();
};
#endif // XFA_FWL_BASEWIDGET_IFWL_PICTUREBOX_H_
|
[
"changhyeok.bae@lge.com"
] |
changhyeok.bae@lge.com
|
5018584415491ab5ecca2fbfbc46fca4a5c17c20
|
8c2a59b0d65d3dbc96337a3b24ab99e87bf47649
|
/Arduino/smart-hub/sketch_nov30a.ino
|
4c9ea616bccfc41b59140a63359cfaa4f53abf9e
|
[] |
no_license
|
luke-truitt/smart-store
|
be8b025943f59703c2f0c48c56e03c76f43e55c9
|
b1284fb2edcc44d5ec2ad4dfac1004397d320b65
|
refs/heads/master
| 2020-09-07T17:58:34.967890
| 2019-12-07T20:21:18
| 2019-12-07T20:21:18
| 220,869,010
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,412
|
ino
|
#include <SoftwareSerial.h>
/*
This Arduino project uses a Bluetooth serial modem, a parallel LCD display, and your Android phone to
demonstrate how an Arduino can communicate with an Android device.
I have added nothing new here; just taken other people's existing work to guide you on how
Arduino and Android can talk to each other through Bluetooth. I created this from the Arduino LCD Display example (Igoe, Fried, Mellis),
NewSoftSerial (Fried, Hart), and Google Bluetooth Chat. Anyone is free to use this software as they wish. Mark Bieschke, 4/2011.
Instructions for this project:
1. Download Google's "Bluetooth Chat" Android example for your target Android version. In the BluetoothChatService class, change the MY_UUID value to :00001101-0000-1000-8000-00805F9B34FB as follows:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Save, Run, and plug your Android phone into your USB so the code deploys to your Android phone (can't use a Virtual device).
On your phone, go to "Settings - Applications - Development" and make sure you turned on USB debugging.
2. Hook up your parallel LCD and BlueSMiRF Gold Bluetooth modem to your Arduino and deploy this code to your Arduino.
See my diagrams on how to wire up everything on instructables.com.
3. Through hyperterminal (or TeraTerm), make sure you have changed your BlueSMiRF Gold BAUD rate to 57.6k. It defaults to 115k.
4. Open up the Android Chat native app on your phone: press the Android menu button, "Connect a Device", then select "Firefly".
Now you have paired Android to Arduino. You may need to type passcode: 1234.
5. Type and send a message from Android phone to Arduino through the text message box in the Bluetooth Chat Android app.
6. See an Arduino-generated String ("Hello from Arduino") appear on your Android device's LCD about 30 seconds after you connect, then again 30 seconds later.
I decided to do this as an easy, maybe lazy, way to send a test message from Arduino to Android.
Parts list:
1. Arduino Board - I used an Uno (328, 16MHz, 5V)
2. Bluetooth Modem - BlueSMiRF Gold (Sparkfun sku: WRL-00582)
Set BAUD to 57.6k using Hyperterminal or TeraTerm
commands to set BAUD: www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-bluetooth-um.pdf
3. Parallel LCD - Basic 16x2 Character LCD (Sparkfun sku: LCD-09051)
Don't forget a 10k potentiometer so you can adjust contrast (a must have)
4. Android device with Bluetooth - I used a Motorola Droid for test
5. wires to connect Arduino, Bluetooth modem, LCD
6. Power supply for your Arduino
Software:
1. Arduino software
2. NewSoftSerial library from Mikal Hart. http://arduiniana.org/libraries/newsoftserial/
His library is better than the built-in "Serial." implementation.
3. Eclipse with Android Development Kit. Make sure you follow Google's directions for downloading and installing ADK.
4. "Bluetooth Chat" sample code from Google. http://developer.android.com/resources/samples/BluetoothChat/index.html
Super important: In the BluetoothChatService class, change the MY_UUID value to :00001101-0000-1000-8000-00805F9B34FB
- this is a common machine UUID that allows Android to communicate with the FireFly Bluetooth module
- save and then run; deploy to actual Android phone because you can't use a virtual device because a virtual device doesn't have Bluetooth
*/
/**************** LCD instructions *****************************
* How to connect the typical Parallel 16x2 LCD (pins shown in parenthesis) to an Arduino Uno board:
* LCD VSS (pin 1 of LCD) to Arduino Ground
* LCD VDD (pin 2) to Arduino 5V
* 10K resistor:
* ends to +5V and ground, respectively
* wiper to LCD VO (pin 3 of LCD)
* LCD RS (pin 4) to Arduino digital pin 9
* LCD R/W (pin 5) to Arduino Ground
* LCD Enable (pin 6) to Arduino digital pin 8
* LCD D4 (pin 11) to Arduino digital pin 7
* LCD D5 (pin 12) to Arduino digital pin 6
* LCD D6 (pin 13) to Arduino digital pin 5
* LCD D7 (pin 14) to Arduino digital pin 4
* LCD LED+ (pin 15) to Arduino 5V (only if LCD has backlight capability)
* LCD LED- (pin 16) to Arduino Ground (only if LCD has backlight capability)
*/
// initialize the LCD library with the numbers of the Arduino digital pins above
int led = A0;
int button = 2;
#define rxPin 10
#define txPin 11
/**************** Serial Port instructions *****************************
NewSoftSerial allows us to create a serial communications port out of thin air on pins 2 (RX) and 3 (TX) to communicate with
the Bluetooth modem (which then communicates to Android device via Bluetooth).
The built-in Arduino Serial communication to the computer is on pins 0 and 1 and we don't need to mess with
those pins because we may want to communicate with the computer through pins 0 and 1 so that's why we create
another serial port on pins 2 and 3.
The Bluetooth modem I used defaults to 115k BAUD which is too fast for Arduino to receive from Android
At low BUAD, like 9600, Arduino sends a "choppy" message to Android (I don't
know how to better articulate it but go ahead and try to connect at 9600 and see what I mean).
To change from 115k default baud, using hyperterminal,
put the Bluetooth modem in "command" mode ($$$) and change to 57.6k BAUD (su,57). Get back in "data" mode (---) for Arduino to communicate with the BlueSMiRF Gold.
*/
SoftwareSerial bluetooth(rxPin, txPin); // (RX, TX)
// **************** these are variables and constants for sending a test message from Arduino to the Android device
// the interval to send a pre-defined message from Arduino to the Droid
int const chatInterval = 5000; // after 30 seconds, send a message to the connected Android device.
int numberOfTimesToSend = 10; // the number of times to send the message (spaced out by number of chatInterval above)
int lastChatSendTime = 0; //the last time - in millis() - that we sent a message to the Droid
String chatMessage = "Hello from Arduino"; // change this to anything you want to send to the Android device
int chatSendCounter = 0; //the number of times we've sent the message
// **************** end section on sending messages from Arduino to the Android device
int buttonState = 0;
void setup()
{
pinMode(led, OUTPUT);
pinMode(button, INPUT);
Serial.begin(9600);
// serial port communications from Arduino to Bluetooth Firefly module (BlueSMiRF Gold)
// BlueSMiRF Gold defaults to 115.2k BAUD. Change to 57.6k BAUD.
// Don't ever use low BAUD like 4800 and 9600.
bluetooth.begin(57600); // Start bluetooth serial at 9600
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
//reset the timer so we can send a message to the Droid in "chatInterval" seconds from now (30 seconds unless you change it in initialization above)
lastChatSendTime = millis();
}
void loop()
{
//bluetooth.print("***looping***");
//*************receiving a message from Android and printing on Arduino*************************
while (bluetooth.available() > 0) {
// display each character to the LCD
char c = bluetooth.read();
Serial.print(c);
if(c=='t') {
digitalWrite(led, HIGH);
}
if(c=='a'){
digitalWrite(led, LOW);
}
}
buttonState = digitalRead(button);
if(buttonState==HIGH)
{
Serial.print("HIGH");
}
if(bluetooth.available()>0) {
Serial.print(bluetooth.available());
Serial.print("\n");
}
if (bluetooth.available())
{
Serial.print("got char: ");
char c = bluetooth.read();
Serial.print(c); //get message from Android device on the Arduino NewSoftSerial serial port and print it out on the LCD
Serial.print("\n");
}
if(Serial.available()>0) {
Serial.print("Sending\n");
bluetooth.print(Serial.read());
}
// //*************sending a message from Arduino to Android *************************
// if (((millis() - lastChatSendTime) > chatInterval))
// //send a predefined message to the Android device after 'chatInterval' seconds and do this 'numberOfTimesToSend' times.
// {
// lastChatSendTime = millis();
// chatSendCounter++; //increment chat counter
// bluetooth.print(chatMessage); //print out the message on the NewSoftSerial serial port which then travels via Bluetooth to the Android device
// }
}
|
[
"lot@duke.edu"
] |
lot@duke.edu
|
22de05f8674f357a91d9401f216ee189e27f2323
|
ecfb6ef1f4480e0644b3f7bd51ed2198b34fec37
|
/Modules/Contents/UI/Include/PolyUIImageButton.h
|
58dcdc7d2864f680f8e09c49e5e410d923875a60
|
[
"MIT"
] |
permissive
|
linuxaged/Polycode
|
4eee34dfa5c867033a4c0c7ea91eda2418bd80b1
|
38bfad114d6b24e8be1f6db76b384777e3372b0f
|
refs/heads/master
| 2020-12-11T01:50:43.875483
| 2013-11-22T05:14:44
| 2013-11-22T05:14:44
| 14,579,437
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,544
|
h
|
/*
Copyright (C) 2012 by Ivan Safrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include "PolyGlobals.h"
#include "PolyScreenImage.h"
#include "PolyScreenShape.h"
#include "PolyScreenEntity.h"
#include "PolyUIEvent.h"
#include "PolyUIElement.h"
namespace Polycode {
class _PolyExport UIImageButton : public UIElement {
public:
UIImageButton(String imageName);
~UIImageButton();
void handleEvent(Event *event);
private:
ScreenShape *buttonRect;
ScreenImage *buttonImage;
bool pressedDown;
};
}
|
[
"ivansafrin@gmail.com"
] |
ivansafrin@gmail.com
|
3e7b6ba9e7b3a14d4df1f3a848829689434b0db8
|
a78aa555b175e699c96553e3d714066bcc281ed8
|
/model/valuesbyetc.cpp
|
3728ccb65c6449e1a99c53e241b5d8632f48ecf6
|
[
"Apache-2.0"
] |
permissive
|
rdffg/bcaa_importer
|
0cb503c289002e573bcf8996178381cf001da742
|
f92e0b39673b5c557540154d4567c53a15adadcd
|
refs/heads/master
| 2021-08-28T16:05:39.936780
| 2021-08-20T20:00:53
| 2021-08-20T20:00:53
| 92,878,678
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,310
|
cpp
|
#include "valuesbyetc.h"
namespace model {
ValuesByETC::ValuesByETC(QObject *parent) : QDjangoModel(parent)
{
}
QString ValuesByETC::taxExemptCode() const
{
return m_taxExemptCode;
}
void ValuesByETC::setTaxExemptCode(const QString &taxExemptCode)
{
m_taxExemptCode = taxExemptCode;
}
QString ValuesByETC::taxExemptDescription() const
{
return m_taxExemptDescription;
}
void ValuesByETC::setTaxExemptDescription(const QString &taxExemptDescription)
{
m_taxExemptDescription = taxExemptDescription;
}
QString ValuesByETC::propertyClassCode() const
{
return m_propertyClassCode;
}
void ValuesByETC::setPropertyClassCode(const QString &propertyClassCode)
{
m_propertyClassCode = propertyClassCode;
}
QString ValuesByETC::propertyClassDescription() const
{
return m_propertyClassDescription;
}
void ValuesByETC::setPropertyClassDescription(const QString &propertyClassDescription)
{
m_propertyClassDescription = propertyClassDescription;
}
double ValuesByETC::landValue() const
{
return m_landValue;
}
void ValuesByETC::setLandValue(const double &value)
{
m_landValue = value;
}
double ValuesByETC::improvementValue() const
{
return m_improvementValue;
}
void ValuesByETC::setImprovementValue(const double &value)
{
m_improvementValue = value;
}
Folio *ValuesByETC::folio() const
{
return qobject_cast<Folio*>(foreignKey("folio"));
}
void ValuesByETC::setFolio(Folio *folio)
{
setForeignKey("folio", folio);
}
//std::unique_ptr<TaxExemptPropertyClassValue> TaxExemptPropertyClassValue::fromXml(dataadvice::ValuesByETC &values)
//{
// auto model = std::make_unique<TaxExemptPropertyClassValue>();
// model->setTaxExemptCode(QString::fromStdString(values.TaxExemptCode()));
// if (values.TaxExemptDescription().present())
// model->setTaxExemptDescription(QString::fromStdString(values.TaxExemptDescription().get()));
// model->setPropertyClassCode(QString::fromStdString(values.PropertyClassCode()));
// if (values.PropertyClassDescription().present())
// model->setPropertyClassDescription(QString::fromStdString(values.PropertyClassDescription().get()));
// model->setLandValue(values.LandValue());
// model->setImprovementValue(values.ImprovementValue());
// return model;
//}
} // namespace model
|
[
"dmahoney@rdffg.bc.ca"
] |
dmahoney@rdffg.bc.ca
|
91b1734c7854f571882ea06f3813aba2cc8f3711
|
4ca256bbc316310255d37675117ea0c6d37cefb2
|
/OF4.0/tutorials/unidirectionalSheetFlow/twoPhaseML/0/alpha.sand
|
16dc921fea121995b39c26ec33a90057511b2d58
|
[] |
no_license
|
CyrilleBonamy/mixt3SedFoam
|
0de2d8cd16f75aff7e9cda196d4d06f13e18e3e2
|
48cba1a24c700cc73cc8f240dde490f7b6d36a69
|
refs/heads/main
| 2023-07-31T05:30:05.162936
| 2021-09-27T14:57:45
| 2021-09-27T14:57:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,553
|
sand
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object alpha.sand;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField nonuniform List<scalar>
400
(
0.529875
0.529852
0.529825
0.529792
0.529754
0.529708
0.529655
0.529591
0.529515
0.529425
0.529318
0.529192
0.529043
0.528866
0.528656
0.528408
0.528114
0.527766
0.527354
0.526867
0.526291
0.525609
0.524803
0.523851
0.522728
0.521402
0.519839
0.517999
0.515835
0.513293
0.510312
0.506823
0.502749
0.498004
0.492495
0.48612
0.478775
0.470351
0.460742
0.449849
0.437586
0.42389
0.408727
0.392101
0.374066
0.354727
0.334244
0.312833
0.290756
0.268312
0.245821
0.223604
0.201968
0.181188
0.161493
0.143061
0.126013
0.110417
0.0962909
0.0836121
0.0723243
0.0623476
0.053586
0.0459347
0.0392858
0.0335326
0.0285729
0.0243108
0.0206583
0.0175356
0.0148711
0.0126015
0.0106711
0.00903124
0.00763969
0.0064599
0.00546039
0.00461417
0.00389812
0.00329249
0.00278046
0.0023477
0.00198205
0.00167316
0.00141228
0.00119199
0.00100599
0.000848975
0.000716429
0.000604554
0.000510132
0.000430445
0.000363198
0.00030645
0.000258564
0.000218158
0.000184064
0.000155297
0.000131025
0.000110545
9.32661e-05
7.86875e-05
6.63874e-05
5.60098e-05
4.72543e-05
3.98673e-05
3.36351e-05
2.8377e-05
2.39409e-05
2.01982e-05
1.70406e-05
1.43766e-05
1.21291e-05
1.0233e-05
8.63321e-06
7.28355e-06
6.14489e-06
5.18424e-06
4.37376e-06
3.69e-06
3.11312e-06
2.62643e-06
2.21583e-06
1.86942e-06
1.57717e-06
1.3306e-06
1.12258e-06
9.47082e-07
7.9902e-07
6.74105e-07
5.68719e-07
4.79808e-07
4.04797e-07
3.41513e-07
2.88123e-07
2.43079e-07
2.05077e-07
1.73017e-07
1.45968e-07
1.23148e-07
1.03896e-07
8.76531e-08
7.39499e-08
6.23889e-08
5.26353e-08
4.44066e-08
3.74643e-08
3.16073e-08
2.6666e-08
2.24971e-08
1.898e-08
1.60128e-08
1.35094e-08
1.13974e-08
9.61561e-09
8.11235e-09
6.8441e-09
5.77413e-09
4.87143e-09
4.10985e-09
3.46734e-09
2.92527e-09
2.46795e-09
2.08212e-09
1.75661e-09
1.48199e-09
1.25031e-09
1.05484e-09
8.8993e-10
7.50803e-10
6.33426e-10
5.34399e-10
4.50854e-10
3.80369e-10
3.20904e-10
2.70736e-10
2.2841e-10
1.92702e-10
1.62576e-10
1.37159e-10
1.15716e-10
9.76259e-11
8.23635e-11
6.94872e-11
5.86239e-11
4.94589e-11
4.17268e-11
3.52034e-11
2.96999e-11
2.50567e-11
2.11395e-11
1.78346e-11
1.50465e-11
1.26942e-11
1.07096e-11
9.03534e-12
7.62278e-12
6.43109e-12
5.42569e-12
4.57745e-12
3.86185e-12
3.2581e-12
2.74874e-12
2.31901e-12
1.95646e-12
1.6506e-12
1.39255e-12
1.17487e-12
9.9119e-13
8.36231e-13
7.05484e-13
5.95214e-13
5.02156e-13
4.23632e-13
3.57405e-13
3.01535e-13
2.54403e-13
2.14626e-13
1.81086e-13
1.52753e-13
1.28893e-13
1.0874e-13
9.17344e-14
7.74064e-14
6.5285e-14
5.50759e-14
4.6485e-14
3.92181e-14
3.30691e-14
2.79204e-14
2.35367e-14
1.98591e-14
1.67699e-14
1.41515e-14
1.19155e-14
1.0062e-14
8.50264e-15
7.14928e-15
6.03129e-15
5.08982e-15
4.29545e-15
3.61877e-15
3.05977e-15
2.58904e-15
2.17715e-15
1.8241e-15
1.55931e-15
1.29452e-15
1.11799e-15
9.41469e-16
7.94365e-16
6.76681e-16
5.58997e-16
4.70735e-16
4.11893e-16
3.2363e-16
2.94209e-16
2.35367e-16
2.05946e-16
1.76525e-16
1.47105e-16
1.17684e-16
8.82627e-17
8.82627e-17
5.88418e-17
5.88418e-17
5.88418e-17
2.94209e-17
2.94209e-17
2.94209e-17
2.94209e-17
2.94209e-17
2.94209e-17
2.94209e-17
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
)
;
boundaryField
{
inlet
{
type cyclic;
}
outlet
{
type cyclic;
}
top
{
type zeroGradient;
}
bottom
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
|
[
"me.ouda@gmail.com"
] |
me.ouda@gmail.com
|
00ac4b81737f0281e0c5adacdb81c5c65b98b959
|
c96ae11059bef7c62a3e7509708c9807e5b7384a
|
/TriggerEditor/App/TgrApp.h
|
e2f5806c64ab2d1df1cc210397fc4cb4266d19b5
|
[] |
no_license
|
liuchunlin/BehaviourEditor
|
40a195fa3455402a585152431219a4411119357a
|
9ce3217f2bfc5490680e8df414286b95b27382ce
|
refs/heads/master
| 2020-12-25T14:13:16.775271
| 2016-08-25T15:45:49
| 2016-08-25T15:45:49
| 65,906,631
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,027
|
h
|
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers)
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/treectrl.h"
#include "wx/richtext/richtextctrl.h"
#include <map>
#include <string>
using namespace std;
class TgrEditFrame;
class TgrEditApp : public wxApp
{
public:
// override base class virtuals
// ----------------------------
// this one is called on application startup and is a good place for the app
// initialization (doing it here and not in the ctor allows to have an error
// return: if OnInit() returns false, the application terminates)
virtual bool OnInit();
virtual int OnExit();
void CreateStyles();
TgrEditFrame* GetTgrFrame(){ return m_TgrFrame; }
private:
TgrEditFrame *m_TgrFrame;
};
DECLARE_APP(TgrEditApp)
extern wchar_t GConfigFileName[MAX_PATH];
|
[
"408354802@qq.com"
] |
408354802@qq.com
|
399e31c18398e17605436eae24a1dd4d0ac80b43
|
b1c4be5357d95a8bef78dab271189a4161ffbd2c
|
/Summer Practice/SPOJ/Road Network.cpp
|
74efad31fa4b79b24db3fd8a2c13d49775c7dd8f
|
[] |
no_license
|
Shaker2001/Algorithms-Library
|
faa0434ce01ad55d4b335c109f4f85736a6869ed
|
1aa09469ca434f6138547592ce49060d4400e349
|
refs/heads/master
| 2023-03-16T04:41:27.367439
| 2017-11-13T00:41:55
| 2017-11-13T00:41:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,658
|
cpp
|
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 1000000000
int cost [152][152][152];
int N, P, Q;
int cities[152];
void initialize(){
for (int i=0;i<=N;i++)
for (int j=0;j<N;j++)
for (int k=0;k<N;k++)
cost[i][j][k] = INF;
}
void floyd_warshall(){
for (int k=1;k<=P;k++)
for (int i=0;i<N;i++)
for (int j=0;j<N;j++)
cost[k][i][j] = min(cost[k-1][i][j], cost[k-1][i][cities[k]]+cost[k-1][cities[k]][j]);
}
int main(){
int t, c, s, d, k;
scanf("%d", &t);
for (int cases=1;cases<=t;cases++){
scanf("%d", &N);
initialize();
for (int i=0;i<N-1;i++){
for (int j=i+1;j<N;j++){
scanf("%d", &c);
if (c!=-1){
cost[0][i][j] = c;
cost[0][j][i] = c;
}
}
}
scanf("%d", &P);
for (int i=1;i<=P;i++){
scanf("%d", &c);
cities[i] = c-1;
}
floyd_warshall();
scanf("%d", &Q);
printf("Case %d: ", cases);
for (int i=0;i<Q-1;i++){
scanf("%d %d %d", &k, &s, &d);
if (s==d)
printf("0 ");
else if (cost[k][s-1][d-1]!=INF)
printf("%d ", cost[k][s-1][d-1]);
else printf("-1 ");
}
scanf("%d %d %d", &k, &s, &d);
if (s==d)
printf("0\n");
else if (cost[k][s-1][d-1]!=INF)
printf("%d\n", cost[k][s-1][d-1]);
else printf("-1\n");
}
}
|
[
"malatawy15@gmail.com"
] |
malatawy15@gmail.com
|
4822cd31c12705f7c2bda297655d542f3006aeb2
|
e815232be140847ecb5bf088d89a656b593ac1da
|
/UVA/UVA 11933.cpp
|
7d93ed3081739de39a0797c876ca8e90f0bc60d9
|
[] |
no_license
|
nada3ssam/CompetitiveProgramming
|
fc176c98574d68f0f0ef51be7cc8cc7f355dce05
|
718e78b3745884c617b7488d18d92ff1148f962f
|
refs/heads/master
| 2021-01-24T10:08:03.411975
| 2018-04-09T15:26:30
| 2018-04-09T15:26:30
| 123,040,303
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 828
|
cpp
|
#include<iostream>
#include<bitset>
#include<cmath>
#include<algorithm>
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159265
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
typedef long long ll;
typedef long double ld;
using namespace std;
void Fast()
{
std::ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
}
int power(int n)
{
int p=1;
for (int i = 0; i < n; i++)
p*=2;
return p;
}
int main()
{
Fast();
int n;
while (cin>>n && n)
{
int c=0;
bitset<32>a(n),x,y;
for (int i = 0; i < a.size(); i++)
{
if(a[i])
{
c++;
if(c%2==0 && c>0)
y[i]=1;
else if(c%2)
x[i]=1;
}
}
ll X=0,Y=0;
for (int i = 0; i < 32; i++)
if(x[i])
X+=(power(i));
for (int i = 0; i < 32; i++)
if(y[i])
Y+=(power(i));
cout<<X<<" "<<Y<<endl;
}
return 0;
}
|
[
"nada3ssam1@gmail.com"
] |
nada3ssam1@gmail.com
|
576c4337ed60aa2524c9e657e714e8e8333e4c5e
|
d625eb0f2e675d6e40b0849d1e5f20b1aef4c406
|
/codeforce/Codeforce_Rating_Round/Round_105/A. Insomnia cure_test.cpp
|
e79759de365713119b2a93ba59b97c344e8ed7e8
|
[] |
no_license
|
aseem01/Competitive_Programming
|
b5a57c7b10b731ea2b03288c500dd85c8f5fda2c
|
ad7354c56cada964b2c5331f15424d580febe2b6
|
refs/heads/master
| 2021-01-25T11:28:57.402352
| 2018-11-09T06:59:46
| 2018-11-09T06:59:46
| 93,930,174
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,030
|
cpp
|
/****************************************************************************\
Belief yourself,Respect yourself |
|
/\ /--------| |--------| |--------| ---- ---- |
/ \ / | | | \ / | |
/ \ | | | | \ / | |
/ \ |----| |--------| |--------| | \ / | |
/--------\ |------| | | | ----- | |
/ \ | | | | | |
/ \ / | | | | |
---- ---- |----------/ |--------| |--------| ---- ---- |
|
******************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define uniq(x) x.erase(unique(x.begin(),x.end()), x.end()) //Unique value find from vector
#define upper(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Upper value search;
#define lower(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Lower value search;
#define max3(a,b,c) max(max(a,b),c)//maximum value find three value;
#define min3(a,b,c) min(min(a,b),c)//minimum value find three value;
#define rep(i,intial,n) for(int i=intial; i<(n) ; i++)
#define REP(i,intial,n) for(int i=intial; i<=(n) ; i++)
#define PI acos(-1.0)//PI Calculation
#define LL long long
#define MP make_pair
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define MX 1000005
#define MOD 1000000007
//Bit Operation
bool checkBit(LL n, int i) { return n&(1LL<<i); } //AND
LL setBit(LL n, int i) { return n|(1LL<<i);; } //OR
LL resetBit(LL n, int i) { return n&(~(1LL<<i)); } //OFF
template<typename T> T POW(T b,T p) //Pow calculation
{
T r=1;
while(p)
{
if(p&1)r=(r*b);
b=(b*b);
p>>=1;
}
return r;
}
LL big_mod(LL n, LL p)
{
if(p==0) return 1;
if(!(p&1))
{
LL r = big_mod(n,p/2) % MOD;
return ( (r%MOD) * (r%MOD) ) % MOD;
}
else return ( ( n%MOD) * (big_mod(n,p-1) %MOD)) % MOD;
}
long long gcd(long long a, long long b) {
while (b != 0) {
long long t = a % b;
a = b;
b = t;
}
return a;
}
//||--------------------------->||Main_Code_Start_From_Here||<---------------------------------||
int main()
{
//freopen("a.in", "r", stdin);
//freopen("a.out", "w", stdout);
int k,L,m,n,d,ar[100010];
while(cin>>k>>L>>m>>n>>d)
{
for(int i=1;i<=d;i++) ar[i]=0;
for(int i=k;i<=d;i+=k) ar[i]=1;
for(int i=L;i<=d;i+=L) ar[i]=1;
for(int i=m;i<=d;i+=m) ar[i]=1;
for(int i=n;i<=d;i+=n) ar[i]=1;
int bad=0;
for(int i=1;i<=d;i++) if(ar[i]==1) bad++;
cout<<bad<<endl;
}
}
|
[
"aseem.cse.cu@gmail.com"
] |
aseem.cse.cu@gmail.com
|
476971421dbd67321e1f7cf7649c1510e91ced7b
|
5838cf8f133a62df151ed12a5f928a43c11772ed
|
/NT/com/netfx/src/clr/vm/confighelper.cpp
|
ea2212039995a4e38cdfb22d08bae62afde7c5d0
|
[] |
no_license
|
proaholic/Win2K3
|
e5e17b2262f8a2e9590d3fd7a201da19771eb132
|
572f0250d5825e7b80920b6610c22c5b9baaa3aa
|
refs/heads/master
| 2023-07-09T06:15:54.474432
| 2021-08-11T09:09:14
| 2021-08-11T09:09:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,243
|
cpp
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//*****************************************************************************
// ConfigHelper.cpp
//
//*****************************************************************************
//
// XML Helper so that NodeFactory can be implemented in Managed code
//
#include "common.h"
#include "confighelper.h"
ConfigFactory::ConfigFactory(IConfigHandler *pFactory){
m_pManagedFactory = pFactory;
m_pManagedFactory->AddRef(); //AddRef the managed Factory interface
}
ConfigFactory::~ConfigFactory(){
m_pManagedFactory->Release(); //Release the managed Factory interface
}
HRESULT STDMETHODCALLTYPE ConfigFactory::NotifyEvent(
/* [in] */ IXMLNodeSource __RPC_FAR *pSource,
/* [in] */ XML_NODEFACTORY_EVENT iEvt)
{
m_pManagedFactory->NotifyEvent(iEvt);
return S_OK;
}
//---------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE ConfigFactory::BeginChildren(
/* [in] */ IXMLNodeSource __RPC_FAR *pSource,
/* [in] */ XML_NODE_INFO __RPC_FAR *pNodeInfo)
{
m_pManagedFactory->BeginChildren(pNodeInfo->dwSize,
pNodeInfo->dwSubType,
pNodeInfo->dwType,
pNodeInfo->fTerminal,
pNodeInfo->pwcText,
pNodeInfo->ulLen,
pNodeInfo->ulNsPrefixLen);
return S_OK;
}
//---------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE ConfigFactory::EndChildren(
/* [in] */ IXMLNodeSource __RPC_FAR *pSource,
/* [in] */ BOOL fEmptyNode,
/* [in] */ XML_NODE_INFO __RPC_FAR *pNodeInfo)
{
m_pManagedFactory->EndChildren(fEmptyNode,
pNodeInfo->dwSize,
pNodeInfo->dwSubType,
pNodeInfo->dwType,
pNodeInfo->fTerminal,
pNodeInfo->pwcText,
pNodeInfo->ulLen,
pNodeInfo->ulNsPrefixLen);
return S_OK;
}
//---------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE ConfigFactory::CreateNode(
/* [in] */ IXMLNodeSource __RPC_FAR *pSource,
/* [in] */ PVOID pNode,
/* [in] */ USHORT cNumRecs,
/* [in] */ XML_NODE_INFO* __RPC_FAR * __RPC_FAR apNodeInfo)
{
XML_NODE_INFO* pNodeInfo = *apNodeInfo;
DWORD i;
WCHAR wstr[128];
WCHAR *pString = wstr;
DWORD dwString = sizeof(wstr)/sizeof(WCHAR);
for( i = 0; i < cNumRecs; i++) {
if ( apNodeInfo[i]->ulLen >= dwString) {
dwString = apNodeInfo[i]->ulLen+1;
pString = (WCHAR*) alloca(sizeof(WCHAR) * dwString);
}
pString[apNodeInfo[i]->ulLen] = L'\0';
wcsncpy(pString, apNodeInfo[i]->pwcText, apNodeInfo[i]->ulLen);
if(i == 0) {
m_pManagedFactory->CreateNode(apNodeInfo[i]->dwSize,
apNodeInfo[i]->dwSubType,
apNodeInfo[i]->dwType,
apNodeInfo[i]->fTerminal,
pString,
apNodeInfo[i]->ulLen,
apNodeInfo[i]->ulNsPrefixLen);
}
else {
m_pManagedFactory->CreateAttribute(apNodeInfo[i]->dwSize,
apNodeInfo[i]->dwSubType,
apNodeInfo[i]->dwType,
apNodeInfo[i]->fTerminal,
pString,
apNodeInfo[i]->ulLen,
apNodeInfo[i]->ulNsPrefixLen);
} // end of switch
}
return S_OK;
}
//
//Helper routines to call into managed Node Factory
//
HRESULT STDMETHODCALLTYPE ConfigHelper::Run(IConfigHandler *pFactory, LPCWSTR filename)
{
HRESULT hr = S_OK;
IXMLParser *pIXMLParser = NULL;
ConfigFactory *helperfactory = NULL;
IStream *pFile = NULL ;
if (!pFactory){
return E_POINTER;
}
hr = CreateConfigStream(filename, &pFile);
if(FAILED(hr)) goto Exit;
hr = GetXMLObject(&pIXMLParser);
if(FAILED(hr)) goto Exit;
helperfactory = new ConfigFactory(pFactory);
if ( ! helperfactory) {
hr = E_OUTOFMEMORY;
goto Exit;
}
helperfactory->AddRef(); // RefCount = 1
hr = pIXMLParser->SetInput(pFile); // filestream's RefCount=2
if ( ! SUCCEEDED(hr))
goto Exit;
hr = pIXMLParser->SetFactory(helperfactory); // factory's RefCount=2
if ( ! SUCCEEDED(hr))
goto Exit;
hr = pIXMLParser->Run(-1);
Exit:
if (hr==XML_E_MISSINGROOT) //empty file
hr=S_OK;
if (pIXMLParser) {
pIXMLParser->Release();
pIXMLParser= NULL ;
}
if ( helperfactory) {
helperfactory->Release();
helperfactory=NULL;
}
if ( pFile) {
pFile->Release();
pFile=NULL;
}
if (hr==XML_E_MISSINGROOT)
hr=S_OK;
return hr;
}
//
// Entrypoint to return an Helper interface which Managed code can call to build managed Node factory
//
LPVOID __stdcall ConfigNative::GetHelper(EmptyArgs *args)
{
LPVOID rv = NULL;
THROWSCOMPLUSEXCEPTION();
// We are about to use COM functions, we need to start COM up.
if (FAILED(QuickCOMStartup()))
COMPlusThrowOM();
ConfigHelper *pv = new ConfigHelper();
if (pv) {
MethodTable *pMT = g_Mscorlib.GetClass(CLASS__ICONFIG_HELPER);
if(pMT) {
//OBJECTREF ob = GetObjectRefFromComIP(pv, pMT);
OBJECTREF ob = GetObjectRefFromComIP(pv, NULL);
*((OBJECTREF*) &rv) = ob;
}
else
delete pv;
}
return rv;
}
|
[
"blindtiger@foxmail.com"
] |
blindtiger@foxmail.com
|
89f6bb25eec67736f7f560e3f138a3d46fc0827a
|
8bb18defef491b43964e8c577046b81fc253162c
|
/eklavya_roboteq/src/roboteq_encoder_client.cpp
|
afb7c55f6d5b584ab1fd145ea853c9d6c3591c07
|
[
"BSD-3-Clause"
] |
permissive
|
gianma123/eklavya-ros-pkg
|
e5e47cb81e1d4dc168442eb7c648dfc3dbcf2884
|
5fec39e8c9a7b5e270496645b007bd905b7077e1
|
refs/heads/master
| 2020-06-18T11:50:30.761476
| 2013-05-09T20:16:30
| 2013-05-09T20:16:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 654
|
cpp
|
#include "ros/ros.h"
#include "eklavya_roboteq/GetSpeed.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "motor_speed_client");
if (argc != 1)
{
ROS_INFO("usage: motor_speed_client");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<eklavya_roboteq::GetSpeed>("motor_speed");
eklavya_roboteq::GetSpeed srv;
if (client.call(srv))
{
ROS_INFO("Speed response : %ld, %ld", (long int)srv.response.left_speed, (long int)srv.response.right_speed);
}
else
{
ROS_ERROR("Failed to call service get speed");
return 1;
}
return 0;
}
|
[
"37.tanmay@gmail.com"
] |
37.tanmay@gmail.com
|
5198b607d8bd2652a48ca37d4ea05ad88d5759b5
|
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
|
/app/src/main/cpp/dir7941/dir22441/dir22442/dir25702/file25756.cpp
|
cc06e97eadbfeb348fefacf3c2aaa9e6cfa85617
|
[] |
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 file25756
#error "macro file25756 must be defined"
#endif
static const char* file25756String = "file25756";
|
[
"tgeng@google.com"
] |
tgeng@google.com
|
56ce23dce79416f5ab9575c6911f1456ead12c22
|
f0dac252997759f70ac463778aea0d4b58360633
|
/Source/TowerDefence/Private/Core/SelectLevelCore/TowerDefenceSelectLevelGameMode.cpp
|
909c17d1bde6e9bd4d010963b9b8e86d10c4107f
|
[] |
no_license
|
GuoPuS/StudyGame
|
b18ae153a824895702d3906a9cc71b24b1750e90
|
a4c621b8010711e25488279eeb8145ebefe019c2
|
refs/heads/master
| 2023-05-04T21:09:56.604924
| 2021-05-28T10:33:33
| 2021-05-28T10:33:33
| 371,582,899
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 148
|
cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Core/SelectLevelCore/TowerDefenceSelectLevelGameMode.h"
|
[
"gpsvictory@163.com"
] |
gpsvictory@163.com
|
5cc2f14c85555e37f7aaafabaa452e8385323e68
|
b67505f3be706aa8c167cce1577a4582f9c36b1c
|
/syakyo/rensyu.cpp
|
c00cee8b1afd8e7ce0138a0ef7db9abf48d5293a
|
[] |
no_license
|
ElenoMome/atcoder
|
87e0fcb226e02cb04ebd97ab997b4cfa8907ead5
|
ff9a8db543affc4c0750ddf14872bcfc9a081468
|
refs/heads/master
| 2020-04-04T13:49:17.557000
| 2019-01-29T05:44:57
| 2019-01-29T05:44:57
| 155,976,430
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,659
|
cpp
|
//二分木で考える貪欲法
//コストの合計は,各葉の節点の板の長さx節点の深さ
typedef long long ll;
//入力
int N, L[MAX_N];
void solve()
{
ll ans = 0;
while(N > 1)
{
int mil1 = 0; mil2 = 1;
if(L[mil1] > L[mil2]) swap(mil1, mil2);
rep(i=2, N)
{
if(L[i] < L[mil1])
{
mil2 = mil1;
mil1 = i;
}
else if (L[i] < L[mil2])
{
mil2 = i;
}
}
}
}
//美しくない......
//動的計画法
//ナップサック問題
//愚直に各品物を入れるか入れないかで分岐しながら全探索
int n, W;
int w[MAX_N], v[MAX_N];
//i番目以降の品物から重さの総和がj以下となるように選ぶ
int rec(int i, int j)
{
int res;
if (i == n) res = 0; //品物はもう残っていない
else if(j < w[i])
{
res = rec(i + 1, j);
}
else
{
res = max(rec(i+1, j), rec(i + 1, j - w[i]) + v[i]);
}
return res;
}
void solve()
{
cout << rec(0, W);
}
//動的計画法メモリ保存版
int dp[MAX_N+1][MAX_W+1];
int rec(int i, int j)
{
if(dp[i][j] >= 0) return dp[i][j];
int res;
if(i == n) res = 0;
else if(j < w[i])
{
res = rec(i+1, j);
}
else
{
res = max();
}
return dp[i][j] = res;
}
memset(dp, -1, sizeof(dp));
int heap[MAX_N], sz = 0;
void push(int x)
{
int i = sz++;
while(i>0)
{
//親のノード番号
int p = (i-1)/2;
//もう逆転していないなら抜ける
if(heap[p] <= x) break;
}
}
//実際にはSTLにヒープは実装されている
#include <queue>
priority_queue<int> pque;
int L,P,N;
int A[MAX_N+1], B[MAX_N+1];
void solve()
{
A[N] = L;
B[N] = 0;
N++;
priority_queue<int> que;
int ans=0; pos=0; tank=p;
rep(i,N)
{
int d = A[i] - pos;
while(tank - d < 0)
{
if(que.empty())
}
}
}
priority_queue<int, vector<int>, qreater<int>> que;
const int ST_SIZE = (1 << 15) - 1;
int N,C;
int L[MAX_N];
int S[MAX_C], A[MAX_N];
//セグメント木のデータ
double vx[ST_SIZE], vy[ST_SIZE];
double ang[ST_SIZE];
//現在の角度
double prv[MAX_N];
//STを初期化
//kは節点の番号, l,rはその節点がl,r区間に対応することを示す
void init(int k, int l, int r)
{
ang[k] = vx[k] = 0.0;
if(r-l == 1)
{
//11 kjhgfdsaiuytrewq @poiuytrewq 葉
vy[k] = L[l];
}
else
{
//葉ではない節点
int chl = k * 2 + 1, chr = k * 2 + 2;
init(chl, 1, (1+r) / 2);
}
}
void solve()
{
init(0,0,N);
}
LL N, X[1009], Y[1009], H[1009]; vector<tuple<LL,LL,LL>>vec;
int main()
{
cin >> N; tuple<LL,LL,LL>G = make_tuple(-1,-1,-1);
FOR(i, 1, N + 1)
{
cin >> X[i] >> Y[i] >> H[i];
if(H[i] >= 1) G = make_tuple(X[i], Y[i], H[i]);
}
REP(i, 101)
{
REP(j, 101)
{
LL V = get<2>(G) + abs(get<0>(G) - i) + abs()
}
}
}
//入力
vector<int> G[MAX_V]; //グラフ
int V; //頂点数
int color[MAX_V]; //頂点iの色 1 or -1
bool dfs(int v, int c)
{
color[v] = c; //頂点vをcで塗る
FOR(i,0,G[v].size())
{
}
}
int main()
{
int N,M;
cin >> N >> M;
vector<pair<int,int>> cities[100001];
REP(i,M)
{
int p,y;
cin >> p >> y;
cities[p].push_back({y,i})
}
PII ans[100001];
FOR(i,1, N+1)
{
sort(cities[i].begin(), cities[i].end());
}
}
\
|
[
"masaki@easter.kuee.kyoto-u.ac.jp"
] |
masaki@easter.kuee.kyoto-u.ac.jp
|
aac0b6d02cd21223f8fc38f373d3e4a23622ca63
|
08b8cf38e1936e8cec27f84af0d3727321cec9c4
|
/data/crawl/git/hunk_6752.cpp
|
8835f54b96bd665a6916a74f34b1fd0c2b96e6f0
|
[] |
no_license
|
ccdxc/logSurvey
|
eaf28e9c2d6307140b17986d5c05106d1fd8e943
|
6b80226e1667c1e0760ab39160893ee19b0e9fb1
|
refs/heads/master
| 2022-01-07T21:31:55.446839
| 2018-04-21T14:12:43
| 2018-04-21T14:12:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 246
|
cpp
|
if (action == REVERT && !no_replay)
die("revert is incompatible with replay");
+ if (read_cache() < 0)
+ die("git %s: failed to read the index", me);
if (no_commit) {
/*
* We do not intend to commit immediately. We just want to
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
d9ee5b933f30de799334e082bdf43bc11056bf0d
|
e9e0f1e544704741ce32188fc31dbc3200899390
|
/src/Brain.cpp
|
329e3b4d44b666bc02dc2588a0cdae9ac7430e60
|
[] |
no_license
|
JacobGunnell/64w-ai-2021-official
|
691c0592f73cdbbc70ca71ac1e3f10ac15e78bda
|
fae3354e29f181bb352e4e7931bda1569b79f90c
|
refs/heads/master
| 2022-12-07T16:33:36.017889
| 2020-08-27T04:19:49
| 2020-08-27T04:19:49
| 262,132,113
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 986
|
cpp
|
#include "Brain.h"
// everything below this line is ugly, but it was the only way
// add an include for every derived class of Brain...
#include "SMP.h"
#include "SP.h"
Brain *_brain_breed(Brain *mother, Brain *father)
{
if(mother != NULL && father != NULL)
{
// TODO
}
return NULL;
}
#define _BRAIN_DYNAMIC_LOAD(c, s, e) \
if(e == c::getExtension()) \
{ \
Brain *b = new c; \
if(b->load(s)) \
return b; \
else \
delete b; \
}
Brain *_brain_dynamic_load(string file)
{
string ext = file.substr(file.find_last_of('.'));
_BRAIN_DYNAMIC_LOAD(SMP, file, ext) // ...add one of these macros for every derived class of Brain...
_BRAIN_DYNAMIC_LOAD(SP, file, ext)
return NULL;
}
Brain *_brain_random(int inputSize)
{
static const int NUM_DERIVED = 2; // ...increment this...
switch(rand() % NUM_DERIVED) // ...and add a new case
{
case 0:
return new SMP(inputSize);
case 1:
return new SP(inputSize);
default:
return NULL;
}
}
|
[
"jacob.gunnell@cox.net"
] |
jacob.gunnell@cox.net
|
83f7dd67f6c0029a42355b809eb69442d212a744
|
4898bafde2c3658dfecde5d457c853cc0f574c89
|
/cq.cpp
|
7d1222a06c4f56eedd62e5a73b5f19ae07d7676a
|
[] |
no_license
|
sanjaykatta95/practiceCode
|
084bd5dad6199c2dd431e386cfdfe8ceb9f27c41
|
448baf3615db4f8ac1ca4200753617abd136eb8b
|
refs/heads/master
| 2020-04-07T04:34:04.941928
| 2018-11-18T08:17:38
| 2018-11-18T08:17:38
| 158,062,321
| 0
| 1
| null | 2018-11-20T17:17:31
| 2018-11-18T08:06:17
|
C++
|
UTF-8
|
C++
| false
| false
| 1,211
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define long long int ll
class circularQueue
{
int front,rear,size,*a;
public:
circularQueue(int size)
{
a=new int[size];
front=-1;
rear=-1;
this->size=size;
}
bool isEmpty()
{
if(front==-1)
return true;
}
bool isFull()
{
if(front==(rear+1)%size)
return true;
return false;
}
void enq(int data)
{
if(isFull())
{
cout<<"queue is full"<<endl;
}
if(front==-1)
front=0;
rear = (rear+1)%size;
a[rear]=data;
}
int deq()
{
if(isEmpty())
{
cout<<"queue is empty"<<endl;
return -1;
}
int item=a[front];
if(front==rear)
{
front=rear=-1;
}
else
front=(front+1)%size;
return item;
}
void display()
{
for(int i=front;i!=rear;i=(i+1)%size)
cout<<a[i]<<" ";
}
int Size()
{
if(rear>front)
return rear-front+1;
else return (size-(front-rear+1));
}
};
int main()
{
ios_base::sync_with_stdio(false);
circularQueue cq(3);
cq.enq(10);
cq.enq(100);
cq.enq(1000);
cout << endl << "Size of queue: " << cq.Size();
cout << endl << "Removed element: " << cq.deq();
cq.display();
return 0;
}
|
[
"sanjay18495@gmail.com"
] |
sanjay18495@gmail.com
|
a8ecd45c912e8a263709b61b7b1b0e9f329efa27
|
aa29ea6821c41fe9834f125fa0dcd1fef30d3ae3
|
/PRETNUM.cpp
|
566891d3886c4336381a47f141fbfe1734156ff6
|
[] |
no_license
|
pushpendragold/CODECHEF
|
82de606ca89bb842168e3b211c310a90c7c0a27a
|
c0cd8b24e40905d53bb2309606cb62ffda8de7ba
|
refs/heads/master
| 2021-01-10T04:45:04.457758
| 2015-10-11T20:19:20
| 2015-10-11T20:19:20
| 44,067,881
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,088
|
cpp
|
/*
Chef doesn't love math anymore. He loves Sasha. Sashen'ka is cute.
Chef goes on a date with her. Flowers are boring, while numbers are not. He knows that most of all this girl loves numbers, that's why he is going to bring
ribbon with numbers L, L+1, L+2, ..., R written on it. Sasha thinks that numbers with prime number of divisors are special. That's why she is going to kiss
boy for each such number he will bring.Now Chef wonder how many times he will be kissed by Sashen'ka ?
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two number L, R.
Output
For each test case, output a single line containing answer for corresponding test case.
Constraints
1 <= T <= 5
1 <= L <= R <= 10^12
0 <= R-L <= 10^6
Example
Input:
1
1 10
Output:
6
Explanation
Example case 1. Numbers 2,3,4,5,7,9 are special.
*/
#include<stdio.h>
#include<math.h>
char a[1000004];
int b[80000],c[15];
void sieve()
{
long long i,j,y,p=1;
b[0]=2;
for(i=1;i<500000;i++)
{
if(a[i]==0)
{
j=2*i+1;
b[p++]=j;
y=i*(j+1);
while(y<500000)
{
a[y]=1;
y+=j;
}
}
}
b[p]=10000000; //last value of p=78497
for(i=0;i<15;i++)
c[i]=b[i]-1;
}
main()
{
sieve();
long long t,m,n,z,l,i,j,k,ans,M,N;
scanf("%lld",&t);
while(t--)
{
scanf("%lld %lld",&m,&n);
if(m==1)
m=2;
l=n-m;
for(z=0;z<l+2;z++)
a[z]=0;
i=0; //prime finder
j=sqrt(n);
while(b[i]<=j)
{
k=((m-1)/b[i]+1);
if(k<2)
k=2;
k=k*b[i]-m;
while(k<=l)
{
a[k]++;
k+=b[i];
}
i++;
}
ans=0;
for(i=0;i<=l;i++)
if(a[i]==0)
ans++;
m--;
for(i=1;i<15;i++)
{
double X1,X2,Y1,Y2;
long long Z1,Z2,I,J;
X1=log10(m)/(c[i]*1.0);
Y1=pow(10,X1);
Z1=(long long)Y1;
X2=log10(n)/(c[i]*1.0);
Y2=pow(10,X2);
Z2=(long long)Y2;
if(Z2==1)
break;
I=0;
while(b[I]<=Z1)
I++;
J=I;
while(b[I]<=Z2)
I++;
ans+=I-J;
}
printf("%lld\n",ans);
}
return 0;
}
|
[
"pushpendragold@bitbucket.org"
] |
pushpendragold@bitbucket.org
|
4518481b3929d89f980f3f7af343f7b60605890c
|
c80cd2d263cffae4981e8a92366ce3dabeec4c75
|
/exercises/7/7_11.cpp
|
6fe08db21f2d16e710d5356f1337eabf461d8d4d
|
[] |
no_license
|
cat1984x/Learning_Cpp_Primer
|
72398a00f4f24c242b9d3bb22b6426391d17c773
|
fb5f1aa3f5a157d19c64e6ab260cd68db571f90a
|
refs/heads/master
| 2022-01-05T12:41:55.587426
| 2018-07-23T03:57:59
| 2018-07-23T03:57:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 368
|
cpp
|
#include <iostream>
#include "7_11_Sales_data.h"
#include <string>
using namespace std;
int main()
{
Sales_data a;
cout << "a: ";
print(cout, a) << endl;
Sales_data b("b");
cout << "b: ";
print(cout, b) << endl;
Sales_data c("c", 2, 20.0);
cout << "c: ";
print(cout, c) << endl;
Sales_data d(cin);
cout << "d: ";
print(cout, d) << endl;
return 0;
}
|
[
"chenyushen1989@163.com"
] |
chenyushen1989@163.com
|
a2f38a6b5095cfb0c4b747af7c5a6039569b89dc
|
cf0063c6c0634cd451bc4d0df9ff429b802f8867
|
/projet_micropro_system_de_verrouillage_de_porte/projet_micropro_system_de_verrouillage_de_porte.ino
|
49e6f14d4a067eee6b2c3ca336b370a92088a581
|
[] |
no_license
|
aghilasakkal/Microprocesseur
|
4d32e7177807be905682ae6a06037e3a1a35a2a6
|
bd5dfc938369c2c69150783b0de91921cc89ab47
|
refs/heads/master
| 2022-06-19T08:31:53.526174
| 2020-05-09T23:17:05
| 2020-05-09T23:17:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,604
|
ino
|
/*
Projet Microprocesseurs : System de verrouillage de porte
AKKAL Aghilas 19009504
lien Tinkercad :
https://www.tinkercad.com/things/2LGuvAvqNk2-system-de-verrouillage-de-porte
NB : J'aurais pu utiliser EEPROMWrite() et EEPROMRead() pour sauvgarder le code octet par octet dans
la mémoire EEPROM de l'arduino et donc éviter de perdre le code à chaque fois qu'on redémarre,
mais vu que c'est juste un simulateur, je ne sais pas si c'est utile d'implanter ça vu que la mémoire
EEPROM est maintenant hardware, et donc unique à chaque carte arduino, mais ça reste faisable.
*/
/*************************************** LES DECLARATIONS ******************************************/
#include <LiquidCrystal.h>
#include <Keypad.h> // librairie du keypad à télécharger et installer manuellement
#include <Servo.h>
#define buzzer 8 // pin du buzzer
int screenOffMsg =0; // variable d'état de l'écran d'acceuil
String password="1234"; // code actuel
String tempPassword; // variable pour sauvgarder code temporaire de saisie
boolean activated = false; // variable d'état "en cours d'écriture"
boolean passChangeMode = false; // variable d'état "changement du code"
boolean passChanged = false; // variable d'état "code changé"
Servo myservo; // déclaration de notre servo moteur
const byte ROWS = 4; //
const byte COLS = 4; //
char keypressed; //
char keyMap[ROWS][COLS] = { // définition
{'1','2','3','A'}, // des lignes
{'4','5','6','B'}, // et colonnes
{'7','8','9','C'}, // à utiliser
{'*','0','#','D'}}; // par le keypad
byte rowPins[ROWS] = {7, 6, 5, 4}; //
byte colPins[COLS] = {3, 2, 1, 0}; //
Keypad myKeypad = Keypad( makeKeymap(keyMap), rowPins, colPins, ROWS, COLS); //
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5); // définition des pins du LCD
/**************************************** LE SETUP *************************************************/
void setup() {
lcd.begin(16,2); // définition de la matrice du LCD
myservo.attach(9); // pin du servo moteur
pinMode(buzzer, OUTPUT); // buzzer en output
}
/***************************************** LE LOOP *************************************************/
void loop() {
if (screenOffMsg == 0 ){ // afficher le message d'acceuil
lcd.clear();
lcd.setCursor(0,0);
lcd.print("A - OUVRIR PORTE");
lcd.setCursor(0,1);
lcd.print("B - CHANGER CODE");
screenOffMsg = 1;
}
keypressed = myKeypad.getKey();
if (keypressed =='A'){ // si on appuie sur A, on ouvre la porte
tone(buzzer, 750, 25);
enterPassword();
}
else if (keypressed =='B') { // si on appuie sur B, on change le code
tone(buzzer, 750, 25);
changePassword();
}
}
/************************************* LES FONCTIONS ***********************************************/
void openServo() { // fonction qui ouvre la porte
int pos;
for (pos=90; pos<=180; pos+=5){ //une boucle for, ou on spécifie les degrés, et le pas en degré
myservo.write(pos);
delay(15);
}
}
void closeServo() { // fonction qui ferme la porte
int pos;
for (pos=180; pos>=90; pos-=5){
myservo.write(pos);
delay(15);
}
}
void enterPassword() { // fonction qui recupere le code
int i, k=7;
tempPassword = "";
activated = true; // statut changé en "ntrain d'écrire
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" VEUILLEZ ENTRER LE CODE| * POUR VALIDER | # POUR EFFACER");
for (i=0; i<66; i++){
lcd.scrollDisplayLeft(); // faire défiler le text vers la gauche, patienter pour pouvoir
delay(70); //ecrire le code ensuite
}
lcd.clear();
lcd.setCursor(0,0);
lcd.print("* ENTREZ CODE *");
lcd.setCursor(0,1);
lcd.print("CODE : ");
while(activated) {
keypressed = myKeypad.getKey();
if (keypressed != NO_KEY){
if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
keypressed == '8' || keypressed == '9' ) { // on s'assure que juste les chiffres sont reconnus
tone(buzzer, 250, 25);
tempPassword += keypressed;
lcd.setCursor(k,1);
lcd.print("*");
k++;
}
}
if (k > 11 || keypressed == '#') { // si on dépasse 4 chiffres, ou appuie sur #, effacer
tone(buzzer, 35, 25);
tempPassword = "";
k=7;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("* ENTREZ CODE *");
lcd.setCursor(0,1);
lcd.print("CODE : ");
}
if (keypressed == '*') { // * permet de valider
if (tempPassword == password ) { // on vérifie que le code est juste
activated = false;
tone(buzzer, 2000, 1000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" ** BIENVENUE ** ");
delay(1000);
openServo();
delay(2000);
for (i=3; i>0; i--){ // i définit le délais avant la fermeture
tone(buzzer, 4000, 250);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" FERMETURE DANS ");
lcd.setCursor(7,1);
lcd.print(i);
delay(1000);
}
tone(buzzer, 40, 1000);
closeServo();
screenOffMsg = 0;
}
else if (tempPassword != password) {
tone(buzzer, 4000, 1000);
lcd.setCursor(0,1);
lcd.print("CODE INCORRECT !");
delay(1000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("* ENTREZ CODE *");
lcd.setCursor(0,1);
lcd.print("CODE : ");
}
}
}
}
void changePassword() { // fonction qui permet de changer le code
int i;
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" VEUILLEZ ENTRER LE CODE| * POUR VALIDER | # POUR EFFACER");
for (i=0; i<66; i++){
lcd.scrollDisplayLeft();
delay(70);
}
i=3;
tempPassword = "";
lcd.clear();
lcd.setCursor(0,0);
lcd.print("CODE ACTUEL :");
lcd.setCursor(0,1);
lcd.print(" > ");
passChangeMode = true; // on est dans le mode "changer le code"
passChanged = false; // code pas encore changé
while(!passChanged) { // on reste dans la boucle tant que le code n'est pas changé
keypressed = myKeypad.getKey();
if (keypressed != NO_KEY){
if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
keypressed == '8' || keypressed == '9' ) {
tone(buzzer, 250, 25);
tempPassword += keypressed;
lcd.setCursor(i,1);
lcd.print("*");
i++;
}
}
if (i > 7 || keypressed == '#') {
tempPassword = "";
i=3;
tone(buzzer, 35, 25);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("CODE ACTUEL :");
lcd.setCursor(0,1);
lcd.print(" > ");
}
if (keypressed == '*') {
tone(buzzer, 500, 25);
if (password != tempPassword) {
tempPassword = "";
i=3;
tone(buzzer, 4000, 1000);
lcd.setCursor(0,1);
lcd.print("CODE INCORRECT !");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("CODE ACTUEL :");
lcd.setCursor(0,1);
lcd.print(" > ");
}
if (password == tempPassword) {
tempPassword="";
i=3;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("NOUVEAU CODE :");
lcd.setCursor(0,1);
lcd.print(" > ");
while(passChangeMode) {// on reste dans la boucle tant tant qu'on le nouveau code n'est pas enregistré
keypressed = myKeypad.getKey();
if (keypressed != NO_KEY){
if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
keypressed == '8' || keypressed == '9' ) {
tone(buzzer, 250, 25);
tempPassword += keypressed;
lcd.setCursor(i,1);
lcd.print("*");
i++;
}
}
if (i > 7 || keypressed == '#') {
tone(buzzer, 35, 25);
tempPassword = "";
i=3;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("NOUVEAU CODE :");
lcd.setCursor(0,1);
lcd.print(" > ");
}
if ( keypressed == '*') {
tone(buzzer, 500, 25);
password = tempPassword;
tone(buzzer, 2000, 1000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" CODE CHANGE !");
delay(2000);
passChanged = true; // code changé
passChangeMode = false; // on sort de mode "changer code"
screenOffMsg = 0;
}
}
}
}
}
}
|
[
"noreply@github.com"
] |
aghilasakkal.noreply@github.com
|
f80a71801ba51a6c35dee1c9db104b003a8a66b5
|
14d07c63cee076aaa4814544f39aa9629d0dd9ac
|
/d3d.h
|
0c350d07a4eca73f3010698cf4d4fc9e24b5981b
|
[] |
no_license
|
TempAccountNull/endscene-hook
|
40e66b215b9f86eed76d57d67b3fc48af1902268
|
7256644f77daf8460e314695bb52f5fb5d30c497
|
refs/heads/master
| 2022-10-06T10:05:18.329095
| 2020-06-07T12:39:53
| 2020-06-07T12:39:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 493
|
h
|
#ifndef D3D_H
#define D3D_H
#include "d3d9.h"
#include <stdexcept>
class d3dHelper {
public:
d3dHelper();
bool getD3D9Device();
// The vTable entries of the D3D9 dummy device
char* d3d9DeviceTable[119];
static void drawRectangle(int x, int y, int h, int w, D3DCOLOR color);
static void APIENTRY endSceneHook(LPDIRECT3DDEVICE9 pDevice);
// Helpers
private:
static BOOL CALLBACK enumGetProcessWindow(HWND _hwnd, LPARAM lParam);
};
#endif
|
[
"ps1337@mailbox.org"
] |
ps1337@mailbox.org
|
df6dfd35e07441c515f29d426bbdc9cd346e0157
|
0185b0451c89d8758af022f2e15225317dba85c8
|
/CPP_module_03/ex02/ClapTrap.cpp
|
61087a4dfd930890c9b34d3819ee45a8d95d325c
|
[] |
no_license
|
atomatoe/CPP_modules
|
8c6acb03193f7ae39d732f44bd08a38678f6be7d
|
b0ca9d84a8fe4404caa1cc2e6f886abc151bb765
|
refs/heads/master
| 2023-03-24T05:47:03.209605
| 2021-03-16T20:21:22
| 2021-03-16T20:21:22
| 320,817,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,078
|
cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atomatoe <atomatoe@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/04 17:58:44 by atomatoe #+# #+# */
/* Updated: 2020/12/07 18:42:29 by atomatoe ### ########.fr */
/* */
/* ************************************************************************** */
#include "ClapTrap.hpp"
ClapTrap::ClapTrap(std::string value)
{
this->name = value;
this->hit_point = 100;
this->max_hit_point = 100;
this->energy_point = 100;
this->max_energy_point = 100;
this->level = 1;
this->melee_attack = 30;
this->ranged_attack = 20;
this->armor_reduction = 5;
std::cout << this->name << " created! (ClapTrap) (FATHER)" << std::endl;
}
ClapTrap & ClapTrap::operator=(const ClapTrap &type)
{
this->name = type.name;
this->hit_point = type.hit_point;
this->max_hit_point = type.max_hit_point;
this->energy_point = type.energy_point;
this->max_energy_point = type.max_energy_point;
this->melee_attack = type.melee_attack;
this->ranged_attack = type.ranged_attack;
this->armor_reduction = type.armor_reduction;
return(*this);
}
ClapTrap::ClapTrap(const ClapTrap &type)
{
*this = type;
}
void ClapTrap::rangedAttack(std::string const & target)
{
if(this->energy_point >= 20)
{
std::cout << "FR4G-TP " << this->name << " attacks " << target << " at range, causing " << this->ranged_attack - this->armor_reduction << " points of damage!" << std::endl;
this->energy_point = this->energy_point - 20;
}
else
{
std::cout << "Not enough energy to attack." << "Current energy: " << this->energy_point << std::endl;
this->beRepaired(20);
}
}
void ClapTrap::meleeAttack(std::string const & target)
{
if(this->energy_point >= 10)
{
std::cout << "FR4G-TP " << this->name << " attacks " << target << " at melee, causing " << this->melee_attack - this->armor_reduction << " points of damage!" << std::endl;
this->energy_point = this->energy_point - 10;
}
else
{
std::cout << "Not enough energy to attack." << "Current energy: " << this->energy_point << std::endl;
this->beRepaired(10);
}
}
void ClapTrap::takeDamage(unsigned int amount)
{
if(this->hit_point > amount)
{
std::cout << this->name << " takes " << amount << " damage!" << std::endl;
this->hit_point = this->hit_point - amount;
}
else
{
std::cout << this->name << " dodges attack!" << std::endl;
this->beRepaired(amount);
}
}
void ClapTrap::beRepaired(unsigned int amount)
{
if((this->hit_point + amount) < this->max_hit_point)
{
std::cout << this->name << " restored " << amount << " hit point's!" << std::endl;
this->hit_point = this->hit_point + amount;
}
else
std::cout << this->name << " has a lot of health" << std::endl;
if((this->energy_point + amount) < this->max_energy_point)
{
std::cout << this->name << " restored " << amount << " energy!" << std::endl;
this->energy_point = this->energy_point + amount;
}
else
std::cout << this->name << " has a lot of energy!" << std::endl;
}
ClapTrap::~ClapTrap()
{
std::cout << this->get_name() << " deleted! (ClapTrap) (FATHER)" << std::endl;
}
std::string ClapTrap::get_name()
{
return(name);
}
int ClapTrap::get_energy()
{
return(energy_point);
}
void ClapTrap::set_energy(int value)
{
energy_point = value;
}
|
[
"atomatoe@si-g3.kzn.21-school.ru"
] |
atomatoe@si-g3.kzn.21-school.ru
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.