blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
โŒ€
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
โŒ€
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
0d96e93bddf4c49516b3fc854069e49dd5e5faac
20ec1ffcb2cf45459b6abc81492331014f503878
/tool/packtool/conver/cpps/activity_oddsConfig.pb.h
231134e6c1b89fc9789514798d710c3765e5b745
[]
no_license
love19862003/fly-server
e5dd5bc57ecc9dc7c9f557989d8cfbc1f5ced7c3
02413ef5bb8ced32b7820028817e740272e667ce
refs/heads/master
2021-01-10T08:17:09.052383
2017-01-16T09:35:23
2017-01-16T09:35:23
45,825,761
2
1
null
null
null
null
UTF-8
C++
false
true
11,014
h
activity_oddsConfig.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: activity_oddsConfig.proto #ifndef PROTOBUF_activity_5foddsConfig_2eproto__INCLUDED #define PROTOBUF_activity_5foddsConfig_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> #include "ConfigTypeGroup.pb.h" // @@protoc_insertion_point(includes) namespace DianShiTech { namespace Config { // Internal implementation detail -- do not call these. void protobuf_AddDesc_activity_5foddsConfig_2eproto(); void protobuf_AssignDesc_activity_5foddsConfig_2eproto(); void protobuf_ShutdownFile_activity_5foddsConfig_2eproto(); class activity_oddsConfig; // =================================================================== class activity_oddsConfig : public ::google::protobuf::Message { public: activity_oddsConfig(); virtual ~activity_oddsConfig(); activity_oddsConfig(const activity_oddsConfig& from); inline activity_oddsConfig& operator=(const activity_oddsConfig& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const activity_oddsConfig& default_instance(); void Swap(activity_oddsConfig* other); // implements Message ---------------------------------------------- activity_oddsConfig* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const activity_oddsConfig& from); void MergeFrom(const activity_oddsConfig& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional int32 currency_type_originalprice = 4; inline bool has_currency_type_originalprice() const; inline void clear_currency_type_originalprice(); static const int kCurrencyTypeOriginalpriceFieldNumber = 4; inline ::google::protobuf::int32 currency_type_originalprice() const; inline void set_currency_type_originalprice(::google::protobuf::int32 value); // optional int32 cost_originalprice = 5; inline bool has_cost_originalprice() const; inline void clear_cost_originalprice(); static const int kCostOriginalpriceFieldNumber = 5; inline ::google::protobuf::int32 cost_originalprice() const; inline void set_cost_originalprice(::google::protobuf::int32 value); // optional int32 currency_type = 2; inline bool has_currency_type() const; inline void clear_currency_type(); static const int kCurrencyTypeFieldNumber = 2; inline ::google::protobuf::int32 currency_type() const; inline void set_currency_type(::google::protobuf::int32 value); // optional int32 cost = 3; inline bool has_cost() const; inline void clear_cost(); static const int kCostFieldNumber = 3; inline ::google::protobuf::int32 cost() const; inline void set_cost(::google::protobuf::int32 value); // optional int32 id = 1; inline bool has_id() const; inline void clear_id(); static const int kIdFieldNumber = 1; inline ::google::protobuf::int32 id() const; inline void set_id(::google::protobuf::int32 value); // repeated int32 bonus = 6; inline int bonus_size() const; inline void clear_bonus(); static const int kBonusFieldNumber = 6; inline ::google::protobuf::int32 bonus(int index) const; inline void set_bonus(int index, ::google::protobuf::int32 value); inline void add_bonus(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& bonus() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_bonus(); // @@protoc_insertion_point(class_scope:DianShiTech.Config.activity_oddsConfig) private: inline void set_has_currency_type_originalprice(); inline void clear_has_currency_type_originalprice(); inline void set_has_cost_originalprice(); inline void clear_has_cost_originalprice(); inline void set_has_currency_type(); inline void clear_has_currency_type(); inline void set_has_cost(); inline void clear_has_cost(); inline void set_has_id(); inline void clear_has_id(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::int32 currency_type_originalprice_; ::google::protobuf::int32 cost_originalprice_; ::google::protobuf::int32 currency_type_; ::google::protobuf::int32 cost_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > bonus_; ::google::protobuf::int32 id_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(6 + 31) / 32]; friend void protobuf_AddDesc_activity_5foddsConfig_2eproto(); friend void protobuf_AssignDesc_activity_5foddsConfig_2eproto(); friend void protobuf_ShutdownFile_activity_5foddsConfig_2eproto(); void InitAsDefaultInstance(); static activity_oddsConfig* default_instance_; }; // =================================================================== // =================================================================== // activity_oddsConfig // optional int32 currency_type_originalprice = 4; inline bool activity_oddsConfig::has_currency_type_originalprice() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void activity_oddsConfig::set_has_currency_type_originalprice() { _has_bits_[0] |= 0x00000001u; } inline void activity_oddsConfig::clear_has_currency_type_originalprice() { _has_bits_[0] &= ~0x00000001u; } inline void activity_oddsConfig::clear_currency_type_originalprice() { currency_type_originalprice_ = 0; clear_has_currency_type_originalprice(); } inline ::google::protobuf::int32 activity_oddsConfig::currency_type_originalprice() const { return currency_type_originalprice_; } inline void activity_oddsConfig::set_currency_type_originalprice(::google::protobuf::int32 value) { set_has_currency_type_originalprice(); currency_type_originalprice_ = value; } // optional int32 cost_originalprice = 5; inline bool activity_oddsConfig::has_cost_originalprice() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void activity_oddsConfig::set_has_cost_originalprice() { _has_bits_[0] |= 0x00000002u; } inline void activity_oddsConfig::clear_has_cost_originalprice() { _has_bits_[0] &= ~0x00000002u; } inline void activity_oddsConfig::clear_cost_originalprice() { cost_originalprice_ = 0; clear_has_cost_originalprice(); } inline ::google::protobuf::int32 activity_oddsConfig::cost_originalprice() const { return cost_originalprice_; } inline void activity_oddsConfig::set_cost_originalprice(::google::protobuf::int32 value) { set_has_cost_originalprice(); cost_originalprice_ = value; } // optional int32 currency_type = 2; inline bool activity_oddsConfig::has_currency_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void activity_oddsConfig::set_has_currency_type() { _has_bits_[0] |= 0x00000004u; } inline void activity_oddsConfig::clear_has_currency_type() { _has_bits_[0] &= ~0x00000004u; } inline void activity_oddsConfig::clear_currency_type() { currency_type_ = 0; clear_has_currency_type(); } inline ::google::protobuf::int32 activity_oddsConfig::currency_type() const { return currency_type_; } inline void activity_oddsConfig::set_currency_type(::google::protobuf::int32 value) { set_has_currency_type(); currency_type_ = value; } // optional int32 cost = 3; inline bool activity_oddsConfig::has_cost() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void activity_oddsConfig::set_has_cost() { _has_bits_[0] |= 0x00000008u; } inline void activity_oddsConfig::clear_has_cost() { _has_bits_[0] &= ~0x00000008u; } inline void activity_oddsConfig::clear_cost() { cost_ = 0; clear_has_cost(); } inline ::google::protobuf::int32 activity_oddsConfig::cost() const { return cost_; } inline void activity_oddsConfig::set_cost(::google::protobuf::int32 value) { set_has_cost(); cost_ = value; } // optional int32 id = 1; inline bool activity_oddsConfig::has_id() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void activity_oddsConfig::set_has_id() { _has_bits_[0] |= 0x00000010u; } inline void activity_oddsConfig::clear_has_id() { _has_bits_[0] &= ~0x00000010u; } inline void activity_oddsConfig::clear_id() { id_ = 0; clear_has_id(); } inline ::google::protobuf::int32 activity_oddsConfig::id() const { return id_; } inline void activity_oddsConfig::set_id(::google::protobuf::int32 value) { set_has_id(); id_ = value; } // repeated int32 bonus = 6; inline int activity_oddsConfig::bonus_size() const { return bonus_.size(); } inline void activity_oddsConfig::clear_bonus() { bonus_.Clear(); } inline ::google::protobuf::int32 activity_oddsConfig::bonus(int index) const { return bonus_.Get(index); } inline void activity_oddsConfig::set_bonus(int index, ::google::protobuf::int32 value) { bonus_.Set(index, value); } inline void activity_oddsConfig::add_bonus(::google::protobuf::int32 value) { bonus_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& activity_oddsConfig::bonus() const { return bonus_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* activity_oddsConfig::mutable_bonus() { return &bonus_; } // @@protoc_insertion_point(namespace_scope) } // namespace Config } // namespace DianShiTech #ifndef SWIG namespace google { namespace protobuf { } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_activity_5foddsConfig_2eproto__INCLUDED
0f59e7854bac089668fd2f03cd33cd3d3459f1d7
a3e1a101673c56e4ced1b5600612b25b145eb472
/beakjoon_algorithm/beakjoon_algorithm/programmers/Level1-์„œ์šธ์—์„œ๊น€์„œ๋ฐฉ์ฐพ๊ธฐ.cpp
0aa08f937771ee960f0022c7eb62e0ef61b252f1
[]
no_license
gwanhyeon/algorithm_study
a95f3f2d559899f734b52d2d6e89d5f0125cebdf
f01af94919946e5adbdd7cb688cc2c1cf54cbbdc
refs/heads/master
2022-01-07T21:34:56.297147
2021-12-29T16:02:02
2021-12-29T16:02:02
162,471,977
0
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
Level1-์„œ์šธ์—์„œ๊น€์„œ๋ฐฉ์ฐพ๊ธฐ.cpp
// // Level1-แ„‰แ…ฅแ„‹แ…ฎแ†ฏแ„‹แ…ฆแ„‰แ…ฅแ„€แ…ตแ†ทแ„‰แ…ฅแ„‡แ…กแ†ผแ„Žแ…กแ†ฝแ„€แ…ต.cpp // beakjoon_algorithm // // Created by kgh on 05/08/2019. // Copyright ยฉ 2019 kgh. All rights reserved. // #include <stdio.h> #include <iostream> #include <string> #include <vector> using namespace std; int main(void){ string str[1001] = {"Jane","kim"}; int size = sizeof(str)/sizeof(str[0]); string answer = ""; vector<string> seoul; seoul.push_back("Jane"); seoul.push_back("kim"); for(int i=0; i<seoul.size(); i++){ if(seoul[i] == "kim"){ string str = to_string(i); answer += "๊น€์„œ๋ฐฉ์€" + to_string(i) + "์— ์žˆ๋‹ค"; } } cout << answer; return 0; } #include <string> #include <vector> using namespace std; string solution(vector<string> seoul) { string answer = ""; answer += "๊น€์„œ๋ฐฉ์€"; for(int i=0; i<seoul.size(); i++){ if(seoul[i] == "Kim"){ answer += to_string(i); } } answer += "์— ์žˆ๋‹ค"; return answer; }
01a257efb7af60bea8d6424528c5c510bdc76a54
b68b9e285b81bc82589f450b371435a27a4db32d
/btrees/btree-base.h
317d548b4decc6b90a0bee9a024189262a96b5c3
[]
no_license
mark-i-m/hot-spots
6cc1b77378a2f0a73232024ed27dc1a3c2ab6686
842d1f76df63e640d582626b9dbebb606353c812
refs/heads/master
2023-01-13T21:40:19.599529
2018-12-18T01:35:18
2018-12-18T01:35:18
153,299,464
1
0
null
null
null
null
UTF-8
C++
false
false
1,263
h
btree-base.h
#ifndef _BTREE_BTREE_BASE_H #define _BTREE_BTREE_BASE_H #include <stdint.h> namespace common { /* * A base class for thread-safe btree maps. * * All implementations should satisfy this interface. This helps with testing * and benchmarking. */ template <class Key, class Value> struct BTreeBase { // Insert the (k, v) pair into the tree. virtual void insert(Key k, Value v) = 0; // Lookup key `k` in the btree. If `k` is in the btree, set `result` to the // value associated with `k` and return true. If `k` is not in the btree, // return false. virtual bool lookup(Key k, Value &result) = 0; // Do a range query on the btree. Starting with the least key greater than // or equal to `k`, scan at most `range` values into the buffer pointed to // by `output`. Return the number of elements read. Note that we may read // fewer than `range` elements even if there are more elements that we // could scan. The caller should keep calling `scan` until no records are // read. virtual uint64_t scan(Key k, int range, Value *output) = 0; // For convenience: insert from pair. template <class Pair> void insert(Pair p) { insert(p.first, p.second); } }; } // namespace common #endif
947dcaa88d4c98c48141e67f3c38efbdd0548f73
b3d06ec7ded7561b46c31b0d1576896c73552a64
/app/src/main/cpp/media_decoder.cpp
3ed49af860aec5e5bbed081b2709ebd43d7fe884
[]
no_license
ChyengJason/SPlayer
d7021726eacb6734192d7cb7c77abaf379f04e6e
d70e9b152e816cfc36bf519af5e447c16543195f
refs/heads/master
2020-04-01T01:48:48.048827
2018-11-12T14:18:28
2018-11-12T14:18:28
152,753,449
3
0
null
null
null
null
UTF-8
C++
false
false
16,716
cpp
media_decoder.cpp
// // Created by chengjunsen on 2018/10/12. // #include "media_decoder.h" MediaDecoder::MediaDecoder() { mformatContext = NULL; mVideoCodecContext = NULL; mAudioCodecContext = NULL; mVideoCodec = NULL; mAudioCodec = NULL; mVideoFrame = NULL; mYuvFrame = NULL; mAudioFrame = NULL; mSwsContext = NULL; mVideoOutBuffer = NULL; mSwrContext = NULL; mAudioOutBuffer = NULL; mAudioOutBufferSize = 0; mVideoStreamIndex = -1; mAudioStreamIndex = -1; mOutChannels = 0; mOutSampleRate = 0; mOutChannelLayout = 0; } MediaDecoder::~MediaDecoder() { } bool MediaDecoder::prepare(const char* path) { mformatContext = NULL; mVideoCodecContext = NULL; mAudioCodecContext = NULL; mVideoCodec = NULL; mAudioCodec = NULL; mVideoFrame = NULL; mYuvFrame = NULL; mAudioFrame = NULL; mSwsContext = NULL; mVideoOutBuffer = NULL; mSwrContext = NULL; mAudioOutBuffer = NULL; mAudioOutBufferSize = 0; mVideoStreamIndex = -1; mAudioStreamIndex = -1; mOutChannels = 0; mOutSampleRate = 0; mOutChannelLayout = 0; return init(path); } bool MediaDecoder::init(const char* path) { if (!getMediaInfo(path)) { release(); return false; } if (!initVideoCodec()) { release(); return false; } if (!initAudioCodec()) { release(); return false; } initVideoFrameAndSwsContext(); initAudioFrameAndSwrContext(); return true; } void MediaDecoder::finish() { release(); } bool MediaDecoder::getMediaInfo(const char* path) { LOGD("path %s", path); int error; char buffer[] = ""; // ๆณจๅ†Œ็ฝ‘็ปœๅ่ฎฎ avformat_network_init(); av_register_all(); // ่Žทๅ–ไธŠไธ‹ๆ–‡ mformatContext = avformat_alloc_context(); // ๆ‰“ๅผ€่ง†้ข‘ error = avformat_open_input(&mformatContext, path, NULL, NULL); if (error < 0) { av_strerror(error, buffer, 1024); LOGE("ๆ‰“ๅผ€่ง†้ข‘ๅคฑ่ดฅ %s : %d(%s)", path, error, buffer); return false; } // ่Žทๅ–่ง†้ข‘ไฟกๆฏ error = avformat_find_stream_info(mformatContext, NULL); if (error < 0) { av_strerror(error, buffer, 1024); LOGE("่Žทๅ–่ง†้ข‘ไฟกๆฏๅคฑ่ดฅ %s : %d(%s)", path, error, buffer); return false; } // ่Žทๅ–่ง†้ข‘ๆตidๅ’Œ้Ÿณ้ข‘ๆตid mAudioStreamIndex = -1; mVideoStreamIndex = -1; for (int i = 0; i < mformatContext->nb_streams; ++i) { enum AVMediaType type = mformatContext->streams[i]->codec->codec_type; if (type == AVMEDIA_TYPE_VIDEO) { mVideoStreamIndex = i; } else if (type == AVMEDIA_TYPE_AUDIO) { mAudioStreamIndex = i; } } if (mAudioStreamIndex == -1 || mVideoStreamIndex == -1) { LOGE("่Žทๅ–่ง†้ข‘ๆตid: %d ๆˆ–้Ÿณ้ข‘ๆตidๅคฑ่ดฅ: %d", mVideoStreamIndex, mAudioStreamIndex); return false; } return true; } bool MediaDecoder::initVideoCodec() { int error; char buffer[] = ""; mVideoCodecContext = mformatContext->streams[mVideoStreamIndex]->codec; // ๅฏปๆ‰พ่งฃ็ ๅ™จ mVideoCodec = avcodec_find_decoder(mVideoCodecContext->codec_id); // ๆ‰“ๅผ€่งฃ็ ๅ™จ error = avcodec_open2(mVideoCodecContext, mVideoCodec, NULL); if (error < 0) { av_strerror(error, buffer, 1024); LOGE("ๆ‰“ๅผ€่ง†้ข‘่งฃ็ ๅ™จๅคฑ่ดฅ: %d(%s)", error, buffer); return false; } return true; } bool MediaDecoder::initAudioCodec() { int error; char buffer[] = ""; int degress = 0; AVStream *videoStream = mformatContext->streams[mAudioStreamIndex]; mAudioCodecContext = videoStream->codec; // ๅฏปๆ‰พ่งฃ็ ๅ™จ mAudioCodec = avcodec_find_decoder(mAudioCodecContext->codec_id); // ๆ‰“ๅผ€่งฃ็ ๅ™จ error = avcodec_open2(mAudioCodecContext, mAudioCodec, NULL); if (error < 0) { av_strerror(error, buffer, 1024); LOGE("ๆ‰“ๅผ€้Ÿณ้ข‘่งฃ็ ๅ™จๅคฑ่ดฅ: %d(%s)", error, buffer); return false; } AVDictionary *videoStreamMetadata = videoStream->metadata; AVDictionaryEntry* entry = NULL; while ((entry = av_dict_get(videoStreamMetadata, "", entry, AV_DICT_IGNORE_SUFFIX))){ printf("entry: key is %s value is %s\n", entry->key, entry->value); if (0 == strcmp(entry->key, "rotate")) { degress = atoi(entry->value); } } LOGD("video ่ง’ๅบฆ๏ผš%d", degress); if (error < 0) { av_strerror(error, buffer, 1024); LOGE("ๆ‰“ๅผ€่ง†้ข‘่งฃ็ ๅ™จๅคฑ่ดฅ: %d(%s)", error, buffer); return false; } return true; } bool MediaDecoder::initVideoFrameAndSwsContext() { mVideoFrame = av_frame_alloc(); mYuvFrame = av_frame_alloc(); if (mVideoCodecContext->pix_fmt != AV_PIX_FMT_YUV420P && mVideoCodecContext->pix_fmt != AV_PIX_FMT_YUVJ420P) { // ๅ…ณ่”็ผ“ๅญ˜ๅŒบ mVideoOutBuffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, mVideoCodecContext->width, mVideoCodecContext->height)); avpicture_fill((AVPicture*)mYuvFrame, mVideoOutBuffer, AV_PIX_FMT_YUV420P, mVideoCodecContext->width, mVideoCodecContext->height); // ่ง†้ข‘ๅ›พๅƒ็š„่ฝฌๆข, ๆฏ”ๅฆ‚ๆ ผๅผ่ฝฌๆข mSwsContext = sws_getContext(mVideoCodecContext->width, mVideoCodecContext->height, mVideoCodecContext->pix_fmt, mVideoCodecContext->width, mVideoCodecContext->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); LOGD("ๅˆ›ๅปบYUV420p่ฝฌๆขๅ™จ"); } else { mVideoOutBuffer = NULL; mSwsContext = NULL; LOGD("ไธ้œ€่ฆๅˆ›ๅปบYUV420p่ฝฌๆขๅ™จ"); } return true; } bool MediaDecoder::initAudioFrameAndSwrContext() { int error; char buffer[] = ""; mSwrContext = swr_alloc(); mAudioFrame = av_frame_alloc(); // ่พ“ๅ‡บ็š„้‡‡ๆ ท็އๅฟ…้กปไธŽ่พ“ๅ…ฅ็›ธๅŒ mOutChannelLayout = AV_CH_LAYOUT_STEREO; mOutFormat = AV_SAMPLE_FMT_S16; mOutSampleRate = mAudioCodecContext->sample_rate; mOutChannels = av_get_channel_layout_nb_channels(mOutChannelLayout); mAudioOutBufferSize = av_samples_get_buffer_size(NULL, mOutChannels, mOutSampleRate, mOutFormat, 1); mAudioOutBuffer = (uint8_t*) av_malloc(mAudioOutBufferSize); LOGD("samperate: %d", mOutSampleRate); LOGD("channel: %d", mOutChannels); LOGD("bufferSize: %d" , mAudioOutBufferSize); swr_alloc_set_opts(mSwrContext, mOutChannelLayout, mOutFormat, mOutSampleRate, mAudioCodecContext->channel_layout, mAudioCodecContext->sample_fmt, mAudioCodecContext->sample_rate, 0, NULL); error = swr_init(mSwrContext); if (error < 0) { av_strerror(error, buffer, 1024); LOGD("initAudioFrameAndSwrContext ๅคฑ่ดฅ: %d(%s)", error, buffer); return false; } return true; } AVPacket* MediaDecoder::readFrame() { if (mformatContext == NULL) { return NULL; } AVPacket* packet = new AVPacket; av_init_packet(packet); if (av_read_frame(mformatContext, packet) >= 0) { return packet; } return NULL; } std::vector<VideoFrame*> MediaDecoder::decodeVideoFrame(AVPacket* packet) { // LOGD("MediaDecoder decodeVideoFrame"); std::vector<VideoFrame*> vec; if (packet == NULL || packet->stream_index != mVideoStreamIndex) { LOGE("ไธๆ˜ฏ่ฆ–้ ปๅน€ๆˆ–่€…ๆ˜ฏ็ฉบ"); return vec; } AVStream *videoStream = mformatContext->streams[mVideoStreamIndex]; int gotframe = 0; double timestamp; double duration; int pktSize = packet->size; //LOGD("MediaDecoder pktSize %d", pktSize); while (pktSize > 0) { //LOGD("ๅผ€ๅง‹่งฃ็ ่ง†้ข‘ๅธง"); // ่งฃ็ ๅ›พๅƒๆ•ฐๆฎ๏ผšRGBAๆ ผๅผไฟๅญ˜ๅœจdata[0] ๏ผŒYUVๆ ผๅผๆœ‰data[0] data[1] data[2] int len = avcodec_decode_video2(mVideoCodecContext, mVideoFrame, &gotframe, packet); //LOGD("่งฃ็ ่ง†้ข‘ๅธง๏ผšlen %d, frameCount %d pktSize %d", len, gotframe, pktSize); if (len < 0) { LOGE("decode video error, skip packet"); break; } if (gotframe) { AVFrame *newFrame = scaleVideoFrame(); int pts = av_frame_get_best_effort_timestamp(newFrame); if (pts == AV_NOPTS_VALUE) { pts = 0; } timestamp = pts * r2d(videoStream->time_base); duration = av_frame_get_pkt_duration(newFrame) * r2d(videoStream->time_base); if (duration <= 0 && packet->pts > 0) { duration = 1.0 / packet->pts; } VideoFrame *videoFrame = createVideoFrame(timestamp, duration, newFrame); //LOGD("่งฃ็ ่ง†้ข‘๏ผštime : %lf, duration : %lf packt->pts ๏ผš%ld ", timestamp, duration, packet->pts); vec.push_back(videoFrame); } if (0 == len) { break; } pktSize -= len; av_free_packet(packet); } //LOGD("่งฃ็ ๅฎŒๆˆ %d", vec.size()); return vec; } std::vector<AudioFrame*> MediaDecoder::decodeAudioFrame(AVPacket* packet) { std::vector<AudioFrame*> audioFrames; if (packet == NULL || packet->stream_index != mAudioStreamIndex) { return audioFrames; } int error = 0; char buffer[] = ""; AVStream* audioStream = mformatContext->streams[mAudioStreamIndex]; // ๅฏนไบŽ่ง†้ข‘ๅธง๏ผŒไธ€ไธชAVPacketๆ˜ฏไธ€ๅธง่ง†้ข‘ๅธง๏ผ›ๅฏนไบŽ้Ÿณ้ข‘ๅธง๏ผŒไธ€ไธชAVPacketๆœ‰ๅฏ่ƒฝๅŒ…ๅซๅคšไธช้Ÿณ้ข‘ๅธง int packetSize = packet->size; while (packetSize > 0) { int gotframe = 0; int len = avcodec_decode_audio4(mAudioCodecContext, mAudioFrame, &gotframe, packet); if (len < 0) { break; } if (gotframe) { int swrlen = swr_convert(mSwrContext, &mAudioOutBuffer, mAudioOutBufferSize, (const uint8_t **) mAudioFrame->data, mAudioFrame->nb_samples); if (swrlen < 0) { av_strerror(error, buffer, 1024); LOGE("decodeAudioFrameๅคฑ่ดฅ: %d(%s)", error, buffer); return audioFrames; } if (swrlen == mAudioOutBufferSize) { LOGE("audio buffer is probably too small"); } int size = swrlen * mAudioCodecContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);//ๆฏๅฃฐ้“้‡‡ๆ ทๆ•ฐ x ๅฃฐ้“ๆ•ฐ x ๆฏไธช้‡‡ๆ ทๅญ—่Š‚ๆ•ฐ // ไธ€ไธช packet ไธญๅฏไปฅๅŒ…ๅซๅคšไธชๅธง๏ผŒpacket ไธญ็š„ PTS ๆฏ”็œŸๆญฃ็š„ๆ’ญๆ”พ็š„ PTS ๅฏ่ƒฝไผšๆ—ฉๅพˆๅคš,ๆ’ญๆ”พ็š„ๆ—ถๅ€™้œ€่ฆ้‡ๆ–ฐ็บ ๆญฃ double timestamp = r2d(audioStream->time_base) * packet->pts; double duration = av_frame_get_pkt_duration(mAudioFrame) * r2d(audioStream->time_base); AudioFrame* audioFrame = createAudioFrame(timestamp, duration, size, mAudioOutBuffer); //LOGD("่งฃ็ ้Ÿณ้ข‘๏ผštime : %lf, duration : %lf packt->pts ๏ผš%ld ", timestamp, duration, packet->pts); if(audioFrame) audioFrames.push_back(audioFrame); av_free_packet(packet); } if (0 == len) { break; } packetSize -= len; } return audioFrames; } float MediaDecoder::getMediaDuration() { if(!mformatContext){ return 0; } if (mformatContext->duration == AV_NOPTS_VALUE){ return -1; } return (float)mformatContext->duration / AV_TIME_BASE; } AudioFrame *MediaDecoder::createAudioFrame(double timestamp , double duration, int size, uint8_t* data) { if (size <= 0 || data == NULL) { return NULL; } AudioFrame* audioFrame = new AudioFrame; audioFrame->size = size; audioFrame->timestamp = timestamp ; audioFrame->duration = duration; audioFrame->samplerate = mOutSampleRate; audioFrame->channels = mOutChannels; audioFrame->data = new char[size]; memcpy(audioFrame->data, (char*)data, size); return audioFrame; } VideoFrame *MediaDecoder::createVideoFrame(double timestamp , double duration, AVFrame *videoFrame) { VideoFrame* yuvFrame = new VideoFrame; yuvFrame->frameWidth = mVideoCodecContext->width; yuvFrame->frameHeight = mVideoCodecContext->height; yuvFrame->timestamp = timestamp; yuvFrame->duration = duration; int width = mVideoCodecContext->width; int height = mVideoCodecContext->height; int lumaLength = height * std::min(videoFrame->linesize[0], width); yuvFrame->luma = new uint8_t[lumaLength]; copyFrameData(yuvFrame->luma, videoFrame->data[0], width, height, videoFrame->linesize[0]); int chromaBLength = height / 2 * std::min(videoFrame->linesize[1], width / 2); yuvFrame->chromaB = new uint8_t[chromaBLength]; copyFrameData(yuvFrame->chromaB, videoFrame->data[1], width/2, height/2, videoFrame->linesize[1]); int chromaRLength = height / 2 * std::min(videoFrame->linesize[2], width /2); yuvFrame->chromaR = new uint8_t[chromaRLength]; copyFrameData(yuvFrame->chromaR, videoFrame->data[2], width/2, height/2, videoFrame->linesize[2]); // LOGD("size %d x %d, linesize %d %d %d", width, height, videoFrame->linesize[0], videoFrame->linesize[1], videoFrame->linesize[2]); // LOGD("lumaLen %d chromaB %d chromaR %d", lumaLength, chromaBLength, chromaRLength); return yuvFrame; } void MediaDecoder::copyFrameData(uint8_t * dst, uint8_t * src, int width, int height, int linesize) { width = std::min(linesize, width); for (int i = 0; i < height; ++i) { memcpy(dst, src, width); dst += width; src += linesize; } } void MediaDecoder::release() { LOGD("MediaDecoder::release"); if (mAudioStreamIndex != -1) { delete mformatContext->streams[mAudioStreamIndex]; mAudioStreamIndex = -1; } if (mVideoStreamIndex != -1) { delete mformatContext->streams[mVideoStreamIndex]; mVideoStreamIndex = -1; } if (mYuvFrame) { av_free(mYuvFrame); mYuvFrame = NULL; } if (mVideoFrame) { av_free(mVideoFrame); mVideoFrame = NULL; } if (mAudioFrame) { av_frame_free(&mAudioFrame); av_free(mAudioFrame); mAudioFrame = NULL; } if (mSwsContext) { sws_freeContext(mSwsContext); mSwsContext = NULL; } if (mVideoOutBuffer) { delete mVideoOutBuffer; mVideoOutBuffer = NULL; } if (mSwrContext) { swr_free(&mSwrContext); mSwrContext = NULL; } if (mAudioOutBuffer) { delete mAudioOutBuffer; mAudioOutBuffer = NULL; } if (mAudioCodecContext) { avcodec_close(mAudioCodecContext); mAudioCodecContext = NULL; } if (mVideoCodecContext) { avcodec_close(mVideoCodecContext); mVideoCodecContext = NULL; } if (mformatContext) { avformat_close_input(&mformatContext); avformat_free_context(mformatContext); mformatContext = NULL; } LOGD("MediaDecoder::release finish"); } int MediaDecoder::getSamplerate() { return mOutSampleRate; } int MediaDecoder::getChannelCount() { return mOutChannels; } bool MediaDecoder::isVideoPacket(AVPacket * const packet) { return packet->stream_index == mVideoStreamIndex; } bool MediaDecoder::isAudioPacket(AVPacket * const packet) { return packet->stream_index == mAudioStreamIndex; } double MediaDecoder::r2d(AVRational r) { return r.num == 0 || r.den == 0 ? 0.:(double)r.num/(double)r.den; } int MediaDecoder::getWidth() { return mVideoCodecContext != NULL ? mVideoCodecContext->width : 0; } int MediaDecoder::getHeight() { return mVideoCodecContext != NULL ? mVideoCodecContext->height : 0; } AVFrame *MediaDecoder::scaleVideoFrame() { if (mVideoOutBuffer == NULL || mSwsContext == NULL) { return mVideoFrame; } else { sws_scale(mSwsContext, (const uint8_t *const *) mVideoFrame->data, mVideoFrame->linesize, 0, mVideoFrame->height, mYuvFrame->data, mYuvFrame->linesize); return mYuvFrame; } } void MediaDecoder::seek(float seconds) { LOGE("seek begin"); int64_t seek_target = seconds * 1000000; int64_t seek_min = INT64_MIN; int64_t seek_max = INT64_MAX; LOGE("before avformat_seek_file..."); int ret = avformat_seek_file(mformatContext, -1, seek_min, seek_target, seek_max, 0); LOGE("after avformat_seek_file... ret is %d", ret); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "cc: error while seeking\n"); } else { avcodec_flush_buffers(mAudioCodecContext); avcodec_flush_buffers(mVideoCodecContext); } LOGE("seek end"); } void MediaDecoder::freePacket(AVPacket *packet) { if (packet) { av_free_packet(packet); delete packet; } }
e37d5ca711225f8b0fe31a33a9779435891e1f42
4fc10b326682128ff6a92a927c8ec44d71d08824
/src/devices/board/drivers/vim3/vim3-mali.cc
46def717733255b24befb1f5e263655ab605b3b5
[ "BSD-2-Clause" ]
permissive
dahliaOS/fuchsia-pi4
f93dc1e0da5ed34018653c72ceab0c50e1d0c1e4
5b534fccefd918b5f03205393c1fe5fddf8031d0
refs/heads/main
2023-05-01T22:57:08.443538
2021-05-20T23:53:40
2021-05-20T23:53:40
367,988,554
5
2
null
null
null
null
UTF-8
C++
false
false
2,359
cc
vim3-mali.cc
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/ddk/binding.h> #include <lib/ddk/debug.h> #include <lib/ddk/platform-defs.h> #include <lib/ddk/hw/reg.h> #include <soc/aml-a311d/a311d-hw.h> #include <soc/aml-common/aml-registers.h> #include "vim3.h" namespace vim3 { static const pbus_mmio_t mali_mmios[] = { { .base = A311D_MALI_BASE, .length = A311D_MALI_LENGTH, }, { .base = A311D_HIU_BASE, .length = A311D_HIU_LENGTH, }, }; static const pbus_irq_t mali_irqs[] = { { .irq = A311D_MALI_IRQ_PP, .mode = ZX_INTERRUPT_MODE_LEVEL_HIGH, }, { .irq = A311D_MALI_IRQ_GPMMU, .mode = ZX_INTERRUPT_MODE_LEVEL_HIGH, }, { .irq = A311D_MALI_IRQ_GP, .mode = ZX_INTERRUPT_MODE_LEVEL_HIGH, }, }; static pbus_bti_t mali_btis[] = { { .iommu_index = 0, .bti_id = BTI_MALI, }, }; static pbus_dev_t mali_dev = []() { pbus_dev_t dev = {}; dev.name = "mali"; dev.vid = PDEV_VID_AMLOGIC; dev.pid = PDEV_PID_AMLOGIC_A311D; dev.did = PDEV_DID_AMLOGIC_MALI_INIT; dev.mmio_list = mali_mmios; dev.mmio_count = countof(mali_mmios); dev.irq_list = mali_irqs; dev.irq_count = countof(mali_irqs); dev.bti_list = mali_btis; dev.bti_count = countof(mali_btis); return dev; }(); static const zx_bind_inst_t root_match[] = { BI_MATCH(), }; static const zx_bind_inst_t reset_register_match[] = { BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_REGISTERS), BI_MATCH_IF(EQ, BIND_REGISTER_ID, aml_registers::REGISTER_MALI_RESET), }; static const device_fragment_part_t reset_register_fragment[] = { {countof(root_match), root_match}, {countof(reset_register_match), reset_register_match}, }; static const device_fragment_t mali_fragments[] = { {"register-reset", countof(reset_register_fragment), reset_register_fragment}, }; zx_status_t Vim3::MaliInit() { zx_status_t status = pbus_.CompositeDeviceAdd( &mali_dev, reinterpret_cast<uint64_t>(mali_fragments), countof(mali_fragments), UINT32_MAX); if (status != ZX_OK) { zxlogf(ERROR, "Sherlock::MaliInit: CompositeDeviceAdd failed: %d", status); return status; } return status; } } // namespace vim3
9db9bce1182d4c5cb6606f378e2f1e3ea45d5ccb
7c8847c1e88242f4aa949853da87c957f86239dc
/bin/num_array_den_error_analysis.cpp
b9fff57482594d84b4e8fe4bba835423c7d960c5
[ "MIT" ]
permissive
hshi/thread_mc_data_manipulate_lib_hao_1
f90ee066e89d7fac6f99c31cab3b81ac59d4183c
c7031f4fd2f8fa8747eba3da37aebd5ade242ce7
refs/heads/master
2020-12-09T18:18:59.859456
2016-08-18T14:15:08
2016-08-18T14:15:08
52,981,468
0
0
null
null
null
null
UTF-8
C++
false
false
3,389
cpp
num_array_den_error_analysis.cpp
#include <math.h> #include <algorithm> #include <iomanip> #include <fstream> #include <complex> #include "error_analysis.h" #include "kahan.h" #include "tensor_all.h" #include "read_write_file.h" using namespace std; using namespace tensor_hao; int main(int argc, char** argv) { if( argc<6 ) { cout<<"Error!!!!! Need input/output file name, array size, and block size!"<<endl; cout<<"Example: ./num_array_den_error_analysis num.dat den.dat out.dat array_size block_size!"<<endl; exit(1); } string num_filename = argv[1]; //numerator filename string den_filename = argv[2]; //denominator filename string out_filename = argv[3]; //output filename int L = atoi( argv[4] ); //Each array size int block_size = atoi( argv[5] ); //Block size int num_sample_size = file_sample_size(num_filename, L); int den_sample_size = file_sample_size(den_filename); int sample_size = (num_sample_size > den_sample_size) ? den_sample_size : num_sample_size; int block_num = sample_size / block_size; if( ( sample_size-block_num*block_size ) !=0 ) { cout<<"ERROR!!!!! Total sample size can not be devided by block size! "<<sample_size<<" "<<block_size<<endl; exit(1); } cout<<"Effective sample points is "<<sample_size<<endl; cout<<"Use reblock to calculate error bar, block number is "<<block_num<<endl; //Open files ifstream num_file; num_file.open(num_filename, ios::in); if ( ! num_file.is_open() ) {cout << "Error opening num file in num_array_den_error_analysis.cpp!!!"<<endl; exit(1);} ifstream den_file; den_file.open(den_filename, ios::in); if ( ! den_file.is_open() ) {cout << "Error opening den file in num_array_den_error_analysis.cpp!!!"<<endl; exit(1);} Tensor_hao<complex<double>, 1> num_tmp(L), num_sum(L); complex<double> den_tmp, den_sum, zero(0,0); Tensor_hao<complex<double>, 1> mean(L), error(L); //Calculate mean valule num_sum = zero; den_sum = zero; for(int i=0; i<sample_size; i++) { read_file(num_tmp, num_file); read_file(den_tmp, den_file); num_sum += num_tmp; den_sum += den_tmp; } mean= num_sum / den_sum; //Clear the file and calculate error bar if( block_num>1 ) { num_file.clear(); den_file.clear(); num_file.seekg(0, ios::beg); den_file.seekg(0, ios::beg); for(int i=0; i<block_num; i++) { num_sum = zero; den_sum = zero; for(int j=0; j<block_size; j++) { read_file(num_tmp, num_file); read_file(den_tmp, den_file); num_sum += num_tmp; den_sum += den_tmp; } error += norm( num_sum/den_sum - mean ); } error /= complex<double>( block_num*(block_num-1), 0.0 ); error = sqrt(error); } else { error = zero; } //Close files num_file.close(); den_file.close(); //Write to output file ofstream out_file; out_file.open(out_filename, ios::out|ios::trunc); out_file<<setprecision(16)<<scientific; for (int i=0; i<L; i++) { out_file<<setw(26)<<mean(i).real()<<setw(26)<<mean(i).imag()<<setw(26)<<error(i).real()<<"\n"; } out_file.close(); return 0; }
c24c2f7974861630ee84371c958672de6153d29e
c870d137d4e86026de017d29f9b8cba784b05027
/Handcard.cpp
d913176d00a773380f2d5052ffea3b8a3aeae84c
[]
no_license
voidism/Big-Two
304402701e882cd9344fe3af237c985e8699cf57
dbe3db0f3ced82666a9b6e89496090e857fd59b5
refs/heads/master
2021-01-25T14:26:43.360562
2019-01-02T11:12:02
2019-01-02T11:12:02
123,697,307
0
1
null
null
null
null
UTF-8
C++
false
false
34,581
cpp
Handcard.cpp
#include <iostream> #include <cstdlib> #include <string> #include "Pair.h" #include "Single.h" #include "Handcard.h" using namespace std; int Handcard::passnum=3; void Handcard::swap(Card& a,Card& b) { Card tmp; tmp=a; a=b; b=tmp; } int Handcard::min(int start) { int m=55,s=hand.size(),counter=0; for(int i=start;i<s;i++) { if(hand.at(i).value<m) { m=hand.at(i).value; counter=i; } } return counter; } void Handcard::sort() { for(int i=0;i<hand.size();i++) { swap(hand.at(i),hand.at(min(i))); } } void Handcard::popout() { for(int i=0;i<hand.size();i++) { if((hand.at(i).getface()==0)&&(hand.at(i).getsuit()==0)) { hand.erase(hand.begin()+i); i--; } } } void Handcard::printall() { for(int i=0;i<hand.size();i++) { cout<<hand.at(i).toString()<<endl; } } void Handcard::userputPair() { myPair.clear(); for(int i=0;i<(hand.size()-1);i++) { if(hand.at(i).getface()==hand.at(i+1).getface()) { hand.at(i).chosen=1; hand.at(i+1).chosen=1; Pair tmp(hand.at(i),hand.at(i+1)); myPair.push_back(tmp); } } sortingPair(); } void Handcard::putPair() { myPair.clear(); for(int i=0; i<(hand.size()-1); i++) { if((hand.at(i).getface()==hand.at(i+1).getface())&&(hand.at(i).chosen==0)&&(hand.at(i+1).chosen==0)) { hand.at(i).chosen=1; hand.at(i+1).chosen=1; Pair tmp(hand.at(i),hand.at(i+1)); myPair.push_back(tmp); } } sortingPair(); } void Handcard::putThree() { myThree.clear(); for(int i=0; i<(hand.size()-2); i++) { if(hand.size()<5)break; if((hand.at(i).getface()==hand.at(i+1).getface())&&(hand.at(i+1).getface()==hand.at(i+2).getface())) { //cout<<"รŸโ€ฐยฎรโˆยจฦ’โ„ขยงF!!!"; hand.at(i).chosen=1; hand.at(i+1).chosen=1; hand.at(i+2).chosen=1; Three tmp(hand.at(i),hand.at(i+1),hand.at(i+2)); myThree.push_back(tmp); } } sortingThree(); } void Handcard::userputThree() { // cout<<"userputthree"; myThree.clear(); for(int i=0; i<(hand.size()-2); i++) { if(hand.size()<5)break; if((hand.at(i).getface()==hand.at(i+1).getface())&&(hand.at(i+1).getface()==hand.at(i+2).getface())) { Three tmp(hand.at(i),hand.at(i+1),hand.at(i+2)); myThree.push_back(tmp); Pair tmp2(hand.at(i),hand.at(i+2)); myPair.push_back(tmp2); } } sortingThree(); sortingPair(); } void Handcard::putSingle() { mySingle.clear(); for(int i=0;i<hand.size();i++) { if((hand.at(i).chosen==0)||(hand.at(i).getface()==13)) { //cout<<"putSingle"<<hand.at(i).toString()<<endl; Single tmp(hand.at(i)); mySingle.push_back(tmp); } } sortingSingle(); } void Handcard::classify() { popout(); sort(); for(int i=0; i<hand.size(); i++) { hand.at(i).chosen=0; } putFour(); putStraight(); putThree(); putPair(); putSingle(); if(myPair.size()==0) { mySingle.clear(); myPair.clear(); myThree.clear(); myFour.clear(); myStraight.clear(); popout(); sort(); for(int i=0; i<hand.size(); i++) { hand.at(i).chosen=0; } putFour(); putStraight(); putPair(); putSingle(); } } void Handcard::userclassify() { popout(); sort(); for(int i=0; i<hand.size(); i++) { hand.at(i).chosen=0; } putSingle(); userputPair(); userputThree(); putFour(); putStraight(); } void Handcard::judgeclassify() { popout(); sort(); for(int i=0; i<hand.size(); i++) { hand.at(i).chosen=0; } putStraight(); putFour(); putThree(); putPair(); putSingle(); } int Handcard::minPair(int start) { int m=55,s=myPair.size(),counter=0; for(int i=start;i<s;i++) { if(myPair.at(i).maxCard->value<m) { m=myPair.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingPair() { for(int i=0;i<myPair.size();i++) { myPair.at(i).swap(myPair.at(i),myPair.at(minPair(i))); } } int Handcard::minThree(int start) { int m=55,s=myThree.size(),counter=0; for(int i=start; i<s; i++) { if(myThree.at(i).maxCard->value<m) { m=myThree.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingThree() { for(int i=0; i<myThree.size(); i++) { myThree.at(i).swap(myThree.at(i),myThree.at(minThree(i))); } } int Handcard::minSingle(int start) { int m=55,s=mySingle.size(),counter=0; for(int i=start;i<s;i++) { if(mySingle.at(i).maxCard->value<m) { m=mySingle.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingSingle() { for(int i=0;i<mySingle.size();i++) { //if(mySingle.at(i).CompareSingle(mySingle.at(i),mySingle.at(minSingle(i)))) //cout<<mySingle.at(i).toString()<<"<->"<<mySingle.at(minSingle(i)).toString()<<endl; int locmin=minSingle(i); mySingle.at(i).swap(mySingle.at(i),mySingle.at(locmin)); } } int Handcard::minFour(int start) { int m=55,s=myFour.size(),counter=0; for(int i=start; i<s; i++) { if(myFour.at(i).maxCard->value<m) { m=myFour.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingFour() { for(int i=0; i<myFour.size(); i++) { myFour.at(i).swap(myFour.at(i),myFour.at(minFour(i))); } } void Handcard::putFour() { myFour.clear(); for(int i=0; i<(hand.size()-3); i++) { if(hand.size()<4)break; if((hand.at(i).getface()==hand.at(i+1).getface())&&(hand.at(i+1).getface()==hand.at(i+2).getface())&&(hand.at(i+2).getface()==hand.at(i+3).getface()) &&(hand.at(i).getsuit()!=hand.at(i+1).getsuit())&&(hand.at(i+1).getsuit()!=hand.at(i+2).getsuit())&&(hand.at(i+2).getsuit()!=hand.at(i+3).getsuit()) ) { hand.at(i).chosen=1; hand.at(i+1).chosen=1; hand.at(i+2).chosen=1; hand.at(i+3).chosen=1; Four tmp(hand.at(i),hand.at(i+1),hand.at(i+2),hand.at(i+3)); myFour.push_back(tmp); } } sortingFour(); } int Handcard::minStraight(int start) { int m=55,s=myStraight.size(),counter=0; for(int i=start; i<s; i++) { if(myStraight.at(i).maxCard->value<m) { m=myStraight.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingStraight() { for(int i=0; i<myStraight.size(); i++) { myStraight.at(i).swap(myStraight.at(i),myStraight.at(minStraight(i))); } } void Handcard::putStraight() { myStraight.clear(); myFlushStraight.clear(); for(int i=0; i<(hand.size()-4); i++) { if(hand.size()<5)break; int a=i; int b=nextface(a); int c=nextface(b); int d=nextface(c); int e=nextface(d); if( (((hand.at(a).getface())==(hand.at(b).getface()-1) &&(hand.at(b).getface()-1)==(hand.at(c).getface()-2) &&(hand.at(c).getface()-2)==(hand.at(d).getface()-3) &&(hand.at(d).getface()-3)==(hand.at(e).getface()-4) ) && ((hand.at(a).getface()!=9)&&(hand.at(b).getface()!=10)&&(hand.at(c).getface()!=11)&&(hand.at(d).getface()!=12)&&(hand.at(e).getface()!=13))) || ((hand.at(a).getface()==1)&&(hand.at(b).getface()==2)&&(hand.at(c).getface()==3)&&(hand.at(d).getface()==12)&&(hand.at(e).getface()==13)) || ((hand.at(a).getface()==1)&&(hand.at(b).getface()==2)&&(hand.at(c).getface()==3)&&(hand.at(d).getface()==4)&&(hand.at(e).getface()==13)) ) { hand.at(a).chosen=1; hand.at(b).chosen=1; hand.at(c).chosen=1; hand.at(d).chosen=1; hand.at(e).chosen=1; Straight tmp(hand.at(a),hand.at(b),hand.at(c),hand.at(d),hand.at(e)); if(((hand.at(a).getsuit())==(hand.at(b).getsuit()) &&(hand.at(b).getsuit())==(hand.at(c).getsuit()) &&(hand.at(c).getsuit())==(hand.at(d).getsuit()) &&(hand.at(d).getsuit())==(hand.at(e).getsuit()) )==0) myStraight.push_back(tmp); if((hand.at(a).getsuit())==(hand.at(b).getsuit()) &&(hand.at(b).getsuit())==(hand.at(c).getsuit()) &&(hand.at(c).getsuit())==(hand.at(d).getsuit()) &&(hand.at(d).getsuit())==(hand.at(e).getsuit()) ) myFlushStraight.push_back(tmp); } } sortingStraight(); sortingFlushStraight(); } int Handcard::minFlushStraight(int start) { int m=55,s=myFlushStraight.size(),counter=0; for(int i=start; i<s; i++) { if(myFlushStraight.at(i).maxCard->value<m) { m=myFlushStraight.at(i).maxCard->value; counter=i; } } return counter; } void Handcard::sortingFlushStraight() { for(int i=0; i<myFlushStraight.size(); i++) { myFlushStraight.at(i).swap(myFlushStraight.at(i),myFlushStraight.at(minFlushStraight(i))); } } Play Handcard::playcardAI(Play in, int inn, vector<Card> &gvector) { classify(); gvector.clear(); switch(in.kindcode) { case 1://if the card last player play Single { if(passnum>=3) { //if already pass three times passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } int counter=-1; for(int i=0; i<mySingle.size(); i++) { if((mySingle.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } if(counter>-1) //if there are proper cards to play { passnum=0; cout<<"playcard:"<<mySingle.at(counter).toString()<<endl<<endl; gvector.push_back(*(mySingle.at(counter).maxCard)); Play out(mySingle.at(counter)); //delete hand's card mySingle.at(counter).maxCard->setface(0); mySingle.at(counter).maxCard->setsuit(0); //delete itself mySingle.erase(mySingle.begin()+counter); return out; } else if(counter==-1) //if no proper card to play { if(myFour.size()>0) { Play alto(4,0); return playcardAI(alto,inn, gvector); } if(myFlushStraight.size()>0) { Play alto(6,0); return playcardAI(alto,inn, gvector); } passnum++; cout<<"PASS!"<<endl<<endl; return in; } } case 2://if the card last player play Pair { if(passnum>=3) { //if already pass three times passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } int counter=-1; for(int i=0; i<myPair.size(); i++) { if((myPair.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } if(counter>-1) //if there are proper cards to play { passnum=0; if(((myPair.size()-1)>counter)&&(myThree.size()>0)) //new:if there are three to play, reserve a small pair to match it. counter++; cout<<"playcard:"<<myPair.at(counter).toString()<<endl<<endl; gvector.push_back(*(myPair.at(counter).maxCard)); gvector.push_back(*(myPair.at(counter).minCard)); Play out(myPair.at(counter)); //delete hand's card myPair.at(counter).p1->setface(0); myPair.at(counter).p1->setsuit(0); myPair.at(counter).p2->setface(0); myPair.at(counter).p2->setsuit(0); //delete itself myPair.erase(myPair.begin()+counter); return out; } else if(counter==-1) //if no proper card to play { if(myFour.size()>0) { Play alto(4,0); return playcardAI(alto,inn, gvector); } if(myFlushStraight.size()>0) { Play alto(6,0); return playcardAI(alto,inn, gvector); } passnum++; cout<<"PASS!"<<endl<<endl; return in; } } case 3://if the card last player play Three { if(passnum>=3) { //if already pass three times passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } //find min but proper three int counter=-1; for(int i=0; i<myThree.size(); i++) { if((myThree.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } //find min but proper pair int pcounter=-1; for(int i=0; i<myPair.size(); i++) { pcounter=i; break; } //to sum up if(counter>-1&&pcounter>-1) //if there are proper cards to play { passnum=0; cout<<"playcard:"<<myThree.at(counter).toString()<<myPair.at(pcounter).toString()<<endl<<endl; Play out(myThree.at(counter),myPair.at(pcounter)); gvector.push_back(*(myThree.at(counter).t[0])); gvector.push_back(*(myThree.at(counter).t[1])); gvector.push_back(*(myThree.at(counter).t[2])); gvector.push_back(*(myPair.at(pcounter).maxCard)); gvector.push_back(*(myPair.at(pcounter).minCard)); //delete hand's card for(int i=0; i<3; i++) { myThree.at(counter).t[i]->setface(0); myThree.at(counter).t[i]->setsuit(0); } //delete itself myThree.erase(myThree.begin()+counter); //delete hand's card myPair.at(counter).p1->setface(0); myPair.at(counter).p1->setsuit(0); myPair.at(counter).p2->setface(0); myPair.at(counter).p2->setsuit(0); //delete itself myPair.erase(myPair.begin()+counter); return out; } else if(counter==-1||pcounter==-1) //if no proper card to play { if(myFour.size()>0) { Play alto(4,0); return playcardAI(alto,inn, gvector); } if(myFlushStraight.size()>0) { Play alto(6,0); return playcardAI(alto,inn, gvector); } passnum++; cout<<"PASS!"<<endl<<endl; return in; } } case 4: { if(passnum>=3) { passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } int counter=-1; for(int i=0; i<myFour.size(); i++) { if((myFour.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } //find min but proper single int scounter=-1; for(int i=0; i<mySingle.size(); i++) { scounter=i; break; } if (counter>-1&&scounter>-1) { passnum=0; cout<<"playcard:"<<myFour.at(counter).toString()<<mySingle.at(scounter).toString()<<endl<<endl; gvector.push_back(*(myFour.at(counter).f[0])); gvector.push_back(*(myFour.at(counter).f[1])); gvector.push_back(*(myFour.at(counter).f[2])); gvector.push_back(*(myFour.at(counter).f[3])); gvector.push_back(*(mySingle.at(scounter).maxCard)); Play out(myFour.at(counter),mySingle.at(scounter)); //delete hand's card for(int i=0; i<4; i++) { myFour.at(counter).f[i]->setface(0); myFour.at(counter).f[i]->setsuit(0); } //delete itself myFour.erase(myFour.begin()+counter); //delete hand's card mySingle.at(counter).maxCard->setface(0); mySingle.at(counter).maxCard->setsuit(0); //delete itself mySingle.erase(mySingle.begin()+counter); return out; } else if(counter==-1) { if(myFlushStraight.size()>0) { Play alto(6,0); return playcardAI(alto,inn, gvector); } passnum++; cout<<"PASS!"<<endl<<endl; return in; } } case 5: { if(passnum>=3) { passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } int counter=-1; for(int i=0; i<myStraight.size(); i++) { if((myStraight.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } if (counter>-1) { passnum=0; cout<<"playcard:"<<myStraight.at(counter).toString()<<endl<<endl; gvector.push_back(*(myStraight.at(counter).s[0])); gvector.push_back(*(myStraight.at(counter).s[1])); gvector.push_back(*(myStraight.at(counter).s[2])); gvector.push_back(*(myStraight.at(counter).s[3])); gvector.push_back(*(myStraight.at(counter).s[4])); Play out(myStraight.at(counter)); //delete hand's card for(int i=0; i<5; i++) { myStraight.at(counter).s[i]->setface(0); myStraight.at(counter).s[i]->setsuit(0); } //delete itself myStraight.erase(myStraight.begin()+counter); return out; } else if(counter==-1) { if(myFour.size()>0) { Play alto(4,0); return playcardAI(alto,inn, gvector); } if(myFlushStraight.size()>0) { Play alto(6,0); return playcardAI(alto,inn, gvector); } passnum++; cout<<"PASS!"<<endl<<endl; return in; } } case 6: { if(passnum>=3) { passnum=0; cout<<"freely "; return freecardAI(inn, gvector); } int counter=-1; for(int i=0; i<myFlushStraight.size(); i++) { if((myFlushStraight.at(i).maxCard->value)>(in.maxCard.value)) { counter=i; break; } } if (counter>-1) { passnum=0; cout<<"playcard:"<<myFlushStraight.at(counter).toString()<<endl<<endl; gvector.push_back(*(myFlushStraight.at(counter).s[0])); gvector.push_back(*(myFlushStraight.at(counter).s[1])); gvector.push_back(*(myFlushStraight.at(counter).s[2])); gvector.push_back(*(myFlushStraight.at(counter).s[3])); gvector.push_back(*(myFlushStraight.at(counter).s[4])); Play out(myFlushStraight.at(counter),6); //delete hand's card for(int i=0; i<5; i++) { myFlushStraight.at(counter).s[i]->setface(0); myFlushStraight.at(counter).s[i]->setsuit(0); } //delete itself myFlushStraight.erase(myFlushStraight.begin()+counter); return out; } else if(counter==-1) { passnum++; cout<<"PASS!"<<endl<<endl; return in; } } } Play a; return a; } Play Handcard::freecardAI(int inn,vector<Card> &gvector) { classify(); int kindarry[7]; //find single if(!mySingle.size()) { kindarry[1]=55; } else kindarry[1]=mySingle.at(0).minCard->value; //find pair if(!myPair.size()) { kindarry[2]=55; } else kindarry[2]=myPair.at(0).minCard->value; //find three if(!myThree.size()) { kindarry[3]=55; } else kindarry[3]=myThree.at(0).minCard->value; //find four if(!myFour.size()) { kindarry[4]=55; } else kindarry[4]=myFour.at(0).minCard->value; //find straight if(!myStraight.size()) { kindarry[5]=55; } else kindarry[5]=myStraight.at(0).minCard->value; //find flushstraight if(!myFlushStraight.size()) { kindarry[6]=55; } else kindarry[6]=myFlushStraight.at(0).minCard->value; int in=0,min=56; for(int i=1; i<7; i++) { if(kindarry[i]<=min) { min=kindarry[i]; in=i; } } //add super AI if(inn>0) if(in==1||in==2) { if(myStraight.size()>0) in=5; else if(myThree.size()>0) in=3; } //if there are straight or three in hand, play them first. if(inn==0) if(in==2) { if(myThree.size()>0) in=3; } //if it want to play pair at first inn, and there are three in hand, play them together. Play input(in,0); return playcardAI(input, inn, gvector); } bool Handcard::judgecard(Play in,int inn,vector<int> clicked) { if(clicked.size()==0) //if no proper card to play { return 1; } for(int i=0; i<clicked.size(); i++) { if((clicked.at(i)>=hand.size())||(clicked.at(i)<0)) { cout<<"\nout of range\n"; return 0; } } Handcard preplay ; for(int i=0; i<clicked.size(); i++) { preplay.hand.push_back(hand.at(clicked.at(i))); } preplay.judgeclassify(); //check wrong card shape int k=preplay.kindswitch(); if(k==0) return 0; if((k==4)&&(in.kindcode!=4)&&(in.kindcode!=6))//Four can play after any other card shape return 1; if((k==6)&&(in.kindcode!=6))//FlushStraight can play after any other card shape return 1; if(passnum>=3) { in.maxCard.setface(0); in.maxCard.setsuit(0); in.maxCard.value=0; in.kindcode=0; cout<<"freely "; } if(k==in.kindcode||passnum>=3) { switch(k) { case 1: { if(preplay.mySingle.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } case 2: { if(preplay.myPair.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } case 3: { if(preplay.myThree.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } case 4: { if(preplay.myFour.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } case 5: { if(preplay.myStraight.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } case 6: { if(preplay.myFlushStraight.at(0).maxCard->value>in.maxCard.value) { return 1; } else { cout<<"\nthe card is not big enough!\n"; return 0; } } } } return 0; } Play Handcard::userplaycard(Play a,vector <int> clicked, vector<Card> &gvector) { gvector.clear(); if(clicked.size()==0) //if user play empty card { passnum++; cout<<"user PASS!"<<endl<<endl; return a; } passnum=0; Handcard preplay; for(int i=0; i<clicked.size(); i++) { preplay.hand.push_back(hand.at(clicked.at(i))); } preplay.judgeclassify(); switch(preplay.kindswitch()) { case 1://if the card last player play is Single { passnum=0; cout<<"user playcard:"<<preplay.mySingle.at(0).toString()<<endl<<"->single"<<endl; gvector.push_back(*(preplay.mySingle.at(0).maxCard)); Play out(preplay.mySingle.at(0)); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.erase(hand.begin()+clicked.at(0)); } //delete itself preplay.mySingle.erase(preplay.mySingle.begin()); return out; } case 2://if the card last player play is Pair { passnum=0; cout<<"user playcard:"<<preplay.myPair.at(0).toString()<<endl<<"->pair"<<endl; gvector.push_back(*(preplay.myPair.at(0).maxCard)); gvector.push_back(*(preplay.myPair.at(0).minCard)); Play out(preplay.myPair.at(0)); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.erase(hand.begin()+clicked.at(0)); } //delete itself preplay.myPair.clear(); return out; } case 3://if the card last player play is Three { passnum=0; cout<<"user playcard:"<<preplay.myThree.at(0).toString()<<preplay.myPair.at(0).toString()<<endl<<"->three"<<endl; gvector.push_back(*(preplay.myThree.at(0).t[0])); gvector.push_back(*(preplay.myThree.at(0).t[1])); gvector.push_back(*(preplay.myThree.at(0).t[2])); gvector.push_back(*(preplay.myPair.at(0).maxCard)); gvector.push_back(*(preplay.myPair.at(0).minCard)); Play out(preplay.myThree.at(0),preplay.myPair.at(0)); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.at(clicked.at(i)).setface(0); hand.at(clicked.at(i)).setsuit(0); } //delete itself preplay.myThree.clear(); preplay.myPair.clear(); return out; } case 4://if the card last player play is Four { passnum=0; cout<<"user playcard:"<<preplay.myFour.at(0).toString()<<preplay.mySingle.at(0).toString()<<endl<<"->four"<<endl; gvector.push_back(*(preplay.myFour.at(0).f[0])); gvector.push_back(*(preplay.myFour.at(0).f[1])); gvector.push_back(*(preplay.myFour.at(0).f[2])); gvector.push_back(*(preplay.myFour.at(0).f[3])); gvector.push_back(*(preplay.mySingle.at(0).maxCard)); Play out(preplay.myFour.at(0),preplay.mySingle.at(0)); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.at(clicked.at(i)).setface(0); hand.at(clicked.at(i)).setsuit(0); } //delete itself preplay.myFour.clear(); preplay.mySingle.clear(); return out; } case 5://if the card last player play is Straight { passnum=0; cout<<"user playcard:"<<preplay.myStraight.at(0).toString()<<endl<<"->straight"<<endl; gvector.push_back(*(preplay.myStraight.at(0).s[0])); gvector.push_back(*(preplay.myStraight.at(0).s[1])); gvector.push_back(*(preplay.myStraight.at(0).s[2])); gvector.push_back(*(preplay.myStraight.at(0).s[3])); gvector.push_back(*(preplay.myStraight.at(0).s[4])); Play out(preplay.myStraight.at(0)); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.at(clicked.at(i)).setface(0); hand.at(clicked.at(i)).setsuit(0); } //delete itself preplay.myStraight.clear(); return out; } case 6://if the card last player play is FlushStraight { passnum=0; cout<<"user playcard:"<<preplay.myFlushStraight.at(0).toString()<<endl<<"->flushstraight"<<endl; gvector.push_back(*(preplay.myFlushStraight.at(0).s[0])); gvector.push_back(*(preplay.myFlushStraight.at(0).s[1])); gvector.push_back(*(preplay.myFlushStraight.at(0).s[2])); gvector.push_back(*(preplay.myFlushStraight.at(0).s[3])); gvector.push_back(*(preplay.myFlushStraight.at(0).s[4])); Play out(preplay.myFlushStraight.at(0),6); //delete hand's card for(int i=0; i<clicked.size(); i++) { hand.at(clicked.at(i)).setface(0); hand.at(clicked.at(i)).setsuit(0); } //delete itself preplay.myFlushStraight.clear(); return out; } } return a; } bool Handcard::club3() { if(hand.size()==13) { if(hand.at(0).value==1) return 1; } return 0; } int Handcard::kindswitch() { if((mySingle.size()==1)&&(myPair.size()==0)&&(myThree.size()==0)&&(myFour.size()==0)&&(myStraight.size()==0)&&(myFlushStraight.size()==0)) { return 1; } if((mySingle.size()==0)&&(myPair.size()==1)&&(myThree.size()==0)&&(myFour.size()==0)&&(myStraight.size()==0)&&(myFlushStraight.size()==0)) { return 2; } if((mySingle.size()==0)&&(myPair.size()==1)&&(myThree.size()==1)&&(myFour.size()==0)&&(myStraight.size()==0)&&(myFlushStraight.size()==0)) { return 3; } if((mySingle.size()==1)&&(myPair.size()==0)&&(myThree.size()==0)&&(myFour.size()==1)&&(myStraight.size()==0)&&(myFlushStraight.size()==0)) { return 4; } if((mySingle.size()==0)&&(myPair.size()==0)&&(myThree.size()==0)&&(myFour.size()==0)&&(myStraight.size()==1)&&(myFlushStraight.size()==0)) { return 5; } if((mySingle.size()==0)&&(myPair.size()==0)&&(myThree.size()==0)&&(myFour.size()==0)&&(myStraight.size()==0)&&(myFlushStraight.size()==1)) { return 6; } else return 0; } int Handcard::nextface(int a) { for(int i=a+1; i<hand.size(); i++) { if(hand.at(a).getface()!=hand.at(i).getface()) return i; } for(int i=0; i<hand.size(); i++) { if(hand.at(a).getface()!=hand.at(i).getface()) return i; } return 0; }
c4f276fb0c011213debc802807ad011da9edcaef
e3986436061b987c51ff97bfbf2efc21f5600045
/ะ—ะฐะดะฐะฝะธะต/Zadanie 1.cpp
551398fa2c48bb44b27de52cdc52f282f01c50e0
[]
no_license
Artem22831/informatics_185_2020
20b10660ffe61f5625a1b6dc1c6427796460404a
38129137f28a48ff1f6441d02a6692d26bb7b967
refs/heads/master
2023-02-03T04:03:16.057665
2020-12-22T17:55:04
2020-12-22T17:55:04
306,718,938
0
0
null
2020-12-01T15:09:56
2020-10-23T18:38:39
C++
UTF-8
C++
false
false
906
cpp
Zadanie 1.cpp
#include <iostream> #include <cmath> //dlv-ะดะปะธะฝะฝะฐ ะฒะตะบั‚ะพั€ะฐ //edx,edy,edz-ะตะดะธะฝะธั†ั‹ x,y,z //sp-ัะบะฐะปัั€ะฝะพะต ะฟั€ะพะธะทะฒะตะดะตะฝะธะต //vp-ะฒะตะบั‚ะพั€ะฝะพะต ะฟั€ะพะธะทะฒะตะดะตะฝะธะต //ev-ะตะดะธะฝะธั‡ะฝั‹ะน ะฒะตะบั‚ะพั€ using namespace std; float edv(float dlv, int a); int main(){ float edx, edy, edz; int x = 1; int y = 5; int z = 3; float dlv = sqrt(x*x+y*y+z*z); edx = edv(dlv,x); edy = edv(dlv,y); edz = edv(dlv,z); cout << "koord 2 vektora" << endl; int x1, y1, z1; cin >> x1; cin >> y1; cin >> z1; int sp = x*x1+y*y1+z*z1; int vprI, vprJ, vprK; cout << "sp= " << sp << endl; cout << "ev= " << " " << edx << " " << edy << " " << edz << endl; vprI = y*z1 - y1*z; vprJ = x1*z - x*z1; vprK = x*y1 - x1*y; cout << "vp= " << "(" << vprI << ";" << vprJ << ";" << vprK << ")" << endl; } float edv(float dlv, int a) { return a/dlv; }
f701d1dd47c65975a332ec9d705e018abad0c82e
702aa7364289f87d16e0fcbd163d648bd9cc4148
/Languages/C++/max_and_min.cpp
0109cdca0b4ea9b0626d2f96adf8ef256c47eb0c
[]
permissive
syyam/Hacktoberfest
f41cc5c1bafafb8fc4b577a4c34f58ca24d60e19
d58c6289d27aca2c728a5095078e6bc623937c5e
refs/heads/master
2022-12-30T23:37:52.748817
2020-10-06T09:21:27
2020-10-06T09:21:27
152,482,182
0
0
MIT
2018-10-10T19:59:15
2018-10-10T19:59:14
null
UTF-8
C++
false
false
550
cpp
max_and_min.cpp
// Program to find maximum and minimum of two numbers without using any loops or conditions #include<bits/stdc++.h> using namespace std; int main () { int first_number , second_number; cout<<"Enter first number : "; cin>> first_number; cout<<"\nEnter second number :"; cin>> second_number; cout<<"\nMaximum of two numbers is : "<<(((first_number + second_number) + abs(first_number - second_number)) / 2); cout<<"\nMinimum of two numbers is :"<<(((first_number + second_number) - abs(first_number - second_number)) / 2); return 0; }
4b3df6d675d1aaeb8e8a0ea3cc5ea1e177047339
05a8ec533c49dfbde253ef109546cea17230d831
/rost_summarizer/src/summarizer.hpp
5d5d71e52ad724885c04d6a176700a17c5cffe65
[]
no_license
mvlvrd/rost-ros
f861f60805e049692742d73e0583b8ff118292cb
e4605d4eb73b83575b89f1762410bf2392465d54
refs/heads/master
2022-04-22T08:26:35.960229
2013-06-13T23:40:00
2013-06-13T23:40:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,772
hpp
summarizer.hpp
#ifndef SUMAMRIZER_203920 #define SUMAMRIZER_203920 #include <iostream> #include <vector> #include <map> #include <cassert> #include <set> #include <limits> #include "boost/tuple/tuple.hpp" #include <cmath> #include <numeric> using namespace std; using namespace boost; template <typename T> class KLDistance{ public: T operator()(const vector<T>& p, const vector<T>& q) const{ // if(p.size() != q.size()){ // cerr<<"p.size()="<<p.size()<<" q.size()="<<q.size()<<endl; // assert(p.size() == q.size()); // } // size_t len = std::min(p.size(), q.size()); //T p_total = std::accumulate(p.begin(), p.begin()+len,0); // T q_total = std::accumulate(q.begin(), q.begin()+len,0); T pv, qv; T d(0); typename vector<T>::const_iterator pi=p.begin(), p_end=p.end(), qi=q.begin(), q_end=q.end(); // for(size_t i=0;i<len; ++i){ // d+= ((p[i]==0 && q[i]==0) ? 0: (p[i]/p_total)*log((p[i]/p_total)/(q[i]/q_total))); // d+= ((p[i]==0 && q[i]==0) ? 0: (p[i]*log(p[i]/q[i]))); // } for(;pi!=p_end && qi!=q_end; ++pi, ++qi){ pv = *pi; qv=*qi; d+= ((pv==0 && qv==0) ? 0: (pv * log(pv/qv ))); } for(;pi!=p_end; ++pi){ pv = *pi; qv=0; d+= ((pv==0 && qv==0) ? 0: (pv * log(pv/qv ))); } for(;qi!=q_end; ++qi){ pv = 0; qv=*qi; d+= ((pv==0 && qv==0) ? 0: (pv * log(pv/qv ))); } if(d<0){ cerr<<"WARNING: dKL="<<d<<endl; //assert(false); d=0; } /* if(d==std::numeric_limits<T>::infinity()){ cerr<<"d=inf"<<endl; copy(p.begin(),p.end(),ostream_iterator<T>(cerr," ")); cerr<<endl; copy(q.begin(),q.end(),ostream_iterator<T>(cerr," ")); cerr<<endl; for(size_t i=0;i<p.size(); ++i){ cerr<<p[i]<<"*log("<<p[i]<<"/"<<q[i]<<")="<<p[i]*log(p[i]/q[i])<<" " ; } cerr<<endl; }*/ return d; } }; template<typename Distance=KLDistance<float> > class Summary{ public: enum ThresholdingStrategy {TH_auto, TH_min, TH_2min, TH_mean, TH_median, TH_doubling}; ThresholdingStrategy thresholding; size_t last_summary_size; typedef vector<float> obs_t; typedef multimap<unsigned int,obs_t > summary_t; typedef multimap<unsigned int,obs_t > observation_set_t; typedef summary_t::iterator iterator; typedef set<unsigned int> uids_t; summary_t summary; //stores the current summary unsigned int K_max; // K_max is the max size of the summary, if set to 0, implies summary size is allowed to increase over time Distance distance; ///distance function used to compute distance between two observations float threshold; //current recommended picking threshold based on the current summary uids_t uids; //stores the unique observation ids currently in the summary Summary(unsigned int K=0, const string& thresholding="auto", const Distance& distance = Distance()); //add observations to the summary void add(const obs_t& topics, size_t id); //add a set of sub_observations, each with the same observation id template<typename ObsIt> void add(ObsIt begin, ObsIt end, size_t id){ for(ObsIt i = begin; i!=end; ++i) summary.insert(make_pair(id, *i)); uids.insert(id); //save the ids. if(K_max>0 && uids.size() > K_max){ trim(); } } void remove(size_t id); bool has(size_t id); tuple<float,unsigned int> surprise(const obs_t& observation); template<typename ObsIt, typename OutSurpIt> tuple<float,unsigned int, ObsIt> surprise(ObsIt begin, ObsIt end, OutSurpIt surp_it){ observation_set_t::iterator it, max_it=summary.end(); ObsIt max_obsit = end; float s = 0, max_s=0; for(ObsIt oit = begin; oit!=end; ++oit){ tie(s,it)=hausdorff(*oit, summary.begin(), summary.end()); *surp_it++ = s; if(s>max_s){ max_it = it; max_s = s; max_obsit = oit; } } return make_tuple(s, max_it->first, max_obsit); } void trim(); size_t num_observation_sets(){ return uids.size(); } void update_threshold(); //retunrs argmin_i dist(o, sum[i]) tuple<float, observation_set_t::iterator> hausdorff(const obs_t& o, observation_set_t::iterator sum_begin, observation_set_t::iterator sum_end) const { summary_t::iterator min_it,it; min_it = it = sum_end; float min_d = numeric_limits<float>::max(); for(it = sum_begin; it!=sum_end; ++it){ float d = distance(it->second, o); if(d<min_d){ //min min_it = it; min_d = d; } } return make_tuple(min_d,min_it); } tuple<float, observation_set_t::iterator> hausdorff(observation_set_t::iterator o_it, observation_set_t::iterator sum_begin, observation_set_t::iterator sum_end) const { summary_t::iterator min_it,it; min_it = it = sum_end; float min_d = numeric_limits<float>::max(); for(it = sum_begin; it!=sum_end; ++it){ if(it->first==o_it->first) continue; //ignore if both have the same observation id float d = distance(it->second, o_it->second); if(d<min_d){ //min min_it = it; min_d = d; } } return make_tuple(min_d,min_it); } /* tuple<float, observation_set_t::iterator> hausdorff(const observation_set_t::iterator& o_it, const observation_set_t & sum) const { return hausdorff(o_it, sum.begin(), sum.end()); } */ //returns argmax_i hausdorff(sum1[i], sum2) tuple<float, observation_set_t::iterator, observation_set_t::iterator> hausdorff(observation_set_t::iterator sum1_begin, observation_set_t::iterator sum1_end, observation_set_t::iterator sum2_begin, observation_set_t::iterator sum2_end){ observation_set_t::iterator max_it,min_it, it1, it2; max_it = sum1_end; min_it = sum2_end; float max_d = 0; float d; for(it1 = sum1_begin; it1!=sum1_end; ++it1){ tie(d, it2) = hausdorff(it1, sum2_begin, sum2_end); if(d >= max_d){ max_it = it1; min_it = it2; max_d = d; } } return make_tuple(max_d, max_it, min_it); } /* tuple<float, observation_set_t::iterator, observation_set_t::iterator> hausdorff(const observation_set_t & sum1, const observation_set_t & sum2){ return hausdorff(sum1.begin(), sum1.end(), sum2.begin(), sum2.end()); }*/ tuple<float, observation_set_t::iterator, observation_set_t::iterator> symmetric_hausdorff(observation_set_t::iterator sum1_begin, observation_set_t::iterator sum1_end, observation_set_t::iterator sum2_begin, observation_set_t::iterator sum2_end){ observation_set_t::iterator left_it1, left_it2, right_it1, right_it2; float d_left, d_right; tie(d_left, left_it1, left_it2) = hausdorff(sum1_begin, sum1_end, sum2_begin, sum2_end); tie(d_right, right_it2, right_it1) = hausdorff(sum2_begin, sum2_end, sum1_begin, sum1_end); return (d_left > d_right)? tie(d_left, left_it1, left_it2) : tie(d_right, right_it1, right_it2); } /* tuple<float, observation_set_t::iterator, observation_set_t::iterator> symmetric_hausdorff(const observation_set_t & sum1, const observation_set_t & sum2){ return symmetric_hausdorff(sum1.begin(), sum1.end(), sum2.begin(), sum2.end()); }*/ }; template<typename Distance> Summary<Distance>::Summary(unsigned int K_, const string& thresholding_, const Distance& distance_): K_max(K_), distance(distance_), threshold(0) { cerr<<"Initialized summarizer with thresholding strategy: "; if(thresholding_ == "2min"){ thresholding = TH_2min; cerr<<"2*min"; } if(thresholding_ == "min"){ thresholding = TH_min; cerr<<"min"; } else if (thresholding_ == "doubling"){ thresholding = TH_doubling; cerr<<"doubling"; } else if (thresholding_ == "mean"){ thresholding = TH_mean; cerr<<"mean"; } else if (thresholding_ == "median"){ thresholding = TH_median; cerr<<"median"; } else{ if(K_max>1){//fixed summary size thresholding = TH_2min; cerr<<"auto=>2*min"; } else{ thresholding = TH_mean; cerr<<"auto=>mean"; } } cerr<<endl; } template<typename Distance> void Summary<Distance>::add(const obs_t& observation, size_t id){ summary.insert(make_pair(id, observation)); uids.insert(id); //save the ids. if(K_max>0 && uids.size() > K_max){ trim(); } } template<typename Distance> void Summary<Distance>::remove(size_t id){ summary.erase(id); uids.erase(id); //save the ids. } template<typename Distance> bool Summary<Distance>::has(size_t id){ if(uids.find(id)!=uids.end()){ //assert(summary.find(id)!=summary.end()); return true; } return false; } template<typename Distance> tuple<float,unsigned int> Summary<Distance>::surprise(const obs_t& observation){ summary_t::iterator it; float s; tie(s,it)=hausdorff(observation, summary.begin(), summary.end()); if(it!=summary.end()){ return make_tuple(s, it->first); } else return make_tuple(0.0f, -1); } template<typename Distance> void Summary<Distance>::trim(){ if(summary.empty()) return; assert(uids.size()>0); unsigned int new_k = uids.size()-1; //keep the last selected image; summary_t::iterator i = summary.end(), i2; float d; --i; summary_t newsum; set<unsigned int> new_uids; newsum.insert(summary.lower_bound(i->first), summary.upper_bound(i->first)); //insert all elemets with key i->first new_uids.insert(i->first); //cerr<<"SumTrim: "<<i->first<<endl; // newsum[i->first]=summary[i->first]; summary.erase(i->first); new_k--; while(new_k>0){ assert(!summary.empty()); tie(d,i,i2) = hausdorff(summary.begin(), summary.end(), newsum.begin(), newsum.end()); newsum.insert(summary.lower_bound(i->first), summary.upper_bound(i->first)); //insert all subsampels with key i-first //cerr<<"SumTrim: "<<i->first<<endl; new_uids.insert(i->first); // newsum[i->first]=i->second; summary.erase(i->first); new_k--; } summary.swap(newsum); uids.swap(new_uids); } template<typename Distance> void Summary<Distance>::update_threshold(){ if(uids.size()<2){ threshold=0; return; } vector<float> dists; float total_d=0; float min_d=std::numeric_limits<float>::max(); //summary_surprise.clear(); vector<float> surprise_scores; // tie(min_d, tuples::ignore, tuples::ignore) = hausdorff(summary.begin(), summary.end(), summary.begin(), summary.end()) for(uids_t::iterator it = uids.begin(); it!=uids.end(); ++it){ float d; summary_t::iterator it1, it2; assert(summary.lower_bound(*it)!=summary.end()); tie(d,it1,it2)=hausdorff(summary.lower_bound(*it), summary.upper_bound(*it), summary.begin(), summary.end()); //cerr<<"surprise score: "<<*it<<" --> "<<d<<endl; surprise_scores.push_back(d); if(d<min_d) min_d = d; total_d+=d; } /* for(summary_t::iterator it = summary.begin(); it!=summary.end(); ++it){ float d; tie(d,tuples::ignore) = hausdorff(it, summary.begin(), summary.end()); surprise_scores.push_back(d); if(d<min_d) min_d = d; total_d+=d; }*/ //cerr<<"Total_d: "<<total_d<<endl; if(uids.size()<K_max && K_max>0){ threshold=0; } else{ switch(thresholding){ case TH_min: threshold= min_d; break; case TH_2min: threshold= min_d*2; break; case TH_doubling: if(uids.size()==2 && threshold==0) threshold = 2*min_d; else if(last_summary_size < uids.size()) threshold *= 2.0; break; case TH_median: sort(surprise_scores.begin(), surprise_scores.end()); threshold = surprise_scores[surprise_scores.size()/2]; break; case TH_mean: default: threshold= total_d/uids.size(); }; } last_summary_size = uids.size(); } #endif
70623e26ce345d8dbf13c192eb5b6119de4f941f
1d3083251b43ee018d540dbd707c2d868c12b6b0
/2.7 Arduino Digital Output/2.7_ExerciseLineBlinkArray/2.7_ExerciseLineBlinkArray.ino
12d6c4b9e12da89ea9f2cd09813cb43f6ee6c9b7
[]
no_license
thinklabph/imakewemake2021
70dea8430e6c0f2c87ed185c5c1d05394dbd7170
aeea7c43249917363c0fb308fe8d22f6adf4e977
refs/heads/main
2023-09-06T09:41:13.427158
2021-11-19T10:10:13
2021-11-19T10:10:13
411,258,890
1
0
null
2021-11-19T10:10:13
2021-09-28T11:45:57
C++
UTF-8
C++
false
false
703
ino
2.7_ExerciseLineBlinkArray.ino
// Line Blink Using Arrays, Code by ThinkLab #define PIN_LED_RED 2 #define PIN_LED_GREEN 3 #define PIN_LED_BLUE 4 #define PIN_LED_YELLOW 5 #define PIN_LED_WHITE 6 int pinLedArray[5] = {PIN_LED_RED, PIN_LED_GREEN, PIN_LED_BLUE, PIN_LED_YELLOW, PIN_LED_WHITE}; void setup() { for (int i = 0; i < 5; i++) { int pin = pinLedArray[i]; pinMode(pin, OUTPUT); } } void loop() { for (int i = 0; i < 5; i++) { int pin = pinLedArray[i]; digitalWrite(pin, HIGH); delay(1000); digitalWrite(pin, LOW); } for (int i = 4; i >= 0; i--) { int pin = pinLedArray[i]; digitalWrite(pin, HIGH); delay(1000); digitalWrite(pin, LOW); } }
262ec11c8067b5fb7fb311da792a3ea4fa74c3a9
a10417092f4e47e98468d8d4f956f73d370e205d
/cs200_intro_to_programming/labs/lab6/task1.cpp
7fbf022f1d48e01b16a14df26b464006b9608b79
[]
no_license
ghanisol/lums
da36e8b052f00104bba35b1eaf51ed0eb2beaf73
0407dbbcf326ee58629de5059eff181ea1ee0f07
refs/heads/master
2020-04-03T09:42:45.386971
2018-10-31T21:59:07
2018-10-31T21:59:07
155,173,951
0
2
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
task1.cpp
#include <iostream> #include <cstdlib> using namespace std; // prototype int* create2DArray(int rows, int columns); void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val); int get(int *arr, int rows, int columns, int desired_row, int desired_column); int main() { int rows = 2, columns = 3; int* ptrToArray = create2DArray(rows, columns); set(ptrToArray, rows, columns, 2, 1, 4); cout << get(ptrToArray, rows, columns, 4, 1); } int* create2DArray(int rows, int columns) { int* ptrToArray; ptrToArray = new int[rows*columns]; return ptrToArray; } void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val) { if (desired_row > rows || desired_column > columns) { cout << "The indexes you gave are invalid" << endl; exit(1); } int index = (desired_row - 1) * columns + (desired_column - 1); arr[index] = val; } int get(int *arr, int rows, int columns, int desired_row, int desired_column) { if (desired_row > rows || desired_column > columns) { cout << "The indexes you gave are invalid" << endl; exit(1); } int index = (desired_row - 1) * columns + (desired_column - 1); return arr[index]; }
d4815d7d8be7265b0d013641546727fdb700d912
e7a8ab3898ef331ca11c63808c4d9449794308c2
/Competitve/C++/Professional Network/Professional Network/main.cpp
e0d29cf27696515ad1f077176efbac14f940465d
[ "MIT" ]
permissive
EdwaRen/Competitve-Programming
615695e00b13bda8024055f9634a7de30534977c
e8bffeb457936d28c75ecfefb5a1f316c15a9b6c
refs/heads/master
2021-06-06T11:23:18.758911
2021-05-29T14:27:04
2021-05-29T14:27:04
97,161,907
1
0
null
null
null
null
UTF-8
C++
false
false
1,001
cpp
main.cpp
// // main.cpp // Professional Network // // Created by - on 2017/06/26. // Copyright ยฉ 2017 Edward Ren-inc. All rights reserved. // #include <iostream> #include <algorithm> #include <array> using namespace std; int getFree(int arr[][2], int A, int n); int main(int argc, const char * argv[]) { int n = 0; cin >> n; int arr[200001][2]; for (int i = 0; i < n; i++) { cin >> arr[i][0]; cin >> arr[i][1]; } int A = 0; A = getFree(arr, 0, n); sort(arr, arr + sizeof(arr) / sizeof(arr[0])); for (int i = 0; i < n; i++) { cout << arr[i][0] << " " << arr[i][1] << endl; } // insert code here... std::cout << "Hello, World!\n"; return 0; } int getFree (int arr[][2], int A, int n) { for (int i = 0; i < n; i++) { if (arr[i][0] <= A) { n--; A +=1; arr[i][0] = 0; i = 0; } } return A; }
56733187b6b99c8b821cc3d0bf5b2e9dc84b708b
80b10a9a27c4db09ea6659be03e9bf7b12e80255
/ๅ›พ่ฎบ/tree/้ž้€’ๅฝ’ๅŽ็ปญ้ๅކ.cpp
bdab5dd119669a7b86a9b9a40f6922a5e8c904ee
[]
no_license
HhTtLllL/algorithm
e1d777672dc8abdac9207ed7ea4b17a4efcbe9f3
4e331cb6dd15d9a6b8ff6ce6b61fa3887a05f9f8
refs/heads/master
2021-09-06T20:50:24.157469
2021-08-11T11:49:41
2021-08-11T11:49:41
203,563,187
3
0
null
null
null
null
UTF-8
C++
false
false
2,041
cpp
้ž้€’ๅฝ’ๅŽ็ปญ้ๅކ.cpp
//################################################################## // File Name: ้ž้€’ๅฝ’ๅŽ็ปญ้ๅކ.c // File Effect: // Author: tttt // mail: tttt@xiyoulinux.org // Created Time: 2019ๅนด11ๆœˆ25ๆ—ฅ ๆ˜ŸๆœŸไธ€ 19ๆ—ถ15ๅˆ†58็ง’ //============================================================= //!/usr/bin/python /*ไบŒๅ‰ๆ ‘็š„้ๅކ* 2011.8.25*/ #include <stdio.h> #include<stdlib.h> #include <stack> using namespace std; typedef char ElemType; typedef struct BiTNode { ElemType data; struct BiTNode * lchild,*rchild; }BiTNode,*BiTree; int CreateBiTree(BiTree *T) { char c; scanf("%c",&c); if('#' == c) { *T = NULL; } else { (*T) = (BiTNode *)malloc(sizeof(BiTNode)); (*T)->data = c; CreateBiTree(&(*T)->lchild); CreateBiTree(&(*T)->rchild); } return 0; } int visit(char c) { printf("%c",c); return 0; } // ๅ‰ๅบ้ๅކ int PreOrderTraverse(BiTree T) { if(T) { visit(T->data); PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); } return 0; } int zhongTraverse(BiTree T) { if(T) { zhongTraverse(T->lchild); visit(T->data); zhongTraverse(T->rchild); } return 0; } int houTraverserse(BiTree T) { if(T) { houTraverserse(T->lchild); houTraverserse(T->rchild); visit(T->data); } return 0; } //ๅŽๅบ้ž้€’ๅฝ’้ๅކ void postOrder(BiTree root) { stack<BiTNode*> s; BiTree cur; BiTree pre = NULL; s.push(root); while(!s.empty()) { cur = s.top(); if((cur->lchild == NULL && cur->rchild == NULL) || (pre != NULL && (pre == cur->lchild || pre == cur->rchild))) { printf("%c",cur->data); s.pop(); pre = cur; } else { if(cur->rchild != NULL) s.push(cur->rchild); if(cur->lchild != NULL) s.push(cur->lchild); } } } int main() { int level = 1; BiTNode *T = NULL; // ๅˆ›ๅปบ ไบŒๅ‰ๆ ‘ CreateBiTree(&T); //่ฆๅฏน T ็š„ๅ†…ๅฎน่ฟ›่กŒๆ›ดๆ”น,ๆ‰€ไปฅ่ฆไผ ๅ…ฅ T็š„ๅœฐๅ€ // ้ๅކ ไบŒๅ‰ๆ ‘ /* PreOrderTraverse(T); puts(" "); zhongTraverse(T); puts(" "); houTraverserse(T); puts(" ");*/ postOrder(T); printf("\n"); return 0; }
8e89a54aaa3af47f12b2a291807a6388bd8a4b88
bed42e15c9acb2cbd8f5fcf700659b4ebaa5791f
/x10abot/x10sions/Thermistor.h
3fb6fe71be441c613a85a6e4beb7e7fc05bf929d
[]
no_license
frazras/mphil-thesis
640c62c101c38b27ecffe270924a2535a25fa936
434ef911f329e2d52ba8e52432a77429de02b1d2
refs/heads/master
2021-06-14T15:34:06.679853
2017-08-30T13:39:13
2017-08-30T13:39:13
38,125,273
2
0
null
null
null
null
UTF-8
C++
false
false
796
h
Thermistor.h
#include "../X10ABOT_MB.h" #include <math.h> class Thermistor: public Sensor { private: byte _db, _port; public: Thermistor(byte db_address, byte port_number):Sensor(_db, _port){ _db = db_address; _port = port_number; } ~Thermistor(){}; double readThermistorCelcius() { //The analog micrcode requests the raw sensor value int RawADC = analog(_db,_port); double Temp; Temp = log(((10240000/RawADC) - 10000)); Temp = 1/(0.001129148+(0.000234125+(0.0000000876741*Temp*Temp))*Temp); Temp = Temp - 273.15; // Convert Kelvin to Celcius return Temp; } double readThermistorFarenheit() { // Convert Celcius to Fahrenheit return (readThermistorCelcius()* 9.0)/ 5.0 + 32.0; } };
cda757c847dd1e4ae9aafdd49b93f52ed43290d9
fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be
/olap/doris/be/src/util/doris_metrics.h
646a4449c0a47fc6928f7afb77117f6dd3e6c456
[ "OpenSSL", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-facebook-patent-rights-2", "PSF-2.0", "dtoa", "MIT", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
alldatacenter/alldata
7bc7713c9f1d56ad6b8e59ea03206d1073b7e047
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
refs/heads/master
2023-08-05T07:32:25.442740
2023-08-03T13:17:24
2023-08-03T13:17:24
213,321,771
774
250
Apache-2.0
2023-09-06T17:35:32
2019-10-07T07:36:18
null
UTF-8
C++
false
false
9,548
h
doris_metrics.h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #pragma once #include <memory> #include <set> #include <string> #include <vector> #include "util/metrics.h" #include "util/system_metrics.h" namespace doris { #define REGISTER_ENTITY_HOOK_METRIC(entity, owner, metric, func) \ owner->metric = (UIntGauge*)(entity->register_metric<UIntGauge>(&METRIC_##metric)); \ entity->register_hook(#metric, [&]() { owner->metric->set_value(func()); }); #define REGISTER_HOOK_METRIC(metric, func) \ REGISTER_ENTITY_HOOK_METRIC(DorisMetrics::instance()->server_entity(), \ DorisMetrics::instance(), metric, func) #define DEREGISTER_ENTITY_HOOK_METRIC(entity, name) \ entity->deregister_metric(&METRIC_##name); \ entity->deregister_hook(#name); #define DEREGISTER_HOOK_METRIC(name) \ DEREGISTER_ENTITY_HOOK_METRIC(DorisMetrics::instance()->server_entity(), name) class DorisMetrics { public: IntCounter* fragment_requests_total; IntCounter* fragment_request_duration_us; IntCounter* query_scan_bytes; IntCounter* query_scan_rows; IntCounter* push_requests_success_total; IntCounter* push_requests_fail_total; IntCounter* push_request_duration_us; IntCounter* push_request_write_bytes; IntCounter* push_request_write_rows; IntCounter* create_tablet_requests_total; IntCounter* create_tablet_requests_failed; IntCounter* drop_tablet_requests_total; IntCounter* report_all_tablets_requests_total; IntCounter* report_all_tablets_requests_failed; IntCounter* report_tablet_requests_total; IntCounter* report_tablet_requests_failed; IntCounter* report_all_tablets_requests_skip; IntCounter* report_disk_requests_total; IntCounter* report_disk_requests_failed; IntCounter* report_task_requests_total; IntCounter* report_task_requests_failed; IntCounter* schema_change_requests_total; IntCounter* schema_change_requests_failed; IntCounter* create_rollup_requests_total; IntCounter* create_rollup_requests_failed; IntCounter* storage_migrate_requests_total; IntCounter* storage_migrate_v2_requests_total; IntCounter* storage_migrate_v2_requests_failed; IntCounter* delete_requests_total; IntCounter* delete_requests_failed; IntCounter* clone_requests_total; IntCounter* clone_requests_failed; IntCounter* alter_inverted_index_requests_total; IntCounter* alter_inverted_index_requests_failed; IntCounter* finish_task_requests_total; IntCounter* finish_task_requests_failed; IntCounter* base_compaction_request_total; IntCounter* base_compaction_request_failed; IntCounter* cumulative_compaction_request_total; IntCounter* cumulative_compaction_request_failed; IntCounter* base_compaction_deltas_total; IntCounter* base_compaction_bytes_total; IntCounter* cumulative_compaction_deltas_total; IntCounter* cumulative_compaction_bytes_total; IntCounter* publish_task_request_total; IntCounter* publish_task_failed_total; IntCounter* meta_write_request_total; IntCounter* meta_write_request_duration_us; IntCounter* meta_read_request_total; IntCounter* meta_read_request_duration_us; // Counters for segment_v2 // ----------------------- // total number of segments read IntCounter* segment_read_total; // total number of rows in queried segments (before index pruning) IntCounter* segment_row_total; IntCounter* stream_load_txn_begin_request_total; IntCounter* stream_load_txn_commit_request_total; IntCounter* stream_load_txn_rollback_request_total; IntCounter* stream_receive_bytes_total; IntCounter* stream_load_rows_total; IntCounter* load_rows; IntCounter* load_bytes; IntCounter* memtable_flush_total; IntCounter* memtable_flush_duration_us; IntGauge* memory_pool_bytes_total; IntGauge* process_thread_num; IntGauge* process_fd_num_used; IntGauge* process_fd_num_limit_soft; IntGauge* process_fd_num_limit_hard; // the max compaction score of all tablets. // Record base and cumulative scores separately, because // we need to get the larger of the two. IntGauge* tablet_cumulative_max_compaction_score; IntGauge* tablet_base_max_compaction_score; IntGauge* all_rowsets_num; IntGauge* all_segments_num; // permits have been used for all compaction tasks IntGauge* compaction_used_permits; // permits required by the compaction task which is waiting for permits IntGauge* compaction_waitting_permits; HistogramMetric* tablet_version_num_distribution; // The following metrics will be calculated // by metric calculator IntGauge* query_scan_bytes_per_second; // Metrics related with file reader/writer IntCounter* local_file_reader_total; IntCounter* s3_file_reader_total; IntCounter* hdfs_file_reader_total; IntCounter* broker_file_reader_total; IntCounter* local_file_writer_total; IntCounter* s3_file_writer_total; IntCounter* file_created_total; IntCounter* s3_file_created_total; IntCounter* local_bytes_read_total; IntCounter* s3_bytes_read_total; IntCounter* local_bytes_written_total; IntCounter* s3_bytes_written_total; IntGauge* local_file_open_reading; IntGauge* s3_file_open_reading; IntGauge* hdfs_file_open_reading; IntGauge* broker_file_open_reading; IntGauge* local_file_open_writing; IntGauge* s3_file_open_writing; // Size of some global containers UIntGauge* rowset_count_generated_and_in_use; UIntGauge* unused_rowsets_count; UIntGauge* broker_count; UIntGauge* data_stream_receiver_count; UIntGauge* fragment_endpoint_count; UIntGauge* active_scan_context_count; UIntGauge* plan_fragment_count; UIntGauge* load_channel_count; UIntGauge* result_buffer_block_count; UIntGauge* result_block_queue_count; UIntGauge* routine_load_task_count; UIntGauge* small_file_cache_count; UIntGauge* stream_load_pipe_count; UIntGauge* new_stream_load_pipe_count; UIntGauge* brpc_endpoint_stub_count; UIntGauge* brpc_function_endpoint_stub_count; UIntGauge* tablet_writer_count; UIntGauge* segcompaction_mem_consumption; UIntGauge* compaction_mem_consumption; UIntGauge* load_mem_consumption; UIntGauge* load_channel_mem_consumption; UIntGauge* query_mem_consumption; UIntGauge* schema_change_mem_consumption; UIntGauge* storage_migration_mem_consumption; UIntGauge* tablet_meta_mem_consumption; // Cache metrics UIntGauge* query_cache_memory_total_byte; UIntGauge* query_cache_sql_total_count; UIntGauge* query_cache_partition_total_count; IntCounter* tablet_schema_cache_count; UIntGauge* tablet_schema_cache_memory_bytes; IntGauge* lru_cache_memory_bytes; UIntGauge* scanner_thread_pool_queue_size; UIntGauge* add_batch_task_queue_size; UIntGauge* send_batch_thread_pool_thread_num; UIntGauge* send_batch_thread_pool_queue_size; UIntGauge* download_cache_thread_pool_thread_num; UIntGauge* download_cache_thread_pool_queue_size; UIntGauge* fragment_thread_pool_queue_size; // Upload metrics UIntGauge* upload_total_byte; IntCounter* upload_rowset_count; IntCounter* upload_fail_count; UIntGauge* light_work_pool_queue_size; UIntGauge* heavy_work_pool_queue_size; UIntGauge* heavy_work_active_threads; UIntGauge* light_work_active_threads; UIntGauge* heavy_work_pool_max_queue_size; UIntGauge* light_work_pool_max_queue_size; UIntGauge* heavy_work_max_threads; UIntGauge* light_work_max_threads; static DorisMetrics* instance() { static DorisMetrics instance; return &instance; } // not thread-safe, call before calling metrics void initialize( bool init_system_metrics = false, const std::set<std::string>& disk_devices = std::set<std::string>(), const std::vector<std::string>& network_interfaces = std::vector<std::string>()); MetricRegistry* metric_registry() { return &_metric_registry; } SystemMetrics* system_metrics() { return _system_metrics.get(); } MetricEntity* server_entity() { return _server_metric_entity.get(); } private: // Don't allow constructor DorisMetrics(); void _update(); void _update_process_thread_num(); void _update_process_fd_num(); private: static const std::string _s_registry_name; static const std::string _s_hook_name; MetricRegistry _metric_registry; std::unique_ptr<SystemMetrics> _system_metrics; std::shared_ptr<MetricEntity> _server_metric_entity; }; }; // namespace doris
cdfe003bffe898d1bcc7a81e7c764c4195568eff
fe851af0193d8d6dce2d7bf0ef44c1da8f8cc31c
/REMember/inc/member.hpp
4fec92c966d193a4c1103a7c1a3b5235f8380df5
[ "BSD-3-Clause" ]
permissive
AirAKose/REMember
d7a23676ad4cb5a6614519f916198a2f1af55071
1248f63acb3a1a0cb7359c97acbb2f487c2caf84
refs/heads/master
2020-12-15T03:59:30.035732
2020-01-20T01:26:00
2020-01-20T01:26:00
234,987,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,921
hpp
member.hpp
#pragma once #include "type_traits.hpp" template<auto Member, auto ... MemPtrList> constexpr inline auto& member_resolve_all(get_member_owner_t<decltype(Member)>* elem) { constexpr std::size_t remaining = get_count<MemPtrList...>::value; if constexpr (remaining == 0) { return elem->*Member; } else { if constexpr (std::is_pointer_v<decltype(elem->*Member)>) { return member_resolve_all<MemPtrList...>(elem->*Member); } else { return member_resolve_all<MemPtrList...>(&(elem->*Member)); } } }; template<auto ... MemberPtrs> class member { static_assert(get_count_v<MemberPtrs...> > 0, "member class requires at least one valid member pointer"); private: using first_type = get_first_type_t<decltype(MemberPtrs)...>; using last_type = get_last_type_t<decltype(MemberPtrs)...>; using root_type = get_member_owner_t<first_type>; public: using type = get_member_type_t<last_type>; using pointer = std::add_pointer_t<type>; using const_pointer = std::add_pointer_t<std::add_const_t<type>>; using reference = std::add_lvalue_reference_t<type>; using const_reference = std::add_const_t<reference>; static constexpr pointer get_ptr(root_type& source) noexcept { return &member_resolve_all<MemberPtrs...>(&source); } static constexpr const_pointer get_ptr(const root_type& source) noexcept { return &member_resolve_all<MemberPtrs...>(&source); } static constexpr reference get_ref(root_type& source) noexcept { return member_resolve_all<MemberPtrs...>(&source); } static constexpr const_reference get_ref(const root_type& source) noexcept { return member_resolve_all<MemberPtrs...>(&source); } constexpr inline reference operator()(root_type& source) noexcept { return get_ref(source); } };
8f6ba410faa31dadbc419802353cd91ed88df8d5
befe2a127a17398eb6b40bbda6d7e4ba63e37318
/Source/cupcakesinspace/Private/ShipObject.cpp
0d2f6b24ef2c6b454b74d8f36ac0e1cf7dd889af
[]
no_license
ndvalenti/cupcakes-in-space
92ebc2ec20b7c30220e7eccf6f7c6709a163b4ed
93063b6781af04f6ea7c445d26ed504011774fd7
refs/heads/master
2023-09-01T01:37:19.101463
2018-04-19T22:33:21
2018-04-19T22:34:05
109,074,231
0
0
null
null
null
null
UTF-8
C++
false
false
4,820
cpp
ShipObject.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ShipObject.h" #include "GameStateManager.h" /*--------------------------PROTECTED FUNCTIONS--------------------------*/ UShipObject::UShipObject() : bSpawned(false) { } void UShipObject::InitializeShip(const FString& Type, const FInt64Vector& InitialPosition, const int32& ShipIndex, const FName& System) { _ShipType = Type; _PreciseShipLocation = InitialPosition; _ShipIndex = ShipIndex; _System = System; UpdateImpreciseLocation(); } void UShipObject::SetDistanceGroup(const EShipDistance ShipDistance) { _ShipDistanceGroup = ShipDistance; } void UShipObject::FlagAsPlayer() { _ShipDistanceGroup = EShipDistance::SH_PLAYER; } void UShipObject::UpdateImpreciseLocation() { _LongShipLocation.X = (_PreciseShipLocation.X / 1798754748); _LongShipLocation.Y = (_PreciseShipLocation.Y / 1798754748); _LongShipLocation.Z = (_PreciseShipLocation.Z / 1798754748); _LongShipLocation /= 100.f; } void UShipObject::SetSystem(FName& In) { _System = In; } /*--------------------------PUBLIC FUNCTIONS--------------------------*/ void UShipObject::GetDistanceGroup(EShipDistance& Out) const { Out = _ShipDistanceGroup; } EShipDistance UShipObject::GetDistanceGroup() const { return _ShipDistanceGroup; } void UShipObject::GetSpawnPositionAndRotation(FVector &OutVector, FRotator &OutRotation) const { /* * Dividing these large floats won't be completely accurate but having a ship's model * possibly spawn at most a few cm (mm in game space) in the wrong direction should go unnoticed * due to the sheer scale of this project and the fact that the local space takes over a ship's logic * once it is close enough to spawn * * Once a final implementation is decided upon this function will be further documented in the header file */ OutVector.X = (float)(_PreciseShipLocation.X - UStaticUtilities::CurrentGlobalOffset().X); OutVector.Y = (float)(_PreciseShipLocation.Y - UStaticUtilities::CurrentGlobalOffset().Y); OutVector.Z = (float)(_PreciseShipLocation.Z - UStaticUtilities::CurrentGlobalOffset().Z); //OutVector /= 10.f; OutRotation = FRotator::ZeroRotator; } EShipDistance UShipObject::CalculateNewDistanceGroup(AGameStateManager* GameStateManager, bool bPlayerExists) const { // This function assumes that the ship in question is in the same system as the player if (bPlayerExists) { FInt64Vector PlayerLocation = UStaticUtilities::CurrentGlobalOffset(); if (_ShipDistanceGroup != EShipDistance::SH_PLAYER && _ShipDistanceGroup != EShipDistance::SH_DOCKED) { if (FVector::Dist(_LongShipLocation, UStaticUtilities::ConvertPreciseToImpreciseDistance(PlayerLocation)) >= UStaticUtilities::FarCheckDistance()) { return EShipDistance::SH_FAR; } else { if (FInt64Vector::Distance(PlayerLocation, _PreciseShipLocation) >= UStaticUtilities::SpawnCheckDistance()) { return EShipDistance::SH_NEAR; } else { return EShipDistance::SH_LOCAL; } } } // This ship's distance group will not change return _ShipDistanceGroup; } return EShipDistance::SH_EXTERNAL; } void UShipObject::GetPreciseLocation(FInt64Vector& Out) const { Out = _PreciseShipLocation; } void UShipObject::GetShipIndex(int32& Out) const { Out = _ShipIndex; } void UShipObject::GetImpreciseLocation(FVector& Out) const { Out = _LongShipLocation; } void UShipObject::GetShipType(FString& Out) const { Out = _ShipType; } void UShipObject::GetShipSystem(FName& Out) const { Out = _System; } FString UShipObject::GetDisplayDistanceTo(const FInt64Vector& From) const { /*Maybe a good idea*/ //UpdateFarLocation(); float Distance = FVector::Dist(_LongShipLocation, UStaticUtilities::ConvertPreciseToImpreciseDistance(From)); if (Distance >= 0.01f) { return GetFloatAsString(Distance, 2).Append(FString(TEXT(" lm"))); } else { Distance = FInt64Vector::Distance(From, _PreciseShipLocation); if (Distance > 10000) { Distance /= 100000; return GetFloatAsString(Distance, 2).Append(FString(TEXT(" km"))); } else { Distance /= 100; return GetFloatAsString(Distance, 0).Append(FString(TEXT(" m"))); } } } FString UShipObject::GetFloatAsString(float Number, const int32 Precision) const { float Rounded = roundf(Number); if (FMath::Abs(Number - Rounded) < FMath::Pow(10, -1 * Precision)) { Number = Rounded; } FNumberFormattingOptions NumberFormat; //Text.h NumberFormat.MinimumIntegralDigits = 1; NumberFormat.MaximumIntegralDigits = 10000; NumberFormat.MinimumFractionalDigits = Precision; NumberFormat.MaximumFractionalDigits = Precision; return FText::AsNumber(Number, &NumberFormat).ToString(); } void UShipObject::TeleportToPreciseLocation(const FInt64Vector& Destination) { _PreciseShipLocation = Destination; }
44fdcef4e7ce914bd9b836ed1b2291d58c0c0771
9d62bcbd0e6f4ce943d19e6ae13b4c2e70fed55d
/xeyes/x_eyes_main.cpp
b3e3c8b9794eaad408054217902ece49ccb28288
[]
no_license
stenniswood/bk_code
87ce26e032c1f1895c1c557c4e2ba4465a61b438
13535863decc23414854c08ebf8fc90c06a92fbd
refs/heads/master
2021-07-05T21:25:37.512024
2021-06-02T08:01:40
2021-06-02T08:01:40
25,167,429
0
0
null
null
null
null
UTF-8
C++
false
false
6,067
cpp
x_eyes_main.cpp
#include <cstdio> #include <string.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include <sys/stat.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> #include <signal.h> #include "x_eyes.hpp" #include "serial.hpp" #include "mouse.h" #include "vision_memory.h" #include "roboclaw.h" #include "face_detect.hpp" #include "face_recog.hpp" #include "face_summary.hpp" #include "neck_thread.hpp" #include "vision_logger.hpp" #include "cal_screen.hpp" #include "optical_flow.hpp" #include "misc_detect.hpp" #include "key_config.hpp" #include "frame_grabber.hpp" #include "nlp_thread.hpp" #include "tk_colors.h" #include "image_proc_misc.hpp" #include "vision_logger.hpp" #include "viki_logger.hpp" #include "plot.hpp" int device_number; const int ScreenWidth = 1280; const int ScreenHeight = 1080; pthread_t serial_thread_id = 1; pthread_t nlp_thread_id = 3; pthread_t roboclaw_thread_id = 2; bool MOVE_TO_MOUSE = false; bool CameraAvailable = false; bool EyeServoBoardAvailable = false; bool NeckServoBoardAvailable = false; static volatile int keepRunning = 1; void app_close_handler(int dummy) { keepRunning = 0; sql_logger.sql_add_system_deactivated(); mouse_close( ); fd_close ( ); frame_grab_close(); exit(1); } void create_thread() { // PWM Board: int iret1 = pthread_create( &serial_thread_id, NULL, serial_setup, (void*) NULL); if (iret1) { fprintf(stderr,"Error - Could not create Servo PWM Interface thread. return code: %d\n",iret1); } // NLP Task: int iret3 = pthread_create( &nlp_thread_id, NULL, nlp_handler, (void*) NULL); if (iret3) { fprintf(stderr,"Error - Could not create NLP handler thread. return code: %d\n",iret1); } // RoboClaw board: int iret2 = pthread_create( &roboclaw_thread_id, NULL, neck_thread, (void*) NULL); if (iret2) { fprintf(stderr,"Error - Could not create RoboClaw Interface thread. return code: %d\n",iret2); } } void init() { mkdir("/home/pi/Pictures/face_recog", S_IRWXU); mkdir("/home/pi/Pictures/robot", S_IRWXU); mkdir("/home/pi/Pictures/robot/detected_faces", S_IRWXU); eye_init(); init_gpio(); sql_logger.connect_to_logger_db(); sql_logger.create_events_table(); sql_logger.sql_add_system_activated( CameraAvailable, EyeServoBoardAvailable, NeckServoBoardAvailable); // Initialize Vision Shared Memory (to abkInstant) int ipc_mem = eyes_connect_shared_memory( 1 ); // FACE RECOGNITION INIT (load model or train): bool needs_training = (does_model_exist()==false); if (needs_training) { string fn_csv = "train.csv"; //printf("Training Face Recognition model...\n"); //train_model( fn_csv ); } else { //printf("Loading Face Recognition model...\n"); //open_model ( FaceRecogModelName ); } //capture.open("/Users/stephentenniswood/Movies/iMovie Library.imovielibrary/My Movie/Original Media/2016-07-24 15_47_08.mov"); //2016-07-24 15_45_46.mov create_thread(); int face_okay = fd_init(); int misc_okay = misc_detect_init(); int r = mouse_init( ScreenWidth, ScreenHeight ); frame_grab_init( device_number ); printf("init() done\n"); //sql_logger.connect_to_logger_db(); } void handle_arguments(int argc, char ** argv) { string fn_csv = "train.csv"; string filename; if ((strcmp(argv[1],"train")==0)) { printf("Training Face Recognition model...\n"); train_model( fn_csv ); exit( EXIT_SUCCESS ); } else if ((strcmp(argv[1],"recog")==0)) { bool needs_training = (does_model_exist()==false); if (needs_training) printf("Face Recognition model NEEDS TRAINING...\n"); else { printf("Loading Face Recognition model...\n"); open_model ( FaceRecogModelName, fn_csv ); } } else if ((strcmp(argv[1],"show")==0)) { filename = "/home/pi/Pictures/face_recog/"; filename += argv[2]; filename += "/"; show_person_faces( filename.c_str() ); //result = show_person_faces("/home/pi/Pictures/face_recog/s10/"); } else if ((strcmp(argv[1],"mouse")==0)) { MOVE_TO_MOUSE = 1; } else if ((strcmp(argv[1],"shrink")==0)) { filename = "/home/pi/Pictures/face_recog/"; filename += argv[2]; filename += "/"; make_training_size( filename ); exit( EXIT_SUCCESS ); } else if ((strcmp(argv[1],"cam")==0)) { device_number = atoi( argv[2] ); } } /* Components of this app: Opencv - Face detector webcam Serial comms to PWM board. Serial comms to roboClaw board. IPC Vision Shared Memory. */ int main(int argc, char ** argv) { int result=0; char* ptr; bool unrecognized = false; if (argc>1) { print_args( argc,argv ); handle_arguments(argc,argv); } // delete_all_shm(); //nlp_test(); //test_viki_logger(); //test_face_summary(); //exit(1); init(); signal(SIGINT, app_close_handler ); text_to_speech_pico( "Welcome, my name is ronny."); //text_to_speech_festival( "Welcome, my name is ronny."); while (1) { mouse_timeslice( ); frame_grabs ( ); process_frames ( ); plot(cv_depth); if (MOVE_TO_MOUSE) { mover_x = trunc( mouse.x ); // Overwrite values assign in process_frames() mover_y = trunc( mouse.y ); mover_width = ScreenWidth; } // CONTROL : printf("mover x,y= %d,%d\r", mover_x, mover_y ); update_neck_angle ( mover_x, mover_width, num_faces_present ); update_eye_positions( mover_x, (mover_height-mover_y), mover_width, mover_height ); // SHOW & CAPTURE : /* Several Events can trigger an image write (unknown face_detect for several frames, or a motion detect, etc) */ if (capture_frame) // Save image to disk. { char* fn = get_new_frame_captured_filename(); imwrite(fn, frame /* see face_detect.cpp */ ); } imshow ( main_window_name, original ); //imshow( "gray", gray_frame ); // USER CONTROL : int c = cv::waitKey( 10 ); handle_key_controls( c ); // Signal NLP (any events) : //eyes_write_server_event( message ); } return 1; }
d6542919c9c8d5ee3ff9f0e10e510e6adbddf5c8
f01336c57bede29b6d51389c0addbab149e527a3
/src/application.h
da894e914785c06d9f1dd801a02d781deeba682f
[]
no_license
evgeny-averin/qmlcomponents
2e985db970f77c95c625605d9bac5c9353ca2e14
e30ab5adbbe2b00ce95553266a958d5a6d361a43
refs/heads/master
2016-09-11T10:26:50.974567
2015-07-03T15:49:31
2015-07-03T15:49:31
30,933,413
1
1
null
null
null
null
UTF-8
C++
false
false
7,115
h
application.h
#pragma once #include <QApplication> #include <QtQuick> #include <QFileSystemWatcher> #include <QDesktopWidget> #include <QResource> #include <QQuickView> #include <QQmlEngine> #include <QQmlContext> #include <QDebug> #include <QEventLoop> #include <QTimer> #include <QOrientationSensor> #include <QOrientationFilter> #include <chrono> #include "convenience.h" #include "physics.h" #ifdef Q_OS_ANDROID #include <QtAndroid> #include <QAndroidJniObject> #include <QAndroidJniEnvironment> #include "runnable.h" #endif class Application: public QObject { Q_OBJECT Q_PROPERTY_DEF(qreal, screenWidth, screenWidth, setScreenWidth, 600) Q_PROPERTY_DEF(qreal, screenHeight, screenHeight, setScreenHeight, 800) Q_PROPERTY_DEF(qreal, scaleX, scaleX, setScaleX, 1.) Q_PROPERTY_DEF(qreal, scaleY, scaleY, setScaleY, 1.) Q_PROPERTY_DEF(qreal, scale, scale, setScale, 1.) Q_PROPERTY_DEF(QString, path, path, setPath, QGuiApplication::applicationFilePath()) Q_PROPERTY_DEF(QString, dir, dir, setDir, QGuiApplication::applicationDirPath() + QDir::separator()) Q_PROPERTY_DEF(QString, speechResult, speechResult, setSpeechResult, "") Q_PROPERTY_DEF(QString, name, name, setName, "") Q_PROPERTY(QString mediaPath READ mediaPath NOTIFY mediaPathChanged) public: Application(const QString &name, QObject *parent = nullptr) : QObject(parent) , _name(name) { #ifdef DEVELOPER_BUILD _watcher.addPath("/sdcard/Develop/flag/resource.lck"); _watcher.addPath("/sdcard/Develop/flag/"); connect(&_watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(reloadResources())); connect(&_watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(reloadResources())); if(!QResource::registerResource("/sdcard/Develop/main.rcc")) { qDebug() << "Failed to load main.rcc"; } #endif // Install translator with system locale auto translator = new QTranslator(this); QString path = QString(":/translations/stock-browser-%1.qm"). arg(QLocale::system().name()); if (translator->load(path)) { QApplication::installTranslator(translator); qDebug() << "Loaded translation file from " << path; } else { qWarning() << "Failed to load translation file from " << path; } _view.setSurfaceType(QSurface::OpenGLSurface); QSurfaceFormat format; format.setAlphaBufferSize(8); format.setRenderableType(QSurfaceFormat::OpenGLES); _view.setFormat(format); _view.setColor(QColor(Qt::transparent)); _view.setClearBeforeRendering(true); _view.engine()->rootContext()->setContextProperty("application", this); _view.engine()->rootContext()->setContextProperty("world", World::instance()); _view.engine()->setOfflineStoragePath(mediaPath() + "dictionaries.db"); _view.setResizeMode(QQuickView::SizeRootObjectToView); _view.setSource(QUrl(QStringLiteral("qrc:////main.qml"))); _view.show(); _view.installEventFilter(this); _speech_pull_timer.setInterval(500); connect(this, SIGNAL(screenWidthChanged (qreal)), this, SLOT(onScreenWidthChanged (qreal))); connect(this, SIGNAL(screenHeightChanged(qreal)), this, SLOT(onScreenHeightChanged(qreal))); connect(_view.engine(), SIGNAL(quit()), this, SIGNAL(quit())); #ifdef Q_OS_ANDROID connect(&_speech_pull_timer, SIGNAL(timeout()), this, SLOT(pullRecognitionResult())); #endif } int exec() { while(_view.isVisible()) { _event_loop.processEvents(QEventLoop::WaitForMoreEvents); } return 0; } Q_SLOT void reloadResources() { QResource::unregisterResource("/sdcard/Develop/main.rcc"); QResource::registerResource("/sdcard/Develop/main.rcc"); _view.engine()->clearComponentCache(); _view.setSource(QUrl(QStringLiteral("qrc:////main.qml"))); qDebug() << "Resources reloaded sucessfully"; } Q_SLOT void onScreenWidthChanged(qreal width) { setScaleX(width / 600); setScale(_scaleX); } Q_SLOT void onScreenHeightChanged(qreal height) { setScaleY(height / 800); setScale(_scaleX); } Q_SLOT QString mediaPath() { #ifdef Q_OS_ANDROID QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" ); QString dataAbsPath = mediaPath.toString() + "/" + _name + "/"; QDir dir(dataAbsPath); if(!dir.exists()) { dir.cdUp(); dir.mkdir("pretty-dictionary"); } return dataAbsPath; #else return dir(); #endif } Q_SLOT void clearComponentCache() { _view.engine()->clearComponentCache(); } Q_SLOT void trimComponentCache() { _view.engine()->trimComponentCache(); } #ifdef Q_OS_ANDROID Q_SLOT void showAdvertizing() { QAndroidJniObject::callStaticMethod<void>("org/qtproject/example/admobqt/AdMobQtActivity", "showAd"); } Q_SLOT void hideAdvertizing() { QAndroidJniObject::callStaticMethod<void>("org/qtproject/example/admobqt/AdMobQtActivity", "hideAd"); } Q_SLOT void recognizeSpeech() { setSpeechResult(""); QtAndroidRunner *runner = QtAndroidRunner::instance(); runner->start(new SpeechInitializer()); _speech_pull_timer.start(500); } Q_SLOT void pullRecognitionResult() { QtAndroidRunner *runner = QtAndroidRunner::instance(); auto *speech_feedback = new SpeechFeedback(); connect(speech_feedback, SIGNAL(resultPulled(QString)), this, SLOT(setSpeechResult(QString))); runner->start(speech_feedback); } #endif Q_SLOT QString formatDate(const QDateTime &dt, const QString &fmt) { return dt.toString(fmt); } Q_SLOT void quit() { QAndroidJniObject::callStaticMethod<void>("org/qtproject/eaverin/stock/browser/AdMobQtActivity", "quit"); } bool eventFilter(QObject *obj, QEvent *event) override { if (event->type() == QEvent::KeyPress) { auto keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Backspace) { emit backspacePressed(); return true; } } return QObject::eventFilter(obj, event); } Q_SIGNAL void worldChanged(); Q_SIGNAL void mediaPathChanged(); Q_SIGNAL void backspacePressed(); private: QEventLoop _event_loop; QQuickView _view; QFileSystemWatcher _watcher; QTimer _speech_pull_timer; };
e713ee267ec40b21117705b834fc8d4ed9207692
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/libs/Spdb/src/WxHazards/ConvRegionHazard.cc
5ed851faf471b7d13fef092a0331c5b29bcaec5c
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
8,776
cc
ConvRegionHazard.cc
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) 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. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* /********************************************************************* * ConvRegionHazard.cc: Class representing a convective region hazard. * * RAP, NCAR, Boulder CO * * June 1999 * * Nancy Rehak * *********************************************************************/ #include <cstdio> #include <unistd.h> #include <vector> #include <dataport/bigend.h> #include <dataport/port_types.h> #include <euclid/WorldPoint2D.hh> #include <euclid/WorldPolygon2D.hh> #include <Spdb/ConvRegionHazard.hh> #include <Spdb/WxHazard.hh> using namespace std; // Global variables /********************************************************************* * Constructor - Creates a ConvRegionHazard from the given information. */ ConvRegionHazard::ConvRegionHazard(double top, double speed, double direction, bool debug_flag) : WxHazard(WxHazard::CONVECTIVE_REGION_HAZARD, debug_flag) { _debugFlag = debug_flag; // Create the polygon object _polygon = new WorldPolygon2D(); // Initialize the region information _top = top; _speed = speed; _direction = direction; } /********************************************************************* * Constructor - Creates a ConvRegionHazard from the given SPDB buffer. */ ConvRegionHazard::ConvRegionHazard(void *buffer, bool debug_flag) : WxHazard(WxHazard::CONVECTIVE_REGION_HAZARD, debug_flag) { ui08 *buffer_ptr = (ui08 *)buffer; // Create the polygon object _polygon = new WorldPolygon2D(); // Skip the hazard header buffer_ptr += sizeof(spdb_hazard_header_t); // Get the needed information from the conv hazard header spdb_header_t *header = (spdb_header_t *)buffer_ptr; _spdbHeaderToNative(header); _top = header->top; _speed = header->speed; _direction = header->direction; buffer_ptr += sizeof(spdb_header_t); // Get the polygon points from the buffer for (int i = 0; i < header->num_polygon_pts; i++) { point_t *point = (point_t *)buffer_ptr; _spdbPointToNative(point); WorldPoint2D *world_point = new WorldPoint2D(point->lat, point->lon); _polygon->addPoint(world_point); buffer_ptr += sizeof(point_t); } } /********************************************************************* * Destructor */ ConvRegionHazard::~ConvRegionHazard() { // Reclaim the space for the polygon delete _polygon; } /********************************************************************* * addPoint() - Add the given point to the end of the region polygon. * * Note that the pointer to this point is saved for the polygon so you * must not change the point value or delete the point object after * calling this routine. */ void ConvRegionHazard::addPoint(WorldPoint2D *point) { _polygon->addPoint(point); } /********************************************************************* * getSpdbNumBytes() - Retrieve the number of bytes occupied by this * hazard when stored in an SPDB database. */ int ConvRegionHazard::getSpdbNumBytes(void) const { int num_bytes = sizeof(spdb_hazard_header_t) + sizeof(spdb_header_t); if (_polygon == (WorldPolygon2D *)NULL) return num_bytes; num_bytes += _polygon->getNumPoints() * sizeof(point_t); return num_bytes; } /********************************************************************* * print() - Print the hazard information to the given stream. */ void ConvRegionHazard::print(FILE *stream) const { fprintf(stream, "Convective Region Hazard:\n"); if (_debugFlag) { fprintf(stream, " debugging on\n"); } fprintf(stream, " top = %f feet\n", _top); fprintf(stream, " speed = %f\n", _speed); fprintf(stream, " direction = %f\n", _direction); fprintf(stream, " polygon points:\n"); for (WorldPoint2D *point = _polygon->getFirstPoint(); point != (WorldPoint2D *)NULL; point = _polygon->getNextPoint()) fprintf(stream, " %f %f\n", point->lat, point->lon); } /********************************************************************* * writeSpdb() - Write the hazard information to the given buffer in * SPDB format. * * Note that the calling routine must call getSpdbNumBytes() and allocate * a large enough buffer before calling this routine. */ void ConvRegionHazard::writeSpdb(ui08 *buffer) const { // Write the header information ui08 *buffer_ptr = (ui08 *)buffer; spdb_hazard_header_t *hazard_header = (spdb_hazard_header_t *)buffer_ptr; hazard_header->hazard_type = CONVECTIVE_REGION_HAZARD; hazard_header->spare = 0; spdbHazardHeaderToBigend(hazard_header); buffer_ptr += sizeof(spdb_hazard_header_t); spdb_header_t *header = (spdb_header_t *)buffer_ptr; header->top = _top; header->speed = _speed; header->direction = _direction; header->spare_fl32 = 0.0; header->spare_si32 = 0; if (_polygon == (WorldPolygon2D *)NULL) { header->num_polygon_pts = 0; return; } header->num_polygon_pts = _polygon->getNumPoints(); _spdbHeaderToBigend(header); buffer_ptr += sizeof(spdb_header_t); // Save the polygon points for (WorldPoint2D *point = _polygon->getFirstPoint(); point != (WorldPoint2D *)NULL; point = _polygon->getNextPoint()) { point_t *point_ptr = (point_t *)buffer_ptr; point_ptr->lat = point->lat; point_ptr->lon = point->lon; _spdbPointToBigend(point_ptr); buffer_ptr += sizeof(point_t); } } /********************************************************************** * Private Member Functions * **********************************************************************/ /********************************************************************* * _spdbHeaderToBigend() - Swaps the spdb_header_t structure from * native format to big-endian format. */ void ConvRegionHazard::_spdbHeaderToBigend(spdb_header_t *header) { BE_from_array_32(header, sizeof(spdb_header_t)); } /********************************************************************* * _spdbHeaderToNative() - Swaps the spdb_header_t structure from * big-endian format to native format. */ void ConvRegionHazard::_spdbHeaderToNative(spdb_header_t *header) { BE_to_array_32(header, sizeof(spdb_header_t)); } /********************************************************************* * _spdbPointToBigend() - Swaps the point_t structure from native * format to big-endian format. */ void ConvRegionHazard::_spdbPointToBigend(point_t *point) { BE_from_array_32(point, sizeof(point_t)); } /********************************************************************* * _spdbPointToNative() - Swaps the point_t structure from big-endian * format to native format. */ void ConvRegionHazard::_spdbPointToNative(point_t *point) { BE_to_array_32(point, sizeof(point_t)); }
1580d1b7b230009d7c2ab199a450092d1f54740b
29a2842e6ff3de92e7faf10e87fe634793d4f94e
/lab/assign5/Ass5_8_18CS10067_18CS10062_thread.cpp
2783561da7c1f7c583a3e992bff5b34301c548c1
[]
no_license
rsrkpatwari1234/Operating-System
db1d967dacdd0d48829608194cedf96a1d762e98
e6b4ccd912f0913d1fc94a95cdbc46cdfe78e33b
refs/heads/main
2023-04-04T11:02:58.857512
2021-04-15T05:27:03
2021-04-15T05:27:03
336,598,989
1
0
null
null
null
null
UTF-8
C++
false
false
8,673
cpp
Ass5_8_18CS10067_18CS10062_thread.cpp
// Atharva Naik, 18CS10067 // Radhika Patwari, 18CS10062 // Assignment 5 // Part 2 #include <fcntl.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <pthread.h> #include <sys/wait.h> #include <sys/types.h> #include <bits/stdc++.h> // ranges of process variables #define MIN_PRIORITY 1 #define MAX_PRIORITY 10 #define MIN_JOB_ID 1 #define MAX_JOB_ID 100000 #define MIN_COMPUTE_TIME 1 #define MAX_COMPUTE_TIME 4 #define MIN_SLEEP_TIME 1000000 // in microseconds #define MAX_SLEEP_TIME 3000000 // in microseconds using namespace std; // check if mutex is defined/suported in the system #ifndef _POSIX_THREAD_PROCESS_SHARED #error No definition found for mutex exit(EXIT_FAILURE); #endif const int QUEUE_SIZE = 8; pthread_mutex_t *mutex_ptr; // pointer to mutex pthread_mutexattr_t mutex_attr; // mutex attribute struct process_t{ int pid; // process id int producer_number; // process number corresponding to no. of producers int priority; // priority of the number ( between 1 and 10 ) int compute_time; // the compute time int jid; // the job id }; // comparing priority of jobs while inserting them in priority queue of the buffer // insert : O(log QUEUE_SIZE) ; delete and rearrangement : O(log QUEUE_SIZE) struct ComparePriority { bool operator()(process_t const& job1, process_t const& job2) { // return "true" if "job1" is ordered // before "job2", ensures job with highest priority is // at the top of the heap (max heap implementation) return job1.priority < job2.priority; } }; struct process_queue_buffer{ int size; // current buffer size (number of elements stored in buffer currently) int job_created; // number of jobs created int job_completed; // number of jobs completed pthread_mutex_t mutex; // mutex priority_queue<process_t, vector<process_t>, ComparePriority> process_queue; // priority queue of processes }; process_queue_buffer* buffer = new process_queue_buffer; int NJOBS, producer_count = 0, consumer_count = 0; // populate process structure with given pid and producer number process_t create_job(int pid, int producer_number) { //srand(pid*time(0)); // seed random number generator with the pid process_t job; // create process structure // populate data members of the process job.pid = pid; job.producer_number = producer_number; job.priority = rand() % MAX_PRIORITY + MIN_PRIORITY; // value ranges from 1 to 10 job.compute_time = rand() % MAX_COMPUTE_TIME + MIN_COMPUTE_TIME; // value ranges from 1 to 4 job.jid = rand() % MAX_JOB_ID + MIN_JOB_ID; // value ranges from 1 to 100000 return job; } // inserting job in the priority queue such that job with highest priority is at the root // of the max heap void insert_in_buffer(process_t job) { (buffer->process_queue).push(job); // pushing job in priority queue (buffer->size)++; // increment buffer sizes } // remove job with maximum priority value as it is consumed by one of the consumers process_t remove_from_buffer() { process_t job_with_max_priority = (buffer->process_queue).top(); (buffer->process_queue).pop(); // popping the max priority job (buffer->size)--; // reduce size (number of processes present in buffer) cout<<"\x1b[44;1m Killing job of priority ="<<job_with_max_priority.priority<<" \x1b[0m"<<endl; // #REMOVE#l; return job_with_max_priority; } void *producer_task(void *param){ int producer_num = producer_count; producer_count++; // producer code while (1) { process_t job = create_job(getpid(), producer_num); usleep(rand() % MAX_SLEEP_TIME); pthread_mutex_lock(mutex_ptr); // check if more jobs are to be crated and buffer has remaining space if ((buffer->job_created) < NJOBS && buffer->size < QUEUE_SIZE) { insert_in_buffer(job); (buffer->job_created)++; cout << "\x1b[34;1mProducer: " << producer_num << "\x1b[0m\x1b[32m pid=" << getpid() << ", priority=" << (job.priority) << ", jid=" << job.jid << ", compute_time=" << job.compute_time << ";\x1b[0m" << endl; cout<<"jobs_completed="<<(buffer->job_completed)<<", jobs_created="<< buffer->job_created << ";" << endl; pthread_mutex_unlock(mutex_ptr); // unlock mutex } // check if buffer is full else if (buffer->size >= QUEUE_SIZE) { cout<<"\x1b[34;1mProducer: "<< producer_num <<"\x1b[0m\x1b[33m Waiting, (queue full)\x1b[0m"<<endl; pthread_mutex_unlock(mutex_ptr); // unlock mutex usleep(MIN_SLEEP_TIME); // sleep } // all jobs have been created else { cout << "\x1b[31;1mKilling Producer: " << producer_num << "\x1b[0m" << endl; pthread_mutex_unlock(mutex_ptr); pthread_exit(0); } } } void *consumer_task(void *param){ int consumer_num = consumer_count; consumer_count++; // consumer code while (1) { pthread_mutex_lock(mutex_ptr); // lock mutex if (buffer->job_completed < NJOBS && buffer->size > 0) { process_t job = remove_from_buffer(); // get new job from buffer (buffer->job_completed)++; cout << "\x1b[37m\x1b[7m\x1b[1m<JOB>\x1b(B\x1b[m " << "\x1b[34;1mConsumer: " << consumer_num << "\x1b[0m\x1b[32m pid=" << getpid() << ";\x1b[0m" << " consumed " << "\x1b[34;1mProducer: " << job.producer_number << "\x1b[0m\x1b[32m pid= " << job.pid << ", priority=" << (job.priority) << " jid=" << job.jid << " compute_time=" << job.compute_time << ";\x1b[0m \x1b[37m\x1b[7m\x1b[1m</JOB>\x1b(B\x1b[m" << endl; cout << "jobs_completed=" << (buffer->job_completed) << ", jobs_created=" << buffer->job_created << ";" << endl; pthread_mutex_unlock(mutex_ptr); usleep(job.compute_time * MIN_SLEEP_TIME); } // check if all jobs have been consumed else if (buffer->job_completed >= NJOBS) { cout << "\x1b[31;1mKilling Consumer: " << consumer_num << "\x1b[0m" <<endl; pthread_mutex_unlock(mutex_ptr); // unlock mutex pthread_exit(0); } // no process in buffer, but more processes will be created (number of jobs created is less than NJOBS) else { cout<<"\x1b[34;1mConsumer: "<< consumer_num <<"\x1b[0m\x1b[33m Waiting, (queue empty)\x1b[0m"<<endl; pthread_mutex_unlock(mutex_ptr); // unlock mutex usleep(MIN_SLEEP_TIME); } } } int main() { int i, NC, NP; cout << "number of producers="; cin >> NP; cout << "number of consumers="; cin >> NC; cout << "number of jobs="; cin >> NJOBS; buffer->size = 0; buffer->job_created=0; buffer->job_completed = 0; mutex_ptr = &(buffer->mutex); int error_code; // setup mutex and catch any errors that might occur if (error_code = pthread_mutexattr_init(&mutex_attr)) { fprintf(stderr,"pthread_mutexattr_init: %s", strerror(error_code)); exit(EXIT_FAILURE); } if (error_code = pthread_mutexattr_setpshared(&mutex_attr,PTHREAD_PROCESS_SHARED)) { fprintf(stderr,"pthread_mutexattr_setpshared %s",strerror(error_code)); exit(EXIT_FAILURE); } if (error_code = pthread_mutex_init(mutex_ptr, &mutex_attr)) { fprintf(stderr,"pthread_mutex_init %s",strerror(error_code)); exit(EXIT_FAILURE); } time_t start_time = time(NULL); pthread_t producer_thread[NP]; pthread_t consumer_thread[NC]; pthread_attr_t attr; pthread_attr_init (&attr); // get default attributes //cout<<"start creating producers...."<<endl; // create producer threads for (int i = 0; i < NP; i++){ pthread_create(&producer_thread[i], &attr, producer_task, &producer_thread[i]); // create the thread //cout<<"\n"<<producer_thread[i]<<endl; } //cout<<"start creating consumers...."<<endl; // create consumer threads for (i = 0; i < NC; i++) pthread_create(&consumer_thread[i], &attr, consumer_task, NULL); // create the thread // join producer threads (kill them) for (i = 0; i < NP; i++) pthread_join(producer_thread[i], NULL); //wait for the threads to exit // join consumer threads (kill them) for (i = 0; i < NC; i++) pthread_join(consumer_thread[i], NULL); //wait for the threads to exit time_t end_time = time(NULL); cout << "\x1b[37m\x1b[7m\x1b[1m time_elapsed=" << end_time - start_time << " \x1b(B\x1b[m" << endl; return 0; }
d59d1780163284a2fa4ebe5a248e7e8b662a9dd6
b02cd8b9d9f53f51b4749c0aec90b946699e3a75
/binary_search_tree.cpp
e03fc464666eaea51716de2e4ce45a62b04331c0
[]
no_license
tanvidadu/TextEditor
788b4649494c1529cc0dc06d471ad7d8456bc22d
0693c9e82547f98c0f274f32268bed2e909f08a5
refs/heads/master
2021-07-10T02:24:25.344122
2017-10-08T17:37:30
2017-10-08T17:37:30
106,196,291
1
0
null
null
null
null
UTF-8
C++
false
false
5,250
cpp
binary_search_tree.cpp
#include<bits/stdc++.h> using namespace std; class Treenode { public: int info; Treenode * left; Treenode * right; Treenode(int d) { info = d; left = right = NULL; } }; Treenode* Search ( Treenode * root , int ele , int mode = 0 ); class Tree { public: Treenode * root; Tree() { root = NULL; } void Insert ( int ele) { Treenode * temp = new Treenode(ele); if( root == NULL) { root = temp; } else { Treenode * par = Search( root , ele , 1); { if( par->info > ele) { par->left = temp; } else { par->right = temp; } } } } void DeleteA ( Treenode * temp , Treenode * par ) { Treenode * child; if(temp-> left == NULL && temp-> right == NULL) { child = NULL; } else if ( temp-> left == NULL ) { child = temp->right; } else if ( temp-> right == NULL) { child = temp->left; } if( par == NULL) { root = child; } else { if( par-> left == temp) { par->left = child; } else { par->right = child; } } } void DeleteB ( Treenode * ptr , Treenode * par ) { Treenode * suc , * sucpar; suc = ptr->right; sucpar = ptr; while( suc->left != NULL) { sucpar = suc; suc = suc->left; } DeleteA(suc , sucpar); if( par == NULL) { root = suc; } else { if( par->left == ptr) { par->left = suc; } else { par->right = suc; } } suc->left = ptr->left; suc->right = ptr->right; } void Delete( int ele) { Treenode * temp = Search( root , ele , 0); Treenode * par = Search( root , ele, 2); if( temp == NULL) { cout<<"Item doesn't exist"<<endl; return; } else { if( temp->left != NULL && temp->right != NULL) { DeleteB( temp , par); } else { DeleteA(temp , par); } } } }; Treenode* Search ( Treenode * root , int ele , int mode ) ///mode 1 : insert ; 0 : search ; 2: delete { Treenode * par = NULL; Treenode * node = root; if( root == NULL) { return NULL; } while( node != NULL) { if( node->info > ele) { par = node; node = node->left; } else if ( node->info == ele) { if( mode == 0 ) { return node; } else if ( mode == 2) { return par; } } else { par = node; node = node->right; } } if( mode == 1) { return par; } else { return NULL; } } void Preorder ( Treenode * root) { stack<Treenode*> s; s.push ( NULL); Treenode * ptr = root; while( ptr != NULL) { cout<<ptr->info<<" "; if( ptr-> right != NULL) { s.push( ptr->right); } if( ptr-> left != NULL) { ptr = ptr->left; } else { ptr = s.top(); s.pop(); } } cout<<endl; } void Inorder ( Treenode * root) { stack<Treenode * > s; s.push( NULL); Treenode * ptr = root; int count = 0; do { while( ptr != NULL) { s.push( ptr); ptr = ptr->left; } ptr = s.top(); s.pop(); bool d = true; while( ptr != NULL && d == true) { cout<<ptr->info<<" "; count++; if( ptr->right == NULL) { ptr = s.top(); s.pop(); } else { ptr = ptr->right; d = false; } } }while( !s.empty()); cout<<endl; } void Postorder ( Treenode * root) { stack< pair< Treenode * , bool > > s; /// true - node , false - right Treenode * ptr = root; s.push( make_pair(nullptr , true)); int count = 0; while (count < 7) { while( ptr != NULL) { s.push( make_pair(ptr , true)); if( ptr-> right != NULL) { s.push( make_pair( ptr->right , false)); } ptr = ptr->left; } pair < Treenode * , bool > x = s.top(); s.pop(); ptr = x.first; while( x.second == true) { cout<<x.first->info<<" "; count++; x = s.top(); s.pop(); ptr = x.first; } if( x.second == false) { x.second = true; } } cout<<endl; } int main() { Tree tt; tt.Insert(10); tt.Insert(5); tt.Insert(17); tt.Insert(16); tt.Insert(20); tt.Insert(3); tt.Insert(6); Preorder( tt.root); Inorder( tt.root); //Postorder(tt.root); int ele; cin>>ele; //tt.Delete(ele); //Postorder(tt.root); }
1e2a689cd8f4fdcb7c9cf8a3971d50603f1e345e
f3852d4af9463caded8289270d329f0e2f4bbd97
/Engine/Point.cpp
79bb020f8a1f6997fc1143cab99cd9a88f26d44d
[]
no_license
arkfil/snake_with_chili
bdac40f2c61a32994b5115a430ad125de1a9165a
36015b8087fbde4165ba64f80abb3f0333259cbd
refs/heads/master
2020-03-07T17:57:06.992290
2018-04-04T07:59:27
2018-04-04T07:59:27
127,625,097
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
Point.cpp
#include "Point.h" Point::Point() { } Point::Point(int p_x, int p_y) : x(p_x), y(p_y) { } Point::~Point() { }
10844ee2254ab469492ec176d40f857c2d6f9462
3f29160a10cb06998657108fc6573ab105927682
/lib/howto_compare_vector_cci.cc
a8ae746490d247a613f5bd68c09807fee9145334
[]
no_license
zitouni/gr_compare_vector
c10302f811f72c7bbe91d1f04b0c5e33dd790dfd
5ee57429c4848ed0fe9da72d2ac7f624dcca7058
refs/heads/master
2020-08-27T05:59:08.590948
2012-12-05T17:14:18
2012-12-05T17:14:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,823
cc
howto_compare_vector_cci.cc
/* -*- c++ -*- */ /* * Copyright 2004,2010 Free Software Foundation, Inc.f * * This file is part of GNU Radio * * GNU Radio 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, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * config.h is generated by configure. It contains the results * of probing for features, options etc. It should be the first * file included in your .cc file. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <gr_count_bits.h> #include <cstdlib> #include <howto_compare_vector_cci.h> #include <gr_io_signature.h> /* * Create a new instance of howto_compare_vector_cci and return * a boost shared_ptr. This is effectively the public constructor. */ howto_compare_vector_cci_sptr howto_make_compare_vector_cci (const std::vector<unsigned char> &data, const std::vector<unsigned char> &preamble, unsigned short iteration_data_reg, unsigned short min_threshold_error, bool repeat) { return gnuradio::get_initial_sptr(new howto_compare_vector_cci(data, preamble, iteration_data_reg, min_threshold_error, repeat)); } /* * Specify constraints on number of input and output streams. * This info is used to construct the input and output signatures * (2nd & 3rd args to gr_block's constructor). The input and * output signatures are used by the runtime system to * check that a valid number and type of inputs and outputs * are connected to this block. In this case, we accept * only 1 input and 1 output. */ static const int MIN_IN = 1; // mininum number of input streams static const int MAX_IN = 1; // maximum number of input streams static const int MIN_OUT = 1; // minimum number of output streams static const int MAX_OUT = 1; // maximum number of output streams /* * The private constructor */ howto_compare_vector_cci::howto_compare_vector_cci (const std::vector<unsigned char> &data, const std::vector<unsigned char> &preamble, unsigned short iteration_data_reg, unsigned short min_threshold_error, bool repeat) : gr_block ("compare_vector_cci", gr_make_io_signature (MIN_IN, MAX_IN, sizeof (unsigned char)), gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (unsigned char))), d_data (data), d_preamble (preamble), d_iteration_data_reg (iteration_data_reg), d_min_threshold_error (min_threshold_error), d_repeat (repeat) { d_shift_reg = 0; d_vector_reg = 0; is_same_vector_number = 0; is_same_vector_decision = false; number_bits = 0; d_preamble_reg = 0; d_size = d_data.size(); d_preamble_size = d_preamble.size(); number_bits_preamble =0; number_bits_data =0; //printf("the size of the data vector is : %d \n", int(d_data.size())); for (int offset=0; offset < d_data.size(); offset++ ){ if (d_data[offset] == 1) d_vector_reg = (d_vector_reg << 1) | 1; else d_vector_reg = d_vector_reg << 1; } //printf("the size of the preamble vector is : %d \n", int(d_preamble.size())); for (int offset=0; offset < d_preamble.size(); offset++ ){ if (d_preamble[offset] == 1) d_preamble_reg = (d_preamble_reg << 1) | 1; else d_preamble_reg = d_preamble_reg << 1; } //printf("Value of d_data_reg is %d \n", d_data_reg); // nothing else required in this example } /* * Our virtual destructor. */ howto_compare_vector_cci::~howto_compare_vector_cci () { // nothing else required in this example } int howto_compare_vector_cci::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; unsigned int size = d_data.size() + d_preamble.size(); unsigned int preamble_not_found = 0; unsigned int data_not_found = 0; //printf("number of noutput_items %d \n", noutput_items); for (int i = 0; i < noutput_items; i++){ //printf("Value of in_stream %d \n", in[i]); //The first test is used to avoid the 31 bits of mask //if(nbr_bits_usrp < 31){ //nbr_bits_usrp++; //number_bits =0; //}else{ //printf("le i numรฉro : %d de in[i]: %d\n", i, in[i]); if (preamble_received) number_bits_data ++; else number_bits_preamble ++; if (in[i] == 1) d_shift_reg = (d_shift_reg << 1) | 1; else d_shift_reg = d_shift_reg << 1; //if((number_bits % d_preamble.size()) == 0){ //preamble_received = is_same_vector(d_shift_reg, d_preamble_reg); //if (number_bits ==32) if(number_bits_preamble == d_preamble.size()){ //compare shift_reg constructed to that of preamble reg //printf("d_shift_reg : %d d_preamble_reg: %d\n", d_shift_reg, d_preamble_reg); preamble_received = is_same_vector(d_shift_reg, d_preamble_reg); if (preamble_received){ //printf("******************Preamble is received *************** : %d******* valeur %d\n", number_bits_preamble, d_shift_reg); //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); //exit(1); //number_bits = 1; }else{ //printf("PREAMBLE not found \n"); preamble_not_found++; is_same_vector_decision = false; is_same_vector_number = 0; //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); } number_bits_preamble = 0; d_shift_reg = 0; } //} if ((number_bits_data == d_data.size()) && (preamble_received)){ //printf("Number of bits %d \n",number_bits); //printf("***************\n"); //printf("d_shift_reg %d \n",d_shift_reg); //printf("***************\n"); data_received = is_same_vector(d_shift_reg, d_vector_reg); if (data_received){ is_same_vector_number+=1; //printf("******************Data is received *************** : %d******* valeur %d\n", number_bits_data, d_shift_reg); //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); //printf("nombre de vecteur trouve : %d le d_iteration_data_reg is : %d \n", is_same_vector_number, d_iteration_data_reg); }else{ //printf("DATA not found \n"); //data_not_found++; //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); is_same_vector_number =0; is_same_vector_decision = false; } preamble_received = false; number_bits_data = 0; d_shift_reg = 0; } if (is_same_vector_number >= d_iteration_data_reg){ //printf("nombre de vecteur trouve : %d le d_iteration_data_reg is : %d \n", is_same_vector_number, d_iteration_data_reg); is_same_vector_decision = true; is_same_vector_number = 0; exit(1); } // if(data_not_found >= 5){ // printf("data not found : %d\n", data_not_found); // exit(0); // } // if(preamble_not_found >= 10){ // printf("preamble not found : %d\n ", preamble_not_found); // exit(0); // } out[i] = in[i]; } //printf("Value of the output %d \n",d_shift_reg); // // Tell runtime system how many input items we consumed on // each input stream. // This instruction allow the flow graph to be stable and to protect the stream across the block. consume_each (noutput_items); return noutput_items; } bool howto_compare_vector_cci::is_same_vector(int d_shift_reg, int d_vector_reg){ int exclusive = (d_vector_reg &0xffffffff) ^ (d_shift_reg&0xffffffff); int count_error = 0; bool same_vector = false; for (int i = 0; i < d_size; i++) if (exclusive & (1<<i)){ count_error++; } //printf("********Begin is same vector function \n"); //printf("valeur de count error is : %d \n", count_error); //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); if (count_error <= d_min_threshold_error){ //printf("*Yes, Value is equal \n"); same_vector = true; //printf("valeur de d_vector_reg: %d \n", d_vector_reg ); //printf("valeur de d_shift_reg: %d \n", d_shift_reg ); //printf("Number of vectors found %d \n",is_same_vector_number); } else{ same_vector = false; } //printf("********End is same vector function \n"); return same_vector; } bool howto_compare_vector_cci::compare_vector_decision(){ if (is_same_vector_decision) return true; else return false; }
86e4c8e39ed1d7455be212f217f92b135d7bd6d5
4435a0a6110b77060478876a464f6187d635f3a3
/MGEOP_gen/Snap-2.3/glib-core/xdt.cpp
f28f290670eec9d8438141d807281834999cf0df
[]
no_license
vshesh/fractal-graphs
014469f650fd42eb9a3334699a73ef9dbfafca1c
5d294f903458148470216d0bca4723d5c8e3644d
refs/heads/main
2021-06-07T07:55:49.462792
2021-04-03T00:51:51
2021-04-03T00:51:51
75,800,804
0
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
xdt.cpp
version https://git-lfs.github.com/spec/v1 oid sha256:7cf0e55eb8c0d8d51231003434830f33065c67f983abbac70d5320b05ba0a34d size 250
99d2318925e61b813008ec84947dc892e305ca53
ef21d605f07fb9b342f050b0ce4ecfb8dd5f3aab
/Classes/TSStagePlayLayerGamePrepare.h
f27f73df6ce7a3bcd2afcc9a93b4a710614ea431
[]
no_license
timxie2008/TreasuresGleaner
532384b09969408f2545278e41237a8192f92ac8
ba325746c5b66345ab99399b27e235c766a3653f
refs/heads/master
2021-01-22T01:33:14.331450
2012-11-16T05:18:20
2012-11-16T05:18:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,626
h
TSStagePlayLayerGamePrepare.h
#if !defined(_STAGE_PLAY_LAYER_GAME_PREPARE_H_) #define _STAGE_PLAY_LAYER_GAME_PREPARE_H_ #include "AStageLayer.h" #include "TSGroupNumber.h" class TSSpritePlayer; class TSSpriteCommon; class TSSpriteButton; class TSStagePlayLayerGamePrepare : public CAStageLayer //, public CCTargetedTouchDelegate { protected: Define_Sprite_Getter(TSSpriteCommon, label_title); Define_Sprite_Getter(TSSpriteCommon, info_dist_back); Define_Sprite_Getter(TSSpriteCommon, label_dist_last); Define_Sprite_Getter(TSSpriteCommon, label_dist_max); Define_Sprite_Getter(TSSpriteButton, button_play); Define_Sprite_Getter(TSSpriteButton, button_moregames); //Define_Sprite_Getter(TSSpriteButton, button_shop); //Define_Sprite_Getter(TSSpriteButton, button_music); Define_Sprite_Getter(TSSpriteButton, button_sound); Define_Sprite_Getter(TSSpriteCommon, prepare_player); Define_Sprite_Getter(TSSpriteCommon, prepare_whale); Define_Sprite_Getter(TSSpriteCommon, prepare_dolphin); Define_Sprite_Getter(TSSpriteCommon, prepare_bubble_whale); Define_Sprite_Getter(TSSpriteCommon, prepare_bubble_dolphin); void _NullGetters() { Init_Sprite_Getter_Var(label_title); Init_Sprite_Getter_Var(info_dist_back); Init_Sprite_Getter_Var(label_dist_last); Init_Sprite_Getter_Var(label_dist_max); //Init_Sprite_Getter_Var(panel_scores); Init_Sprite_Getter_Var(button_play); Init_Sprite_Getter_Var(button_moregames); //Init_Sprite_Getter_Var(button_shop); //Init_Sprite_Getter_Var(button_music); Init_Sprite_Getter_Var(button_sound); Init_Sprite_Getter_Var(prepare_player); Init_Sprite_Getter_Var(prepare_whale); Init_Sprite_Getter_Var(prepare_dolphin); Init_Sprite_Getter_Var(prepare_bubble_whale); Init_Sprite_Getter_Var(prepare_bubble_dolphin); } void _InitGetters() { Init_Sprite_Getter(TSSpriteCommon, label_title); Init_Sprite_Getter(TSSpriteCommon, info_dist_back); Init_Sprite_Getter(TSSpriteCommon, label_dist_last); Init_Sprite_Getter(TSSpriteCommon, label_dist_max); Init_Sprite_Getter(TSSpriteButton, button_play); Init_Sprite_Getter(TSSpriteButton, button_moregames); //Init_Sprite_Getter(TSSpriteButton, button_shop); //Init_Sprite_Getter(TSSpriteButton, button_music); Init_Sprite_Getter(TSSpriteButton, button_sound); Init_Sprite_Getter(TSSpriteCommon, prepare_player); Init_Sprite_Getter(TSSpriteCommon, prepare_whale); Init_Sprite_Getter(TSSpriteCommon, prepare_dolphin); Init_Sprite_Getter(TSSpriteCommon, prepare_bubble_whale); Init_Sprite_Getter(TSSpriteCommon, prepare_bubble_dolphin); } void _findNumberSprites(const char* prefix, CASprite** ppsprs, int size); TSGroupNumber _dist_last; TSGroupNumber _dist_max; bool _bScoreDirty; int _score_last; int _score_max; //void _updateNumber(const char* prefix, int nValue); /* DELCARE_STATE_HANDLER(Idle); DELCARE_STATE_HANDLER(Fadein); DELCARE_STATE_HANDLER(Running); DELCARE_STATE_HANDLER(OnShop); DELCARE_STATE_HANDLER(OnPlay); DELCARE_STATE_HANDLER(Fadeout); */ public: TSStagePlayLayerGamePrepare(CAStage* pstage, CAStageLayer* playerParent); virtual ~TSStagePlayLayerGamePrepare(void); virtual void show(bool s); virtual string debuglog(); virtual void onEnter(); virtual void onUpdate(); virtual void onExit(); virtual void onEvent(CAEvent* pevt); virtual bool checkCondition(CAState* from, const CATransition& trans); virtual void onStateBegin(CAState* from, void* param); //virtual void onStateUpdate(CAState* from, size_t counter, ccTime time); virtual void onStateEnd(CAState* from, void* param); }; #endif //_STAGE_PLAY_LAYER_GAME_PREPARE_H_
29a5c26b41578f9518bb2df38db069d4fcce6b9d
48ebaa4e5091529e9673f4b66d74adbac6ee32d6
/1023/main.cpp
c875d1f6fc7dece223449e1809f8e5c866664b01
[]
no_license
keshego/COJ
4ffa910f44f387574dff05f1d8341123d04ee55a
bb17552864c9b072885f60fe64a4b2e7a947d4ca
refs/heads/master
2021-04-29T07:40:17.355165
2017-01-03T19:52:02
2017-01-03T19:52:02
77,947,717
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
main.cpp
#include <iostream> using namespace std; int main() { double S=0,B; for(int j=1;j<=12;j++) { cin>>B; S=S+B; } S=S/double(12); cout<<"$"<<S<<endl; return 0; }
03992be0ca2858e86f07cb3e73948ceb9610f86a
5eb9f43b40ce870764aa65eb646b3532ebdf01f2
/NMGame/AladdinState.cpp
b4655eeb62eb7dfc3959a589a13e88c0d8cbcf79
[]
no_license
anqck/NMGame
911f8cb5ea6142c35bdadbc21339cfb34e614969
3a11e2d7c620dd620dbac07fd27d35ce943b3f26
refs/heads/master
2021-09-15T15:07:10.711772
2017-12-28T08:49:36
2017-12-28T08:49:36
105,494,656
0
0
null
2017-11-25T18:12:53
2017-10-02T03:28:28
C++
UTF-8
C++
false
false
3,611
cpp
AladdinState.cpp
//#include "AladdinState.h" // //AladdinState::AladdinState() //{ // this->mPosition = D3DXVECTOR3(0, 0, 0); // this->mVelocity = D3DXVECTOR2(0, 0); // this->ResetFlag = true; //} // //AladdinState::AladdinState(LPD3DXSPRITE SpriteHandle) //{ // this->mSpriteHandle = SpriteHandle; // this->mPosition = D3DXVECTOR3(0, 0, 0); // this->mVelocity = D3DXVECTOR2(0, 0); // this->ResetFlag = true; //} // //AladdinState::AladdinState(LPD3DXSPRITE SpriteHandle, D3DXVECTOR3 Position) //{ // this->mSpriteHandle = SpriteHandle; // this->mPosition = D3DXVECTOR3(0, 0, 0); // this->mVelocity = D3DXVECTOR2(0, 0); // this->SetPosition(Position); // this->ResetFlag = true; //} // //AladdinState::AladdinState(LPD3DXSPRITE SpriteHandle, int X, int Y) //{ // this->mSpriteHandle = SpriteHandle; // this->mPosition = D3DXVECTOR3(0, 0, 0); // this->mVelocity = D3DXVECTOR2(0, 0); // this->SetPosition(X, Y); // this->ResetFlag = true; //} // //AladdinState::~AladdinState() //{ // if (this->mSprite) // delete(this->mSprite); //} // //void AladdinState::Render() //{ // this->mSprite->Render(); //} // //void AladdinState::Update(float DeltaTime) //{ //} // // //void AladdinState::Animate(float DeltaTime) //{ // // DWORD now = GetTickCount(); // if (now - last_time > 1000 / ANIMATE_RATE) // { // if (this->GetVelocity().x != 0) // this->nextFrame(); // // last_time = now; // } //} // //void AladdinState::Move(float delta_time) //{ // SetPosition(mSprite->GetPosition().x + this->GetVelocity().x * delta_time, mSprite->GetPosition().y + this->GetVelocity().y * delta_time); //} // //void AladdinState::nextFrame() //{ // if (this->ResetFlag) // { // ResetFlag = false; // return; // } // // mCurrentIdx = (mCurrentIdx + mEndIdx - 1) % mEndIdx; // this->mSprite->SetFrame(mCurrentIdx); //} // //void AladdinState::nextFrameWithoutLoop() //{ // if (this->ResetFlag) // { // this->mSprite->SetFrame(mCurrentIdx); // ResetFlag = false; // } // else // { // if (mCurrentIdx < mEndIdx) // { // mCurrentIdx += 1; // // } // } // if (mCurrentIdx < mEndIdx) // this->mSprite->SetFrame(mCurrentIdx); //} // //void AladdinState::resetFrame() //{ // mCurrentIdx = 0; // this->mSprite->SetFrame(0); // this->ResetFlag = true; //} // //D3DXVECTOR3 AladdinState::GetPosition() //{ // return this->mPosition; //} // //D3DXVECTOR2 AladdinState::GetVelocity() //{ // return this->mVelocity; //} // //void AladdinState::SetVelocity(D3DXVECTOR2 Velocity) //{ // this->mVelocity = Velocity; //} // //void AladdinState::SetVelocity(float X, float Y) //{ // this->mVelocity.x = X; // this->mVelocity.y = Y; //} // //bool AladdinState::GetFlipVertical() //{ // return this->mIsFlipVertical; //} // //void AladdinState::SetFlipVertical(bool flipV) //{ // this->mIsFlipVertical = flipV; // // if (this->mIsFlipVertical != this->mSprite->IsFlipVertical()) // this->mSprite->FlipVertical(this->mIsFlipVertical); //} // //int AladdinState::GetCurrentIdx() //{ // return this->mCurrentIdx; //} // //int AladdinState::GetEndIdx() //{ // return this->mEndIdx; //} // //bool AladdinState::isDone() //{ // if (this->mCurrentIdx == this->mEndIdx) // return true; // // return false; //} // //void AladdinState::GoToLastFrameIdx() //{ // this->mCurrentIdx = this->mEndIdx - 1; // this->mSprite->SetFrame(this->mEndIdx - 1); //} // // // //void AladdinState::SetPosition(D3DXVECTOR3 Position) //{ // this->mPosition = Position; // this->mSprite->SetPosition(this->mPosition); //} // //void AladdinState::SetPosition(int X, int Y) //{ // this->mPosition.x = X; // this->mPosition.y = Y; // this->mSprite->SetPosition(this->mPosition); //}
3a175743c1f3abcfc28ae129c3faa8d020ce1799
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/tests/Proactor_Test.h
02bd4a407967cfad598cc389870cd2d22218ef9f
[ "Apache-2.0" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
3,992
h
Proactor_Test.h
//============================================================================= /** * @file Proactor_Test.h * * Define class needed for generating templates. IBM C++ requires this to * be in its own file for auto template instantiation. * * @author @author Alexander Libman <alibman@baltimore.com> */ //============================================================================= #ifndef ACE_TESTS_PROACTOR_TEST_H #define ACE_TESTS_PROACTOR_TEST_H #include "ace/Synch_Traits.h" #include "ace/Thread_Mutex.h" // forward declaration class TestData; class Server : public ACE_Service_Handler { public: Server (); Server (TestData *tester, int id); ~Server (void); int id (void) { return this->id_; } size_t get_total_snd (void) { return this->total_snd_; } size_t get_total_rcv (void) { return this->total_rcv_; } long get_total_w (void) { return this->total_w_; } long get_total_r (void) { return this->total_r_; } // This is called to pass the new connection's addresses. virtual void addresses (const ACE_INET_Addr& peer, const ACE_INET_Addr& local); /// This is called after the new connection has been accepted. virtual void open (ACE_HANDLE handle, ACE_Message_Block &message_block); void cancel (); protected: //// This is called when asynchronous <read> operation from the //// socket completes. /** * @name AIO callback handling * * These methods are called by the framework */ virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); /// This is called when an asynchronous <write> to the socket /// completes. virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); private: int initiate_read_stream (void); int initiate_write_stream (ACE_Message_Block &mb, size_t nbytes); TestData *tester_; int id_; ACE_Asynch_Read_Stream rs_; ACE_Asynch_Write_Stream ws_; ACE_HANDLE handle_; ACE_SYNCH_MUTEX lock_; int io_count_; // Number of currently outstanding I/O requests int flg_cancel_; size_t total_snd_; // Number of bytes successfully sent size_t total_rcv_; // Number of bytes successfully received int total_w_; // Number of write operations int total_r_; // Number of read operations }; // ******************************************* // Client // ******************************************* class Client : public ACE_Service_Handler { public: /// This is called after the new connection has been established. virtual void open (ACE_HANDLE handle, ACE_Message_Block &message_block); Client (); Client (TestData *tester, int id); ~Client (void); int id (void) { return this->id_; } size_t get_total_snd (void) { return this->total_snd_; } size_t get_total_rcv (void) { return this->total_rcv_; } int get_total_w (void) { return this->total_w_; } int get_total_r (void) { return this->total_r_; } // This is called to pass the new connection's addresses. virtual void addresses (const ACE_INET_Addr& peer, const ACE_INET_Addr& local); /// This is called when asynchronous reads from the socket complete virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); /// This is called when asynchronous writes from the socket complete virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); void cancel (void); private: int initiate_read_stream (void); int initiate_write_stream (void); void close (void); TestData *tester_; int id_; ACE_Asynch_Read_Stream rs_; ACE_Asynch_Write_Stream ws_; ACE_HANDLE handle_; ACE_SYNCH_MUTEX lock_; int io_count_; int stop_writing_; // Writes are shut down; just read. int flg_cancel_; size_t total_snd_; size_t total_rcv_; int total_w_; int total_r_; }; #endif /* ACE_TESTS_PROACTOR_TEST_H */
847938a9bdad6cccb59cc2352aaed6673b07334c
ddef58b04a7b9e37a1ccedd4ae4ac237c636b4ed
/internal/source/engine/action/DelegateAction.cpp
a60017c25b938c03b33f1e32e65b41bc3b0655a9
[]
no_license
ncguy2/Omicron
9f97e7594acd6cbaf9f1be763f34ea6b98ff3a2a
f67b6aa6c103685bba20305aeb25b4ee4e9f469c
refs/heads/master
2021-03-27T19:14:46.482386
2018-02-09T12:49:15
2018-02-09T12:49:15
96,109,868
1
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
DelegateAction.cpp
// // Created by Guy on 18/08/2017. // #include <engine/action/DelegateAction.hpp> namespace Omicron { namespace Actions { DelegateAction::DelegateAction(BaseAction* action) : action(action) {} bool DelegateAction::Act(OmicronEntity* entity, float delta) { return Delegate(entity, delta); } } }
28c2c738a707f838635515b3087bb4540c440903
b72890d0e6503b4528bef2b09743f6df72cb01d2
/shared/acsdkManufactory/include/acsdkManufactory/internal/SharedPointerCache.h
361a0105b632776fa78820846029471d54677c92
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-pml-2020", "LicenseRef-.amazon.com.-AmznSL-1.0" ]
permissive
shivasiddharth/avs-device-sdk
b1375db55f204f1baaa9a4825e31f944a6e6d13c
c7ca5a12f65ce95f99d56fc7a1ab79cc96147ed8
refs/heads/master
2021-12-01T17:21:42.067397
2021-11-28T09:34:42
2021-11-28T09:34:42
152,394,898
0
2
Apache-2.0
2021-11-26T09:17:25
2018-10-10T09:09:11
C++
UTF-8
C++
false
false
2,252
h
SharedPointerCache.h
/* * Copyright 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. */ #ifndef ACSDKMANUFACTORY_INTERNAL_SHAREDPOINTERCACHE_H_ #define ACSDKMANUFACTORY_INTERNAL_SHAREDPOINTERCACHE_H_ #include "acsdkManufactory/internal/AbstractPointerCache.h" #include "acsdkManufactory/internal/AbstractRecipe.h" namespace alexaClientSDK { namespace acsdkManufactory { namespace internal { /** * Class used to cache a shared_ptr to an instance. */ class SharedPointerCache : public AbstractPointerCache { public: /** * Constructor. * * @param recipe The recipe that contains information on the means of producing an instance. */ SharedPointerCache(std::shared_ptr<AbstractRecipe> recipe); /** * Destructor. */ ~SharedPointerCache(); /// @name AbstractPointerCache methods. /// @{ void* get(RuntimeManufactory& runtimeManufactory) override; void cleanup() override; /// @} private: /// The recipe containing information about the means of producing an instance. std::shared_ptr<AbstractRecipe> m_recipe; /// The @c ProduceInstanceFunction to produce an instance. AbstractRecipe::ProduceInstanceFunction m_produceInstance; /// The @c DeleteInstanceFunction to delete the cached instance on this cache's destruction. AbstractRecipe::DeleteInstanceFunction m_deleteInstance; /// The cached instance (if any). This is a void pointer to a std::shared_ptr<Type>. Using a void pointer /// allows this class to be unaware of the type it is caching, to reduce use of class templates. void* m_cachedValue; }; } // namespace internal } // namespace acsdkManufactory } // namespace alexaClientSDK #endif // ACSDKMANUFACTORY_INTERNAL_SHAREDPOINTERCACHE_H_
af0eebf366c0d6feb1d248b4f244e4a434127fcc
e80a1aeb1160ccb574ed5a90c0a9f15e1710e059
/gserver.h
a6e8d0f499615fba53b23b36c38e6c6405dc08c0
[ "BSD-3-Clause" ]
permissive
maxohm/gserver
a49d21ea826bc8730aa6685b7b596cd86d5c7d2d
82a00f909344066a2dd857e00bc781bc763596a5
refs/heads/master
2020-04-12T11:48:32.991087
2018-12-23T19:03:10
2018-12-23T19:03:10
162,471,817
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
gserver.h
#ifndef GSERVER_H #define GSERVER_H // #include <QMainWindow> #include <QTcpServer> #include <QTcpSocket> // #include "msock.h" namespace Ui { class gserver; } class gserver : public QMainWindow { Q_OBJECT public: explicit gserver(QWidget *parent = 0); ~gserver(); private slots: void cliconnect(); void clidisconn(); // void log(QString s); void monitor(); // void rx(); void tx(QString s); private: // Ui::gserver *ui; // int conn_lim; QTcpServer* listener; QList<msock*> st; }; #endif // GSERVER_H
082e496ceb744737106030ed8c61d573ddd11975
60619a8daa4603fb65f4f86f383a6ddde841e326
/2014-05-02/i.cpp
c982d7ded0f5ae8c0ea99e3afbe72b03b4915d35
[]
no_license
MYREarth/secret-weapon
f4b1d4b995951546b2fb1e40190707a805fb88b5
77f3ff1111aafaaae8f56893b78e3be9134437a9
refs/heads/master
2020-05-22T02:29:43.024017
2015-10-03T08:17:46
2015-10-03T08:17:46
186,199,326
3
0
null
2019-05-12T01:46:13
2019-05-12T01:46:13
null
UTF-8
C++
false
false
3,313
cpp
i.cpp
#include <cstdio> #include <cmath> #include <algorithm> using namespace std; const double pi=acos(-1.0); struct point { double x,y; point(){} point(double x,double y):x(x),y(y){} point unit() const { double t=sqrt(x*x+y*y); return(point(x/t,y/t)); } double angle() const { return(atan2(y,x)); } }; inline point operator +(const point &a,const point &b) { return(point(a.x+b.x,a.y+b.y)); } inline point operator -(const point &a,const point &b) { return(point(a.x-b.x,a.y-b.y)); } inline point operator *(const point &a,double b) { return(point(a.x*b,a.y*b)); } inline point operator /(const point &a,double b) { return(point(a.x/b,a.y/b)); } inline int sign(double x,double eps=1e-8) { return(x<-eps?-1:x>eps); } inline bool operator <(const point &a,const point &b) { return(sign(a.x-b.x)<0 || sign(a.x-b.x)==0 && sign(a.y-b.y)<0); } inline double det(const point &a,const point &b) { return(a.x*b.y-a.y*b.x); } inline double sqr(double x) { return(x*x); } inline double dist(const point &a,const point &b) { return(sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))); } inline double ptoline(const point &p,const point &a,const point &b) { return(fabs(det(p-a,b-a))/dist(a,b)); } inline point half(const point &p,const point &a,const point &b) { point u=p+(a-p).unit(); point v=p+(b-p).unit(); return((u+v)/2); } inline point intersect(const point &a,const point &b,const point &c,const point &d) { double s1=det(b-a,c-a),s2=det(b-a,d-a); return((c*s2-d*s1)/(s2-s1)); } inline void convex(int &n,point a[]) { point b[110]; int m=0; sort(a+1,a+n+1); for (int i=1;i<=n;i++) { while (m>=2 && sign(det(b[m]-b[m-1],a[i]-b[m]))<=0) m--; b[++m]=a[i]; } int rev=m; for (int i=n-1;i;i--) { while (m>rev && sign(det(b[m]-b[m-1],a[i]-b[m]))<=0) m--; b[++m]=a[i]; } n=m-1; for (int i=1;i<=n;i++) a[i]=b[i]; } inline double move(int n,point a[],double len) { double ret=0; a[0]=a[n]; a[n+1]=a[1]; point b[110]; for (int i=1;i<=n;i++) { point dir=(half(a[i],a[i-1],a[i+1])-a[i]).unit(); double theta=dir.angle()-(a[i+1]-a[i]).angle(); double dis=len/sin(theta); ret+=dis; b[i]=a[i]+dir*dis; } for (int i=1;i<=n;i++) a[i]=b[i]; return(ret); } point a[110]; int main() { freopen("roof.in","r",stdin); freopen("roof.out","w",stdout); int n; scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%lf%lf",&a[i].x,&a[i].y); double ans=0; while (1) { convex(n,a); if (n<=2) { if (n==2) ans+=dist(a[1],a[2]); break; } a[0]=a[n]; a[n+1]=a[1]; a[n+2]=a[2]; double len=1e100; for (int i=1;i<=n;i++) { point p=half(a[i],a[i-1],a[i+1]); point q=half(a[i+1],a[i],a[i+2]); point tmp=intersect(a[i],p,a[i+1],q); len=min(len,ptoline(tmp,a[i],a[i+1])); len=min(len,ptoline(tmp,a[i-1],a[i])); len=min(len,ptoline(tmp,a[i+1],a[i+2])); } ans+=move(n,a,len); } printf("%.10f\n",ans); return(0); }
77a20c6f2e8ab8eb45cbbf9392566ac399f14b25
1f83f73102d2b3df84f9a1148639ea1fa0f6e372
/DemonSlayer/Source/DemonSlayer/Objective.h
16d336a6ce43ae5bf43d0817f61f04b6bf583afe
[]
no_license
jjjames98/Demon-Slayer
661acf325448dbdf5931a951673226ed1ae58c52
b361a2f57859793c8de376135401067411e2276d
refs/heads/master
2023-03-20T07:54:52.283225
2019-11-11T12:03:34
2019-11-11T12:03:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
797
h
Objective.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "InteractableObject.h" /** * */ class DEMONSLAYER_API Objective { /* Objective details */ int objectiveID; FString description; FString secondaryDescription; bool objectiveCompleted; AInteractableObject* objectConnectedTo; public: Objective(int ID, FString objectiveDescription, FString objectiveSecondary); ~Objective(); // Accessors FString GetDescription() { return description; } FString GetSecondary() { return secondaryDescription; } int GetID() { return objectiveID; } AInteractableObject* GetObject() { return objectConnectedTo; } // Mutators void SetObject(AInteractableObject* connectedObject) { objectConnectedTo = connectedObject; } };
e8d54d8fe9acb11ca73d4c6ce7b96d146c17f603
323435c570e4a334827c7bfac15128202ad08efc
/Cpp_Practice/Cpp_Practice/Exer01_1_1.cpp
dfc37b9023e563f7087f41806b80ed3628053d45
[]
no_license
Jiwon-Seo/Cpp_Training
f8478a7deee4542c75b1473d279c37c98ec697af
ce8c0f2b81eabd1c2c6ae4885410e6d02062cf2e
refs/heads/master
2023-07-05T11:57:29.266887
2021-09-01T12:19:08
2021-09-01T12:19:08
395,870,119
0
0
null
null
null
null
UHC
C++
false
false
241
cpp
Exer01_1_1.cpp
#include<iostream> #define NUM 5 int main() { int sum = 0; for (int i = 0, in; i < NUM; i++) { std::cout << i + 1 << "๋ฒˆ์งธ ์ •์ˆ˜ ์ž…๋ ฅ: "; std::cin >> in; sum += in; } std::cout << "ํ•ฉ๊ณ„: " << sum << std::endl; return 0; }
eef6ed861029f3bdc1d2f013daa50464664b3a81
e9605b49dafd914700f982bc61fee8b9787390e0
/state.h
82312da9460ce7a57354da280e6f7abcbc2bc08b
[]
no_license
cpptutor-coder/brace-parser
afe6c2a1adbceeea5030a174352feec4d7980fe0
5dfaa8cdc8e6a395d8844446b3be3b5d083dcbac
refs/heads/main
2023-01-21T12:27:08.226906
2020-11-22T05:43:20
2020-11-22T05:43:20
314,968,188
0
0
null
null
null
null
UTF-8
C++
false
false
754
h
state.h
#ifndef OKC_ASSIGN_STATE_H #define OKC_ASSIGN_STATE_H #include "finite_state.h" // Abstract base class for Finite State Automata classes class State { public: virtual EState next_state(char c) = 0; virtual ~State() {} // To get around spurious warning }; class StartState : public State { private: EState next_state(char c) override; }; class AlphaState: public State { private: EState next_state(char c) override; }; class OpenBraceState : public State { private: EState next_state(char c) override; }; class CloseBraceState : public State { private: EState next_state(char c) override; }; class CommaState : public State { private: EState next_state(char c) override; }; #endif // OKC_ASSIGN_STATE_H
20b6604acb779168f1117f7120df3bc3e5d7f63e
34f1d13644f01f96ab1f3eb5a68567a2405f7b12
/events/ColorBlock.h
049e0a98d670c2a30f36bea3100a20e21f72f7fa
[]
no_license
antoniovazquezaraujo/8x8
41f49c5dfdc3e7704694a495857943b6f5cb3e4d
2aaf2d0d99404d5274e40ee184189e1e566738fb
refs/heads/master
2021-01-15T12:25:50.803723
2012-06-01T15:18:04
2012-06-01T15:18:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
h
ColorBlock.h
#ifndef COLOR_BLOCK #define COLOR_BLOCK #include "ColorSpace.h" class ColorBlock{ public: ColorBlock(int levels, int cols, int rows); const int getNumLevels() const; ColorSpace & operator[](int pos); void addLevel(); void reset(); int cols, rows; vector<ColorSpace> spaces; }; #endif
b20b2663e477047d4a4fbdc2ca55e6eef3ec7c5f
ebe0a443d0751c7318f094c4ab9568288dccfc58
/include/player.h
51f49dbf554ee0a8968b3e498b8dd149cb6932ff
[]
no_license
nackata/geo-engine
3d0ede799a3d3b9eff28a314b2da075f390cc683
960d5569389fbbe79d69d3e7adc73c1e91234708
refs/heads/master
2021-06-26T05:43:01.692673
2020-11-20T07:51:33
2020-11-20T07:51:33
182,409,505
1
0
null
2019-10-29T10:23:12
2019-04-20T13:29:30
C
UTF-8
C++
false
false
1,001
h
player.h
#pragma once #include "fpsCam.h" #include "sceneobject.h" #include "aabb.h" #include <lib/glm/glm.hpp> #include <vector> class Player { FpsCam camera; std::vector<Object *> collisionObj; public: FpsCam * getCameraPtr() { return &camera; } void addObj(Object * obj) { collisionObj.push_back(obj); } AABB box; Player(); bool checkCollision(); void setAction(bool act) { camera.setAction(act); } void setPosition(glm::vec3 pos) { camera.setPos(pos); box.setPos(pos); } void setDirection(float yaw, float pitch) { camera.setDirection(yaw, pitch); } float getYaw() { return camera.getYaw(); } float getPitch() { return camera.getPitch(); } glm::vec3 getPosition() { return camera.getPos(); } glm::vec3 getDirection() { return camera.getDir(); } void processKeyBoardInput(keyBoardIn input, double deltaTime); void processMouseMovement(double xoffset, double yoffset, bool constraint = true); };
fb02bc3a0e1a60a2c00600d879e02a0047ba9cfe
fb46c46f05441285a5106d5f4eb811692148e070
/GpsxProtocal_DL/Protocol/ProtocolMan/GpsJTT808.h
f41c238729a7fc624b391cfd6ba16366b406e758
[]
no_license
github188/GPSGater
3b92366bbba26f4d3172ba9fdd72a8cf522c4e59
e3237e5d728a52275ef5b9b21a877787ec827938
refs/heads/master
2021-01-12T17:15:36.214918
2014-06-24T13:43:39
2014-06-24T13:43:39
null
0
0
null
null
null
null
GB18030
C++
false
false
3,318
h
GpsJTT808.h
#pragma once #include "gpsbase.h" class GpsJTT808 : public GPSClass { public: GpsJTT808(void); ~GpsJTT808(void); virtual BOOL isThisProtocol(char *buf,GPSINFO *pGpsInfo); virtual char* getProtocolName(int &nDevID); /* * ๆŠŠgps ไธŠๆฅ็š„ๆ•ฐๆฎ๏ผˆbuf)็ฟป่ฏ‘ๅˆฐ struct gpsInfo ไธญ */ virtual long getGpsInfo(char *buf,int nbufLen,GPSINFO &gpsInfo); virtual BOOL getResMsg(char *strBuf,GPSINFO &gpsInfo); virtual void getMsgID(char *buf,GPSINFO &gpsInfo); protected: virtual long _handleCmd_overspeed(GPSCommand*pGpsCommand,int nMaxSpeed,int nMinSpeed,int nContinue,int nValid=1); virtual long _handleCmd_SetArea(GPSCommand*pGpsCommand,TCHAR *pAreaID,TCHAR *palertType,TCHAR *pType,TCHAR *pLeftLat,TCHAR *prightlat,TCHAR *pleftlng,TCHAR *prightlng,TCHAR *pcenterlat,TCHAR *pcenterlng,TCHAR *pRadius); virtual long _handleCmd_CacelArea(GPSCommand*pGpsCommand,TCHAR *pAreaID); virtual long _handleCmd_SetHeartTime(GPSCommand*pGpsCommand,TCHAR *pInterval); virtual long _handleCmd_SetTimingTrack(GPSCommand*pGpsCommand,TCHAR *pInterval,TCHAR*pReportCount); virtual long _handleCmd_SetTurnReport(GPSCommand*pGpsCommand,TCHAR*pAngle); virtual long _handleCmd_SetGPRSParam(GPSCommand*pGpsCommand,TCHAR*pLinkMod,TCHAR*pIP,TCHAR*pPort,TCHAR*pAPN,TCHAR*pAPN_UserName,TCHAR*pAPN_PassWord); virtual long _handleCmd_Set_BackGPRSServer(GPSCommand*pGpsCommand,TCHAR*pIP,TCHAR*pPort); virtual long _handleCmd_Get_ErrorCode(GPSCommand*pGpsCommand); virtual long _handleCmd_Set_VehicleType(GPSCommand*pGpsCommand,TCHAR*pVehicleType); virtual long _handleCmd_Get_VehicleType(GPSCommand*pGpsCommand); virtual long _handleCmd_Set_OpenOBD(GPSCommand*pGpsCommand,TCHAR*pFlag); virtual long _handleCmd_Set_OBDParam(GPSCommand*pGpsCommand,int nParamCount,void *pstArrParams); virtual long _handleCmd_Set_Oil_LowAlarm(GPSCommand*pGpsCommand,TCHAR*poilvalue); virtual long _handleCmd_Get_Device_Version_and_SN(GPSCommand*pGpsCommand,TCHAR*psetType); virtual long _handleCmd_Set_Reset_Mileage_and_Runtime(GPSCommand*pGpsCommand); virtual long _handleCmd_Set_oFFOil_offElectricity(GPSCommand*pGpsCommand,BOOL bOff=TRUE); private: struct tagMsgPaket{ WORD msgTotalPakets; WORD msgPaketIdx; }; struct tagMsgBodyAttribute{ tagMsgBodyAttribute(){tagMsgBodyAttribute(0);}; tagMsgBodyAttribute(WORD wAttribute){ this->msgBodyLen = wAttribute&0x3FF; this->msgDecodeType=(wAttribute>>10)&0x7; this->bPaket = (wAttribute>>13)&0x1; this->Rev=(wAttribute>>14)&3; }; WORD getWordValue(){return msgBodyLen|(msgDecodeType<<10)|(bPaket<<13)|(Rev<<14);} int msgBodyLen:10; int msgDecodeType:3; int bPaket:1; int Rev:2; }; struct tagMsgHead{ WORD msgID; tagMsgBodyAttribute msgBodyAttribute; char sim[12]; WORD msgSN; tagMsgPaket msgPaket; tagMsgHead(){ ZeroMemory(this,sizeof(tagMsgHead)); } tagMsgHead(int msgid,int sn,char * pStrSim){ tagMsgHead(); this->msgID=msgid; this->msgSN =sn++; this->msgBodyAttribute.bPaket=0; this->msgBodyAttribute.Rev =0; this->msgBodyAttribute.msgDecodeType=0; memcpy(this->sim,pStrSim,strlen(pStrSim)); }; }; int diposMsgBody(tagMsgHead msgHead,const BYTE *pMsgBody,GPSINFO *gpsInfo); int getFullCmdLine(char *pDestBuf,tagMsgHead *pMsgHead,char *pstrMsgBody,int nMsgBodyLen); DWORD m_MsgSN;//ๅ…จๅฑ€ๆถˆๆฏๆตๆฐดๅท };
4e13ffda7d70058d57e055874533c84af2c3c117
36544b6dffb1fcf9943330004dc1e98699eaebfa
/arrosino.ino
303329dda3379751ee501c2a3495471ace10fc68
[]
no_license
CelineBateauKessler/arrosino
1ee7081a47ee476cbd6fa32df8b325af72fcecca
df408d046a26dd277210a32eb4a19dab8096eafd
refs/heads/master
2016-09-16T17:22:15.579262
2015-12-17T21:02:01
2015-12-17T21:02:01
46,009,493
0
0
null
null
null
null
UTF-8
C++
false
false
4,748
ino
arrosino.ino
/* Grove Temperature and Humidity Sensor * --> DHT library by: http://www.seeedstudio.com */ #include "DHT.h"; #define DHT_PIN A0 // what pin we're connected to #define DHT_TYPE DHT22 DHT dht(DHT_PIN, DHT_TYPE); /* Grove Moisture Sensor */ #define MOISTURE_PIN A1 /* Electrovalve */ #define ELECTROVALVE 4 /* Variables */ float humd = 0.0; float temp = 0.0; float moist = 0.0; float flow = 0.0; bool waterIsOn = false; bool waterWasOn = false; bool autoWaterOn = false; bool manualWaterOn = false; bool manualWaterOff = false; /* Communication with Atheros*/ #include <Bridge.h> #include <Process.h> /* Periodic sensor read */ const unsigned long MEASURE_PERIOD = 600000; // 10 minutes unsigned long lastRun = (unsigned long)-600000;//MEASURE_PERIOD; void setup() { Bridge.begin(); Console.begin(); dht.begin(); pinMode(ELECTROVALVE, OUTPUT); restartLinuxCron(); } void loop() { unsigned long now = millis(); // run again if it's been RUN_INTERVAL_MILLIS milliseconds since we last ran if (now - lastRun >= MEASURE_PERIOD) { lastRun = now; // Read sensors // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) humd = dht.readHumidity(); temp = dht.readTemperature(); moist = analogRead(A1)/10.0; // to get a value between 0 and 100 //flow = TODO update with true measure // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(temp) || isnan(humd)) { Console.println("Failed to read from DHT"); humd = 0.0; temp = 0.0; } else { Console.print("Temperature: "); Console.print(temp); Console.print(" deg\t"); Console.print("Humidity: "); Console.print(humd); Console.print(" %\t"); Console.print("Moisture: "); Console.print(moist); Console.println(); } sqlInsertMeasuresInDb(temp, humd, moist, flow); sqlUpdateWaterStatusInDb(flow); updateWaterCmd(); } // water ON / OFF // Read command from automatic process and manual commands char data[1]; Bridge.get("AUTO_WATER_ON", data, 1); autoWaterOn = (data[0] == '1'); Bridge.get("MANUAL_WATER_ON", data, 1); manualWaterOn = (data[0] == '1'); Bridge.get("MANUAL_WATER_OFF", data, 1); manualWaterOff = (data[0] == '1'); waterIsOn = autoWaterOn; if (manualWaterOn) {waterIsOn = true;} if (manualWaterOff) {waterIsOn = false;} if (waterIsOn){ flow = 100.0; // TODO remove digitalWrite(ELECTROVALVE, HIGH); } else { flow = 0.0; // TODO remove digitalWrite(ELECTROVALVE, LOW); } if (waterIsOn != waterWasOn) { sqlUpdateWaterStatusInDb(flow); // Default flow value only used for watering session time stamp Console.println (waterIsOn); } waterWasOn = waterIsOn; } /* Restart linux cron */ /*************************************/ void restartLinuxCron() { Process p; p.runShellCommand("/etc/init.d/cron start"); } /* Store sensor measures in database */ /*************************************/ unsigned int sqlInsertMeasuresInDb(float temp, float humd, float moist, float flow){ Process p; String cmd = "python "; String scriptName ="/mnt/sda1/arduino/www/arrosino/scripts/processSensorUpdate.py "; String scriptArgs = String(moist)+" "+String(humd)+" "+String(temp)+" "+String(flow); p.runShellCommand(cmd + scriptName + scriptArgs); // Read process output while (p.available()>0) { char c = p.read(); Console.print(c); } // Ensure the last bit of data is sent. Console.flush(); } /* Store watering status in database */ /*************************************/ unsigned int sqlUpdateWaterStatusInDb(float flow){ Process p; String cmd = "python "; String scriptName ="/mnt/sda1/arduino/www/arrosino/scripts/processWateringStatusUpdate.py "; String scriptArgs = String(flow); p.runShellCommand(cmd + scriptName + scriptArgs); // Read process output while (p.available()>0) { char c = p.read(); Console.print(c); } // Ensure the last bit of data is sent. Console.flush(); } /* Update watering command */ /*************************************/ void updateWaterCmd(){ Console.println("updateWaterCmd"); Process p; String cmd = "python "; String scriptName ="/mnt/sda1/arduino/www/arrosino/scripts/wateringOnOffTest.py "; p.runShellCommand(cmd + scriptName); // Read process output while (p.available()>0) { char c = p.read(); Console.print(c); } // Ensure the last bit of data is sent. Console.flush(); }
0723a21d8cd047a79338831076fc13a54887e496
b3a44c8c5319afba2870928b976d4ae543ece143
/mcucpp/ARM/Stm32f37x/clock.h
7b1862f25bf304e6b37e26241cc0ad9e448b9ff0
[ "BSD-3-Clause" ]
permissive
evugar/Mcucpp
58446aedc37746ae89dc2e9c0d0f1dbe30aacbf6
202d98587e8b9584370a32c1bafa2c7315120c9e
refs/heads/master
2021-07-11T19:07:39.871347
2020-07-21T19:01:42
2020-07-21T19:01:42
281,441,055
0
0
NOASSERTION
2020-07-21T15:52:45
2020-07-21T15:52:44
null
UTF-8
C++
false
false
14,119
h
clock.h
#pragma once #include "ioreg.h" #include <stm32f37x.h> #ifndef F_OSC #warning F_OSC is not defined. F_OSC is in its default value 8 MHZ. Verify that external cristal freq is correct. #define F_OSC 8000000u #endif namespace Mcucpp { namespace Clock { class ClockBase { protected: static const uint32_t ClockStartTimeout = 8000; static bool EnableClockSource(unsigned turnOnMask, unsigned waitReadyMask) { if(RCC->CR & waitReadyMask) return true; uint32_t timeoutCounter = 0; RCC->CR |= turnOnMask; while(((RCC->CR & waitReadyMask) == 0) && (timeoutCounter < ClockStartTimeout)) { timeoutCounter++; } return (RCC->CR & waitReadyMask) != 0; } static bool DisablelockSource(unsigned turnOnMask, unsigned waitReadyMask) { uint32_t timeoutCounter = 0; RCC->CR &= ~turnOnMask; while(((RCC->CR & waitReadyMask) != 0) && (timeoutCounter < ClockStartTimeout)) { timeoutCounter++; } return (RCC->CR & waitReadyMask) == 0; } }; class HseClock :public ClockBase { public: static uint32_t SrcClockFreq() { return F_OSC; } static uint32_t GetDivider() { return 1; } static uint32_t GetMultipler() { return 1; } static uint32_t ClockFreq() { return SrcClockFreq(); } static bool Enable() { return ClockBase::EnableClockSource(RCC_CR_HSEON, RCC_CR_HSERDY); } static bool Disable() { return ClockBase::DisablelockSource(RCC_CR_HSEON, RCC_CR_HSERDY); } }; class HsiClock :public ClockBase { public: static uint32_t SrcClockFreq() { return 8000000u; } static uint32_t GetDivider() { return 1; } static uint32_t GetMultipler() { return 1; } static uint32_t ClockFreq() { return SrcClockFreq(); } static bool Enable() { return ClockBase::EnableClockSource(RCC_CR_HSION, RCC_CR_HSIRDY); } static bool Disable() { return ClockBase::DisablelockSource(RCC_CR_HSION, RCC_CR_HSIRDY); } }; class LseClock :public ClockBase { public: static uint32_t SrcClockFreq() { return 32768; } static uint32_t GetDivider() { return 1; } static uint32_t GetMultipler() { return 1; } static uint32_t ClockFreq() { return SrcClockFreq(); } static bool Enable() { return false; // TODO } static bool Disable() { return false; // TODO } }; class PllClock :public ClockBase { public: enum ClockSource { Internal = RCC_CFGR_PLLSRC_HSI_Div2, External = RCC_CFGR_PLLSRC_PREDIV1, }; static uint32_t SrcClockFreq() { if ((RCC->CFGR & RCC_CFGR_PLLSRC) == 0) return HsiClock::ClockFreq(); else return HseClock::ClockFreq(); } static uint32_t GetDivider() { if ((RCC->CFGR & RCC_CFGR_PLLSRC) == 0) return 2; else return (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; } static uint32_t GetMultipler() { return ((RCC->CFGR & RCC_CFGR_PLLMULL) >> 18) + 2; } static void SetMultipler(uint8_t multiler) { multiler-=2; if(multiler > 15) multiler = 15; RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_PLLMULL) | (multiler << 18); } static void SetDivider(uint8_t divider) { divider-=1; if(divider > 15) divider = 15; RCC->CFGR2 = (RCC->CFGR2 & ~RCC_CFGR2_PREDIV1) | (divider); } static void SelectClockSource(ClockSource clockSource) { RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE) ) | clockSource; } static uint32_t ClockFreq() { return SrcClockFreq() / GetDivider() * GetMultipler(); } static bool Enable() { if ((RCC->CFGR & RCC_CFGR_PLLSRC) == 0) { if (!HsiClock::Enable()) return false; } else if (!HseClock::Enable()) return false; return ClockBase::EnableClockSource(RCC_CR_PLLON, RCC_CR_PLLRDY); } static void Disable() { ClockBase::DisablelockSource(RCC_CR_PLLON, RCC_CR_PLLRDY); } }; class SysClock { public: enum ClockSource { Internal = 0, External = 1, Pll = 2 }; public: static bool SelectClockSource(ClockSource clockSource) { uint32_t clockStatusValue; uint32_t clockSelectMask; if(clockSource == Internal) { clockStatusValue = RCC_CFGR_SWS_HSI; clockSelectMask = RCC_CFGR_SW_HSI; if (!HsiClock::Enable()) return false; }else if(clockSource == External) { clockStatusValue = RCC_CFGR_SWS_HSE; clockSelectMask = RCC_CFGR_SW_HSE; if (!HseClock::Enable()) return false; }if(clockSource == Pll) { clockStatusValue = RCC_CFGR_SWS_PLL; clockSelectMask = RCC_CFGR_SW_PLL; if (!PllClock::Enable()) return false; }else return false; FLASH->ACR = FLASH_ACR_PRFTBE | (uint32_t)FLASH_ACR_LATENCY_1; //RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2; RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | clockSelectMask; while ((RCC->CFGR & RCC_CFGR_SWS) != clockStatusValue) { } return true; } static uint32_t ClockFreq() { uint32_t clockSrc = RCC->CFGR & RCC_CFGR_SWS; switch (clockSrc) { case 0: return HsiClock::ClockFreq(); case RCC_CFGR_SWS_0: return HseClock::ClockFreq(); case RCC_CFGR_SWS_1: return PllClock::ClockFreq(); } return 0; } static uint32_t SrcClockFreq() { return ClockFreq(); } }; template<class Reg, unsigned Mask, class ClockSrc> class ClockControl :public ClockSrc { public: static void Enable() { Reg::Or(Mask); } static void Disable() { Reg::And(~Mask); } }; IO_BITFIELD_WRAPPER(RCC->CFGR, AhbPrescalerBitField, uint32_t, 4, 4); IO_BITFIELD_WRAPPER(RCC->CFGR, Apb1PrescalerBitField, uint32_t, 8, 3); IO_BITFIELD_WRAPPER(RCC->CFGR, Apb2PrescalerBitField, uint32_t, 11, 3); IO_BITFIELD_WRAPPER(RCC->CFGR, McoBitField, uint32_t, 24, 3); IO_BITFIELD_WRAPPER(RCC->CFGR3, Usart1ClockSwitch, uint32_t, 0, 2); IO_BITFIELD_WRAPPER(RCC->CFGR3, Usart2ClockSwitch, uint32_t, 16, 2); IO_BITFIELD_WRAPPER(RCC->CFGR3, Usart3ClockSwitch, uint32_t, 18, 2); IO_BITFIELD_WRAPPER(RCC->CFGR, AdcPrescaller, uint32_t, 14, 2); class AhbClock { public: enum Prescaller { Div1 = 0, Div2 = 0x08, Div4 = 0x09, Div8 = 0x0A, Div16 = 0x0B, Div64 = 0x0C, Div128 = 0x0D, Div256 = 0x0E, Div512 = 0x0F }; static uint32_t SrcClockFreq() { return SysClock::ClockFreq(); } static uint32_t ClockFreq() { uint32_t clock = SysClock::ClockFreq(); uint8_t clockPrescShift[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; uint8_t shiftBits = clockPrescShift[AhbPrescalerBitField::Get()]; clock >>= shiftBits; return clock; } static void SetPrescaller(Prescaller prescaller) { AhbPrescalerBitField::Set((uint32_t)prescaller); } }; class Apb1Clock { public: enum Prescaller { Div1 = 0, Div2 = 0x04, Div4 = 0x05, Div8 = 0x06, Div16 = 0x07, }; static uint32_t SrcClockFreq() { return AhbClock::ClockFreq(); } static uint32_t ClockFreq() { uint32_t clock = AhbClock::ClockFreq(); uint8_t clockPrescShift[] = {0, 0, 0, 0, 1, 2, 3, 4}; uint8_t shiftBits = clockPrescShift[Apb1PrescalerBitField::Get()]; clock >>= shiftBits; return clock; } static void SetPrescaller(Prescaller prescaller) { Apb1PrescalerBitField::Set((uint32_t)prescaller); } }; class Apb2Clock { public: enum Prescaller { Div1 = 0, Div2 = 0x04, Div4 = 0x05, Div8 = 0x06, Div16 = 0x07, }; static uint32_t SrcClockFreq() { return AhbClock::ClockFreq(); } static uint32_t ClockFreq() { uint32_t clock = AhbClock::ClockFreq(); const uint8_t clockPrescShift[] = {0, 0, 0, 0, 1, 2, 3, 4}; uint8_t shiftBits = clockPrescShift[Apb2PrescalerBitField::Get()]; clock >>= shiftBits; return clock; } static void SetPrescaller(Prescaller prescaller) { Apb2PrescalerBitField::Set((uint32_t)prescaller); } }; class AdcClockSource { public: enum ClockSource { Apb2 = 0, }; enum Prescaller { Div2 = 0, Div4 = 1, Div6 = 2, Div8 = 3, }; static bool SelectClockSource(ClockSource) { return true; } static void SetPrescaller(Prescaller prescaller) { AdcPrescaller::Set((uint32_t)prescaller); } static uint32_t SrcClockFreq() { return Apb2Clock::ClockFreq(); } static uint32_t ClockFreq() { return SrcClockFreq() / ((AdcPrescaller::Get() + 1) * 2); } }; class Usart1ClockSource { public: enum ClockSource { Ahb = 0, System = 1, Lse = 2, Hsi = 3, }; static bool SelectClockSource(ClockSource source) { Usart1ClockSwitch::Set((uint32_t)source); return true; } static uint32_t SrcClockFreq() { switch(Usart1ClockSwitch::Get()) { case 0: return AhbClock::ClockFreq(); case 1: return SysClock::ClockFreq(); case 2: return LseClock::ClockFreq(); case 3: return HsiClock::ClockFreq(); } return 0; } static uint32_t ClockFreq() { return SrcClockFreq(); } }; IO_REG_WRAPPER(RCC->APB2ENR, PeriphClockEnable2, uint32_t); IO_REG_WRAPPER(RCC->APB1ENR, PeriphClockEnable1, uint32_t); IO_REG_WRAPPER(RCC->AHBENR, AhbClockEnableReg, uint32_t); typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_DMA1EN , AhbClock> Dma1Clock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_DMA2EN , AhbClock> Dma2Clock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_SRAMEN , AhbClock> SramClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_FLITFEN, AhbClock> FlitfClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_CRCEN , AhbClock> CrcClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIOAEN, AhbClock> GpioaClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIOBEN, AhbClock> GpiobClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIOCEN, AhbClock> GpiocClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIODEN, AhbClock> GpiodClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIOEEN, AhbClock> GpioeClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_GPIOFEN, AhbClock> GpiofClock; typedef ClockControl<AhbClockEnableReg, RCC_AHBENR_TSEN , AhbClock> TsClock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_SYSCFGEN, Apb2Clock> SyscfgClock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_ADC1EN , AdcClockSource> Adc1Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_SPI1EN , Apb2Clock> Spi1Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_USART1EN, Usart1ClockSource> Usart1Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_TIM15EN , Apb2Clock> Tim15Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_TIM16EN , Apb2Clock> Tim16Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_TIM17EN , Apb2Clock> Tim17Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_TIM19EN , Apb2Clock> Tim19Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_SDADC1EN, Apb2Clock> SdAdc1Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_SDADC2EN, Apb2Clock> SdAdc2Clock; typedef ClockControl<PeriphClockEnable2, RCC_APB2ENR_SDADC3EN, Apb2Clock> SdAdc3Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM2EN , Apb1Clock> Tim2Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM3EN , Apb1Clock> Tim3Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM4EN , Apb1Clock> Tim4Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM5EN , Apb1Clock> Tim5Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM6EN , Apb1Clock> Tim6Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM7EN , Apb1Clock> Tim7Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM12EN , Apb1Clock> Tim12Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM13EN , Apb1Clock> Tim13Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM14EN , Apb1Clock> Tim14Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_TIM18EN , Apb1Clock> Tim18Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_WWDGEN , Apb1Clock> WwdgClock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_SPI2EN , Apb1Clock> Spi2Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_SPI3EN , Apb1Clock> Spi3Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_USART2EN, Apb1Clock> Usart2Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_USART3EN, Apb1Clock> Usart3Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_I2C1EN , Apb1Clock> I2c1Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_I2C2EN , Apb1Clock> I2c2Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_USBEN , Apb1Clock> UsbClock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_CAN1EN , Apb1Clock> CanClock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_PWREN , Apb1Clock> PwrClock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_DAC1EN , Apb1Clock> Dac1Clock; typedef ClockControl<PeriphClockEnable1, RCC_APB1ENR_DAC2EN , Apb1Clock> Dac2Clock; } }
59a4bb9ea7926d8d43bd3806e30ca2d0fdf52390
45716a35c9fa862145b20e68b47a3187bbfbfb81
/src/pks/energy/base/energy_base_physics.cc
89e82d9d5e7f1e52b81081e8931b227cb352151b
[ "BSD-3-Clause" ]
permissive
ddwivedi08/ats
3c5f3e69797ddcd07110a4c80c47581034c28a2f
932aba910b977e86121942cd24f2059f0b6bee65
refs/heads/master
2021-01-19T14:53:40.104447
2017-04-06T01:16:22
2017-04-06T01:16:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,658
cc
energy_base_physics.cc
/* -*- mode++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Solves: de/dt + q dot grad h = div Ke grad T + S? ------------------------------------------------------------------------- */ #include "advection.hh" #include "FieldEvaluator.hh" #include "energy_base.hh" #include "Op.hh" namespace Amanzi { namespace Energy { // ------------------------------------------------------------- // Accumulation of energy term de/dt // ------------------------------------------------------------- void EnergyBase::AddAccumulation_(const Teuchos::Ptr<CompositeVector>& g) { double dt = S_next_->time() - S_inter_->time(); // update the energy at both the old and new times. S_next_->GetFieldEvaluator(energy_key_)->HasFieldChanged(S_next_.ptr(), name_); S_inter_->GetFieldEvaluator(energy_key_)->HasFieldChanged(S_inter_.ptr(), name_); // get the energy at each time Teuchos::RCP<const CompositeVector> e1 = S_next_->GetFieldData(energy_key_); Teuchos::RCP<const CompositeVector> e0 = S_inter_->GetFieldData(energy_key_); // Update the residual with the accumulation of energy over the // timestep, on cells. g->ViewComponent("cell", false) ->Update(1.0/dt, *e1->ViewComponent("cell", false), -1.0/dt, *e0->ViewComponent("cell", false), 1.0); }; // ------------------------------------------------------------- // Advective term for transport of enthalpy, q dot grad h. // ------------------------------------------------------------- void EnergyBase::AddAdvection_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& g, bool negate) { // set up the operator // NOTE: fluxes are a MOLAR flux by choice of the flow pk, i.e. // [flux] = mol/s // NOTE: this will be the eventual way to ensure it is up to date, // but there is no FieldEvaluator for darcy flux yet. When there // is, we can take the evaluation out of Flow::commit_state(), // but for now we'll leave it there and assume it has been updated. --etc // S->GetFieldEvaluator(flux_key_)->HasFieldChanged(S.ptr(), name_); Teuchos::RCP<const CompositeVector> flux = S->GetFieldData(flux_key_); db_->WriteVector(" adv flux", flux.ptr(), true); matrix_adv_->global_operator()->Init(); matrix_adv_->Setup(*flux); matrix_adv_->UpdateMatrices(*flux); // apply to enthalpy S->GetFieldEvaluator(enthalpy_key_)->HasFieldChanged(S.ptr(), name_); Teuchos::RCP<const CompositeVector> enth = S->GetFieldData(enthalpy_key_);; ApplyDirichletBCsToEnthalpy_(S.ptr()); matrix_adv_->ApplyBCs(bc_adv_, true); // apply matrix_adv_->global_operator()->ComputeNegativeResidual(*enth, *g, false); } // ------------------------------------------------------------- // Diffusion term, div K grad T // ------------------------------------------------------------- void EnergyBase::ApplyDiffusion_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& g) { // update the thermal conductivity UpdateConductivityData_(S_next_.ptr()); Teuchos::RCP<const CompositeVector> conductivity = S_next_->GetFieldData(uw_conductivity_key_); // update the stiffness matrix matrix_diff_->global_operator()->Init(); matrix_diff_->SetScalarCoefficient(conductivity, Teuchos::null); matrix_diff_->UpdateMatrices(Teuchos::null, Teuchos::null); Teuchos::RCP<const CompositeVector> temp = S->GetFieldData(key_); // update the flux if needed Teuchos::RCP<CompositeVector> flux = S->GetFieldData(energy_flux_key_, name_); matrix_diff_->UpdateFlux(*temp, *flux); // finish assembly of the stiffness matrix matrix_diff_->ApplyBCs(true, true); // calculate the residual matrix_diff_->global_operator()->ComputeNegativeResidual(*temp, *g); }; // --------------------------------------------------------------------- // Add in energy source, which are accumulated by a single evaluator. // Note that that evaluator applies the factor of cell volume. // --------------------------------------------------------------------- void EnergyBase::AddSources_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& g) { Teuchos::OSTab tab = vo_->getOSTab(); // external sources of energy if (is_source_term_) { Epetra_MultiVector& g_c = *g->ViewComponent("cell",false); // Update the source term S->GetFieldEvaluator(source_key_)->HasFieldChanged(S, name_); const Epetra_MultiVector& source1 = *S->GetFieldData(source_key_)->ViewComponent("cell",false); // Add into residual unsigned int ncells = g_c.MyLength(); for (unsigned int c=0; c!=ncells; ++c) { g_c[0][c] -= source1[0][c]; } if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << "Adding external source term" << std::endl; db_->WriteVector(" Q_ext", S->GetFieldData(source_key_).ptr(), false); db_->WriteVector("res (src)", g, false); } } } void EnergyBase::AddSourcesToPrecon_(const Teuchos::Ptr<State>& S, double h) { // external sources of energy (temperature dependent source) if (is_source_term_ && S->GetFieldEvaluator(source_key_)->IsDependency(S, key_)) { std::vector<double>& Acc_cells = preconditioner_acc_->local_matrices()->vals; S->GetFieldEvaluator(source_key_)->HasFieldDerivativeChanged(S, name_, key_); const Epetra_MultiVector& dsource_dT = *S->GetFieldData(dsource_dT_key_)->ViewComponent("cell",false); unsigned int ncells = dsource_dT.MyLength(); for (unsigned int c=0; c!=ncells; ++c) { Acc_cells[c] -= dsource_dT[0][c]; } } } // ------------------------------------------------------------- // Plug enthalpy into the boundary faces manually. // This will be removed once boundary faces exist. // ------------------------------------------------------------- void EnergyBase::ApplyDirichletBCsToEnthalpy_(const Teuchos::Ptr<State>& S) { // put the boundary fluxes in faces for Dirichlet BCs. S->GetFieldEvaluator(enthalpy_key_)->HasFieldChanged(S, name_); const Epetra_MultiVector& enth_bf = *S->GetFieldData(enthalpy_key_)->ViewComponent("boundary_face",false); const Epetra_Map& vandalay_map = mesh_->exterior_face_map(false); const Epetra_Map& face_map = mesh_->face_map(false); int nbfaces = enth_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { AmanziMesh::Entity_ID f = face_map.LID(vandalay_map.GID(bf)); if (bc_markers_adv_[f] == Operators::OPERATOR_BC_DIRICHLET) { bc_values_adv_[f] = enth_bf[0][bf]; } } } } //namespace Energy } //namespace Amanzi
a89d8fb8d1042ac24a771f0a3c0a90d2fa008ffe
bcf0c52fa95f9111756a7ab3829d9ccd340a5e95
/src/ckodo/encoder.hpp
ef49a69d9e924df6d3e09cbc3f251f837b3a427b
[]
no_license
msherif4/kodo-c-bindings
fc52caa3c75018ba68d8eb5a909008dc608b66c4
bc54077bed2f10c50e5f5013ce068033a35f864d
refs/heads/master
2020-12-25T06:03:31.775268
2013-07-14T22:30:43
2013-07-14T22:30:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
549
hpp
encoder.hpp
// Copyright Steinwurf ApS 2011-2013. // Distributed under the "STEINWURF RESEARCH LICENSE 1.0". // See accompanying file LICENSE.rst or // http://www.steinwurf.com/licensing #pragma once #include "coder.hpp" namespace kodo { struct encoder : public coder { virtual uint32_t encode(uint8_t *) = 0; virtual void set_symbols( const uint8_t* data, uint32_t size) = 0; virtual void set_symbol( uint32_t index, const uint8_t* data, uint32_t size) = 0; virtual ~encoder(){} }; }
476f95587e97a1b3fa4049cf07f38c58a34fae51
b8d457b9ce160911e6eba460e69c72d9d31ed260
/ArxRle/Reactor/ArxRleUiTdcTransientReactors.cpp
c458a069cda13184cc553ee8a05416aa7ab8b113
[]
no_license
inbei/AutoDesk-ArxRle-2018
b91659a34a73727987513356bfcd1bff9fe09ee3
3c8d4a34f586467685c0f9bce7c3693233e43308
refs/heads/master
2023-01-19T08:27:38.231533
2020-11-25T00:52:13
2020-11-25T00:52:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,565
cpp
ArxRleUiTdcTransientReactors.cpp
// ////////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // #include "StdAfx.h" #if defined(_DEBUG) && !defined(AC_FULL_DEBUG) #error _DEBUG should not be defined except in internal Adesk debug builds #endif #include "ArxRleUiTdcTransientReactors.h" #include "Snoop/ArxRleUiDlgObjState.h" #include "AcadUtils/ArxRleUtils.h" #include "ArxRle.h" #include "ArxRleUiTdmREactors.h" #include "AcadUtils/ArxRleDocLockWrite.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // static state variables for showing state of notifying object BOOL ArxRleUiTdcTransientReactors::m_doStateModified = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateCancelled = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateErased = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateCopied = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateGoodbye = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateOpenMod = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateSubObjMod = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateModUndone = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateModXdata = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateModGraphics = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateUnappended = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateReappended = FALSE; BOOL ArxRleUiTdcTransientReactors::m_doStateClosed = FALSE; // These statics are all MDI aware ArxRleTransientObjReactor* ArxRleUiTdcTransientReactors::m_objReactor = NULL; ArxRleTransientEntReactor* ArxRleUiTdcTransientReactors::m_entReactor = NULL; /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::ArxRleUiTdcTransientReactors ** ** **jma ** *************************************/ ArxRleUiTdcTransientReactors::ArxRleUiTdcTransientReactors() : ArxRleUiTdcObjReactorsBase() { //{{AFX_DATA_INIT(ArxRleUiTdcTransientReactors) //}}AFX_DATA_INIT } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::cleanUpReactors ** static function to clean up any left over reactors if ** app exits and they are still turned on. ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::cleanUpReactors() { delete m_objReactor; delete m_entReactor; m_objReactor = NULL; m_entReactor = NULL; } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::DoDataExchange ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::DoDataExchange(CDataExchange* pDX) { ArxRleUiTdcObjReactorsBase::DoDataExchange(pDX); //{{AFX_DATA_MAP(ArxRleUiTdcTransientReactors) DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_MODIFIED, m_doStateModified); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_CANCELLED, m_doStateCancelled); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_ERASED, m_doStateErased); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_COPIED, m_doStateCopied); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_GOODBYE, m_doStateGoodbye); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_OPENMOD, m_doStateOpenMod); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_SUBOBJMOD, m_doStateSubObjMod); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_MODUNDONE, m_doStateModUndone); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_MODXDATA, m_doStateModXdata); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_MODGRAPHICS, m_doStateModGraphics); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_UNAPPENDED, m_doStateUnappended); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_REAPPENDED, m_doStateReappended); DDX_Check(pDX, ARXRLE_REACTORS_CK_STATE_CLOSED, m_doStateClosed); //}}AFX_DATA_MAP } ///////////////////////////////////////////////////////////////////////////// // ArxRleUiTdcTransientReactors message handlers BEGIN_MESSAGE_MAP(ArxRleUiTdcTransientReactors, ArxRleUiTdcObjReactorsBase) //{{AFX_MSG_MAP(ArxRleUiTdcTransientReactors) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // ArxRleUiTdcTransientReactors message handlers /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::OnInitDialog ** ** **jma ** *************************************/ BOOL ArxRleUiTdcTransientReactors::OnInitDialog() { ArxRleUiTdcObjReactorsBase::OnInitDialog(); return TRUE; } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::getAttachedObjects ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::getAttachedObjects(AcDbObjectIdArray& objIds) { if (m_objReactor) objIds = m_objReactor->m_objList; } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::getAttachedEntities ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::getAttachedEntities(AcDbObjectIdArray& objIds) { if (m_entReactor) objIds = m_entReactor->m_objList; } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::detachSelectedEnts ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::detachSelectedEnts(const AcDbObjectIdArray& objIds) { if (m_entReactor != NULL) { Acad::ErrorStatus es; AcDbEntity* ent; ArxRleDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbEntity(ent, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { m_entReactor->delFromObject(ent); ent->close(); } else { ArxRleUtils::rxErrorAlert(es); } } else { ArxRleUtils::rxErrorAlert(es); } } } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::detachSelectedObjs ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::detachSelectedObjs(const AcDbObjectIdArray& objIds) { if (m_objReactor != NULL) { Acad::ErrorStatus es; AcDbObject* obj; ArxRleDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbObject(obj, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { m_objReactor->delFromObject(obj); obj->close(); } else { ArxRleUtils::rxErrorAlert(es); } } else { ArxRleUtils::rxErrorAlert(es); } } } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::attachObjReactors ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::attachObjReactors(const AcDbObjectIdArray& objIds) { // re-use same reactor if it is already allocated if (m_objReactor == NULL) { acutPrintf(_T("\nAllocating new ObjectReactor...")); m_objReactor = new ArxRleTransientObjReactor; } Acad::ErrorStatus es; AcDbObject* obj; ArxRleDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbObject(obj, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { m_objReactor->addToObject(obj); obj->close(); } else { ArxRleUtils::rxErrorAlert(es); } } else { ArxRleUtils::rxErrorAlert(es); } } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::attachEntReactors ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::attachEntReactors() { // re-use same reactor if it is already allocated if (m_entReactor == NULL) { acutPrintf(_T("\nAllocating new EntityReactor...")); m_entReactor = new ArxRleTransientEntReactor; } // unfortunately, this structure for making this page know about the main // dialog means that we could never use this page within another main dialog // container. So, cast to our known type of owning Main Dialog ArxRleUiTdmReactors* tdmReactors = static_cast<ArxRleUiTdmReactors*>(GetMainDialog()); tdmReactors->attachEntTransientReactor(m_entReactor); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::detachEntReactors ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::detachEntReactors() { // unfortunately, this structure for making this page know about the main // dialog means that we could never use this page within another main dialog // container. So, cast to our known type of owning Main Dialog ArxRleUiTdmReactors* tdmReactors = static_cast<ArxRleUiTdmReactors*>(GetMainDialog()); tdmReactors->detachEntTransientReactor(m_entReactor); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxCacelled ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxCacelled(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateCancelled) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Cancelled")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxCopied ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxCopied(const AcDbObject* obj, const AcDbObject* newObject) { if (ArxRleUiTdcTransientReactors::m_doStateCopied) { ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Copied (source object)")); ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Copied (new object)")); } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxErased ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxErased(const AcDbObject* obj, Adesk::Boolean isErasing) { if (ArxRleUiTdcTransientReactors::m_doStateErased) { if (isErasing) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Erase")); else ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Un-erase")); } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxGoodbye ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxGoodbye(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateGoodbye) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Goodbye")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxOpenedModify ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxOpenedModify(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateOpenMod) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Open For Modify")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxModified ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxModified(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateModified) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Modified")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxSubObjModified ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxSubObjModified(const AcDbObject* obj, const AcDbObject* subObj) { if (ArxRleUiTdcTransientReactors::m_doStateSubObjMod) { ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("SubObject Modified (main object)")); ArxRleUiTdcTransientReactors::doStateDbox(subObj, _T("SubObject Modified (sub-object)")); } } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxModifyUndone ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxModifyUndone(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateModUndone) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Modify Undone")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxModifiedXdata ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxModifiedXdata(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateModXdata) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Modified Xdata")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxModifiedGraphics ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxModifiedGraphics(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateModGraphics) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Modified Graphics")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxUnappended ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxUnappended(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateUnappended) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Un-appended")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxReappended ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxReappended(const AcDbObject* obj) { if (ArxRleUiTdcTransientReactors::m_doStateReappended) ArxRleUiTdcTransientReactors::doStateDbox(obj, _T("Re-appended")); } /**************************************************************************** ** ** ArxRleUiTdcTransientReactors::doStateDboxClosed ** ** **jma ** *************************************/ void ArxRleUiTdcTransientReactors::doStateDboxClosed(const AcDbObjectId& objId) { if (ArxRleUiTdcTransientReactors::m_doStateClosed) ArxRleUiTdcTransientReactors::doStateDbox(objId, _T("Object Closed")); }
3b43971155e4730f3c71b9253cc996efe5c9bf54
cdf49187bd2a6ab73c9aa34e03d1ac9d5c81e348
/src/Particle.cxx
f66b604686b577f1c9538ec7546183777eb29d23
[]
no_license
rdisipio/MAMbo
4770fddbba2700f0ec3cc5970b676c39178d6810
75ac630402b8c8aaa2febf8218b0213a7f2320dd
refs/heads/master
2020-05-04T10:33:00.058916
2017-09-12T09:45:28
2017-09-12T09:45:28
179,089,927
1
0
null
null
null
null
UTF-8
C++
false
false
900
cxx
Particle.cxx
/* * File: Particle.cpp * Author: Michele * * Created on 31 October 2014, 18:22 */ #include "Particle.h" Particle::Particle() { } Particle::Particle(EventData::Reco_t& particle, int index) { pt = particle.pT.at(index); eta = particle.eta.at(index); phi = particle.phi.at(index); E = particle.E.at(index); m = particle.m.at(index); y = PhysicsHelperFunctions::Rapidity(particle, index); } Particle::Particle(EventData::Truth_t& particle, int index) { pt = particle.pT.at(index); eta = particle.eta.at(index); phi = particle.phi.at(index); E = particle.E.at(index); m = particle.m.at(index); y = PhysicsHelperFunctions::Rapidity(particle, index); } Particle::Particle(const Particle& orig) { } Particle::~Particle() { } TLorentzVector Particle::MakeLorentz() { TLorentzVector vec; vec.SetPtEtaPhiM(pt, eta, phi, m); return vec; }
c07d0aef4949df7dc0b44c4f20dcd0eb41debdcf
900e9f27338ec229a67e3aa46b9031e3309ca317
/RBE2002code/src/drive.cpp
c78befda085f4568e5160c111025a66d918b07a2
[]
no_license
JosuContrer/RBE2002
68d721302ad79f255b768605d5a420221ecfff11
164e593f120f8cb0ade095a6e53dd8625406d45c
refs/heads/master
2021-09-13T05:52:49.394724
2018-04-25T18:08:39
2018-04-25T18:08:39
125,138,830
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
drive.cpp
#include "Motor.h" #include "drive.h" #include "globalPins.h" #include <Ultrasonic.h> #include "PID.h" /** * Constructor for drive class */ drive::drive(): leftMotor(DLEFTMOTOR, ALEFTMOTOR, false), rightMotor(DRIGHTMOTOR, ARIGHTMOTOR, true) { } /** * Initialize drive class by setting motors to be stopped */ void drive::initialize(){ leftMotor.setPower(0); rightMotor.setPower(0); } /** * Sets drivetrain motors to be left and right input speeds * @param lMotor Left motor speed * @param rMotor Right motor speed */ void drive::setPower(int lMotor, int rMotor){ leftMotor.setPower(lMotor); rightMotor.setPower(rMotor); }
01df4d6e15ffec42eddd447867607375e8d79e1f
4228045ad91468ca27b78ebb5d566f6fb2ecdf84
/ProjectGoogle/tictactoe.cpp
d6d400782fb48af09eafc8926e8c70f071a4811b
[]
no_license
vineethkumart/snippet
5bc622c6475bdc68e4ff9d49e6f5e8253dc4c85d
01824f8a39bdfe23ccd51c8e6f1f9e829591905c
refs/heads/master
2023-06-05T05:13:38.711649
2021-06-26T15:56:51
2021-06-26T15:56:51
47,300,923
0
0
null
null
null
null
UTF-8
C++
false
false
1,721
cpp
tictactoe.cpp
#include<iostream> #include <vector> #include <cassert> typedef enum { EMPTY, P1, P2 } mark_t; bool check(std::vector<std::vector<mark_t>>& board, const mark_t p) { const int N = board.size(); assert(board[0].size() == N); // check all rows, colums and 2 diagonals for (int i = 0; i < N; i++) { // check each of the i rows if (board[i][0] != p) continue; bool win(true); for (int j = 0; j < N; j++) { if (board[i][j] != p) { win = false; break; } } if (win) return true; } for (int j = 0; j < N; j++) { // check each of the i columns if (board[0][j] != p) continue; bool win(true); for (int i = 0; i < N; i++) { if (board[i][j] != p) { win = false; break; } } if (win) return true; } // check diag 1 bool win(true); for (int i = 0; i < N; i++) { if (board[i][i] != p) { win = false; break; } } if (win) return true; // check diag 2 for (int i = 0; i < N; i++) { if (board[N-i-1][i] != p) { win = false; break; } } if (win) return true; return false; } int main() { const int N = 3; std::vector<std::vector<mark_t>> board(N, std::vector<mark_t>(N, EMPTY)); board[0][0] = P1; board[1][0] = P1; std::cout << check(board, P1); board[2][0] = P1; std::cout << check(board, P1); board[2][0] = P2; std::cout << check(board, P1); board[1][1] = P1; board[2][2] = P1; std::cout << check(board, P1); return 0; }
40d7e844fac2a9665f96c12bda68878bc911b279
585fca9077b618c565157935328d131d6db56190
/main.cpp
c8a07058d8043b23f70269302b747f4591799af4
[]
no_license
Junyao16/Polynomial-Calculator-in-Linux
c81820641da4bc32773ddc5ac878eee71fdeb545
87a535bb6234371c00aa816af5fc76452ccc8344
refs/heads/master
2023-01-22T18:12:30.002826
2020-06-03T15:19:27
2020-06-03T15:35:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
103
cpp
main.cpp
#include<iostream> #include"control.h" using namespace std; int main(){ return control(); }
e7838a882cf35ed1de0cb10f37d02fab17f0812e
a079ee9042946248564bb7eed4e6efd61b50a76e
/Josephus_problem.cpp
c0974fcad2ecfa8b554f5221bde1775538356817
[]
no_license
Sreepadashastry/APS
1055fdb7332acd9a780d4dee26d85192cd0342a5
2fafcb72601ef21420db93c268daf3b20fffd7b9
refs/heads/master
2020-12-20T20:04:05.916026
2020-05-17T20:07:48
2020-05-17T20:07:48
236,195,438
0
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
Josephus_problem.cpp
#include <iostream> #include<math.h> #include<bits/stdc++.h> using namespace std; int last_pers(int n) { int l=ceil(log(n)/log(2)); if(n!=1 && (n&(n-1))==0) l=l+1; int diff=n-pow(2,l-1); return 2*diff+1; } int main() { int n; cin>>n; cout<<last_pers(n); return 0; }
7098a4d16d0a2aa13ba2f5aeed437efcece8a4e7
92d603849f9470804b4eb850e14660bc61181950
/2_7GCD.cpp
e9657a54fb7d75532c62292e368a8a45e2aec832
[]
no_license
Dthird/BOP
9ede1d5561a625c49433e84dac7c2d7c808db7a1
a6e9cb24265eb122d8158711ee6cbf1ae7d5c940
refs/heads/master
2016-09-05T15:28:09.111238
2015-02-03T13:11:38
2015-02-03T13:11:38
29,900,345
0
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
2_7GCD.cpp
#include <iostream> using namespace std; /* Solution 1: k = x / y; b = x % y x = k * y + b gcd(x, y) = gcd(y, b) */ long gcd1(long x, long y){ return y == 0 ? x : gcd1(y, x%y); } /* Solution 2: gcd(x, y) = gcd(x-y, y) */ long gcd2(long x, long y){ if(x < y) return gcd2(y, x); return y == 0 ? x : gcd2(x-y, y); } /* Solution 3: if y = k * y1, x = k * x1 then gcd(x, y) = k * gcd(x1, y1) if x = p * x1 and if p is a prime number, then y % p != 0 then f(x, y) = f(x1, y) discuss x and y 's even and odd cases! let p = 2 if x and y are both even, gcd(x, y) = 2 * gcd(x>>1, y>>1) if x is even and y is odd, gcd(x, y) = gcd(x>>1, y) if x is odd and y is even, gcd(x, y) = gcd(x, y>>1) if x and y are both odd, gcd(x, y) = gcd(x-y, y) */ int main(){ cout << gcd1(1100100210001,120200021) << endl; return 0; }
be00c1c49d39704d076431e1ed35bd2c21ad319f
62d0ff2de41f373524c4822570b1ac01e00f0c37
/estrutura de dados/arvore_binaria/main_bst.cpp
2880b233d4a7b1b1ee7e8dd5bc7d1ed532b4d399
[ "MIT" ]
permissive
Lucas-MSF/Cpp
9474c0d5f75f676c9ae4a5c0000a46b3e116d376
8eaac18aaef5edf6127a7b3da6af9cc6de7748d4
refs/heads/main
2023-08-18T04:00:31.579081
2021-09-29T01:50:05
2021-09-29T01:50:05
411,490,363
0
0
null
null
null
null
UTF-8
C++
false
false
2,396
cpp
main_bst.cpp
#include <iostream> #include "bst.h" #include <stdlib.h> using namespace std; void menu(int resposta, bst& arvore) { string nome; int ra; bool buscar=false; if(resposta==1) { cout<<"Insira o nome do aluno: "; cin>>nome; cout<<"Insira o RA do aluno: "; cin>> ra; Aluno aluno(ra,nome); arvore.push(aluno); }else if(resposta==2) { if(arvore.is_empty()){ cout<<"A pilha esta vazia, nao e possivel inserir elementos.\n"; }else{ cout<<"Insira o RA do aluno q vc deseja remover: "; cin>>ra; Aluno aluno(ra," "); arvore.pop(aluno); } }else if(resposta==3) { cout<<"Insira o RA do aluno que deseja buscar: "; cin>>ra; Aluno aluno(ra, " "); arvore.search(aluno,buscar); if(buscar) { cout<<"Aluno encontrado."<<endl; cout<<"Nome: "<<aluno.retorna_Nome()<<endl; cout<<"RA: "<<aluno.retorna_Ra()<<endl; }else { cout<<"aluno nao encontrado."<<endl; } }else if(resposta==4) { int imprimir; cout<<"Insira a maneira q deseja imprimir a arvore: \n"; cout<<"[1] Pre-ordem\n"; cout<<"[2] Em ordem\n"; cout<<"[3] Pos-ordem\n"; cin>> imprimir; if(imprimir==1){ arvore.imprimirPreOrdem(arvore.obterRaiz()); }else if( imprimir==2){ arvore.imprimirEmOrdem(arvore.obterRaiz()); }else if (imprimir==3) { arvore.imprimirPosOrdem(arvore.obterRaiz()); }else{ cout<<"Opcao invalida!\n"; } }else if(resposta==5) { arvore.~bst(); }else if(resposta==6) { cout<<"encerrando programa..."<<endl; }else { cout<<"Opcao invalida!"<<endl; } } int main() { bst arvore; int resposta; do{ system("cls"); cout<<"[1] adcionar elemento"<<endl; cout<<"[2] remover elemento"<<endl; cout<<"[3] buscar elemento"<<endl; cout<<"[4] imprimir arvore"<<endl; cout<<"[5] deletar arvore"<<endl; cout<<"[6] sair"<<endl; cout<<">>"; cin>>resposta; menu(resposta,arvore); system("pause"); }while(resposta!=6); return 0; }
bf60191fe4537486e047ce6c6071e1c69ea17114
b266b49440414f063a803d3d4287907e1827ef64
/Source/GlobalGameJam2020/RoomDamageController.h
c92f9f679fd478334c17e7d63046b91c59ebc338
[]
no_license
Kylejohn175/ReviveTheHiveRevisited
4fd1981bb956015b5278c61abd2b80eddfedb607
1030f163a0feb1d4dfc9aba077a66162282bfc26
refs/heads/master
2020-12-29T04:51:46.301572
2020-02-26T16:16:10
2020-02-26T16:16:10
238,456,240
1
0
null
2020-02-26T16:16:12
2020-02-05T13:25:48
C++
UTF-8
C++
false
false
1,014
h
RoomDamageController.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ShipEvent_Actor.h" #include "RoomDamageController.generated.h" UCLASS() class GLOBALGAMEJAM2020_API ARoomDamageController : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ARoomDamageController(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; AShipEvent_Actor* shipEventHandler; UPROPERTY(EditAnywhere) TEnumAsByte<EventRoom> roomType; // Event Handling UFUNCTION() void RoomBreaking(EventRoom breakingRoomType); UFUNCTION() void RoomFixed(EventRoom fixedRoomType); // Damage Details UPROPERTY(EditAnywhere) bool isDamaging; UPROPERTY(EditAnywhere) float timeToDamage; float currentDamageTimer; UPROPERTY(EditAnywhere) float roomDamageValue; };
3d63d8fea1f1885b45da061507fd9aac03e9c1c9
6413ca249100812bc84f2a0a948c3173c93d4717
/include/bootinfo.hh
add17a4af89641cbf34feb0f6eb7c5fdff714b5c
[]
no_license
mbrock/jambos
00ee7cb4cdc72e64a82aa04433a95865c2554773
ff85ccaab23d050834337d001c65405f09d10382
refs/heads/master
2020-04-29T11:14:23.748871
2009-06-01T23:18:38
2009-06-01T23:18:38
191,789
7
2
null
2015-06-08T14:05:22
2009-05-03T23:34:47
C++
UTF-8
C++
false
false
317
hh
bootinfo.hh
#ifndef BOOTINFO_HH #define BOOTINFO_HH #include <common.hh> struct MemoryMapEntry { u64_t base; u64_t length; u32_t type; } __attribute__ ((__packed__)); struct BootInfo { u16_t memory_map_entries; MemoryMapEntry memory_map[32]; } __attribute__ ((__packed__)); extern BootInfo bootinfo; #endif
16cc1af2d0efd4508d07aee050c15b829f520af3
534f1bb6a4cc2ac5d337ea0be7b8f00017b8169c
/motors/Navigator.cpp
e77d8b22c3ee25044695c223ca1763a9c94a9408
[]
no_license
KLINKBOT/arduino
96c99cfd5d121fafe66638e1c957b54d56fea2eb
129535e10a8aa05a5b2da6ce7b8a4aee4a635864
refs/heads/master
2021-01-22T14:46:50.881190
2012-03-29T06:57:13
2012-03-29T06:57:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,428
cpp
Navigator.cpp
#include <PID_v1.h> #include "Common.h" #include "Navigator.h" #include "MotorController.h" #include "ESC.h" #include "IMU.h" #include "Eyes.h" #define SPEED 150 #define LOOK_DURATION 2000 #define TURN_DURATION 1200 #define HEADING_CORRECTION_INTERVAL 500 Navigator::Navigator(PlatformMotionController &platform, ESC &esc, IMU &imu, Eyes &eyes) : platform(&platform), esc(&esc), imu(&imu), eyes(&eyes), state(Stopped), nextState(Starting), enteredAt(0) { difference = 0; actualHeading = 0; desiredHeading = 0; pid = NULL; memcpy(&command, &Forward, sizeof(platform_command_t)); } boolean Navigator::isMoving() { return state == Searching; } void Navigator::begin() { } void Navigator::search() { nextState = Searching; } void Navigator::stop() { nextState = Stopped; } void Navigator::service() { boolean entered = nextState != state; if (entered) { enteredAt = millis(); } state = nextState; switch (state) { case Starting: break; case Stopped: if (entered) { DPRINTF("Nav: Stopping\n\r"); esc->disable(); platform->stop(); } break; case Searching: if (entered) { DPRINTF("Nav: Searching\n\r"); esc->configure(SPEED, SPEED); platform->execute(&command); actualHeading = desiredHeading = imu->getHeading(); difference = 0; delete pid; pid = new PID(&actualHeading, &difference, &desiredHeading, 40, 0, 20, MANUAL); pid->SetMode(AUTOMATIC); } if (eyes->didChangedState()) { switch (eyes->getState()) { case Eyes::Starting: { break; } case Eyes::Scanning: { break; } case Eyes::Found: { break; } case Eyes::Lost: { break; } case Eyes::Alert: { esc->disable(); platform->stop(); eyes->lookNext(); pause(Looking, LOOK_DURATION); break; } } } if (millis() - lastCorrectedHeading > HEADING_CORRECTION_INTERVAL) { actualHeading = imu->getHeading(); pid->Compute(); DPRINTF("Nav: %f %f %f\n\r", desiredHeading, actualHeading, difference); esc->configure(SPEED - difference, SPEED + difference); lastCorrectedHeading = millis(); } break; case Waiting: if (entered) DPRINTF("Nav: Waiting\n\r"); if (waitingFor > 0) { if (millis() - enteredAt > waitingFor) { nextState = nextStateAfterPause; } } else if (!platform->isExecuting()) { nextState = nextStateAfterPause; } break; case Looking: if (entered) DPRINTF("Nav: Looking\n\r"); if (eyes->getState() == Eyes::Alert) { eyes->lookNext(); pause(Looking, LOOK_DURATION); } else { if (entered) { esc->disable(); switch (eyes->getLookDirection()) { case FORWARD_INDEX: break; case LEFT_INDEX: platform->execute(&Left, TURN_DURATION); break; case RIGHT_INDEX: platform->execute(&Right, TURN_DURATION); break; } eyes->lookForward(); pauseWhileMoving(Searching); } } break; } } void Navigator::pause(state_t after, uint16_t time) { waitingFor = time; nextState = Waiting; nextStateAfterPause = after; } void Navigator::pauseWhileMoving(state_t after) { pause(after, 0); }
3d8de8bac3d80ed53b64b2e4e0c4638779a7277c
b48cc66bf4f5a173338e42ba02245da043e71ce7
/LuoguCodes/P1020.cpp
6a427b1b5a9a562ef824a63a4172b204e211203c
[ "MIT" ]
permissive
Anguei/OI-Codes
6f79f5c446e87b13c6bffe3cc758c722e8d0d65c
0ef271e9af0619d4c236e314cd6d8708d356536a
refs/heads/master
2020-04-22T22:18:14.531234
2019-02-14T14:24:36
2019-02-14T14:24:36
170,703,285
1
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
P1020.cpp
// luogu-judger-enable-o2 #include <vector> #include <iostream> #include <algorithm> #define dbg(x) std::cout << #x << " = " << (x) << std::endl int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int tmp, ans; std::vector<int> a{ 0 }; while (std::cin >> tmp) a.emplace_back(tmp); int n = a.size() - 1; std::vector<int> dp(n + 1); dp[1] = a[1]; ans = 1; for (int i = 2; i <= n; ++i) if (a[i] <= dp[ans]) dp[++ans] = a[i]; else dp[std::upper_bound(dp.begin() + 1, dp.begin() + ans + 1, a[i], std::greater<int>()) - dp.begin()] = a[i]; std::cout << ans << std::endl; dp[1] = a[1]; ans = 1; for (int i = 2; i <= n; ++i) if (a[i] > dp[ans]) dp[++ans] = a[i]; else dp[std::lower_bound(dp.begin() + 1, dp.begin() + ans + 1, a[i]) - dp.begin()] = a[i]; std::cout << ans << std::endl; }
f09f214f9fc1c462477e596f0c1a75e4798d9333
2d194e0f39dd2ca7e7fecaf8ab68c89e0617ff7a
/Ladder11/35.cpp
f6f0319b768530be0dbad523890cb48a29e09097
[ "MIT" ]
permissive
vimarsh6739/CP
016f7ce9d2655560f155639422b01f47442f5f76
dfdd6a3c43547d34dcff48dba6dc85662030d10a
refs/heads/master
2022-06-15T06:32:48.140485
2020-05-09T07:24:55
2020-05-09T07:24:55
250,560,882
1
0
null
null
null
null
UTF-8
C++
false
false
425
cpp
35.cpp
#include <bits/stdc++.h> using namespace std; int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int ab,bc,ac; cin>>ab>>bc>>ac; int a,b,c; for(a = 1; a <= ab; ++a) { if(ab%a == 0 && ac%a==0) { b = ab/a; c = ac/a; if(b*c == bc){ // cout<<a<<"\n"<<b<<"\n"<<c<<"\n"; cout<<4*(a+b+c)<<"\n"; break; } } } return 0; }
75ee3a152c3828158191b3c1322665070f2cbf12
3f4cebcffe9d5beb7d288600ceed2b8448f6afea
/packages/CefSharp.Common.63.0.3/src/CefSharp.Core/RequestContextHandler.h
fa11202fe7d4abb5945b75cd31b611f6d4d88fa4
[ "MIT" ]
permissive
kevinlau2015/CEFSharp.wpf.H.264
7276cbd2bb21533bbed44ed0c536ccd67ac34ca6
dc05d6960f644b331be56dedeb081c02395b55fe
refs/heads/master
2022-09-15T00:44:28.479862
2020-06-04T01:11:44
2020-06-04T01:11:44
269,229,294
0
0
MIT
2020-06-04T01:10:04
2020-06-04T01:10:04
null
WINDOWS-1252
C++
false
false
3,072
h
RequestContextHandler.h
// Copyright ยฉ 2010-2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "CookieManager.h" #include "Internals\ReportUnhandledExceptions.h" #include "Internals\TypeConversion.h" namespace CefSharp { private class RequestContextHandler : public CefRequestContextHandler { gcroot<IRequestContextHandler^> _requestContextHandler; public: RequestContextHandler(IRequestContextHandler^ requestContextHandler) : _requestContextHandler(requestContextHandler) { } ~RequestContextHandler() { _requestContextHandler = nullptr; } virtual CefRefPtr<CefCookieManager> GetCookieManager() OVERRIDE { if (Object::ReferenceEquals(_requestContextHandler, nullptr)) { return NULL; } auto cookieManager = _requestContextHandler->GetCookieManager(); if (cookieManager == nullptr) { return NULL; } //Cookie manager can only be our managed wrapper if (cookieManager->GetType() == CookieManager::typeid) { return (CookieManager^)cookieManager; } //Report the exception on the thread pool so it can be caught in AppDomain::UnhandledException auto msg = gcnew String(L"ICookieManager must be of type " + CookieManager::typeid + ". CEF does not support custom implementation"); ReportUnhandledExceptions::Report(msg, gcnew NotSupportedException(msg)); return NULL; } virtual bool OnBeforePluginLoad(const CefString& mime_type, const CefString& plugin_url, bool is_main_frame, const CefString& top_origin_url, CefRefPtr<CefWebPluginInfo> plugin_info, CefRequestContextHandler::PluginPolicy* plugin_policy) OVERRIDE { if (!Object::ReferenceEquals(_requestContextHandler, nullptr)) { auto pluginInfo = TypeConversion::FromNative(plugin_info); auto pluginPolicy = (CefSharp::PluginPolicy)*plugin_policy; auto result = _requestContextHandler->OnBeforePluginLoad(StringUtils::ToClr(mime_type), StringUtils::ToClr(plugin_url), is_main_frame, StringUtils::ToClr(top_origin_url), pluginInfo, pluginPolicy); *plugin_policy = (CefRequestContextHandler::PluginPolicy)pluginPolicy; return result; } return false; } IMPLEMENT_REFCOUNTING(RequestContextHandler); }; }
db6511c5d70c6a1b751e6f57806d6ae80a187542
2480ceee9f28f5e8a69fb6f5ed42fd63c22b4205
/test/Math/QuaternionTest.cpp
4dd72b11b0e5b8c42c29296a12e1cb362715c6a0
[ "MIT" ]
permissive
rokrepo/pomdog
165db7884598c74bd530a4b7a1e83bc1e315c945
b21fd4fef295aaa3e06ca15e5952109cd8e93f00
refs/heads/master
2022-10-25T04:09:09.721827
2020-06-18T05:33:25
2020-06-18T05:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
747
cpp
QuaternionTest.cpp
// Copyright (c) 2013-2020 mogemimi. Distributed under the MIT license. #include "Pomdog/Math/Quaternion.hpp" #include "catch.hpp" using Pomdog::Quaternion; TEST_CASE("Quaternion", "[Quaternion]") { SECTION("Quaternion") { Quaternion quaternion{0, 0, 0, 1}; REQUIRE(quaternion.X == 0.0f); REQUIRE(quaternion.Y == 0.0f); REQUIRE(quaternion.Z == 0.0f); REQUIRE(quaternion.W == 1.0f); quaternion = {4, 3, 2, 1}; REQUIRE(quaternion.X == 4.0f); REQUIRE(quaternion.Y == 3.0f); REQUIRE(quaternion.Z == 2.0f); REQUIRE(quaternion.W == 1.0f); } SECTION("Constants") { REQUIRE(Quaternion(0.0f, 0.0f, 0.0f, 1.0f) == Quaternion::Identity); } }
fbcb79284866a13046b3c3184b995adbd61e5f1b
b8041c3e36af9797968a441c68c6244763945171
/Prob4.cpp
d9ed28417b8a863d7dcc2ae4394c3df0be561cb5
[]
no_license
brcsomnath/ICPC
21fa304e6830265cd1d504f1c6974cd850f5c8d5
745f00e82fe66954f5a8d67151dc63abecfd9e62
refs/heads/master
2020-04-17T20:22:39.720522
2016-10-02T05:40:18
2016-10-02T05:40:18
66,577,555
0
0
null
null
null
null
UTF-8
C++
false
false
2,216
cpp
Prob4.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned int ul; typedef unsigned long long ull; typedef vector <int> vi; typedef map<string,string> mss; typedef map<int, vector<int> > mvii; typedef map<int, int> mii; typedef queue <int> qi; typedef map <int, vector<string> > mvis; typedef map <string, vector<int> > mvsi; typedef vector <string> vs; typedef pair <int, int> pii; typedef pair<double,double> dd; #define gc getchar() #define pc putchar #define MP make_pair #define SORT(a) sort (a.begin(), a.end()) #define REVERSE(a) reverse (a.begin(), a.end()) #define PI acos(-1) #define ms(x,y) memset (x, y, sizeof (x)) #define INF 2000000000 #define pb push_back #define all(c) (c).begin(),(c).end() #define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++) #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) #define MAX 5000000 #define debug cout<<"A"<<endl #define prnt(a) cout<<a<<endl #define MOD 1000000009 #define epsilon 1e-6 #define FOR(i,a,b) for (ll i=(a); i<(b); i++) #define FORr(i,a,b) for (ll i=(a); i>=b; i--) #define itrALL(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++) #define D(x) cout << #x " is " << x << endl int d[1<<15], suiche[40]; int main() { int n, m; scanf("%d %d", &n, &m); for (int i=0, k, x; i<m; ++i){ suiche[i] = 0; scanf("%d", &k); while (k--){ scanf("%d", &x); suiche[i] |= (1 << x); } } for (int i=0; i<(1<<n); ++i) d[i] = INT_MAX; queue<int> q; d[0] = 0; q.push(0); while (q.size()) { int u = q.front(); q.pop(); for (int k=0; k<m; ++k) { int v = u ^ suiche[k]; //Toggles lights if (d[u] + 1 < d[v]) { d[v] = d[u] + 1; q.push(v); } } } int queries; scanf("%d", &queries); while (queries--) { int destiny = 0; char buf[16]; scanf("%s", buf); for (int i=n-1; i>=0; --i) { int bit = buf[i] - '0'; destiny |= (bit << (n - i - 1)); } printf("%d\n", d[destiny] < INT_MAX ? d[destiny] : -1); } return 0; }
d7189bed33db96613f5b673849b6a32a0bd9d1ad
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5695413893988352_0/C++/priyanshu95/2S.cpp
099a2e2f6106a9890efa1311b04863239e1bdda6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,270
cpp
2S.cpp
#include <bits/stdc++.h> #define sf scanf #define pf printf #define pb push_back #define mp make_pair using namespace std; string C, J; int arr[2][4]; int ans1 = 999999, ans2 = 999999; string A1, A2; int min_abs = 9999999; string curr_a, curr_b; void generate(int pos, int val1,int val2) { if(pos == C.size()) { //cout << val1 << '\t' << val2 << endl; if(abs(val1-val2) < min_abs) { min_abs = abs(val1-val2); ans1 = val1; ans2 = val2; A1 = curr_a; A2 = curr_b; return; } else if(abs(val1-val2) == min_abs) { if(val1 < ans1) { ans1 = val1; ans2 = val2; A1 = curr_a; A2 = curr_b; } else if(val1 == ans1 && val2 < ans2) { ans2 = val2; A1 = curr_a; A2 = curr_b; } return; } return; } if(arr[0][pos] == -1) { for(int i = 0; i < 10; i++) { int v1 = val1*10 + i; if(arr[1][pos] == -1) { for(int j = 0; j < 10; j++) { int v2 = val2*10 + j; curr_a += ('0'+i); curr_b += ('0'+j); generate(pos+1, v1, v2); curr_a.erase(curr_a.end()-1); curr_b.erase(curr_b.end()-1); } } else { curr_a += ('0'+i); curr_b += ('0'+arr[1][pos]); generate(pos+1, v1, val2*10 + arr[1][pos]); curr_a.erase(curr_a.end()-1); curr_b.erase(curr_b.end()-1); } } } else { int v1 = val1*10 + arr[0][pos]; if(arr[1][pos] == -1) { for(int j = 0; j < 10; j++) { int v2 = val2*10 + j; curr_a += '0'+arr[0][pos]; curr_b += ('0'+j); generate(pos+1, v1, v2); curr_a.erase(curr_a.end()-1); curr_b.erase(curr_b.end()-1); } } else { curr_a += ('0'+arr[0][pos]); curr_b += ('0'+arr[1][pos]); generate(pos+1, v1, val2*10 + arr[1][pos]); curr_a.erase(curr_a.end()-1); curr_b.erase(curr_b.end()-1); } } } int main() { int T; cin >> T; for(int t = 1; t <= T; t++) { cin >> C >> J; ans1 = 999999; ans2 = 9999999; min_abs = 9999999; for(int i = 0; i < C.size(); i++) { if(C[i] == '?') arr[0][i] = -1; else arr[0][i] = C[i] - '0'; if(J[i] == '?') arr[1][i] = -1; else arr[1][i] = J[i] - '0'; } generate(0, 0, 0); cout << "Case #"<<t << ": " << A1 << " " << A2 << endl; //cout << "Absoulute diff is : " << min_abs << endl; } return 0; }
394471d97a6cf6bda5b1310da8edab5a1313d07c
c4a7b9e365e0f060d1e26dc693e61bb620e68082
/DirChangeWatcher.h
178af9917f821cc99317c2a4a9fc043a0eb464c9
[ "Zlib" ]
permissive
Svengali/cblib
85542837f25a9054356b3a067abfd26b7517e180
77ddfd452cff842575750b9e6d792790f5ec5fee
refs/heads/master
2022-05-09T23:08:35.031894
2020-10-15T01:43:37
2020-10-15T01:43:37
122,876,049
3
0
null
null
null
null
UTF-8
C++
false
false
1,254
h
DirChangeWatcher.h
#pragma once #include "Base.h" #include "Sptr.h" #include "vector.h" #include "String.h" START_CB /* #define FILE_ACTION_ADDED 0x00000001 #define FILE_ACTION_REMOVED 0x00000002 #define FILE_ACTION_MODIFIED 0x00000003 #define FILE_ACTION_RENAMED_OLD_NAME 0x00000004 #define FILE_ACTION_RENAMED_NEW_NAME 0x00000005 */ struct DirChangeRecord { // Command is added from the thread char path[_MAX_PATH]; uint32 action; time_t time; }; extern const uint32 c_dirChangeDefaultNotifyFlags; extern const char * c_dirChangeActionStrings[]; //----------------------------------------------------- SPtrFwd(DirChangeWatcher); class DirChangeWatcher : public RefCounted { public: virtual ~DirChangeWatcher() { } //returns if any virtual bool GetDirChanges(cb::vector<DirChangeRecord> * pInto ) = 0; // same as above but just discards the records virtual bool GetDirChangesDiscard() = 0; // stop watching dirs virtual void Stop() = 0; protected: DirChangeWatcher() { } }; DirChangeWatcherPtr StartWatchingDirs(const char ** dirs,const int numDirs,uint32 notifyFlags); DirChangeWatcherPtr StartWatchingDirs(const vector<String> & dirs,uint32 notifyFlags); END_CB
b102f33ed19dd0b1bbe78abe023ec941082dd860
18d371db3d537a9c1bb4b1e40d93e03757b19646
/DAL/unitofwork.cpp
2bd9b05a9c062b8ac1c9aeeaf16a27219a41db77
[]
no_license
Lv385/Project
7c9b4499be9d84c4fed55e2d724f1af1e110d5b4
70f558b08dbabd0e4b8339d77d7ab4937763ba18
refs/heads/master
2021-06-11T04:08:43.399470
2019-07-16T10:12:35
2019-07-16T10:12:35
171,315,808
1
3
null
2019-04-18T12:56:18
2019-02-18T16:15:43
C++
UTF-8
C++
false
false
472
cpp
unitofwork.cpp
#include "unitofwork.h" namespace dal { std::atomic<unsigned int> UnitOfWork::connection_number_ = 0; UnitOfWork::UnitOfWork() : connection_(nullptr) {} void UnitOfWork::GenerateUniqueConnection() { connection_ = std::make_shared<Connect>(GenerateNewConnection()); } UnitOfWork::~UnitOfWork() { connection_->Close(); } QString UnitOfWork::GenerateNewConnection() { return QString("Connection number:" + QString::number(connection_number_++)); } } // namespace dal
fbbe7e84350ccb811387a6e3ea573bd8320d2231
19219c7e74facdc253ecbb718f1674172998da8d
/student_management_system/StudentManagementSystem/CString.h
8d32ac24c2f53645c911d0cf0ae9fb1f39450f73
[]
no_license
2254649642/my_project
00d4e2981512412bc32653796c84041d049a7253
d4471e49a05b5fafd00ec40d59a17b5d4da25294
refs/heads/master
2023-06-06T14:35:46.053020
2021-06-25T14:45:12
2021-06-25T14:45:12
null
0
0
null
null
null
null
GB18030
C++
false
false
5,681
h
CString.h
#pragma once #include <iostream> using namespace std; /*======================================================= * o(*๏ฟฃโ–ฝ๏ฟฃ*)o * Name๏ผšCString * FileName๏ผšCString.h * Programmer๏ผšileemi * Start Date๏ผš2020/05/12 * Last UpDate๏ผš2020/06/11 *=======================================================*/ class CString { public: CString(); // ้ป˜่ฎคๆž„้€ ๅ‡ฝๆ•ฐ ~CString(); // ๆžๆž„ๅ‡ฝๆ•ฐ CString(const char* szStr); // ๅธฆๅ‚ๆž„้€ ๅ‡ฝๆ•ฐ CString(const CString& obj); // ๆ‹ท่ดๆž„้€  CString(int nVal); // ๅธฆๅ‚ๆ•ฐ็š„้ป˜่ฎคๆž„้€  CString(float fltVal); CString(double dblVal); int GetStringLength(); // ่Žทๅ–ๅฏนๅบ”ๅญ—็ฌฆไธฒ็š„้•ฟๅบฆ const char* GetString(); // ่Žทๅ–ๅฏนๅบ”็š„ๅญ—็ฌฆไธฒ public: CString& operator=(const CString& strObj); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ = ่ฟ็ฎ—็ฌฆๅณ่พนไธบ็ฑปๅฏน่ฑก CString& operator=(const char* szStr); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ = ่ฟ็ฎ—็ฌฆๅณ่พนไธบๅญ—็ฌฆไธฒ CString& operator+=(const CString& strObj); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ += ่ฟ็ฎ—็ฌฆๅณ่พนไธบ็ฑปๅฏน่ฑก CString& operator+=(const char* szStr); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ += ่ฟ็ฎ—็ฌฆๅณ่พนไธบๅญ—็ฌฆไธฒ bool operator==(const CString& strObj); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ == ่ฟ็ฎ—็ฌฆๅณ่พนไธบ็ฑปๅฏน่ฑก bool operator==(const char* szStr); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ == ่ฟ็ฎ—็ฌฆๅณ่พนไธบๅญ—็ฌฆไธฒ bool operator>(const CString& strObj); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ > ่ฟ็ฎ—็ฌฆๅณ่พนไธบ็ฑปๅฏน่ฑก bool operator>(const char* szStr); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ > ่ฟ็ฎ—็ฌฆๅณ่พนไธบๅญ—็ฌฆไธฒ bool operator<(const CString& strObj); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ < ่ฟ็ฎ—็ฌฆๅณ่พนไธบ็ฑปๅฏน่ฑก bool operator<(const char* szStr); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ < ่ฟ็ฎ—็ฌฆๅณ่พนไธบๅญ—็ฌฆไธฒ public: friend ostream& operator<<(ostream& os, const CString& str); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ << friend istream& operator>>(istream& is, CString& str); // ้‡่ฝฝ่ฟ็ฎ—็ฌฆ >> public: CString& Append(const char* szStr); // ๅญ—็ฌฆไธฒๆ‹ผๆŽฅ ->็›ธๅฝ“ไบŽstrcat CString& Append(const CString& str); // ไฝฟ็”จๆ‹ท่ดๅ‡ฝๆ•ฐไผ ้€’CStringๅฏน่ฑก CString& Append(int nVal); // ๅฐ†int็ฑปๅž‹็š„ๆ•ฐๆฎ่ฝฌๆขๆˆๅญ—็ฌฆไธฒ CString& Append(double dblVal); // ๅฐ†double็ฑปๅž‹็š„ๆ•ฐๆฎ่ฝฌๆขๆˆๅญ—็ฌฆไธฒ CString& Append(char chVal); // ๅฐ†ๅญ—็ฌฆ 'chVal' ไปฅ ๅญ—็ฌฆ "chVal" ็š„ๅฝขๅผ่พ“ๅ‡บ CString& Append(float fVal); // ๅฐ†float็ฑปๅž‹็š„ๆ•ฐๆฎ่ฝฌๆขๆˆๅญ—็ฌฆไธฒ CString& Append(long lVal); // ๆŠŠ้•ฟๆ•ดๅฝขๆ•ฐ่ฝฌๆขไธบไปปๆ„่ฟ›ๅˆถ็š„ๅญ—็ฌฆไธฒ public: int Find(int nIdxBegin, const char* szStr); // ๆญฃๅ‘ๆŸฅๆ‰พ๏ผŒไปŽๆŒ‡ๅฎšไฝ็ฝฎๅผ€ๅง‹ๆŸฅๆ‰พๅญ—็ฌฆไธฒ int Find(int nIdxBegin, const CString& str); int Find(const char* szStr); // ๆŸฅๆ‰พๅญ—็ฌฆไธฒ int Find(const CString& str); int ReverseFind(const char* szStr); // ้€†ๅ‘ๆŸฅๆ‰พๅญ—็ฌฆไธฒ int ReverseFind(const CString& str); // ๆ›ฟๆข้€‚ๅˆ CString& // ไปŽๆŒ‡ๅฎšไฝ็ฝฎๅผ€ๅง‹ๆŸฅๆ‰พ๏ผŒๅฐ†ๅญ—็ฌฆไธฒๆ›ฟๆข ๅฐ† szStr ๆ›ฟๆขๆˆ szDst CString& Replace(int nIdxBegin, const char* szSrc, const char* szDst); CString& Replace(int nIdxBegin, const CString& strSrc, CString& strDst); // ๅชๆ›ฟๆข็ฌฌไธ€ไธชๅ‡บ็Žฐ็š„ CString& Replace(const char* szSrc, const char* szDst); CString& Replace(const CString& strSrc, CString& strDst); // ๆŒ‡ๅฎšๆŒ‡ๅฎšไฝ็ฝฎๆ›ฟๆข CString& Replace(int nIdxBegin, const char* szDst); CString& Replace(int nIdxBegin, const CString& strDst); // ๅญ—็ฌฆไธฒๆ‹ท่ด -> strcpy void Copy(const char* szStr); void Copy(const CString& str); // ๆๅ–ๅญไธฒ // ไปŽ็ดขๅผ• nIdx ๅผ€ๅง‹ๆๅ–nLengthไธชๅญ—่Š‚ไธบๆ–ฐ็š„ๅญ—็ฌฆไธฒ CString Mid(int nIdx, int nLength); // ไธญ้—ดๆๅ– CString Left(int nLength); // ไปŽๅญ—็ฌฆไธฒๅทฆไพงๅผ€ๅง‹ๆๅ–nLengthไธชๅญ—่Š‚ไธบๆ–ฐ็š„ๅญ—็ฌฆไธฒ CString Right(int nLength); // ไปŽๅญ—็ฌฆไธฒๅณไพงๅผ€ๅง‹ๆๅ–nLengthไธชๅญ—่Š‚ไธบๆ–ฐ็š„ๅญ—็ฌฆไธฒ void Strip(); // ๅŽป้™ค็ฉบ็™ฝๅญ—็ฌฆ(strip)๏ผšๅฏไปฅไปŽๅญ—็ฌฆไธฒ็š„ๅคด้ƒจๅฐพ้ƒจๆŸฅ็œ‹ๆ˜ฏๅฆๆœ‰็ฉบๆ ผใ€tabใ€ๅ›ž่ฝฆ void Format(const char* szFmt, ...); // ๅฐ†็ผ“ๅ†ฒๅŒบไธญ็š„ๆ•ฐๆฎๆ ผๅผๅŒ–(ๆตฎ็‚น๏ผŒๆ•ดๆ•ฐ็ญ‰ๆ ผๅผๅŒ–ไธบๅญ—็ฌฆไธฒ) private: //ๅฐ่ฃ…ๅ‡ฝๆ•ฐ๏ผŒ็”จไบŽ่งฃๅ†ณ้‡ๅคไปฃ็  void SetString(const char* szStr); // ๅˆๅง‹ๅŒ–็ผ“ๅ†ฒๅŒบ(ๅญ—็ฌฆไธฒ)๏ผŒ่ฎพ็ฝฎไธ€ไธชๆ–ฐ็š„ๅญ—็ฌฆไธฒ void Clear(); // ้‡Šๆ”พๅ†…ๅญ˜๏ผŒ่งฃๅ†ณๆทฑๆ‹ท่ด้—ฎ้ข˜ void Reserve(); // ๅฐ†ๅญ—็ฌฆไธฒ้€†ๅบ // ๆ นๆฎ็ผ“ๅ†ฒๅŒบๅ†…็š„็ฉบ็™ฝๅญ—็ฌฆไธชๆ•ฐ๏ผŒไธ่ฎก็ฉบ็™ฝๅญ—็ฌฆ๏ผŒๅฐ†ๅญ—็ฌฆ่ฟ›่กŒ็งปไฝ bool Move(void* pvBuf, int iBufSize, int iStart, int iMoveLen); /* Date๏ผš2020/05/14 ๅฎŒๅ–„CString็ฑป๏ผŒๅŠ ๅ…ฅๅธธๆˆๅ‘˜ๅ‡ฝๆ•ฐ๏ผŒๅขžๅŠ ไปฅไธ‹้™ๆ€ๆ–นๆณ• */ public: static CString ValueOf(bool bVal); // true ==> "true" static CString ValueOf(char chVal); // a ==> "a" static CString ValueOf(double dblVal); // 3.5 ==> "3.5" static CString ValueOf(float fltVal); // 4.5f ==> "4.5" static CString ValueOf(int nVal); // 123 ==> "123" static CString ValueOf(long lVal); // 123 ==> "123" static CString ValueOf(short sVal); // 123 ==> "123" static CString ValueOf(const char* data); // char[] = "123" ==> string "123" // ่ฟ”ๅ›žๆŒ‡ๅฎšๆ•ฐ็ป„ไธญ๏ผŒไปŽๆŒ‡ๅฎšๅ็งปๅค„ๅผ€ๅง‹ๅˆๅง‹ๆŒ‡ๅฎšๅคงๅฐๅญ—่Š‚็š„ๅญ—็ฌฆไธฒ static CString CopyValueOf(const char* pData, int nOffset, int nCount); // char[] = "123" ==> string "123" static CString FromFormat(const char* pszFmt, ...); // ("%d", 123) ==> string "123" char& operator[](int nindex); //้‡่ฝฝๆ•ฐ็ป„ไธ‹ๆ ‡ๆ“ไฝœ็ฌฆ[], ไฝฟไน‹ๅ…ทๆœ‰ๅˆคๆ–ญไธŽๅค„็†ไธ‹ๆ ‡่ถŠ็•Œ็š„ๅŠŸ่ƒฝ // ๆ•ฐๆฎๆˆๅ‘˜ private: char* m_pStrBuff; // ๆŒ‡ๅ‘ๅญ—็ฌฆไธฒ็š„็ผ“ๅ†ฒๅŒบ int* m_pnRefCount; // ๆฏๆฌกไฟฎๆ”น็ผ“ๅญ˜ไธญ็š„ๆ•ฐๆฎๆ—ถ๏ผŒไธบๅ…ถๅœจๅ †ไธญ็”ณ่ฏทไธ€ไธชๅผ•็”จ่ฎกๆ•ฐ(่ฎฐๅฝ•ๅฝ“ๅ‰ไฝฟ็”จ่ฏฅ็ผ“ๅญ˜็š„ๅฏน่ฑกๆ•ฐ้‡) int m_nBuffLength; // ็ผ“ๅ†ฒๅŒบ็š„ๅคงๅฐ int m_nStrLength; // ็ผ“ๅ†ฒๅŒบไธญๅญ—็ฌฆไธฒ็š„ๅคงๅฐ };
25ce0aac503bcfa40ec0b23a13f9ef2334ca861b
05b0c763ab92086e69a8d00ae6465009c596f6bc
/csrc/cpu/jit/cpu/kernels/LinearSwishCustomized.cpp
05ee33b436d503257a2260315e3b72f26776495f
[ "Apache-2.0" ]
permissive
intel/intel-extension-for-pytorch
60ce2af2ec3a1dacae0d0db13dd51a5b44512e61
7f9266789de7ca9d8bcf55606f3204f1a3640640
refs/heads/master
2023-09-01T09:13:16.866410
2023-08-31T08:00:37
2023-08-31T08:00:37
256,061,008
991
144
Apache-2.0
2023-08-13T13:56:07
2020-04-15T23:35:29
Python
UTF-8
C++
false
false
676
cpp
LinearSwishCustomized.cpp
#include "LinearSwishCustomized.h" #include "aten/AddSwish.h" #include <ATen/Context.h> #include <ATen/InferSize.h> #include <c10/util/Exception.h> #include <c10/util/Logging.h> #include <torch/csrc/autograd/function.h> #include <limits> #include <ideep.hpp> namespace torch_ipex { namespace cpu { at::Tensor dil_linear_swish_customized( at::Tensor& x, const at::Tensor& weight, const at::Tensor& bias) { RECORD_FUNCTION( "dil_linear_swish_customized", c10::ArrayRef<c10::IValue>({})); // at::linear w/o bias auto linear_res = at::linear(x, weight); return AddSwish(x, linear_res, weight, bias); } } // namespace cpu } // namespace torch_ipex
55cedde8e0512c09ec72959cdf4af9f345ea9b39
06bed8ad5fd60e5bba6297e9870a264bfa91a71d
/libPr3/Roster/rostermediapane.cpp
91d68d5e6da0574f574cbdaa7980726b2da91b30
[]
no_license
allenck/DecoderPro_app
43aeb9561fe3fe9753684f7d6d76146097d78e88
226c7f245aeb6951528d970f773776d50ae2c1dc
refs/heads/master
2023-05-12T07:36:18.153909
2023-05-10T21:17:40
2023-05-10T21:17:40
61,044,197
4
3
null
null
null
null
UTF-8
C++
false
false
7,129
cpp
rostermediapane.cpp
#include "rostermediapane.h" #include "ui_rostermedia.h" #include "rosterentry.h" #include <QMenu> #include "fileutil.h" #include <QFileInfo> #include <QMessageBox> #include <QFileDialog> #include <QDragEnterEvent> RosterMediaPane::RosterMediaPane(RosterEntry* re, QWidget *parent) : QWidget(parent), ui(new Ui::RosterMediaPane) { ui->setupUi(this); this->re = re; log = new Logger("RosterMedia"); ui->lblMainImage->setContextMenuPolicy(Qt::CustomContextMenu); ui->lblMainImage->setAcceptDrops(true); ui->lblIconImage->setAcceptDrops(true); // tab 2 QImage img(re->getImagePath()); if(!img.isNull()) { ui->lblMainImage->setPixmap(QPixmap::fromImage(img).scaledToHeight(200)); ui->btnRemoveImage->setVisible(true); connect(ui->btnRemoveImage, SIGNAL(clicked()), this, SLOT(on_removeAction_triggered())); } else ui->btnRemoveImage->setVisible(false); connect(ui->lblMainImage, SIGNAL(fileNameChanged(QString)), this, SLOT(dropImage(QString))); if(re->getIconPath() != "") { QImage icon(re->getIconPath()); if(!icon.isNull()) { ui->lblIconImage->setPixmap(QPixmap::fromImage(icon).scaledToHeight(100)); ui->btnRemoveIcon->setVisible(true); connect(ui->btnRemoveIcon, SIGNAL(clicked()), this, SLOT(on_removeIcon_triggered())); } else ui->btnRemoveIcon->setVisible(false); } else { QImage img(re->getImagePath()); ui->lblIconImage->setPixmap(QPixmap::fromImage(img).scaledToHeight(45)); } //connect(ui->lblIconImage, SIGNAL(fileNameChanged(QString)), this, SLOT(dropIcon(QString))); connect(ui->lblMainImage, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(on_customContexMenuRequest(QPoint))); ui->edWebReference->setText(re->getURL()); connect(ui->edWebReference, SIGNAL(textEdited(QString)),this, SLOT(on_edWebReference_textEdited(QString))); } RosterMediaPane::~RosterMediaPane() { delete ui; } void RosterMediaPane::on_customContexMenuRequest(QPoint) { QMenu* menu = new QMenu(); if(re->getImagePath() != "") { QAction* removeAction = new QAction(tr("Remove"), this); menu->addAction(removeAction); connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_triggered())); } QAction* newImageAction = new QAction(tr("Add image"), this); connect(newImageAction, SIGNAL(triggered()), this, SLOT(on_removeIcon_triggered())); menu->addAction(newImageAction); menu->exec(QCursor::pos()); } void RosterMediaPane::on_removeAction_triggered() { re->setImagePath(""); ui->lblMainImage->setPixmap(QPixmap()); ui->btnRemoveImage->setVisible(false); } void RosterMediaPane::on_removeIcon_triggered() { re->setIconPath(""); ui->lblIconImage->setPixmap(QPixmap()); ui->btnRemoveIcon->setVisible(false); } void RosterMediaPane::on_addImageAction_triggered() { setCursor(Qt::WaitCursor); fileName = QFileDialog::getOpenFileName(this,tr("Add or replace image"), FileUtil::getUserResourcePath(),tr("Image Files (*.png *.jpg *.bmp")); setCursor(Qt::ArrowCursor); dropImage(fileName); re->setImagePath(fileName); QImage img(re->getImagePath()); ui->lblMainImage->setPixmap(QPixmap::fromImage(img).scaledToWidth(ui->lblMainImage->width())); } void RosterMediaPane::on_addIconAction_triggered() { setCursor(Qt::WaitCursor); fileName = QFileDialog::getOpenFileName(this,tr("Add or replace image"), FileUtil::getUserResourcePath(),tr("Image Files (*.png *.jpg *.bmp")); setCursor(Qt::ArrowCursor); dropIcon(fileName); re->setIconPath(fileName); QImage img(re->getIconPath()); ui->lblIconImage->setPixmap(QPixmap::fromImage(img).scaledToWidth(ui->lblIconImage->width())); } void RosterMediaPane::dropImage(QString fileName) { ui->btnRemoveImage->setVisible(true); connect(ui->btnRemoveImage, SIGNAL(clicked()), this, SLOT(on_removeAction_triggered())); QFileInfo info(fileName); //if(info.absolutePath()+QDir::separator() != FileUtil::getUserResourcePath()) if(info.absolutePath()+QDir::separator() != LocoFile::getFileLocation()) { // log->debug(tr("Must move image from '%1' to '%2'").arg(info.absolutePath()).arg(FileUtil::getUserResourcePath())); log->debug(tr("Must move image from '%1' to '%2'").arg(info.absolutePath()).arg(LocoFile::getFileLocation())); //if(QFile::exists(FileUtil::getUserResourcePath()+ info.fileName())) if(QFile::exists(LocoFile::getFileLocation() + info.fileName())) { switch(QMessageBox::question(this, tr("File already exists"), tr("The file already exists. Do you want to replace it?"), QMessageBox::Yes | QMessageBox::No)) { case QMessageBox::Yes: break; default: case QMessageBox::No: return; } } //QFile::copy(fileName, FileUtil::getUserResourcePath()+ info.fileName()); QFile::copy(fileName, LocoFile::getFileLocation()+ info.fileName()); //fileName= FileUtil::getUserResourcePath()+ info.fileName(); this->fileName= LocoFile::getFileLocation()+ info.fileName(); re->setImagePath(this->fileName); } } void RosterMediaPane::dropIcon(QString fileName) { ui->btnRemoveIcon->setVisible(true); connect(ui->btnRemoveIcon, SIGNAL(clicked()), this, SLOT(on_removeIcon_triggered())); QFileInfo info(fileName); //if(info.absolutePath()+QDir::separator() != FileUtil::getUserResourcePath()) if(info.absolutePath()+QDir::separator() != LocoFile::getFileLocation()) { // log->debug(tr("Must move image from '%1' to '%2'").arg(info.absolutePath()).arg(FileUtil::getUserResourcePath())); log->debug(tr("Must move image from '%1' to '%2'").arg(info.absolutePath()).arg(LocoFile::getFileLocation())); { switch(QMessageBox::question(this, tr("File already exists"), tr("The file already exists. Do you want to replace it?"), QMessageBox::Yes | QMessageBox::No)) { case QMessageBox::Yes: break; default: case QMessageBox::No: return; } } // QFile::copy(fileName, FileUtil::getUserResourcePath()+ info.fileName()); QFile::copy(fileName, LocoFile::getFileLocation()+ info.fileName()); // fileName= FileUtil::getUserResourcePath()+ info.fileName(); this->fileName= LocoFile::getFileLocation() + info.fileName(); re->setIconPath(this->fileName); } } void RosterMediaPane::on_edWebReference_textEdited(QString text) { re->setURL(text); } void RosterMediaPane::dragEnterEvent(QDragEnterEvent *evt) { QRect iconImageRect = ui->lblIconImage->geometry(); QRect mainImageRect = ui->lblMainImage->geometry(); QPoint mousePos = ui->lblIconImage->mapFromGlobal(evt->pos()); if(iconImageRect.contains(mousePos) || mainImageRect.contains(mousePos)) { if(!evt->mimeData()->text().isEmpty()) evt->accept(); } } void RosterMediaPane::dragMoveEvent(QDragMoveEvent */*evt*/) { } void RosterMediaPane::dropEvent(QDropEvent * evt) { QRect iconImageRect = ui->lblIconImage->geometry(); QRect mainImageRect = ui->lblMainImage->geometry(); QPoint mousePos = ui->lblIconImage->mapFromGlobal(evt->pos()); QString text = evt->mimeData()->text(); if(text.startsWith("file://")) { text.remove("\r\n"); //ImageIcon* icon = new ImageIcon(text.mid(7),text.mid(7)); if(mainImageRect.contains(mousePos)) dropImage(text); if(iconImageRect.contains(mousePos)) dropIcon(text); } }
cf22d72890bd091bd956bc044fe34f60fb619f24
709e79dc1b9ed2eb0e255482681e0f8d263158f3
/benchmark/askit_release/rkdtsrc/generator/uniform.cpp
61f45e27c3ac72402e91974602dd7bc98f83e264
[ "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
kexinrong/rehashing
ebd935cc30cdbb40dca54f7ef76a08b0c87d8048
401b1f99970d2cc8cb8444f4c7ee5b94f4ebeb7f
refs/heads/master
2021-07-03T10:45:32.498877
2020-10-21T05:42:28
2020-10-21T05:42:28
186,186,245
22
3
MIT
2020-10-09T04:15:15
2019-05-11T22:15:47
C++
UTF-8
C++
false
false
1,064
cpp
uniform.cpp
#include <direct_knn.h> #include <omp.h> #include <mpi.h> #include <cmath> #include <cstdlib> #ifndef __APPLE__ void generateUniform(int n, int d, double *x, MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); struct drand48_data *seeds; #pragma omp parallel { int t = omp_get_thread_num(); int p = omp_get_num_threads(); //Seed each thread's prng #pragma omp master { seeds = new struct drand48_data[p]; srand48((long)time(NULL) + rank*size); for(int i = 0; i < p; i++) srand48_r(lrand48(), &(seeds[i])); } #pragma omp barrier #pragma omp for for (int j=0; j<n*d ; j++){ drand48_r(&(seeds[t]), &(x[j])); } } delete[] seeds; } #else void generateUniform(int n, int d, double *x, MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); srand48( (unsigned)time(NULL) + rank ); for(int i = 0; i < n*d; i++) x[i] = drand48(); } #endif
40313c9ea020c42163223ed666f6ea2f626dbf44
81cf157e25185df17b78ac09f5686c51198d8db7
/Algorithm/ๆ้ซ˜/ๅ›พ่ฎบ/่ดŸ็Žฏ/่ง‚ๅ…‰ๅฅถ็‰›.cpp
6f7c4e305cd000730e67b21085f1920dd5793d8b
[]
no_license
renyajie/Learning
97e3263e6dbe4ccff37ad3fabd9a6490259ab2b7
5174b0e7120ef30c8834fe3d06fcd482240ac2f6
refs/heads/master
2023-03-22T01:28:40.647641
2021-03-23T02:41:20
2021-03-23T02:41:20
349,076,372
0
0
null
null
null
null
UTF-8
C++
false
false
1,631
cpp
่ง‚ๅ…‰ๅฅถ็‰›.cpp
#include<iostream> #include<cstring> #include<algorithm> using namespace std; const int N = 1010, M = 5010; int h[N], e[M], ne[M], w[M], idx; int f[N]; double dist[N]; int cnt[N], q[N]; bool st[N]; int n, m; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; } bool check(double x) { memset(st, 0, sizeof st); memset(cnt, 0, sizeof cnt); memset(dist, 0, sizeof dist); int hh = 0, tt = 0; for(int i = 1; i <= n; i++) { q[tt++] = i; st[i] = true; } while(hh != tt) { int t = q[hh++]; if(hh == N) hh = 0; st[t] = false; for(int i = h[t]; ~i; i = ne[i]) { int j = e[i]; if(dist[j] < dist[t] + f[t] - x * w[i]) { dist[j] = dist[t] + f[t] - x * w[i]; cnt[j] = cnt[t] + 1; if(cnt[j] >= n) return true; if(!st[j]) { q[tt++] = j; if(tt == N) tt = 0; st[j] = true; } } } } return false; } int main() { scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) scanf("%d", &f[i]); memset(h, -1, sizeof h); for(int i = 0; i < m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); } double l = 0, r = 1000; while(r - l > 1e-4) { double mid = (l + r) / 2; if(check(mid)) l = mid; else r = mid; } printf("%.2lf\n", l); return 0; }
36c5a96f8822c276bde5c3c965ab5fa3afdcd2d7
0a224bc3e6937a2bffa152406a42633fd942dc4d
/Programas/temp/Particle2D.h
285df6d3f0a916802d27b4457f4c5dd14d6f3778
[]
no_license
fgmaion/IC
1c7870a00590160aebfdda998b44edacf4442b27
6f9eafc63f6420dff327edef608f1bacc565078d
refs/heads/master
2020-12-03T06:30:24.494839
2017-08-09T14:36:20
2017-08-09T14:36:20
95,685,941
0
0
null
null
null
null
UTF-8
C++
false
false
175
h
Particle2D.h
#include <iostream.h> class Particle { public: double mass; double x_t[2]; double velo_t[2]; double a_t[2]; Particle(); ~Particle(); }; Particle::Particle() { }
584f146a2faff1c97195ad275b0daffd531ae72f
aed4af3c5bbfbb90069db34322e255ed25dbfe53
/tinyvm/src/GarbageCollector.cpp
cca6b47c755fe150d1763f16a84c015993af3c24
[]
no_license
murador/tinyvm
083cfbb86f115a3622ce9c07e764eb46f64ab3d0
90d8e85b911c4a073254cb81268f86b4bda02992
refs/heads/master
2020-04-06T03:39:13.675548
2015-09-26T16:33:45
2015-09-26T16:33:45
25,740,874
1
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
GarbageCollector.cpp
/* * GarbageCollector.cpp * * Created on: 26/dic/2014 * Author: glutters */ #include "GarbageCollector.h" namespace vm { namespace runtime { GarbageCollector::GarbageCollector() { // TODO A } GarbageCollector::~GarbageCollector() { // TODO Auto-generated destructor stub } } /* namespace runtime */ } /* namespace vm */
01a6c706d1faca450a073f24b307735af2e5a336
ba90cba096ba4e1a1de31af346e0b769c17ccc9e
/include/Instructions/NOPInstruction.hpp
bf61ad88d072e07772a80d6f9026dcea5ebaddd5
[ "MIT" ]
permissive
KaravolisL/ARM-ISA-Simulator
f5ed222eff2d82c6fdad8ec822fec856570419c9
cc5b927ff40054d912e208a469545089125e6911
refs/heads/master
2023-01-02T03:35:05.483981
2020-10-21T00:35:37
2020-10-21T00:35:37
253,665,149
0
0
MIT
2020-09-11T21:59:09
2020-04-07T02:19:19
C++
UTF-8
C++
false
false
1,070
hpp
NOPInstruction.hpp
///////////////////////////////// /// @file NOPInstruction.hpp /// /// @brief Declaration of NOPInstruction class /// /// @author Luke Karavolis ///////////////////////////////// #ifndef NOP_INSTRUCTION_HPP #define NOP_INSTRUCTION_HPP // SYSTEM INCLUDES // (None) // C PROJECT INCLUDES // (None) // C++ PROJECT INCLUDES #include "InstructionBase.hpp" // For InstructionBase // FORWARD DECLARATIONS // (None) //////////////////////////////// /// @class NOPInstruction /// /// @brief Class to represent NOP instruction //////////////////////////////// class NOPInstruction : public InstructionBase { public: ///////////////////////////////////// /// @brief Constructs a new NOPInstruction object ///////////////////////////////////// NOPInstruction() : InstructionBase(OpCode::NOP) {} //////////////////////////////// /// @brief ... does absolutely nothing /// /// @copydoc InstructionBase::Execute() //////////////////////////////// void Execute(Registers& rProcessRegisters) {} protected: private: }; #endif
21738f95f1473839eb26748e3694f92fe4f84c93
8f17b34aa5c1ee123302096c279581834ccdf213
/1004.cpp
0ab9bd701aa18c5c3ccacd9fb101ec5941f0082d
[]
no_license
Honlan/poj-org-c-plus-plus
58b005c302e24a7ec765227f0b88956bfafb5bbf
2441a1c92ec6c0753f582ce5e2b79fb4d1d3d3d9
refs/heads/master
2021-01-10T17:52:26.149808
2015-11-05T02:47:54
2015-11-05T02:47:54
45,180,548
0
0
null
null
null
null
UTF-8
C++
false
false
314
cpp
1004.cpp
#include <iostream> using namespace std; int main(){ double fare, average = 0, total = 0; //่พ“ๅ‡บ12ไธชๆœˆไปฝ็š„ๅผ€้”€ๅนถๆฑ‚ๅ’Œ for(int i = 0; i < 12; i++){ cin >> fare; total += fare; } //ๆฑ‚ๅนณๅ‡ average = total / 12; cout << "$" << average << endl; return 0; }
aa909ad016a9cdf6b1932fd6a97c39e565b2f051
e9ed46363f3a6f7c6b40ebdc03cac6b476b2b89d
/FigureEx01/FigureEx01/main.cpp
e26e8b019ac9e55ee229d8a6210a993a7f4759d8
[]
no_license
moo1o/CppStudy
2593c9a5fdf498653082d9c9de89b30e595b942a
1abdb57be50173befc3a361e69379cafade2a476
refs/heads/master
2021-07-22T03:41:56.906378
2017-10-30T22:48:38
2017-10-30T22:48:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
main.cpp
#include <iostream> #include "Figure.h" using namespace std; #define FIGURES 10 int main(void) { /*Ellipse ellipse(30, 20, 50, 20); Triangle triangle(10, 10, 20, 30); Rectangle rectangle(20, 30, 10, 20); ellipse.Draw(); triangle.Draw(); rectangle.Draw(); */ Figure *figures[FIGURES] = { new Triangle(10, 10, 20, 30), new Rectangle(20, 30, 10, 20), new Ellipse(30, 20, 50, 20), new Rectangle(20, 30, 10, 20), new Rectangle(20, 30, 10, 20), new Ellipse(10, 20, 40, 30), new Triangle(20, 30, 10, 10), new Ellipse(10, 30, 70, 40), new Ellipse(30, 40, 90, 20), new Triangle(50, 0, 30, 20) }; for(int i=0 ; i<FIGURES ; i++) { figures[i]->Draw(); } for(int i=0 ; i<FIGURES ; i++) { delete figures[i]; } return 0; }
3aafac477cab7cef2c79093345ea63a596210c3f
7f2e7edff293b0277137516a4f0b88021a63f1e3
/UnitTest_PZ/TestDeRham/TPZMatDeRhamHDivL2.cpp
693756cf72cf0c920161254a32e84b5e5da90240
[]
no_license
labmec/neopz
3c8da1844164765606a9d4890597947c1fadbb41
4c6b6d277ce097b97bfc8dea1b6725860f4fe05a
refs/heads/main
2023-08-30T22:35:13.662951
2022-03-18T19:57:30
2022-03-18T19:57:30
33,341,900
48
17
null
2023-09-13T19:46:34
2015-04-03T02:18:47
C++
UTF-8
C++
false
false
2,130
cpp
TPZMatDeRhamHDivL2.cpp
#include "TPZMatDeRhamHDivL2.h" #include "TPZCompElHCurl.h" #include "pzaxestools.h" TPZMatDeRhamHDivL2* TPZMatDeRhamHDivL2::NewMaterial() const{ return new TPZMatDeRhamHDivL2(*this); } void TPZMatDeRhamHDivL2::Contribute( const TPZVec<TPZMaterialDataT<STATE>> &datavec, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef) { if(datavec[0].fShapeType != TPZShapeData::EVecShape) DebugStop(); if(datavec[1].fShapeType != TPZShapeData::EScalarShape) DebugStop(); const TPZFMatrix<REAL> &phiHDiv = datavec[fHDivMeshIndex].divphi; const auto &phiL2 = datavec[fL2MeshIndex].fPhi; const int64_t nHDiv = phiHDiv.Rows(); const int64_t nL2 = phiL2.Rows(); for(int64_t iHDiv = 0; iHDiv < nHDiv; iHDiv++){ for(int jHDiv = 0; jHDiv < nHDiv; jHDiv++){ STATE phiIphiJ = phiHDiv(iHDiv,0) * phiHDiv(jHDiv,0); ek(iHDiv,jHDiv) += phiIphiJ * weight; } for(int jL2 = 0; jL2 < nL2; jL2++){ STATE phiIphiJ = phiL2(jL2,0) * phiHDiv(iHDiv,0); ek(iHDiv,nHDiv+jL2) += phiIphiJ * weight; ek(nHDiv+jL2,iHDiv) += phiIphiJ * weight; } } for (int64_t iL2 = 0; iL2 < nL2; iL2++) { for (int64_t jL2 = 0; jL2 < nL2; jL2++) { STATE PhiIPhiJ = phiL2(iL2,0) * phiL2(jL2,0); ek(nHDiv + iL2, nHDiv + jL2) += PhiIPhiJ * weight; } } } int TPZMatDeRhamHDivL2::VariableIndex(const std::string &name) const { if( strcmp(name.c_str(), "SolutionLeft") == 0) return 0; if( strcmp(name.c_str(), "SolutionRight") == 0) return 1; DebugStop(); return -1; } int TPZMatDeRhamHDivL2::NSolutionVariables(int var) const { switch (var) { case 0: // SolutionLeft return 3; case 1: // SolutionRight return 1; default: DebugStop(); break; } return 1; } void TPZMatDeRhamHDivL2::Solution(const TPZVec<TPZMaterialDataT<STATE>> &datavec, int var, TPZVec<STATE> &solout) { auto solHDiv = datavec[fHDivMeshIndex].sol[0]; auto solL2 = datavec[fL2MeshIndex].sol[0]; switch (var) { case 0: { solout = solHDiv; break; } case 1: { solout = solL2; break; } default: DebugStop(); } }
379606fcbd51d71f5345b40846ee6f215cad4673
120b640cf0c673cd20387cda7b94219eb0b6bc4d
/src/MeshData.h
40909bcb3030d2f8dab8d095121227863648716f
[]
no_license
giseburt/Miracle-Grue
a6ba431477c94e12e6f6cb269f6309895c33157a
e6aaa619d466b05d89f3026f0e694b74379bdfde
refs/heads/master
2021-01-09T06:16:39.836293
2011-11-07T18:27:42
2011-11-07T18:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
MeshData.h
/** MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com> Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. */ #ifndef MESH_DATA_H_ #define MESH_DATA_H_ #include <vector> #include "DataEnvelope.h" // // The Path data contains triangles // class MeshData: public DataEnvelope { public: MeshData (); virtual ~MeshData(); }; #endif // MESH_DATA_H_
cdf5f94bfae1d64f6c61a947eca102c66a2a164a
4c380b2c1076051947a8fee7d30359b1c65c5176
/iiitp codes sem2/assignment 1/a.cpp
5d464f70554db750fd7692f2ce37bbac3c5154f1
[]
no_license
blank-27/iiitpcodes_sem1
4a41a2878a6b2d60f4a3b410a54401579dd09d98
ab773d9f40ed7e27ecee9e1e5ec02647f9007fab
refs/heads/master
2020-11-29T13:09:09.808288
2020-10-01T07:01:22
2020-10-01T07:01:22
230,120,080
0
0
null
null
null
null
UTF-8
C++
false
false
84
cpp
a.cpp
#include<iostream> using namespace std; void main() { cout<<"hey world-chan"; }
3c77803186ccd08fa1aa570c45e9c09630d7788b
486b15bc1abf2cda3fcb733b6d31a6b9364020eb
/safety_diagnostics/diagnostics/src/camera_states_manager.cpp
cde9dca9b7458e9df695a11bd4c5ba16701444e2
[]
no_license
xnvst/robotics
376f6a6f6a95cca8ce7606f4e74b4abb94687334
8e12abe1e2d6d618118aadc8d8858df78cd74f08
refs/heads/master
2021-01-16T00:09:33.455018
2019-04-14T19:40:24
2019-04-14T19:40:24
99,957,587
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
cpp
camera_states_manager.cpp
/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * Copyright 2016, Avidbots Corp. * @name camera_states_manager.cpp * @brief Source File containing the CameraStatesManager class * @author Feng Cao */ #include "avidbots_diagnostics/camera_states_manager.h" /** * @name CameraStatesManager * @brief Default constructor */ CameraStatesManager::CameraStatesManager() { } /** * @name ~CameraStatesManager * @brief Destructor */ CameraStatesManager::~CameraStatesManager() {} /** * @name Init() * @brief Initialize CameraStatesManager * @param[in] hardware_id, to identify different device */ void CameraStatesManager::Init(uint8_t hardware_id) { ROS_INFO_STREAM("CameraStatesManager Init"); id_ = hardware_id; num_states_ = avidbots_diagnostics_constants::CAMERA_MSG_ID_NUM; states_ = avidbots_msgs::diagnostics_states::kStateOk; } /** * @name UpdateDiagnostics() * @brief Update Diagnostics message * @param[in] states, data reference for avidbots_msgs::diagnostics_states * @param[in] diagnostics_msg, data reference for avidbots_msgs::diagnostics */ void CameraStatesManager::UpdateDiagnostics(const avidbots_msgs::diagnostics_states &states, avidbots_msgs::diagnostics &diagnostics_msg) { if (states.hardware_id == avidbots_msgs::diagnostics_states::k3DCameraLeft) { diagnostics_msg.hardware_id = avidbots_msgs::diagnostics_states::k3DCameraLeft; diagnostics_msg.name = "Left Camera:\n"; diagnostics_msg.status_camera_left = states.states; } else if (states.hardware_id == avidbots_msgs::diagnostics_states::k3DCameraRight) { diagnostics_msg.hardware_id = avidbots_msgs::diagnostics_states::k3DCameraRight; diagnostics_msg.name = "Right Camera:\n"; diagnostics_msg.status_camera_right = states.states; } else { return; } diagnostics_msg.stamp = states.stamp; }
c18fac55a4730b01045dc13fec2555810d771cd8
a41ff94559e24cba03f42081ee5452f64063622a
/Easy/Codechef/DIVIDING.CPP
a1b711cd4c536fe37fa30d28d42ec8b8a1db7ee8
[]
no_license
RavenColEvol/competitive-journey
aaff3ebd66bb6fdbbcff33de7516ac401023e1f0
0e5cd2ff7e7c92644a8bee2b016c2eead4cb8370
refs/heads/master
2022-11-23T02:06:10.966813
2020-07-30T13:32:57
2020-07-30T13:32:57
229,191,033
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
DIVIDING.CPP
#include<bits/stdc++.h> #define ll long long #define lli long long int #define ull unsigned long long #define test while(t--) #define MOD 1000000007 using namespace std; int main() { ll n; cin >> n; lli sum = 0; for(int i = 0;i<n;i++) { ll temp ; cin >> temp; sum += temp; } if((n*(n+1)/2) == sum) cout<<"YES"<<'\n'; else cout<<"NO"<<'\n'; return 0; }
6f892e6550b364325ef8d22aff40f3547367837b
a9ffa5e56f4104e34405ce9592d4c40924ba4a51
/ZipString/main.cpp
a76f773e676971566eccf718bf4dbb3b4d70ed69
[]
no_license
BPLSH/Algorism
6839543502d946cd4527857b435580c9ab48e4f1
5e78706ade0cee203498bd9c9a5e3386cf407b0e
refs/heads/master
2020-04-18T12:42:50.398021
2019-03-09T10:53:14
2019-03-09T10:53:14
167,541,873
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
622
cpp
main.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ASCII 127 char* Zip(const char* ptr) { //รรถยฟยชยบยฏยผรถ char * dptr = (char*)malloc(sizeof(char)*ASCII); int i = 0; char *str = (char*)malloc(sizeof(char)*ASCII); for (int i = 0; i < ASCII; i++) { printf("index : %d : %d\n", i,*(dptr + i)); } while (*ptr) { int i = *ptr; *ptr++; dptr[i]++; } printf("-----------------\n"); for (int i = 0; i < ASCII; i++) { printf("index : %d : %d\n", i, *(dptr + i)); } return str; } int main(void) { char* zipMessage = Zip("aaabbbccc"); //printf("%s", zipMessage); getchar(); return 0; }
a429045af52ad9e78d52033ce03c4304e3f362e4
6d1f1166fe96de017f8c54c37c30d56a7f550571
/oggsound/src/OgreOggStaticWavSound.cpp
b94adec20c8712f9ccf59ca677f74f077ac94421
[ "BSD-3-Clause", "MIT" ]
permissive
OGRECave/ogre-audiovideo
d61d09e1cc8b9fa45c7750a09037fe13ff3e03e4
25ea305dd87607d1b83dff401c0c148eff936995
refs/heads/master
2023-08-25T16:28:14.729737
2023-06-10T21:59:46
2023-06-10T21:59:46
135,934,377
10
9
BSD-3-Clause
2022-06-17T23:23:30
2018-06-03T19:34:41
C++
UTF-8
C++
false
false
16,444
cpp
OgreOggStaticWavSound.cpp
/** * @author Ian Stangoe * * LICENSE: * * This source file is part of OgreOggSound, an OpenAL wrapper library for * use with the Ogre Rendering Engine. * * Copyright (c) 2017 Ian Stangoe * * 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 "OgreOggStaticWavSound.h" #include <string> #include <iostream> #include "OgreOggSoundManager.h" namespace OgreOggSound { /*/////////////////////////////////////////////////////////////////*/ OgreOggStaticWavSound::OgreOggStaticWavSound( const Ogre::String& name #if OGRE_VERSION_MAJOR == 2 , Ogre::SceneManager* scnMgr, Ogre::IdType id, Ogre::ObjectMemoryManager *objMemMgr, Ogre::uint8 renderQueueId #endif ) : OgreOggISound( name #if OGRE_VERSION_MAJOR == 2 , scnMgr, id, objMemMgr, renderQueueId #endif ) ,mAudioName("") ,mPreviousOffset(0) { mStream=false; mFormatData.mFormat=0; mBufferData.clear(); mBuffers.reset(new BufferList(1, AL_NONE)); } /*/////////////////////////////////////////////////////////////////*/ OgreOggStaticWavSound::~OgreOggStaticWavSound() { // Notify listener if ( mSoundListener ) mSoundListener->soundDestroyed(this); _release(); mBufferData.clear(); if (mFormatData.mFormat) OGRE_FREE(mFormatData.mFormat, Ogre::MEMCATEGORY_GENERAL); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_openImpl(Ogre::DataStreamPtr& fileStream) { // WAVE descriptor vars char* sound_buffer=0; int bytesRead=0; ChunkHeader c; // Store stream pointer mAudioStream = fileStream; // Store file name mAudioName = mAudioStream->getName(); // Allocate format structure mFormatData.mFormat = OGRE_NEW_T(WaveHeader, Ogre::MEMCATEGORY_GENERAL); // Read in "RIFF" chunk descriptor (4 bytes) mAudioStream->read(mFormatData.mFormat, sizeof(WaveHeader)); Ogre::String format; switch(mFormatData.mFormat->mFormatTag) { case 0x0001: format = "PCM"; break; case 0x0003: format = "IEEE float (unsupported)"; break; case 0x0006: format = "8-bit ITU-T G.711 A-law (unsupported)"; break; case 0x0007: format = "8-bit ITU-T G.711 ยต-law (unsupported)"; break; default: format = "*unknown* (unsupported)"; break; } Ogre::LogManager::getSingleton().logMessage("Sound '" + mAudioName + "': Loading WAV with " + Ogre::StringConverter::toString(mFormatData.mFormat->mChannels) + " channels, " + Ogre::StringConverter::toString(mFormatData.mFormat->mSamplesPerSec) + " Hz, " + Ogre::StringConverter::toString(mFormatData.mFormat->mBitsPerSample) + " bps " + format + " format."); // Valid 'RIFF'? if ( strncmp(mFormatData.mFormat->mRIFF, "RIFF", 4) != 0 ) { OGRE_EXCEPT(Ogre::Exception::ERR_FILE_NOT_FOUND, mAudioName + " - Not a valid RIFF file!", "OgreOggStaticWavSound::_openImpl()"); } // Valid 'WAVE'? if ( strncmp(mFormatData.mFormat->mWAVE, "WAVE", 4) != 0 ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, mAudioName + " - Not a valid WAVE file!", "OgreOggStaticWavSound::_openImpl()"); } // Valid 'fmt '? if ( strncmp(mFormatData.mFormat->mFMT, "fmt", 3) != 0 ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, mAudioName + " - Invalid Format!", "OgreOggStaticWavSound::_openImpl()"); } // mFormatData.mFormat: Should be 16 unless compressed ( compressed NOT supported ) if ( !mFormatData.mFormat->mHeaderSize >= 16 ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, mAudioName + " - Compressed WAV NOT supported!", "OgreOggStaticWavSound::_openImpl()"); } // PCM == 1 if ( (mFormatData.mFormat->mFormatTag != 0x0001) && (mFormatData.mFormat->mFormatTag != 0xFFFE) ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, mAudioName + " - WAV file NOT in PCM format!", "OgreOggStaticWavSound::_openImpl()"); } // Bits per sample check.. if ( (mFormatData.mFormat->mBitsPerSample != 16) && (mFormatData.mFormat->mBitsPerSample != 8) ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, mAudioName + " - BitsPerSample NOT 8/16, unsupported format!", "OgreOggStaticWavSound::_openImpl()"); } // Calculate extra WAV header info unsigned int extraBytes = mFormatData.mFormat->mHeaderSize - (sizeof(WaveHeader) - 20); // If WAVEFORMATEXTENSIBLE read attributes if (mFormatData.mFormat->mFormatTag==0xFFFE) { extraBytes-=static_cast<unsigned int>(mAudioStream->read(&mFormatData.mSamples, 2)); extraBytes-=static_cast<unsigned int>(mAudioStream->read(&mFormatData.mChannelMask, 2)); extraBytes-=static_cast<unsigned int>(mAudioStream->read(&mFormatData.mSubFormat, 16)); } // Skip mAudioStream->skip(extraBytes); do { // Read in chunk header mAudioStream->read(&c, sizeof(ChunkHeader)); // 'data' chunk... //if ( c.chunkID[0]=='d' && c.chunkID[1]=='a' && c.chunkID[2]=='t' && c.chunkID[3]=='a' ) if ( strncmp(c.chunkID, "data", 4) == 0 ) { // Store byte offset of start of audio data mAudioOffset = static_cast<unsigned int>(mAudioStream->tell()); // Check data size int fileCheck = c.length % mFormatData.mFormat->mBlockAlign; // Store end pos mAudioEnd = mAudioOffset+(c.length-fileCheck); // Allocate array sound_buffer = OGRE_ALLOC_T(char, mAudioEnd-mAudioOffset, Ogre::MEMCATEGORY_GENERAL); // Read entire sound data bytesRead = static_cast<int>(mAudioStream->read(sound_buffer, mAudioEnd-mAudioOffset)); // Jump out break; } // Skip unsupported chunk... else { if( (mAudioStream->tell() / sizeof(ChunkHeader)) % 100000 == 0) Ogre::LogManager::getSingleton().logMessage("OgreOggStaticWavSound::_openImpl() - Looking for 'data' chunk in: " + fileStream->getName()); mAudioStream->skip(c.length); } } while ( mAudioStream->eof() || ( strncmp(c.chunkID, "data", 4) != 0 )); // Create OpenAL buffer alGetError(); alGenBuffers(1, &(*mBuffers)[0]); if ( alGetError() != AL_NO_ERROR ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "Unable to create OpenAL buffer.", "OgreOggStaticWavSound::_openImpl()"); return; } #if OGGSOUND_HAVE_EFX == 1 // Upload to XRAM buffers if available if ( OgreOggSoundManager::getSingleton().hasXRamSupport() ) OgreOggSoundManager::getSingleton().setXRamBuffer(1, &(*mBuffers)[0]); #endif // Check format support if (!_queryBufferInfo()) OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "Format NOT supported.", "OgreOggStaticWavSound::_openImpl()"); // Calculate length in seconds mPlayTime = static_cast<float>(((mAudioEnd-mAudioOffset) * 8.f) / static_cast<float>((mFormatData.mFormat->mSamplesPerSec * mFormatData.mFormat->mChannels * mFormatData.mFormat->mBitsPerSample))); alGetError(); alBufferData((*mBuffers)[0], mFormat, sound_buffer, static_cast<ALsizei>(bytesRead), mFormatData.mFormat->mSamplesPerSec); if ( alGetError() != AL_NO_ERROR ) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "Unable to load audio data into buffer!", "OgreOggStaticWavSound::_openImpl()"); return; } OGRE_FREE(sound_buffer, Ogre::MEMCATEGORY_GENERAL); // Register shared buffer OgreOggSoundManager::getSingleton()._registerSharedBuffer(mAudioName, (*mBuffers)[0], this); // Notify listener if ( mSoundListener ) mSoundListener->soundLoaded(this); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_openImpl(const Ogre::String& fName, sharedAudioBuffer* buffer) { if ( !buffer ) return; // Set buffer _setSharedProperties(buffer); // Filename mAudioName = fName; // Notify listener if ( mSoundListener ) mSoundListener->soundLoaded(this); } /*/////////////////////////////////////////////////////////////////*/ bool OgreOggStaticWavSound::isMono() { if ( !mInitialised ) return false; return ( (mFormat==AL_FORMAT_MONO16) || (mFormat==AL_FORMAT_MONO8) ); } /*/////////////////////////////////////////////////////////////////*/ bool OgreOggStaticWavSound::_queryBufferInfo() { if ( !mFormatData.mFormat ) return false; switch(mFormatData.mFormat->mChannels) { case 1: { if ( mFormatData.mFormat->mBitsPerSample == 8 ) { // 8-bit mono mFormat = AL_FORMAT_MONO8; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize = mFormatData.mFormat->mSamplesPerSec/4; } else { // 16-bit mono mFormat = AL_FORMAT_MONO16; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } } break; case 2: { if ( mFormatData.mFormat->mBitsPerSample == 8 ) { // 8-bit stereo mFormat = AL_FORMAT_STEREO8; // Set BufferSize to 250ms (Frequency * 2 (8bit stereo) divided by 4 (quarter of a second)) mBufferSize = mFormatData.mFormat->mSamplesPerSec >> 1; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % 2); } else { // 16-bit stereo mFormat = AL_FORMAT_STEREO16; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } } break; case 4: { // 16-bit Quad surround mFormat = alGetEnumValue("AL_FORMAT_QUAD16"); if (!mFormat) return false; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } break; case 6: { // 16-bit 5.1 surround mFormat = alGetEnumValue("AL_FORMAT_51CHN16"); if (!mFormat) return false; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } break; case 7: { // 16-bit 7.1 surround mFormat = alGetEnumValue("AL_FORMAT_61CHN16"); if (!mFormat) return false; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } break; case 8: { // 16-bit 8.1 surround mFormat = alGetEnumValue("AL_FORMAT_71CHN16"); if (!mFormat) return false; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } break; default: { // Error message Ogre::LogManager::getSingleton().logMessage("Unable to determine number of channels: defaulting to 16-bit stereo"); // 16-bit stereo mFormat = AL_FORMAT_STEREO16; // Queue 250ms of audio data mBufferSize = mFormatData.mFormat->mAvgBytesPerSec >> 2; // IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ... mBufferSize -= (mBufferSize % mFormatData.mFormat->mBlockAlign); } break; } return true; } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_release() { setSource(AL_NONE); OgreOggSoundManager::getSingleton()._releaseSharedBuffer(mAudioName, (*mBuffers)[0]); mPlayPosChanged = false; mPlayPos = 0.f; } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_prebuffer() { if (mSource==AL_NONE) return; // Queue buffer alSourcei(mSource, AL_BUFFER, (*mBuffers)[0]); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::setSource(ALuint src) { if (src != AL_NONE) { // Attach new source mSource=src; // Load audio data onto source _prebuffer(); // Init source properties _initSource(); } else { // Validity check if ( mSource != AL_NONE ) { // Need to stop sound BEFORE unqueuing alSourceStop(mSource); // Unqueue buffer alSourcei(mSource, AL_BUFFER, 0); } // Attach new source mSource=src; // Cancel initialisation mInitialised = false; } } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_pauseImpl() { assert(mState != SS_DESTROYED); if ( mSource==AL_NONE ) return; alSourcePause(mSource); mState = SS_PAUSED; // Notify listener if ( mSoundListener ) mSoundListener->soundPaused(this); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_playImpl() { assert(mState != SS_DESTROYED); if(isPlaying()) return; if (mSource == AL_NONE) if ( !OgreOggSoundManager::getSingleton()._requestSoundSource(this) ) return; // Pick up position change if ( mPlayPosChanged ) setPlayPosition(mPlayPos); alSourcePlay(mSource); mState = SS_PLAYING; // Notify listener if ( mSoundListener ) mSoundListener->soundPlayed(this); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_stopImpl() { assert(mState != SS_DESTROYED); if ( mSource==AL_NONE ) return; alSourceStop(mSource); alSourceRewind(mSource); mState = SS_STOPPED; mPreviousOffset = 0; if (mTemporary) { mState = SS_DESTROYED; OgreOggSoundManager::getSingleton()._destroyTemporarySound(this); } // Give up source immediately if specfied else if (mGiveUpSource) OgreOggSoundManager::getSingleton()._releaseSoundSource(this); // Notify listener if ( mSoundListener ) mSoundListener->soundStopped(this); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::loop(bool loop) { mLoop = loop; if(mSource != AL_NONE) { alSourcei(mSource, AL_LOOPING, loop); if ( alGetError() != AL_NO_ERROR ) OGRE_LOG_ERROR("OgreOggStaticWavSound::loop() - Unable to set looping status!"); } else Ogre::LogManager::getSingleton().logMessage("OgreOggStaticWavSound::loop() - No source attached to sound!"); } /*/////////////////////////////////////////////////////////////////*/ void OgreOggStaticWavSound::_updateAudioBuffers() { if (!isPlaying()) return; ALenum state; alGetSourcei(mSource, AL_SOURCE_STATE, &state); if (state == AL_STOPPED) { stop(); // Finished callback if ( mSoundListener ) mSoundListener->soundFinished(this); } else { ALint bytes=0; // Use byte offset to work out current position alGetSourcei(mSource, AL_BYTE_OFFSET, &bytes); // Has the audio looped? if ( mPreviousOffset>bytes ) { // Notify listener if ( mSoundListener ) mSoundListener->soundLooping(this); } // Store current offset position mPreviousOffset=bytes; } } }
42a767f8f374a0119f84e30b16f9bdaca15a9a70
86522141ea662460a348c4c3c2a59ca57ab67fc0
/introductory_problems/problem1.5.cpp
a7d68214e99c37534f8ff176dc33abf238f11757
[]
no_license
pranshulnarang/cses_problems
312359c65fdf461d4294836a12f7027644af2049
41c09843d4992fdce556b84dad88e26e4d3c6d58
refs/heads/master
2022-11-20T19:49:29.855074
2020-07-26T00:46:00
2020-07-26T00:46:00
282,507,604
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
problem1.5.cpp
#include <bits/stdc++.h> #include <vector> #include <algorithm> using namespace std; int main(){ long long n; vector<long long> even; vector<long long> odd; cin>>n; if(n==1) cout<<1<<"\n"; else if(n<=3) cout<<"NO SOLUTION\n"; else { for(int i=1;i<=n;i++) { if(i%2==0) even.push_back(i); else { odd.push_back(i); } } for(int j=0;j<even.size();j++) cout<<even[j]<<" "; for(int k=0;k<odd.size();k++) cout<<odd[k]<<" "; } }
3918140b4e280494849b72d18a6388c1d86aa14f
205b4b45814c7376733e44c8a309685665903f26
/mainwindow.cpp
ba50d47f3d56f4518194e51a6920a583f2bcb5bb
[]
no_license
LeopoldArkham/Etiquette
fa262497ce470735075a814bef87866c1aa75dd9
5434f1e327a52e628878647028691106bc246895
refs/heads/master
2021-08-26T09:13:19.678716
2017-11-22T20:12:04
2017-11-22T20:12:04
111,727,781
0
0
null
null
null
null
UTF-8
C++
false
false
8,102
cpp
mainwindow.cpp
#include <QLabel> #include <QGridLayout> #include <QFormLayout> #include <QPushButton> #include <QMessageBox> #include "outputwindow.h" #include "mainwindow.h" mainWindow::mainWindow() : QWidget() { setWindowTitle("C++ Class Generator"); resize(650, 500); // Create Info section className = new QLineEdit; classInherits = new QLineEdit; QFormLayout *classInfoFormLayout = new QFormLayout; classInfoFormLayout->addRow("Class name:", className); classInfoFormLayout->addRow("Inherits:", classInherits); QGroupBox *classInfoGroupBox = new QGroupBox; classInfoGroupBox->setTitle("Class information"); classInfoGroupBox->setLayout(classInfoFormLayout); // Create inclusions section multipleInclusions = new QCheckBox("Protect header against multipe inclusions"); multipleInclusions->setChecked(true); QLabel *headerGuardLabel = new QLabel("Header guard template:"); headerGuardStructure = new QLineEdit; headerGuardStructure->setText("%class_DEFINED"); defaultConstructor = new QCheckBox("Generate constructor"); defaultConstructor->setChecked(true); destructor = new QCheckBox("Generate destructor"); QObjectMacro = new QCheckBox("Insert QObject macro"); generateCounter = new QCheckBox("Generate counter"); QGridLayout *inclusionsLayout = new QGridLayout; inclusionsLayout->addWidget(multipleInclusions, 0, 0, 1, 2); inclusionsLayout->addWidget(headerGuardLabel, 1, 0); inclusionsLayout->addWidget(headerGuardStructure, 1, 1); inclusionsLayout->addWidget(defaultConstructor, 2, 0); inclusionsLayout->addWidget(generateCounter, 2, 1); inclusionsLayout->addWidget(destructor, 3, 0); inclusionsLayout->addWidget(QObjectMacro, 3, 1); QGroupBox *inclusionsGroupBox = new QGroupBox; inclusionsGroupBox->setTitle("Include and generate"); inclusionsGroupBox->setLayout(inclusionsLayout); //Comments QLabel *authorLabel = new QLabel("Author:"); QLabel *classDescriptionLabel = new QLabel("Class description:"); author = new QLineEdit; classDescription = new QTextEdit; QGridLayout *commentsLayout = new QGridLayout; commentsLayout->addWidget(authorLabel, 0, 0); commentsLayout->addWidget(author, 0, 1); commentsLayout->addWidget(classDescriptionLabel, 1, 0); commentsLayout->addWidget(classDescription, 2, 0, 1, 2); commentsGroupBox = new QGroupBox; commentsGroupBox->setCheckable(true); commentsGroupBox->setTitle("Comments"); commentsGroupBox->setLayout(commentsLayout); //Attributes variable = new QLineEdit; QPushButton *add = new QPushButton("Add"); add->setMaximumWidth(35); generateGetter = new QCheckBox("Generate getter method"); generateSetter = new QCheckBox("Generate setter method"); generateGetter->setChecked(true); prefix = new QCheckBox("Add \"_m\" prefix"); prefix->setChecked(true); variablesList = new QListWidget; QPushButton *removeVariable = new QPushButton("Remove"); QHBoxLayout *attributesHBox1 = new QHBoxLayout; attributesHBox1->addWidget(variable); attributesHBox1->addWidget(add); QGridLayout *attributesGrid = new QGridLayout; attributesGrid->addWidget(generateGetter, 0, 0); attributesGrid->addWidget(generateSetter, 0, 1); attributesGrid->addWidget(prefix, 1, 0); QGridLayout *attributesGrid2 = new QGridLayout; attributesGrid2->addWidget(variablesList, 0, 0, 1, 3); attributesGrid2->addWidget(removeVariable, 1, 1); QVBoxLayout *attributesLayout = new QVBoxLayout; attributesLayout->addLayout(attributesHBox1); attributesLayout->addLayout(attributesGrid); attributesLayout->addLayout(attributesGrid2); QGroupBox *attributesGroupBox = new QGroupBox; attributesGroupBox->setTitle("Add new:"); attributesGroupBox->setLayout(attributesLayout); //File Policy QLabel *headerPathLabel = new QLabel("Header file:"); QLabel *sourcePathLabel = new QLabel("Source file:"); generateHeaderFile = new QCheckBox(); generateSourceFile = new QCheckBox(" "); headerFilePath = new QLineEdit; sourceFilePath = new QLineEdit; QPushButton *selectHeaderFilePath = new QPushButton("..."); selectHeaderFilePath->setMaximumWidth(25); QPushButton *selectSourceFilePath = new QPushButton("..."); selectSourceFilePath->setMaximumWidth(25); noCaps = new QCheckBox("File names are all lower-case"); QGridLayout *filePolicyLayout = new QGridLayout; filePolicyLayout->setSpacing(1); filePolicyLayout->addWidget(headerPathLabel, 0, 0, 1, 3); filePolicyLayout->addWidget(generateHeaderFile, 1, 0); filePolicyLayout->addWidget(headerFilePath, 1, 1); filePolicyLayout->addWidget(selectHeaderFilePath, 1, 2); filePolicyLayout->addWidget(sourcePathLabel, 2, 0, 1, 3); filePolicyLayout->addWidget(generateSourceFile, 3, 0); filePolicyLayout->addWidget(sourceFilePath, 3, 1); filePolicyLayout->addWidget(selectSourceFilePath, 3, 2); filePolicyLayout->addWidget(noCaps, 4, 0, 1, 3); QGroupBox *filePolicyGroupBox = new QGroupBox(this); filePolicyGroupBox->setTitle("File Policy"); filePolicyGroupBox->setLayout(filePolicyLayout); // Create main layout QVBoxLayout *vbox1 = new QVBoxLayout; vbox1->addWidget(classInfoGroupBox); vbox1->addWidget(inclusionsGroupBox); vbox1->addWidget(commentsGroupBox); QPushButton *generateCodeButton = new QPushButton("Generate"); QVBoxLayout *vbox2 = new QVBoxLayout; vbox2->addWidget(attributesGroupBox); vbox2->addWidget(filePolicyGroupBox); vbox2->addWidget(generateCodeButton); //vbox2->addStretch(1); QHBoxLayout *hbox = new QHBoxLayout(this); hbox->addLayout(vbox1); hbox->addLayout(vbox2); //Connect connect(add, SIGNAL(clicked()), this, SLOT(addVariable())); connect(variable, SIGNAL(returnPressed()), this, SLOT(addVariable())); connect(removeVariable, SIGNAL(clicked()), this, SLOT(removeVariable())); connect(generateCodeButton, SIGNAL(clicked()), this, SLOT(generateCode())); } // Slots void mainWindow::addVariable() { if(!variable->text().isEmpty()) { Variable var(variable->text(), generateGetter->isChecked(), generateSetter->isChecked(), prefix->isChecked()); variableVector.push_back(var); var.addToList(variablesList); } } void mainWindow::removeVariable() { unsigned int current(variablesList->currentRow()); if(current != 4294967295U) { variableVector.erase(variableVector.begin() + current); variablesList->takeItem(current); } } void mainWindow::generateCode() { if(className->text().isEmpty()) { QMessageBox::warning(this, "Missing field", "'Class Name' cannot be empty."); return; } QString code; if(commentsGroupBox->isChecked()) { code += "/*\nClass " + className->text(); if(!classInherits->text().isEmpty()) code += ", inherits" + classInherits->text(); code += "\nAuthor: " + author->text() + "\n"; code += "Created: " + QDate::currentDate().toString() + "\n\n"; code += classDescription->toPlainText() + "\n*/\n\n"; } if(multipleInclusions->isChecked()) { QString def(headerGuardStructure->text().replace("%class", className->text().toUpper())); code += "#ifndef " + def + "\n#define " + def + "\n\n"; } code += "class " + className->text(); if(!classInherits->text().isEmpty()) { code += " : public " + classInherits->text(); } code += "\n{\n"; if(QObjectMacro->isChecked()) code += " Q_OBJECT\n"; QString publicBlock, privateBlock; publicBlock += "public:\n"; if(defaultConstructor->isChecked()) publicBlock += " " + className->text() + "();\n"; privateBlock += "private:\n"; for (Variable v : variableVector) v.addToCode(publicBlock, privateBlock); code += publicBlock + "\n"; code += privateBlock + "\n"; code += "}\n\n"; if(multipleInclusions->isChecked()) code += "#endif "; outputWindow *out = new outputWindow(code, this); out->exec(); }
9b95e78fdfac40b5cd11eead750b745b029c110c
95ccbdb193f6e9c5c3899d0abfbb7feddd7b52c5
/src/utils/utils_io.cpp
8ab589f329a00538db4caf19024c07afeb3ae7f1
[ "Apache-2.0" ]
permissive
cw1997/verilog-preprocessor
6bf31d8b7673f658a5a523d53dadf4dc809cedd6
be5b2d82e5de6c6468ee085a15185cbdc6c92105
refs/heads/main
2023-06-04T21:17:03.165637
2021-06-25T18:04:43
2021-06-25T18:04:43
377,129,166
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
utils_io.cpp
// // Created by 86759 on 2021/6/24. // #include "utils_io.h" #include "utils_string.h" #include <fstream> #include <iostream> #include <sstream> using namespace std; std::vector<std::string> get_file_lines(const std::string& path) { ifstream file_stream(path); // file_stream.open(path); if (!file_stream.is_open()) { cout << "Error opening file_stream: " << path << endl; exit (1); } std::ostringstream buffer; buffer << file_stream.rdbuf(); std::string source_content = buffer.str(); std::vector<std::string> v = split_by_break_line(source_content); return v; }
a6b39388496c9f67a7b889465fbd738057d9eb67
eecbafb28fbb52d32e630698f714895dec5af3f4
/build/include/seeta/QualityStructure.h
486c811bdc57a5360d443bf19b5e89ded9f0efc4
[]
no_license
qiujun-shenzhen/SeetaFace6-Lib
bf6e9532f615d8688fdd40116d0ef1005a49d278
eaeec7046150b50b70eeac8d43ec7f4d8ece80c3
refs/heads/master
2023-06-11T05:15:50.503726
2021-07-08T03:16:59
2021-07-08T03:16:59
383,815,866
4
0
null
null
null
null
UTF-8
C++
false
false
1,731
h
QualityStructure.h
// // Created by kier on 19-7-24. // #ifndef SEETA_QULITY_EVALUATOR_QULITY_STRUCTURE_H #define SEETA_QULITY_EVALUATOR_QULITY_STRUCTURE_H #include "Common/Struct.h" namespace seeta { namespace v3 { enum QualityLevel { LOW = 0, MEDIUM = 1, HIGH = 2, }; class QualityResult { public: using self = QualityResult; QualityResult() = default; QualityResult(QualityLevel level, float score = 0) : level(level), score(score) {} QualityLevel level = LOW; ///< quality level float score = 0; ///< greater means better, no range limit }; struct QualityResultEx { int attr; QualityLevel level; ///< quality level float score; ///< greater means better, no range limit }; struct QualityResultExArray { int size; QualityResultEx *data; }; class QualityRule { public: using self = QualityRule; virtual ~QualityRule() = default; /** * * @param image original image * @param face face location * @param points landmark on face * @param N how many landmark on face given, normally 5 * @return Quality result */ virtual QualityResult check( const SeetaImageData &image, const SeetaRect &face, const SeetaPointF *points, int32_t N) = 0; }; } using namespace v3; } #endif //SEETA_QULITY_EVALUATOR_QULITY_STRUCTURE_H
e8660cc3238c672b63c9a061d000fbf513522556
d7cac5199dd34d396548f96107e63277f0b71e52
/mainwindow.cpp
ccdddc11db80b39d0317be59d72b00d550835b50
[]
no_license
lupl/myzip
6f16fa50bdb71d633f7549a85889b26eae74afc9
7eee9676dafe52ca2deaa83a04f64f42037760f0
refs/heads/master
2021-08-14T14:27:14.301351
2017-11-16T00:53:45
2017-11-16T00:53:45
110,196,002
0
1
null
null
null
null
UTF-8
C++
false
false
439
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); debugBox = new QMessageBox(this); connect(ui->zipBtn, &QPushButton::clicked, this, &MainWindow::zipFile); } MainWindow::~MainWindow() { delete ui; } void MainWindow::zipFile() { debugBox->setText(ui->zipDirLineEdit->text()); debugBox->show(); }
f0f99cce83e4b21682a4ba0b7041e437e6077967
0115be14e248f6a11ddcfc016605500f168c5ef7
/services/distributeddataservice/libs/distributeddb/common/src/task_queue.cpp
4825fb831c71abc038661ec81263d06a5e49edf1
[ "Apache-2.0" ]
permissive
RobertIndie/distributeddatamgr_datamgr
78900eb56fbadc9eea7252310bd81c31632658e4
cc0a4040f70b3f84d41e18f8ec42197a1f960188
refs/heads/master
2023-09-01T00:44:45.620308
2021-10-20T13:07:35
2021-10-20T13:07:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
task_queue.cpp
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "task_queue.h" namespace DistributedDB { TaskQueue::TaskQueue(bool lockable) :lockable_(lockable) {} TaskQueue::~TaskQueue() {} void TaskQueue::PutTask(const Task &task) { if (!task) { return; } tasks_.push(task); } Task TaskQueue::GetTaskAutoLock() { if (lockable_) { std::thread::id thisId = std::this_thread::get_id(); if (thisId != lockThread_) { if (lockThread_ == std::thread::id()) { lockThread_ = thisId; } else { return nullptr; } } } if (tasks_.empty()) { ReleaseLock(); return nullptr; } // copy and return Task task = tasks_.front(); tasks_.pop(); return task; } void TaskQueue::ReleaseLock() { if (!lockable_) { return; } if (lockThread_ == std::this_thread::get_id()) { lockThread_ = std::thread::id(); } } bool TaskQueue::IsEmptyAndUnlocked() const { if (lockable_) { if (lockThread_ != std::thread::id()) { return false; } } if (!tasks_.empty()) { return false; } return true; } }
1c9572e8b3ce3873f389e5033491548d6ce98c17
de4cd6e8abc86d91f851098911597df74f93fb2f
/tp2017/tp09/ex1/tp1.cpp
ddefd5aeaad10d230d8725a477de5d712bfd59b5
[]
no_license
G4bleb/tpcpp
e82b7dcc56d37d498c5e4cc9fca6f2a8d3c19612
2580e935b59c03e32d675284ad18ca21d75ef01a
refs/heads/master
2021-09-15T09:51:16.845955
2018-05-30T08:15:19
2018-05-30T08:15:19
104,993,500
0
1
null
null
null
null
UTF-8
C++
false
false
503
cpp
tp1.cpp
#include <iostream> using namespace std; void affiche(int val){ cout << val << endl; } void affiche(int* tabval, int taille){ for (int i = 0; i < taille; i++) { affiche(tabval[i]); } } int *initTab(int &i){ int *tabval = NULL; for (i = 0; i != 4; i++) { tabval = new int[i+1]; //Le new afface les valeurs prรฉcรฉdentes :( cout << "allow" << endl; cin >> tabval[i]; } return tabval; } int main(){ int i; int *tabval = initTab(i); affiche(tabval, i); return 0; }
7f5acd5ada8d6cfb2dbc8289d60ea6a040dbfcd6
9f57194d6a78ffa4d90f30f7553469d240d90326
/Labs/L36/L36/main.cpp
eaf015c900505b38ad7ee309f413a4e99fc459c0
[]
no_license
farnorthgit/CS201
a6726073a76e0710006046583f5b3dc933d0fea8
371a0464cca360fc451feeee77bfe735a51f869a
refs/heads/main
2023-04-18T16:00:50.434774
2021-04-27T17:00:33
2021-04-27T17:00:33
329,751,228
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
cpp
main.cpp
// sandwich.cpp // Glenn G. Chappell // 16 Apr 2018 // // For CS 201 Spring 2018 // Sandwich Toppings - Passing Flags in an int #include <iostream> using std::cout; using std::endl; using std::cin; void testfunction(unsigned number) { if (number == 1) cout << " 1"; else if (number == 3) cout << " 3"; if (number == 5) cout << " 5"; if (number == 15) cout << " 15"; cout << endl; } void flag (unsigned a) { cout << endl << "New flag" << endl; if (a & 1) cout << "Your number is odd" << endl; if (a | 2) cout << "This could be a function" << endl; if ((a & 15) == 15) cout << "This is a rare output" << endl; } // Main Program // Call function "sandwich" to specify sandwiches with various // combinations of toppings. int main() { cout << "Test #1" << endl; testfunction(1 | 2); // 0011 = 3 cout << endl; cout << "Test #2" << endl; testfunction(1 | 1); // 0001 = 1 cout << endl; cout << "Test #3" << endl; testfunction(1 | 4); // 0101 = 5 cout << endl; cout << "Test #4" << endl; testfunction(1 | 2 | 4 | 8); // 1111 = 15 cout << endl; cout << "Test #4" << endl; testfunction(1 | 5); // 0101 = 5 cout << endl; flag(33); flag(8796); flag(127); // Wait for user cout << "PRESS ENTER to quit "; while (cin.get() != '\n') ; }
26917073db3432ee0cbaf426df6f81160886f84c
1411c27806cd8f11556478d52e749025ffe931e6
/Software/Embedded/remote control conversion/template/MDK/stm32103c8t6/app/Main.cpp
8533b8cb11050b26d92596a9fb9f6674666e68b8
[]
no_license
dianzhichong/Quadcopter
e70c136003ce875d0f476cd8d92af28c5d24e095
d8135478207629521b16c9681de9ac6026659d04
refs/heads/master
2020-12-26T05:32:11.605852
2016-08-09T07:12:41
2016-08-09T07:12:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,231
cpp
Main.cpp
#include "stm32f10x.h" #include "Configuration.h" #include "TaskManager.h" #include "USART.h" #include "Timer.h" #include "ADC.h" #include "flash.h" #include "RemoteControl.h" #include "LED.h" #include "InputCapture_TIM.h" #include "Communication.h" InputCapture_TIM hunter(TIM4, 400, true, true, true, true); //TIM4 as InputCapture for remoter controller USART com1(1,115200,true); USART com2(2,115200,true); Communication Hi(com1,com2); ADC pressure(1); //PA1่ฏปๅ–ADๅ€ผ //flash InfoStore(0x08000000+100*MEMORY_PAGE_SIZE,true); //flash //GPIO ledRedGPIO(GPIOB,0,GPIO_Mode_Out_PP,GPIO_Speed_50MHz);//LED GPIO GPIO ledBlueGPIO(GPIOB,5,GPIO_Mode_Out_PP,GPIO_Speed_50MHz);//LED GPIO //LED ledRed(ledRedGPIO);//LED red //LED ledBlue(ledBlueGPIO);//LED blue RemoteControl RC(&hunter,1,3,2,4); int main() { u8 State=REMOTECONTROL_LOCK; u8 OldState=REMOTECONTROL_LOCK; double Receive_data=0; //ๆŽฅๆ”ถๆ•ฐๆฎ 10ms double RcUpdata=0; //้ฅๆŽงๅ™จ็Šถๆ€ๆ›ดๆ–ฐๆ—ถ้—ด 20ms ledBlueGPIO.SetLevel(0); while(1) { if(tskmgr.TimeSlice(Receive_data,0.01) ) //0.01 { Hi.DataListening_SendPC();//็›‘ๅฌ้ฃžๆœบๅ‘้€ๆฅ็š„ๆ•ฐๆฎ่ฝฌๅ‘็ป™PC Hi.DataListening_SendCopter();//็›‘ๅฌPCๅ‘้€ๆฅ็š„ๆ•ฐๆฎ่ฝฌๅ‘็ป™้ฃžๆœบ } if(tskmgr.TimeSlice(RcUpdata,0.08) ) { State=RC.Updata(80,2000); Hi.SendData2Copter(RC.GetYawVal(),RC.GetThrottleVal(),RC.GetRollVal(),RC.GetPitchVal(),false); if(State == REMOTECONTROL_LOCK && OldState ==REMOTECONTROL_UNLOCK ) { OldState = REMOTECONTROL_LOCK; Hi.SendOrder(0XA0); ledBlueGPIO.SetLevel(1);//ไธŠ้”็Šถๆ€ไธบไบฎ } else if(State ==REMOTECONTROL_UNLOCK && OldState ==REMOTECONTROL_LOCK)//่งฃ้” { Hi.SendOrder(0XA1); OldState = REMOTECONTROL_UNLOCK; ledBlueGPIO.SetLevel(0);//่งฃ้”็Šถๆ€ไธบ็ญ //tskmgr.DelayS(1); } if(State == REMOTECONTROL_UNLOCK) //ๅฆ‚ๆžœ่งฃ้”ไบ†ๆ‰ๅ‘ไธŠไฝๆœบๅ‘้€ Hi.SendData2Copter(RC.GetYawVal(),RC.GetThrottleVal(),RC.GetRollVal(),RC.GetPitchVal(),true); } } } /* ้ฅๆŽงๅ™จไธขๅคฑๆƒ…ๅ†ต 1.ไธŠ็”ตไธขๅคฑ๏ผŒไธ€ๅผ€ๅง‹ๅฐฑๆฒกๆฃ€ๆŸฅๅˆฐ้ฅๆŽงๅ™จ ๏ผˆๅ…จไธบ0๏ผ‰ 2.ไฝฟ็”จไธญไธขๅคฑ ่ฟ™ไธชๆฏ”่พƒ้บป็ƒฆใ€‚ใ€‚ๆ–ญๅผ€ๅŽๆŽฅๆ”ถๅ™จไพ็„ถๅ‘้€ๆ–ญๅผ€ๆ—ถๅˆป็š„ๆ•ฐๆฎ */
3a5c854253a95d55142aca267f439d7fcb40e3c6
ff443629c167f318d071f62886581167c51690c4
/src/test/fuzz/script_interpreter.cpp
5d59771682f1c9a01bdd4047943d68a25a81e24a
[ "MIT" ]
permissive
bitcoin/bitcoin
a618b2555d9fe5a2b613e5fec0f4b1eca3b4d86f
6f03c45f6bb5a6edaa3051968b6a1ca4f84d2ccb
refs/heads/master
2023-09-05T00:16:48.295861
2023-09-02T17:43:00
2023-09-02T17:46:33
1,181,927
77,104
33,708
MIT
2023-09-14T20:47:31
2010-12-19T15:16:43
C++
UTF-8
C++
false
false
1,980
cpp
script_interpreter.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <primitives/transaction.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <optional> #include <string> #include <vector> bool CastToBool(const std::vector<unsigned char>& vch); FUZZ_TARGET(script_interpreter) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); { const CScript script_code = ConsumeScript(fuzzed_data_provider); const std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider); if (mtx) { const CTransaction tx_to{*mtx}; const unsigned int in = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); if (in < tx_to.vin.size()) { (void)SignatureHash(script_code, tx_to, in, fuzzed_data_provider.ConsumeIntegral<int>(), ConsumeMoney(fuzzed_data_provider), fuzzed_data_provider.PickValueInArray({SigVersion::BASE, SigVersion::WITNESS_V0}), nullptr); const std::optional<CMutableTransaction> mtx_precomputed = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider); if (mtx_precomputed) { const CTransaction tx_precomputed{*mtx_precomputed}; const PrecomputedTransactionData precomputed_transaction_data{tx_precomputed}; (void)SignatureHash(script_code, tx_to, in, fuzzed_data_provider.ConsumeIntegral<int>(), ConsumeMoney(fuzzed_data_provider), fuzzed_data_provider.PickValueInArray({SigVersion::BASE, SigVersion::WITNESS_V0}), &precomputed_transaction_data); } } } } { (void)CastToBool(ConsumeRandomLengthByteVector(fuzzed_data_provider)); } }
d9a6ab3a14880c8abb0a46db1c9e5df632bd2110
d624bdea4a62da70209ae1e86edfa38aa6dfe769
/onesp/sketch_esp/sketch_esp.ino
21f2469bd0eae2c6ce3f434a0f0423a0cf15dfbe
[]
no_license
Leystryku/ledstrip_esp8266_and_arduino
e0b63f3be756d6837f0253788751328576891e25
1436bea0ed14679b040a1816ee47d34cfc7d2a23
refs/heads/master
2020-04-08T05:18:36.206264
2018-11-25T17:20:50
2018-11-25T17:20:50
159,055,400
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
ino
sketch_esp.ino
#include <Adafruit_NeoPixel.h> #include <ESP8266WiFi.h> #include <WiFiClient.h> const char* ssid = "ssid"; const char* password = "password"; WiFiServer server(5151); #define PIN 2 #define meters 5 #define num_leds 30*meters Adafruit_NeoPixel strip = Adafruit_NeoPixel(num_leds, PIN, NEO_GRB + NEO_KHZ800); WiFiClient theclient; void setup() { pinMode(PIN, OUTPUT); Serial.begin(9600); digitalWrite(PIN, HIGH); delay(3000); digitalWrite(PIN, LOW); WiFi.begin(ssid,password); Serial.println("started"); int flick = 0; while(WiFi.status() != WL_CONNECTED) { flick =!flick; digitalWrite(PIN, flick); delay(500); Serial.println("."); } server.begin(); theclient.stop(); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); strip.begin(); strip.show(); // Initialize all pixels to 'off' for (int i=0;i<num_leds;i++) { strip.setPixelColor(i, 25, 0, 0); strip.show(); } } void loop() { if(!theclient.connected()||theclient.status()==CLOSED) { theclient.stop(); theclient = server.available(); if(!theclient.connected()) { return; } theclient.print("[STRIP] Connection successful\n"); //this part works } int receivedbytes = theclient.available(); if(4>receivedbytes) { return; } bool unchanged = true; if(receivedbytes % 4 != 0) { unchanged=false; receivedbytes = receivedbytes - (receivedbytes % 4); return; } if(!receivedbytes) { return; } for(receivedbytes;receivedbytes!=0;receivedbytes--) { unsigned char num = theclient.read(); unsigned char r = theclient.read(); unsigned char g = theclient.read(); unsigned char b = theclient.read(); if(num&&r==0xFF&&g==0xFF&&b==0xFF)//eof { strip.show(); } if(num>num_leds) { theclient.print("[STRIP] don't have that much leds!\n"); return; } //char bananas[40] = {0}; //sprintf(bananas, "ok: %x _ %x _ %x _ %x : %x\n", lednum, r, g, b, receivedbytes); //theclient.print(bananas); strip.setPixelColor(num, r, g, b); } if(unchanged) { theclient.flush(); } }
7eaa6a1d8bbc5f1e90be21b5338f1b648abcb40e
0131b66c1169079a944fbac2fcb90280eaa41036
/Ramses/include/RegInstrucao.h
107e9c2eb04d6c97e2cf8d1c97a9e3cfee410344
[]
no_license
gahbdias/SimuladorDeProcessadores
e8b67109ef52498969352fcb4c2c551be55f9a3a
25f60b96481603ab5fa26d04b50979b282ec1bdd
refs/heads/master
2020-05-25T06:37:46.649899
2019-06-02T19:54:43
2019-06-02T19:54:43
187,670,841
0
0
null
null
null
null
UTF-8
C++
false
false
2,221
h
RegInstrucao.h
/** * @file RegInstrucao.h * @authors Karine Piacentini Coelho, Gabriela Carvalho Dias. * @brief Simulador do Ramses * @version 1.00 * @date Jun-2019 * * @copyright Copyright (c) 2019 * */ #ifndef _RegInstrucao_H_ #define _RegInstrucao_H_ #include <iostream> enum operacoes { NOP = 10, STR, LDR, ADD, OR, AND, SUB, NOT, JMP, JN, JZ, JC, JSR, NEG, SHR, HLT // 25 }; enum registradores { A = 30, B, X, NONE // 33 }; enum modoEnderecamento { DIRETO = 40, INDIRETO, IMEDIATO, INDEXADO // 43 }; class RegInstrucao { // Registrador de intruรงรตes public: int opcode; // cรณdigo da operaรงรฃo int registrador; // qual registrador serรก utilizado int modo; // modo de enderaรงamento public: RegInstrucao( ) { opcode = NOP; } ~RegInstrucao( void ) = default; void loadRI( int instrucao ); void decodificar( int instrucao ); void imprimeRI( void ) { switch( opcode ) { case NOP: std::cout << "RI: NOP(10)" << std::endl; break; case STR: std::cout << "RI: STR(11)" << std::endl; break; case LDR: std::cout << "RI: LDR(12)" << std::endl; break; case ADD: std::cout << "RI: ADD(13)" << std::endl; break; case OR: std::cout << "RI: OR(14)" << std::endl; break; case AND: std::cout << "RI: AND(15)" << std::endl; break; case SUB: std::cout << "RI: SUB(16)" << std::endl; break; case NOT: std::cout << "RI: NOT(17)" << std::endl; break; case JMP: std::cout << "RI: JMP(18)" << std::endl; break; case JN: std::cout << "RI: JN(19)" << std::endl; break; case JZ: std::cout << "RI: JZ(20)" << std::endl; break; case JC: std::cout << "RI: JC(21)" << std::endl; break; case JSR: std::cout << "RI: JSR(22)" << std::endl; break; case NEG: std::cout << "RI: NEG(23)" << std::endl; break; case SHR: std::cout << "RI: SHR(24)" << std::endl; break; case HLT: std::cout << "RI: HLT(25)" << std::endl; break; } } }; #endif
27f8b648d3aaac5d53aa69a83517ccc56784e351
0798201c11dc3df7dba291946d45779ae596e206
/library/comm_smm/src/tsmm.cpp
8ca99bdadeb56f667d8b278d9d52747e46d8326a
[]
no_license
lzw978/IceCodeBase
0602eabb5cd138a35be96b5ac5285a89230a294d
c3336c945438583c606a1327ba743888f030e743
refs/heads/master
2021-01-21T17:06:40.516530
2018-03-21T12:47:10
2018-03-21T12:47:10
91,933,850
0
0
null
null
null
null
UTF-8
C++
false
false
13,203
cpp
tsmm.cpp
/******************************************** ** ๆจกๅ—ๅ็งฐ๏ผštsmm.h ** ๆจกๅ—ๅŠŸ่ƒฝ: ** ๆจกๅ—็ฎ€่ฟฐ: ไฟกๅท้‡+ๅ…ฑไบซๅ†…ๅญ˜+ๆถˆๆฏ้˜Ÿๅˆ— ** ็ผ– ๅ†™ ไบบ: ** ๆ—ฅ ๆœŸ: 2017.08.11 ** ไฟฎ ๆ”น ไบบ: ** ไฟฎๆ”นๆ—ฅๆœŸ: ** ไฟฎๆ”น็›ฎ็š„๏ผš ** ็‰นๅˆซ่ฏดๆ˜Ž: ** ้—ฎ ้ข˜๏ผš *********************************************/ #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <sys/time.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/msg.h> #include "tsmm.h" typedef struct { long mtype; char mtext[9]; }TSMM_MSG; CCommSMM::CCommSMM() { m_iFdLck = 0; m_iShmId = 0; m_iMsgId = 0; m_iErrCode = 0; m_iBuffLen = 0; m_iMaxMsgLen = 0; m_iMaxMsgNum = 0; memset(m_szPath , 0, sizeof(m_szPath)); memset(m_szMsgId , 0, sizeof(m_szMsgId)); memset(m_szMsgFile, 0, sizeof(m_szMsgFile)); memset(m_szSemFile, 0, sizeof(m_szSemFile)); memset(m_szErrDesc, 0, sizeof(m_szErrDesc)); m_pBuffer = NULL; } CCommSMM::~CCommSMM() { if (NULL != m_pBuffer) { delete m_pBuffer; m_pBuffer = NULL; } if (m_iFdLck >= 0) { close(m_iFdLck); } } // ๅˆ›ๅปบ่ต„ๆบ int CCommSMM::OpenSMM() { key_t key = -1; int msgid = -1; // ๆ–‡ไปถ้” m_iFdLck = open(m_szMsgFile, O_EXCL|O_RDWR, 0600); if (m_iFdLck < 0) { m_iFdLck = open(m_szMsgFile, O_CREAT|O_RDWR, 0600); } // ๅˆ›ๅปบๅคฑ่ดฅ่ฟ”ๅ›ž if (m_iFdLck < 0) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "create file lock [%s] error:[%d][%s]", m_szMsgFile, errno, strerror(errno)); return m_iFdLck; } // ้”ฎๅ€ผ key = ftok(m_szMsgFile, 'a'); if ( -1 == key) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "create msgqueue key [%s] error:[%d][%s]", m_szMsgFile, errno, strerror(errno)); return key; } // ๅ…ฑไบซๅ†…ๅญ˜ msgid = shmget(key, m_iMaxMsgLen*m_iMaxMsgNum, IPC_EXCL); if (-1 == msgid) { msgid = shmget(key, m_iMaxMsgLen*m_iMaxMsgNum, IPC_CREAT | 0666); } if (-1 == msgid) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "create shm msgid [%s] error:[%d][%s]", m_szMsgFile, errno, strerror(errno)); return msgid; } m_iShmId = msgid; // ๆถˆๆฏ้˜Ÿๅˆ— msgid = msgget(key, IPC_EXCL); if (-1 == msgid) { msgid = msgget(key, IPC_CREAT | 0666); } if (-1 == msgid) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "create msgq msgid [%s] error:[%d][%s]", m_szMsgFile, errno, strerror(errno)); return msgid; } m_iMsgId = msgid; return msgid; } // ๅˆๅง‹ๅŒ– int CCommSMM::InitSMM(const char* lpMsgFile, const char* lpPath, int iMaxMsgLen, int iMaxMsgNum) { char szEtc[256+1] = {0}; char szTmp[256+1] = {0}; char *pTmp = NULL; // ่Žทๅ–้…็ฝฎๆ–‡ไปถ่ทฏๅพ„ //char *pEtc = getenv("SCPS_ETC"); char *pEtc = "/home/linzhenwei/IceCode/library/comm_smm"; //DEBUG if (NULL == pEtc) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "getenv %s error", "SCPS_ETC"); return -1; } // ไฟกๅท้‡ๆ ‡่ฏ†็ฌฆๅขžๅŠ ็”จๆˆทๅ๏ผŒๆ”ฏๆŒๅŒไธ€ๅฐๆœบๅ™จ้ƒจ็ฝฒๅคšๅฅ—ๅบ”็”จ char *pUser = getenv("USER"); if (NULL == pUser) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "getenv %s error", "USER"); return -1; } // ็”จๆˆทๅ่ฝฌๆขไธบๅคงๅ†™ char *pszTmp = pUser; while (*pszTmp != 0) { if (*pszTmp>='a' && *pszTmp<='z') *pszTmp = *pszTmp + 'A' - 'a'; pszTmp++; } // ไปŽ ้…็ฝฎๆ–‡ไปถ่ทฏๅพ„ ไธญ่Žทๅ– ้…็ฝฎๆ–‡ไปถๅ็งฐ while (1) { pTmp = strstr(pEtc, "/"); if (NULL != pTmp) { memset(szTmp, 0, sizeof(szTmp)); memcpy(szTmp, pEtc, pTmp-pEtc); strcat(szEtc, szTmp); strcat(szEtc, "/"); pEtc = pTmp + 1; } else { break; } } printf("szEtc path=[%s]\n", szEtc); //DEBUG // ็ป„่ฃ…ๆถˆๆฏ้˜Ÿๅˆ—ไปฅๅŠๅ…ฑไบซๅ†…ๅญ˜ๆ–‡ไปถๅ strncpy(m_szMsgFile, szEtc, sizeof(m_szMsgFile)-1); strcat(m_szMsgFile, "."); strcat(m_szMsgFile, lpMsgFile); strcat(m_szMsgFile, ".kid"); // ไฟกๅท้‡ๆ–‡ไปถๅ strncpy(m_szSemFile, pUser, sizeof(m_szSemFile)-1); strcat(m_szSemFile, lpMsgFile); strcat(m_szSemFile, ".kid"); // ๅคงๆŠฅๆ–‡็ผ“ๅญ˜่ทฏๅพ„ strncpy(m_szPath, lpPath, sizeof(m_szPath)-1); // ่ฎพ็ฝฎๆŠฅๆ–‡้•ฟๅบฆ(่‡ณๅฐ‘ไธบๆœ€ๅฐ้•ฟๅบฆ) m_iMaxMsgLen = iMaxMsgLen; if (m_iMaxMsgLen < MIN_MSG_LEN) { m_iMaxMsgLen = MIN_MSG_LEN; } // ่ฎพ็ฝฎๆŠฅๆ–‡ไธชๆ•ฐ(่‡ณๅฐ‘ไธบๆœ€ๅฐไธชๆ•ฐ) m_iMaxMsgNum = iMaxMsgNum; if (m_iMaxMsgNum < MIN_MSG_NUM) { m_iMaxMsgNum = MIN_MSG_NUM; } // ็”ณ่ฏท็ผ“ๅ†ฒๅŒบ m_iBuffLen = m_iMaxMsgLen + 1; m_pBuffer = new char[m_iMaxMsgLen+1]; if (NULL == m_pBuffer) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "malloc [%d] error[%d][%s]", m_iMaxMsgLen+1, errno, strerror(errno)); return -3; } printf("DEBUG: lpMsgFile=[%s] lpPath=[%s]\n", lpMsgFile, lpPath); printf("DEBUG m_iMaxMsgLen=[%d] m_iMsgMsgNum=[%d] bufferLen=[%d]\n", m_iMaxMsgLen, m_iMaxMsgNum, m_iBuffLen); return OpenSMM(); } // ่Žทๅ–ๆถˆๆฏ iWaitFlag๏ผš0-้˜ปๅกž 1-ไธ้˜ปๅกž iWaitTime๏ผš็ญ‰ๅพ…ๆ—ถ้—ด(็ง’) lpMsgId:ๅŒๆญฅ็ญ‰ๅพ…ๅ…ณ่”ID int CCommSMM::GetMsg(string& strMsg, int iWaitFlag, int iWaitTime, const char* lpMsgId) { int iRet = -1; int iRecvLen = -1; int iMsgFlag = 0; long lMsgType = 9; char* pRecvData = NULL; TSMM_MSG stuMsg; memset(&stuMsg, 0, sizeof(stuMsg)); // ๆถˆๆฏ็ฑปๅž‹๏ผˆๅคงไบŽ0๏ผŒๅˆ™่ฟ”ๅ›žๅ…ถ็ฑปๅž‹ไธบmtype็š„็ฌฌไธ€ไธชๆถˆๆฏ๏ผ‰ if (NULL != lpMsgId && strlen(lpMsgId) > 0) { lMsgType = atol(lpMsgId); } // ไธ้˜ปๅกž if ( 1 == iWaitFlag) { iMsgFlag = IPC_NOWAIT; } // ๆŽฅๆ”ถๆ•ฐๆฎ for (int i=0; i<iWaitTime+1; ++i) { iRecvLen = msgrcv(m_iMsgId, &stuMsg, 8, lMsgType, iMsgFlag); if (iRecvLen < 0) { // ๆฒกๆœ‰ๆถˆๆฏ if ( IPC_NOWAIT == iMsgFlag && ENOMSG == errno) { // ๅฆ‚ๆžœไธ็ญ‰ๅพ…๏ผŒๆฒกๆœ‰ๆถˆๆฏๅˆ™็ซ‹ๅณ่ฟ”ๅ›ž,ๅฆๅˆ™ไผ‘็œ ็ปง็ปญ็ญ‰ๅพ… if ( 0 == iWaitTime) { return 0; } sleep(1); continue; } // ๅ…ถไป–้”™่ฏฏ่ฟ”ๅ›ž้”™่ฏฏ็ ่ทŸๆ่ฟฐ m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "recv msg error[%d][%s]", errno, strerror(errno)); return iRecvLen; } else { // ่ฏปๅ–ๆถˆๆฏๆˆๅŠŸ break; } } // ๅˆคๆ–ญ่ฏปๅ–็š„ๆ•ฐๆฎ if (iRecvLen < 0) { if ( IPC_NOWAIT == iMsgFlag && ENOMSG == errno) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "recv msg no data."); return 0; } m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "recv msg error[%d][%s]", errno, strerror(errno)); return iRecvLen; } // ่ฎฐๅฝ•ๅ็งป้‡ int iPos = atoi(stuMsg.mtext); // ่ฏปๅ–ๆ•ฐๆฎ pRecvData = (char*)shmat(m_iShmId, NULL, 0); if (NULL == pRecvData || 0 == pRecvData[iPos*m_iMaxMsgLen+1]) { iRecvLen = 1; strMsg = ""; } else { memset(m_pBuffer, 0, m_iBuffLen); memcpy(m_pBuffer, pRecvData+iPos*m_iMaxMsgLen+1, m_iMaxMsgLen-1); strMsg = m_pBuffer + 1; iRecvLen = strMsg.length(); } // ่ฟ˜ๅŽŸๅ›žโ€œๆœชไฝฟ็”จโ€็Šถๆ€๏ผˆๆญค่กŒไปฃ็ ๅˆซ็š„่ฟ›็จ‹ๅฐฑๅ˜ไธบN๏ผ‰ memcpy(pRecvData+iPos*m_iMaxMsgLen, "N", 1); // ๆญค่กŒไปฃ็ ไธไผšๅฝฑๅ“ๅˆซ็š„่ฟ›็จ‹็š„ๆ•ฐๆฎ shmdt(pRecvData); // ๆ–‡ไปถๅญ˜ๅ‚จ if ('F' == m_pBuffer[0]) { int iFileLen = 0; char szFile[256+1] = {0}; char szFileLen[8+1] = {0}; char *pFileBuff = NULL; memcpy(szFileLen, m_pBuffer+1, 8); memcpy(szFile , m_pBuffer+9, 256); iFileLen = atoi(szFileLen); printf("DEBUG: read Largemsg=[%s]\n", szFile); // ๆ‰“ๅผ€ๆ–‡ไปถ FILE *fp = fopen(szFile, "rb"); if ( NULL == fp) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "fopen [%s] error [%d][%s]", szFile, errno, strerror(errno)); return -2; } // ็”ณ่ฏท็ผ“ๅ†ฒๅŒบ pFileBuff = new char[iFileLen+1]; // ่ฏปๅ–ๆ–‡ไปถ fread(pFileBuff, 1, iFileLen, fp); fclose(fp); // ้˜ฒๆญข็ป“ๅฐพไนฑ็  pFileBuff[iFileLen] = 0; strMsg = pFileBuff; iRecvLen = strMsg.length(); // ้‡Šๆ”พ่ต„ๆบ delete pFileBuff; remove(szFile); } return iRecvLen; } // ๅ‘้€ๆถˆๆฏ int CCommSMM::PutMsg(const char* lpMsg, int iLen, const char* lpMsgId) { int iRet = -1; int iSendLen = -1; char *pSendData = NULL; TSMM_MSG stuMsg; memset(&stuMsg, 0, sizeof(stuMsg)); // ๆŠฅๆ–‡่ถ…่ฟ‡ๅ†…ๅญ˜ๅคงๅฐ๏ผŒ่ฝฌไธบๆ–‡ไปถๅญ˜ๅ‚จ(ๅœจ้”ๅค–้ขๅฎŒๆˆ๏ผŒๅ‡ๅฐ‘้”ๆ—ถ้—ด) char szFile[256+1] = {0}; char szFileLen[8+1] = {0}; if (iLen > (m_iMaxMsgLen-8)) { // ๆž„ๅปบๆŠฅๆ–‡ๆ–‡ไปถๅ:็คบไพ‹: char szTmp[32] = {0}; snprintf(szTmp, sizeof(szTmp), "%010d%s", getpid(), GetSMMCurrTime()); strcat(szFile, m_szPath); strcat(szFile, "/SMM"); strcat(szFile, szTmp); sprintf(szFileLen, "%08d", iLen); printf("DEBUG: write LargeMsg=[%s] szFileLen=[%s] iLen=[%d]\n", szFile, szFileLen, iLen); // ๆ‰“ๅผ€ๆ–‡ไปถ FILE *fp = fopen(szFile, "wb"); if ( NULL == fp) { snprintf(m_szErrDesc, sizeof(m_szErrDesc), "fopen [%s] error [%d][%s]", szFile, errno, strerror(errno)); return -2; } // ๅ†™ๅ…ฅๆ–‡ไปถ fwrite(lpMsg, 1, iLen, fp); fclose(fp); } // ๅŠ ้” struct flock fLck; fLck.l_type = F_WRLCK; fLck.l_whence = SEEK_SET; fLck.l_start = 0; fLck.l_len = 0; iRet = fcntl(m_iFdLck, F_SETLKW, &fLck); if (iRet < 0) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "lock [%s][%d] error [%d][%s]", m_szMsgFile, m_iFdLck, errno, strerror(errno)); return -1; } // ๅญ˜ๅ‚จๆ•ฐๆฎ(่Žทๅ–ๅ…ฑไบซๅ†…ๅญ˜ไธญๆŠฅๆ–‡ๆ•ฐ้‡) pSendData = (char*)shmat(m_iShmId, NULL, 0); int i = 0; for (i=0; i<m_iMaxMsgNum; ++i) { if ( 'U' == pSendData[i*m_iMaxMsgLen]) { continue; } else // "ๆœชไฝฟ็”จ"็Šถๆ€ { // ๆŠฅๆ–‡่ถ…่ฟ‡ๅ†…ๅญ˜ๅคงๅฐ๏ผŒ่ฝฌไธบๆ–‡ไปถๅญ˜ๅ‚จ if (iLen > (m_iMaxMsgLen-8)) { memset(pSendData+i*m_iMaxMsgLen , 0, m_iMaxMsgLen); memcpy(pSendData+i*m_iMaxMsgLen , "U", 1); memcpy(pSendData+i*m_iMaxMsgLen+1, "F", 1); memcpy(pSendData+i*m_iMaxMsgLen+2, szFileLen, 8); memcpy(pSendData+i*m_iMaxMsgLen+10, szFile, strlen(szFile)); } else { memset(pSendData+i*m_iMaxMsgLen , 0, m_iMaxMsgLen); memcpy(pSendData+i*m_iMaxMsgLen , "U", 1); memcpy(pSendData+i*m_iMaxMsgLen+1, "N", 1); memcpy(pSendData+i*m_iMaxMsgLen+2, lpMsg, iLen); } break; } } shmdt(pSendData); // ่งฃ้” struct flock fUnLck; fUnLck.l_type = F_UNLCK; fUnLck.l_whence = SEEK_SET; fUnLck.l_start = 0; fUnLck.l_len = 0; iRet = fcntl(m_iFdLck, F_SETLK, &fUnLck); if (iRet < 0) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "unlock [%s][%d] error [%d][%s]", m_szMsgFile, m_iFdLck, errno, strerror(errno)); return -1; } // ๅˆคๆ–ญๆ˜ฏๅฆ่ถ…่ฟ‡ๆŠฅๆ–‡ไธชๆ•ฐ if ( i >= m_iMaxMsgNum) { m_iErrCode = -1; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "shm catch full.[%d]", m_iMaxMsgNum); return -1; } // ๆถˆๆฏ็ฑปๅž‹ stuMsg.mtype = 9; if (NULL!=lpMsgId && strlen(lpMsgId)>0) { stuMsg.mtype = atol(lpMsgId); } sprintf(stuMsg.mtext, "%08d", i); // ๅ‘้€ๆ•ฐๆฎ iSendLen = msgsnd(m_iMsgId, &stuMsg, 8, IPC_NOWAIT); if (iSendLen < 0) { m_iErrCode = errno; snprintf(m_szErrDesc, sizeof(m_szErrDesc), "send msg error...[%d][%s]", errno, strerror(errno)); return iSendLen; } return iSendLen; } // ่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด(20ๅญ—่Š‚้•ฟๅบฆ) char* CCommSMM::GetSMMCurrTime() { static char szCurrTime[32] = {0}; struct timeval tp; struct tm *p; time_t timep; time(&timep); p = localtime(&timep); gettimeofday(&tp, NULL); sprintf(szCurrTime, "%04d%02d%02d%02d%02d%02d%06d", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, (int)tp.tv_usec); return szCurrTime; } // ่Žทๅ–้”™่ฏฏไฟกๆฏ char* CCommSMM::GetErrorDesc() { return m_szErrDesc; }
c8f3b70148241fc9ea5c8b6f404b2c61d0c4d916
0646b45467033de19d5a64b8a8c8ff4fcb9185f2
/q9.cpp
3f8b53d5af9e05912ff621355c1c813a74346df5
[]
no_license
apratimchoudhury/lab7
4652e891bee0322a35b45178b6b4b1d19baf8954
4db47d4d8b04c37ded280c0a9f77acd7732a5057
refs/heads/master
2020-03-31T03:06:36.994223
2018-10-06T15:33:00
2018-10-06T15:33:00
151,853,062
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
q9.cpp
#include<iostream> //include library using namespace std; int fact(int n) //function for calculting factorial of a given number { if(n!=0) //stopping condition { return n*fact(n-1); //return factorial value through recursion } else return 1; } int main() //driver function { int n; cout<<"Enter a number: "; //take input cin>>n; cout<<"The factorial of "<<n<<" is "<<fact(n)<<endl; //display output return 0; }
32cf413b51d7a1c3100c1f05549ae44b108c3912
f2fc57911a68ba9c582783b3d851cd08466fc000
/Doodle/includes/Grid.h
a396af189c87e5410d32f4b0369ac13f0892bf16
[]
no_license
Morpheu5/Doodle
636093b74d8db29c163cd3c1fb383bd65f2c3069
fb11d9690bfc3973791b6f3789ae9733637d74e7
refs/heads/master
2021-03-12T22:34:02.995240
2013-07-19T09:17:40
2013-07-19T09:17:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,464
h
Grid.h
/* (C) 2009 by Andrea Franceschini <andrea.franceschini@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GRID_H_ #define GRID_H_ #include <QVector> #include <QSet> #include <QDebug> #include <cmath> namespace Doodle { /*! * A Grid for quick search and location of objects in Viewport (GL_QUAD) space. * This is used to quickly find neightbors of a given object (point). * * Template parameter T is a Target. */ template <class T> class Grid { public: /*! * Standard constructor. */ Grid() { } /*! * Standard destructor. */ virtual ~Grid() { } /*! * Subdivides the space in rows and columns. * * \param rows Number of rows. * \param cols Number of columns. */ void resize(int rows, int cols) { _grid.resize(rows); int i; for(i= 0; i < _grid.size(); i++) { _grid[i].resize(cols); } } /*! * \param row Row coordinate. * \param col Column coordinate. * * \return The objects in the cell (row,col). */ const QSet<T*>& at(int row, int col) const { return _grid[row][col]; } /*! * Converts a position into a Grid cell and returns the objects in that * cell. * * \param x x coordinate. * \param y y coordinate. * * \return The set of objects in the cell containing (x,y). */ const QSet<T*>& at(float x, float y) const { int nx = (int)floor(((x-0.1666)/1.3333)*_grid[0].size())-1; int ny = (int)floor(y*_grid.size())-1; return at(ny, nx); } /*! * \param t A Target, passed by pointer. * * \return The set of objects in the same cell of t. */ const QSet<T*>& at(T* t) const { return at(t->x(), t->y()); } /*! * \param t A Target, passed by reference. * * \return The set of objects in the same cell of t. */ const QSet<T*>& at(const T& t) const { return at(t.x(), t.y()); } /*! * Computes the Grid cell that the Target falls into. Then stores the Target * in that cell. * * \param t A Target. */ void insert(T* t) { int nx = (int)floor(((t->x()-0.1666)/1.3333)*(_grid[0].size())-1); int ny = (int)floor(t->y()*(_grid.size())-1); _grid[ny][nx].insert(t); } /*! * Updates a Target that is already into the Grid. * * \param t A Target. */ void update(T* t) { int nx = (int)floor(((t->x()-0.1666)/1.3333)*(_grid[0].size())-1); int ny = (int)floor(t->y()*(_grid.size())-1); bool found = false; foreach(T* u, _grid[ny][nx]) { if(u->sessionID() == t->sessionID()) { found = true; } } if(!found) { remove(t); } _grid[ny][nx].insert(t); } /*! * Removes a Target from the Grid. * * \param t A Target. */ void remove(T* t) { foreach(QVector<QSet<T*> > v, _grid) { foreach(QSet<T*> s, v) { foreach(T* u, s) { if(u->sessionID() == t->sessionID()) { s.remove(u); } } } } } private: QVector<QVector<QSet<T*> > > _grid; }; } #endif /* GRID_H_ */
4cf8e505592596b513e9481841cd48c7dea677f6
a06eff155ed5aa78441ed527930971acfe60c286
/src/Joypad.cpp
74fc676aa0edddc12904c1bf32a3fd410f6a214a
[]
no_license
Stenodyon/gb
2ea104e21df38e1453d2c4eacc5d0f204956f3cc
0d96ba22c40b70f3525ab842f6b135f69e96bbfb
refs/heads/master
2023-03-20T01:11:49.765748
2021-03-12T10:31:14
2021-03-12T10:31:14
282,471,588
2
0
null
null
null
null
UTF-8
C++
false
false
1,639
cpp
Joypad.cpp
#include "Joypad.hpp" #include "Emulator.hpp" namespace GB { Joypad::Joypad(Emulator& emulator) : m_emulator(emulator) { } void Joypad::cycle() { u8 prev_value = m_joypad_reg; m_joypad_reg &= 0x30; m_joypad_reg |= (buttons_selected() && m_A_pressed) || (directions_selected() && m_right_pressed) ? 0 : 0x1; m_joypad_reg |= (buttons_selected() && m_B_pressed) || (directions_selected() && m_left_pressed) ? 0 : 0x2; m_joypad_reg |= (buttons_selected() && m_select_pressed) || (directions_selected() && m_up_pressed) ? 0 : 0x4; m_joypad_reg |= (buttons_selected() && m_start_pressed) || (directions_selected() && m_down_pressed) ? 0 : 0x8; if ((prev_value & 0x0f) != (m_joypad_reg & 0x0f)) m_emulator.cpu().request_joypad_interrupt(); } void Joypad::set_button_status(Buttons::Button button, bool pressed) { switch (button) { case Buttons::DOWN: m_down_pressed = pressed; break; case Buttons::UP: m_up_pressed = pressed; break; case Buttons::LEFT: m_left_pressed = pressed; break; case Buttons::RIGHT: m_right_pressed = pressed; break; case Buttons::START: m_start_pressed = pressed; break; case Buttons::SELECT: m_select_pressed = pressed; break; case Buttons::A: m_A_pressed = pressed; break; case Buttons::B: m_B_pressed = pressed; break; } } } // namespace GB
44ff467e930b57b2971271f80c65d6c826260189
d99d922978a174f5132ed98bb1ee7dcbd0cad824
/remote_file_explorer_client/serveraccess.h
3c983a81ebf90e5f69043a29dea223cc27b4c296
[]
no_license
grizlip/remote_file_explorer
03686951ece869a869884cbc2c7e5471ef5efce3
2808d969dee56b91f7638a9562a02ede1712e554
refs/heads/master
2023-08-30T12:32:27.305866
2021-11-05T21:28:58
2021-11-05T21:28:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
630
h
serveraccess.h
#ifndef SERVERACCESS_H #define SERVERACCESS_H #include "servercommunication.h" #include <QObject> #include <QString> #include <QStringList> namespace remote_file_explorer_client { class ServerAccess { public: explicit ServerAccess(ServerCommunication& serverCommunication) : m_serverCommunication(&serverCommunication) { } QString getFile(QString path); void setNewPath(QString path); protected: inline Response executeCommand(file_remote_explorer_library::Command command, QStringList args); private: ServerCommunication* m_serverCommunication; }; } #endif // SERVERACCESS_H
70252dd5f5458cb1a2fc2a7df8a7492bbe508bcd
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/policy/networking/policy_cert_service.cc
909496fed436121c6a3c1ce0ac108226625844ec
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
8,857
cc
policy_cert_service.cc
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/networking/policy_cert_service.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/net/nss_temp_certs_cache_chromeos.h" #include "chrome/browser/net/profile_network_context_service.h" #include "chrome/browser/net/profile_network_context_service_factory.h" #include "chrome/browser/policy/networking/policy_cert_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chromeos/ash/components/network/policy_certificate_provider.h" #include "chromeos/components/onc/certificate_scope.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "extensions/browser/extension_util.h" #include "net/cert/x509_certificate.h" #include "url/gurl.h" namespace policy { PolicyCertService::~PolicyCertService() { StopListeningToPolicyCertificateProvider(); } PolicyCertService::PolicyCertService( Profile* profile, ash::PolicyCertificateProvider* policy_certificate_provider, bool may_use_profile_wide_trust_anchors) : profile_(profile), policy_certificate_provider_(policy_certificate_provider), may_use_profile_wide_trust_anchors_(may_use_profile_wide_trust_anchors) { DCHECK(policy_certificate_provider_); DCHECK(profile_); policy_certificate_provider_->AddPolicyProvidedCertsObserver(this); profile_wide_all_server_and_authority_certs_ = policy_certificate_provider_->GetAllServerAndAuthorityCertificates( chromeos::onc::CertificateScope::Default()); profile_wide_trust_anchors_ = GetAllowedProfileWideTrustAnchors(); } PolicyCertService::PolicyCertService(Profile* profile) : profile_(profile), policy_certificate_provider_(nullptr), may_use_profile_wide_trust_anchors_(true) {} void PolicyCertService::OnPolicyProvidedCertsChanged() { profile_wide_all_server_and_authority_certs_ = policy_certificate_provider_->GetAllServerAndAuthorityCertificates( chromeos::onc::CertificateScope::Default()); profile_wide_trust_anchors_ = GetAllowedProfileWideTrustAnchors(); // Make all policy-provided server and authority certificates available to NSS // as temp certificates. // While the network service is out-of-process so it is not affected by this, // this is important for client certificate selection which still happens in // the browser process. // Note that this is done on the UI thread because the assumption is that NSS // has already been initialized by Chrome OS specific start-up code in chrome, // expecting that the operation of creating in-memory NSS certs is cheap in // that case. temp_policy_provided_certs_ = std::make_unique<network::NSSTempCertsCacheChromeOS>( profile_wide_all_server_and_authority_certs_); auto* profile_network_context = ProfileNetworkContextServiceFactory::GetForContext(profile_); profile_network_context->UpdateAdditionalCertificates(); } void PolicyCertService::OnPolicyCertificateProviderDestroying() { StopListeningToPolicyCertificateProvider(); } void PolicyCertService::GetPolicyCertificatesForStoragePartition( const base::FilePath& partition_path, net::CertificateList* out_all_server_and_authority_certificates, net::CertificateList* out_trust_anchors) const { *out_all_server_and_authority_certificates = profile_wide_all_server_and_authority_certs_; *out_trust_anchors = profile_wide_trust_anchors_; if (policy_certificate_provider_->GetExtensionIdsWithPolicyCertificates() .empty()) { return; } // The following code adds policy-provided extension specific certificates. // Policy can specify these keyed by extension ID. // In general, there is no direct mapping from a StoragePartition path to an // extension ID, because extensions could be using the default // StoragePartition of the Profile. // However, for extensions with isolated storage, the extension will be in a // StoragePartition that is exclusively used by this extension. // Policy-provided extension specific certificates are thus only allowed for // extensions with isolated storage. // The following code checks those preconditions and attempts to find the // extension ID (among extensions IDs with policy-provided certificates) that // corresponds to |partition_path|. base::FilePath default_storage_partition_path = profile_->GetDefaultStoragePartition()->GetPath(); // Among the extension IDs that have policy-provided certificates, attempt to // find the extension ID which corresponds to |partition_path|. // This is done by iterating the extension IDs because there's no trivial // conversion from |partition_path| to extension ID as explained above. std::string current_extension_id_with_policy_certificates; std::set<std::string> extension_ids_with_policy_certificates = policy_certificate_provider_->GetExtensionIdsWithPolicyCertificates(); for (const auto& extension_id : extension_ids_with_policy_certificates) { // Only allow policy-provided certificates for extensions with isolated // storage. Also sanity-check that it's not the default partition. content::StoragePartition* extension_partition = extensions::util::GetStoragePartitionForExtensionId( extension_id, profile_, /*can_create=*/false); if (!extension_partition) continue; if (!extensions::util::HasIsolatedStorage(extension_id, profile_) || extension_partition->GetPath() == default_storage_partition_path) { LOG(ERROR) << "Ignoring policy certificates for " << extension_id << " because it does not have isolated storage"; continue; } if (partition_path == extension_partition->GetPath()) { current_extension_id_with_policy_certificates = extension_id; break; } } if (current_extension_id_with_policy_certificates.empty()) return; net::CertificateList extension_all_server_and_authority_certificates = policy_certificate_provider_->GetAllServerAndAuthorityCertificates( chromeos::onc::CertificateScope::ForExtension( current_extension_id_with_policy_certificates)); out_all_server_and_authority_certificates->insert( out_all_server_and_authority_certificates->end(), extension_all_server_and_authority_certificates.begin(), extension_all_server_and_authority_certificates.end()); net::CertificateList extension_trust_anchors = policy_certificate_provider_->GetWebTrustedCertificates( chromeos::onc::CertificateScope::ForExtension( current_extension_id_with_policy_certificates)); out_trust_anchors->insert(out_trust_anchors->end(), extension_trust_anchors.begin(), extension_trust_anchors.end()); } bool PolicyCertService::UsedPolicyCertificates() const { return profile_->GetPrefs()->GetBoolean(prefs::kUsedPolicyCertificates); } void PolicyCertService::SetUsedPolicyCertificates() { profile_->GetPrefs()->SetBoolean(prefs::kUsedPolicyCertificates, true); } net::CertificateList PolicyCertService::GetAllowedProfileWideTrustAnchors() { if (!may_use_profile_wide_trust_anchors_) return {}; return policy_certificate_provider_->GetWebTrustedCertificates( chromeos::onc::CertificateScope::Default()); } // static void PolicyCertService::RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterBooleanPref(prefs::kUsedPolicyCertificates, false); } // static std::unique_ptr<PolicyCertService> PolicyCertService::CreateForTesting( Profile* profile) { return base::WrapUnique(new PolicyCertService(profile)); } void PolicyCertService::SetPolicyTrustAnchorsForTesting( const net::CertificateList& trust_anchors) { // Only allow this call in an instance that has been created through // PolicyCertService::CreateForTesting. CHECK_EQ(nullptr, policy_certificate_provider_); profile_wide_all_server_and_authority_certs_ = trust_anchors; profile_wide_trust_anchors_ = trust_anchors; } void PolicyCertService::StopListeningToPolicyCertificateProvider() { if (!policy_certificate_provider_) { return; } policy_certificate_provider_->RemovePolicyProvidedCertsObserver(this); policy_certificate_provider_ = nullptr; } } // namespace policy
d91ad74d37f63bf0b9660313605d7b47ebcacdfc
890eaf082da0b5c5043156f5984957980394ff1f
/libs/vcdparse/src/libvcdparse/vcd_loader.hpp
62eb8b372ff355e2b16956ab57e3db2feabeb796
[ "MIT" ]
permissive
kmurray/esta
e5c704d4fde160b49dac5d38d26f7f0d9203f43a
4c6833fef137b816c6a399403e9f3bda9e99725a
refs/heads/master
2021-01-17T23:32:01.148702
2017-10-12T21:12:41
2017-10-12T21:12:41
62,819,388
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
hpp
vcd_loader.hpp
#pragma once #include <iosfwd> #include <memory> #include <set> #include "vcd_data.hpp" namespace vcdparse { //Forward delcarations class Lexer; class Parser; class ParseError; //Class for loading an SDF file. // //The vcd file can be parsed using load(), which returns true //if successful - after which the loaded data can be accessed via //get_vcd_data(). // //The virtual method on_error() can be overriding to control //error handling. The default simply prints out an error message, //but it could also be defined to (re-)throw an exception. class Loader { public: Loader(); ~Loader(); bool load(std::string filename); bool load(std::istream& is, std::string filename="<inputstream>"); const VcdData& get_vcd_data() { return vcd_data_; }; protected: virtual void on_error(ParseError& error); private: Var::Id generate_var_id(std::string str_id); private: friend Parser; std::string filename_; std::unique_ptr<Lexer> lexer_; std::unique_ptr<Parser> parser_; bool pre_allocate_time_values_ = true; VcdData vcd_data_; std::vector<std::string> current_scope_; size_t curr_time_; size_t change_count_; VcdData::TimeValues time_values_; std::map<std::string,Var::Id> var_str_to_id_; Var::Id max_var_id_ = 0; }; } //vcdparse
5cb7a541e9ccc6c02743623b7160e5c754085e51
15ab9d0f6779932a0179ab018d0577aecd4cb3f3
/models/graph.hpp
fbf6c96126594381f1ae5ef0abde3f361ee85fab
[]
no_license
igmagollo/sudoku-graph-coloring
a17ef394ec38ae43de4da059390737410a9bc05e
7b7f414383d9045632fca1fa280e53d98d9219ff
refs/heads/master
2020-04-07T12:34:38.631839
2018-11-26T02:08:16
2018-11-26T02:08:16
158,372,856
0
0
null
null
null
null
UTF-8
C++
false
false
881
hpp
graph.hpp
#ifndef GRAPH_HPP #define GRAPH_HPP #include <vector> #include <iostream> #include <set> using namespace std; class graph { private: vector<set<int> > v; /** * push back a target vertice in a vertice */ void pushBackEdge(int v_index, int v_target); public: graph() = default; graph(vector<set<int> > vertices); ~graph() = default; /** * add a new vertice and returns your number */ int newVertice(); /** * add n vertices */ void newNVertices(int n); /** * returns true if v2 is in v1's neighbors */ bool edgeExists(const set<int>& v1, int v2) const; /** * add an edge */ void addEdge(int v1, int v2); /** * get a vertice */ const set<int>& getVertice(int v_index) const; /** * get the degree of the vertice at the index specified */ int getVerticeDegree(int v_index) const; /** * print the graph */ void printGraph() const; }; #endif