blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8e7dc034058886c4d61a288cd401b0be9d532d5d | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/070/345/CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cpy_72b.cpp | 29c963db5733f7441312c4e39b842ccc7bc5083a | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cpy_72b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_src.label.xml
Template File: sources-sink-72b.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sinks: cpy
* BadSink : Copy data to string using wcscpy
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#include <wchar.h>
using namespace std;
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cpy_72
{
#ifndef OMITBAD
void badSink(vector<wchar_t *> dataVector)
{
/* copy data out of dataVector */
wchar_t * data = dataVector[2];
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
wcscpy(dest, data);
printWLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<wchar_t *> dataVector)
{
wchar_t * data = dataVector[2];
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
wcscpy(dest, data);
printWLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
60947c46e89c0390115714adbc301eeea48a0daf | 2b6560886febdc8584ac20ad5fa74d375277fe5d | /input.h | 2dd48f893847524ed943e6c6e801e006858e6cd8 | [] | no_license | csorgocsaba/heat-changers | 9625e842890372fb7781a78d544a8adecdf094b4 | 8e1f2852fa601a90afcdfa3fd30d4e43700e4ab6 | refs/heads/master | 2021-01-10T13:16:22.708007 | 2016-03-07T09:50:58 | 2016-03-07T09:50:58 | 53,314,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | h | #ifndef INPUT_H
#define INPUT_H
#include "stream.h"
#include <QDialog>
namespace Ui {
class Input;
}
class Input : public QDialog
{
Q_OBJECT
public:
explicit Input(QWidget *parent = 0);
~Input();
void setStreams(std::vector<Stream> *streamvect);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
std::vector<Stream> *streams;
Ui::Input *ui;
};
#endif // INPUT_H
| [
"csorgocsaba@gmail.com"
] | csorgocsaba@gmail.com |
7ebce44af9aacc159c3e3c1cdedaab2238d58be3 | 376fcdeb205e4c02c112e6dbbfe44c9109637d92 | /Whisky Engine/Source/Component Library/BehaviorComponent.cpp | abe1dcf0ef69e92ece8e14422c9f5f519dda794a | [] | no_license | Nightmask3/Whisky-Engine | 78e4307a32e21a1c3930f832b0bec2522be7c267 | fec9f4a69794c6186bf2091d47bf873aec832023 | refs/heads/master | 2020-05-29T09:14:28.065036 | 2016-01-27T20:16:29 | 2016-01-27T20:16:29 | 49,865,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | cpp | #include "PhysicsComponent.h"
#include "..\Entity Library\GameObject.h"
#include "..\Physics Library\BoundingSphere.h"
#include "BehaviorComponent.h"
#include <time.h>
void BehaviorComponent::Update()
{
srand(time(NULL));
TransformComponent * t = nullptr;
t = static_cast<TransformComponent *>(mOwner->GetComponent(Component::TRANSFORM));
if (mMoveDir == 0)
{
random = rand() % 2 + 1;
}
// If not colliding with an object, keep moving in a random direction
countdown--;
if (mColliding == false)
{
mMoveDir = 1;
switch (random)
{
case 1:
t->Translate(0, 0, moveCoordinate);
break;
case 2:
t->Translate(0, 0, -moveCoordinate);
break;
default:
break;
}
}
// If entity is colliding with an object, change direction
if (countdown == 0)
{
countdown = 10;
mMoveDir = 0;
}
}
void BehaviorComponent::HandleEvent(Event *pEvent)
{
} | [
"Nightmask3@gmail.com"
] | Nightmask3@gmail.com |
abc67a5ff1d5fe46fcd6d59867a0dabc393d85cb | 1b8a79bb13c1376ef7041acffec16ee7dcce3dbb | /td/telegram/DialogAction.h | cd33d248a8319cfdb3cf3e18f24cf56fa14149b0 | [
"JSON",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bejbybox/td | c748a3f48e1f1f40df95830f017eb8ee3b774e53 | 1979b2b142fdb8dffce273ede8559c8620dbd56d | refs/heads/master | 2023-03-31T16:20:32.981454 | 2021-04-12T15:32:47 | 2021-04-12T15:32:47 | 357,327,212 | 1 | 0 | BSL-1.0 | 2021-04-12T22:38:19 | 2021-04-12T20:15:43 | null | UTF-8 | C++ | false | false | 2,281 | h | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "td/telegram/MessageContentType.h"
#include "td/telegram/secret_api.h"
#include "td/telegram/td_api.h"
#include "td/telegram/telegram_api.h"
#include "td/utils/common.h"
#include "td/utils/StringBuilder.h"
namespace td {
class DialogAction {
enum class Type : int32 {
Cancel,
Typing,
RecordingVideo,
UploadingVideo,
RecordingVoiceNote,
UploadingVoiceNote,
UploadingPhoto,
UploadingDocument,
ChoosingLocation,
ChoosingContact,
StartPlayingGame,
RecordingVideoNote,
UploadingVideoNote,
SpeakingInVoiceChat,
ImportingMessages
};
Type type_ = Type::Cancel;
int32 progress_ = 0;
DialogAction(Type type, int32 progress);
void init(Type type);
void init(Type type, int32 progress);
public:
DialogAction() = default;
explicit DialogAction(tl_object_ptr<td_api::ChatAction> &&action);
explicit DialogAction(tl_object_ptr<telegram_api::SendMessageAction> &&action);
tl_object_ptr<telegram_api::SendMessageAction> get_input_send_message_action() const;
tl_object_ptr<secret_api::SendMessageAction> get_secret_input_send_message_action() const;
td_api::object_ptr<td_api::ChatAction> get_chat_action_object() const;
bool is_cancelled_by_message_of_type(MessageContentType message_content_type) const;
static DialogAction get_uploading_action(MessageContentType message_content_type, int32 progress);
static DialogAction get_typing_action();
static DialogAction get_speaking_action();
int32 get_importing_messages_action_progress() const;
friend bool operator==(const DialogAction &lhs, const DialogAction &rhs) {
return lhs.type_ == rhs.type_ && lhs.progress_ == rhs.progress_;
}
friend StringBuilder &operator<<(StringBuilder &string_builder, const DialogAction &action);
};
inline bool operator!=(const DialogAction &lhs, const DialogAction &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const DialogAction &action);
} // namespace td
| [
"levlam@telegram.org"
] | levlam@telegram.org |
a0638886433bde70b85a319f18525a587b9974fb | 8f2bd46f3a43e9256faf5070acd8bb00064fc09a | /cpp/silly_recursive_ptr/silly_recursive_ptr.cpp | 36e20e5569b38b535fcb1db26a332fe21166419d | [] | no_license | sashang/notebook_of_code | b15f05a796fece77ac1bea5f4b347bf050768acb | 040800974db9614f9f894e47385102443bf17e74 | refs/heads/master | 2021-08-11T23:18:42.711676 | 2021-07-31T19:22:45 | 2021-07-31T19:22:45 | 2,428,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cpp | //silly program that demonstrates the use of templates to create
//type that requires 10 *s to dereference.
#include <boost/shared_ptr.hpp>
using namespace boost;
template <int count>
class BP
{
public:
typedef shared_ptr< typename BP<count - 1>::inner_type > inner_type;
};
template <>
class BP<0>
{
public:
typedef int inner_type;
};
int
main(int argc, char** argv)
{
BP<1>::inner_type p_1; //**p
BP<10>::inner_type p_10; //10 *s needed to dereference!!!
*p_1 = 1; //yes i know this is silly
**********p_10 = 1;
}
| [
"sashan@zenskg.net"
] | sashan@zenskg.net |
944d1d33fdf2a8e3ca90bf609ea6985ad690d106 | ecf0bc675b4225da23f1ea36c0eda737912ef8a9 | /Reco_Csrc/WorldEditor/VirtualTreeNode.cpp | 2c9dd0181f131ad6b74790dd6c9b8872e7539fe8 | [] | no_license | Artarex/MysteryV2 | 6015af1b501ce5b970fdc9f5b28c80a065fbcfed | 2fa5608a4e48be36f56339db685ae5530107a520 | refs/heads/master | 2022-01-04T17:00:05.899039 | 2019-03-11T19:41:19 | 2019-03-11T19:41:19 | 175,065,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cpp | version https://git-lfs.github.com/spec/v1
oid sha256:cd455cad7c08593e596e10f66b77d5ef43ec7609739c76945e23ed219f5d848d
size 3282
| [
"artarex@web.de"
] | artarex@web.de |
fcd0bf82e749d164d09eb1a5f8d4f795f458e87b | 607e69f9e4440ef3ab9c33b7b6e85e95b5e982fb | /deps/museum/7.0.0/art/runtime/dex_method_iterator.h | 658b0d18c2dc10eacfa27f4765fcb90553088390 | [
"Apache-2.0"
] | permissive | simpleton/profilo | 8bda2ebf057036a55efd4dea1564b1f114229d1a | 91ef4ba1a8316bad2b3080210316dfef4761e180 | refs/heads/master | 2023-03-12T13:34:27.037783 | 2018-04-24T22:45:58 | 2018-04-24T22:45:58 | 125,419,173 | 0 | 0 | Apache-2.0 | 2018-03-15T19:54:00 | 2018-03-15T19:54:00 | null | UTF-8 | C++ | false | false | 4,240 | h | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_RUNTIME_DEX_METHOD_ITERATOR_H_
#define ART_RUNTIME_DEX_METHOD_ITERATOR_H_
#include <museum/7.0.0/external/libcxx/vector>
#include <museum/7.0.0/art/runtime/dex_file.h>
namespace facebook { namespace museum { namespace MUSEUM_VERSION { namespace art {
class DexMethodIterator {
public:
explicit DexMethodIterator(const std::vector<const DexFile*>& dex_files)
: dex_files_(dex_files),
found_next_(false),
dex_file_index_(0),
class_def_index_(0),
class_def_(nullptr),
class_data_(nullptr),
direct_method_(false) {
CHECK_NE(0U, dex_files_.size());
}
bool HasNext() {
if (found_next_) {
return true;
}
while (true) {
// End of DexFiles, we are done.
if (dex_file_index_ == dex_files_.size()) {
return false;
}
if (class_def_index_ == GetDexFileInternal().NumClassDefs()) {
// End of this DexFile, advance and retry.
class_def_index_ = 0;
dex_file_index_++;
continue;
}
if (class_def_ == nullptr) {
class_def_ = &GetDexFileInternal().GetClassDef(class_def_index_);
}
if (class_data_ == nullptr) {
class_data_ = GetDexFileInternal().GetClassData(*class_def_);
if (class_data_ == nullptr) {
// empty class, such as a marker interface
// End of this class, advance and retry.
class_def_ = nullptr;
class_def_index_++;
continue;
}
}
if (it_.get() == nullptr) {
it_.reset(new ClassDataItemIterator(GetDexFileInternal(), class_data_));
// Skip fields
while (GetIterator().HasNextStaticField()) {
GetIterator().Next();
}
while (GetIterator().HasNextInstanceField()) {
GetIterator().Next();
}
direct_method_ = true;
}
if (direct_method_ && GetIterator().HasNextDirectMethod()) {
// Found method
found_next_ = true;
return true;
}
direct_method_ = false;
if (GetIterator().HasNextVirtualMethod()) {
// Found method
found_next_ = true;
return true;
}
// End of this class, advance and retry.
DCHECK(!GetIterator().HasNext());
it_.reset(nullptr);
class_data_ = nullptr;
class_def_ = nullptr;
class_def_index_++;
}
}
void Next() {
found_next_ = false;
if (it_.get() != nullptr) {
// Advance to next method if we currently are looking at a class.
GetIterator().Next();
}
}
const DexFile& GetDexFile() {
CHECK(HasNext());
return GetDexFileInternal();
}
uint32_t GetMemberIndex() {
CHECK(HasNext());
return GetIterator().GetMemberIndex();
}
InvokeType GetInvokeType() {
CHECK(HasNext());
CHECK(class_def_ != nullptr);
return GetIterator().GetMethodInvokeType(*class_def_);
}
private:
ClassDataItemIterator& GetIterator() const {
CHECK(it_.get() != nullptr);
return *it_.get();
}
const DexFile& GetDexFileInternal() const {
CHECK_LT(dex_file_index_, dex_files_.size());
const DexFile* dex_file = dex_files_[dex_file_index_];
CHECK(dex_file != nullptr);
return *dex_file;
}
const std::vector<const DexFile*>& dex_files_;
bool found_next_;
uint32_t dex_file_index_;
uint32_t class_def_index_;
const DexFile::ClassDef* class_def_;
const uint8_t* class_data_;
std::unique_ptr<ClassDataItemIterator> it_;
bool direct_method_;
};
} } } } // namespace facebook::museum::MUSEUM_VERSION::art
#endif // ART_RUNTIME_DEX_METHOD_ITERATOR_H_
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
73c71f7f17fc07c03f4f7b02c39db126e82eb806 | 94db6acf97d414ffd0a0058453dc1d0d4ecbe80f | /test/point_concept_test.cpp | 323c1afbf93a40a15cc5d698cb83f7289b491792 | [
"MIT"
] | permissive | loic-yvonnet/convex-hull-cpp14 | 10887373b7e073b80576af6431214c163dbfffd7 | 9dcb17abea8a0f5de0f3fe114c612b10f96ab422 | refs/heads/master | 2021-01-22T14:21:26.278045 | 2017-09-26T18:18:02 | 2017-09-26T18:18:02 | 100,712,756 | 2 | 1 | MIT | 2020-10-03T16:03:44 | 2017-08-18T13:06:20 | C++ | UTF-8 | C++ | false | false | 7,788 | cpp | /**
* Unit tests for the point concept.
*/
#include "test_main.hpp"
#include "../hull/point_concept.hpp"
#include <array>
static auto test_has_member_x = add_test([] {
// Arrange
struct p1 {
int x;
};
struct p2 {
};
// Act & Assert
assert(hull::has_member_x<p1>::value == true);
assert(hull::has_member_x<p2>::value == false);
});
static auto test_valid_point_lower_case = add_test([] {
// Arrange
struct p {
int x;
int y;
};
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_upper_case = add_test([] {
// Arrange
struct p {
int X;
int Y;
};
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_method_accessor_lower_case = add_test([] {
// Arrange
class p {
float coord_x{};
float coord_y{};
public:
float x() const noexcept { return coord_x; }
float y() const noexcept { return coord_y; }
};
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_method_accessor_upper_case = add_test([] {
// Arrange
class p {
short coord_x{};
short coord_y{};
public:
short X() const noexcept { return coord_x; }
short Y() const noexcept { return coord_y; }
};
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_array_size_2 = add_test([] {
// Arrange
using p = int[2];
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_array_size_3 = add_test([] {
// Arrange
using p = int[3];
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_pair = add_test([] {
// Arrange
using p = std::pair<int, int>;
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_invalid_point_pair = add_test([] {
// Arrange
using p = std::pair<int, float>;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_valid_point_tuple = add_test([] {
// Arrange
using p = std::tuple<float, float>;
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_other_tuple = add_test([] {
// Arrange
using p = std::tuple<short, short, char, double, std::pair<int, int>>;
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_invalid_point_tuple = add_test([] {
// Arrange
using p = std::tuple<int, float>;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_invalid_point_other_tuple = add_test([] {
// Arrange
using p = std::tuple<short>;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_invalid_point_another_tuple = add_test([] {
// Arrange
using p = std::tuple<char, short, int, long>;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_valid_point_array = add_test([] {
// Arrange
using p = std::array<int, 3>;
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_valid_point_other_array = add_test([] {
// Arrange
using p = std::array<float, 2>;
// Act & Assert
assert(hull::is_point<p>::value == true);
});
static auto test_invalid_point_array = add_test([] {
// Arrange
using p = std::array<int, 1>;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_missing_y_coordinate = add_test([] {
// Arrange
struct p {
int x;
};
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_missing_x_coordinate = add_test([] {
// Arrange
struct p {
int y;
};
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_missing_coordinates = add_test([] {
// Arrange
struct p {
};
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_case_mismatch = add_test([] {
// Arrange
class p {
short coord_x{};
short coord_y{};
public:
short x() const noexcept { return coord_x; }
short Y() const noexcept { return coord_y; }
};
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_missing_y_method = add_test([] {
// Arrange
class p {
short coord_x{};
public:
short x() const noexcept { return coord_x; }
};
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_too_small_array = add_test([] {
// Arrange
using p = float[1];
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_a_value_is_not_a_point = add_test([] {
// Arrange
using p = float;
// Act & Assert
assert(hull::is_point<p>::value == false);
});
static auto test_x_free_function = add_test([] {
// Arrange
struct p {
int x{};
} _;
// Act & Assert
assert(hull::x(_) == 0);
});
static auto test_X_free_function = add_test([] {
// Arrange
struct p {
int X{};
} _;
// Act & Assert
assert(hull::x(_) == 0);
});
static auto test_x_free_function_for_method_accessor = add_test([] {
// Arrange
class p {
int coord_x{};
public:
constexpr int x() const noexcept { return coord_x; }
} _;
// Act & Assert
assert(hull::x(_) == 0);
});
static auto test_X_free_function_for_method_accessor = add_test([] {
// Arrange
class p {
int coord_x{};
public:
constexpr int X() const noexcept { return coord_x; }
} _;
// Act & Assert
assert(hull::x(_) == 0);
});
static auto test_x_free_function_for_array = add_test([] {
// Arrange
char coord[1] = { 0 };
// Act & Assert
assert(hull::x(coord) == 0);
});
static auto test_y_free_function_for_array = add_test([] {
// Arrange
double coord[3] = { 1., 2., 3. };
// Act & Assert
assert(hull::y(coord) == 2.);
});
static auto test_x_free_function_for_pair = add_test([] {
// Arrange
std::pair<int, int> p{};
// Act & Assert
assert(hull::x(p) == 0);
});
static auto test_y_free_function_for_pair = add_test([] {
// Arrange
std::pair<double, double> p{2., 4.};
// Act & Assert
assert(hull::y(p) == 4.);
});
static auto test_x_free_function_for_tuple = add_test([] {
// Arrange
std::tuple<int, int> p{};
// Act & Assert
assert(hull::x(p) == 0);
});
static auto test_y_free_function_for_tuple = add_test([] {
// Arrange
std::tuple<double, double, char> p{2., 4.};
// Act & Assert
assert(hull::y(p) == 4.);
});
static auto test_x_free_function_for_std_array = add_test([] {
// Arrange
std::array<int, 2> p{};
// Act & Assert
assert(hull::x(p) == 0);
});
static auto test_y_free_function_for_std_array = add_test([] {
// Arrange
std::array<int, 2> p{{4, 2}};
// Act & Assert
assert(hull::y(p) == 2);
});
static auto test_make_point_general_case = add_test([] {
// Arrange
using p = std::pair<int, int>;
// Act & Assert
assert((hull::make_point<p>(4, 2) == p{4, 2}));
});
static auto test_make_point_std_array_case = add_test([] {
// Arrange
using p = std::array<int, 2>;
// Act & Assert
assert((hull::make_point<p>(4, 2) == p{{4, 2}}));
});
| [
"loic.yvonnet.pro@gmail.com"
] | loic.yvonnet.pro@gmail.com |
d48e922fc34f8d2a0c69e46aa5c8779e2310cff0 | 0f53692fc00dd2b5da5ebd3f3332e01448657f30 | /cocos2dx/GeniusXTest/frameworks/genius-x/genius/ECS/Common/Components/EntityCom.h | 84950d0584740625e2288419b9ba359983e2c73b | [] | no_license | RayRiver/misc | 5b8a5d8da7e6b01d2723757f49d74c09afd50cbc | f5c4e60ee9f20a929496272944026147b77af335 | refs/heads/master | 2016-09-06T10:05:49.252850 | 2015-09-11T13:26:48 | 2015-09-11T13:26:48 | 17,079,707 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,002 | h | /****************************************************************************
Copyright (c) 2014 Elvis Qin
Copyright (c) 2014 Soulgame Inc.
http://www.genius-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __GX__EntityCom__
#define __GX__EntityCom__
#include "cocos2d.h"
#include "../../../GXMacros.h"
#include "../../Com.h"
#include "../../Entity.h"
NS_GX_BEGIN
/**
* 定义一个集合的游戏对象Entity,这些游戏对象在初始化的时候被创建
*
*/
class EntityCom :public GX::Com
{
public:
static std::string _TYPE;
EntityCom();
static EntityCom* create(){return new EntityCom();}
std::map<std::string,std::string> entityNames;;
std::map<std::string,GX::Entity*> entities;
protected:
virtual void initWithMap(rapidjson::Value&) override;
virtual Com* cloneEmpty() const override;
};
NS_GX_END
#endif /* defined(__GX__EntityCom__) */
| [
"Messanger.6085@gmail.com"
] | Messanger.6085@gmail.com |
bc2b44cdda5d9b97684d01e4c97e84f389d2ba49 | 961019788852c18b3e8ce38e3458b7bdae6c0a3e | /Wimmer/Game.cpp | 3f82d2c92b21116c9bb3a402a33bebacdde6e3c6 | [] | no_license | dsch/c4_17mme | b3bf06639ec07311539208fe24ab7db34ade226e | ff725d799399663837e5cfdfe0553c4d50aea737 | refs/heads/master | 2021-03-22T02:54:30.973795 | 2017-12-25T13:11:58 | 2018-01-23T21:37:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,096 | cpp | #include "Game.h"
bool Game::Unentschieden(const UserInterface::GridType& grid)
{
int row = 0;
int zaehler = 0;
for(int col=0; col<=6; col++)
{
if(grid[row][col].isEmpty() == false)
{
zaehler++;
}
}
if(zaehler >= 7)
{
ui.notifyDraw();
return true;
}
return false;
}
int Game::Gewonnen(const UserInterface::GridType& grid)
{
int rueckgabe = 0;
/// nach rechts
for(int row=0; row<=7; row++)
{
for(int col=0; col<=3; col++)
{
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::RED)&&\
(grid[row][col+1].getColor() == UserInterface::Color::RED)&&\
(grid[row][col+1].isEmpty() == false)&&\
(grid[row][col+2].getColor() == UserInterface::Color::RED)&&\
(grid[row][col+2].isEmpty() == false)&&\
(grid[row][col+3].getColor() == UserInterface::Color::RED)&&\
(grid[row][col+3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::RED);
rueckgabe = 1;
}
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row][col+1].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row][col+1].isEmpty() == false)&&\
(grid[row][col+2].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row][col+2].isEmpty() == false)&&\
(grid[row][col+3].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row][col+3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::YELLOW);
rueckgabe = 1;
}
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////
/// nach oben
for(int col=0; col<=6; col++)
{
for(int row=0; row<=2; row++)
{
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col].isEmpty() == false)&&\
(grid[row+2][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+2][col].isEmpty() == false)&&\
(grid[row+3][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+3][col].isEmpty() == false))
{
ui.notifyWinner(ui.Color::RED);
rueckgabe = 1;
}
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col].isEmpty() == false)&&\
(grid[row+2][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+2][col].isEmpty() == false)&&\
(grid[row+3][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+3][col].isEmpty() == false))
{
ui.notifyWinner(ui.Color::YELLOW);
rueckgabe = 1;
}
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////
/// schr�g nach rechts oben
for(int col=0; col<=6; col++)
{
for(int row=0; row<=2; row++)
{
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col+1].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col+1].isEmpty() == false)&&\
(grid[row+2][col+2].getColor() == UserInterface::Color::RED)&&\
(grid[row+2][col+2].isEmpty() == false)&&\
(grid[row+3][col+3].getColor() == UserInterface::Color::RED)&&\
(grid[row+3][col+3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::RED);
rueckgabe = 1;
}
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col+1].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col+1].isEmpty() == false)&&\
(grid[row+2][col+2].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+2][col+2].isEmpty() == false)&&\
(grid[row+3][col+3].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+3][col+3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::YELLOW);
rueckgabe = 1;
}
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////
/// schr�g nach links oben
for(int col=3; col<=6; col++)
{
for(int row=7; row>=0; row--)
{
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col-1].getColor() == UserInterface::Color::RED)&&\
(grid[row+1][col-1].isEmpty() == false)&&\
(grid[row+2][col-2].getColor() == UserInterface::Color::RED)&&\
(grid[row+2][col-2].isEmpty() == false)&&\
(grid[row+3][col-3].getColor() == UserInterface::Color::RED)&&\
(grid[row+3][col-3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::RED);
rueckgabe = 1;
}
if((grid[row][col].isEmpty() == false)&&\
(grid[row][col].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col-1].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+1][col-1].isEmpty() == false)&&\
(grid[row+2][col-2].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+2][col-2].isEmpty() == false)&&\
(grid[row+3][col-3].getColor() == UserInterface::Color::YELLOW)&&\
(grid[row+3][col-3].isEmpty() == false))
{
ui.notifyWinner(ui.Color::YELLOW);
rueckgabe = 1;
}
}
}
if (rueckgabe == 1){
return 1;
}
else return 0;
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////
Game::Game(UserInterface& ui) : ui(ui)
{
//ctor
}
Game::~Game()
{
//dtor
}
//definieren was gemacht wird wenn play() aufgerufen wird
void Game::play()
{
UserInterface::GridType SpielFeld;
unsigned int colNow;
// UserInterface::ColumnType col;
UserInterface::RowType row;
UserInterface::GridType grid;
// ui.askPlayer(UserInterface::Color::RED); //gut
// ui.askPlayer(ui.Color::RED);
// ui.notifyDraw();
// ui.notifyWinner(ui.Color::RED);
int Reihe = 0;
int run =1;
ui.updateBoard(SpielFeld);
while (run)
{
Reihe = 5;
colNow = ui.askPlayer(ui.Color::RED);
while (SpielFeld[Reihe][colNow].isEmpty() == false)
{
Reihe--;
if(Reihe < 0)
{
// std::cout << "Fail - Spalte ist voll. Andere Spalte w�hlen";
colNow = ui.askPlayer(ui.Color::RED);
Reihe = 5;
}
}
SpielFeld[Reihe][colNow] = (ui.Color::RED); /// col in int?
ui.updateBoard(SpielFeld);
run = (Gewonnen(SpielFeld) == 0) && !Unentschieden(SpielFeld);
if (run)
{
Reihe = 5;
colNow = ui.askPlayer(ui.Color::YELLOW);
while (SpielFeld[Reihe][colNow].isEmpty() == false)
{
Reihe--;
if(Reihe < 0)
{
// std::cout << "Fail Spalte voll. Andere Spalte w�hlen";
colNow = ui.askPlayer(ui.Color::YELLOW);
/// if (0 <= colNow <= 7)
Reihe = 5;
}
}
SpielFeld[Reihe][colNow] = (ui.Color::YELLOW); /// col in int?
ui.updateBoard(SpielFeld);
run = (Gewonnen(SpielFeld) == 0) && !Unentschieden(SpielFeld);
}
}
}
| [
"schneidav81@gmail.com"
] | schneidav81@gmail.com |
c6916a57097850e9b31e4e22ff334b97d800a343 | 6a9f099663aca2eea9795df7c5306fb0996ee36a | /OrderServer/MainWindow.cpp | 9bb021ea7b1c3b974094646d5bfe0c0a548ebdd3 | [] | no_license | Galytskyi/iCafe | f741e3adc60601fcfefb7ef455f636507861147f | e259f8a3a2ee00ce4ecb361d1646c556fe770d5d | refs/heads/master | 2020-03-28T20:34:39.839396 | 2018-11-01T07:30:47 | 2018-11-01T07:30:47 | 148,613,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,955 | cpp | #include "MainWindow.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QStatusBar>
#include <QThread>
#include <QMessageBox>
#include "Database.h"
#include "ProviderDialog.h"
#include "../lib/wassert.h"
#include "../lib/Provider.h"
// -------------------------------------------------------------------------------------------------------------------
//
// MainWindow class implementation
//
// -------------------------------------------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// init interface
//
createInterface();
startArchThread();
loadBase();
startRemoveOrderThread();
startConfigUdpThread();
startCustomerOrderUdpThread();
startProviderOrderUdpThread();
}
// -------------------------------------------------------------------------------------------------------------------
MainWindow::~MainWindow()
{
stopConfigUdpThread();
stopCustomerOrderUdpThread();
stopProviderOrderUdpThread();
stopRemoveOrderThread();
stopArchThread();
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::createInterface()
{
setWindowIcon(QIcon(":/icons/Logo.png"));
setWindowTitle(tr("Server of orders"));
setMinimumSize(700, 500);
move(QApplication::desktop()->availableGeometry().center() - rect().center());
createActions();
createMenu();
createToolBars();
createProviderView();
createStatusBar();
createContextMenu();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::createActions()
{
// Providers
//
m_pAppendProviderAction = new QAction(tr("Append ..."), this);
m_pAppendProviderAction->setShortcut(Qt::CTRL + Qt::Key_Insert);
m_pAppendProviderAction->setIcon(QIcon(":/icons/Append.png"));
m_pAppendProviderAction->setToolTip(tr("Append provider"));
connect(m_pAppendProviderAction, &QAction::triggered, this, &MainWindow::onAppendProvider);
m_pEditProviderAction = new QAction(tr("Edit ..."), this);
m_pEditProviderAction->setShortcut(Qt::CTRL + Qt::Key_Enter);
m_pEditProviderAction->setIcon(QIcon(":/icons/Edit.png"));
m_pEditProviderAction->setToolTip(tr("Edit provider data"));
connect(m_pEditProviderAction, &QAction::triggered, this, &MainWindow::onEditProvider);
m_pRemoveProviderAction = new QAction(tr("Remove ..."), this);
m_pRemoveProviderAction->setShortcut(Qt::CTRL + Qt::Key_Delete);
m_pRemoveProviderAction->setIcon(QIcon(":/icons/Remove.png"));
m_pRemoveProviderAction->setToolTip(tr("Remove provider"));
connect(m_pRemoveProviderAction, &QAction::triggered, this, &MainWindow::onRemoveProvider);
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::createMenu()
{
QMenuBar* pMenuBar = menuBar();
if (pMenuBar == nullptr)
{
return;
}
m_pProviderMenu = pMenuBar->addMenu(tr("&Provider"));
m_pProviderMenu->addAction(m_pAppendProviderAction);
m_pProviderMenu->addAction(m_pEditProviderAction);
m_pProviderMenu->addAction(m_pRemoveProviderAction);
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::createToolBars()
{
// Control panel measure process
//
m_pControlToolBar = new QToolBar(this);
if (m_pControlToolBar != nullptr)
{
m_pControlToolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
m_pControlToolBar->setWindowTitle(tr("Control panel"));
m_pControlToolBar->setObjectName(m_pControlToolBar->windowTitle());
addToolBarBreak(Qt::TopToolBarArea);
addToolBar(m_pControlToolBar);
m_pControlToolBar->addAction(m_pAppendProviderAction);
m_pControlToolBar->addAction(m_pEditProviderAction);
m_pControlToolBar->addAction(m_pRemoveProviderAction);
}
return true;
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::createProviderView()
{
m_pView = new ProviderView;
if (m_pView == nullptr)
{
return;
}
// connect(this, &MainWindow::setTextFilter, pView, &ProviderView::setTextFilter, Qt::QueuedConnection);
// connect(&theProviderBase, &Provider::Base::cfgXmlDataLoaded, m_pView, &ProviderView::updateList, Qt::QueuedConnection);
// connect(&theProviderBase, &Provider::Base::cfgXmlDataLoaded,m_pView, &ProviderView::updateOrderList, Qt::QueuedConnection);
connect(m_pView, &QTableView::doubleClicked, this, &MainWindow::onProviderListClick);
setCentralWidget(m_pView);
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::createStatusBar()
{
QStatusBar* pStatusBar = statusBar();
if (pStatusBar == nullptr)
{
return;
}
m_statusEmpty = new QLabel(pStatusBar);
m_statusProviderCount = new QLabel(pStatusBar);
m_statusOrderCount = new QLabel(pStatusBar);
m_statusProviderCount->setText(tr("Provider count: 0"));
m_statusOrderCount->setText(tr("Order count: 0"));
pStatusBar->addWidget(m_statusOrderCount);
pStatusBar->addWidget(m_statusProviderCount);
pStatusBar->addWidget(m_statusEmpty);
pStatusBar->setLayoutDirection(Qt::RightToLeft);
m_statusEmpty->setText(QString());
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::createContextMenu()
{
// create context menu
//
m_pContextMenu = new QMenu(this);
m_pContextMenu->addAction(m_pAppendProviderAction);
m_pContextMenu->addAction(m_pEditProviderAction);
m_pContextMenu->addAction(m_pRemoveProviderAction);
// init context menu
//
if (m_pView == nullptr)
{
return;
}
m_pView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_pView, &QTableView::customContextMenuRequested, this, &MainWindow::onContextMenu);
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::startArchThread()
{
m_pArchThread = new ArchThread;
if (m_pArchThread == nullptr)
{
return false;
}
QThread *pThread = new QThread;
if (pThread == nullptr)
{
delete m_pArchThread;
m_pArchThread = nullptr;
return false;
}
m_pArchThread->moveToThread(pThread);
connect(pThread, &QThread::started, m_pArchThread, &ArchThread::slot_onThreadStarted);
connect(pThread, &QThread::finished, m_pArchThread, &ArchThread::slot_onThreadFinished);
connect(this, &MainWindow::appendMessageToArch, m_pArchThread, &ArchThread::appendMessage, Qt::QueuedConnection);
pThread->start();
emit appendMessageToArch(ARCH_MSG_TYPE_EVENT, __FUNCTION__, QString("App started"));
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::stopArchThread()
{
if (m_pArchThread == nullptr)
{
return false;
}
QThread *pThread = m_pArchThread->thread();
if (pThread == nullptr)
{
return false;
}
pThread->quit();
pThread->wait();
pThread->deleteLater();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::loadBase()
{
if (thePtrDB == nullptr)
{
emit appendMessageToArch(ARCH_MSG_TYPE_ERROR, __FUNCTION__, "thePtrDB == nullptr");
return 0;
}
QVector<Provider::Item> providerList;
QVector<Provider::Type> typeList;
QTime responseTime;
responseTime.start();
// load providers
//
SqlTable* table = thePtrDB->openTable(SQL_TABLE_PROVIDER);
if (table != nullptr)
{
QMutex providerMutex;
providerMutex.lock();
providerList.resize(table->recordCount());
table->read(providerList.data());
providerMutex.unlock();
table->close();
}
// load provider types
//
table = thePtrDB->openTable(SQL_TABLE_PROVIDER_TYPE);
if (table != nullptr)
{
QMutex typeMutex;
typeMutex.lock();
typeList.resize(table->recordCount());
table->read(typeList.data());
typeMutex.unlock();
table->close();
}
int rt = responseTime.elapsed();
theProviderBase.append(providerList);
theProviderTypeBase.append(typeList);
QString msg = QString("ProviderBase::load() - Loaded providers: %1, Loaded provider types: %2, Time for load: %3 ms" ).arg(theProviderBase.count()).arg(theProviderTypeBase.count()).arg(rt);
emit appendMessageToArch(ARCH_MSG_TYPE_EVENT, __FUNCTION__, msg);
if (m_pView != nullptr)
{
m_pView->updateList();
}
m_statusProviderCount->setText(tr("Provider count: %1").arg(theProviderBase.count()));
return theProviderBase.count();
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::saveProviderBase()
{
/*if (thePtrDB == nullptr)
{
return false;
}
SqlTable* table = thePtrDB->openTable(SQL_TABLE_PROVIDER);
if (table == nullptr)
{
return false;
}
if (table->clear() == false)
{
table->close();
return false;
}
int writtenRecordCount = 0;
m_providerMutex.lock();
writtenRecordCount = table->write(m_providerList.data(), m_providerList.count());
m_providerMutex.unlock();
table->close();
if (writtenRecordCount != count())
{
return false;
}
qDebug() << "ProviderBase::save() - Written providers: " << writtenRecordCount;*/
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::startConfigUdpThread()
{
m_pConfigSocket = new ConfigSocket(QHostAddress::Any, PORT_CONFIG_XML_REQUEST);
if (m_pConfigSocket == nullptr)
{
return false;
}
QThread *pThread = new QThread;
if (pThread == nullptr)
{
delete m_pConfigSocket;
m_pConfigSocket = nullptr;
return false;
}
connect(m_pConfigSocket, &ConfigSocket::msgBox, this, &MainWindow::msgBox);
m_pConfigSocket->moveToThread(pThread);
connect(pThread, &QThread::started, m_pConfigSocket, &ConfigSocket::slot_onThreadStarted);
connect(pThread, &QThread::finished, m_pConfigSocket, &ConfigSocket::slot_onThreadFinished);
connect(m_pConfigSocket, &ConfigSocket::appendMessageToArch, m_pArchThread, &ArchThread::appendMessage, Qt::QueuedConnection);
pThread->start();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::stopConfigUdpThread()
{
if (m_pConfigSocket == nullptr)
{
return false;
}
QThread *pThread = m_pConfigSocket->thread();
if (pThread == nullptr)
{
return false;
}
pThread->quit();
pThread->wait();
pThread->deleteLater();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::startCustomerOrderUdpThread()
{
m_pCustomerOrderSocket = new CustomerOrderSocket(QHostAddress::Any, PORT_CUSTOMER_ORDER_REQUEST);
if (m_pCustomerOrderSocket == nullptr)
{
return false;
}
QThread *pThread = new QThread;
if (pThread == nullptr)
{
delete m_pCustomerOrderSocket;
m_pCustomerOrderSocket = nullptr;
return false;
}
connect(m_pCustomerOrderSocket, &CustomerOrderSocket::msgBox, this, &MainWindow::msgBox);
m_pCustomerOrderSocket->moveToThread(pThread);
connect(pThread, &QThread::started, m_pCustomerOrderSocket, &CustomerOrderSocket::slot_onThreadStarted);
connect(pThread, &QThread::finished, m_pCustomerOrderSocket, &CustomerOrderSocket::slot_onThreadFinished);
connect(m_pCustomerOrderSocket, &CustomerOrderSocket::appendMessageToArch, m_pArchThread, &ArchThread::appendMessage, Qt::QueuedConnection);
pThread->start();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::stopCustomerOrderUdpThread()
{
if (m_pCustomerOrderSocket == nullptr)
{
return false;
}
QThread *pThread = m_pCustomerOrderSocket->thread();
if (pThread == nullptr)
{
return false;
}
pThread->quit();
pThread->wait();
pThread->deleteLater();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::startProviderOrderUdpThread()
{
m_pProviderOrderSocket = new ProviderOrderSocket(QHostAddress::Any, PORT_PROVIDER_ORDER_REQUEST);
if (m_pProviderOrderSocket == nullptr)
{
return false;
}
QThread *pThread = new QThread;
if (pThread == nullptr)
{
delete m_pProviderOrderSocket;
m_pProviderOrderSocket = nullptr;
return false;
}
connect(m_pProviderOrderSocket, &ProviderOrderSocket::msgBox, this, &MainWindow::msgBox);
connect(m_pProviderOrderSocket, &ProviderOrderSocket::providerStateChanged, this, &MainWindow::providerStateChanged, Qt::QueuedConnection);
if (m_pRemoveOrderThread != nullptr)
{
connect(m_pProviderOrderSocket, &ProviderOrderSocket::removeFrendlyOrdersByProviderID, m_pRemoveOrderThread, &RemoveOrderThread::removeFrendlyOrdersByProviderID, Qt::QueuedConnection);
connect(m_pProviderOrderSocket, &ProviderOrderSocket::removeFrendlyOrdersByPhone, m_pRemoveOrderThread, &RemoveOrderThread::removeFrendlyOrdersByPhone, Qt::QueuedConnection);
}
m_pProviderOrderSocket->moveToThread(pThread);
connect(pThread, &QThread::started, m_pProviderOrderSocket, &ProviderOrderSocket::slot_onThreadStarted);
connect(pThread, &QThread::finished, m_pProviderOrderSocket, &ProviderOrderSocket::slot_onThreadFinished);
connect(m_pProviderOrderSocket, &ProviderOrderSocket::appendMessageToArch, m_pArchThread, &ArchThread::appendMessage, Qt::QueuedConnection);
pThread->start();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::stopProviderOrderUdpThread()
{
if (m_pProviderOrderSocket == nullptr)
{
return false;
}
QThread *pThread = m_pProviderOrderSocket->thread();
if (pThread == nullptr)
{
return false;
}
pThread->quit();
pThread->wait();
pThread->deleteLater();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::startRemoveOrderThread()
{
m_pRemoveOrderThread = new RemoveOrderThread;
if (m_pRemoveOrderThread == nullptr)
{
return false;
}
QThread *pThread = new QThread;
if (pThread == nullptr)
{
delete m_pRemoveOrderThread;
m_pRemoveOrderThread = nullptr;
return false;
}
m_pRemoveOrderThread->moveToThread(pThread);
connect(pThread, &QThread::started, m_pRemoveOrderThread, &RemoveOrderThread::slot_onThreadStarted);
connect(pThread, &QThread::finished, m_pRemoveOrderThread, &RemoveOrderThread::slot_onThreadFinished);
connect(m_pRemoveOrderThread, &RemoveOrderThread::appendMessageToArch, m_pArchThread, &ArchThread::appendMessage, Qt::QueuedConnection);
pThread->start();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
bool MainWindow::stopRemoveOrderThread()
{
if (m_pRemoveOrderThread == nullptr)
{
return false;
}
QThread *pThread = m_pRemoveOrderThread->thread();
if (pThread == nullptr)
{
return false;
}
pThread->quit();
pThread->wait();
pThread->deleteLater();
return true;
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::onAppendProvider()
{
ProviderDialog dialog;
if (dialog.exec() != QDialog::Accepted)
{
return;
}
Provider::Item provider(dialog.provider());
// append data in database
//
SqlTable* table = thePtrDB->openTable(SQL_TABLE_PROVIDER);
if (table == nullptr)
{
QMessageBox::information(this, tr("Database"), tr("Error of opening table SQL_TABLE_PROVIDER for write") );
return;
}
if (table->write(&provider) != 1)
{
QMessageBox::information(this, tr("Database"), tr("Error append to table") );
return;
}
table->close();
// append data in theProviderBase
//
int index = theProviderBase.append(provider);
if (index == -1)
{
return;
}
// update data in ConfigSocket
//
m_pConfigSocket->createCfgXml();
// append data in View
//
m_pView->table().append(provider);
// statusBar
//
m_statusProviderCount->setText(tr("Provider count: %1").arg(theProviderBase.count()));
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::onEditProvider()
{
if (m_pView == nullptr)
{
return;
}
int index = m_pView->currentIndex().row();
if (index < 0 || index >= m_pView->table().count())
{
return;
}
onProviderListClick(m_pView->currentIndex());
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::onRemoveProvider()
{
if (m_pView == nullptr)
{
return;
}
int index = m_pView->currentIndex().row();
if (index < 0 || index >= m_pView->table().count())
{
return;
}
Provider::Item provider = m_pView->table().at(index);
QMessageBox::StandardButton reply = QMessageBox::question(this, tr("Remove provider"), tr("Do you want to remove provider:\n%1?").arg(provider.name()), QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
{
return;
}
// update data in database
//
SqlTable* table = thePtrDB->openTable(SQL_TABLE_PROVIDER);
if (table == nullptr)
{
QMessageBox::information(this, tr("Database"), tr("Error of opening table SQL_TABLE_PROVIDER for write") );
return;
}
if (table->remove(provider.providerID()) != 1)
{
QMessageBox::information(this, tr("Database"), tr("Error remove from table") );
return;
}
table->close();
// remove in theProviderBase
//
theProviderBase.remove(provider.providerID());
// update data in ConfigSocket
//
m_pConfigSocket->createCfgXml();
// remove in View
//
m_pView->table().remove(index);
// statusBar
//
m_statusProviderCount->setText(tr("Provider count: %1").arg(theProviderBase.count()));
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::onContextMenu(QPoint)
{
if (m_pContextMenu == nullptr)
{
return;
}
m_pContextMenu->exec(QCursor::pos());
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::onProviderListClick(const QModelIndex& index)
{
if (thePtrDB == nullptr)
{
return;
}
if (m_pConfigSocket == nullptr)
{
return;
}
if (m_pView == nullptr)
{
return;
}
int i = index.row();
if (i < 0 || i >= m_pView->table().count())
{
return;
}
Provider::Item provider = m_pView->table().at(i);
ProviderDialog dialog(provider);
if (dialog.exec() != QDialog::Accepted)
{
return;
}
provider = dialog.provider();
// update data in database
//
SqlTable* table = thePtrDB->openTable(SQL_TABLE_PROVIDER);
if (table == nullptr)
{
QMessageBox::information(this, tr("Database"), tr("Error of opening table SQL_TABLE_PROVIDER for write") );
return;
}
if (table->write(&provider, 1, provider.providerID()) != 1)
{
QMessageBox::information(this, tr("Database"), tr("Error update in table") );
return;
}
table->close();
// update data in theProviderBase
//
Provider::Item* pProvider = theProviderBase.providerPtr(provider.providerID());
if (pProvider == nullptr)
{
return;
}
//
//
*pProvider = provider;
// update data in ConfigSocket
//
m_pConfigSocket->createCfgXml();
// update data in View
//
m_pView->table().set(i, provider);
m_pView->table().updateRow(i);
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::msgBox(const QString &title, const QString& text)
{
QMessageBox::information(this, title, text);
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::providerStateChanged(quint32 providerID, quint32 state)
{
if (m_pView == nullptr)
{
return;
}
int index = theProviderBase.providerIndex(providerID);
if (index < 0 || index >= m_pView->table().count())
{
return;
}
Provider::Item provider = m_pView->table().at(index);
provider.setState(state);
// update data in View
//
m_pView->table().set(index, provider);
m_pView->table().updateRow(index);
}
// -------------------------------------------------------------------------------------------------------------------
void MainWindow::closeEvent(QCloseEvent* e)
{
emit appendMessageToArch(ARCH_MSG_TYPE_EVENT, __FUNCTION__, "App finished");
QMainWindow::closeEvent(e);
}
// -------------------------------------------------------------------------------------------------------------------
| [
"Galytskyi@gmail.com"
] | Galytskyi@gmail.com |
5b5d3871b64c049c13b01c4e02d1d889943145c7 | 6043a3f07d7d642949545b8a4297d4ad27a29e8c | /4.cpp | bb00ddf45f6687c92c1c72b3528c0a95169903c0 | [] | no_license | sohana08/week_of_code | e0fa42ffc8c3aec51621f459dcc1ea93abf28e74 | 3a79aa0a54171816996c423d9083461602e275fd | refs/heads/master | 2022-02-24T04:37:48.857167 | 2022-02-05T18:24:43 | 2022-02-05T18:24:43 | 98,986,416 | 0 | 0 | null | 2022-02-05T18:24:44 | 2017-08-01T09:52:52 | C++ | UTF-8 | C++ | false | false | 737 | cpp | #include <bits/stdc++.h>
using namespace std;
class Person{
public:
int age;
Person(int initialAge);
void amIOld();
void yearPasses();
};
Person::Person(int initialAge)
{
if(initialAge>0){
age=initialAge;
}else{
age=0;
cout<<"Age is not valid. Setting age to 0"<<endl;
}
}
void Person::amIOld()
{
if(age<13){
cout<<"You are young"<<endl;
}else if(age>=13 && age<18){
cout<<"You are a teenage"<<endl;
}else
{
cout<<"You are old"<<endl;
}
}
void Person::yearPasses()
{
age=age+1;
}
int main()
{
int age,n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>age;
Person p(age);
p.amIOld();
for(int j=0;j<3;j++)
{
p.yearPasses();
}
p.amIOld();
cout<<'\n';
}
return 0;
} | [
"sonamtenzin24@yahoo.com"
] | sonamtenzin24@yahoo.com |
769673eaff9a33840906aa56c569080ac5612928 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/MixAll/inst/projects/Clustering/include/STK_MixtureLearner.h | ef2a90ae05ecfa80c4897571ca5cbee217d13365 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,593 | h | /*--------------------------------------------------------------------*/
/* Copyright (C) 2004-2016 Serge Iovleff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place,
Suite 330,
Boston, MA 02111-1307
USA
Contact : S..._Dot_I..._At_stkpp_Dot_org (see copyright for ...)
*/
/*
* Project: stkpp::Clustering
* created on: 14 nov. 2013
* Author: iovleff, S..._Dot_I..._At_stkpp_Dot_org (see copyright for ...)
* Originally created by Parmeet Bhatia <b..._DOT_p..._AT_gmail_Dot_com>
**/
/** @file STK_MixtureLearner.h
* @brief In this file we define the class MixtureLearner.
**/
#ifndef STK_MIXTURELEARNER_H
#define STK_MIXTURELEARNER_H
#include <vector>
#include <list>
#include "STK_IMixtureLearner.h"
namespace STK
{
class IMixture;
/** @ingroup Clustering
* Main class for learning mixture models. A composed mixture model on some
* composed space
* \f$ \mathbb{X} = \subset \mathcal{X}^1\times \ldots \times \mathcal{X}^L \f$
* is a density of the form
* \f[
* f(\mathbf{x}|\boldsymbol{\theta})
* = \sum_{k=1}^K p_k \prod_{l=1}^L f^l(\mathbf{x}^l;\boldsymbol{\lambda}^l_k,\boldsymbol{\alpha}^l)
* \quad \mathbf{x} \in \mathbb{X}.
* \f]
* The \f$ p_k > 0\f$ with \f$ \sum_{k=1}^K p_k =1\f$ are the mixing proportions.
* The density \e f is called the component of the model. The parameters
* \f$\boldsymbol{\lambda}^l_k, \, k=1,\ldots K \f$ are the cluster specific parameters
* and the parameters \f$ \boldsymbol{\alpha}^l \f$ are the shared parameters.
*
* The MixtureLearner class is a final class implementing the features requested
* by the interface class IMixtureLearner.
*
* It uses injection dependency in order to create/release mixture and
* get/set parameters of a mixture. The class responsible of the injection is
* derived from an STK::IMixtureManager.
* @sa IMixtureLearner, IMixtureManager
**/
class MixtureLearner: public IMixtureLearner
{
public:
typedef std::vector<IMixture*>::const_iterator ConstMixtIterator;
typedef std::vector<IMixture*>::iterator MixtIterator;
/** Constructor.
* @param nbCluster,nbSample number of clusters and samples.
*/
MixtureLearner( int nbSample, int nbCluster);
/** copy constructor.
* @param composer the composer to copy
*/
MixtureLearner(MixtureLearner const& composer);
/** The registered mixtures will be deleted there.*/
virtual ~MixtureLearner();
/** Create a composer, but reinitialize the mixtures parameters. */
virtual MixtureLearner* create() const;
/** Create a clone of the current model, with mixtures parameters preserved. */
virtual MixtureLearner* clone() const;
/** @return the value of the probability of the i-th sample in the k-th component.
* @param i,k indexes of the sample and of the class
**/
virtual Real lnComponentProbability(int i, int k) const;
/** write the parameters of the model in the stream os. */
virtual void writeParameters(ostream& os) const;
/** initialize randomly the parameters of the components of the model */
virtual void randomInit();
/** Compute the model parameters given the current imputed/simulated
* missing values. This method updates then the lnLikelihood_ of the model.
**/
virtual void paramUpdateStep();
/** @brief Impute the data missing values. */
virtual void imputationStep();
/** @brief Simulation of all the data missing values.
*/
virtual void samplingStep();
/**@brief This step can be used to signal to the mixtures that they must
* store results. This is usually called after a burn-in phase. The composer
* store the current value of the log-Likelihood.
**/
virtual void storeIntermediateResults(int iteration);
/**@brief This step can be used to signal to the mixtures that they must
* release the stored results. This is usually called if the estimation
* process failed.
**/
virtual void releaseIntermediateResults();
/** @brief Utility method allowing to signal to a mixture to set its parameters.
* It will be called once enough intermediate results have been stored. */
virtual void setParametersStep();
/**@brief This step can be used by developer to finalize any thing. It will
* be called only once after we finish running the estimation algorithm.
**/
virtual void finalizeStep();
protected:
/** @brief Create the composer using existing data handler and mixtures.
* This method is essentially used by the create() method and can be
* reused in derived classes.
* @sa MixtureLearnerFixedProp
**/
void createLearner( std::vector<IMixture*> const& v_mixtures_);
private:
/** averaged lnLikelihood values. Will be used by the
* storeIntermediateResults method.
**/
Real meanlnLikelihood_;
};
} /* namespace STK */
#endif /* STK_MIXTURELEARNER_H */
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
7080277cbcdd74cf5a0ea52ad753cd11d2545e6e | b76d04ac7dc38c5ea128eab0123d208405b78292 | /Section_10_Lab/ContactNode.h | 62fe822bbab5dbca59c277f1ed60436b8493c184 | [] | no_license | P-Burk/Programming_Languages | 5eff948eb80b62d0ca4b5dd3c488589a5543d528 | 402fa22031ca08b9c51471aa1ecc450450c59d4f | refs/heads/main | 2023-03-31T15:28:39.075287 | 2021-04-05T05:33:08 | 2021-04-05T05:33:08 | 347,528,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | #ifndef CONTACTNODE_H
#define CONTACTNODE_H
#include <string>
using namespace std;
class ContactNode {
public:
ContactNode(string name, string phoneNum, ContactNode* nextloc = nullptr);
void InsertAfter(ContactNode* nodeLoc);
string GetName(); // accessor
string GetPhoneNumber(); // accessor
ContactNode* GetNext(); // accessor
void PrintContactNode();
private:
string contactName;
string contactPhoneNum;
ContactNode* nextNodePtr;
};
#endif | [
"P-Burk@users.noreply.github.com"
] | P-Burk@users.noreply.github.com |
8481e75f8d13478094a4a955a91cb17fe7bc9d9e | 97794b40862ce56c2d566604b9d4d223767f2518 | /nativecode.cpp | 26b766e2b4961063ddfaf2fb0eb412ab9d8c3680 | [] | no_license | sbwzq8/CSInlineAsm | 9b1361aeb49aab91af881edbd63d9bfdfde7b132 | b874cb945b82ed783551462c461c0a1c0d87b881 | refs/heads/master | 2020-04-14T00:44:36.951029 | 2019-01-04T06:50:30 | 2019-01-04T06:50:30 | 163,541,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,890 | cpp | #include "string.h"
#include "nativecode.h"
#include "stdio.h"
#include <cstdlib>
wchar_t* GetStringFromNative(int size)
{
int cypher[] = { 2366981,13,2455638,7833,1969907,17,833,859,0,278775,188055,254,6297303,19,13,51138,1045748,46158,146,3747,349977,13937091,46807,376388,4632,278775,479,3260788,108792,13,57554,191611,407292,13,1774,4632,17028678,51357,833,5086887,167240,185423,1410635,254,4632,10302704,6297303,19,1031361,2470182,14258,13557614,157,4091537,110,4632,1471289,697881,60609,20500575,32,26161,4632,182710,615190,35,76798,8070075,9496840,32,7227253,157,348445,424,7650687,760,5985040,833,859,4526177,60609,3285425,4632,43518,15994367,76798,730617,7,46250,833,159855,146,749939,19,344753,254,156537,99158,33763146,12472,668518,19,76798,8070075,9496840,32 };
char clen[] = { 5,1,5,3,5,1,2,2,1,5,4,2,5,1,1,4,4,3,2,3,4,5,4,4,3,5,2,5,3,1,4,4,4,1,3,3,5,4,2,5,5,4,4,2,3,5,5,1,4,5,3,5,2,5,3,3,5,4,4,5,1,3,3,4,5,1,4,5,5,1,5,2,5,2,5,2,5,2,2,5,4,5,3,4,5,4,4,2,3,2,5,2,5,1,4,2,4,4,5,3,5,1,4,5,5,1 };
int ccount = 106;
static wchar_t output[1500];
char *cle = clen;
int *cyp = cypher;
wchar_t *outp = output;
_asm {
start:
mov edi, outp
mov esi, cyp
mov ecx, cle
xor eax, eax
loop1 :
cmp eax, ccount
jge endloop1
xor ebx, ebx
loop2 :
cmp bl, byte ptr[ecx + eax]
jge endloop2
mov edx, dword ptr[esi + 4 * eax]
imul edx, 41C64E6Dh
add edx, 3039h
mov dword ptr[esi + 4 * eax], edx
push eax
push ebx
shr edx, 10h
mov eax, edx
xor edx, edx
mov ebx, 8000h
idiv ebx
mov eax, edx
xor edx, edx
mov ebx, 1Ah
idiv ebx
add edx, 41h
mov byte ptr[edi], dl
pop ebx
pop eax
add edi, 1
inc ebx
jmp loop2
endloop2 :
mov byte ptr[edi], 32
add edi, 1
inc eax
jmp loop1
endloop1 :
mov byte ptr[edi], 00
endstart :
}
return outp;
} | [
"sbwzq8@mail.missouri.edu"
] | sbwzq8@mail.missouri.edu |
d49f37975d9adefba06323755ad11e580cb51072 | b3237ad61a6f29c118106bce7b7c90af7f13696d | /4ºYear/2ºSemester/CACM/Code/check_gcd.cpp | a1359925cf2a179969a9309259c142b9b9e7befe | [] | no_license | FranFnGc/UPV_ComputerScience | b30bca3e59c44a9219f8e21a557f67893938410a | 3b439baf17f91e05e4571c4d71073f303d9daa0d | refs/heads/master | 2023-06-20T19:47:37.874669 | 2021-07-24T09:26:17 | 2021-07-24T09:26:17 | 428,739,883 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp |
#include <cstdio>
int gcd(int a, int b, int *x, int *y);
using namespace std;
int main(int argc, char *argv[])
{
int x, y;
int a = 34398, b = 2132;
int g = gcd(a, b, &x, &y);
printf("\n\n");
printf("%d * %d + %d * %d = %d\n", a, x, b, y, g);
return 0;
}
| [
"ragnarokshadows99@gmail.com"
] | ragnarokshadows99@gmail.com |
32797b6eb35c4f1633c175b1dd680f403bc0059b | f7c673d103a0a7261246dbdde75490f8eed918ab | /source/GameCore/trait/DynamicTrait.h | 9c4bd84b170b5f22f10b6b44a974cc6663d679e5 | [] | no_license | phisn/PixelJumper2 | 2c69faf83c09136b81befd7a930c19ea0ab521f6 | 842878cb3e44113cc2753abe889de62921242266 | refs/heads/master | 2022-11-14T04:44:00.690120 | 2020-07-06T09:38:38 | 2020-07-06T09:38:38 | 277,490,158 | 0 | 0 | null | 2020-07-06T09:38:42 | 2020-07-06T08:48:52 | C++ | UTF-8 | C++ | false | false | 395 | h | #pragma once
#include <vector>
namespace Game
{
struct DynamicTrait
{
virtual void processLogic() = 0;
};
class DynamicTraitContainer
{
public:
void pushDynamicTrait(DynamicTrait* const dynamic)
{
dynamics.push_back(dynamic);
}
const std::vector<DynamicTrait*>& getDynamicTrait() const
{
return dynamics;
}
protected:
std::vector<DynamicTrait*> dynamics;
};
}
| [
"phisn@outlook.de"
] | phisn@outlook.de |
b03f2920d111e23029421204f8cf3154007f6b3d | 22c5f8e46811b2fab7cd11efa00c897b8270707b | /Hydrodynamix/Main.cpp | 5f19cc6f2159de8026504e590e4489d8c6db4772 | [
"MIT"
] | permissive | fechbmaster/particleengine | 1efddbaffd59d867867b95cf34765c397f72acde | 742558f331aebabbab76869f12185c03529ade7c | refs/heads/master | 2020-03-18T19:02:33.913408 | 2018-05-28T08:16:06 | 2018-05-28T08:16:06 | 135,130,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,413 | cpp | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Hydrodynamix
*
* 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 "StdAfx.hpp"
#include "MainWindow.hpp"
#include "Computation/CudaHelper.hpp"
#include <QApplication>
#include <QSurfaceFormat>
#if defined(_MSC_VER) && defined(_DEBUG)
#include <crtdbg.h>
#endif
bool applyStyleSheet(const QString& fileName) {
QFile stylesheet(fileName);
if (!stylesheet.open(QFile::ReadOnly)) {
qDebug() << "Unable to load stylesheet file.";
return false;
}
qApp->setStyleSheet(stylesheet.readAll());
return true;
}
int main(int argc, char *argv[]) {
#if defined(_MSC_VER) && defined(_DEBUG)
// Enable memory leak detection in debug mode (Visual Studio only)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
// Check for CUDA memory leaks
atexit([] { Computation::checkForDeviceMemoryLeaks(); });
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setSwapInterval(1);
format.setSamples(4);
format.setVersion(4, 3);
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(format);
QApplication::setDesktopSettingsAware(false);
QApplication app(argc, argv);
applyStyleSheet("hydrodynamix.qss");
MainWindow window;
window.show();
return app.exec();
}
| [
"bernd.fecht1@hs-augsburg.de"
] | bernd.fecht1@hs-augsburg.de |
60700ea0d3770ad1d533f22aa6b7c3bf94dd788f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_patch_hunk_3652.cpp | 879b883ffed44ff37dd7094126b5bc7c34cf145a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | cpp | */
static BOOL stapling_cache_response(server_rec *s, modssl_ctx_t *mctx,
OCSP_RESPONSE *rsp, certinfo *cinf,
BOOL ok, apr_pool_t *pool)
{
SSLModConfigRec *mc = myModConfig(s);
- unsigned char resp_der[MAX_STAPLING_DER];
+ unsigned char resp_der[MAX_STAPLING_DER]; /* includes one-byte flag + response */
unsigned char *p;
- int resp_derlen;
+ int resp_derlen, stored_len;
BOOL rv;
apr_time_t expiry;
- resp_derlen = i2d_OCSP_RESPONSE(rsp, NULL) + 1;
+ resp_derlen = i2d_OCSP_RESPONSE(rsp, NULL);
if (resp_derlen <= 0) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01927)
"OCSP stapling response encode error??");
return FALSE;
}
- if (resp_derlen > sizeof resp_der) {
+ stored_len = resp_derlen + 1; /* response + ok flag */
+ if (stored_len > sizeof resp_der) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01928)
"OCSP stapling response too big (%u bytes)", resp_derlen);
return FALSE;
}
p = resp_der;
| [
"993273596@qq.com"
] | 993273596@qq.com |
a16a9604a1ed0277298170825627f9e834ba4361 | 4afc9826c4f153d465405410851a67ba20c41bc7 | /History Parser/HistoryParser_DLL/PSParadiseLogPlayerFirxtAction.cpp | fba5538307b1e4f6c041b58cd3442b846efb463e | [] | no_license | aliakbarRashidi/2003RTOnlinePokerStats | 3755656b73b830ed8f7d3fb36a28fd2764f1c7a4 | 1132eff688ae4b00269583b6efa84272dbe3d8b4 | refs/heads/master | 2020-05-09T21:08:42.386148 | 2016-09-29T11:49:49 | 2016-09-29T11:49:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | cpp | // PSParadiseLogPlayerFirxtAction.cpp: implementation of the CPSParadiseLogPlayerFirxtAction class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HistoryParser_DLL.h"
#include "PSParadiseLogPlayerFirxtAction.h"
#include "PSParadiseLogPlayerAction.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPSParadiseLogPlayerFirstAction::CPSParadiseLogPlayerFirstAction(CParseFile* cPF)
: CPSParadiseLog(cPF)
{
}
CPSParadiseLogPlayerFirstAction::~CPSParadiseLogPlayerFirstAction()
{
}
CParseState* CPSParadiseLogPlayerFirstAction::ParseI(const CString &strInLine, const CString &strFullLine)
{
CString strUnreadLine = strInLine;
if (strUnreadLine.Left(strlen("** DEALING")) == "** DEALING")
{
throw(new CParsingException(IDS_PARADISE_HAND_JUMBLED));;
}
PPlayerAction cAction;
CString strAction = ReverseGetNextWord(strUnreadLine);
cAction = PPlayerAction(strAction);
if (cAction == PPlayerAction(PPlayerAction::ACTION_NONE))
{
return this;
}
strUnreadLine.TrimLeft(' ');
strUnreadLine.TrimRight(' ');
if (IsNickInNickList(strUnreadLine))
{
if (sm_listNicks.size() < PARADISE_MIN_NUMBER_OF_PLAYERS)
{
throw(new CParsingException(IDS_NOT_ENOUGH_PLAYERS));
}
sm_cInputHand.AddPlayerAction(strUnreadLine, cAction, 0);
return new CPSParadiseLogPlayerAction(m_cParseFile);
}
else
{
if (cAction != PPlayerAction(PPlayerAction::ACTION_POST))
{
sm_listNicks.push_back(strUnreadLine);
}
sm_cInputHand.AddPlayer(0, strUnreadLine, 0);
sm_cInputHand.AddPlayerAction(strUnreadLine, cAction, 0);
return this;
}
}
| [
"piers.shepperson@btinternet.com"
] | piers.shepperson@btinternet.com |
359147ef6d2e945cc6e292fc0608d018defcf0db | 3c761ddfeadde07c39f033b12457fe490df6339f | /br_moneyhub4.0/GetBill/Alipay/stdafx.cpp | 9ab2405af61d510b08e8854d2326c55c2fa4152f | [] | no_license | 3660628/chtmoneyhub | d8fe22cef017d7a12b4c582667b6484af01032d2 | 7861d387a49edfe395379c1450df18cb1b8658f2 | refs/heads/master | 2021-01-02T09:20:08.263263 | 2012-01-11T08:32:20 | 2012-01-11T08:32:20 | 33,034,456 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CMBChinaGetBill.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"robustwell@218c79bb-c378-f353-48b6-e0d4b39d76f1"
] | robustwell@218c79bb-c378-f353-48b6-e0d4b39d76f1 |
de8b1179b5411a0d9fc10818f169153efaf31e04 | a6b2335cadafbb96b193554280cab0d890470841 | /kernel/textio.hpp | f6207496f00eb72c6efc2d402689d4a45e36e55f | [
"BSD-3-Clause"
] | permissive | Meisaka/xivix | e4fe63793cfe7b040c322e678be086f97e8d2448 | 954d835208aa8e605d13a73b298f1c8d77983f2a | refs/heads/main | 2022-01-25T17:23:17.375333 | 2022-01-03T17:59:28 | 2022-01-03T17:59:28 | 31,726,516 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 538 | hpp | /* ***
* textio.hpp - interface for console like devices
* Copyright (c) 2014-2021 Meisaka Yukara
* See LICENSE for full details
* e6af70ca
*/
#ifndef TEXTIO_HAI
#define TEXTIO_HAI
#include "ktypes.hpp"
namespace xiv {
struct TextIO {
virtual void reset() {};
virtual void setto(uint16_t c, uint16_t r) = 0;
virtual uint16_t getrow() const = 0;
virtual uint16_t getcol() const = 0;
virtual void putc(char c) = 0;
virtual void putat(uint16_t c, uint16_t r, char v) = 0;
virtual void nextline() = 0;
};
} // ns xiv
#endif
| [
"Meisaka.Yukara@gmail.com"
] | Meisaka.Yukara@gmail.com |
92704aaf5ca165331254eb917784d3cd4bcd1ce6 | d1b66d3831f524ca0ee32c4719a650651eda1415 | /Map.h | d250092132970700466b366bf82c0f4a2345af44 | [] | no_license | vinitran/FlappyBird | 08f5360ab01e80d9590885212519a8d0b6535273 | 1d304db0a523cf8c2f0dbc4961f574a780795acf | refs/heads/main | 2023-04-19T04:28:48.488959 | 2021-05-04T03:52:14 | 2021-05-04T03:52:14 | 361,970,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | h | #pragma once
#include "Game.hpp"
#include "GameObject.h"
#include "List_coordinates.h"
class Map{
public:
Map();
~Map();
void LoadMap();
void DrawMap();
void Draw_startgame();
void Update();
void Update_startgame();
void Draw_overgame();
double x_pos();
double y_pos();
void Reset_map();
GameObject* Continue;
GameObject* Resume;
private:
GameObject* background1;
GameObject* background2;
GameObject* base1;
GameObject* base2;
GameObject* start_game;
GameObject* Menu_overgame;
GameObject* Ok;
GameObject* Gameover;
GameObject* Menu;
};
| [
"noreply@github.com"
] | noreply@github.com |
cb8fe17006f6bd5dc2d95694be98a525063d2746 | 331775d728efbabd6c26688635c52555393b1c82 | /src/main.h | 9289d42d635f8717ad3ff59a928cc82333527f32 | [
"MIT"
] | permissive | Switzerlanddcoin/switzerlandcoin | 2c378e9ff5ccaafb196475f229bf9277f84ffd18 | 15f90b31577d113f7b294895120d80bd2ea5f780 | refs/heads/master | 2016-09-06T15:44:49.600550 | 2014-06-03T10:47:32 | 2014-06-03T10:47:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,049 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class CAddress;
class CInv;
class CNode;
struct CBlockIndexWorkComparator;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit
/** Obsolete: maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit
/** Default for -blockmaxsize, maximum size for mined blocks **/
static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000;
/** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000;
/** The maximum size for transactions we're willing to relay/mine */
static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** The maximum number of orphan transactions kept in memory */
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
/** The maximum number of entries in an 'inv' protocol message */
static const unsigned int MAX_INV_SZ = 50000;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
/** Dust Soft Limit, allowed with additional fee per output */
static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 LTC
/** Dust Hard Limit, ignored as wallet inputs (mininput default) */
static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 LTC mininput
/** No amount larger than this (in satoshi) is valid */
static const int64 MAX_MONEY = 90000000 * COIN;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
static const int COINBASE_MATURITY = 10;
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Maximum number of script-checking threads allowed */
static const int MAX_SCRIPTCHECK_THREADS = 16;
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern uint256 nBestChainWork;
extern uint256 nBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern bool fImporting;
extern bool fReindex;
extern bool fBenchmark;
extern int nScriptCheckThreads;
extern bool fTxIndex;
extern unsigned int nCoinCacheSize;
// Settings
extern int64 nTransactionFee;
extern int64 nMinimumInputValue;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CCoinsDB;
class CBlockTreeDB;
struct CDiskBlockPos;
class CCoins;
class CTxUndo;
class CCoinsView;
class CCoinsViewCache;
class CScriptCheck;
class CValidationState;
struct CBlockTemplate;
/** Register a wallet to receive updates from core */
void RegisterWallet(CWallet* pwalletIn);
/** Unregister a wallet from core */
void UnregisterWallet(CWallet* pwalletIn);
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
/** Process an incoming block */
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
/** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Open an undo file (rev?????.dat) */
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Import blocks from an external file */
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
/** Initialize a new block tree database + block data on disk */
bool InitBlockIndex();
/** Load the block tree and coins database from disk */
bool LoadBlockIndex();
/** Unload database information */
void UnloadBlockIndex();
/** Verify consistency of the block and coin databases */
bool VerifyDB(int nCheckLevel, int nCheckDepth);
/** Print the loaded block tree */
void PrintBlockTree();
/** Find a block by height in the currently-connected chain */
CBlockIndex* FindBlockByHeight(int nHeight);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom);
/** Send queued protocol messages to be sent to a give node */
bool SendMessages(CNode* pto, bool fSendTrickle);
/** Run an instance of the script checking thread */
void ThreadScriptCheck();
/** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
/** Do mining precalculation */
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
/** Check mined block */
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
/** Get the number of active peers */
int GetNumBlocksOfPeers();
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(std::string strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
/** Find the best known block, and make it the tip of the block chain */
bool ConnectBestBlock(CValidationState &state);
/** Create a new block index entry for a given block hash */
CBlockIndex * InsertBlockIndex(uint256 hash);
/** Verify a signature */
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
/** Abort with a message */
bool AbortNode(const std::string &msg);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
struct CDiskBlockPos
{
int nFile;
unsigned int nPos;
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
)
CDiskBlockPos() {
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return !(a == b);
}
void SetNull() { nFile = -1; nPos = 0; }
bool IsNull() const { return (nFile == -1); }
};
struct CDiskTxPos : public CDiskBlockPos
{
unsigned int nTxOffset; // after header
IMPLEMENT_SERIALIZE(
READWRITE(*(CDiskBlockPos*)this);
READWRITE(VARINT(nTxOffset));
)
CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
}
CDiskTxPos() {
SetNull();
}
void SetNull() {
CDiskBlockPos::SetNull();
nTxOffset = 0;
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
bool IsDust() const;
std::string ToString() const
{
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static int64 nMinTxFee;
static int64 nMinRelayTxFee;
static const int CURRENT_VERSION=1;
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
vin.clear();
vout.clear();
nLockTime = 0;
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard(std::string& strReason) const;
bool IsStandard() const
{
std::string strReason;
return IsStandard(strReason);
}
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
*/
bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
*/
unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
*/
int64 GetValueIn(CCoinsViewCache& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 576 / 250;
}
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
GetHash().ToString().c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
// Check whether all prevouts of this transaction are present in the UTXO set represented by view
bool HaveInputs(CCoinsViewCache &view) const;
// Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
// This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
// instead of being performed inline.
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
std::vector<CScriptCheck> *pvChecks = NULL) const;
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
// Context-independent validity checks
bool CheckTransaction(CValidationState &state) const;
// Try to accept this transaction into the memory pool
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL);
protected:
static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut &txout;
public:
static uint64 CompressAmount(uint64 nAmount);
static uint64 DecompressAmount(uint64 nAmount);
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
IMPLEMENT_SERIALIZE(({
if (!fRead) {
uint64 nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));
} else {
uint64 nVal = 0;
READWRITE(VARINT(nVal));
txout.nValue = DecompressAmount(nVal);
}
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
});)
};
/** Undo information for a CTxIn
*
* Contains the prevout's CTxOut being spent, and if this was the
* last output of the affected transaction, its metadata as well
* (coinbase or not, height, transaction version)
*/
class CTxInUndo
{
public:
CTxOut txout; // the txout data before being spent
bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
unsigned int nHeight; // if the outpoint was the last unspent: its height
int nVersion; // if the outpoint was the last unspent: its version
CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
unsigned int GetSerializeSize(int nType, int nVersion) const {
return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
(nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
if (nHeight > 0)
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
::Unserialize(s, VARINT(nCode), nType, nVersion);
nHeight = nCode / 2;
fCoinBase = nCode & 1;
if (nHeight > 0)
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
}
};
/** Undo information for a CTransaction */
class CTxUndo
{
public:
// undo information for all txins
std::vector<CTxInUndo> vprevout;
IMPLEMENT_SERIALIZE(
READWRITE(vprevout);
)
};
/** Undo information for a CBlock */
class CBlockUndo
{
public:
std::vector<CTxUndo> vtxundo; // for all but the coinbase
IMPLEMENT_SERIALIZE(
READWRITE(vtxundo);
)
bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to read
CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
return true;
}
};
/** pruned version of CTransaction: only retains metadata and unspent transaction outputs
*
* Serialized format:
* - VARINT(nVersion)
* - VARINT(nCode)
* - unspentness bitvector, for vout[2] and further; least significant byte first
* - the non-spent CTxOuts (via CTxOutCompressor)
* - VARINT(nHeight)
*
* The nCode value consists of:
* - bit 1: IsCoinBase()
* - bit 2: vout[0] is not spent
* - bit 4: vout[1] is not spent
* - The higher bits encode N, the number of non-zero bytes in the following bitvector.
* - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
* least one non-spent output).
*
* Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
* <><><--------------------------------------------><---->
* | \ | /
* version code vout[1] height
*
* - version = 1
* - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
* - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
* - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
* * 8358: compact amount representation for 60000000000 (600 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
* - height = 203998
*
*
* Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
* <><><--><--------------------------------------------------><----------------------------------------------><---->
* / \ \ | | /
* version code unspentness vout[4] vout[16] height
*
* - version = 1
* - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
* 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
* - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
* - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
* * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
* - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
* * bbd123: compact amount representation for 110397 (0.001 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
* - height = 120891
*/
class CCoins
{
public:
// whether transaction is a coinbase
bool fCoinBase;
// unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
// at which height this transaction was included in the active block chain
int nHeight;
// version of the CTransaction; accesses to this value should probably check for nHeight as well,
// as new tx version will probably only be introduced at certain heights
int nVersion;
// construct a CCoins from a CTransaction, at a given height
CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
// empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
// remove spent outputs at the end of vout
void Cleanup() {
while (vout.size() > 0 && vout.back().IsNull())
vout.pop_back();
if (vout.empty())
std::vector<CTxOut>().swap(vout);
}
void swap(CCoins &to) {
std::swap(to.fCoinBase, fCoinBase);
to.vout.swap(vout);
std::swap(to.nHeight, nHeight);
std::swap(to.nVersion, nVersion);
}
// equality test
friend bool operator==(const CCoins &a, const CCoins &b) {
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.nVersion == b.nVersion &&
a.vout == b.vout;
}
friend bool operator!=(const CCoins &a, const CCoins &b) {
return !(a == b);
}
// calculate number of bytes for the bitmask, and its number of non-zero bytes
// each bit in the bitmask represents the availability of one output, but the
// availabilities of the first two outputs are encoded separately
void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool IsCoinBase() const {
return fCoinBase;
}
unsigned int GetSerializeSize(int nType, int nVersion) const {
unsigned int nSize = 0;
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
// size of header code
nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
// spentness bitmask
nSize += nMaskSize;
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++)
if (!vout[i].IsNull())
nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
// height
nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
return nSize;
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Serialize(s, VARINT(nCode), nType, nVersion);
// spentness bitmask
for (unsigned int b = 0; b<nMaskSize; b++) {
unsigned char chAvail = 0;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
if (!vout[2+b*8+i].IsNull())
chAvail |= (1 << i);
::Serialize(s, chAvail, nType, nVersion);
}
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++) {
if (!vout[i].IsNull())
::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
}
// coinbase height
::Serialize(s, VARINT(nHeight), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
// version
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Unserialize(s, VARINT(nCode), nType, nVersion);
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = nCode & 2;
vAvail[1] = nCode & 4;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail, nType, nVersion);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
}
// coinbase height
::Unserialize(s, VARINT(nHeight), nType, nVersion);
Cleanup();
}
// mark an outpoint spent, and construct undo information
bool Spend(const COutPoint &out, CTxInUndo &undo) {
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.nVersion = this->nVersion;
}
return true;
}
// mark a vout spent
bool Spend(int nPos) {
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
// check whether a particular output is still available
bool IsAvailable(unsigned int nPos) const {
return (nPos < vout.size() && !vout[nPos].IsNull());
}
// check whether the entire CCoins is spent
// note that only !IsPruned() CCoins can be serialized
bool IsPruned() const {
BOOST_FOREACH(const CTxOut &out, vout)
if (!out.IsNull())
return false;
return true;
}
};
/** Closure representing one script verification
* Note that this stores references to the spending transaction */
class CScriptCheck
{
private:
CScript scriptPubKey;
const CTransaction *ptxTo;
unsigned int nIn;
unsigned int nFlags;
int nHashType;
public:
CScriptCheck() {}
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
bool operator()() const;
void swap(CScriptCheck &check) {
scriptPubKey.swap(check.scriptPubKey);
std::swap(ptxTo, check.ptxTo);
std::swap(nIn, check.nIn);
std::swap(nFlags, check.nFlags);
std::swap(nHashType, check.nHashType);
}
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
};
/** Data structure that represents a partial merkle tree.
*
* It respresents a subset of the txid's of a known block, in a way that
* allows recovery of the list of txid's and the merkle root, in an
* authenticated way.
*
* The encoding works as follows: we traverse the tree in depth-first order,
* storing a bit for each traversed node, signifying whether the node is the
* parent of at least one matched leaf txid (or a matched txid itself). In
* case we are at the leaf level, or this bit is 0, its merkle node hash is
* stored, and its children are not explorer further. Otherwise, no hash is
* stored, but we recurse into both (or the only) child branch. During
* decoding, the same depth-first traversal is performed, consuming bits and
* hashes as they written during encoding.
*
* The serialization is fixed and provides a hard guarantee about the
* encoded size:
*
* SIZE <= 10 + ceil(32.25*N)
*
* Where N represents the number of leaf nodes of the partial tree. N itself
* is bounded by:
*
* N <= total_transactions
* N <= 1 + matched_transactions*tree_height
*
* The serialization format:
* - uint32 total_transactions (4 bytes)
* - varint number of hashes (1-3 bytes)
* - uint256[] hashes in depth-first order (<= 32*N bytes)
* - varint number of bytes of flag bits (1-3 bytes)
* - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
* The size constraints follow from this.
*/
class CPartialMerkleTree
{
protected:
// the total number of transactions in the block
unsigned int nTransactions;
// node-is-parent-of-matched-txid bits
std::vector<bool> vBits;
// txids and internal hashes
std::vector<uint256> vHash;
// flag set when encountering invalid data
bool fBad;
// helper function to efficiently calculate the number of nodes at given height in the merkle tree
unsigned int CalcTreeWidth(int height) {
return (nTransactions+(1 << height)-1) >> height;
}
// calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
// recursive function that traverses tree nodes, storing the data as bits and hashes
void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
// recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
// it returns the hash of the respective node.
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
public:
// serialization implementation
IMPLEMENT_SERIALIZE(
READWRITE(nTransactions);
READWRITE(vHash);
std::vector<unsigned char> vBytes;
if (fRead) {
READWRITE(vBytes);
CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
us.vBits.resize(vBytes.size() * 8);
for (unsigned int p = 0; p < us.vBits.size(); p++)
us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
us.fBad = false;
} else {
vBytes.resize((vBits.size()+7)/8);
for (unsigned int p = 0; p < vBits.size(); p++)
vBytes[p / 8] |= vBits[p] << (p % 8);
READWRITE(vBytes);
}
)
// Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
CPartialMerkleTree();
// extract the matching txid's represented by this partial merkle tree.
// returns the merkle root, or 0 in case of failure
uint256 ExtractMatches(std::vector<uint256> &vMatch);
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int CURRENT_VERSION=2;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockHeader()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
IMPLEMENT_SERIALIZE
(
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
)
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
}
uint256 GetPoWHash() const
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
const uint256 &GetTxHash(unsigned int nIndex) const {
assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
assert(nIndex < vtx.size());
return vMerkleTree[nIndex];
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(CDiskBlockPos &pos)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (!CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
GetHash().ToString().c_str(),
HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(),
GetPoWHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().c_str());
printf("\n");
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
* will be true if no problems were found. Otherwise, the return value will be false in case
* of problems. Note that in any case, coins may be modified. */
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
// Apply the effects of this block (with given index) on the UTXO set represented by coins
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
// Read a block from disk
bool ReadFromDisk(const CBlockIndex* pindex);
// Add this block to the block index, and if necessary, switch the active block chain to this
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
// Context-independent validity checks
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
// Store block on disk
// if dbp is provided, the file is known to already reside on disk
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
};
class CBlockFileInfo
{
public:
unsigned int nBlocks; // number of blocks stored in file
unsigned int nSize; // number of used bytes of block file
unsigned int nUndoSize; // number of used bytes in the undo file
unsigned int nHeightFirst; // lowest height of block in file
unsigned int nHeightLast; // highest height of block in file
uint64 nTimeFirst; // earliest time of block in file
uint64 nTimeLast; // latest time of block in file
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
)
void SetNull() {
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo() {
SetNull();
}
std::string ToString() const {
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
}
// update statistics (does not update nSize)
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
if (nBlocks==0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks==0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightFirst)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
extern CCriticalSection cs_LastBlockFile;
extern CBlockFileInfo infoLastBlockFile;
extern int nLastBlockFile;
enum BlockStatus {
BLOCK_VALID_UNKNOWN = 0,
BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
BLOCK_VALID_MASK = 7,
BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
BLOCK_HAVE_MASK = 24,
BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, // descends from failed block
BLOCK_FAILED_MASK = 96
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
// pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock;
// pointer to the index of the predecessor of this block
CBlockIndex* pprev;
// (memory only) pointer to the index of the *active* successor of this block
CBlockIndex* pnext;
// height of the entry in the chain. The genesis block has height 0
int nHeight;
// Which # file this block is stored in (blk?????.dat)
int nFile;
// Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
// Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
// (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork;
// Number of transactions in this block.
// Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
// (memory only) Number of transactions in the chain up to and including this block
unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
// Verification status of this block. See enum BlockStatus
unsigned int nStatus;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(CBlockHeader& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CDiskBlockPos GetBlockPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
/** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256.
* This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */
return true; // return CheckProofOfWork(GetBlockHash(), nBits);
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nHeight,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
struct CBlockIndexWorkComparator
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
return false; // identical blocks
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Capture information about block/transaction validation */
class CValidationState {
private:
enum mode_state {
MODE_VALID, // everything ok
MODE_INVALID, // network rule violation (DoS value may be set)
MODE_ERROR, // run-time error
} mode;
int nDoS;
bool corruptionPossible;
public:
CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
bool DoS(int level, bool ret = false, bool corruptionIn = false) {
if (mode == MODE_ERROR)
return ret;
nDoS += level;
mode = MODE_INVALID;
corruptionPossible = corruptionIn;
return ret;
}
bool Invalid(bool ret = false) {
return DoS(0, ret);
}
bool Error() {
mode = MODE_ERROR;
return false;
}
bool Abort(const std::string &msg) {
AbortNode(msg);
return Error();
}
bool IsValid() {
return mode == MODE_VALID;
}
bool IsInvalid() {
return mode == MODE_INVALID;
}
bool IsError() {
return mode == MODE_ERROR;
}
bool IsInvalid(int &nDoSOut) {
if (IsInvalid()) {
nDoSOut = nDoS;
return true;
}
return false;
}
bool CorruptionPossible() {
return corruptionPossible;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs);
bool addUnchecked(const uint256& hash, const CTransaction &tx);
bool remove(const CTransaction &tx, bool fRecursive = false);
bool removeConflicts(const CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
void pruneSpent(const uint256& hash, CCoins &coins);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64 nTransactions;
uint64 nTransactionOutputs;
uint64 nSerializedSize;
uint256 hashSerialized;
int64 nTotalAmount;
CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
};
/** Abstract view on the open txout dataset. */
class CCoinsView
{
public:
// Retrieve the CCoins (unspent transaction outputs) for a given txid
virtual bool GetCoins(const uint256 &txid, CCoins &coins);
// Modify the CCoins for a given txid
virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
// Just check whether we have data for a given txid.
// This may (but cannot always) return true for fully spent transactions
virtual bool HaveCoins(const uint256 &txid);
// Retrieve the block index whose state this CCoinsView currently represents
virtual CBlockIndex *GetBestBlock();
// Modify the currently active block index
virtual bool SetBestBlock(CBlockIndex *pindex);
// Do a bulk modification (multiple SetCoins + one SetBestBlock)
virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Calculate statistics about the unspent transaction output set
virtual bool GetStats(CCoinsStats &stats);
// As we use CCoinsViews polymorphically, have a virtual destructor
virtual ~CCoinsView() {}
};
/** CCoinsView backed by another CCoinsView */
class CCoinsViewBacked : public CCoinsView
{
protected:
CCoinsView *base;
public:
CCoinsViewBacked(CCoinsView &viewIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
void SetBackend(CCoinsView &viewIn);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
bool GetStats(CCoinsStats &stats);
};
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
class CCoinsViewCache : public CCoinsViewBacked
{
protected:
CBlockIndex *pindexTip;
std::map<uint256,CCoins> cacheCoins;
public:
CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
// Standard CCoinsView methods
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Return a modifiable reference to a CCoins. Check HaveCoins first.
// Many methods explicitly require a CCoinsViewCache because of this method, to reduce
// copying.
CCoins &GetCoins(const uint256 &txid);
// Push the modifications applied to this cache to its base.
// Failure to call this method before destruction will cause the changes to be forgotten.
bool Flush();
// Calculate the size of the cache (in number of transactions)
unsigned int GetCacheSize();
private:
std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
};
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
CTxMemPool &mempool;
public:
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool HaveCoins(const uint256 &txid);
};
/** Global variable that points to the active CCoinsView (protected by cs_main) */
extern CCoinsViewCache *pcoinsTip;
/** Global variable that points to the active block tree (protected by cs_main) */
extern CBlockTreeDB *pblocktree;
struct CBlockTemplate
{
CBlock block;
std::vector<int64_t> vTxFees;
std::vector<int64_t> vTxSigOps;
};
#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64)
extern unsigned int cpuid_edx;
#endif
/** Used to relay blocks as header + vector<merkle branch>
* to filtered nodes.
*/
class CMerkleBlock
{
public:
// Public only for unit testing
CBlockHeader header;
CPartialMerkleTree txn;
public:
// Public only for unit testing and relay testing
// (not relayed)
std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
// Create from a CBlock, filtering transactions according to filter
// Note that this will call IsRelevantAndUpdate on the filter for each transaction,
// thus the filter will likely be modified.
CMerkleBlock(const CBlock& block, CBloomFilter& filter);
IMPLEMENT_SERIALIZE
(
READWRITE(header);
READWRITE(txn);
)
};
#endif
| [
"neilyobanks@safe-mail.net"
] | neilyobanks@safe-mail.net |
67e850be7a79a3257ae7046e8593da0f93124397 | 0902544dd84d48e689a0bb72d45c4a0d59997a13 | /src/HardDriveInfo/WmiClassObject.cpp | 884e42b98420be502d7ff8bb3af40c9f8d319161 | [
"MIT"
] | permissive | yottaawesome/win32-experiments | 2cb56baecceb935046a6c403ab57926906b0c1e1 | 2fed7e74a148ab55b676cfe97abdf23cce770e82 | refs/heads/master | 2023-07-05T23:54:06.278458 | 2023-06-26T09:23:51 | 2023-06-26T09:23:51 | 232,983,991 | 4 | 1 | MIT | 2020-12-12T21:35:44 | 2020-01-10T06:46:38 | C++ | UTF-8 | C++ | false | false | 6,251 | cpp | #include "Header.hpp"
#include <iostream>
#include <sstream>
//https://docs.microsoft.com/en-us/windows/win32/api/propidlbase/ns-propidlbase-propvariant
WmiClassObject::WmiClassObject(IWbemClassObject* clsObj)
: m_clsObj(clsObj)
{ }
WmiClassObject::~WmiClassObject()
{
if (m_clsObj)
m_clsObj->Release();
}
const short WmiClassObject::Short(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_I2)
throw new std::runtime_error("WMI value is not typed as a VT_I2.");
return vtProp.iVal;
}
const bool WmiClassObject::Bool(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_BOOL)
throw new std::runtime_error("WMI value is not typed as a VT_BOOL.");
return vtProp.iVal;
}
const int WmiClassObject::Int32(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_I4)
throw new std::runtime_error("WMI value is not typed as a VT_I4.");
return vtProp.intVal;
}
const BYTE WmiClassObject::Byte(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_UI1)
throw new std::runtime_error("WMI value is not typed as a VT_I1.");
return vtProp.bVal;
}
const long WmiClassObject::Long(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_I4)
throw new std::runtime_error("WMI value is not typed as a VT_I4.");
return vtProp.lVal;
}
const long long WmiClassObject::Int64(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_I8)
throw new std::runtime_error("WMI value is not typed as a VT_I8.");
return vtProp.llVal;
}
const unsigned short WmiClassObject::UShort(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_UI2)
throw new std::runtime_error("WMI value is not typed as a VT_UI2.");
return vtProp.uiVal;
}
const unsigned int WmiClassObject::UInt32(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_UI4)
throw new std::runtime_error("WMI value is not typed as a VT_UI4.");
return vtProp.uintVal;
}
const unsigned long WmiClassObject::ULong(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_UI4)
throw new std::runtime_error("WMI value is not typed as a VT_UI4.");
return vtProp.ulVal;
}
const unsigned long long WmiClassObject::UInt64(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (vtProp.vt != VT_UI8)
throw new std::runtime_error("WMI value is not typed as a VT_UI8.");
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
return vtProp.ullVal;
}
const std::vector<std::wstring> WmiClassObject::StringVector(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
Util::CheckHr(hr, "Failed ClassObject::Get()");
std::vector<std::wstring> results;
if (vtProp.vt != (VT_ARRAY | VT_BSTR))
throw new std::runtime_error("WMI value is not typed as a BSTR.");
SAFEARRAY* addrArray = vtProp.parray;
// get array bounds
long lowerBound = 0;
long upperBound = 0;
SafeArrayGetLBound(addrArray, 1, &lowerBound);
SafeArrayGetUBound(addrArray, 1, &upperBound);
long elementCount = upperBound - lowerBound + 1;
for (long i = 0; i < elementCount; i++)
{
BSTR addr;
SafeArrayGetElement(vtProp.parray, &i, &addr);
results.push_back(std::wstring(addr, SysStringLen(addr)));
}
return results;
}
const std::wstring WmiClassObject::String(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
Util::CheckHr(hr, "Failed ClassObject::Get()");
if (vtProp.vt != VT_BSTR && vtProp.vt != VT_NULL && vtProp.vt != VT_EMPTY)
throw new std::runtime_error("WMI value is not typed as a BSTR.");
if (vtProp.bstrVal == nullptr)
return L"";
return std::wstring(vtProp.bstrVal, SysStringLen(vtProp.bstrVal));
}
// TODO ugly, find a better way
const uint64_t WmiClassObject::StringAsUInt64(const wchar_t* name) const
{
_variant_t vtProp;
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
Util::CheckHr(hr, "Failed ClassObject::Get()");
if (vtProp.vt != VT_BSTR)
throw new std::runtime_error("WMI value is not typed as a BSTR.");
if (vtProp.bstrVal == nullptr)
return 0;
std::wstring str(vtProp.bstrVal, SysStringLen(vtProp.bstrVal));
uint64_t returnVal;
std::wistringstream ss(str);
ss >> returnVal;
if (ss.fail())
{
std::stringstream ss;
ss
<< "Failed to convert value to UINT64. Value: "
<< Util::ConvertWStringToString(str);
throw std::runtime_error(ss.str());
}
return returnVal;
}
const void* WmiClassObject::ObjectRef(const wchar_t* name) const
{
VARIANT vtProp;
VariantInit(&vtProp);
HRESULT hr = m_clsObj->Get(name, 0, &vtProp, 0, 0);
if (FAILED(hr))
throw new std::runtime_error("Failed ClassObject::Get()");
if (vtProp.vt != VT_BYREF)
throw new std::runtime_error("WMI value is not typed as a BSTR.");
// We don't clean up the variant here, because this is a byref object.
// As such, clearing the variant would release the object prematurely.
// It is up to the client code to release the object, as appropriate.
return vtProp.byref;
}
| [
"etameson@gmail.com"
] | etameson@gmail.com |
cdbd23ec392c1692f2e73e9006c57abf0b94fab2 | 9f9cbb082eac69bac1e7a44c944e40fc2eb7901d | /lesson-02/1-fahrenheit-celsius-macro/main.cpp | e8c80e02032e06455a5cbd05990eb4f7c00a7da1 | [] | no_license | dutow/elte-cpp-examples | af5f666aff9dbb164d4eee6da03a5b1bbdc78074 | 82cd4789a8c192aa2a80e2f24a16b2ca7aafec44 | refs/heads/master | 2021-01-10T12:23:12.311051 | 2016-04-21T17:41:55 | 2016-04-21T17:41:55 | 51,207,144 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 252 | cpp |
#include <iostream>
//#define FAHRENHEIT_TO_CELSIUS(f) 5 * (f - 32) / 9
#define FAHRENHEIT_TO_CELSIUS(f) ((5/9.0) * ( (f) - 32))
int main(int argc, char* argv[])
{
using namespace std;
cout << FAHRENHEIT_TO_CELSIUS(30) << endl;
return 0;
}
| [
"zsolt.parragi@cancellar.hu"
] | zsolt.parragi@cancellar.hu |
672a0a100a95d137e98562e58e9485ae51518515 | c7ad1dd84604e275ebfc5a7e354b23ceb598fca5 | /include/objtools/data_loaders/genbank/impl/reader_id1_base.hpp | 23cd6f2517141c385f2a6332577a47f17eaaf38d | [] | no_license | svn2github/ncbi_tk | fc8cfcb75dfd79840e420162a8ae867826a3d922 | c9580988f9e5f7c770316163adbec8b7a40f89ca | refs/heads/master | 2023-09-03T12:30:52.531638 | 2017-05-15T14:17:27 | 2017-05-15T14:17:27 | 60,197,012 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,565 | hpp | #ifndef READER_ID1_BASE__HPP_INCLUDED
#define READER_ID1_BASE__HPP_INCLUDED
/* $Id$
* ===========================================================================
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description: Base class for ID1 and PubSeqOS readers
*
*/
#include <corelib/ncbiobj.hpp>
#include <objtools/data_loaders/genbank/reader.hpp>
//#define GENBANK_USE_SNP_SATELLITE_15 1
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CTSE_Info;
class CTSE_Chunk_Info;
class CSeq_annot_SNP_Info;
class NCBI_XREADER_EXPORT CId1ReaderBase : public CReader
{
public:
CId1ReaderBase(void);
~CId1ReaderBase(void);
/*
bool LoadSeq_idSeq_ids(CReaderRequestResult& result,
const CSeq_id_Handle& seq_id);
bool LoadSeq_idBlob_ids(CReaderRequestResult& result,
const CSeq_id_Handle& seq_id,
const SAnnotSelector* sel);
*/
bool LoadBlob(CReaderRequestResult& result,
const TBlobId& blob_id);
bool LoadBlobState(CReaderRequestResult& result,
const TBlobId& blob_id);
bool LoadBlobVersion(CReaderRequestResult& result,
const TBlobId& blob_id);
bool LoadChunk(CReaderRequestResult& result,
const TBlobId& blob_id, TChunkId chunk_id);
virtual void GetBlobState(CReaderRequestResult& result,
const CBlob_id& blob_id) = 0;
virtual void GetBlobVersion(CReaderRequestResult& result,
const CBlob_id& blob_id) = 0;
virtual void GetBlob(CReaderRequestResult& result,
const TBlobId& blob_id,
TChunkId chunk_id) = 0;
enum ESat {
eSat_ANNOT_CDD = 10,
eSat_ANNOT = 26,
eSat_TRACE = 28,
eSat_TRACE_ASSM = 29,
eSat_TR_ASSM_CH = 30,
eSat_TRACE_CHGR = 31
};
enum ESubSat {
eSubSat_main = 0,
eSubSat_SNP = 1<<0,
eSubSat_SNP_graph = 1<<2,
eSubSat_CDD = 1<<3,
eSubSat_MGC = 1<<4,
eSubSat_HPRD = 1<<5,
eSubSat_STS = 1<<6,
eSubSat_tRNA = 1<<7,
eSubSat_microRNA = 1<<8,
eSubSat_Exon = 1<<9
};
static bool IsAnnotSat(int sat);
static ESat GetAnnotSat(int subsat);
};
END_SCOPE(objects)
END_NCBI_SCOPE
#endif//READER_ID1_BASE__HPP_INCLUDED
| [
"vasilche@112efe8e-fc92-43c6-89b6-d25c299ce97b"
] | vasilche@112efe8e-fc92-43c6-89b6-d25c299ce97b |
06842fdfdd0afbc6752cc5c5161b72a4d2c7c30c | 955840f10284ad8008c19fbd6053570d6a4aa9c9 | /WebSecurity/hw1-DES/tables.cpp | 4df11430a7d4c967fe472541554725a5c34a76a3 | [] | no_license | MarshallW906/homeworkSYSU | 4bc8bed7186444222d3aac2bd65b841a5b7a2747 | a3e8c202cd3849712a1573d139356cd3fdd24d71 | refs/heads/master | 2018-11-06T04:30:07.615434 | 2018-08-27T09:58:40 | 2018-08-27T09:58:40 | 107,306,482 | 1 | 1 | null | 2018-06-12T02:41:38 | 2017-10-17T18:12:32 | JavaScript | UTF-8 | C++ | false | false | 4,305 | cpp | // 初始置换表
int IP[] = {58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7};
// 结尾置换表
int IP_1[] = {40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25};
/*------------------下面是生成密钥所用表-----------------*/
// 密钥置换表,将64位密钥变成56位
int PC_1[] = {57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4};
// 压缩置换,将56位密钥压缩成48位子密钥
int PC_2[] = {14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32};
// 每轮左移的位数
int shiftBits[] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
/*------------------下面是密码函数 f 所用表-----------------*/
// 扩展置换表,将 32位 扩展至 48位
int E[] = {32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1};
// S盒,每个S盒是4x16的置换表,6位 -> 4位
int S_BOX[8][4][16] = {
{{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}},
{{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}},
{{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}},
{{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}},
{{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}},
{{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}},
{{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}},
{{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}};
// P置换,32位 -> 32位
int P[] = {16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25}; | [
"MarshallW906@users.noreply.github.com"
] | MarshallW906@users.noreply.github.com |
5904ccc5b9a2df8e1a2ba5c9caac9ba34e18d3a4 | 0d430563d908de7cda867380b6fe85e77be11c3d | /RandomPrograms/Cpp programs/CodeChefTrainers.cpp | c863f714bebc5f3b0cf3680fc6612ac41c1a6240 | [] | no_license | hshar89/MyCodes | e2eec3b9a2649fec04e5b391d0ca3d4d9d5ae6dc | e388f005353c9606873b6cafdfce1e92d13273e7 | refs/heads/master | 2022-12-23T00:36:01.951137 | 2020-04-03T13:39:22 | 2020-04-03T13:39:22 | 252,720,397 | 1 | 0 | null | 2022-12-16T00:35:41 | 2020-04-03T12:04:10 | Java | UTF-8 | C++ | false | false | 2,318 | cpp | #include <bits/stdc++.h>
#include <conio.h>
using namespace std;
class Trainer{
public:
int sadnessLevel;
int arrivalDay;
int lectures;
};
class MinHeap{
int capacity;
int heap_size;
Trainer *harr;
public:
MinHeap(int cap){
heap_size=0;
capacity = cap;
harr = new Trainer[cap];
}
void Minheapify(int i);
Trainer extractMin();
int parent(int i){
return (i-1)/2;
}
int left(int i){
return 2*i+1;
}
int right(int i){
return 2*i+2;
}
void insert(Trainer t);
};
void MinHeap::insert(Trainer t){
if(heap_size>=capacity){
return;
}
heap_size++;
int i = heap_size-1;
harr[i] = t;
while(i!=0 && harr[parent(i)].sadnessLevel<harr[i].sadnessLevel){
swap(harr[parent(i)],harr[i]);
i = parent(i);
}
}
Trainer MinHeap::extractMin(){
if(heap_size <=0){
return;
}
Trainer temp = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
Minheapify(0);
return temp;
}
void MinHeap::Minheapify(int i){
int l = left(i);
int r = right(i);
int largest = i;
if(l<heap_size && harr[l].sadnessLevel>harr[i].sadnessLevel){
largest = l;
}
if(r<heap_size && harr[r].sadnessLevel > harr[largest].sadnessLevel){
largest = r;
}
if(largest!=i){
swap(harr[i],harr[largest]);
Minheapify(largest);
}
}
int main() {
// your code goes here
int n = 2;
int d = 3;
Trainer trainers[n];
trainers[0].arrivalDay = 1;
trainers[0].lectures = 2;
trainers[0].sadnessLevel = 300;
trainers[1].arrivalDay = 2;
trainers[1].lectures = 2;
trainers[1].sadnessLevel = 100;
MinHeap minheap(n);
minheap.insert(trainers[0]);
minheap.insert(trainers[1]);
int days[d+1];
memset(days,0,sizeof(days));
long totalSadness = 0;
while(n--){
Trainer temp = minheap.extractMin();
int i =temp.arrivalDay;
int j =temp.lectures+i>=d?d:temp.lectures+i;
int lecturesTaken = 0;
while(i<j){
if(!days[i]){
days[i] = 1;
lecturesTaken++;
}
i++;
}
totalSadness += ((temp.lectures-lecturesTaken)*temp.sadnessLevel);
}
return 0;
} | [
"harshsharma3@deloitte.com"
] | harshsharma3@deloitte.com |
222496c0a6773e765c821d36b1a24c6f15e57a2a | 8bf1aed9ef31254280340940b219a008b9a86f50 | /Finished/AlipayUser2/user.hpp | c6555b7f4bf214745b6fa74189416ff30bbd4889 | [] | no_license | Xianbo-X/Matrix_General_HW | 8f03a16122e27f77846ff4b46ea309171e5542eb | 5406f77b79b6076952fbcf7fdafbc59ad2625b1e | refs/heads/master | 2022-01-12T19:23:25.687742 | 2019-06-21T11:46:46 | 2019-06-21T11:46:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | hpp | #ifndef ALIPAY_USER_H_
#define ALIPAY_USER_H_
namespace Alipay {
class user {
char username[21];
char password[21];
double balance;
public:
user(const char* username, const char* password);
~user();
const char* getUsername() const;
const char* getPassword() const;
const void setUsername(const char* username);
const void setPassword(const char* password);
double getBalance();
bool withdraw(double amount);
bool deposite(double amount);
};
}
#endif // !ALIPAY_USER_H_ | [
"Silas_X@outlook.com"
] | Silas_X@outlook.com |
83d7420abda563730d51370cb70b194b5052bed0 | b3c64bd7b1997afeaa0b847d80e9d8bbbbe4ed7e | /scripts/outland/black_temple/boss_teron_gorefiend.cpp | 85f77ba8f64312a13b8fa3c45668cb24ae954be4 | [] | no_license | Corsol/ScriptDev3 | 3d7f34d6c3689c12d53165b9bfaf4ee8d969e705 | 7700e5ec4f9f79aa4e63e9e6e74c60d84d428602 | refs/heads/master | 2021-01-15T20:33:37.635689 | 2015-07-31T21:34:53 | 2015-07-31T21:34:53 | 40,475,601 | 1 | 0 | null | 2015-08-10T09:55:40 | 2015-08-10T09:55:40 | null | UTF-8 | C++ | false | false | 8,736 | cpp | /**
* ScriptDev3 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
* Copyright (C) 2014-2015 MaNGOS <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/* ScriptData
SDName: Boss_Teron_Gorefiend
SD%Complete: 60
SDComment: Requires Mind Control support for Ghosts.
SDCategory: Black Temple
EndScriptData */
#include "precompiled.h"
#include "black_temple.h"
enum
{
// Speech'n'sound
SAY_INTRO = -1564037,
SAY_AGGRO = -1564038,
SAY_SLAY1 = -1564039,
SAY_SLAY2 = -1564040,
SAY_SPELL1 = -1564041,
SAY_SPELL2 = -1564042,
SAY_SPECIAL1 = -1564043,
SAY_SPECIAL2 = -1564044,
SAY_ENRAGE = -1564045,
SAY_DEATH = -1564046,
// Spells - boss spells
SPELL_INCINERATE = 40239,
SPELL_CRUSHING_SHADOWS = 40243,
SPELL_SHADOW_OF_DEATH = 40251,
SPELL_BERSERK = 45078,
SPELL_SUMMON_DOOM_BLOSSOM = 40188,
SPELL_SUMMON_SKELETON_1 = 40270,
SPELL_SUMMON_SKELETON_2 = 41948,
SPELL_SUMMON_SKELETON_3 = 41949,
SPELL_SUMMON_SKELETON_4 = 41950,
SPELL_SUMMON_SPIRIT = 40266,
SPELL_DESTROY_SPIRIT = 41626, // purpose unk
SPELL_DESTROY_ALL_SPIRITS = 44659, // purpose unk
// Spells - other
// SPELL_ATROPHY = 40327, // Shadowy Constructs use this when they get within melee range of a player
SPELL_SHADOWY_CONSTRUCT = 40326,
// NPC_DOOM_BLOSSOM = 23123, // scripted in eventAI
NPC_SHADOWY_CONSTRUCT = 23111, // scripted in eventAI
// NPC_VENGEFUL_SPIRIT = 23109, // npc controlled by the dead player
};
struct boss_teron_gorefiend : public CreatureScript
{
boss_teron_gorefiend() : CreatureScript("boss_teron_gorefiend") {}
struct boss_teron_gorefiendAI : public ScriptedAI
{
boss_teron_gorefiendAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
m_bIntroDone = false;
}
ScriptedInstance* m_pInstance;
uint32 m_uiIncinerateTimer;
uint32 m_uiSummonDoomBlossomTimer;
uint32 m_uiBerserkTimer;
uint32 m_uiCrushingShadowsTimer;
uint32 m_uiShadowOfDeathTimer;
bool m_bIntroDone;
void Reset() override
{
m_uiIncinerateTimer = urand(20000, 30000);
m_uiSummonDoomBlossomTimer = urand(5000, 10000);
m_uiShadowOfDeathTimer = 10000;
m_uiCrushingShadowsTimer = 22000;
m_uiBerserkTimer = 10 * MINUTE * IN_MILLISECONDS;
}
void JustReachedHome() override
{
if (m_pInstance)
{
m_pInstance->SetData(TYPE_GOREFIEND, FAIL);
}
}
void Aggro(Unit* /*pWho*/) override
{
DoScriptText(SAY_AGGRO, m_creature);
if (m_pInstance)
{
m_pInstance->SetData(TYPE_GOREFIEND, IN_PROGRESS);
}
}
void MoveInLineOfSight(Unit* pWho) override
{
if (!m_bIntroDone && pWho->GetTypeId() == TYPEID_PLAYER && m_creature->IsWithinDistInMap(pWho, 60.0f))
{
DoScriptText(SAY_INTRO, m_creature);
m_bIntroDone = true;
}
ScriptedAI::MoveInLineOfSight(pWho);
}
void KilledUnit(Unit* pVictim) override
{
if (pVictim->GetTypeId() != TYPEID_PLAYER)
{
return;
}
DoScriptText(urand(0, 1) ? SAY_SLAY1 : SAY_SLAY2, m_creature);
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
{
m_pInstance->SetData(TYPE_GOREFIEND, DONE);
}
DoScriptText(SAY_DEATH, m_creature);
}
void JustSummoned(Creature* pSummoned) override
{
if (pSummoned->GetEntry() == NPC_SHADOWY_CONSTRUCT)
{
pSummoned->CastSpell(pSummoned, SPELL_SHADOWY_CONSTRUCT, true);
}
pSummoned->SetInCombatWithZone();
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
if (m_uiSummonDoomBlossomTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_DOOM_BLOSSOM) == CAST_OK)
{
if (urand(0, 1))
{
DoScriptText(urand(0, 1) ? SAY_SPELL1 : SAY_SPELL2, m_creature);
}
m_uiSummonDoomBlossomTimer = 35000;
}
}
else
{
m_uiSummonDoomBlossomTimer -= uiDiff;
}
if (m_uiIncinerateTimer < uiDiff)
{
Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1);
if (DoCastSpellIfCan(pTarget ? pTarget : m_creature->getVictim(), SPELL_INCINERATE) == CAST_OK)
{
m_uiIncinerateTimer = urand(20000, 50000);
}
}
else
{
m_uiIncinerateTimer -= uiDiff;
}
if (m_uiCrushingShadowsTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_CRUSHING_SHADOWS) == CAST_OK)
{
if (urand(0, 1))
{
DoScriptText(urand(0, 1) ? SAY_SPECIAL1 : SAY_SPECIAL2, m_creature);
}
m_uiCrushingShadowsTimer = urand(10000, 26000);
}
}
else
{
m_uiCrushingShadowsTimer -= uiDiff;
}
if (m_uiShadowOfDeathTimer < uiDiff)
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1, SPELL_SHADOW_OF_DEATH, SELECT_FLAG_PLAYER))
{
if (DoCastSpellIfCan(pTarget, SPELL_SHADOW_OF_DEATH) == CAST_OK)
{
DoScriptText(urand(0, 1) ? SAY_SPECIAL1 : SAY_SPECIAL2, m_creature);
m_uiShadowOfDeathTimer = 30000;
}
}
}
else
{
m_uiShadowOfDeathTimer -= uiDiff;
}
if (m_uiBerserkTimer)
{
if (m_uiBerserkTimer <= uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK)
{
DoScriptText(SAY_ENRAGE, m_creature);
m_uiBerserkTimer = 0;
}
}
else
{
m_uiBerserkTimer -= uiDiff;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* pCreature) override
{
return new boss_teron_gorefiendAI(pCreature);
}
};
void AddSC_boss_teron_gorefiend()
{
Script* s;
s = new boss_teron_gorefiend();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "boss_teron_gorefiend";
//pNewScript->GetAI = &GetAI_boss_teron_gorefiend;
//pNewScript->RegisterSelf();
}
| [
"Antz@getMaNGOS.co.uk"
] | Antz@getMaNGOS.co.uk |
b56254f3c4aa5debb3c3c9b475428ac95baf57c6 | ee0af171e0fac50c041560aa8c58150cd80d73ef | /BOJ/Greedy/2437.cpp | dcdae7eac4a29e7d6516b35d66ac91e2ea111281 | [] | no_license | Linter97/Algorithm | fdcc094fd7c327a3721d62bf7714f1029deccb8c | 8e3d72466da715cf0399bc748eb3d3f6fbb892b3 | refs/heads/master | 2021-04-01T07:57:09.273240 | 2020-09-28T06:13:04 | 2020-09-28T06:13:04 | 248,170,460 | 0 | 0 | null | 2020-04-08T05:57:44 | 2020-03-18T07:56:29 | C++ | UTF-8 | C++ | false | false | 526 | cpp | #include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
int sum = 1;
for (int i = 0; i < n; i++) {
if (sum < v[i]) break;
sum += v[i];
}
cout << sum << "\n";
}
| [
"noreply@github.com"
] | noreply@github.com |
c535ae05141d6934d5c9a1dd036f12a8fce28960 | d22553a05278edc6e1ce8fc81fa7a203026c745b | /code/controller/commands/control/help/Help.cpp | 3ec5115845be0150600bfd62d9ea0cb645bd256f | [] | no_license | shoshirizel/DNA-Analyzer-System | a625111a4e83002ca8766700fccadb5ec159abd2 | a6ae07e8a8fdfc5bdae437bdc78c658a9796adc7 | refs/heads/master | 2023-01-06T21:34:45.216146 | 2020-11-05T20:47:05 | 2020-11-05T20:47:05 | 290,235,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | cpp | //
// Created by shoshi on 9/14/20.
//
#include "Help.h"
#include "HelpParams.h"
#include "../../../commands_container.h"
#include "../../../errors/InvalidCommand.h"
std::string Help::action(const IParameters& fatherArgs)
{
const HelpParams& args = dynamic_cast<const HelpParams&>(fatherArgs);
if (args.m_commandName == "")
{
return CommandsContainer::getCommandsList();
}
ICommand* command = CommandsContainer::getCommand(args.m_commandName).first;
return command->help();
}
std::string Help::help()
{
return "help:\n If <command> is not provided, help lists all the available commands.\n"
"If a valid command is provided, it shows a short explanation of it.\n"
"<>: parameters []: optional parameters.\n"
"help [<command>]";
} | [
"sh0534157975@gmail.com"
] | sh0534157975@gmail.com |
cad76f4e73a24cf887c329f1c00645f5e86a5280 | 983786cac7fccdbfde0ecf549f9d43101e6daacb | /Source/TextBox.h | 91c7d490414daa5e1463da772eca8d4ff9f59ac8 | [] | no_license | Saftur/pow | a31ed7a90eb1e061418c2c010179737e10ffd3bf | ff992ccffacf807a44bea61950e99dd70cc3c336 | refs/heads/master | 2018-09-08T14:37:50.956036 | 2018-08-24T01:53:01 | 2018-08-24T01:53:01 | 120,832,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | h | #pragma once
#include <vector>
using std::vector;
#include "Rendertext.h"
#include "Transform.h"
#include "Sprite.h"
class TextBox : public Text {
public:
TextBox();
void Load(rapidjson::Value &obj);
Component *Clone() const;
void Update(float dt);
void Draw(Camera *cam) const;
virtual void EnterEffect();
private:
bool focus;
unsigned charCap;
static vector<char> keys;
static vector<char> keyVals;
static vector<char> keyShiftVals;
};
| [
"arthurabouvier@gmail.com"
] | arthurabouvier@gmail.com |
3ec24c46b3ad4c95d697e5082e83def0c6944934 | 6b40e9cba1dd06cd31a289adff90e9ea622387ac | /Develop/mdk/MAsyncDatabase/MSQLSTMT.h | fb62a933f6cca643ca22d0b1b5fabdc4a8387fbb | [] | no_license | AmesianX/SHZPublicDev | c70a84f9170438256bc9b2a4d397d22c9c0e1fb9 | 0f53e3b94a34cef1bc32a06c80730b0d8afaef7d | refs/heads/master | 2022-02-09T07:34:44.339038 | 2014-06-09T09:20:04 | 2014-06-09T09:20:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | h | #pragma once
#include "MADBLib.h"
#include "sqltypes.h"
namespace mdb
{
class MDatabase;
class MADB_API MSQLSTMT
{
public :
MSQLSTMT();
~MSQLSTMT();
bool Init(MDatabase* pDatabase);
bool Close();
SQLHSTMT GetSTMT();
protected :
SQLHSTMT m_hStmt;
};
} | [
"shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4"
] | shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4 |
74772e55f6b263fef32a6df5f877cbd4104e93fd | fe8cd23da48035816c0c7ec55f22150ab0a1bb75 | /cs1/mod1/lesson1-104-2.cpp | 8db1326a084c066803552d94e2e47c3c7486e3d8 | [] | no_license | scarolac/first-year-menus | b9975a7a75bc460bde8e83cb080b8f4bc89296b4 | e8e313ff1d3e0861ab3d3705446db77f7e6cdc63 | refs/heads/master | 2020-03-27T21:29:36.725710 | 2018-09-03T03:59:21 | 2018-09-03T03:59:21 | 147,148,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,932 | cpp | // Section CSC160 - Computer Science I: C++
// File Name: lesson1-104-2.cpp
// Student: Chris Scarola
// Homework Number: 1
// Description:
/* The Babylonian algorithm to compute the square root of a number n is as
follows:
1. Make a guess at the answer (you can pick n/2 as your initial guess).
2. Compute r = n / guess
3. Set guess = (guess + r) / 2
4. Go back to step 2 for as many iterations as necessary. The more that
steps 2 and 3 are repeated, the closer guess will become to the square
root of n.
Write a program that inputs a double for n and iterates through the
Babylonian algorithm 100 times. For a more challenging version, iterate
until guess is within 1% of the previous guess, and outputs the answer as
a double.
*/
// Last Changed: 8/24/2016
#include "cs1/mod1/cs1mod1.h"
namespace lesson1_104_2
{
using namespace std;
void run()
{
do
{
clear_screen();
cout << "Computing the babylonian estimated sqrt of a number\n\n";
double number;
double guess;
double r;
//get the data and initial guess
cout << "Input a number to take the sqrt of: ";
cin >> number;
guess = number / 2;
//calculate the root
double prev_guess;
double guess_ratio = 1.0; //ratio is stored until it is within 1% of the value
while(guess_ratio > 0.01)
{
if (number == 1) //the sqrt of 1 is 1
{
guess = 1;
break;
}
prev_guess = guess;
//algorithm from the text to calculate the root
r = number / guess;
guess = (guess + r) / 2;
guess_ratio = (prev_guess - guess) / guess;
}
//show the answer
cout << "The estimated sqrt of " << number << " is " << guess << endl;
}while(prompt());
}
}
| [
"scarolac@gmail.com"
] | scarolac@gmail.com |
b9e9dea9acb244c380adf8182427b1edb2279177 | d7795f1c445b585f87fb884f8c91292ab42c6571 | /DataStructure/quickSort.cpp | 3d5a7befc04984e42e8c20507bad2b62e42eee84 | [] | no_license | KevinKingdom/DataS | fda420beb65cb8bece48f32b830aeaa36d63dd1f | d219e9bdbd37e67b71f9b297920268b3554c170b | refs/heads/master | 2021-01-10T20:54:48.106447 | 2015-05-07T10:24:57 | 2015-05-07T10:24:57 | 34,767,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | #include "stdio.h"
void QuickSort(int *a, int low, int high){
int index=a[low];
int i=low;
int j=high;
if(low>=high)
return;
while(i<j){
while(i<j&&a[j]>=index)
j--;
a[i]=a[j];
while(i<j&&a[i]<=index)
i++;
a[j]=a[i];
}
a[i]=index;
QuickSort(a,low,i-1);
QuickSort(a,i+1,high);
}
| [
"zwmthu@163.com"
] | zwmthu@163.com |
c2352eafddb8d88b0411ee39873813beaf03eaf5 | bd96efca2ae3f0dcb75c3db522915f6ad0acc1f7 | /Bc2BsPi/include/PreSelection.h | b0f59d9cfcb17bc3e9a0034e2dcc1236e2760bb8 | [] | no_license | nikita6004/LHCbAnalysis | 6db162658bdb145edc3797bf140e3cab8a60732b | 0839f80b48ed92e4ea2d110d62623404f329f291 | refs/heads/master | 2023-04-08T06:01:59.487354 | 2018-03-13T10:13:08 | 2018-03-13T10:13:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #ifndef Bc2BsPi_PreSelection_h
#define Bc2BsPi_PreSelection_h
#include "Analyser.h"
#include "Variables_PreSel.h"
namespace Bc2BsPi {
class PreSelection : public Analyser {
public:
PreSelection(TString _name, Variables_PreSel *_v);
~PreSelection();
bool AnalyseEvent();
Variables_PreSel *v;
};
}
#endif
| [
"mkenzie@hep.phy.cam.ac.uk"
] | mkenzie@hep.phy.cam.ac.uk |
9c66538fb0707dfb270def31ef66cc925eb81724 | 9647fd27fed29c2614f8d406fa90f19f1b55370c | /simon-touch/messagemodel.h | 3eeb5cab2c18e84ea35a688fc9232d91fade9d12 | [] | no_license | KDE/simon-tools | aa42bdd96dff99a67c0e1a93adaa89afce7f749b | ca668c91b6ac2455b8bdd47f013701eff1ea1fb9 | refs/heads/master | 2021-01-06T20:37:26.029880 | 2019-03-03T01:06:46 | 2019-03-03T01:06:46 | 42,732,489 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | h | /*
* Copyright (C) 2011-2012 Peter Grasch <grasch@simon-listens.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef MESSAGEMODEL_H
#define MESSAGEMODEL_H
#include <QAbstractListModel>
#include "mail.h"
class MessageModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit MessageModel(QObject *parent = 0);
void clear();
void addItems(const QList<Mail*>& items);
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const;
void readMessage(int messageIndex);
~MessageModel();
private slots:
void changed(Mail* m);
private:
QList< Mail* > m_messages;
};
#endif // MESSAGEMODEL_H
| [
"grasch@simon-listens.org"
] | grasch@simon-listens.org |
85e0d3cd94100030e8214951669c588b9125eba2 | e4767371bc76f7d881f022c049d8d5c77f5f9241 | /cyber/common/global_data.cc | b1da4c0b3aea3f82c61e495c422d1fc981f168fb | [] | no_license | Forrest-Z/apollo_cyber | beb2b8bf46b841fe53b38e61a646c5670632d237 | c71b63eb022836e9056112c4f9e95f81d7806435 | refs/heads/master | 2023-08-11T06:08:11.460630 | 2021-10-07T04:23:51 | 2021-10-07T04:23:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,311 | cc | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/common/global_data.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <functional>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
namespace apollo {
namespace cyber {
namespace common {
AtomicHashMap<uint64_t, std::string, 512> GlobalData::node_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::channel_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::service_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::task_id_map_;
namespace {
const std::string& kEmptyString = "";
std::string program_path() {
char path[PATH_MAX];
auto len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len == -1) {
return kEmptyString;
}
path[len] = '\0';
return std::string(path);
}
} // namespace
GlobalData::GlobalData() {
InitHostInfo();
ACHECK(InitConfig());
process_id_ = getpid();
auto prog_path = program_path();
if (!prog_path.empty()) {
process_group_ = GetFileName(prog_path) + "_" + std::to_string(process_id_);
} else {
process_group_ = "cyber_default_" + std::to_string(process_id_);
}
const auto& run_mode_conf = config_.run_mode_conf();
run_mode_ = run_mode_conf.run_mode();
clock_mode_ = run_mode_conf.clock_mode();
}
GlobalData::~GlobalData() {}
int GlobalData::ProcessId() const { return process_id_; }
void GlobalData::SetProcessGroup(const std::string& process_group) {
process_group_ = process_group;
}
const std::string& GlobalData::ProcessGroup() const { return process_group_; }
void GlobalData::SetComponentNums(const int component_nums) {
component_nums_ = component_nums;
}
int GlobalData::ComponentNums() const { return component_nums_; }
void GlobalData::SetSchedName(const std::string& sched_name) {
sched_name_ = sched_name;
}
const std::string& GlobalData::SchedName() const { return sched_name_; }
const std::string& GlobalData::HostIp() const { return host_ip_; }
const std::string& GlobalData::HostName() const { return host_name_; }
void GlobalData::EnableSimulationMode() {
run_mode_ = RunMode::MODE_SIMULATION;
}
void GlobalData::DisableSimulationMode() { run_mode_ = RunMode::MODE_REALITY; }
bool GlobalData::IsRealityMode() const {
return run_mode_ == RunMode::MODE_REALITY;
}
bool GlobalData::IsMockTimeMode() const {
return clock_mode_ == ClockMode::MODE_MOCK;
}
void GlobalData::InitHostInfo() {
char host_name[1024];
gethostname(host_name, sizeof(host_name));
host_name_ = host_name;
host_ip_ = "127.0.0.1";
// if we have exported a non-loopback CYBER_IP, we will use it firstly,
// otherwise, we try to find first non-loopback ipv4 addr.
const char* ip_env = getenv("CYBER_IP");
if (ip_env != nullptr) {
// maybe we need to verify ip_env
std::string ip_env_str(ip_env);
std::string starts = ip_env_str.substr(0, 3);
if (starts != "127") {
host_ip_ = ip_env_str;
AINFO << "host ip: " << host_ip_;
return;
}
}
// ifaddrs* ifaddr = nullptr;
// if (getifaddrs(&ifaddr) != 0) {
// AERROR << "getifaddrs failed, we will use 127.0.0.1 as host ip.";
// return;
// }
// for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
// if (ifa->ifa_addr == nullptr) {
// continue;
// }
// int family = ifa->ifa_addr->sa_family;
// if (family != AF_INET) {
// continue;
// }
// char addr[NI_MAXHOST] = {0};
// if (getnameinfo(ifa->ifa_addr, sizeof(sockaddr_in), addr, NI_MAXHOST, NULL,
// 0, NI_NUMERICHOST) != 0) {
// continue;
// }
// std::string tmp_ip(addr);
// std::string starts = tmp_ip.substr(0, 3);
// if (starts != "127") {
// host_ip_ = tmp_ip;
// break;
// }
// }
// freeifaddrs(ifaddr);
AINFO << "host ip: " << host_ip_;
}
bool GlobalData::InitConfig() {
auto config_path = GetAbsolutePath(WorkRoot(), "conf/cyber.pb.conf");
if (!GetProtoFromFile(config_path, &config_)) {
AERROR << "read cyber default conf failed!";
return false;
}
return true;
}
const CyberConfig& GlobalData::Config() const { return config_; }
uint64_t GlobalData::RegisterNode(const std::string& node_name) {
auto id = Hash(node_name);
while (node_id_map_.Has(id)) {
std::string* name = nullptr;
node_id_map_.Get(id, &name);
if (node_name == *name) {
break;
}
++id;
AWARN << " Node name hash collision: " << node_name << " <=> " << *name;
}
node_id_map_.Set(id, node_name);
return id;
}
std::string GlobalData::GetNodeById(uint64_t id) {
std::string* node_name = nullptr;
if (node_id_map_.Get(id, &node_name)) {
return *node_name;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterChannel(const std::string& channel) {
auto id = Hash(channel);
while (channel_id_map_.Has(id)) {
std::string* name = nullptr;
channel_id_map_.Get(id, &name);
if (channel == *name) {
break;
}
++id;
AWARN << "Channel name hash collision: " << channel << " <=> " << *name;
}
channel_id_map_.Set(id, channel);
return id;
}
std::string GlobalData::GetChannelById(uint64_t id) {
std::string* channel = nullptr;
if (channel_id_map_.Get(id, &channel)) {
return *channel;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterService(const std::string& service) {
auto id = Hash(service);
while (service_id_map_.Has(id)) {
std::string* name = nullptr;
service_id_map_.Get(id, &name);
if (service == *name) {
break;
}
++id;
AWARN << "Service name hash collision: " << service << " <=> " << *name;
}
service_id_map_.Set(id, service);
return id;
}
std::string GlobalData::GetServiceById(uint64_t id) {
std::string* service = nullptr;
if (service_id_map_.Get(id, &service)) {
return *service;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterTaskName(const std::string& task_name) {
auto id = Hash(task_name);
while (task_id_map_.Has(id)) {
std::string* name = nullptr;
task_id_map_.Get(id, &name);
if (task_name == *name) {
break;
}
++id;
AWARN << "Task name hash collision: " << task_name << " <=> " << *name;
}
task_id_map_.Set(id, task_name);
return id;
}
std::string GlobalData::GetTaskNameById(uint64_t id) {
std::string* task_name = nullptr;
if (task_id_map_.Get(id, &task_name)) {
return *task_name;
}
return kEmptyString;
}
} // namespace common
} // namespace cyber
} // namespace apollo
| [
"dingbobby@hotmail.com"
] | dingbobby@hotmail.com |
7f0b828b53700b5856463bf64e2bede821eccd6b | 7cfc4308e576dd00d8914ef7b8419fa876bbfcd6 | /codeforces/1368/D.cpp | a97a2a5574fbc654dc5ab77170dca8173daff59d | [] | no_license | sharad2307/codeforces-submissions | 58cb35f710d422991466c8054041ba45d6b95436 | b3e90a6ab22e406b1982f459d2a1d96dae876069 | refs/heads/master | 2023-02-06T11:17:19.907183 | 2020-04-13T05:46:00 | 2020-12-25T13:24:32 | 324,364,474 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,166 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
typedef unsigned long long ull;
#define loop(i,a,b) for(ll i=a;i<b;i++)
#define f(i,a,b) for(ll i=a;i<=b;i++)
// #define testcases ll t;cin>>t;while(t--)
#define dec(x) greater<x>()
/*** Define fues ***/
#define mx 200005
#define mod 1000000007
#define PI acos(-1.0)
#define eps 1e-7
#define size1 100005
const char nl = '\n';
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define mem(name, fue) memset(name, fue, sizeof(name))
/*** STLs ***/
typedef vector <ll> vll;
typedef set <ll> sll;
typedef multiset <ll> msll;
typedef queue <ll> qll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll , ll> > vpll;
/*** Sorts ***/
#define all(v) (v).begin(), (v).end()
#define rev(v) reverse(all(v))
#define srt(v) sort(all(v))
#define srtGreat(v) sort(all(v), greater<ll>())
inline bool cmp(pll a, pll b) { if (a.ff == b.ff)return a.ss < b.ss; return a.ff > b.ff; }
#define en cout << '\n';
#define no cout << "NO" << '\n'
#define yes cout << "YES" << '\n'
#define case cout << "Case " << t++ << ": "
/*** Functions
ll BigMod(ll base, ll pow, ll modfue){ if (pow == 0) return 1; ll ans = BigMod(base, pow / 2, modfue);ll total = ((ans % modfue) * (ans % modfue)) % modfue; if(pow % 2 == 0) return total; else{ return (total * (base % modfue) ) % modfue; } }
ll InverseMod(ll base, ll pow) { if(pow == 0) return 1; ll ans = InverseMod(base, pow / 2); ans = (ans * ans) % mod; if(pow & 1){ return (ans * base) % mod; } else{ return ans; } }
bool checkprime(ll num) { if(num < 2) return false; for(ll i = 2; i * i <= num; i++){ if(num % i == 0) return false; } return true; }
ll EularPHI(ll num) { double ans = num; for(ll i = 2; i * i <= num; i++){ if(num % i == 0){ while (num % i == 0) { num /= i; } ans *= (1.0 - (1.0 / (double)i)); } } if(num > 1) ans *= (1.0 - (1.0 / (double)num)); return (ll)ans; }
ll sumofdigit(ll n){ll sum=0;while(n){sum=sum+n%10;n=n/10;}return sum;}
ll countDigit(ll n) { if (n == 0) return 0; return 1 + countDigit(n / 10); }
ll countDigit(ll n) { return floor(log10(n) + 1); } //only positive
***/
template <class T> inline T gcd(T a, T b) {if (b == 0)return a; return gcd(b, a % b);}
template <class T> inline T lcm(T a, T b) {return a * b / gcd<T>(a, b);}
template <class T> inline T power(T b, T p) {ll ans = 1; while (p--) ans *= b; return ans;}
void solve()
{
ll n;cin >> n;
ll count_one[21] = {0};
loop(i,0,n)
{
ll x; cin >> x;
ll v = 0;
while (x)
{
if (x & 1)
count_one[v]++;
x = x >> 1;
v++;
}
}
ll ans = 0;
loop(i,0,n)
{
ll f = 0;
loop(v,0,20)
{
if (count_one[v])
{
f = f + (1 << v);
count_one[v]--;
}
}
ans += f * f;
}
cout << ans <<nl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("C:/Users/91731/Documents/input.txt", "r", stdin);
freopen("C:/Users/91731/Documents/output.txt", "w", stdout);
freopen("C:/Users/91731/Documents/error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
ll t=1;
// cin>>t;
while(t--)
{
// cout<<"CASE"<<t<<" ";
solve();
}
}
| [
"manuandmehrotra@gmail.com"
] | manuandmehrotra@gmail.com |
b14b8e3b71c4360ca19032707600199c90928f99 | 05f7573db159e870fb26c847991c4cb8c407ed4c | /VBF/Source/VBF_CORE4.0/VBF_Public/VBF_3DMap/VBF_Driver/model_feature_label/FeatureLabelModelOptions | bd21fd8396c72ce30b1b4a15f1602829fe90cc71 | [] | no_license | riyue625/OneGIS.ModelingTool | e126ef43429ce58d22c65832d96dbd113eacbf85 | daf3dc91584df7ecfed6a51130ecdf6671614ac4 | refs/heads/master | 2020-05-28T12:12:43.543730 | 2018-09-06T07:42:00 | 2018-09-06T07:42:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,885 | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2010 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#ifndef OSGEARTH_DRIVER_FEATURE_LABEL_MODEL_OPTIONS
#define OSGEARTH_DRIVER_FEATURE_LABEL_MODEL_OPTIONS 1
#include <VBF_3DMap/VBF_Terrain/Common.h>
#include <VBF_3DMap/VBF_Features/VBF_SourceModelFeature.h>
namespace osgEarth { namespace Drivers
{
using namespace osgEarth;
using namespace osgEarth::Features;
class FeatureLabelModelOptions : public FeatureModelSourceOptions // NO EXPORT; header only
{
public:
CVBF_Optional<std::string>& url() { return _url; }
const CVBF_Optional<std::string>& url() const { return _url; }
CVBF_Optional<double>& heightOffset() { return _heightOffset; }
const CVBF_Optional<double>& heightOffset() const { return _heightOffset; }
CVBF_Optional<bool>& hideClutter() { return _hideClutter; }
const CVBF_Optional<bool>& hideClutter() const { return _hideClutter; }
public:
FeatureLabelModelOptions( const ConfigOptions& opt =ConfigOptions() ) : FeatureModelSourceOptions( opt ),
_heightOffset( 0.0 )
{
setDriver( "feature_label" );
fromConfig( _conf );
}
public:
Config getConfig() const {
Config conf = FeatureModelSourceOptions::getConfig();
conf.updateIfSet( "url", _url );
conf.updateIfSet( "height_offset", _heightOffset );
conf.updateIfSet( "hide_clutter", _hideClutter );
return conf;
}
protected:
void mergeConfig( const Config& conf ) {
FeatureModelSourceOptions::mergeConfig( conf );
fromConfig( conf );
}
private:
void fromConfig( const Config& conf ) {
conf.getIfSet( "url", _url );
conf.getIfSet( "height_offset", _heightOffset );
conf.getIfSet( "hide_clutter", _hideClutter );
}
CVBF_Optional<std::string> _url;
CVBF_Optional<double> _heightOffset;
CVBF_Optional<bool> _hideClutter;
};
} } // namespace osgEarth::Drivers
#endif // OSGEARTH_DRIVER_FEATURE_GEOM_MODEL_OPTIONS
| [
"robertsam@126.com"
] | robertsam@126.com | |
264234c49e21561df93ea3b76a82b4684fcb819d | 51685ead3a4cf702829c25854d9537626f8de2df | /lab5/main.cpp | 4d7d263fcd1f8a113a23967190c75001c55546d4 | [] | no_license | mrBlufi/labs | 1de3bd75e219641d2598f2710c6437d4b84eecce | ea25d2f6bc674ce2d298e543639cc07d43534d3e | refs/heads/master | 2020-04-01T18:59:35.738000 | 2018-10-17T21:39:49 | 2018-10-17T21:39:49 | 153,526,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
int n, m, t, kol = 0, s = 0;
cout << "Input T" << endl;
cin >> t;
cout << "Input N and M" << endl;
cin >> n;
cin >> m;
int** a = new int*[n];
for (int i = 0; i < n; i++){
a[i] = new int[m];
}
cout << "\nMassiv A" << endl;
for(int i = 0; i < n; i++) {
for (int j = 0; j < m; j++){
cout << " a[ " << i+1 << " ][ " << j+1 << " ] = ";
cin >> *(*(a + i)+j);
if((*(a+i))[j]>t){
s += i[a][j];
kol++;
}
}
}
cout << "\n summ: " << s << endl << "kol: " << kol << endl;
for (int i = 0; i < n; i++){
delete(a[i]);
}
delete[](a);
return 0;
}
| [
"k3023310@gmail.com"
] | k3023310@gmail.com |
659d7a0cbae33ee494a0a6418cb74e0c0cba2471 | aafac944e282d1835c8c1d84ebc18a71ceb47d45 | /src/d3d11/d3d11_context_ext.cpp | b5a933b3bacb80c19b2cb7ee107fd55db67da21c | [
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ValveSoftware/dxvk | 8a215f938f28ef31c77ad5b19dbd5b87c0b58c37 | 3f91cdbc126abde7b2334e739d08de0ef2edd1d2 | refs/heads/proton_5.13 | 2023-08-22T20:03:33.531682 | 2021-02-06T07:48:52 | 2021-02-09T13:02:25 | 144,907,892 | 351 | 46 | Zlib | 2021-02-17T15:41:42 | 2018-08-15T22:04:04 | C++ | UTF-8 | C++ | false | false | 4,341 | cpp | #include "d3d11_context.h"
namespace dxvk {
D3D11DeviceContextExt::D3D11DeviceContextExt(
D3D11DeviceContext* pContext)
: m_ctx(pContext) {
}
ULONG STDMETHODCALLTYPE D3D11DeviceContextExt::AddRef() {
return m_ctx->AddRef();
}
ULONG STDMETHODCALLTYPE D3D11DeviceContextExt::Release() {
return m_ctx->Release();
}
HRESULT STDMETHODCALLTYPE D3D11DeviceContextExt::QueryInterface(
REFIID riid,
void** ppvObject) {
return m_ctx->QueryInterface(riid, ppvObject);
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::MultiDrawIndirect(
UINT DrawCount,
ID3D11Buffer* pBufferForArgs,
UINT ByteOffsetForArgs,
UINT ByteStrideForArgs) {
D3D10DeviceLock lock = m_ctx->LockContext();
m_ctx->SetDrawBuffers(pBufferForArgs, nullptr);
m_ctx->EmitCs([
cCount = DrawCount,
cOffset = ByteOffsetForArgs,
cStride = ByteStrideForArgs
] (DxvkContext* ctx) {
ctx->drawIndirect(cOffset, cCount, cStride);
});
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::MultiDrawIndexedIndirect(
UINT DrawCount,
ID3D11Buffer* pBufferForArgs,
UINT ByteOffsetForArgs,
UINT ByteStrideForArgs) {
D3D10DeviceLock lock = m_ctx->LockContext();
m_ctx->SetDrawBuffers(pBufferForArgs, nullptr);
m_ctx->EmitCs([
cCount = DrawCount,
cOffset = ByteOffsetForArgs,
cStride = ByteStrideForArgs
] (DxvkContext* ctx) {
ctx->drawIndexedIndirect(cOffset, cCount, cStride);
});
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::MultiDrawIndirectCount(
UINT MaxDrawCount,
ID3D11Buffer* pBufferForCount,
UINT ByteOffsetForCount,
ID3D11Buffer* pBufferForArgs,
UINT ByteOffsetForArgs,
UINT ByteStrideForArgs) {
D3D10DeviceLock lock = m_ctx->LockContext();
m_ctx->SetDrawBuffers(pBufferForArgs, pBufferForCount);
m_ctx->EmitCs([
cMaxCount = MaxDrawCount,
cArgOffset = ByteOffsetForArgs,
cCntOffset = ByteOffsetForCount,
cStride = ByteStrideForArgs
] (DxvkContext* ctx) {
ctx->drawIndirectCount(cArgOffset, cCntOffset, cMaxCount, cStride);
});
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::MultiDrawIndexedIndirectCount(
UINT MaxDrawCount,
ID3D11Buffer* pBufferForCount,
UINT ByteOffsetForCount,
ID3D11Buffer* pBufferForArgs,
UINT ByteOffsetForArgs,
UINT ByteStrideForArgs) {
D3D10DeviceLock lock = m_ctx->LockContext();
m_ctx->SetDrawBuffers(pBufferForArgs, pBufferForCount);
m_ctx->EmitCs([
cMaxCount = MaxDrawCount,
cArgOffset = ByteOffsetForArgs,
cCntOffset = ByteOffsetForCount,
cStride = ByteStrideForArgs
] (DxvkContext* ctx) {
ctx->drawIndexedIndirectCount(cArgOffset, cCntOffset, cMaxCount, cStride);
});
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::SetDepthBoundsTest(
BOOL Enable,
FLOAT MinDepthBounds,
FLOAT MaxDepthBounds) {
D3D10DeviceLock lock = m_ctx->LockContext();
DxvkDepthBounds db;
db.enableDepthBounds = Enable;
db.minDepthBounds = MinDepthBounds;
db.maxDepthBounds = MaxDepthBounds;
m_ctx->EmitCs([cDepthBounds = db] (DxvkContext* ctx) {
ctx->setDepthBounds(cDepthBounds);
});
}
void STDMETHODCALLTYPE D3D11DeviceContextExt::SetBarrierControl(
UINT ControlFlags) {
D3D10DeviceLock lock = m_ctx->LockContext();
DxvkBarrierControlFlags flags;
if (ControlFlags & D3D11_VK_BARRIER_CONTROL_IGNORE_WRITE_AFTER_WRITE)
flags.set(DxvkBarrierControl::IgnoreWriteAfterWrite);
m_ctx->EmitCs([cFlags = flags] (DxvkContext* ctx) {
ctx->setBarrierControl(cFlags);
});
}
}
| [
"philip.rebohle@tu-dortmund.de"
] | philip.rebohle@tu-dortmund.de |
61d09196baa4408fc9e2949ac3a79e8cecbe8b80 | be026334d457b1f78050f8262cd693922c6c8579 | /onnxruntime/core/mlas/lib/transpose.cpp | 37181ec2f3acd181fc2e27bbfc4d84ea6985bc04 | [
"MIT"
] | permissive | ConnectionMaster/onnxruntime | 953c34c6599c9426043a8e5cd2dba05424084e3b | bac9c0eb50ed5f0361f00707dd6434061ef6fcfe | refs/heads/master | 2023-04-05T00:01:50.750871 | 2022-03-16T15:49:42 | 2022-03-16T15:49:42 | 183,019,796 | 1 | 0 | MIT | 2023-04-04T02:03:14 | 2019-04-23T13:21:11 | C++ | UTF-8 | C++ | false | false | 11,175 | cpp | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
Module Name:
transpose.cpp
Abstract:
This module implements the transpose operation.
--*/
#include "mlasi.h"
#if defined(MLAS_SSE2_INTRINSICS)
MLAS_FORCEINLINE
void
MlasTranspose4x4Block(
const uint32_t* Input,
size_t InputStride,
uint32_t* Output,
size_t OutputStride
)
{
__m128i a0 = _mm_loadu_si128((const __m128i*)&Input[InputStride * 0]);
__m128i a1 = _mm_loadu_si128((const __m128i*)&Input[InputStride * 1]);
__m128i a2 = _mm_loadu_si128((const __m128i*)&Input[InputStride * 2]);
__m128i a3 = _mm_loadu_si128((const __m128i*)&Input[InputStride * 3]);
__m128i b0 = _mm_unpacklo_epi32(a0, a2);
__m128i b1 = _mm_unpackhi_epi32(a0, a2);
__m128i b2 = _mm_unpacklo_epi32(a1, a3);
__m128i b3 = _mm_unpackhi_epi32(a1, a3);
__m128i c0 = _mm_unpacklo_epi32(b0, b2);
__m128i c1 = _mm_unpackhi_epi32(b0, b2);
__m128i c2 = _mm_unpacklo_epi32(b1, b3);
__m128i c3 = _mm_unpackhi_epi32(b1, b3);
_mm_storeu_si128((__m128i*)&Output[OutputStride * 0], c0);
_mm_storeu_si128((__m128i*)&Output[OutputStride * 1], c1);
_mm_storeu_si128((__m128i*)&Output[OutputStride * 2], c2);
_mm_storeu_si128((__m128i*)&Output[OutputStride * 3], c3);
}
MLAS_FORCEINLINE
void
MlasTranspose8x8Block(
const uint8_t* Input,
size_t InputStride,
uint8_t* Output,
size_t OutputStride
)
{
__m128i a0 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 0]);
__m128i a1 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 1]);
__m128i b0 = _mm_unpacklo_epi8(a0, a1);
__m128i a2 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 2]);
__m128i a3 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 3]);
__m128i b1 = _mm_unpacklo_epi8(a2, a3);
__m128i a4 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 4]);
__m128i a5 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 5]);
__m128i b2 = _mm_unpacklo_epi8(a4, a5);
__m128i a6 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 6]);
__m128i a7 = _mm_loadl_epi64((const __m128i*)&Input[InputStride * 7]);
__m128i b3 = _mm_unpacklo_epi8(a6, a7);
__m128i c0 = _mm_unpacklo_epi16(b0, b1);
__m128i c1 = _mm_unpackhi_epi16(b0, b1);
__m128i c2 = _mm_unpacklo_epi16(b2, b3);
__m128i c3 = _mm_unpackhi_epi16(b2, b3);
__m128 d0 = _mm_castsi128_ps(_mm_unpacklo_epi32(c0, c2));
_mm_storel_pi((__m64*)&Output[OutputStride * 0], d0);
_mm_storeh_pi((__m64*)&Output[OutputStride * 1], d0);
__m128 d1 = _mm_castsi128_ps(_mm_unpackhi_epi32(c0, c2));
_mm_storel_pi((__m64*)&Output[OutputStride * 2], d1);
_mm_storeh_pi((__m64*)&Output[OutputStride * 3], d1);
__m128 d2 = _mm_castsi128_ps(_mm_unpacklo_epi32(c1, c3));
_mm_storel_pi((__m64*)&Output[OutputStride * 4], d2);
_mm_storeh_pi((__m64*)&Output[OutputStride * 5], d2);
__m128 d3 = _mm_castsi128_ps(_mm_unpackhi_epi32(c1, c3));
_mm_storel_pi((__m64*)&Output[OutputStride * 6], d3);
_mm_storeh_pi((__m64*)&Output[OutputStride * 7], d3);
}
#elif defined(MLAS_NEON_INTRINSICS)
MLAS_FORCEINLINE
void
MlasTranspose4x4Block(
const uint32_t* Input,
size_t InputStride,
uint32_t* Output,
size_t OutputStride
)
{
uint32x4_t a0 = vld1q_u32(&Input[InputStride * 0]);
uint32x4_t a1 = vld1q_u32(&Input[InputStride * 1]);
uint32x4_t a2 = vld1q_u32(&Input[InputStride * 2]);
uint32x4_t a3 = vld1q_u32(&Input[InputStride * 3]);
uint32x4x2_t b0 = vzipq_u32(a0, a2);
uint32x4x2_t b1 = vzipq_u32(a1, a3);
uint32x4x2_t c0 = vzipq_u32(b0.val[0], b1.val[0]);
uint32x4x2_t c1 = vzipq_u32(b0.val[1], b1.val[1]);
vst1q_u32(&Output[OutputStride * 0], c0.val[0]);
vst1q_u32(&Output[OutputStride * 1], c0.val[1]);
vst1q_u32(&Output[OutputStride * 2], c1.val[0]);
vst1q_u32(&Output[OutputStride * 3], c1.val[1]);
}
MLAS_FORCEINLINE
void
MlasTranspose8x8Block(
const uint8_t* Input,
size_t InputStride,
uint8_t* Output,
size_t OutputStride
)
{
uint8x8_t a0 = vld1_u8(&Input[InputStride * 0]);
uint8x8_t a1 = vld1_u8(&Input[InputStride * 1]);
uint8x8x2_t b0 = vzip_u8(a0, a1);
uint8x8_t a2 = vld1_u8(&Input[InputStride * 2]);
uint8x8_t a3 = vld1_u8(&Input[InputStride * 3]);
uint8x8x2_t b1 = vzip_u8(a2, a3);
uint8x8_t a4 = vld1_u8(&Input[InputStride * 4]);
uint8x8_t a5 = vld1_u8(&Input[InputStride * 5]);
uint8x8x2_t b2 = vzip_u8(a4, a5);
uint8x8_t a6 = vld1_u8(&Input[InputStride * 6]);
uint8x8_t a7 = vld1_u8(&Input[InputStride * 7]);
uint8x8x2_t b3 = vzip_u8(a6, a7);
uint16x4x2_t c0 = vzip_u16(vreinterpret_u16_u8(b0.val[0]), vreinterpret_u16_u8(b1.val[0]));
uint16x4x2_t c1 = vzip_u16(vreinterpret_u16_u8(b0.val[1]), vreinterpret_u16_u8(b1.val[1]));
uint16x4x2_t c2 = vzip_u16(vreinterpret_u16_u8(b2.val[0]), vreinterpret_u16_u8(b3.val[0]));
uint16x4x2_t c3 = vzip_u16(vreinterpret_u16_u8(b2.val[1]), vreinterpret_u16_u8(b3.val[1]));
uint32x2x2_t d0 = vzip_u32(vreinterpret_u32_u16(c0.val[0]), vreinterpret_u32_u16(c2.val[0]));
uint32x2x2_t d1 = vzip_u32(vreinterpret_u32_u16(c0.val[1]), vreinterpret_u32_u16(c2.val[1]));
uint32x2x2_t d2 = vzip_u32(vreinterpret_u32_u16(c1.val[0]), vreinterpret_u32_u16(c3.val[0]));
uint32x2x2_t d3 = vzip_u32(vreinterpret_u32_u16(c1.val[1]), vreinterpret_u32_u16(c3.val[1]));
vst1_u8(&Output[OutputStride * 0], vreinterpret_u8_u32(d0.val[0]));
vst1_u8(&Output[OutputStride * 1], vreinterpret_u8_u32(d0.val[1]));
vst1_u8(&Output[OutputStride * 2], vreinterpret_u8_u32(d1.val[0]));
vst1_u8(&Output[OutputStride * 3], vreinterpret_u8_u32(d1.val[1]));
vst1_u8(&Output[OutputStride * 4], vreinterpret_u8_u32(d2.val[0]));
vst1_u8(&Output[OutputStride * 5], vreinterpret_u8_u32(d2.val[1]));
vst1_u8(&Output[OutputStride * 6], vreinterpret_u8_u32(d3.val[0]));
vst1_u8(&Output[OutputStride * 7], vreinterpret_u8_u32(d3.val[1]));
}
#endif
template<typename ElementType>
MLAS_FORCEINLINE
void
MlasTranspose4xNVector(
const ElementType* Input,
size_t InputStride,
ElementType* Output,
size_t OutputStride
)
{
ElementType a0 = Input[InputStride * 0];
ElementType a1 = Input[InputStride * 1];
ElementType a2 = Input[InputStride * 2];
ElementType a3 = Input[InputStride * 3];
Output[OutputStride * 0] = a0;
Output[OutputStride * 1] = a1;
Output[OutputStride * 2] = a2;
Output[OutputStride * 3] = a3;
}
template<typename ElementType>
MLAS_FORCEINLINE
void
MlasTranspose8xNVector(
const ElementType* Input,
size_t InputStride,
ElementType* Output,
size_t OutputStride
)
{
MlasTranspose4xNVector(&Input[InputStride * 0], InputStride, &Output[OutputStride * 0], OutputStride);
MlasTranspose4xNVector(&Input[InputStride * 4], InputStride, &Output[OutputStride * 4], OutputStride);
}
void
MLASCALL
MlasTranspose(
const uint32_t* Input,
uint32_t* Output,
size_t M,
size_t N
)
/*++
Routine Description:
This routine transposes the input matrix (M rows by N columns) to the
output matrix (N rows by M columns).
Arguments:
Input - Supplies the input buffer.
Output - Supplies the output buffer.
M - Supplies the number of rows for the input matrix and the number of
columns for the output matrix.
N - Supplies the number of columns for the input matrix and the number of
rows for the output matrix.
Return Value:
None.
--*/
{
size_t n = N;
//
// Transpose elements from the input matrix to the output matrix 4 columns
// at a time.
//
while (n >= 4) {
const uint32_t* s = Input;
uint32_t* d = Output;
size_t m = M;
#if defined(MLAS_SSE2_INTRINSICS) || defined(MLAS_NEON_INTRINSICS)
while (m >= 4) {
MlasTranspose4x4Block(s, N, d, M);
s += N * 4;
d += 4;
m -= 4;
}
#endif
while (m > 0) {
MlasTranspose4xNVector(s, 1, d, M);
s += N;
d += 1;
m -= 1;
}
Input += 4;
Output += M * 4;
n -= 4;
}
//
// Transpose elements from the input matrix to the output matrix for the
// remaining columns.
//
while (n > 0) {
const uint32_t* s = Input;
uint32_t* d = Output;
size_t m = M;
while (m >= 4) {
MlasTranspose4xNVector(s, N, d, 1);
s += N * 4;
d += 4;
m -= 4;
}
while (m > 0) {
d[0] = s[0];
s += N;
d += 1;
m -= 1;
}
Input += 1;
Output += M;
n -= 1;
}
}
void
MLASCALL
MlasTranspose(
const float* Input,
float* Output,
size_t M,
size_t N
)
{
MlasTranspose(
reinterpret_cast<const uint32_t*>(Input),
reinterpret_cast<uint32_t*>(Output),
M,
N);
}
void
MLASCALL
MlasTranspose(
const uint8_t* Input,
uint8_t* Output,
size_t M,
size_t N
)
/*++
Routine Description:
This routine transposes the input matrix (M rows by N columns) to the
output matrix (N rows by M columns).
Arguments:
Input - Supplies the input buffer.
Output - Supplies the output buffer.
M - Supplies the number of rows for the input matrix and the number of
columns for the output matrix.
N - Supplies the number of columns for the input matrix and the number of
rows for the output matrix.
Return Value:
None.
--*/
{
size_t n = N;
//
// Transpose elements from the input matrix to the output matrix 8 columns
// at a time.
//
while (n >= 8) {
const uint8_t* s = Input;
uint8_t* d = Output;
size_t m = M;
#if defined(MLAS_SSE2_INTRINSICS) || defined(MLAS_NEON_INTRINSICS)
while (m >= 8) {
MlasTranspose8x8Block(s, N, d, M);
s += N * 8;
d += 8;
m -= 8;
}
#endif
while (m > 0) {
MlasTranspose8xNVector(s, 1, d, M);
s += N;
d += 1;
m -= 1;
}
Input += 8;
Output += M * 8;
n -= 8;
}
//
// Transpose elements from the input matrix to the output matrix for the
// remaining columns.
//
while (n > 0) {
const uint8_t* s = Input;
uint8_t* d = Output;
size_t m = M;
while (m >= 8) {
MlasTranspose8xNVector(s, N, d, 1);
s += N * 8;
d += 8;
m -= 8;
}
while (m > 0) {
d[0] = s[0];
s += N;
d += 1;
m -= 1;
}
Input += 1;
Output += M;
n -= 1;
}
}
void
MLASCALL
MlasTranspose(
const int8_t* Input,
int8_t* Output,
size_t M,
size_t N)
{
MlasTranspose(
reinterpret_cast<const uint8_t*>(Input),
reinterpret_cast<uint8_t*>(Output),
M,
N);
} | [
"noreply@github.com"
] | noreply@github.com |
3d7b5cadd72ed6c6a943fd930c063ad0deed3c5e | 513b2d732655aaac16abbd0f7635b85b7fa58fb4 | /src/gui.cpp | 2e8216b0f00b223f86beb149abef5d883c28ce73 | [] | no_license | snyh/JJJ | f326b82cd91a699d1aecb211410ab05f7806a497 | 35157b0679f7601c522598809f8906b8f6a2c68d | refs/heads/master | 2016-09-11T06:54:40.728776 | 2012-05-10T01:42:53 | 2012-05-10T01:42:53 | 3,671,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,029 | cpp | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Dec 20 2010)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "gui.h"
///////////////////////////////////////////////////////////////////////////
maindialog::maindialog( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer* bSizer2;
bSizer2 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer4;
bSizer4 = new wxBoxSizer( wxHORIZONTAL );
m_sstaticText1 = new wxStaticText( this, wxID_ANY, wxT("当前文件数:"), wxDefaultPosition, wxDefaultSize, 0 );
m_sstaticText1->Wrap( -1 );
bSizer4->Add( m_sstaticText1, 0, wxALL, 5 );
number = new wxStaticText( this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
number->Wrap( -1 );
bSizer4->Add( number, 0, wxALL, 5 );
m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
m_staticline1->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_APPWORKSPACE ) );
bSizer4->Add( m_staticline1, 1, wxEXPAND | wxALL, 5 );
b_listen = new wxButton( this, wxID_ANY, wxT("开始监听"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer4->Add( b_listen, 0, wxALL, 5 );
b_doc = new wxButton( this, wxID_ANY, wxT("存档文件夹"), wxDefaultPosition, wxDefaultSize, 0 );
b_doc->SetDefault();
bSizer4->Add( b_doc, 0, wxALL, 5 );
dir_doc = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
dir_doc->Wrap( -1 );
bSizer4->Add( dir_doc, 0, wxALL, 5 );
bSizer2->Add( bSizer4, 0, wxEXPAND, 5 );
wxBoxSizer* bSizer3;
bSizer3 = new wxBoxSizer( wxHORIZONTAL );
m_notebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
bSizer3->Add( m_notebook, 1, wxEXPAND | wxALL, 5 );
bSizer2->Add( bSizer3, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer5;
bSizer5 = new wxBoxSizer( wxHORIZONTAL );
b_print = new wxButton( this, wxID_ANY, wxT("总上报表"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer5->Add( b_print, 0, wxALL, 5 );
c_all = new wxCheckBox( this, wxID_ANY, wxT("全选"), wxDefaultPosition, wxDefaultSize, 0 );
c_all->SetValue(true);
bSizer5->Add( c_all, 0, wxALL, 5 );
m_staticline2 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
m_staticline2->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_APPWORKSPACE ) );
bSizer5->Add( m_staticline2, 1, wxEXPAND | wxALL, 5 );
b_table1 = new wxButton( this, wxID_ANY, wxT("统计表"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer5->Add( b_table1, 0, wxALL, 5 );
bSizer2->Add( bSizer5, 0, wxEXPAND, 5 );
wxBoxSizer* bSizer7;
bSizer7 = new wxBoxSizer( wxHORIZONTAL );
m_staticText4 = new wxStaticText( this, XZ_0, wxT("李店"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText4->Wrap( -1 );
m_staticText4->SetForegroundColour( wxColour( 85, 152, 215 ) );
bSizer7->Add( m_staticText4, 0, wxALL, 5 );
m_staticText5 = new wxStaticText( this, XZ_1, wxT("府城"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText5->Wrap( -1 );
m_staticText5->SetForegroundColour( wxColour( 222, 165, 165 ) );
bSizer7->Add( m_staticText5, 0, wxALL, 5 );
m_staticText6 = new wxStaticText( this, XZ_2, wxT("南城"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText6->Wrap( -1 );
m_staticText6->SetForegroundColour( wxColour( 255, 118, 118 ) );
bSizer7->Add( m_staticText6, 0, wxALL, 5 );
m_staticText7 = new wxStaticText( this, XZ_3, wxT("赵棚"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText7->Wrap( -1 );
m_staticText7->SetForegroundColour( wxColour( 3, 156, 154 ) );
bSizer7->Add( m_staticText7, 0, wxALL, 5 );
m_staticText8 = new wxStaticText( this, XZ_4, wxT("巡店"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText8->Wrap( -1 );
m_staticText8->SetForegroundColour( wxColour( 24, 201, 49 ) );
bSizer7->Add( m_staticText8, 0, wxALL, 5 );
m_staticText9 = new wxStaticText( this, XZ_5, wxT("棠棣"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText9->Wrap( -1 );
m_staticText9->SetForegroundColour( wxColour( 145, 52, 52 ) );
bSizer7->Add( m_staticText9, 0, wxALL, 5 );
m_staticText10 = new wxStaticText( this, XZ_6, wxT("王义贞"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText10->Wrap( -1 );
m_staticText10->SetForegroundColour( wxColour( 233, 51, 225 ) );
bSizer7->Add( m_staticText10, 0, wxALL, 5 );
m_staticText11 = new wxStaticText( this, XZ_7, wxT("雷公"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText11->Wrap( -1 );
m_staticText11->SetForegroundColour( wxColour( 79, 25, 73 ) );
bSizer7->Add( m_staticText11, 0, wxALL, 5 );
m_staticText12 = new wxStaticText( this, XZ_8, wxT("孛畈"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText12->Wrap( -1 );
m_staticText12->SetForegroundColour( wxColour( 228, 217, 4 ) );
bSizer7->Add( m_staticText12, 0, wxALL, 5 );
m_staticText13 = new wxStaticText( this, XZ_9, wxT("烟店"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText13->Wrap( -1 );
m_staticText13->SetForegroundColour( wxColour( 191, 118, 8 ) );
bSizer7->Add( m_staticText13, 0, wxALL, 5 );
m_staticText14 = new wxStaticText( this, XZ_10, wxT("洑水"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText14->Wrap( -1 );
m_staticText14->SetForegroundColour( wxColour( 2, 4, 115 ) );
bSizer7->Add( m_staticText14, 0, wxALL, 5 );
m_staticText15 = new wxStaticText( this, XZ_11, wxT("陈店"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText15->Wrap( -1 );
m_staticText15->SetForegroundColour( wxColour( 160, 34, 180 ) );
bSizer7->Add( m_staticText15, 0, wxALL, 5 );
m_staticText16 = new wxStaticText( this, XZ_12, wxT("辛榨"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText16->Wrap( -1 );
m_staticText16->SetForegroundColour( wxColour( 28, 112, 4 ) );
bSizer7->Add( m_staticText16, 0, wxALL, 5 );
m_staticText17 = new wxStaticText( this, XZ_13, wxT("木梓"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText17->Wrap( -1 );
m_staticText17->SetForegroundColour( wxColour( 26, 119, 50 ) );
bSizer7->Add( m_staticText17, 0, wxALL, 5 );
m_staticText18 = new wxStaticText( this, XZ_14, wxT("接官"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText18->Wrap( -1 );
m_staticText18->SetForegroundColour( wxColour( 176, 242, 17 ) );
bSizer7->Add( m_staticText18, 0, wxALL, 5 );
m_staticText19 = new wxStaticText( this, XZ_15, wxT("开发区"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText19->Wrap( -1 );
m_staticText19->SetForegroundColour( wxColour( 66, 7, 7 ) );
bSizer7->Add( m_staticText19, 0, wxALL, 5 );
bSizer2->Add( bSizer7, 0, 0, 5 );
this->SetSizer( bSizer2 );
this->Layout();
this->Centre( wxBOTH );
// Connect Events
b_listen->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_listenOnButtonClick ), NULL, this );
b_doc->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_docOnButtonClick ), NULL, this );
m_notebook->Connect( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, wxNotebookEventHandler( maindialog::m_notebookOnNotebookPageChanged ), NULL, this );
b_print->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_printOnButtonClick ), NULL, this );
c_all->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( maindialog::c_allOnCheckBox ), NULL, this );
b_table1->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_table1OnButtonClick ), NULL, this );
m_staticText4->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText5->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText6->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText7->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText8->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText9->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText10->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText11->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText12->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText13->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText14->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText15->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText16->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText17->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText18->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText19->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
}
maindialog::~maindialog()
{
// Disconnect Events
b_listen->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_listenOnButtonClick ), NULL, this );
b_doc->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_docOnButtonClick ), NULL, this );
m_notebook->Disconnect( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, wxNotebookEventHandler( maindialog::m_notebookOnNotebookPageChanged ), NULL, this );
b_print->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_printOnButtonClick ), NULL, this );
c_all->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( maindialog::c_allOnCheckBox ), NULL, this );
b_table1->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( maindialog::b_table1OnButtonClick ), NULL, this );
m_staticText4->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText5->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText6->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText7->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText8->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText9->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText10->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText11->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText12->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText13->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText14->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText15->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText16->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText17->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText18->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
m_staticText19->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( maindialog::m_select_xz ), NULL, this );
}
| [
"snyh@snyh.org"
] | snyh@snyh.org |
fa6ea239e17114ea5939d74ce2f86c99bd89fe30 | 4117c18ded9dbf3a352ca1c578850ff33c046a86 | /encode/src/QCore.cc | eceb2033acd5d0d5a68e1e24c6d276111e00c2c6 | [] | no_license | gauzinge/rd53stream | 85206827f7b364782a7b8a56a64dbb0ab57e4f68 | 7442a05d4107ed8bb447691fe4356e82172b2a12 | refs/heads/master | 2021-06-12T19:41:43.125023 | 2020-09-09T13:39:15 | 2020-09-09T13:39:15 | 254,384,519 | 1 | 1 | null | 2020-04-09T13:51:12 | 2020-04-09T13:51:11 | null | UTF-8 | C++ | false | false | 10,750 | cc | #include <encode/interface/QCore.h>
QCore::QCore (int event_in, int module_in, int chip_in, uint32_t ccol_in, uint32_t qcrow_in, bool isneighbour_in, bool islast_in, std::vector<ADC> adcs_in) :
event (event_in),
module (module_in),
chip (chip_in),
adcs (adcs_in),
isneighbour (isneighbour_in),
islast (islast_in),
qcrow (qcrow_in),
ccol (ccol_in),
hitmap (adcs_to_hitmap (adcs) )
//encoded_hitmap (encoder_in->encode_hitmap (this->hitmap) )
{
this->encoded_hitmap.clear();
this->encode_hitmap();
}
std::vector<bool > QCore::binary_tots () const
{
std::vector<bool > tots;
for (auto const& adc : adcs)
{
if (adc == 0)
continue;
for (size_t bit = 4; bit > 0; bit--)
tots.push_back ( (adc >> (bit - 1) ) & 0x1);
}
assert (tots.size() <= 4 * adcs.size() );
return tots;
};
std::vector<bool > QCore::adcs_to_hitmap (std::vector<ADC > adcs)
{
assert (adcs.size() == 16);
std::vector<bool > hitmap;
// Set up uncompressed hitmap
hitmap.reserve (16);
for (auto const adc : adcs)
hitmap.push_back (adc > 0);
assert (hitmap.size() == 16);
return hitmap;
};
std::vector<bool > QCore::row (int row_index) const
{
if ( (row_index < 0) or (row_index > 1) )
throw;
std::vector<bool > row;
row.insert (row.end(), this->hitmap.begin() + 8 * row_index, this->hitmap.begin() + 8 * (row_index + 1) );
assert (row.size() == 8);
return row;
}
void QCore::print (std::ostream& stream = std::cout) const
{
stream << " Module " << this->module << " Chip " << this->chip << " | Quarter core: CoreCol: " << this->ccol << " QRow: " << this->qcrow << " Hitmap: " << std::endl;
size_t index = 0;
for (auto hit : this->hitmap)
{
stream << hit << " ";
if (index == 7) stream << std::endl;
index++;
}
stream << std::endl;
}
/**
* Encode the 16-bit hitmap of using tree-based encoding
*
* The output will be between 4 and 30 bits:
* [Row OR (1-2 bits)][Row 1 (3-14 bits)][Row 2 (3-14 bits)]
*/
void QCore::encode_hitmap ()
{
assert (this->hitmap.size() == 16);
// Separate rows
std::vector<bool> row1, row2;
row1.insert (row1.end(), this->hitmap.begin(), this->hitmap.begin() + 8);
row2.insert (row2.end(), this->hitmap.begin() + 8, this->hitmap.end() );
assert (row1.size() == 8 and row2.size() == 8);
// Row OR information
std::vector<bool> row_or = {0, 0};
for ( auto const bit : row1)
{
if (bit)
{
row_or[0] = 1;
break;
}
}
for ( auto const bit : row2)
{
if (bit)
{
row_or[1] = 1;
break;
}
}
// Compress the components separately
// using lookup tables
// this already replaces 01->0
std::vector<bool> row_or_enc = enc2 (row_or);
//this is too easy, I actually need to do the whole separation
//std::vector<bool> row1_enc = enc8 (row1);
//std::vector<bool> row2_enc = enc8 (row2);
std::vector<bool>s2_row1 = {0, 0};
std::vector<bool>s3_row1 = {0, 0, 0, 0};
std::vector<bool>s2_row2 = {0, 0};
std::vector<bool>s3_row2 = {0, 0, 0, 0};
//now get the binary tree bits for step2 and step3 as per RD53B manual (p70)
if (row_or[0])
{
for (int index = 0; index < row1.size(); index++)
{
//if (index < row1.size() / 2 && row1.at (index) ) s2_row1[0] = 1;
//else if (index >= row1.size() / 2 && row1.at (index) ) s2_row1[1] = 1;
if (row1.at (index) )
{
if (index < 2)
{
s2_row1[0] = 1;
s3_row1[0] = 1;
}
else if (index >= 2 && index < 4)
{
s2_row1[0] = 1;
s3_row1[1] = 1;
}
else if (index >= 4 && index < 6)
{
s2_row1[1] = 1;
s3_row1[2] = 1;
}
else
{
s2_row1[1] = 1;
s3_row1[3] = 1;
}
}
}
}
if (row_or[1])
{
for (int index = 0; index < row2.size(); index++)
{
//if (index < row2.size() / 2 && row2.at (index) ) s2_row2[0] = 1;
//else if (index >= row2.size() && row2.at (index) ) s2_row2[1] = 1;
if (row2.at (index) )
{
if (index < 2)
{
s2_row2[0] = 1;
s3_row2[0] = 1;
}
else if (index >= 2 && index < 4)
{
s2_row2[0] = 1;
s3_row2[1] = 1;
}
else if (index >= 4 && index < 6)
{
s2_row2[1] = 1;
s3_row2[2] = 1;
}
else
{
s2_row2[1] = 1;
s3_row2[3] = 1;
}
}
}
}
// Merge together
//vector<bool> encoded_hitmap;
//this->encoded_hitmap.reserve (row_or_enc.size() + row1_enc.size() + row2_enc.size() );
//insert first the binary code substituted row_or (step1)
this->encoded_hitmap.insert (this->encoded_hitmap.end(), row_or_enc.begin(), row_or_enc.end() );
if (row_or[0])
{
//a hit in the first row, so I need the step 2 infor for this row
std::vector<bool> enc_s2_row1 = enc2 (s2_row1);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s2_row1.begin(), enc_s2_row1.end() );
//now check which branch of the tree is there
if (s2_row1[0]) // the left half of row 1 is hit
{
std::vector<bool> s3_left = {s3_row1[0], s3_row1[1]};
std::vector<bool> enc_s3_left = enc2 (s3_left);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s3_left.begin(), enc_s3_left.end() );
}
if (s2_row1[1]) // the right part of row 1 is hit
{
std::vector<bool> s3_right = {s3_row1[2], s3_row1[3]};
std::vector<bool> enc_s3_right = enc2 (s3_right);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s3_right.begin(), enc_s3_right.end() );
}
//now take care to append the hitmaps
if (s3_row1[0]) // the left quarter of row 1 is hit
{
std::vector<bool> map = {row1[0], row1[1]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row1[1]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row1[2], row1[3]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row1[2]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row1[4], row1[5]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row1[3]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row1[6], row1[7]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
}
if (row_or[1])
{
//a hit in the second row, so I need the step 2 infor for this row
std::vector<bool> enc_s2_row2 = enc2 (s2_row2);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s2_row2.begin(), enc_s2_row2.end() );
//now check which branch of the tree is there
if (s2_row2[0]) // the left half of row 2 is hit
{
std::vector<bool> s3_left = {s3_row2[0], s3_row2[1]};
std::vector<bool> enc_s3_left = enc2 (s3_left);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s3_left.begin(), enc_s3_left.end() );
}
if (s2_row2[1]) // the right part of row 2 is also hit
{
std::vector<bool> s3_right = {s3_row2[2], s3_row2[3]};
std::vector<bool> enc_s3_right = enc2 (s3_right);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_s3_right.begin(), enc_s3_right.end() );
}
//now take care to append the hitmaps
if (s3_row2[0]) // the left quarter of row 1 is hit
{
std::vector<bool> map = {row2[0], row2[1]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row2[1]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row2[2], row2[3]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row2[2]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row2[4], row2[5]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
if (s3_row2[3]) // the second quarter of row1 is hit
{
std::vector<bool> map = {row2[6], row2[7]};
std::vector<bool> enc_map = enc2 (map);
this->encoded_hitmap.insert (this->encoded_hitmap.end(), enc_map.begin(), enc_map.end() );
}
}
//std::cout << "HITMAP" << std::endl;
//std::cout << row1[0] << row1[1] << "|" << row1[2] << row1[3] << "|" << row1[4] << row1[5] << "|" << row1[6] << row1[7] << std::endl;
//std::cout << row2[0] << row2[1] << "|" << row2[2] << row2[3] << "|" << row2[4] << row2[5] << "|" << row2[6] << row2[7] << std::endl;
//std::cout << "TREE" << std::endl;
//std::cout << " " << row_or[0] << row_or[1] << std::endl;
//std::cout << " " << s2_row1[0] << s2_row1[1] << " " << s2_row2[0] << s2_row2[1] << std::endl;
//std::cout << s3_row1[0] << s3_row1[1] << s3_row1[2] << s3_row1[3] << s3_row2[0] << s3_row2[1] << s3_row2[2] << s3_row2[3] << std::endl;
//this->encoded_hitmap.insert (this->encoded_hitmap.end(), row1_enc.begin(), row1_enc.end() );
//this->encoded_hitmap.insert (this->encoded_hitmap.end(), row2_enc.begin(), row2_enc.end() );
//return encoded_hitmap;
}
| [
"georg.auzinger@cern.ch"
] | georg.auzinger@cern.ch |
61945e84e0cfcf1d587c927d86e2882718e82e1f | b58b041560d9383893536f9f05a0275c74a6efeb | /include/cpp-sort/comparators/total_greater.h | 77aa1ca3d794e8fe53ccb9b1417a55a94141c8df | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LLVM-exception",
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | afakihcpr/cpp-sort | 314fa90342983f195edb5e70783d4d8c70883cbb | 8e4d3728f26d654899f54dc261e3765fdd782acb | refs/heads/master | 2023-08-26T11:36:42.195133 | 2021-07-27T14:31:38 | 2021-07-27T14:31:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | h | /*
* Copyright (c) 2016-2019 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_COMPARATORS_TOTAL_GREATER_H_
#define CPPSORT_COMPARATORS_TOTAL_GREATER_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cmath>
#include <type_traits>
#include <utility>
#include <cpp-sort/utility/branchless_traits.h>
#include <cpp-sort/utility/static_const.h>
#include "../detail/floating_point_weight.h"
namespace cppsort
{
namespace detail
{
////////////////////////////////////////////////////////////
// Total order for integral types
template<typename T>
constexpr auto total_greater(T lhs, T rhs) noexcept
-> std::enable_if_t<std::is_integral<T>::value, bool>
{
return lhs > rhs;
}
////////////////////////////////////////////////////////////
// Total order for floating point types
template<typename T>
auto total_greater(T lhs, T rhs)
-> std::enable_if_t<std::is_floating_point<T>::value, bool>
{
if (std::isfinite(lhs) && std::isfinite(rhs)) {
if (lhs == 0 && rhs == 0) {
return std::signbit(rhs) && not std::signbit(lhs);
}
return lhs > rhs;
}
int lhs_weight = total_weight(lhs);
int rhs_weight = total_weight(rhs);
return lhs_weight > rhs_weight;
}
////////////////////////////////////////////////////////////
// Customization point
struct total_greater_fn
{
template<typename T, typename U>
constexpr auto operator()(T&& lhs, U&& rhs) const
noexcept(noexcept(total_greater(std::forward<T>(lhs), std::forward<U>(rhs))))
-> decltype(total_greater(std::forward<T>(lhs), std::forward<U>(rhs)))
{
return total_greater(std::forward<T>(lhs), std::forward<U>(rhs));
}
using is_transparent = void;
};
}
using total_greater_t = detail::total_greater_fn;
namespace
{
constexpr auto&& total_greater = utility::static_const<
detail::total_greater_fn
>::value;
}
// Branchless traits
namespace utility
{
template<typename T>
struct is_probably_branchless_comparison<cppsort::total_greater_t, T>:
std::is_integral<T>
{};
}
}
#endif // CPPSORT_COMPARATORS_TOTAL_GREATER_H_
| [
"morwenn29@hotmail.fr"
] | morwenn29@hotmail.fr |
fea8e01acb79532e09276c5840954ca0787c398d | a5346bb5946871f632a427967aab9c1c5d0d83c7 | /esp32injectexample.ino | 97ef1477ad6f17afa9b02985ea2ddff11cce4d8d | [] | no_license | Celppu/esp32injectfordummiess | c9da8507aa2716eb95c0950e3a810dec36f68c42 | 1fef33467da284d20e5cf6f03e25af2d85a201bb | refs/heads/master | 2020-05-24T16:08:06.882854 | 2019-05-18T12:58:13 | 2019-05-18T12:58:13 | 187,349,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,453 | ino |
#include "freertos/FreeRTOS.h"
#include "esp_event_loop.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "string.h"
#include <WiFi.h>
uint8_t channell = 13;
// Access point MAC
uint8_t ap[6] = {0x00,0x01,0x02,0x03,0x04,0x05};
// Client MAC
//uint8_t clientt[6] = {0x06,0x07,0x08,0x09,0x0A,0x0B};
uint8_t clientt[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
// Sequence number of a packet from AP to client
uint16_t seq_n = 0;
// Packet buffer
uint8_t packet_buffer[1000] = {0};
esp_err_t event_handler(void *ctx, system_event_t *event) {
return ESP_OK;
}
//https://www.esp32.com/viewtopic.php?f=19&t=3017
//rates:
/*
0 - B 1Mb CCK
1 - B 2Mb CCK
2 - B 5.5Mb CCK
3 - B 11Mb CCK
4 - XXX Not working. Should be B 1Mb CCK SP
5 - B 2Mb CCK SP
6 - B 5.5Mb CCK SP
7 - B 11Mb CCK SP
8 - G 48Mb ODFM
9 - G 24Mb ODFM
10 - G 12Mb ODFM
11 - G 6Mb ODFM
12 - G 54Mb ODFM
13 - G 36Mb ODFM
14 - G 18Mb ODFM
15 - G 9Mb ODFM
16 - N 6.5Mb MCS0
17 - N 13Mb MCS1
18 - N 19.5Mb MCS2
19 - N 26Mb MCS3
20 - N 39Mb MCS4
21 - N 52Mb MCS5
22 - N 58Mb MCS6
23 - N 65Mb MCS7
24 - N 7.2Mb MCS0 SP
25 - N 14.4Mb MCS1 SP
26 - N 21.7Mb MCS2 SP
27 - N 28.9Mb MCS3 SP
28 - N 43.3Mb MCS4 SP
29 - N 57.8Mb MCS5 SP
30 - N 65Mb MCS6 SP
31 - N 72Mb MCS7 SP
*/
typedef union {
uint8_t fix_rate;
uint8_t b5;
uint8_t b4;
struct {
uint8_t b3;
uint8_t b2;
} b1;
struct {
uint32_t a1;
uint8_t a2;
uint8_t a3;
uint8_t a4;
uint8_t a5;
struct {
uint8_t a6;
uint8_t a7;
} a8[4];
uint8_t a9;
uint8_t a10;
uint8_t a11;
uint8_t a12;
} a13;
} wifi_internal_rate_t;
extern "C" {
esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq);
esp_err_t esp_wifi_internal_set_rate(int a, int b, int c, wifi_internal_rate_t *d);
}
uint16_t empty_data_packet(uint8_t *buf, uint8_t *clientt, uint8_t *ap, uint16_t seq)
{
int i=0;
buf[0] = 0b00001000; //oikea järjestys
buf[1] = 0b00000001; //flipattu
// Duration 0 msec, will be re-written by ESP
buf[2] = 0x00;
buf[3] = 0x00;
// Destination
for (i=0; i<6; i++) buf[i+4] = clientt[i];
// Sender
for (i=0; i<6; i++) buf[i+10] = ap[i];
for (i=0; i<6; i++) buf[i+16] = ap[i];
// Seq_n
buf[22] = seq % 0xFF;
buf[23] = seq / 0xFF;
for (i=24; i<1000; i++) buf[i] = 0xFF;
return 1000;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
tcpip_adapter_init();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
wifi_config_t sta_config;
sta_config.sta.channel = 13;
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config));
ESP_ERROR_CHECK(esp_wifi_start());
wifi_internal_rate_t rate;
rate.fix_rate = 15; //rate number from table
esp_wifi_internal_set_rate(100, 1, 4, &rate);
esp_wifi_set_channel(13, WIFI_SECOND_CHAN_NONE);
}
void loop() {
// put your main code here, to run repeatedly:
uint16_t size = empty_data_packet(packet_buffer, clientt, ap, seq_n+0x10);
Serial.println(esp_wifi_80211_tx(WIFI_IF_STA, packet_buffer, size, false));
delay(1);
}
| [
"noreply@github.com"
] | noreply@github.com |
4105c31b62dc9b5089d4bf31addcfd14470eee6c | 254a5fec21417d5286bf52aa0fabac1ec17ed92a | /src/Cubestein3D/ShotBehavior.h | a1089fbf737ce5b2312a7aa0465b89a4cf8006f6 | [
"MIT"
] | permissive | DioMuller/cubestein3D | 05c57cff5588e981121dd48fa1746b1f3ffd0763 | 5a358e1662287f72fdb8e3a10a664413f24a462e | refs/heads/master | 2020-03-21T11:15:52.100715 | 2014-04-12T00:04:55 | 2014-04-12T00:04:55 | 138,497,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | h | #pragma once
#include "Behavior.h"
#include "Vector.h"
class ShotBehavior : public Behavior
{
////////////////////////////////////////
// Attributes
////////////////////////////////////////
private:
float elapsedLifetime;
Vector direction;
////////////////////////////////////////
// Constructor / Destructor
////////////////////////////////////////
public:
ShotBehavior(Entity* parent, Vector direction);
~ShotBehavior();
////////////////////////////////////////
// Methods
////////////////////////////////////////
public:
void Update(long delta);
};
| [
"diogo.muller@live.com"
] | diogo.muller@live.com |
2cc8cef2aa056868081399436ed515d2ce1ab40d | e8363fac1e229ac367d7789cd1bcd6bb9815c8c6 | /util/coding.h | 49580eeb12226a571dcf52220100e3259947b6de | [
"BSD-3-Clause"
] | permissive | DongyuanPan/CuckooDB | 6861fc018574725ec0a557d985fda96bfc180f8f | 24682f5336269deab6b751b3f7ac0f154e3e45cf | refs/heads/master | 2020-11-26T05:23:56.894400 | 2020-01-15T14:15:00 | 2020-01-15T14:15:00 | 228,975,781 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,932 | h | // The code below was copied from LevelDB.
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
// Endian-neutral encoding:
// * Fixed-length numbers are encoded with least-significant byte first
// * In addition we support variable length "varint" encoding
// * Strings are encoded prefixed by their length in varint format
#ifndef CUCKOODB_CODING_H_
#define CUCKOODB_CODING_H_
#include <stdint.h>
#include <string.h>
#include <string>
#include "util/endian.h"
#include "util/status.h"
namespace cdb {
// Standard Put... routines append to a string
extern void PutFixed32(std::string* dst, uint32_t value);
extern void PutFixed64(std::string* dst, uint64_t value);
extern void PutVarint32(std::string* dst, uint32_t value);
extern void PutVarint64(std::string* dst, uint64_t value);
extern int GetVarint32(char* input, uint64_t size, uint32_t* value);
extern int GetVarint64(char* input, uint64_t size, uint64_t* value);
// Pointer-based variants of GetVarint... These either store a value
// in *v and return a pointer just past the parsed value, or return
// NULL on error. These routines only look at bytes in the range
// [p..limit-1]
extern const char* GetVarint32Ptr(const char* p,const char* limit, uint32_t* v);
extern const char* GetVarint64Ptr(const char* p,const char* limit, uint64_t* v);
// Returns the length of the varint32 or varint64 encoding of "v"
extern int VarintLength(uint64_t v);
// Lower-level versions of Put... that write directly into a character buffer
// REQUIRES: dst has enough space for the value being written
extern void EncodeFixed32(char* dst, uint32_t value);
extern void EncodeFixed64(char* dst, uint64_t value);
extern void GetFixed32(const char* src, uint32_t* value);
extern void GetFixed64(const char* src, uint64_t* value);
// Lower-level versions of Put... that write directly into a character buffer
// and return a pointer just past the last byte written.
// REQUIRES: dst has enough space for the value being written
extern char* EncodeVarint32(char* dst, uint32_t value);
extern char* EncodeVarint64(char* dst, uint64_t value);
// Lower-level versions of Get... that read directly from a character buffer
// without any bounds checking.
inline uint32_t DecodeFixed32(const char* ptr) {
if (cdb::kLittleEndian) {
// Load the raw bytes
uint32_t result;
memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
return result;
} else {
return ((static_cast<uint32_t>(static_cast<unsigned char>(ptr[0])))
| (static_cast<uint32_t>(static_cast<unsigned char>(ptr[1])) << 8)
| (static_cast<uint32_t>(static_cast<unsigned char>(ptr[2])) << 16)
| (static_cast<uint32_t>(static_cast<unsigned char>(ptr[3])) << 24));
}
}
inline uint64_t DecodeFixed64(const char* ptr) {
if (cdb::kLittleEndian) {
// Load the raw bytes
uint64_t result;
memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
return result;
} else {
uint64_t lo = DecodeFixed32(ptr);
uint64_t hi = DecodeFixed32(ptr + 4);
return (hi << 32) | lo;
}
}
// Internal routine for use by fallback path of GetVarint32Ptr
extern const char* GetVarint32PtrFallback(const char* p,
const char* limit,
uint32_t* value);
inline const char* GetVarint32Ptr(const char* p,
const char* limit,
uint32_t* value) {
if (p < limit) {
uint32_t result = *(reinterpret_cast<const unsigned char*>(p));
if ((result & 128) == 0) {
*value = result;
return p + 1;
}
}
return GetVarint32PtrFallback(p, limit, value);
}
} // namespace cdb
#endif // CUCKOODB_CODING_H_
| [
"641234230@qq.com"
] | 641234230@qq.com |
d7edcc2e973419fb0e6011f04f070f8e244d1133 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14173/function14173_schedule_16/function14173_schedule_16_wrapper.cpp | c88c6687e85d40be7e987ff161a37741de85b3e6 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | #include "Halide.h"
#include "function14173_schedule_16_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64, 512);
Halide::Buffer<int32_t> buf01(2048);
Halide::Buffer<int32_t> buf02(2048, 64);
Halide::Buffer<int32_t> buf0(2048, 64, 512);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14173_schedule_16(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14173/function14173_schedule_16/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
393d5587496d94c465de0144795a5cef63183af1 | 4afee8c9d257572f138260ef725145e48ccd20c8 | /AandBandCompilationErrors.cpp | 86da061ce873b8c04e826d2836f4128489646da3 | [] | no_license | 8adam95/problems | 4f9ed06a2320d68e220e168fbcaa79eb3af95eea | cf8a878608eb3959637c4f5524b5a6e932f5a430 | refs/heads/master | 2020-12-24T16:23:27.076894 | 2016-10-02T20:40:39 | 2016-10-02T20:40:39 | 41,453,505 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | cpp | //http://codeforces.com/problemset/problem/519/B
#include<cstdio>
#include<iostream>
#include<map>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
#define REP(I, N) for(int I = 0; I < (N); I++)
#define FOR(I, A, B) for(int I = (A); I <= (B); I++)
#define FORD(I, A, B) for(int I = (A); I >= (B); I--)
#define ll long long
#define F first
#define S second
#define MP make_pair
#define PB push_back
const int MAXN = 100006;
int n, tab[MAXN], res1[MAXN], res2[MAXN], mis;
int main()
{
scanf("%d", &n);
REP(i, n)
scanf("%d", tab+i);
sort(tab, tab+n);
REP(i, n-1)
scanf("%d", res1+i);
sort(res1, res1+n-1);
REP(i, n)
if(res1[i] != tab[i])
{
printf("%d\n", tab[i]);
tab[i] = 1000000009;
break;
}
sort(tab, tab+n);
REP(i, n-2)
scanf("%d", res2+i);
sort(res2, res2+n-2);
REP(i, n)
if(res2[i] != tab[i])
{
printf("%d\n", tab[i]);
break;
}
return 0;
} | [
"adam.szefer@gmail.com"
] | adam.szefer@gmail.com |
736a2f901c4eb5b885d2e6fd2b89b4958d6bd2f7 | e24d68690fc3407933b0362b358668e9d81e5763 | /src/core/SkLightingShader.h | d28648767db68ddc2369d81bfe7f9468fdde3b80 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | webbjiang/skia | 39300e2faf38c47cd579392f77e22af4ce1184c1 | a04c650459280363454da3b43ae910b8593434c8 | refs/heads/master | 2021-01-16T07:13:04.593971 | 2015-08-26T22:27:59 | 2015-08-26T22:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,044 | h |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkLightingShader_DEFINED
#define SkLightingShader_DEFINED
#include "SkFlattenable.h"
#include "SkLight.h"
#include "SkShader.h"
#include "SkTDArray.h"
class SkBitmap;
class SkMatrix;
class SK_API SkLightingShader {
public:
class Lights : public SkRefCnt {
public:
class Builder {
public:
Builder(const SkLight lights[], int numLights)
: fLights(new Lights(lights, numLights)) {}
Builder() : fLights(new Lights) {}
// TODO: limit the number of lights here or just ignore those
// above some maximum?
void add(const SkLight& light) {
if (fLights) {
*fLights->fLights.push() = light;
}
}
const Lights* finish() {
return fLights.detach();
}
private:
SkAutoTUnref<Lights> fLights;
};
int numLights() const {
return fLights.count();
}
const SkLight& light(int index) const {
return fLights[index];
}
private:
Lights() {}
Lights(const SkLight lights[], int numLights) : fLights(lights, numLights) {}
SkTDArray<SkLight> fLights;
typedef SkRefCnt INHERITED;
};
/** Returns a shader that lights the diffuse and normal maps with a single light.
It returns a shader with a reference count of 1.
The caller should decrement the shader's reference count when done with the shader.
It is an error for count to be < 2.
@param diffuse the diffuse bitmap
@param normal the normal map
@param light the light applied to the normal map
@param ambient the linear (unpremul) ambient light color. Range is 0..1/channel.
@param localMatrix the matrix mapping the textures to the dest rect
NULL will be returned if:
either 'diffuse' or 'normal' are empty
either 'diffuse' or 'normal' are too big (> 65535 on a side)
'diffuse' and 'normal' aren't the same size
The lighting equation is currently:
result = LightColor * DiffuseColor * (Normal * LightDir) + AmbientColor
The normal map is currently assumed to be an 8888 image where the normal at a texel
is retrieved by:
N.x = R-127;
N.y = G-127;
N.z = B-127;
N.normalize();
The +Z axis is thus encoded in RGB as (127, 127, 255) while the -Z axis is
(127, 127, 0).
*/
static SkShader* Create(const SkBitmap& diffuse, const SkBitmap& normal,
const Lights* lights, const SkVector& invNormRotation,
const SkMatrix* diffLocalMatrix, const SkMatrix* normLocalMatrix);
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
};
#endif
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
924c0b4b53187f87ba3ab6d716afb745a4203c21 | b61e7668a43d47b2267b84758f09f64065a3b5d1 | /src/main.cpp | 05e1fbe24da1cd547b1d9d19e52ed348e341167e | [
"MIT"
] | permissive | ddrevicky/cudann | fa42b0652e396a11e478c9b9224dac6b6432c42b | 44eb973c497492f98fd09a758a34e9d4f3a20e47 | refs/heads/master | 2020-07-30T14:14:31.737811 | 2019-09-23T03:52:37 | 2019-09-23T03:52:37 | 124,567,142 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,383 | cpp | #define EIGEN_DONT_VECTORIZE // The GPU implementation relies on Eigen matrices not being aligned
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#endif
#include <iostream>
#include <iomanip>
#include <vector>
#include <cuda_runtime.h>
#include <cuda.h>
#include <cuda_profiler_api.h>
#include <device_launch_parameters.h>
#include "neural_net_cpu.h"
#include "neural_net_gpu.h"
#include "test_cpu.h"
#include "test_gpu.h"
#include "gpu_matrix.h"
#include "main_util.h"
using std::cout;
using std::cerr;
int main(int argc, char **argv)
{
{
#ifdef _DEBUG
#if defined(_WIN32)
unsigned int crtFlags = _CRTDBG_LEAK_CHECK_DF; // Perform automatic leak checking at program exit through a call to _CrtDumpMemoryLeaks
crtFlags |= _CRTDBG_DELAY_FREE_MEM_DF; // Keep freed memory blocks in the heap's linked list, assign them the _FREE_BLOCK type, and fill them with the byte value 0xDD
crtFlags |= _CRTDBG_CHECK_ALWAYS_DF; // Call _CrtCheckMemory at every allocation and deallocation request. _crtBreakAlloc = 323; tracks the erroneous malloc
#endif
// Tests
TestCPU::RunAllTests();
TestGPU::RunAllTests();
#endif
HyperParameters params;
int result = ParseArgs(argc, argv, params);
if (result != 0)
return result;
// Get MNIST directory
std::string filePath = __FILE__;
filePath.erase(filePath.length() - strlen("/src/main.cpp"), strlen("/src/main.cpp"));
std::string MNISTDir = filePath + "/data/mnist";
// Make dataset
Dataset MNIST;
result = MakeMNIST(MNIST, MNISTDir.c_str());
if (result != 0)
return result;
// Model
float initWeightScale = 0.1f;
int randomSeed = 256;
unsigned inputDim = 784;
unsigned numClasses = 10;
std::vector<unsigned> layers = std::vector<unsigned>{ inputDim };
layers.insert(layers.end(), params.hiddenLayers.begin(), params.hiddenLayers.end());
layers.push_back(numClasses);
cout << "NN Architecture: \n";
for (int i = 0; i < layers.size(); ++i)
{
cout << layers[i];
if (i < layers.size() - 1)
cout << "-";
else
cout << "\n\n";
}
bool verboseSGD = params.verbose; // Slows down neural net on GPU due to device to host copying
// Train on CPU
NeuralNetCPU nnCPU(layers, params.activation, params.regularization, initWeightScale, randomSeed, params.batchSize);
cout << "CPU TRAINING FOR " << params.cpuEpochs << " EPOCHS\n";
cout << "Initial test set results:";
nnCPU.ReportAccuracy(MNIST.XVal, MNIST.yVal);
double averageEpochTimeCPU = nnCPU.SGD(MNIST.XTrain, MNIST.yTrain, params.cpuEpochs, params.learningRate, params.decreaseLearnRateAfterEpochs, params.decreaseFactor, verboseSGD);
cout << "Final test set results:";
nnCPU.ReportAccuracy(MNIST.XVal, MNIST.yVal);
// Predict on CPU
double averagePredictTimeCPU = ProfilePredictCPU(nnCPU, MNIST.XDev, MNIST.yDev);
// Train on GPU
NeuralNetGPU nnGPU(layers, params.activation, params.regularization, initWeightScale, randomSeed, params.batchSize);
cout << "\nGPU TRAINING FOR " << params.gpuEpochs << " EPOCHS\n";
cout << "Initial test set results:";
nnGPU.ReportAccuracy(MNIST.XVal, MNIST.yVal);
double averageEpochTimeGPU = nnGPU.SGD(MNIST.XTrain, MNIST.yTrain, params.gpuEpochs, params.learningRate, params.decreaseLearnRateAfterEpochs, params.decreaseFactor, verboseSGD);
cout << "Final test set results:";
nnGPU.ReportAccuracy(MNIST.XVal, MNIST.yVal);
// Predict on GPU
double averagePredictTimeGPU = ProfilePredictGPU(nnGPU, MNIST.XDev, MNIST.yDev);
// Compare performance
std::cout << "\nPERFORMANCE COMPARISON" << std::endl;
std::cout << "Average epoch train time: " << std::endl;
std::cout << "CPU " << averageEpochTimeCPU << " ms" << std::endl;
std::cout << "GPU " << averageEpochTimeGPU << " ms, " << averageEpochTimeCPU / averageEpochTimeGPU << "X speedup\n" << std::endl;
std::cout << "Average prediction time: " << std::endl;
std::cout << "CPU " << averagePredictTimeCPU << " ms" << std::endl;
std::cout << "GPU " << averagePredictTimeGPU << " ms, " << averagePredictTimeCPU / averagePredictTimeGPU << "X speedup\n" << std::endl;
}
#if defined(_WIN32) && defined(_DEBUG)
int debugResult = _CrtDumpMemoryLeaks();
#endif
return 0;
} | [
"drevicky@gmail.com"
] | drevicky@gmail.com |
d6c1dd06d348b08f1134276292c387a1ccd91548 | de6b1d3e0c737ef87c2883ca5dc84db61b31fdb6 | /main.cpp | 5c8c0484ba49acfaedeee1731da3f087cf68279d | [] | no_license | xxvms/ClassTemplate1 | a84cd62fa1c0805d28b29bdc81006acd9a468cba | 46243122b09f94065ce08931e59f126c02fb5267 | refs/heads/master | 2021-01-21T21:00:08.376142 | 2017-06-19T11:13:00 | 2017-06-19T11:13:00 | 94,768,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp | #include <iostream>
const int MAX = 100; // size of array
template <class Type>
class Stack
{
private:
Type st[MAX]; // stack array of any type
int top; // number of top of stack
public:
Stack(): top(-1) // constructor
{}
void push(Type var) // put member on stack
{
st[++top] = var;
}
Type pop() // take number of the stack
{
return st[top--];
}
};
int main() {
Stack<float> s1; // s1 is object of class Stack<float>
s1.push(1111.11); // push 3 floats and pop 3 floats
s1.push(2222.22);
s1.push(3333.33);
std::cout << "1: " << s1.pop() << std::endl;
std::cout << "2: " << s1.pop() << std::endl;
std::cout << "3: " << s1.pop() << std::endl;
Stack<long> s2; // s2 is object of class Stack<long>
s2.push(123123123); // push 3 longs and pop 3 longs
s2.push(234234234);
s2.push(345345345);
std::cout << "1: " << s2.pop() << std::endl;
std::cout << "2: " << s2.pop() << std::endl;
std::cout << "3: " << s2.pop() << std::endl;
return 0;
}
| [
"tom@pcservicegroup.co.uk"
] | tom@pcservicegroup.co.uk |
64702e0a505a9e9d27f1062f92d885f33da5029d | de58c954b511189b5b60ce3bd073764ccfd7032d | /Práctica 3/TPV2/SRandBasedGenerator.cpp | a991607761aa1f53c705de6b5eaff83aa9e27a09 | [] | no_license | jorgmo02/TPV2 | 6871e1bef77661c9904d8a8636b76c3a53774299 | e7560074093a14e69d12d953896c88f283a07c75 | refs/heads/master | 2022-11-13T21:51:37.707142 | 2020-07-06T16:05:45 | 2020-07-06T16:05:45 | 239,794,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | #include "SRandBasedGenerator.h"
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <assert.h>
using namespace std;
SRandBasedGenerator::SRandBasedGenerator() :
seed_(std::time(0)) {
}
SRandBasedGenerator::SRandBasedGenerator(unsigned seed) :
seed_(seed) {
init();
}
SRandBasedGenerator::~SRandBasedGenerator() {
}
void SRandBasedGenerator::init() {
srand(seed_);
}
int SRandBasedGenerator::nextInt() {
return rand();
}
int SRandBasedGenerator::nextInt(int low, int high) {
assert(low < high);
return low + (nextInt() % (high - low));
} | [
"jorgemomartin@gmail.com"
] | jorgemomartin@gmail.com |
cc406fc913d857e93b05331554c10eaa8cbb1311 | 07d784d60aacc1872b19525e4de755378ba5fe9e | /EersteGraphicEngine/Color.h | 53e0557ea08d6c2671ed464b9e34c0e341c61807 | [
"MIT"
] | permissive | fabsgc/EersteGraphicEngine | 0c9308a51d1b2b2e83f0f22da9950e75bdf5ee0b | 09d0da03dbe3a17a5da6651409f697a0db8634bd | refs/heads/master | 2021-04-29T15:47:30.391663 | 2018-09-24T14:13:48 | 2018-09-24T14:13:48 | 121,803,405 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | h | #pragma once
#include "PrerequisitesCore.h"
namespace ege
{
class Color
{
public:
Color();
Color(const float& r, const float& g, const float& b, const float& a = DefaultColorA);
Color(const XMFLOAT3& Color);
Color(const XMFLOAT4& Color);
XMFLOAT3 ToXMFLOAT3() const;
XMFLOAT4 ToXMFLOAT4() const;
const float& R() const;
const float& G() const;
const float& B() const;
const float& A() const;
protected:
static const float DefaultColorR;
static const float DefaultColorG;
static const float DefaultColorB;
static const float DefaultColorA;
protected:
float _r;
float _g;
float _b;
float _a;
};
} | [
"fabienbeaudimi@hotmail.fr"
] | fabienbeaudimi@hotmail.fr |
65905ebbca5817f8456f9723dd1125bb2995fd52 | 156d7b3e35d249377df5923017cc8af52489f97f | /brlycmbd/CrdBrlyLeg/QryBrlyLeg1NFlight_blks.cpp | c701296cd8c76551223731f30d02b8a3bd71704b | [
"MIT"
] | permissive | mpsitech/brly-BeamRelay | fa11efae1fdd34110505ac10dee9d2e96a5ea8bd | ade30cfa9285360618d9d8c717fe6591da0c8683 | refs/heads/master | 2022-09-30T21:12:35.188234 | 2022-09-12T20:46:24 | 2022-09-12T20:46:24 | 282,705,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,712 | cpp | /**
* \file QryBrlyLeg1NFlight_blks.cpp
* job handler for job QryBrlyLeg1NFlight (implementation of blocks)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 11 Jan 2021
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class QryBrlyLeg1NFlight::StatApp
******************************************************************************/
void QryBrlyLeg1NFlight::StatApp::writeJSON(
Json::Value& sup
, string difftag
, const uint firstcol
, const uint jnumFirstdisp
, const uint ncol
, const uint ndisp
) {
if (difftag.length() == 0) difftag = "StatAppQryBrlyLeg1NFlight";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["firstcol"] = firstcol;
me["jnumFirstdisp"] = jnumFirstdisp;
me["ncol"] = ncol;
me["ndisp"] = ndisp;
};
void QryBrlyLeg1NFlight::StatApp::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
, const uint firstcol
, const uint jnumFirstdisp
, const uint ncol
, const uint ndisp
) {
if (difftag.length() == 0) difftag = "StatAppQryBrlyLeg1NFlight";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemAppQryBrlyLeg1NFlight";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "firstcol", firstcol);
writeUintAttr(wr, itemtag, "sref", "jnumFirstdisp", jnumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "ncol", ncol);
writeUintAttr(wr, itemtag, "sref", "ndisp", ndisp);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class QryBrlyLeg1NFlight::StatShr
******************************************************************************/
QryBrlyLeg1NFlight::StatShr::StatShr(
const uint ntot
, const uint jnumFirstload
, const uint nload
) :
Block()
{
this->ntot = ntot;
this->jnumFirstload = jnumFirstload;
this->nload = nload;
mask = {NTOT, JNUMFIRSTLOAD, NLOAD};
};
void QryBrlyLeg1NFlight::StatShr::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "StatShrQryBrlyLeg1NFlight";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["ntot"] = ntot;
me["jnumFirstload"] = jnumFirstload;
me["nload"] = nload;
};
void QryBrlyLeg1NFlight::StatShr::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StatShrQryBrlyLeg1NFlight";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemShrQryBrlyLeg1NFlight";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "ntot", ntot);
writeUintAttr(wr, itemtag, "sref", "jnumFirstload", jnumFirstload);
writeUintAttr(wr, itemtag, "sref", "nload", nload);
xmlTextWriterEndElement(wr);
};
set<uint> QryBrlyLeg1NFlight::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (ntot == comp->ntot) insert(items, NTOT);
if (jnumFirstload == comp->jnumFirstload) insert(items, JNUMFIRSTLOAD);
if (nload == comp->nload) insert(items, NLOAD);
return(items);
};
set<uint> QryBrlyLeg1NFlight::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NTOT, JNUMFIRSTLOAD, NLOAD};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class QryBrlyLeg1NFlight::StgIac
******************************************************************************/
QryBrlyLeg1NFlight::StgIac::StgIac(
const uint jnum
, const uint jnumFirstload
, const uint nload
) :
Block()
{
this->jnum = jnum;
this->jnumFirstload = jnumFirstload;
this->nload = nload;
mask = {JNUM, JNUMFIRSTLOAD, NLOAD};
};
bool QryBrlyLeg1NFlight::StgIac::readJSON(
const Json::Value& sup
, bool addbasetag
) {
clear();
bool basefound;
const Json::Value& me = [&]{if (!addbasetag) return sup; return sup["StgIacQryBrlyLeg1NFlight"];}();
basefound = (me != Json::nullValue);
if (basefound) {
if (me.isMember("jnum")) {jnum = me["jnum"].asUInt(); add(JNUM);};
if (me.isMember("jnumFirstload")) {jnumFirstload = me["jnumFirstload"].asUInt(); add(JNUMFIRSTLOAD);};
if (me.isMember("nload")) {nload = me["nload"].asUInt(); add(NLOAD);};
};
return basefound;
};
bool QryBrlyLeg1NFlight::StgIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacQryBrlyLeg1NFlight");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StgitemIacQryBrlyLeg1NFlight";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "jnum", jnum)) add(JNUM);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "jnumFirstload", jnumFirstload)) add(JNUMFIRSTLOAD);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "nload", nload)) add(NLOAD);
};
return basefound;
};
void QryBrlyLeg1NFlight::StgIac::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "StgIacQryBrlyLeg1NFlight";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["jnum"] = jnum;
me["jnumFirstload"] = jnumFirstload;
me["nload"] = nload;
};
void QryBrlyLeg1NFlight::StgIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StgIacQryBrlyLeg1NFlight";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StgitemIacQryBrlyLeg1NFlight";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "jnum", jnum);
writeUintAttr(wr, itemtag, "sref", "jnumFirstload", jnumFirstload);
writeUintAttr(wr, itemtag, "sref", "nload", nload);
xmlTextWriterEndElement(wr);
};
set<uint> QryBrlyLeg1NFlight::StgIac::comm(
const StgIac* comp
) {
set<uint> items;
if (jnum == comp->jnum) insert(items, JNUM);
if (jnumFirstload == comp->jnumFirstload) insert(items, JNUMFIRSTLOAD);
if (nload == comp->nload) insert(items, NLOAD);
return(items);
};
set<uint> QryBrlyLeg1NFlight::StgIac::diff(
const StgIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {JNUM, JNUMFIRSTLOAD, NLOAD};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
| [
"aw@mpsitech.com"
] | aw@mpsitech.com |
e383dbb93a765b3e1d4c23cb5f2bcb406ea38011 | 4d51eea684625b74fa323981d076b5eded207c12 | /04-75-LCD_advanced_mode_with_MCP9808/04-75-LCD_advanced_mode_with_MCP9808.ino | 619266f820276ceca71a31d005647773c6eed5a2 | [] | no_license | futureshocked/Arduino-mobile-development-with-Blynk | 5f4d95018d83316bb0b5420f0dbd6dc7d56b1da1 | 91aaeb9beb730a6cb31df8a9fe49819316529d66 | refs/heads/main | 2023-07-24T05:53:06.002409 | 2021-09-07T21:24:58 | 2021-09-07T21:24:58 | 301,262,762 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | ino | /* Arduino Mobile Development With Blynk
This code is part of a course from Tech Explorations.
For information about this course, please see
https://techexplorations.com/so/blynk/
For information on hardware components and the wiring needed to
run this sketch, please see the relevant lecture in the course.
Created by Peter Dalmaris
*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include "secrets.h"
#include "Adafruit_MCP9808.h"
Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
WidgetLCD lcd(V0);
BlynkTimer timer;
void setup()
{
Serial.begin(9600);
if (!tempsensor.begin(0x18)) {
Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
while (1);
}
tempsensor.setResolution(3);
Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, update_lcd);
lcd.clear();
lcd.print(0, 0, "Temp: ");
}
void loop()
{
Blynk.run();
timer.run();
}
void update_lcd()
{
lcd.print(6, 0, tempsensor.readTempC());
lcd.print(12, 0, "°C");
lcd.print(6, 1, tempsensor.readTempF());
lcd.print(12, 1, "°F");
}
| [
"peter@txplore.com"
] | peter@txplore.com |
e026bdba1c2118532bf45490213daa545c90824e | 2143afe23fd76ee68237de3bd512374805b02975 | /CMP505Coursework/LSystem.h | b08cfbc1fc0deebe02050e6818911007e1e4c5d8 | [] | no_license | dielbarnes/ProceduralGamePrototype | 65020b9b02fe7393615b9c23214e145e1048ca2e | 8f87ea2d263b62b0dd25a26f96bfeff890b5982f | refs/heads/master | 2020-05-04T12:41:08.695390 | 2019-05-24T15:52:34 | 2019-05-24T15:52:34 | 179,129,887 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 4,989 | h | //
// LSystem.h
// Copyright © 2019 Diel Barnes. All rights reserved.
//
// Constants
// Cogwheel thickness : 0.5f
// Number of subdivisions : 24
// Min inner radius : 0.5f
// Min tube thickness : 0.25f
// Min distance between tube and inner cylinder/tube : 0.5f
// Min radius to spawn inner cylinder/tube : 0.5f + 0.25f + 0.5f = 1.25f
// Modules
// C(r, b, w, h) : Add cylinder mesh (parameters: radius, number of boxes, box width, box height)
// T(r1, r2, b, w, h) : Add tube mesh (parameters: inner radius, outer radius, number of boxes, box width, box height)
// B(w, h) : Add box mesh (parameters: width, height)
// ^(d) : Translate up (parameter: distance)
// /(a) : Rotate clockwise (parameter: angle)
// o : Go back to origin
// Rules
// C(r, b, i, w, h) : b > 1 -> C(r, b-1, i, w, h) /(360/b*i) B(w, h)
// : b == 1 -> C(r, 0, i, w, h) ^(r + (h/2) - 0.2) B(w, h)
//
// T(r1, r2, b, i, w, h) : b > 1 -> T(r1, r2, b-1, i, w, h) /(360/b*i) B(w, h)
// : b == 1 -> T(r1, r2, 0, i, w, h) ^(r + (h/2) - 0.2) B(w, h)
// : b == 0, r1 >= 1.25 -> T(r1, r2, 0, i, w, h)
// -> C(r2/3, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> C(r2/4, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> C(r2/3, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> C(r2/4, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
//
// -> T(r2/3*0.5, r2/3, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/3*0.667, r2/3, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/3*0.334, r2/3, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
//
// -> T(r2/4*0.5, r2/4, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/4*0.667, r2/4, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/4*0.334, r2/4, round(b/2), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
//
// -> T(r2/3*0.5, r2/3, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/3*0.667, r2/3, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/3*0.334, r2/3, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
//
// -> T(r2/4*0.5, r2/4, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/4*0.667, r2/4, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
// -> T(r2/4*0.334, r2/4, round(b/4), i, w/2, r1 - r) o T(r1, r2, 0, w, h)
#pragma once
#include <functional>
#include <vector>
#include <map>
#include "Model.h"
#include "Utils.h"
#define CYLINDER_SYMBOL 'C'
#define TUBE_SYMBOL 'T'
#define BOX_SYMBOL 'B'
#define TRANSLATE_UP_SYMBOL '^'
#define ROTATE_CW_SYMBOL '/'
#define ORIGIN_SYMBOL 'o'
#define COGWHEEL_THICKNESS 0.5f
#define SUBDIVISION_COUNT 24
#define MIN_RADIUS_TO_SPAWN 1.5f
#define MIN_SPOKE_COUNT 3.0f
#define COGWHEEL_ROTATION_MATRIX XMMatrixRotationRollPitchYaw(XM_PI * 0.5f, XM_PI * 0.0f, XM_PI * 0.0f)
enum CylinderParameters : int
{
CylinderRadius = 0,
CylinderBoxCount,
CylinderBoxIterator,
CylinderBoxWidth,
CylinderBoxHeight
};
enum TubeParameters : int
{
TubeInnerRadius = 0,
TubeOuterRadius,
TubeBoxCount,
TubeBoxIterator,
TubeBoxWidth,
TubeBoxHeight
};
enum BoxParameters : int
{
BoxWidth = 0,
BoxHeight
};
struct Module
{
char symbol;
std::vector<float> parameters; // Should be the same order as the enums
Module() {}
Module(char c, std::vector<float> params)
{
symbol = c;
parameters = params;
}
};
using Word = std::vector<Module>;
using ConditionFunction = std::function<bool(std::vector<float>)>;
using SuccessorFunction = std::function<Word(Module)>;
struct Rule
{
ConditionFunction conditionFunction;
std::vector<SuccessorFunction> successorFunctions; // Equal probability
Rule() {}
Rule(ConditionFunction condFunc, std::vector<SuccessorFunction> successorFuncs)
{
conditionFunction = condFunc;
successorFunctions = successorFuncs;
}
};
class LSystem
{
public:
LSystem();
~LSystem();
void GenerateModel(Word axiom, Model *pModel);
private:
std::map<char, std::vector<Rule>> m_rules;
void AddRules();
Word ApplyRules(Word word);
Word ApplyRule(Module module);
};
| [
"diel.barnes@gmail.com"
] | diel.barnes@gmail.com |
7d89709e5fa3e13d5b4b2cd9d19f20d543b770c8 | 5163a289556a7d4a9d849eee9e205c20bd4c8cc9 | /2. Add Two Numbers.cpp | 815c9c81c16b057aa456a89aff02de0065464404 | [] | no_license | Aman-Arcanion9/CP-for-interview-preparation | 985accdc4c493ded06e72b5b61efcadeb89b11e1 | 4237cf4763daabfc78552069723a5e6c9b255963 | refs/heads/master | 2022-12-08T07:52:13.450363 | 2020-08-29T11:48:06 | 2020-08-29T11:48:06 | 268,521,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL &&l2==NULL) return l1;
if(l1==NULL) return l2;
if(l2==NULL) return l1;
int a = l1->val + l2->val;
ListNode* p = new ListNode(a%10);
p->next = addTwoNumbers(l1->next,l2->next);
if(a>=10) p->next = addTwoNumbers(p->next, new ListNode(1));
return p;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
b1749c035b99a70bef46d755a25f6f21293dd2b5 | cf71991e4eddae008037f30c1f9e964deee2e7e1 | /prefixsum_seq.cpp | 0997f53c206894f14738b8e2ed2061c6b0fd8104 | [] | no_license | sabusajin/openmp_parallel | 7feec37d26b697c466274fa8ff5710a5097c2a3b | 6e75d154e923d02a8f1ce645b712c7c6ea66fca6 | refs/heads/master | 2021-07-12T22:23:20.971083 | 2017-10-17T18:05:43 | 2017-10-17T18:05:43 | 106,616,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | cpp | #include <chrono>
#include <stdio.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
void generatePrefixSumData (int* arr, size_t n);
void checkPrefixSumResult (int* arr, size_t n);
#ifdef __cplusplus
}
#endif
int main (int argc, char* argv[]) {
if (argc < 2) {
std::cerr<<"Usage: "<<argv[0]<<" <n>"<<std::endl;
return -1;
}
int n = atoi(argv[1]);
int * arr = new int [n];
generatePrefixSumData (arr, n);
//write code here
std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
int* newarr = new int [n+1];
newarr[0] = 0;
for (int i=0; i<n; ++i) {
newarr[i+1] = newarr[i] + arr[i];
}
std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cerr<<elapsed_seconds.count()<<std::endl;
checkPrefixSumResult(newarr, n);
delete[] arr;
delete[] newarr;
return 0;
}
| [
"sajinsabu1905@gmail.com"
] | sajinsabu1905@gmail.com |
4bc0f6611f165b97cc0e01242dbe2dd2b38d6ca2 | bbc61fe39037810826b481d965f295ef5a21dd36 | /src/test/addrman_tests.cpp | 5f0a350bea5f99b11911a8cc4a86bcd19218657a | [
"MIT"
] | permissive | matthewchincy92/unionew | df7d58f39b752b1b31deb3a0917f7528e3771ef0 | 91951af8a98fb85eefa556d52cff5c1bd52a2e33 | refs/heads/master | 2021-04-03T02:53:01.283946 | 2018-10-23T04:53:45 | 2018-10-23T04:53:45 | 124,864,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,340 | cpp | // Copyright (c) 2012-2015 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 "addrman.h"
#include "test/test_unio.h"
#include <string>
#include <boost/test/unit_test.hpp>
#include "hash.h"
#include "netbase.h"
#include "random.h"
using namespace std;
class CAddrManTest : public CAddrMan
{
uint64_t state;
public:
CAddrManTest()
{
state = 1;
}
//! Ensure that bucket placement is always the same for testing purposes.
void MakeDeterministic()
{
nKey.SetNull();
seed_insecure_rand(true);
}
int RandomInt(int nMax)
{
state = (CHashWriter(SER_GETHASH, 0) << state).GetHash().GetCheapHash();
return (unsigned int)(state % nMax);
}
CAddrInfo* Find(const CNetAddr& addr, int* pnId = NULL)
{
return CAddrMan::Find(addr, pnId);
}
CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = NULL)
{
return CAddrMan::Create(addr, addrSource, pnId);
}
void Delete(int nId)
{
CAddrMan::Delete(nId);
}
};
static CNetAddr ResolveIP(const char* ip)
{
CNetAddr addr;
BOOST_CHECK_MESSAGE(LookupHost(ip, addr, false), strprintf("failed to resolve: %s", ip));
return addr;
}
static CNetAddr ResolveIP(std::string ip)
{
return ResolveIP(ip.c_str());
}
static CService ResolveService(const char* ip, int port = 0)
{
CService serv;
BOOST_CHECK_MESSAGE(Lookup(ip, serv, port, false), strprintf("failed to resolve: %s:%i", ip, port));
return serv;
}
static CService ResolveService(std::string ip, int port = 0)
{
return ResolveService(ip.c_str(), port);
}
BOOST_FIXTURE_TEST_SUITE(addrman_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(addrman_simple)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CNetAddr source = ResolveIP("252.2.2.2");
// Test 1: Does Addrman respond correctly when empty.
BOOST_CHECK(addrman.size() == 0);
CAddrInfo addr_null = addrman.Select();
BOOST_CHECK(addr_null.ToString() == "[::]:0");
// Test 2: Does Addrman::Add work as expected.
CService addr1 = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 1);
CAddrInfo addr_ret1 = addrman.Select();
BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333");
// Test 3: Does IP address deduplication work correctly.
// Expected dup IP should not be added.
CService addr1_dup = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1_dup, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 1);
// Test 5: New table has one addr and we add a diff addr we should
// have two addrs.
CService addr2 = ResolveService("250.1.1.2", 8333);
addrman.Add(CAddress(addr2, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 2);
// Test 6: AddrMan::Clear() should empty the new table.
addrman.Clear();
BOOST_CHECK(addrman.size() == 0);
CAddrInfo addr_null2 = addrman.Select();
BOOST_CHECK(addr_null2.ToString() == "[::]:0");
}
BOOST_AUTO_TEST_CASE(addrman_ports)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK(addrman.size() == 0);
// Test 7; Addr with same IP but diff port does not replace existing addr.
CService addr1 = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 1);
CService addr1_port = ResolveService("250.1.1.1", 8334);
addrman.Add(CAddress(addr1_port, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 1);
CAddrInfo addr_ret2 = addrman.Select();
BOOST_CHECK(addr_ret2.ToString() == "250.1.1.1:8333");
// Test 8: Add same IP but diff port to tried table, it doesn't get added.
// Perhaps this is not ideal behavior but it is the current behavior.
addrman.Good(CAddress(addr1_port, NODE_NONE));
BOOST_CHECK(addrman.size() == 1);
bool newOnly = true;
CAddrInfo addr_ret3 = addrman.Select(newOnly);
BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_select)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CNetAddr source = ResolveIP("252.2.2.2");
// Test 9: Select from new with 1 addr in new.
CService addr1 = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 1);
bool newOnly = true;
CAddrInfo addr_ret1 = addrman.Select(newOnly);
BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333");
// Test 10: move addr to tried, select from new expected nothing returned.
addrman.Good(CAddress(addr1, NODE_NONE));
BOOST_CHECK(addrman.size() == 1);
CAddrInfo addr_ret2 = addrman.Select(newOnly);
BOOST_CHECK(addr_ret2.ToString() == "[::]:0");
CAddrInfo addr_ret3 = addrman.Select();
BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333");
BOOST_CHECK(addrman.size() == 1);
// Add three addresses to new table.
CService addr2 = ResolveService("250.3.1.1", 8333);
CService addr3 = ResolveService("250.3.2.2", 9838);
CService addr4 = ResolveService("250.3.3.3", 9838);
addrman.Add(CAddress(addr2, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Add(CAddress(addr3, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Add(CAddress(addr4, NODE_NONE), ResolveService("250.4.1.1", 8333));
// Add three addresses to tried table.
CService addr5 = ResolveService("250.4.4.4", 8333);
CService addr6 = ResolveService("250.4.5.5", 7777);
CService addr7 = ResolveService("250.4.6.6", 8333);
addrman.Add(CAddress(addr5, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Good(CAddress(addr5, NODE_NONE));
addrman.Add(CAddress(addr6, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Good(CAddress(addr6, NODE_NONE));
addrman.Add(CAddress(addr7, NODE_NONE), ResolveService("250.1.1.3", 8333));
addrman.Good(CAddress(addr7, NODE_NONE));
// Test 11: 6 addrs + 1 addr from last test = 7.
BOOST_CHECK(addrman.size() == 7);
// Test 12: Select pulls from new and tried regardless of port number.
BOOST_CHECK(addrman.Select().ToString() == "250.4.6.6:8333");
BOOST_CHECK(addrman.Select().ToString() == "250.3.2.2:9838");
BOOST_CHECK(addrman.Select().ToString() == "250.3.3.3:9838");
BOOST_CHECK(addrman.Select().ToString() == "250.4.4.4:8333");
}
BOOST_AUTO_TEST_CASE(addrman_new_collisions)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK(addrman.size() == 0);
for (unsigned int i = 1; i < 18; i++) {
CService addr = ResolveService("250.1.1." + boost::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
//Test 13: No collision in new table yet.
BOOST_CHECK(addrman.size() == i);
}
//Test 14: new table collision!
CService addr1 = ResolveService("250.1.1.18");
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 17);
CService addr2 = ResolveService("250.1.1.19");
addrman.Add(CAddress(addr2, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 18);
}
BOOST_AUTO_TEST_CASE(addrman_tried_collisions)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK(addrman.size() == 0);
for (unsigned int i = 1; i < 80; i++) {
CService addr = ResolveService("250.1.1." + boost::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(CAddress(addr, NODE_NONE));
//Test 15: No collision in tried table yet.
BOOST_TEST_MESSAGE(addrman.size());
BOOST_CHECK(addrman.size() == i);
}
//Test 16: tried table collision!
CService addr1 = ResolveService("250.1.1.80");
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 79);
CService addr2 = ResolveService("250.1.1.81");
addrman.Add(CAddress(addr2, NODE_NONE), source);
BOOST_CHECK(addrman.size() == 80);
}
BOOST_AUTO_TEST_CASE(addrman_find)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
BOOST_CHECK(addrman.size() == 0);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9838), NODE_NONE);
CAddress addr3 = CAddress(ResolveService("251.255.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
CNetAddr source2 = ResolveIP("250.1.2.2");
addrman.Add(addr1, source1);
addrman.Add(addr2, source2);
addrman.Add(addr3, source1);
// Test 17: ensure Find returns an IP matching what we searched on.
CAddrInfo* info1 = addrman.Find(addr1);
BOOST_CHECK(info1);
if (info1)
BOOST_CHECK(info1->ToString() == "250.1.2.1:8333");
// Test 18; Find does not discriminate by port number.
CAddrInfo* info2 = addrman.Find(addr2);
BOOST_CHECK(info2);
if (info2)
BOOST_CHECK(info2->ToString() == info1->ToString());
// Test 19: Find returns another IP matching what we searched on.
CAddrInfo* info3 = addrman.Find(addr3);
BOOST_CHECK(info3);
if (info3)
BOOST_CHECK(info3->ToString() == "251.255.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_create)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
BOOST_CHECK(addrman.size() == 0);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
int nId;
CAddrInfo* pinfo = addrman.Create(addr1, source1, &nId);
// Test 20: The result should be the same as the input addr.
BOOST_CHECK(pinfo->ToString() == "250.1.2.1:8333");
CAddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK(info2->ToString() == "250.1.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_delete)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
BOOST_CHECK(addrman.size() == 0);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
int nId;
addrman.Create(addr1, source1, &nId);
// Test 21: Delete should actually delete the addr.
BOOST_CHECK(addrman.size() == 1);
addrman.Delete(nId);
BOOST_CHECK(addrman.size() == 0);
CAddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK(info2 == NULL);
}
BOOST_AUTO_TEST_CASE(addrman_getaddr)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
// Test 22: Sanity check, GetAddr should never return anything if addrman
// is empty.
BOOST_CHECK(addrman.size() == 0);
vector<CAddress> vAddr1 = addrman.GetAddr();
BOOST_CHECK(vAddr1.size() == 0);
CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE);
addr1.nTime = GetAdjustedTime(); // Set time so isTerrible = false
CAddress addr2 = CAddress(ResolveService("250.251.2.2", 9838), NODE_NONE);
addr2.nTime = GetAdjustedTime();
CAddress addr3 = CAddress(ResolveService("251.252.2.3", 8333), NODE_NONE);
addr3.nTime = GetAdjustedTime();
CAddress addr4 = CAddress(ResolveService("252.253.3.4", 8333), NODE_NONE);
addr4.nTime = GetAdjustedTime();
CAddress addr5 = CAddress(ResolveService("252.254.4.5", 8333), NODE_NONE);
addr5.nTime = GetAdjustedTime();
CNetAddr source1 = ResolveIP("250.1.2.1");
CNetAddr source2 = ResolveIP("250.2.3.3");
// Test 23: Ensure GetAddr works with new addresses.
addrman.Add(addr1, source1);
addrman.Add(addr2, source2);
addrman.Add(addr3, source1);
addrman.Add(addr4, source2);
addrman.Add(addr5, source1);
// GetAddr returns 23% of addresses, 23% of 5 is 1 rounded down.
BOOST_CHECK(addrman.GetAddr().size() == 1);
// Test 24: Ensure GetAddr works with new and tried addresses.
addrman.Good(CAddress(addr1, NODE_NONE));
addrman.Good(CAddress(addr2, NODE_NONE));
BOOST_CHECK(addrman.GetAddr().size() == 1);
// Test 25: Ensure GetAddr still returns 23% when addrman has many addrs.
for (unsigned int i = 1; i < (8 * 256); i++) {
int octet1 = i % 256;
int octet2 = (i / 256) % 256;
int octet3 = (i / (256 * 2)) % 256;
string strAddr = boost::to_string(octet1) + "." + boost::to_string(octet2) + "." + boost::to_string(octet3) + ".23";
CAddress addr = CAddress(ResolveService(strAddr), NODE_NONE);
// Ensure that for all addrs in addrman, isTerrible == false.
addr.nTime = GetAdjustedTime();
addrman.Add(addr, ResolveIP(strAddr));
if (i % 8 == 0)
addrman.Good(addr);
}
vector<CAddress> vAddr = addrman.GetAddr();
size_t percent23 = (addrman.size() * 23) / 100;
BOOST_CHECK(vAddr.size() == percent23);
BOOST_CHECK(vAddr.size() == 461);
// (Addrman.size() < number of addresses added) due to address collisons.
BOOST_CHECK(addrman.size() == 2007);
}
BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9838), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.1.1");
CAddrInfo info1 = CAddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
BOOST_CHECK(info1.GetTriedBucket(nKey1) == 40);
// Test 26: Make sure key actually randomizes bucket placement. A fail on
// this test could be a security issue.
BOOST_CHECK(info1.GetTriedBucket(nKey1) != info1.GetTriedBucket(nKey2));
// Test 27: Two addresses with same IP but different ports can map to
// different buckets because they have different keys.
CAddrInfo info2 = CAddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetTriedBucket(nKey1) != info2.GetTriedBucket(nKey1));
set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE),
ResolveIP("250.1.1." + boost::to_string(i)));
int bucket = infoi.GetTriedBucket(nKey1);
buckets.insert(bucket);
}
// Test 28: IP addresses in the same group (\16 prefix for IPv4) should
// never get more than 8 buckets
BOOST_CHECK(buckets.size() == 8);
buckets.clear();
for (int j = 0; j < 255; j++) {
CAddrInfo infoj = CAddrInfo(
CAddress(ResolveService("250." + boost::to_string(j) + ".1.1"), NODE_NONE),
ResolveIP("250." + boost::to_string(j) + ".1.1"));
int bucket = infoj.GetTriedBucket(nKey1);
buckets.insert(bucket);
}
// Test 29: IP addresses in the different groups should map to more than
// 8 buckets.
BOOST_CHECK(buckets.size() == 160);
}
BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9838), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
CAddrInfo info1 = CAddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
BOOST_CHECK(info1.GetNewBucket(nKey1) == 786);
// Test 30: Make sure key actually randomizes bucket placement. A fail on
// this test could be a security issue.
BOOST_CHECK(info1.GetNewBucket(nKey1) != info1.GetNewBucket(nKey2));
// Test 31: Ports should not effect bucket placement in the addr
CAddrInfo info2 = CAddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetNewBucket(nKey1) == info2.GetNewBucket(nKey1));
set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE),
ResolveIP("250.1.1." + boost::to_string(i)));
int bucket = infoi.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test 32: IP addresses in the same group (\16 prefix for IPv4) should
// always map to the same bucket.
BOOST_CHECK(buckets.size() == 1);
buckets.clear();
for (int j = 0; j < 4 * 255; j++) {
CAddrInfo infoj = CAddrInfo(CAddress(
ResolveService(
boost::to_string(250 + (j / 255)) + "." + boost::to_string(j % 256) + ".1.1"), NODE_NONE),
ResolveIP("251.4.1.1"));
int bucket = infoj.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test 33: IP addresses in the same source groups should map to no more
// than 64 buckets.
BOOST_CHECK(buckets.size() <= 64);
buckets.clear();
for (int p = 0; p < 255; p++) {
CAddrInfo infoj = CAddrInfo(
CAddress(ResolveService("250.1.1.1"), NODE_NONE),
ResolveIP("250." + boost::to_string(p) + ".1.1"));
int bucket = infoj.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test 34: IP addresses in the different source groups should map to more
// than 64 buckets.
BOOST_CHECK(buckets.size() > 64);
}
BOOST_AUTO_TEST_SUITE_END() | [
"matthew@wtech.software"
] | matthew@wtech.software |
d1bfb8727e3f7fdb79d388ae3a4edb7965e45af8 | 0ca9d0bd67be775fe94399c9c3a94a9ef09c1701 | /327FIVE/327FIVE.cpp | d821e1da986cf20283df2c13d67ddc45bf179bd1 | [] | no_license | casc1244/327FIVE | 892b3efc120fe2a219b408c9a76a0175b6951444 | 3f0ff6ad55fa88cd17d053759ae9c8becb43ecbe | refs/heads/master | 2021-05-16T21:03:28.807433 | 2020-03-27T07:30:00 | 2020-03-27T07:30:00 | 250,468,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | cpp | #include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
VideoCapture cap(0);
double scale = 1.5;
//设定皮肤的颜色
double i_minh = 0;
double i_maxh = 20;
//设定饱和度
double i_mins = 43;
double i_maxs = 255;
//设定亮度
double i_minv = 100;
double i_maxv = 255;
while (1)
{
Mat frame;
Mat hsvMat;
Mat detectMat;
Mat medMat;
Mat dipMat;
cap >> frame;
Size resimgsize = Size(frame.cols*scale, frame.rows*scale);
Mat rFrame = Mat(resimgsize, frame.type());
resize(frame, rFrame, resimgsize, INTER_LINEAR);
cvtColor(rFrame, hsvMat, COLOR_BGR2HSV);
rFrame.copyTo(detectMat);
inRange(hsvMat, Scalar(i_minh, i_mins, i_minv), Scalar(i_maxh, i_maxs, i_maxv), detectMat);
cv::GaussianBlur(rFrame, medMat, cv::Size(5, 5), 3, 3);
rFrame.copyTo(dipMat);
medMat.copyTo(dipMat, detectMat);
imshow("while :in the range", detectMat);
imshow("frame", rFrame);
imshow("display",dipMat);
waitKey(30);
}
return 0;
}
| [
"1356602646@qq.com"
] | 1356602646@qq.com |
84aa395150a65750ee92e2fbb8e07aa924c38c6b | 46597f2cd98f8b66534aac8f77576d29e3099ea4 | /source/core/native_dialog.cpp | 9fd49218851be6e90313c7f758ce89ae48c440eb | [] | no_license | Gabriele91/HCUBOEngine | 0ed8819433e3f4c9b124e505e3cd8f1c14957799 | d60aeef3b3ac150f53e08fc171e1a9e55fd43016 | refs/heads/master | 2021-03-27T16:14:56.480859 | 2017-10-16T20:41:45 | 2017-10-16T20:41:45 | 44,763,452 | 1 | 1 | null | 2017-10-16T19:51:02 | 2015-10-22T17:59:21 | C++ | UTF-8 | C++ | false | false | 2,548 | cpp | //
// file_to_open.cpp
// OGLHCubeView
//
// Created by Gabriele on 06/07/16.
// Copyright © 2016 Gabriele. All rights reserved.
//
#include <hcube/core/native_dialog.h>
#include <vector>
#include <hcube/core/filesystem.h>
namespace hcube
{
namespace native_dialog
{
#if defined( __APPLE__ )
extern open_file_output cocoa_open_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
extern save_file_output cocoa_save_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
#define xxxx_open_file cocoa_open_file
#define xxxx_save_file cocoa_save_file
#elif defined( _WIN32 )
extern open_file_output window_open_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
extern save_file_output window_save_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
#define xxxx_open_file window_open_file
#define xxxx_save_file window_save_file
#elif defined( HCUBE_USE_GTK )
extern open_file_output gtk_open_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
extern save_file_output gtk_save_file
(
GLFWwindow* window,
const std::string& title,
const std::string& path,
const std::vector< std::string >& allowed_file_types
);
#define xxxx_open_file gtk_open_file
#define xxxx_save_file gtk_save_file
#elif defined( HCUBE_NO_NATIVE_DIALOG )
#define xxxx_open_file(x,y,z,w) open_file_output()
#define xxxx_save_file(x,y,z,w) save_file_output()
#else
#error OS not supported
#endif
static inline std::string get_home_or_working_dir()
{
std::string home = filesystem::home_dir();
if (home.size()) return home;
else return filesystem::working_dir();
}
open_file_output open_file_dialog
(
GLFWwindow* window,
const std::string& title,
const std::vector<std::string>& types
)
{
return xxxx_open_file(window, title, get_home_or_working_dir(), types);
}
save_file_output save_file_dialog
(
GLFWwindow* window,
const std::string& title,
const std::vector<std::string>& types
)
{
return xxxx_save_file(window, title, get_home_or_working_dir(), types);
}
};
} | [
"dbgabri@gmail.com"
] | dbgabri@gmail.com |
929560793ed876658f9cf914255df2b6e10e3841 | 705cdc3424b3f98d18be79c284101d8d9a3543a0 | /src/Index.re | b1913a5e7d772285699c7023983a89a5718dd639 | [] | no_license | avigil06/reason-contact-form | 4f9819e803604084b340e63ab52c7ef746650987 | 790390a9cb5a7c17530bb98a7ae868d30afaf0ce | refs/heads/master | 2020-04-30T19:44:09.203626 | 2019-04-01T02:49:32 | 2019-04-01T02:49:32 | 177,047,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59 | re | ReactDOMRe.renderToElementWithId(<ContactForm />, "app");
| [
"avigil06@gmail.com"
] | avigil06@gmail.com |
7a2db41ddaef1e7f454c8750491da48dfe70b1ce | fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f | /SDK/Battle_Dmg_Total_functions.cpp | bb9c013b14d2af6efd322e886cf0409741b75fba | [] | no_license | zanzo420/DBZ-Kakarot-SDK | d5a69cd4b147d23538b496b7fa7ba4802fccf7ac | 73c2a97080c7ebedc7d538f72ee21b50627f2e74 | refs/heads/master | 2021-02-12T21:14:07.098275 | 2020-03-16T10:07:00 | 2020-03-16T10:07:00 | 244,631,123 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | cpp |
#include "../SDK.h"
// Name: DBZKakarot, Version: 1.0.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function Battle_Dmg_Total.Battle_Dmg_Total_C.ConstructFirstOnly
// (Event, Protected, BlueprintEvent)
void UBattle_Dmg_Total_C::ConstructFirstOnly()
{
static auto fn = UObject::FindObject<UFunction>("Function Battle_Dmg_Total.Battle_Dmg_Total_C.ConstructFirstOnly");
UBattle_Dmg_Total_C_ConstructFirstOnly_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Battle_Dmg_Total.Battle_Dmg_Total_C.ExecuteUbergraph_Battle_Dmg_Total
// (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBattle_Dmg_Total_C::ExecuteUbergraph_Battle_Dmg_Total(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Battle_Dmg_Total.Battle_Dmg_Total_C.ExecuteUbergraph_Battle_Dmg_Total");
UBattle_Dmg_Total_C_ExecuteUbergraph_Battle_Dmg_Total_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
52b255af2ba50d303c8cf9278097c389aa387ce1 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /media/fuchsia/common/vmo_buffer.cc | ec7e46ae84383d19b18fe092ce0b552305736849 | [
"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 | 5,138 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/fuchsia/common/vmo_buffer.h"
#include <zircon/rights.h>
#include <algorithm>
#include "base/bits.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/memory/page_size.h"
namespace media {
// static
fuchsia::sysmem::BufferCollectionConstraints
VmoBuffer::GetRecommendedConstraints(size_t min_buffer_count,
absl::optional<size_t> min_buffer_size,
bool writable) {
fuchsia::sysmem::BufferCollectionConstraints buffer_constraints;
buffer_constraints.usage.cpu = fuchsia::sysmem::cpuUsageRead;
if (writable)
buffer_constraints.usage.cpu |= fuchsia::sysmem::cpuUsageWrite;
buffer_constraints.min_buffer_count = min_buffer_count;
if (min_buffer_size) {
buffer_constraints.has_buffer_memory_constraints = true;
buffer_constraints.buffer_memory_constraints.min_size_bytes =
min_buffer_size.value();
buffer_constraints.buffer_memory_constraints.ram_domain_supported = true;
buffer_constraints.buffer_memory_constraints.cpu_domain_supported = true;
}
return buffer_constraints;
}
// static
std::vector<VmoBuffer> VmoBuffer::CreateBuffersFromSysmemCollection(
fuchsia::sysmem::BufferCollectionInfo_2* info,
bool writable) {
std::vector<VmoBuffer> buffers;
buffers.resize(info->buffer_count);
fuchsia::sysmem::BufferMemorySettings& settings =
info->settings.buffer_settings;
for (size_t i = 0; i < info->buffer_count; ++i) {
fuchsia::sysmem::VmoBuffer& buffer = info->buffers[i];
if (!buffers[i].Initialize(std::move(buffer.vmo), writable,
buffer.vmo_usable_start, settings.size_bytes,
settings.coherency_domain)) {
return {};
}
}
return buffers;
}
VmoBuffer::VmoBuffer() = default;
VmoBuffer::~VmoBuffer() {
if (!base_address_) {
return;
}
zx_status_t status = zx::vmar::root_self()->unmap(
reinterpret_cast<uintptr_t>(base_address_), mapped_size());
ZX_DCHECK(status == ZX_OK, status) << "zx_vmar_unmap";
}
VmoBuffer::VmoBuffer(VmoBuffer&&) = default;
VmoBuffer& VmoBuffer::operator=(VmoBuffer&&) = default;
bool VmoBuffer::Initialize(zx::vmo vmo,
bool writable,
size_t offset,
size_t size,
fuchsia::sysmem::CoherencyDomain coherency_domain) {
DCHECK(!base_address_);
DCHECK(vmo);
writable_ = writable;
offset_ = offset;
size_ = size;
coherency_domain_ = coherency_domain;
zx_vm_option_t options = ZX_VM_PERM_READ;
if (writable)
options |= ZX_VM_PERM_WRITE;
uintptr_t addr;
zx_status_t status =
zx::vmar::root_self()->map(options, /*vmar_offset=*/0, vmo,
/*vmo_offset=*/0, mapped_size(), &addr);
if (status != ZX_OK) {
ZX_DLOG(ERROR, status) << "zx_vmar_map";
return false;
}
vmo_ = std::move(vmo);
base_address_ = reinterpret_cast<uint8_t*>(addr);
return true;
}
size_t VmoBuffer::Read(size_t offset, base::span<uint8_t> data) {
if (offset >= size_)
return 0U;
size_t bytes_to_fill = std::min(size_ - offset, data.size());
FlushCache(offset, bytes_to_fill, /*invalidate=*/true);
memcpy(data.data(), base_address_ + offset_ + offset, bytes_to_fill);
return bytes_to_fill;
}
size_t VmoBuffer::Write(base::span<const uint8_t> data) {
DCHECK(writable_);
size_t bytes_to_fill = std::min(size_, data.size());
memcpy(base_address_ + offset_, data.data(), bytes_to_fill);
FlushCache(0, bytes_to_fill, /*invalidate=*/false);
return bytes_to_fill;
}
base::span<const uint8_t> VmoBuffer::GetMemory() {
FlushCache(0, size_, /*invalidate=*/true);
return base::make_span(base_address_ + offset_, size_);
}
base::span<uint8_t> VmoBuffer::GetWritableMemory() {
DCHECK(writable_);
return base::make_span(base_address_ + offset_, size_);
}
void VmoBuffer::FlushCache(size_t flush_offset,
size_t flush_size,
bool invalidate) {
DCHECK_LE(flush_size, size_ - flush_offset);
if (coherency_domain_ != fuchsia::sysmem::CoherencyDomain::RAM)
return;
uint8_t* address = base_address_ + offset_ + flush_offset;
uint32_t options = ZX_CACHE_FLUSH_DATA;
if (invalidate)
options |= ZX_CACHE_FLUSH_INVALIDATE;
zx_status_t status = zx_cache_flush(address, flush_size, options);
ZX_DCHECK(status == ZX_OK, status) << "zx_cache_flush";
}
size_t VmoBuffer::mapped_size() {
return base::bits::AlignUp(offset_ + size_, base::GetPageSize());
}
zx::vmo VmoBuffer::Duplicate(bool writable) {
zx_rights_t rights = ZX_RIGHT_DUPLICATE | ZX_RIGHT_TRANSFER | ZX_RIGHT_READ |
ZX_RIGHT_MAP | ZX_RIGHT_GET_PROPERTY;
if (writable)
rights |= ZX_RIGHT_WRITE;
zx::vmo vmo;
zx_status_t status = vmo_.duplicate(rights, &vmo);
ZX_CHECK(status == ZX_OK, status) << "zx_handle_duplicate";
return vmo;
}
} // namespace media
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
cb65faec97c08944ad2a3f46d005b88b5e48d078 | a66bff405468ff22f73462accfaaa3c416e346a9 | /return_ref/bad.cpp | 9100a0d9a883be280269d7f324255834497a4675 | [] | no_license | huy/cpp_samples | 4688884eecf98657c1ecb1ba263b1535e55bcdce | c9d34ea55a767002aa0201333363ba781a5ea3ae | refs/heads/master | 2021-01-15T22:28:40.056801 | 2011-11-11T21:33:04 | 2011-11-11T21:33:04 | 2,448,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | cpp | #include <string>
const std::string& ReturnStackVar()
{
std::string result("bad");
return result;
}
const std::string& ReturnHeapVar()
{
std::string* result= new std::string("can lead to memory leak");
return *result;
}
| [
"lehuy20@gmail.com"
] | lehuy20@gmail.com |
c195ea7137d5c64e0d9157b9d8a8de019afebf46 | 119c1ef4d2cf07f07bfb88b5e789932dfe8a0db3 | /program/opengl/release/moc_oview.cpp | 4ab7ac4776eeae5941c25018ab130e5be1355978 | [] | no_license | hmoevip/myprogram | 4d036a3f91bebf9d4926cc2992e75251f63b7dcd | 2bb2364c682ebe9f1bcf50f70c8f9a1b71558fe9 | refs/heads/master | 2021-01-19T01:01:07.415875 | 2016-07-09T14:04:52 | 2016-07-09T14:04:52 | 62,952,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'oview.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.7)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../oview.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'oview.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.7. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_OView[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
6, 32, 37, 37, 0x0a,
38, 32, 37, 37, 0x0a,
65, 32, 37, 37, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_OView[] = {
"OView\0GetTransParameter(float*)\0para\0"
"\0GetExtendParameter(float*)\0"
"GetRollParameter(float*)\0"
};
void OView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
OView *_t = static_cast<OView *>(_o);
switch (_id) {
case 0: _t->GetTransParameter((*reinterpret_cast< float*(*)>(_a[1]))); break;
case 1: _t->GetExtendParameter((*reinterpret_cast< float*(*)>(_a[1]))); break;
case 2: _t->GetRollParameter((*reinterpret_cast< float*(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData OView::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject OView::staticMetaObject = {
{ &QGLWidget::staticMetaObject, qt_meta_stringdata_OView,
qt_meta_data_OView, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &OView::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *OView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *OView::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_OView))
return static_cast<void*>(const_cast< OView*>(this));
return QGLWidget::qt_metacast(_clname);
}
int OView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGLWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"hmoe@vip.qq.com"
] | hmoe@vip.qq.com |
42d6bd97888daf8af83cf50aded1a44fae5bfc35 | 77c87187c2036611b05fa84d6a7168c7480d5993 | /0162.cpp | 62e3d97071eff538f9cd1cd57d4a68abcab0e32b | [] | no_license | lethe2211/aoj | 2dab57e308d7d273e5216419282d51f5ed424ed8 | e50e970ed205857e709416ae3518d93d348c7ff2 | refs/heads/master | 2021-01-09T22:48:17.211666 | 2014-05-19T05:19:06 | 2014-05-19T05:19:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | #include <iostream>
#define MAX 21960000
using namespace std;
int main() {
int m,n;
int ans;
int temp;
while(cin >> m) {
if(m==0) break;
cin >> n;
ans=0;
for(int i=m;i<=n;i++) {
temp=i;
if(MAX%temp==0) {ans++; cout << temp << " ";}
}
cout << ans << endl;
}
return 0;
}
| [
"lethe2211@gmail.com"
] | lethe2211@gmail.com |
c7eb610ed316923bb911ae8137b6efe290dbfa4e | ba87bc742befee66ad634e251191d202504dbd56 | /5.8_5.10_stl_hash_set.h | 73993f097e65c5482f2ca085559d860202b8d909 | [] | no_license | guangkuan/Standard-Template-Library | 0bcd4b1a953bc47d32350ba46c520459d90d250d | e12cae25ef8e1a217fb6fbabb6cc37d184595af9 | refs/heads/master | 2020-05-20T02:33:31.623494 | 2019-06-25T07:00:37 | 2019-06-25T07:00:37 | 185,335,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,231 | h | /*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
#ifndef __SGI_STL_INTERNAL_HASH_SET_H
#define __SGI_STL_INTERNAL_HASH_SET_H
#include <concept_checks.h>
__STL_BEGIN_NAMESPACE
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#pragma set woff 1375
#endif
// Forward declaration of equality operator; needed for friend declaration.
template <class _Value,
class _HashFcn __STL_DEPENDENT_DEFAULT_TMPL(hash<_Value>),
class _EqualKey __STL_DEPENDENT_DEFAULT_TMPL(equal_to<_Value>),
class _Alloc = __STL_DEFAULT_ALLOCATOR(_Value) >
class hash_set;
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2);
/*
/ 运用set,为的是能够迅速搜寻元素。这一点,不论是其底层是RB-tree或是hashtable,都可以达成任务。
/ 但是,RB-tree有自动排序功能而hashtable没有,反应出来的结果就是,set的元素有自动排序功能而hash_set没有。
/ hash_set的用法与set完全相同
/ 凡是hashtable无法处理者,hash_set也无法处理。
*/
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_set
{
// requirements:
__STL_CLASS_REQUIRES(_Value, _Assignable);
__STL_CLASS_UNARY_FUNCTION_CHECK(_HashFcn, size_t, _Value);
__STL_CLASS_BINARY_FUNCTION_CHECK(_EqualKey, bool, _Value, _Value);
private:
typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey, _Alloc> _Ht;
//底层机制以hash table完成
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::const_pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::const_reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::const_iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
// 默认使用大小为100的表格。将被hash table调整为最接近且较大的质数
hash_set() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_set(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_set(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_set(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#else
// 以下插入操作全部使用insert_unique(),不允许键值重复
hash_set(const value_type* __f, const value_type* __l) : _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#endif /*__STL_MEMBER_TEMPLATES */
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); }
#ifdef __STL_MEMBER_TEMPLATES
template <class _Val, class _HF, class _EqK, class _Al>
friend bool operator== (const hash_set<_Val, _HF, _EqK, _Al>&,
const hash_set<_Val, _HF, _EqK, _Al>&);
#else /* __STL_MEMBER_TEMPLATES */
friend bool __STD_QUALIFIER
operator== __STL_NULL_TMPL_ARGS (const hash_set&, const hash_set&);
#endif /* __STL_MEMBER_TEMPLATES */
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
pair<iterator, bool> insert(const value_type& __obj)
{
pair<typename _Ht::iterator, bool> __p = _M_ht.insert_unique(__obj);
return pair<iterator,bool>(__p.first, __p.second);
}
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_unique(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_unique(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{_M_ht.insert_unique(__f, __l); }
#endif /*__STL_MEMBER_TEMPLATES */
pair<iterator, bool> insert_noresize(const value_type& __obj)
{
pair<typename _Ht::iterator, bool> __p =
_M_ht.insert_unique_noresize(__obj);
return pair<iterator, bool>(__p.first, __p.second);
}
iterator find(const key_type& __key) const { return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
pair<iterator, iterator> equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
public:
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator!=(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2) {
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline void
swap(hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
__hs1.swap(__hs2);
}
#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */
// hash_multiset和hash_set实现上的唯一差别在于,前者的元素插入操作采用底层机制hashtable的insert_equal(),后者则是采用insert_unique()。
template <class _Value, class _HashFcn __STL_DEPENDENT_DEFAULT_TMPL(hash<_Value>), class _EqualKey __STL_DEPENDENT_DEFAULT_TMPL(equal_to<_Value>), class _Alloc = __STL_DEFAULT_ALLOCATOR(_Value) >
class hash_multiset;
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2);
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_multiset
{
// requirements:
__STL_CLASS_REQUIRES(_Value, _Assignable);
__STL_CLASS_UNARY_FUNCTION_CHECK(_HashFcn, size_t, _Value);
__STL_CLASS_BINARY_FUNCTION_CHECK(_EqualKey, bool, _Value, _Value);
private:
typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
_EqualKey, _Alloc> _Ht;
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::const_pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::const_reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::const_iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
hash_multiset()
: _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_multiset(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_multiset(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#else
hash_multiset(const value_type* __f, const value_type* __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#endif /*__STL_MEMBER_TEMPLATES */
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); }
#ifdef __STL_MEMBER_TEMPLATES
template <class _Val, class _HF, class _EqK, class _Al>
friend bool operator== (const hash_multiset<_Val, _HF, _EqK, _Al>&,
const hash_multiset<_Val, _HF, _EqK, _Al>&);
#else /* __STL_MEMBER_TEMPLATES */
friend bool __STD_QUALIFIER
operator== __STL_NULL_TMPL_ARGS (const hash_multiset&,const hash_multiset&);
#endif /* __STL_MEMBER_TEMPLATES */
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
iterator insert(const value_type& __obj)
{ return _M_ht.insert_equal(__obj); }
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_equal(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_equal(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{ _M_ht.insert_equal(__f, __l); }
#endif /*__STL_MEMBER_TEMPLATES */
iterator insert_noresize(const value_type& __obj)
{ return _M_ht.insert_equal_noresize(__obj); }
iterator find(const key_type& __key) const { return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
pair<iterator, iterator> equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
public:
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator!=(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline void
swap(hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
__hs1.swap(__hs2);
}
#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */
// Specialization of insert_iterator so that it will work for hash_set
// and hash_multiset.
#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class insert_iterator<hash_set<_Value, _HashFcn, _EqualKey, _Alloc> > {
protected:
typedef hash_set<_Value, _HashFcn, _EqualKey, _Alloc> _Container;
_Container* container;
public:
typedef _Container container_type;
typedef output_iterator_tag iterator_category;
typedef void value_type;
typedef void difference_type;
typedef void pointer;
typedef void reference;
insert_iterator(_Container& __x) : container(&__x) {}
insert_iterator(_Container& __x, typename _Container::iterator)
: container(&__x) {}
insert_iterator<_Container>&
operator=(const typename _Container::value_type& __value) {
container->insert(__value);
return *this;
}
insert_iterator<_Container>& operator*() { return *this; }
insert_iterator<_Container>& operator++() { return *this; }
insert_iterator<_Container>& operator++(int) { return *this; }
};
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class insert_iterator<hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> > {
protected:
typedef hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> _Container;
_Container* container;
typename _Container::iterator iter;
public:
typedef _Container container_type;
typedef output_iterator_tag iterator_category;
typedef void value_type;
typedef void difference_type;
typedef void pointer;
typedef void reference;
insert_iterator(_Container& __x) : container(&__x) {}
insert_iterator(_Container& __x, typename _Container::iterator)
: container(&__x) {}
insert_iterator<_Container>&
operator=(const typename _Container::value_type& __value) {
container->insert(__value);
return *this;
}
insert_iterator<_Container>& operator*() { return *this; }
insert_iterator<_Container>& operator++() { return *this; }
insert_iterator<_Container>& operator++(int) { return *this; }
};
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#pragma reset woff 1375
#endif
__STL_END_NAMESPACE
#endif /* __SGI_STL_INTERNAL_HASH_SET_H */
// Local Variables:
// mode:C++
// End:
| [
"guangkuo_527@126.com"
] | guangkuo_527@126.com |
d664f9f3c9b689d6299ef8c23694fb4c915fbe74 | 24ed8f7a35ae9450e29c5c7a5631a55403489189 | /src/test/mempool_tests.cpp | d8972c8f24ae703d046e0c7bfd2157c22545055f | [
"MIT"
] | permissive | wavicom/wavi | fa07e8f3c4a4794fdccb4b43b2128c15a95dbac2 | 4cc6151d4dee36f809de81f0edb6d1c803412ec5 | refs/heads/master | 2020-03-23T14:22:42.293688 | 2018-08-02T19:42:06 | 2018-08-02T19:42:06 | 141,672,210 | 0 | 1 | MIT | 2018-07-20T06:24:24 | 2018-07-20T06:24:23 | null | UTF-8 | C++ | false | false | 19,713 | cpp | // Copyright (c) 2011-2015 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 "txmempool.h"
#include "util.h"
#include "test/test_wavi.h"
#include <boost/test/unit_test.hpp>
#include <list>
#include <vector>
BOOST_FIXTURE_TEST_SUITE(mempool_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(MempoolRemoveTest)
{
// Test CTxMemPool::remove functionality
TestMemPoolEntryHelper entry;
// Parent transaction with three children,
// and three grand-children:
CMutableTransaction txParent;
txParent.vin.resize(1);
txParent.vin[0].scriptSig = CScript() << OP_11;
txParent.vout.resize(3);
for (int i = 0; i < 3; i++)
{
txParent.vout[i].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
txParent.vout[i].nValue = 33000LL;
}
CMutableTransaction txChild[3];
for (int i = 0; i < 3; i++)
{
txChild[i].vin.resize(1);
txChild[i].vin[0].scriptSig = CScript() << OP_11;
txChild[i].vin[0].prevout.hash = txParent.GetHash();
txChild[i].vin[0].prevout.n = i;
txChild[i].vout.resize(1);
txChild[i].vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
txChild[i].vout[0].nValue = 11000LL;
}
CMutableTransaction txGrandChild[3];
for (int i = 0; i < 3; i++)
{
txGrandChild[i].vin.resize(1);
txGrandChild[i].vin[0].scriptSig = CScript() << OP_11;
txGrandChild[i].vin[0].prevout.hash = txChild[i].GetHash();
txGrandChild[i].vin[0].prevout.n = 0;
txGrandChild[i].vout.resize(1);
txGrandChild[i].vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
txGrandChild[i].vout[0].nValue = 11000LL;
}
CTxMemPool testPool(CFeeRate(0));
std::list<CTransaction> removed;
// Nothing in pool, remove should do nothing:
testPool.remove(txParent, removed, true);
BOOST_CHECK_EQUAL(removed.size(), 0);
// Just the parent:
testPool.addUnchecked(txParent.GetHash(), entry.FromTx(txParent));
testPool.remove(txParent, removed, true);
BOOST_CHECK_EQUAL(removed.size(), 1);
removed.clear();
// Parent, children, grandchildren:
testPool.addUnchecked(txParent.GetHash(), entry.FromTx(txParent));
for (int i = 0; i < 3; i++)
{
testPool.addUnchecked(txChild[i].GetHash(), entry.FromTx(txChild[i]));
testPool.addUnchecked(txGrandChild[i].GetHash(), entry.FromTx(txGrandChild[i]));
}
// Remove Child[0], GrandChild[0] should be removed:
testPool.remove(txChild[0], removed, true);
BOOST_CHECK_EQUAL(removed.size(), 2);
removed.clear();
// ... make sure grandchild and child are gone:
testPool.remove(txGrandChild[0], removed, true);
BOOST_CHECK_EQUAL(removed.size(), 0);
testPool.remove(txChild[0], removed, true);
BOOST_CHECK_EQUAL(removed.size(), 0);
// Remove parent, all children/grandchildren should go:
testPool.remove(txParent, removed, true);
BOOST_CHECK_EQUAL(removed.size(), 5);
BOOST_CHECK_EQUAL(testPool.size(), 0);
removed.clear();
// Add children and grandchildren, but NOT the parent (simulate the parent being in a block)
for (int i = 0; i < 3; i++)
{
testPool.addUnchecked(txChild[i].GetHash(), entry.FromTx(txChild[i]));
testPool.addUnchecked(txGrandChild[i].GetHash(), entry.FromTx(txGrandChild[i]));
}
// Now remove the parent, as might happen if a block-re-org occurs but the parent cannot be
// put into the mempool (maybe because it is non-standard):
testPool.remove(txParent, removed, true);
BOOST_CHECK_EQUAL(removed.size(), 6);
BOOST_CHECK_EQUAL(testPool.size(), 0);
removed.clear();
}
template<int index>
void CheckSort(CTxMemPool &pool, std::vector<std::string> &sortedOrder)
{
BOOST_CHECK_EQUAL(pool.size(), sortedOrder.size());
typename CTxMemPool::indexed_transaction_set::nth_index<index>::type::iterator it = pool.mapTx.get<index>().begin();
int count=0;
for (; it != pool.mapTx.get<index>().end(); ++it, ++count) {
BOOST_CHECK_EQUAL(it->GetTx().GetHash().ToString(), sortedOrder[count]);
}
}
BOOST_AUTO_TEST_CASE(MempoolIndexingTest)
{
CTxMemPool pool(CFeeRate(0));
TestMemPoolEntryHelper entry;
entry.hadNoDependencies = true;
/* 3rd highest fee */
CMutableTransaction tx1 = CMutableTransaction();
tx1.vout.resize(1);
tx1.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx1.vout[0].nValue = 10 * COIN;
pool.addUnchecked(tx1.GetHash(), entry.Fee(10000LL).Priority(10.0).FromTx(tx1));
/* highest fee */
CMutableTransaction tx2 = CMutableTransaction();
tx2.vout.resize(1);
tx2.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx2.vout[0].nValue = 2 * COIN;
pool.addUnchecked(tx2.GetHash(), entry.Fee(20000LL).Priority(9.0).FromTx(tx2));
/* lowest fee */
CMutableTransaction tx3 = CMutableTransaction();
tx3.vout.resize(1);
tx3.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx3.vout[0].nValue = 5 * COIN;
pool.addUnchecked(tx3.GetHash(), entry.Fee(0LL).Priority(100.0).FromTx(tx3));
/* 2nd highest fee */
CMutableTransaction tx4 = CMutableTransaction();
tx4.vout.resize(1);
tx4.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx4.vout[0].nValue = 6 * COIN;
pool.addUnchecked(tx4.GetHash(), entry.Fee(15000LL).Priority(1.0).FromTx(tx4));
/* equal fee rate to tx1, but newer */
CMutableTransaction tx5 = CMutableTransaction();
tx5.vout.resize(1);
tx5.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx5.vout[0].nValue = 11 * COIN;
entry.nTime = 1;
entry.dPriority = 10.0;
pool.addUnchecked(tx5.GetHash(), entry.Fee(10000LL).FromTx(tx5));
BOOST_CHECK_EQUAL(pool.size(), 5);
std::vector<std::string> sortedOrder;
sortedOrder.resize(5);
sortedOrder[0] = tx3.GetHash().ToString(); // 0
sortedOrder[1] = tx5.GetHash().ToString(); // 10000
sortedOrder[2] = tx1.GetHash().ToString(); // 10000
sortedOrder[3] = tx4.GetHash().ToString(); // 15000
sortedOrder[4] = tx2.GetHash().ToString(); // 20000
CheckSort<1>(pool, sortedOrder);
/* low fee but with high fee child */
/* tx6 -> tx7 -> tx8, tx9 -> tx10 */
CMutableTransaction tx6 = CMutableTransaction();
tx6.vout.resize(1);
tx6.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx6.vout[0].nValue = 20 * COIN;
pool.addUnchecked(tx6.GetHash(), entry.Fee(0LL).FromTx(tx6));
BOOST_CHECK_EQUAL(pool.size(), 6);
// Check that at this point, tx6 is sorted low
sortedOrder.insert(sortedOrder.begin(), tx6.GetHash().ToString());
CheckSort<1>(pool, sortedOrder);
CTxMemPool::setEntries setAncestors;
setAncestors.insert(pool.mapTx.find(tx6.GetHash()));
CMutableTransaction tx7 = CMutableTransaction();
tx7.vin.resize(1);
tx7.vin[0].prevout = COutPoint(tx6.GetHash(), 0);
tx7.vin[0].scriptSig = CScript() << OP_11;
tx7.vout.resize(2);
tx7.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx7.vout[0].nValue = 10 * COIN;
tx7.vout[1].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx7.vout[1].nValue = 1 * COIN;
CTxMemPool::setEntries setAncestorsCalculated;
std::string dummy;
BOOST_CHECK_EQUAL(pool.CalculateMemPoolAncestors(entry.Fee(2000000LL).FromTx(tx7), setAncestorsCalculated, 100, 1000000, 1000, 1000000, dummy), true);
BOOST_CHECK(setAncestorsCalculated == setAncestors);
pool.addUnchecked(tx7.GetHash(), entry.FromTx(tx7), setAncestors);
BOOST_CHECK_EQUAL(pool.size(), 7);
// Now tx6 should be sorted higher (high fee child): tx7, tx6, tx2, ...
sortedOrder.erase(sortedOrder.begin());
sortedOrder.push_back(tx6.GetHash().ToString());
sortedOrder.push_back(tx7.GetHash().ToString());
CheckSort<1>(pool, sortedOrder);
/* low fee child of tx7 */
CMutableTransaction tx8 = CMutableTransaction();
tx8.vin.resize(1);
tx8.vin[0].prevout = COutPoint(tx7.GetHash(), 0);
tx8.vin[0].scriptSig = CScript() << OP_11;
tx8.vout.resize(1);
tx8.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx8.vout[0].nValue = 10 * COIN;
setAncestors.insert(pool.mapTx.find(tx7.GetHash()));
pool.addUnchecked(tx8.GetHash(), entry.Fee(0LL).Time(2).FromTx(tx8), setAncestors);
// Now tx8 should be sorted low, but tx6/tx both high
sortedOrder.insert(sortedOrder.begin(), tx8.GetHash().ToString());
CheckSort<1>(pool, sortedOrder);
/* low fee child of tx7 */
CMutableTransaction tx9 = CMutableTransaction();
tx9.vin.resize(1);
tx9.vin[0].prevout = COutPoint(tx7.GetHash(), 1);
tx9.vin[0].scriptSig = CScript() << OP_11;
tx9.vout.resize(1);
tx9.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx9.vout[0].nValue = 1 * COIN;
pool.addUnchecked(tx9.GetHash(), entry.Fee(0LL).Time(3).FromTx(tx9), setAncestors);
// tx9 should be sorted low
BOOST_CHECK_EQUAL(pool.size(), 9);
sortedOrder.insert(sortedOrder.begin(), tx9.GetHash().ToString());
CheckSort<1>(pool, sortedOrder);
std::vector<std::string> snapshotOrder = sortedOrder;
setAncestors.insert(pool.mapTx.find(tx8.GetHash()));
setAncestors.insert(pool.mapTx.find(tx9.GetHash()));
/* tx10 depends on tx8 and tx9 and has a high fee*/
CMutableTransaction tx10 = CMutableTransaction();
tx10.vin.resize(2);
tx10.vin[0].prevout = COutPoint(tx8.GetHash(), 0);
tx10.vin[0].scriptSig = CScript() << OP_11;
tx10.vin[1].prevout = COutPoint(tx9.GetHash(), 0);
tx10.vin[1].scriptSig = CScript() << OP_11;
tx10.vout.resize(1);
tx10.vout[0].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
tx10.vout[0].nValue = 10 * COIN;
setAncestorsCalculated.clear();
BOOST_CHECK_EQUAL(pool.CalculateMemPoolAncestors(entry.Fee(200000LL).Time(4).FromTx(tx10), setAncestorsCalculated, 100, 1000000, 1000, 1000000, dummy), true);
BOOST_CHECK(setAncestorsCalculated == setAncestors);
pool.addUnchecked(tx10.GetHash(), entry.FromTx(tx10), setAncestors);
/**
* tx8 and tx9 should both now be sorted higher
* Final order after tx10 is added:
*
* tx3 = 0 (1)
* tx5 = 10000 (1)
* tx1 = 10000 (1)
* tx4 = 15000 (1)
* tx2 = 20000 (1)
* tx9 = 200k (2 txs)
* tx8 = 200k (2 txs)
* tx10 = 200k (1 tx)
* tx6 = 2.2M (5 txs)
* tx7 = 2.2M (4 txs)
*/
sortedOrder.erase(sortedOrder.begin(), sortedOrder.begin()+2); // take out tx9, tx8 from the beginning
sortedOrder.insert(sortedOrder.begin()+5, tx9.GetHash().ToString());
sortedOrder.insert(sortedOrder.begin()+6, tx8.GetHash().ToString());
sortedOrder.insert(sortedOrder.begin()+7, tx10.GetHash().ToString()); // tx10 is just before tx6
CheckSort<1>(pool, sortedOrder);
// there should be 10 transactions in the mempool
BOOST_CHECK_EQUAL(pool.size(), 10);
// Now try removing tx10 and verify the sort order returns to normal
std::list<CTransaction> removed;
pool.remove(pool.mapTx.find(tx10.GetHash())->GetTx(), removed, true);
CheckSort<1>(pool, snapshotOrder);
pool.remove(pool.mapTx.find(tx9.GetHash())->GetTx(), removed, true);
pool.remove(pool.mapTx.find(tx8.GetHash())->GetTx(), removed, true);
/* Now check the sort on the mining score index.
* Final order should be:
*
* tx7 (2M)
* tx2 (20k)
* tx4 (15000)
* tx1/tx5 (10000)
* tx3/6 (0)
* (Ties resolved by hash)
*/
sortedOrder.clear();
sortedOrder.push_back(tx7.GetHash().ToString());
sortedOrder.push_back(tx2.GetHash().ToString());
sortedOrder.push_back(tx4.GetHash().ToString());
if (tx1.GetHash() < tx5.GetHash()) {
sortedOrder.push_back(tx5.GetHash().ToString());
sortedOrder.push_back(tx1.GetHash().ToString());
} else {
sortedOrder.push_back(tx1.GetHash().ToString());
sortedOrder.push_back(tx5.GetHash().ToString());
}
if (tx3.GetHash() < tx6.GetHash()) {
sortedOrder.push_back(tx6.GetHash().ToString());
sortedOrder.push_back(tx3.GetHash().ToString());
} else {
sortedOrder.push_back(tx3.GetHash().ToString());
sortedOrder.push_back(tx6.GetHash().ToString());
}
CheckSort<3>(pool, sortedOrder);
}
BOOST_AUTO_TEST_CASE(MempoolSizeLimitTest)
{
CTxMemPool pool(CFeeRate(1000));
TestMemPoolEntryHelper entry;
entry.dPriority = 10.0;
CMutableTransaction tx1 = CMutableTransaction();
tx1.vin.resize(1);
tx1.vin[0].scriptSig = CScript() << OP_1;
tx1.vout.resize(1);
tx1.vout[0].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
tx1.vout[0].nValue = 10 * COIN;
pool.addUnchecked(tx1.GetHash(), entry.Fee(10000LL).FromTx(tx1, &pool));
CMutableTransaction tx2 = CMutableTransaction();
tx2.vin.resize(1);
tx2.vin[0].scriptSig = CScript() << OP_2;
tx2.vout.resize(1);
tx2.vout[0].scriptPubKey = CScript() << OP_2 << OP_EQUAL;
tx2.vout[0].nValue = 10 * COIN;
pool.addUnchecked(tx2.GetHash(), entry.Fee(5000LL).FromTx(tx2, &pool));
pool.TrimToSize(pool.DynamicMemoryUsage()); // should do nothing
BOOST_CHECK(pool.exists(tx1.GetHash()));
BOOST_CHECK(pool.exists(tx2.GetHash()));
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4); // should remove the lower-feerate transaction
BOOST_CHECK(pool.exists(tx1.GetHash()));
BOOST_CHECK(!pool.exists(tx2.GetHash()));
pool.addUnchecked(tx2.GetHash(), entry.FromTx(tx2, &pool));
CMutableTransaction tx3 = CMutableTransaction();
tx3.vin.resize(1);
tx3.vin[0].prevout = COutPoint(tx2.GetHash(), 0);
tx3.vin[0].scriptSig = CScript() << OP_2;
tx3.vout.resize(1);
tx3.vout[0].scriptPubKey = CScript() << OP_3 << OP_EQUAL;
tx3.vout[0].nValue = 10 * COIN;
pool.addUnchecked(tx3.GetHash(), entry.Fee(20000LL).FromTx(tx3, &pool));
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4); // tx3 should pay for tx2 (CPFP)
BOOST_CHECK(!pool.exists(tx1.GetHash()));
BOOST_CHECK(pool.exists(tx2.GetHash()));
BOOST_CHECK(pool.exists(tx3.GetHash()));
pool.TrimToSize(::GetSerializeSize(CTransaction(tx1), SER_NETWORK, PROTOCOL_VERSION)); // mempool is limited to tx1's size in memory usage, so nothing fits
BOOST_CHECK(!pool.exists(tx1.GetHash()));
BOOST_CHECK(!pool.exists(tx2.GetHash()));
BOOST_CHECK(!pool.exists(tx3.GetHash()));
CFeeRate maxFeeRateRemoved(25000, ::GetSerializeSize(CTransaction(tx3), SER_NETWORK, PROTOCOL_VERSION) + ::GetSerializeSize(CTransaction(tx2), SER_NETWORK, PROTOCOL_VERSION));
BOOST_CHECK_EQUAL(pool.GetMinFee(1).GetFeePerK(), maxFeeRateRemoved.GetFeePerK() + 1000);
CMutableTransaction tx4 = CMutableTransaction();
tx4.vin.resize(2);
tx4.vin[0].prevout.SetNull();
tx4.vin[0].scriptSig = CScript() << OP_4;
tx4.vin[1].prevout.SetNull();
tx4.vin[1].scriptSig = CScript() << OP_4;
tx4.vout.resize(2);
tx4.vout[0].scriptPubKey = CScript() << OP_4 << OP_EQUAL;
tx4.vout[0].nValue = 10 * COIN;
tx4.vout[1].scriptPubKey = CScript() << OP_4 << OP_EQUAL;
tx4.vout[1].nValue = 10 * COIN;
CMutableTransaction tx5 = CMutableTransaction();
tx5.vin.resize(2);
tx5.vin[0].prevout = COutPoint(tx4.GetHash(), 0);
tx5.vin[0].scriptSig = CScript() << OP_4;
tx5.vin[1].prevout.SetNull();
tx5.vin[1].scriptSig = CScript() << OP_5;
tx5.vout.resize(2);
tx5.vout[0].scriptPubKey = CScript() << OP_5 << OP_EQUAL;
tx5.vout[0].nValue = 10 * COIN;
tx5.vout[1].scriptPubKey = CScript() << OP_5 << OP_EQUAL;
tx5.vout[1].nValue = 10 * COIN;
CMutableTransaction tx6 = CMutableTransaction();
tx6.vin.resize(2);
tx6.vin[0].prevout = COutPoint(tx4.GetHash(), 1);
tx6.vin[0].scriptSig = CScript() << OP_4;
tx6.vin[1].prevout.SetNull();
tx6.vin[1].scriptSig = CScript() << OP_6;
tx6.vout.resize(2);
tx6.vout[0].scriptPubKey = CScript() << OP_6 << OP_EQUAL;
tx6.vout[0].nValue = 10 * COIN;
tx6.vout[1].scriptPubKey = CScript() << OP_6 << OP_EQUAL;
tx6.vout[1].nValue = 10 * COIN;
CMutableTransaction tx7 = CMutableTransaction();
tx7.vin.resize(2);
tx7.vin[0].prevout = COutPoint(tx5.GetHash(), 0);
tx7.vin[0].scriptSig = CScript() << OP_5;
tx7.vin[1].prevout = COutPoint(tx6.GetHash(), 0);
tx7.vin[1].scriptSig = CScript() << OP_6;
tx7.vout.resize(2);
tx7.vout[0].scriptPubKey = CScript() << OP_7 << OP_EQUAL;
tx7.vout[0].nValue = 10 * COIN;
tx7.vout[1].scriptPubKey = CScript() << OP_7 << OP_EQUAL;
tx7.vout[1].nValue = 10 * COIN;
pool.addUnchecked(tx4.GetHash(), entry.Fee(7000LL).FromTx(tx4, &pool));
pool.addUnchecked(tx5.GetHash(), entry.Fee(1000LL).FromTx(tx5, &pool));
pool.addUnchecked(tx6.GetHash(), entry.Fee(1100LL).FromTx(tx6, &pool));
pool.addUnchecked(tx7.GetHash(), entry.Fee(9000LL).FromTx(tx7, &pool));
// we only require this remove, at max, 2 txn, because its not clear what we're really optimizing for aside from that
pool.TrimToSize(pool.DynamicMemoryUsage() - 1);
BOOST_CHECK(pool.exists(tx4.GetHash()));
BOOST_CHECK(pool.exists(tx6.GetHash()));
BOOST_CHECK(!pool.exists(tx7.GetHash()));
if (!pool.exists(tx5.GetHash()))
pool.addUnchecked(tx5.GetHash(), entry.Fee(1000LL).FromTx(tx5, &pool));
pool.addUnchecked(tx7.GetHash(), entry.Fee(9000LL).FromTx(tx7, &pool));
pool.TrimToSize(pool.DynamicMemoryUsage() / 2); // should maximize mempool size by only removing 5/7
BOOST_CHECK(pool.exists(tx4.GetHash()));
BOOST_CHECK(!pool.exists(tx5.GetHash()));
BOOST_CHECK(pool.exists(tx6.GetHash()));
BOOST_CHECK(!pool.exists(tx7.GetHash()));
pool.addUnchecked(tx5.GetHash(), entry.Fee(1000LL).FromTx(tx5, &pool));
pool.addUnchecked(tx7.GetHash(), entry.Fee(9000LL).FromTx(tx7, &pool));
std::vector<CTransaction> vtx;
std::list<CTransaction> conflicts;
SetMockTime(42);
SetMockTime(42 + CTxMemPool::ROLLING_FEE_HALFLIFE);
BOOST_CHECK_EQUAL(pool.GetMinFee(1).GetFeePerK(), maxFeeRateRemoved.GetFeePerK() + 1000);
// ... we should keep the same min fee until we get a block
pool.removeForBlock(vtx, 1, conflicts);
SetMockTime(42 + 2*CTxMemPool::ROLLING_FEE_HALFLIFE);
BOOST_CHECK_EQUAL(pool.GetMinFee(1).GetFeePerK(), (maxFeeRateRemoved.GetFeePerK() + 1000)/2);
// ... then feerate should drop 1/2 each halflife
SetMockTime(42 + 2*CTxMemPool::ROLLING_FEE_HALFLIFE + CTxMemPool::ROLLING_FEE_HALFLIFE/2);
BOOST_CHECK_EQUAL(pool.GetMinFee(pool.DynamicMemoryUsage() * 5 / 2).GetFeePerK(), (maxFeeRateRemoved.GetFeePerK() + 1000)/4);
// ... with a 1/2 halflife when mempool is < 1/2 its target size
SetMockTime(42 + 2*CTxMemPool::ROLLING_FEE_HALFLIFE + CTxMemPool::ROLLING_FEE_HALFLIFE/2 + CTxMemPool::ROLLING_FEE_HALFLIFE/4);
BOOST_CHECK_EQUAL(pool.GetMinFee(pool.DynamicMemoryUsage() * 9 / 2).GetFeePerK(), (maxFeeRateRemoved.GetFeePerK() + 1000)/8);
// ... with a 1/4 halflife when mempool is < 1/4 its target size
SetMockTime(42 + 7*CTxMemPool::ROLLING_FEE_HALFLIFE + CTxMemPool::ROLLING_FEE_HALFLIFE/2 + CTxMemPool::ROLLING_FEE_HALFLIFE/4);
BOOST_CHECK_EQUAL(pool.GetMinFee(1).GetFeePerK(), 1000);
// ... but feerate should never drop below 1000
SetMockTime(42 + 8*CTxMemPool::ROLLING_FEE_HALFLIFE + CTxMemPool::ROLLING_FEE_HALFLIFE/2 + CTxMemPool::ROLLING_FEE_HALFLIFE/4);
BOOST_CHECK_EQUAL(pool.GetMinFee(1).GetFeePerK(), 0);
// ... unless it has gone all the way to 0 (after getting past 1000/2)
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"gekiganga77@hotmail.com"
] | gekiganga77@hotmail.com |
2b1de81a3fa1370c0d1500246cb12423c86adb79 | 76be4e25a6e8625e3d45f7f92db84dbdd19c69c1 | /device/se/x8/libsensors/LightSensor.cpp | b17424bc6400fbf317806ac8fbc3855515c1b3fb | [
"Apache-2.0"
] | permissive | nippongo/FreeXperia | 7c957d9065218e870ecd211b49d63642834c6886 | 5f6950c9b84f290d4996e51954d1720dc7fd7135 | refs/heads/master | 2021-07-23T15:21:41.106037 | 2011-04-12T18:56:32 | 2011-04-12T18:56:32 | 1,613,056 | 2 | 0 | null | 2021-01-18T21:48:31 | 2011-04-14T06:49:24 | C | UTF-8 | C++ | false | false | 3,163 | cpp | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <linux/lightsensor.h>
#include <cutils/log.h>
#include "LightSensor.h"
/*****************************************************************************/
LightSensor::LightSensor()
: SensorBase(LS_DEVICE_NAME, "lm3530"),
mInputReader(4),
mHasPendingEvent(false)
{
mPendingEvent.version = sizeof(sensors_event_t);
mPendingEvent.sensor = ID_L;
mPendingEvent.type = SENSOR_TYPE_LIGHT;
memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));
setInitialState();
}
LightSensor::~LightSensor() {
}
int LightSensor::setInitialState() {
struct input_absinfo absinfo;
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_LIGHT), &absinfo)) {
mPendingEvent.light = absinfo.value;
mHasPendingEvent = true;
}
return 0;
}
int LightSensor::enable(int32_t, int en) {
if(en) {
setInitialState();
}
return 0;
}
bool LightSensor::hasPendingEvents() const {
return mHasPendingEvent;
}
int LightSensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;
if (mHasPendingEvent) {
mHasPendingEvent = false;
mPendingEvent.timestamp = getTimestamp();
*data = mPendingEvent;
return 1;
}
ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;
int numEventReceived = 0;
input_event const* event;
while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_LED) { // light sensor 1
if (event->code == EVENT_TYPE_LIGHT) {
mPendingEvent.light = event->value;
}
} else if (type == EV_MSC) { // light sensor 2
/* Light sensor 2 seems to put out lower lux values than
* light sensor 1, and I can't decide which is more "accurate",
* so for now just disabling #2
if (event->code == EVENT_TYPE_LIGHT2) {
mPendingEvent.light = event->value;
}
*/
} else if (type == EV_SYN) {
mPendingEvent.timestamp = timevalToNano(event->time);
*data++ = mPendingEvent;
count--;
numEventReceived++;
} else {
LOGE("LightSensor: unknown event (type=%d, code=%d)",
type, event->code);
}
mInputReader.next();
}
return numEventReceived;
}
| [
"jerpelea@gmail.com"
] | jerpelea@gmail.com |
1e09dbde5afdb22ddd80803fc362b92280a191c2 | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Modules/Core/SpatialObjects/include/itkSpatialObjectPoint.hxx | 1e7f8c6092563166fa7b1dc23799e679a8330644 | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"... | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 5,884 | hxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkSpatialObjectPoint_hxx
#define itkSpatialObjectPoint_hxx
#include "itkSpatialObjectPoint.h"
namespace itk
{
/** Constructor */
template< unsigned int TPointDimension >
SpatialObjectPoint< TPointDimension >
::SpatialObjectPoint(void)
{
m_ID = -1;
m_Color.SetRed(1.0); // red by default
m_Color.SetGreen(0);
m_Color.SetBlue(0);
m_Color.SetAlpha(1);
for ( unsigned int i = 0; i < TPointDimension; i++ )
{
m_X[i] = 0;
}
}
/** Destructor */
template< unsigned int TPointDimension >
SpatialObjectPoint< TPointDimension >
::~SpatialObjectPoint(void)
{}
/** Return the color of the point */
template< unsigned int TPointDimension >
const typename SpatialObjectPoint< TPointDimension >::PixelType &
SpatialObjectPoint< TPointDimension >
::GetColor(void) const
{
return m_Color;
}
/** Set the color of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetColor(const PixelType & color)
{
m_Color = color;
}
/** Set the color of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetColor(float r, float g, float b, float a)
{
m_Color.SetRed(r);
m_Color.SetGreen(g);
m_Color.SetBlue(b);
m_Color.SetAlpha(a);
}
/** Set the red channel of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetRed(float r)
{
m_Color.SetRed(r);
}
/** Return the red channel of the point */
template< unsigned int TPointDimension >
float
SpatialObjectPoint< TPointDimension >
::GetRed(void) const
{
return m_Color.GetRed();
}
/** Set the green channel of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetGreen(float g)
{
m_Color.SetGreen(g);
}
/** Return the green channel of the point */
template< unsigned int TPointDimension >
float
SpatialObjectPoint< TPointDimension >
::GetGreen(void) const
{
return m_Color.GetGreen();
}
/** Set the blue channel of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetBlue(float b)
{
m_Color.SetBlue(b);
}
/** Return the blue channel of the point */
template< unsigned int TPointDimension >
float
SpatialObjectPoint< TPointDimension >
::GetBlue(void) const
{
return m_Color.GetBlue();
}
/** Set the alpha value of the point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetAlpha(float a)
{
m_Color.SetAlpha(a);
}
/** Return the alpha value of the point */
template< unsigned int TPointDimension >
float
SpatialObjectPoint< TPointDimension >
::GetAlpha(void) const
{
return m_Color.GetAlpha();
}
/** Set the Identification number of a point */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetID(const int newID)
{
m_ID = newID;
}
/** Get the Identification number of a point */
template< unsigned int TPointDimension >
int
SpatialObjectPoint< TPointDimension >
::GetID(void) const
{
return m_ID;
}
/** Return the position of a point */
template< unsigned int TPointDimension >
const typename SpatialObjectPoint< TPointDimension >::PointType &
SpatialObjectPoint< TPointDimension >
::GetPosition(void) const
{
return m_X;
}
/** Set the position : n-D case */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetPosition(const PointType & newX)
{
m_X = newX;
}
/** Set the position : 3D case */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetPosition(const double x0, const double x1, const double x2)
{
m_X[0] = x0;
m_X[1] = x1;
m_X[2] = x2;
}
/** Set the position : 2D case */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::SetPosition(const double x0, const double x1)
{
m_X[0] = x0;
m_X[1] = x1;
}
/** Copy a point to another point */
template< unsigned int TPointDimension >
typename SpatialObjectPoint< TPointDimension >::Self &
SpatialObjectPoint< TPointDimension >
::operator=(const SpatialObjectPoint & rhs)
{
m_ID = rhs.m_ID;
m_X = rhs.m_X;
m_Color = rhs.m_Color;
return *this;
}
/** PrintSelfMethod */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::Print(std::ostream & os) const
{
this->PrintSelf(os, 3);
}
/** PrintSelfMethod */
template< unsigned int TPointDimension >
void
SpatialObjectPoint< TPointDimension >
::PrintSelf(std::ostream & os, Indent indent) const
{
os << indent << "RGBA: " << m_Color.GetRed() << " ";
os << m_Color.GetGreen() << " ";
os << m_Color.GetBlue() << " ";
os << m_Color.GetAlpha() << std::endl;
os << indent << "Position: ";
for ( unsigned int i = 1; i < TPointDimension; i++ )
{
os << m_X[i - 1] << ",";
}
os << m_X[TPointDimension - 1] << std::endl;
}
} // end namespace itk
#endif
| [
"ruizhi@csail.mit.edu"
] | ruizhi@csail.mit.edu |
ee31f78848ef711aab7b0b3cf3ac8005bce684ca | 2ee0679557c5705bfcec35dd3dc9e91668ec87e7 | /Arrays/00prob2.cpp | 76cd74f0ef3c22dcd39cce282cb9e204cb7e82dc | [] | no_license | Aryan22g/Data-Structures-and-Algorithms | 7488036a4a271a874b3c3e166d044048933f7dcb | fdc65cef30bd046c5b63c99c0607068018d6d450 | refs/heads/master | 2023-07-13T07:01:45.449841 | 2021-08-27T12:57:15 | 2021-08-27T12:57:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
int target;
cin>>target;
//brute force approach O(n^3)
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
for(int k=j+1; k<n; k++){
int sum=arr[i]+arr[j]+arr[k];
if(sum==target) cout<<i<<" "<<j<<" "<<k<<endl;
}
}
}
} | [
"22garyan@gmail.com"
] | 22garyan@gmail.com |
22c05833c1cccf0046ca2d0f4b598aeae2189d60 | 326a6f5c3892ac4bd042e57281289983a239d94d | /prioritysettingdialog.h | 030a738cda2cff4729b416ff3b1e2893adf01244 | [] | no_license | ljianhui/TaskManager | 356d8a927af0d067a9810bd0f26aeb7bb8ab5122 | c84aa1f255fec1aa16bad1f8dfa84e525118ceaf | refs/heads/master | 2020-05-22T12:34:43.664081 | 2015-07-08T14:37:37 | 2015-07-08T14:37:37 | 38,697,293 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #ifndef PRIORITYSETTINGDIALOG_H
#define PRIORITYSETTINGDIALOG_H
#include <QDialog>
namespace Ui {
class PrioritySettingDialog;
}
class Process;
class PrioritySettingDialog : public QDialog
{
Q_OBJECT
public:
explicit PrioritySettingDialog(const Process *p, QWidget *parent = 0);
~PrioritySettingDialog();
private slots:
void adjustNice(int nice);
void setNice();
private:
void initViews();
private:
Ui::PrioritySettingDialog *ui;
const Process *mProcess;
int mNice;
};
#endif // PRIORITYSETTINGDIALOG_H
| [
"ljianhui2012@163.com"
] | ljianhui2012@163.com |
493abdccd312aee3da3e2279b589052f34eee854 | bba8bb04425c9b166323cb5a831c94643cf62b97 | /Source/Voxel/Public/VoxelSpawners/VoxelSpawnerConfig.h | 2d1afae92dfc2134ead422b0a0819ce1be24e504 | [
"MIT"
] | permissive | jacobcoughenour/VoxelPlugin | 2cf2e2195209285fbd8a589d8f994f7caaa651c2 | fc2ddcc0d3bd4424a9be73c3ada70c4c5c158184 | refs/heads/master | 2022-11-11T04:16:35.908916 | 2020-07-04T11:12:38 | 2020-07-04T11:12:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,521 | h | // Copyright 2020 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "VoxelMinimal.h"
#include "VoxelConfigEnums.h"
#include "VoxelSpawnerConfig.generated.h"
class UVoxelSpawner;
class FVoxelWorldGeneratorInstance;
class UVoxelSpawnerConfig;
class UVoxelSpawnerOutputsConfig;
USTRUCT()
struct FVoxelSpawnerOutputName
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "Voxel")
FName Name;
FVoxelSpawnerOutputName() = default;
template<typename... TArgs>
FVoxelSpawnerOutputName(TArgs... Args)
: Name(Forward<TArgs>(Args)...)
{
}
inline operator FName() const
{
return Name;
}
inline bool IsNone() const
{
return Name.IsNone();
}
};
UENUM()
enum class EVoxelSpawnerDensityType : uint8
{
// Use a constant as density
Constant,
// Use a generator output
GeneratorOutput,
// Use one of the material RGBA channels. Only for Ray Spawners.
MaterialRGBA,
// Use the material UV channels. Only for Ray Spawners.
MaterialUVs,
// Use a five way blend strength. Only for Ray Spawners.
MaterialFiveWayBlend,
// Use a single index channel. Only for Ray Spawners.
SingleIndex,
// Use a multi index channel. Only for Ray Spawners.
MultiIndex,
// Use the voxel foliage channels. Only for Ray Spawners.
Foliage
};
UENUM()
enum class EVoxelSpawnerUVAxis
{
U,
V
};
UENUM()
enum class EVoxelSpawnerDensityTransform
{
Identity UMETA(DisplayName = "None"),
OneMinus UMETA(DisplayName = "1 - X"),
};
USTRUCT()
struct FVoxelSpawnerDensity
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "Voxel")
EVoxelSpawnerDensityType Type = EVoxelSpawnerDensityType::Constant;
UPROPERTY(EditAnywhere, Category = "Voxel")
float Constant = 1.f;
// Your world generator needs to have a float output named like this
UPROPERTY(EditAnywhere, Category = "Voxel")
FVoxelSpawnerOutputName GeneratorOutputName;
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "RGBA Channel"))
EVoxelRGBA RGBAChannel;
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "UV Channel", ClampMin = 0, ClampMax = 3))
int32 UVChannel;
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "UV Axis"))
EVoxelSpawnerUVAxis UVAxis;
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (ClampMin = 0, ClampMax = 4))
int32 FiveWayBlendChannel = 0;
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (ClampMin = 0, ClampMax = 255))
TArray<int32> SingleIndexChannels = { 0 };
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (ClampMin = 0, ClampMax = 255))
TArray<int32> MultiIndexChannels = { 0 };
UPROPERTY(EditAnywhere, Category = "Voxel")
EVoxelRGBA FoliageChannel;
// Transform to apply to the density
UPROPERTY(EditAnywhere, Category = "Voxel")
EVoxelSpawnerDensityTransform Transform = EVoxelSpawnerDensityTransform::Identity;
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
UENUM()
enum class EVoxelSpawnerConfigElementRandomGenerator : uint8
{
// Evenly distributed points
Sobol,
// More uneven points than Sobol. Unreal uses Halton to spawn grass in the default Landscape system
Halton
};
UENUM()
enum class EVoxelSpawnerType
{
// Will line trace the voxel geometry to find spawning locations. Works with any kind of world/shapes
Ray,
// These spawners uses a height output from the world generator to spawn, allowing for large spawn distance.
Height
};
USTRUCT()
struct FVoxelSpawnerConfigSpawnerSeed
{
GENERATED_BODY()
// Name referencing to the voxel world seed map
UPROPERTY(EditAnywhere, Category = "Voxel")
FName SeedName = "FoliageSeed";
// Seed if SeedName is not found in the voxel world seed map
UPROPERTY(EditAnywhere, Category = "Voxel")
uint32 DefaultSeed = 1337;
};
USTRUCT()
struct FVoxelSpawnerConfigSpawner
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "Voxel")
UVoxelSpawner* Spawner = nullptr;
UPROPERTY(EditAnywhere, Category = "Voxel")
EVoxelSpawnerType SpawnerType = EVoxelSpawnerType::Ray;
public:
UPROPERTY(EditAnywhere, Category = "Voxel")
FVoxelSpawnerDensity Density;
// Final Density = Density * DensityMultiplier. Use this to eg paint an Erase Foliage channel.
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "Density Multiplier"))
FVoxelSpawnerDensity DensityMultiplier_RayOnly;
// The name of the custom graph output used to determine the height
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "Height Graph Output Name"))
FVoxelSpawnerOutputName HeightGraphOutputName_HeightOnly = "Height";
public:
// Chunk size, affects the LOD if ray spawner
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "Chunk Size"))
uint32 ChunkSize_EditorOnly = 32;
// The LOD of the mesh to trace rays against
// High LOD = faster but less precise
UPROPERTY(VisibleAnywhere, Category = "Voxel")
int32 LOD = 0;
// Generation distance in voxels
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "Generation Distance"))
uint32 GenerationDistanceInVoxels_EditorOnly = 0;
UPROPERTY(VisibleAnywhere, Category = "Voxel")
int32 GenerationDistanceInChunks = 2;
public:
// Whether to save the instances that are removed
// If false will also respawn instances if they are out of range
UPROPERTY(EditAnywhere, Category = "Voxel")
bool bSave = true;
// If false, instances that are out of range will be despawned. If true, they will stay forever.
UPROPERTY(EditAnywhere, Category = "Voxel")
bool bDoNotDespawn = false;
// Seed for this spawner. Note that changing this is not required to get unique results per spawner.
UPROPERTY(EditAnywhere, Category = "Voxel")
FVoxelSpawnerConfigSpawnerSeed Seed;
public:
// Controls the spawning pattern
UPROPERTY(EditAnywhere, Category = "Voxel")
EVoxelSpawnerConfigElementRandomGenerator RandomGenerator = EVoxelSpawnerConfigElementRandomGenerator::Halton;
// Unique ID used when saving spawners to disk
UPROPERTY(VisibleAnywhere, Category = "Voxel")
FGuid Guid;
// Controls whether to compute the density or the height first. Try both and see which is faster
// If false, the following are true when querying the density:
// - for flat worlds: Z = Height
// - for sphere worlds: Length(X, Y, Z) = Height
UPROPERTY(EditAnywhere, Category = "Voxel", meta = (DisplayName = "Compute Density First"))
bool bComputeDensityFirst_HeightOnly = false;
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
USTRUCT()
struct FVoxelSpawnerConfigElementAdvanced_Height
{
GENERATED_BODY()
UPROPERTY()
bool bSave = true;
UPROPERTY()
bool bDoNotDespawn = false;
UPROPERTY()
FName SeedName = "FoliageSeed";
UPROPERTY()
uint32 DefaultSeed = 1337;
UPROPERTY()
EVoxelSpawnerConfigElementRandomGenerator RandomGenerator = EVoxelSpawnerConfigElementRandomGenerator::Halton;
UPROPERTY()
bool bComputeDensityFirst = false;
UPROPERTY()
FGuid Guid;
};
USTRUCT()
struct FVoxelSpawnerConfigElementAdvanced_Ray
{
GENERATED_BODY()
UPROPERTY()
bool bSave = true;
UPROPERTY()
bool bDoNotDespawn = false;
UPROPERTY()
FName SeedName = "FoliageSeed";
UPROPERTY()
uint32 DefaultSeed = 1337;
UPROPERTY()
EVoxelSpawnerConfigElementRandomGenerator RandomGenerator = EVoxelSpawnerConfigElementRandomGenerator::Halton;
UPROPERTY()
FGuid Guid;
};
USTRUCT()
struct FVoxelSpawnerConfigElement_Height
{
GENERATED_BODY()
UPROPERTY()
UVoxelSpawner* Spawner = nullptr;
UPROPERTY()
FVoxelSpawnerDensity Density;
UPROPERTY()
FVoxelSpawnerOutputName DensityGraphOutputName_DEPRECATED;
UPROPERTY()
FVoxelSpawnerConfigElementAdvanced_Height Advanced;
};
USTRUCT()
struct FVoxelSpawnerConfigElement_Ray
{
GENERATED_BODY()
UPROPERTY()
UVoxelSpawner* Spawner = nullptr;
UPROPERTY()
FVoxelSpawnerDensity Density;
UPROPERTY()
FVoxelSpawnerDensity DensityMultiplier;
UPROPERTY()
FVoxelSpawnerOutputName DensityGraphOutputName_DEPRECATED;
UPROPERTY()
FVoxelSpawnerConfigElementAdvanced_Ray Advanced;
};
USTRUCT()
struct FVoxelSpawnerConfigHeightGroup
{
GENERATED_BODY()
UPROPERTY()
FVoxelSpawnerOutputName HeightGraphOutputName = "Height";
UPROPERTY()
uint32 ChunkSize = 32;
UPROPERTY()
uint32 GenerationDistanceInChunks = 2;
UPROPERTY()
uint32 GenerationDistanceInVoxels_EditorOnly = 0;
UPROPERTY()
TArray<FVoxelSpawnerConfigElement_Height> Spawners;
};
USTRUCT()
struct FVoxelSpawnerConfigRayGroup
{
GENERATED_BODY()
UPROPERTY()
uint32 LOD = 0;
UPROPERTY()
uint32 ChunkSize_EditorOnly = 32;
UPROPERTY()
uint32 GenerationDistanceInChunks = 2;
UPROPERTY()
uint32 GenerationDistanceInVoxels_EditorOnly = 0;
UPROPERTY()
TArray<FVoxelSpawnerConfigElement_Ray> Spawners;
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
UENUM()
enum class EVoxelSpawnerConfigRayWorldType : uint8
{
Flat,
Sphere
};
USTRUCT(BlueprintType)
struct FVoxelSpawnerConfigFiveWayBlendSetup
{
GENERATED_BODY()
// If true, will ignore Alpha
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Voxel")
bool bFourWayBlend = false;
};
UCLASS()
class VOXEL_API UVoxelSpawnerConfig : public UObject
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, Category = "Config")
EVoxelSpawnerConfigRayWorldType WorldType;
UPROPERTY(EditAnywhere, Category = "Config")
UVoxelSpawnerOutputsConfig* WorldGeneratorOutputs;
UPROPERTY(EditAnywhere, Category = "Config", AdvancedDisplay)
FVoxelSpawnerConfigFiveWayBlendSetup FiveWayBlendSetup;
public:
UPROPERTY(EditAnywhere, Category = "Spawners")
TArray<FVoxelSpawnerConfigSpawner> Spawners;
public:
UPROPERTY()
TArray<FVoxelSpawnerConfigRayGroup> RaySpawners_DEPRECATED;
UPROPERTY()
TArray<FVoxelSpawnerConfigHeightGroup> HeightSpawners_DEPRECATED;
protected:
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
virtual void PostLoad() override;
void SetReadOnlyPropertiesFromEditorOnly();
void SetEditorOnlyPropertiesFromReadOnly();
void FixGuids();
void FixSpawnerDensityTypes();
}; | [
"phyronnaz@gmail.com"
] | phyronnaz@gmail.com |
706cbe7cd08c2ab29417d5c67063f93236676c33 | 3a13b93b605cd3481b6ec54202d253af2a0ad854 | /FN/SDK/FN_InputCore_classes.hpp | 75bb86e7393dc0d029ee1a6dd9a851a9c606718d | [] | no_license | antiwar3/WXY-SDK | 12bc929c3371756fb8eac2f9aba6ffb53be17109 | 20c2e89189fbcdd40c407c799d71ff20da096584 | refs/heads/master | 2020-04-15T10:19:42.493604 | 2019-01-08T07:39:48 | 2019-01-08T07:39:48 | 164,591,515 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 558 | hpp | #pragma once
// Fortnite (1.6.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class InputCore.InputCoreTypes
// 0x0000 (0x0028 - 0x0028)
class UInputCoreTypes : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class InputCore.InputCoreTypes");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"237213@qq.com"
] | 237213@qq.com |
cf5c0a52085a60eaededb2191ed51eb90d912371 | a65aebf715b52feb7dc8264e60ebacfdf812684d | /rekthook/Menu_Backup.h | 9901536ed25d2f5ea89fc9ff4b61c8b257f1c46f | [] | no_license | chilledgamer1985/Rekthook | 37faf1f1401551888b56184354350363ba055be1 | 16da93c8ed61c5ecbef66466f64361aadd35baec | refs/heads/master | 2021-09-06T06:43:59.763311 | 2018-02-03T11:14:03 | 2018-02-03T11:14:03 | 119,590,830 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,612 | h | #include "stdafx.h"
int MenuRed;
int MenuGreen;
int MenuBlue;
int MenuAlpha;
int TextRed;
int TextGreen;
int TextBlue;
int TextAlpha;
int BackgroundRed;
int BackgroundGreen;
int BackgroundBlue;
int BackgroundAlpha;
int OutlineRed;
int OutlineGreen;
int OutlineBlue;
int OutlineAlpha;
char *speed_smothX = "Movement X";
char *speed_smothY = "Movement Y";
int changeaimtype = Settings.GetMenuSetting(Tab_LegitBot, Legit_typeofaim);
void colourUpdate()
{
MenuRed = Settings.GetSetting( Tab_Other, Other_MenuRed);
MenuGreen = Settings.GetSetting( Tab_Other, Other_MenuGreen);
MenuBlue = Settings.GetSetting( Tab_Other, Other_MenuBlue);
MenuAlpha = Settings.GetSetting( Tab_Other, Other_MenuAlpha);
TextRed = Settings.GetSetting( Tab_Other, Other_TextRed);
TextGreen = Settings.GetSetting( Tab_Other, Other_TextGreen);
TextBlue = Settings.GetSetting( Tab_Other, Other_TextBlue);
TextAlpha = Settings.GetSetting( Tab_Other, Other_TextAlpha);
BackgroundRed = Settings.GetSetting( Tab_Other, Other_BackgroundRed);
BackgroundGreen = Settings.GetSetting( Tab_Other, Other_BackgroundGreen);
BackgroundBlue = Settings.GetSetting( Tab_Other, Other_BackgroundBlue);
BackgroundAlpha = Settings.GetSetting( Tab_Other, Other_BackgroundAlpha);
OutlineRed = Settings.GetSetting( Tab_Other, Other_OutlineRed);
OutlineGreen = Settings.GetSetting( Tab_Other, Other_OutlineGreen);
OutlineBlue = Settings.GetSetting( Tab_Other, Other_OutlineBlue);
OutlineAlpha = Settings.GetSetting( Tab_Other, Other_OutlineAlpha);
}
bool Clicked_This_Frame;
bool Holding_Mouse_1;
bool Dont_Click;
bool Holding_Menu;
int Menu_Drag_X;
int Menu_Drag_Y;
int Tab_Count = 0;
bool keys[256];
bool oldKeys[256];
bool GetKeyPress(unsigned int key)
{
if (keys[key] == true && oldKeys[key] == false)
return true;
else
return false;
}
char* KeyStrings[254] = { "undefined", "Left Mouse", "Right Mouse", "Break", "Middle Mouse", "Mouse 4", "Mouse 5",
"undefined", "Backspace", "TAB", "undefined", "undefined", "undefined", "ENTER", "undefined", "undefined", "SHIFT",
"CTRL", "ALT","PAUSE","CAPS LOCK", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"ESC", "undefined", "undefined", "undefined", "undefined", "SPACEBAR","PG UP", "PG DOWN", "END", "HOME", "Left",
"Up", "Right", "Down", "undefined", "Print", "undefined", "Print Screen", "Insert","Delete", "undefined", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X","Y", "Z", "Left Windows", "Right Windows", "undefined", "undefined", "undefined", "NUM 0", "NUM 1",
"NUM 2", "NUM 3", "NUM 4", "NUM 5", "NUM 6","NUM 7", "NUM 8", "NUM 9", "*", "+", "_", "-", ".", "/", "F1", "F2", "F3",
"F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12","F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21",
"F22", "F23", "F24", "undefined", "undefined", "undefined", "undefined", "undefined","undefined", "undefined", "undefined",
"NUM LOCK", "SCROLL LOCK", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "undefined","undefined", "undefined", "undefined", "undefined", "undefined", "LSHIFT", "RSHIFT", "LCONTROL",
"RCONTROL", "LMENU", "RMENU", "undefined","undefined", "undefined","undefined", "undefined", "undefined", "undefined",
"undefined", "undefined", "undefined", "Next Track", "Previous Track", "Stop", "Play/Pause", "undefined", "undefined",
"undefined", "undefined", "undefined", "undefined", ";", "+", ",", "-", ".", "/?", "~", "undefined", "undefined",
"undefined", "undefined","undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined","undefined",
"undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "[{", "\\|", "}]", "'\"", "undefined",
"undefined", "undefined", "undefined","undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined",
"undefined", "undefined" };
void DrawMouse()
{
static int Texturer = Interfaces.pSurface->CreateNewTextureID(true);
unsigned char buffer[4] = { BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha };
Interfaces.pSurface->DrawSetTextureRGBA(Texturer, buffer, 1, 1);
Interfaces.pSurface->DrawSetTexture(Texturer);
Interfaces.pSurface->DrawSetColor(MenuRed - 10, MenuGreen - 10, MenuBlue - 10, MenuAlpha);
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
Vertex_t Verts[3];
Verts[0].x = Mouse.x;
Verts[0].y = Mouse.y;
Verts[1].x = Mouse.x + 16;
Verts[1].y = Mouse.y + 10;
Verts[2].x = Mouse.x;
Verts[2].y = Mouse.y + 16;
Interfaces.pSurface->DrawTexturedPolygon(3, Verts);
}
void CMenu::Set_Current_Tab(int tab)
{
Current_tab = tab;
}
int CMenu::GetCurret_Tab()
{
return Current_tab;
}
void CMenu::Update_Frame()
{
if (!Holding_Mouse_1)
{
if (GetClicked())
{
Holding_Menu = true;
}
else
{
Holding_Menu = false;
}
}
if (Holding_Menu)
{
MenuPOS NewPOS;
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
NewPOS.x = Mouse.x - Menu_Drag_X;
NewPOS.y = Mouse.y - Menu_Drag_Y;
this->pos = NewPOS;
}
}
bool CMenu::GetClicked()
{
if (!(GetAsyncKeyState(VK_LBUTTON) & 0x8000))
{
return false;
}
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y && Mouse.x < this->pos.x + 900 && Mouse.y < this->pos.y + 20)
{
if (!Holding_Mouse_1)
{
Menu_Drag_X = Mouse.x - pos.x;
Menu_Drag_Y = Mouse.y - pos.y;
}
return true;
}
else
{
return false;
}
}
CMenu Menu;
class CButton;
class CSlider;
class CDropbox;
class CKeybutton;
class CTab;
class CMenuBox;
class CButton
{
private:
MenuPOS pos;
MenuPOS offset;
int Tab;
int Setting;
char* Name = "ERROR";
bool Clicked()
{
if (!Clicked_This_Frame)
{
return false;
}
if (Holding_Mouse_1)
{
return false;
}
if (Dont_Click)
{
return false;
}
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y && Mouse.x < this->pos.x + 20 && Mouse.y < this->pos.y + 20)
{
return true;
}
return false;
}
public:
void Update()
{
this->pos.x = Menu.pos.x + this->offset.x;
this->pos.y = Menu.pos.y + this->offset.y;
if (Menu.GetCurret_Tab() == Tab)
{
if (Clicked())
{
Dont_Click = true;
Settings.SetBoolSetting(Tab, Setting, !Settings.GetSetting( Tab, Setting));
}
}
}
void Draw()
{
if (Menu.GetCurret_Tab() == Tab)
{
Interfaces.pSurface->DrawSetColor(BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x, this->pos.y, this->pos.x + 20, this->pos.y + 20);
if (Settings.GetMenuSetting(this->Tab, this->Setting))
{
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x + 4, this->pos.y + 4, this->pos.x + 16, this->pos.y + 16);
// Interfaces.pSurface->DrawSetColor(OutlineRed, OutlineGreen, OutlineBlue, 255);
// Interfaces.pSurface->DrawOutlinedRect(this->pos.x + 4, this->pos.y + 4, this->pos.x + 16, this->pos.y + 16);
//Interfaces.pSurface->DrawFilledCircle(this->pos.x + 10, this->pos.y + 10, 8, MenuRed, MenuGreen, MenuBlue, MenuAlpha);
}
Interfaces.pSurface->DrawSetColor(OutlineRed, OutlineGreen, OutlineBlue, OutlineAlpha);
//Interfaces.pSurface->DrawColoredCircle(this->pos.x + 10, this->pos.y + 10, 10, 100, 100, 100, 255);
Interfaces.pSurface->DrawOutlinedRect(this->pos.x, this->pos.y, this->pos.x + 20, this->pos.y + 20);
Interfaces.pSurface->DrawT(this->pos.x + 30, this->pos.y + 6, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, false, this->Name);
}
}
void Init(int Tab, int Setting, bool defult, int x, int y, char* name)
{
this->Tab = Tab;
this->Setting = Setting;
this->offset.y = y;
this->offset.x = x;
this->Name = name;
Settings.SetBoolSetting(Tab, Setting, defult);
}
};
class CSlider
{
private:
int Tab = 0;
int Setting = 0;
double Max = 100;
double Min = 0;
MenuPOS pos;
MenuPOS offset;
char* Name = "ERROR";
bool Is_Holding;
bool GetClicked()
{
if (!Clicked_This_Frame)
{
this->Is_Holding = false;
return false;
}
if (Holding_Mouse_1)
{
if (!this->Is_Holding)
{
return false;
}
}
if (Dont_Click)
return false;
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y && Mouse.x < this->pos.x + 100 && Mouse.y < this->pos.y + 20)
{
this->Is_Holding = true;
return true;
}
else if (this->Is_Holding)
{
return true;
}
else
{
return false;
}
}
public:
void Draw()
{
if (Menu.GetCurret_Tab() == Tab)
{
double Ratio = Settings.GetMenuSetting(this->Tab, this->Setting) / (this->Max - this->Min);
double Location = Ratio * 100;
Interfaces.pSurface->DrawSetColor(80, 80, 80, 255);
Interfaces.pSurface->DrawOutlinedRect(this->pos.x, this->pos.y + 5, this->pos.x + 100, this->pos.y + 15);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x + 2, this->pos.y + 7, this->pos.x + Location, this->pos.y + 13);
Interfaces.pSurface->DrawSetColor(200, 200, 200, 255);
Interfaces.pSurface->DrawFilledRect(this->pos.x + Location - 3, this->pos.y, this->pos.x + Location + 3, this->pos.y + 20);
Interfaces.pSurface->DrawSetColor(170, 170, 170, 255);
Interfaces.pSurface->DrawOutlinedRect(this->pos.x + Location - 3, this->pos.y, this->pos.x + Location + 3, this->pos.y + 20);
Interfaces.pSurface->DrawT(this->pos.x, this->pos.y - 12, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, false, "%s: %.1f", this->Name, (float)Settings.GetMenuSetting(this->Tab, this->Setting));
}
}
void Init(int x, int y, double min, double max, double defult, char* name, int tab, int setting)
{
offset.x = x;
offset.y = y;
Tab = tab;
Setting = setting;
Max = max;
Min = min;
Name = name;
Settings.SetSetting(Tab, Setting, defult);
}
void Update()
{
this->pos.x = Menu.pos.x + offset.x;
this->pos.y = Menu.pos.y + offset.y;
// get clicked and changing value
if (Menu.GetCurret_Tab() == Tab)
{
if (this->GetClicked())
{
Dont_Click = true;
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
// get differance
double idifference;
idifference = Mouse.x - this->pos.x;
// Set Value
double value = ((idifference / 100)*(this->Max - this->Min));
if (value < Min)
{
value = Min;
}
else if (value > Max)
{
value = Max;
}
Settings.SetSetting(Tab, Setting, value);
}
}
}
};
class CDropBox
{
private:
int Tab = 0;
int Setting = 0;
char* Name = "ERROR";
char* Parts[20];
int Amount = 0;
bool Dropping = false;
MenuPOS pos;
MenuPOS offset;
bool GetClicked()
{
if (!Clicked_This_Frame)
{
return false;
}
if (Holding_Mouse_1)
{
return false;
}
if (Dont_Click)
{
return false;
}
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y && Mouse.x < this->pos.x + 100 && Mouse.y < this->pos.y + 20)
{
return true;
}
else
{
return false;
}
}
int GetPartClicked()
{
if (!Clicked_This_Frame)
{
return -1;
}
if (Holding_Mouse_1)
{
return -1;
}
if (Dont_Click)
{
return -1;
}
POINT Mouse;
POINT mp;
GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x;
Mouse.y = mp.y;
for (int i = 1; i < this->Amount; i++)
{
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y + (20 * (i)) && Mouse.x < this->pos.x + 100 && Mouse.y < this->pos.y + (20 * (i + 1)))
{
return i;
}
}
return -1;
}
public:
void Update()
{
pos.x = Menu.pos.x + offset.x;
pos.y = Menu.pos.y + offset.y;
if (Tab == Menu.GetCurret_Tab())
{
if (this->GetClicked())
{
if (this->Dropping == true)
{
this->Dropping = false;
}
else
{
this->Dropping = true;
}
Dont_Click = true;
}
else if (this->Dropping)
{
int index = this->GetPartClicked();
if (index != -1)
{
Settings.SetSetting(this->Tab, this->Setting, index);
this->Dropping = false;
Dont_Click = true;
}
else if (Clicked_This_Frame && !Holding_Mouse_1)
{
Dropping = false;
}
}
}
else
{
Dropping = false;
}
}
void Draw()
{
if (Tab == Menu.GetCurret_Tab())
{
Interfaces.pSurface->DrawSetColor(BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x, this->pos.y, this->pos.x + 100, this->pos.y + 21);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);;
Interfaces.pSurface->DrawOutlinedRect(this->pos.x, this->pos.y, this->pos.x + 100, this->pos.y + 21);
Interfaces.pSurface->DrawT(this->pos.x, this->pos.y - 12, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, false, this->Name);
if (this->Dropping)
{
for (int i = 1; i < this->Amount; i++)
{
Interfaces.pSurface->DrawSetColor(BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x, this->pos.y + (20 * i), this->pos.x + 100, this->pos.y + (20 * i) + 21);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawOutlinedRect(this->pos.x, this->pos.y + (20 * i), this->pos.x + 100, this->pos.y + (20 * i) + 21);
Interfaces.pSurface->DrawT(this->pos.x + 50, this->pos.y + 5 + (20 * i), CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, this->Parts[i]);
}
}
else
{
Interfaces.pSurface->DrawT(this->pos.x + 50, this->pos.y + 5, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, this->Parts[(int)Settings.GetMenuSetting(Tab, Setting)]);
static int Texture = Interfaces.pSurface->CreateNewTextureID(true); //need to make a texture with procedural true
unsigned char buffer[4] = { BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha };//{ color.r(), color.g(), color.b(), color.a() };
Interfaces.pSurface->DrawSetTextureRGBA(Texture, buffer, 1, 1); //Texture, char array of texture, width, height
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha); // keep this full color and opacity use the RGBA @top to set values.
Interfaces.pSurface->DrawSetTexture(Texture); // bind texture
Vertex_t Verts2[3];
Verts2[0].x = this->pos.x + 85;
Verts2[0].y = this->pos.y + 6;
Verts2[1].x = this->pos.x + 95;
Verts2[1].y = this->pos.y + 6;
Verts2[2].x = this->pos.x + 90;
Verts2[2].y = this->pos.y + 14;
Interfaces.pSurface->DrawTexturedPolygon(3, Verts2);
}
}
}
void Init(int x, int y, int tab, int setting, char* name, int parts, char* arr[100])
{
Name = name;
Amount = parts;
for (int i = 0; i < parts; i++)
{
Parts[i] = arr[i];
}
Tab = tab;
Setting = setting;
offset.x = x;
offset.y = y;
}
};
class CKeyButton
{
private:
MenuPOS pos;
MenuPOS offset;
int Tab;
int Setting;
bool Getting_New_Key;
char* Name = "ERROR";
bool GetClicked()
{
if (!Clicked_This_Frame)
{
return false;
}
if (Holding_Mouse_1)
{
return false;
}
if (Dont_Click)
{
return false;
}
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > this->pos.x && Mouse.y > this->pos.y && Mouse.x < this->pos.x + 100 && Mouse.y < this->pos.y + 20)
{
return true;
}
else
{
return false;
}
}
public:
void Draw()
{
if (Menu.GetCurret_Tab() == Tab)
{
Interfaces.pSurface->DrawT(this->pos.x, this->pos.y - 12, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, false, "%s", this->Name);
Interfaces.pSurface->DrawSetColor(BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha);
Interfaces.pSurface->DrawFilledRect(this->pos.x, this->pos.y, this->pos.x + 100, this->pos.y + 20);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawOutlinedRect(this->pos.x, this->pos.y, this->pos.x + 100, this->pos.y + 20);
if (this->Getting_New_Key)
{
Interfaces.pSurface->DrawT(this->pos.x + 50, this->pos.y + 5, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, "<GETTING KEY>");
}
else
{
if (Settings.GetMenuSetting(this->Tab, this->Setting) == -1)
Interfaces.pSurface->DrawT(this->pos.x + 50, this->pos.y + 5, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, "<UNSET>");
else
{
char* NameOfKey = KeyStrings[(int)Settings.GetMenuSetting(this->Tab, this->Setting)];
Interfaces.pSurface->DrawT(this->pos.x + 50, this->pos.y + 5, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, NameOfKey);
}
}
}
}
void Update()
{
pos.x = Menu.pos.x + offset.x;
pos.y = Menu.pos.y + offset.y;
if (Menu.GetCurret_Tab() == Tab)
{
if (Getting_New_Key)
{
for (int i = 0; i < 255; i++)
{
if (GetKeyPress(i))
{
if (i == VK_BACK)
{
this->Getting_New_Key = false;
Settings.SetSetting(Tab, Setting, -1);
break;
}
Settings.SetSetting(Tab, Setting, i);
this->Getting_New_Key = false;
break;
}
}
}
else if (this->GetClicked())
{
this->Getting_New_Key = !this->Getting_New_Key;
}
}
}
void Init(int x, int y, int tab, int setting, char* name)
{
offset.x = x;
offset.y = y;
Tab = tab;
Setting = setting;
Name = name;
Settings.SetSetting(Tab, Setting, -1);
}
};
class CTab
{
public:
void Update()
{
pos.x = Menu.pos.x + ((700 / Tab_Count) * Tab) + 2;
pos.y = Menu.pos.y + 20;
if (GetClicked())
{
Dont_Click = true;
Menu.Set_Current_Tab(Tab);
}
}
void Draw()
{
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawFilledRect(pos.x, pos.y, pos.x + (700 / Tab_Count), pos.y + 20);
if (Menu.GetCurret_Tab() == Tab)
{
Interfaces.pSurface->DrawSetColor(MenuRed - 20, MenuGreen - 20, MenuBlue - 20, 255);
Interfaces.pSurface->DrawFilledRect(pos.x, pos.y, pos.x + (700 / Tab_Count), pos.y + 20);
}
Interfaces.pSurface->DrawT(pos.x + ((700 / Tab_Count) / 2), pos.y + 3, CColor(TextRed, TextGreen, TextBlue, TextAlpha), 39, true, Name);
}
void Init(char* name, int tab)
{
Name = name;
Tab = tab;
}
private:
int Tab;
MenuPOS pos;
char* Name = "ERROR";
bool GetClicked()
{
if (!Clicked_This_Frame)
{
return false;
}
if (Holding_Mouse_1)
{
return false;
}
POINT Mouse;
POINT mp; GetCursorPos(&mp);
ScreenToClient(GetForegroundWindow(), &mp);
Mouse.x = mp.x; Mouse.y = mp.y;
if (Mouse.x > pos.x && Mouse.y > pos.y && Mouse.x < pos.x + ((700 / Tab_Count)) && Mouse.y < pos.y + 20)
{
return true;
}
else
{
return false;
}
}
};
class CMenuBox
{
public:
void Init(char* name, int x, int y, int w, int h, int tab)
{
Name = name;
offset.x = x;
offset.y = y;
size.x = w;
size.y = h;
Tab = tab;
}
void Update()
{
pos.x = Menu.pos.x + offset.x;
pos.y = Menu.pos.y + offset.y;
}
void Draw()
{
if (Tab == Menu.GetCurret_Tab())
{
Interfaces.pSurface->DrawT(pos.x + (size.x / 2), pos.y - 3, CColor(TextRed, TextBlue, TextGreen, 255), 39, true, Name);
char Buffer[2048] = { '\0' };
va_list Args;
va_start(Args, Name);
vsprintf_s(Buffer, Name, Args);
va_end(Args);
size_t Size = strlen(Buffer) + 1;
/* set up size.xidebuffer*/
wchar_t* wBuffer = new wchar_t[Size];
/* char -> size.xchar */
mbstowcs_s(0, wBuffer, Size, Buffer, Size - 1);
/* check center */
int Width = 0, Height = 0;
Interfaces.pSurface->GetTextSize(5, wBuffer, Width, Height);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawLine(pos.x, pos.y, pos.x, pos.y + size.y);
Interfaces.pSurface->DrawLine(pos.x, pos.y + size.y, pos.x + size.x, pos.y + size.y);
Interfaces.pSurface->DrawLine(pos.x + size.x, pos.y, pos.x + size.x, pos.y + size.y);
Interfaces.pSurface->DrawLine(pos.x, pos.y, pos.x + ((size.x / 2) - (Width / 2) - 2), pos.y);
Interfaces.pSurface->DrawLine(pos.x + ((size.x / 2) + (Width / 2) + 2), pos.y, pos.x + size.x, pos.y);
}
}
private:
MenuPOS pos;
MenuPOS offset;
MenuPOS size;
char* Name = "ERROR";
int Tab;
};
std::vector<CSlider> Sliders;
std::vector<CButton> Buttons;
std::vector<CDropBox> Dropboxes;
std::vector<CKeyButton> KeyButtons;
std::vector<CMenuBox> MenuBoxs;
std::vector<CTab> Tabs;
int Dropboxs_Amount = 0;
void AddNewButton(int Tab, int Setting, bool defult, int x, int y, char* name)
{
CButton Filler;
Filler.Init(Tab, Setting, defult, x, y, name);
Buttons.push_back(Filler);
}
void AddNewSlider(int x, int y, double min, double max, double defult, char* name, int tab, int setting)
{
CSlider Slid;
Slid.Init(x, y, min, max, defult, name, tab, setting);
Sliders.push_back(Slid);
}
void AddNewDropbox(int x, int y, int tab, int setting, char* name, int parts, char* arr[100])
{
CDropBox Dropper;
Dropper.Init(x, y, tab, setting, name, parts, arr);
Dropboxes.push_back(Dropper);
Dropboxs_Amount++;
}
void AddNewKeyButton(int x, int y, int tab, int setting, char* name)
{
CKeyButton KeyButton;
KeyButton.Init(x, y, tab, setting, name);
KeyButtons.push_back(KeyButton);
}
void AddNewTab(char* Name, int Tab)
{
CTab Filler;
Filler.Init(Name, Tab);
Tabs.push_back(Filler);
Tab_Count++;
}
void AddNewMenuBox(char* name, int x, int y, int w, int h, int tab)
{
CMenuBox Filler;
Filler.Init(name, x, y, w, h, tab);
MenuBoxs.push_back(Filler);
}
void SetupMenu()
{
char* arr[20] = { "ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR","ERROR" };
AddNewTab("Ragebot", Tab_Ragebot);
AddNewTab("Legitbot", Tab_LegitBot);
AddNewTab("Visuals", Tab_Visuals);
AddNewTab("Misc", Tab_Misc);
AddNewTab("Configs", Tab_Config);
AddNewTab("Others", Tab_Other);
AddNewButton(Tab_LegitBot, Legit_Activate, false, 10, 50, "Active");
/* LEGITBOT */
AddNewMenuBox("Aimbot", 10, 80, 120, 200, Tab_LegitBot);
{
AddNewButton(Tab_LegitBot, Legit_Active, false, 20, 90, "Active");
AddNewSlider(20, 130, 0, 20, 4, "FOV", Tab_LegitBot, Legit_LegitFOV);
char *aimbone[10] = { "Head", "Head", "Neck", "Chest", "Stomach", "Nearest", "Random" };
AddNewDropbox(20, 170, Tab_LegitBot, Legit_AimBone, "Aimbone", 7, aimbone);
AddNewSlider(20, 210, 0, 100, 4, speed_smothX, Tab_LegitBot, Legit_LegitNormalAimSpeedX);
AddNewSlider(20, 250, 0, 100, 4, speed_smothY, Tab_LegitBot, Legit_LegitNormalAimSpeedY);
}
AddNewMenuBox("Smart Aim", 140, 80, 120, 200, Tab_LegitBot);
{
AddNewButton(Tab_LegitBot, Legit_SAActive, false, 160, 90, "Active");
AddNewSlider(150, 130, 0, 20, 4, "SA Bullets", Tab_LegitBot, Legit_Saim);
char *Saimbone[10] = { "Head", "Head", "Neck", "Chest", "Stomach", "Nearest", "Random" };
AddNewDropbox(150, 170, Tab_LegitBot, Legit_Sabone, "SA Bone", 7, Saimbone);
AddNewSlider(150, 210, 0, 100, 4, speed_smothX, Tab_LegitBot, Legit_SALegitNormalAimSpeedX);
AddNewSlider(150, 250, 0, 100, 4, speed_smothY, Tab_LegitBot, Legit_SALegitNormalAimSpeedY);
}
AddNewMenuBox("Global", 270, 80, 120, 200, Tab_LegitBot);
{
AddNewSlider(280, 100, 0, 20, 0, "Randomise", Tab_LegitBot, Legit_Random);
char *typeofaim[10] = { "Speed", "Speed", "Smooth", "Curve" };
AddNewDropbox(280, 140, Tab_LegitBot, Legit_typeofaim, "Type", 4, typeofaim);
AddNewSlider(280, 180, 0, 10, 5, "Type Factor", Tab_LegitBot, Legit_Factor);
AddNewSlider(280, 220, 0, 200, 50, "Target Delay", Tab_LegitBot, Legit_lastcount);
AddNewSlider(280, 250, 0, 100, 0, "TrickShot", Tab_LegitBot, Legit_Trick);
}
AddNewButton(Tab_LegitBot, Trigger_Active, false, 400, 50, "Active");
AddNewMenuBox("Trigger", 400, 80, 120, 200, Tab_LegitBot);
{
AddNewButton(Tab_LegitBot, Trigger_Type, true, 410, 90, "On Key");
AddNewKeyButton(410, 130, Tab_LegitBot, Trigger_Key, "Key");
AddNewSlider(410, 170, 0, 30, 0, "Delay", Tab_LegitBot, Trigger_Delay);
AddNewSlider(410, 210, 0, 30, 0, "After", Tab_LegitBot, Trigger_After);
AddNewButton(Tab_LegitBot, Trigger_Magnet, true, 410, 250, "Mag Active");
}
AddNewMenuBox("Magnet Trigger", 530, 80, 120, 200, Tab_LegitBot);
{
char *Trigbone[10] = { "Head", "Head", "Neck", "Chest", "Stomach", "Nearest", "Random" };
AddNewDropbox(540, 100, Tab_LegitBot, Trigger_AimBone, "Bone", 7, Trigbone);
AddNewSlider(540, 140, 0, 10, 3, "Fov", Tab_LegitBot, Trigger_Fov);
AddNewSlider(540, 180, 0, 100, 3, speed_smothX, Tab_LegitBot, Trigger_SpeedX);
AddNewSlider(540, 220, 0, 100, 3, speed_smothY, Tab_LegitBot, Trigger_SpeedY);
AddNewButton(Tab_LegitBot, Trigger_Instant, false, 540, 250, "Instant");
}
AddNewMenuBox("RCS", 10, 290, 240, 100, Tab_LegitBot);
{
AddNewButton(Tab_LegitBot, Legit_RCS_Enable, true, 20, 300, "Active");
char *rcstype[10] = { "Aim", "Aim", "Standalone", "+Aim" };
AddNewDropbox(20, 340, Tab_LegitBot, Legit_RCS_Type, "Type", 4, rcstype);
AddNewSlider(130, 310, 0, 2, 2, "RCS X", Tab_LegitBot, Legit_RCS_X);
AddNewSlider(130, 350, 0, 2, 2, "RCS Y", Tab_LegitBot, Legit_RCS_Y);
}
/* Ragebot */
AddNewButton(Tab_Ragebot, Ragebot_Enable, false, 10, 50, "Enable Ragebot");
AddNewMenuBox("Aimbot", 10, 80, 130, 100, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, Ragebot_Aimbot, false, 20, 90, "Enable Aimbot");
AddNewButton(Tab_Ragebot, Ragebot_Silent_Aim, false, 20, 120, "Silent");
AddNewButton(Tab_Ragebot, Ragebot_pSilent, false, 20, 150, "pSilent");
}
AddNewButton(Tab_Ragebot, Ragebot_Multipoint, false, 300, 150, "MutiPoint");
AddNewMenuBox("Speed", 10, 190, 130, 80, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, Ragebot_Speed_Limit, false, 20, 200, "Max Speed");
AddNewSlider(20, 240, 0, 180, 30, "Speed Amount", Tab_Ragebot, Ragebot_Speed_Limit_Amount);
}
AddNewMenuBox("On Button", 10, 280, 130, 80, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, Ragebot_On_Key_Press, false, 20, 290, "Enabled");
AddNewKeyButton(20, 330, Tab_Ragebot, Rabebot_On_Key_Button, "Key");
}
AddNewMenuBox("Movement", 150, 80, 130, 80, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, Ragebot_AutoDuck, false, 160, 90, "Auto Duck");
AddNewButton(Tab_Ragebot, Ragebot_AutoStop, false, 160, 120, "Auto Stop");
}
AddNewMenuBox("Sniper", 150, 170, 130, 40, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, Ragebot_Autoscope, false, 160, 180, "Auto Scope");
}
AddNewMenuBox("AntiAim", 290, 170, 130, 40, Tab_Ragebot);
{
AddNewButton(Tab_Ragebot, AntiAim_Enable, false, 300, 180, "AntiAim");
char *Antiaim_X[10] = { "", "","Emotion", "Down", "Up", "Jitter", "Fakedown" };
AddNewDropbox(300, 200, Tab_Ragebot, AntiAim_X, "Antiaim_X", 7, Antiaim_X);
char *Antiaim_Y[10] = { "", "","Back", "Side", "Fake Sideways", "Fast Spin", "Slow Spin" };
AddNewDropbox(300, 220, Tab_Ragebot, AntiAim_Y, "Antiaim_Y", 7, Antiaim_Y);
AddNewButton(Tab_Ragebot, AntiAim_Enable, false, 300, 180, "AntiAim");
AddNewButton(Tab_Ragebot, AntiAim_LispAngles, false, 300, 250, "LISP ANGLES");
}
/* MISC */
AddNewMenuBox("Bunny Hop", 10, 80, 130, 100, Tab_Misc);
{
AddNewButton(Tab_Misc, Misc_Bunny_Hop, true, 20, 90, "Enabled");
AddNewButton(Tab_Misc, Misc_Auto_Strafer, true, 20, 120, "AutoStrafer");
}
//Move them pls dont remove them
AddNewButton(Tab_Misc, Misc_Unhook, false, 20, 190, "unhook");
AddNewButton(Tab_Misc, Misc_WeaponConfigs, false, 20, 230, "Weapon Configs");
char *wgroup[10] = { "Current", "Rifle","Pistol", "Dak", "Awp", "Scout", "Shotgun", "SMG", "Heavy", "Current" };
AddNewDropbox(20, 270, Tab_Misc, Misc_WhichWeapon, "Weapon Group", 10, wgroup);
//Config
AddNewMenuBox("Load", 10, 80, 130, 100, Tab_Config);
{
char *configtype[10] = { "Default", "Legit","HvH", "Rage", "Casual", "Custom1", "Custom2" };
AddNewDropbox(20, 100, Tab_Config, Config_type, "Config", 7, configtype);
AddNewButton(Tab_Config, Config_save, false, 20, 140, "Save");
AddNewButton(Tab_Config, Config_load, false, 20, 180, "Load");
}
/* OTHER */
AddNewMenuBox("Menu", 10, 50, 130, 140, Tab_Other);
{
AddNewSlider(20, 70, 0, 255, 70, "Red", Tab_Other, Other_MenuRed);
AddNewSlider(20, 100, 0, 255, 250, "Green", Tab_Other, Other_MenuGreen);
AddNewSlider(20, 130, 0, 255, 170, "Blue", Tab_Other, Other_MenuBlue);
AddNewSlider(20, 160, 0, 255, 255, "Alpha", Tab_Other, Other_MenuAlpha);
}
AddNewMenuBox("Text", 10, 200, 130, 140, Tab_Other);
{
AddNewSlider(20, 200, 0, 255, 0, "Red", Tab_Other, Other_TextRed);
AddNewSlider(20, 230, 0, 255, 0, "Green", Tab_Other, Other_TextGreen);
AddNewSlider(20, 260, 0, 255, 0, "Blue", Tab_Other, Other_TextBlue);
AddNewSlider(20, 290, 0, 255, 255, "Alpha", Tab_Other, Other_TextAlpha);
}
AddNewMenuBox("Background", 150, 50, 130, 140, Tab_Other);
{
AddNewSlider(160, 70, 0, 255, 255, "Red", Tab_Other, Other_BackgroundRed);
AddNewSlider(160, 100, 0, 255, 255, "Green", Tab_Other, Other_BackgroundGreen);
AddNewSlider(160, 130, 0, 255, 255, "Blue", Tab_Other, Other_BackgroundBlue);
AddNewSlider(160, 160, 0, 255, 255, "Alpha", Tab_Other, Other_BackgroundAlpha);
}
AddNewMenuBox("Outline", 150, 200, 130, 140, Tab_Other);
{
AddNewSlider(160, 200, 0, 100, 100, "Red", Tab_Other, Other_OutlineRed);
AddNewSlider(160, 230, 0, 100, 100, "Green", Tab_Other, Other_OutlineGreen);
AddNewSlider(160, 260, 0, 100, 100, "Blue", Tab_Other, Other_OutlineBlue);
AddNewSlider(160, 290, 0, 255, 255, "Alpha", Tab_Other, Other_OutlineAlpha);
}
}
extern void savesets();
extern std::string settingstostring();
void DrawMenu()
{
if (Settings.GetSetting( Tab_Config, Config_save)) {
settingstostring();
Settings.SetSetting(Tab_Config, Config_save, 0);
}
if (Settings.GetSetting( Tab_Config, Config_load)) {
savesets();
Settings.SetSetting(Tab_Config, Config_load, 0);
}
colourUpdate();
static bool firsttime = true;
Dont_Click = false;
/* UPDATE KEYS */
std::copy(keys, keys + 255, oldKeys);
for (int x = 0; x < 255; x++)
{
keys[x] = (GetAsyncKeyState(x));
}
if (GetKeyPress(VK_INSERT))
{
Menu.Opened = !Menu.Opened;
std::string msg = "cl_mouseenable " + std::to_string(!Menu.Opened);
Interfaces.pEngine->ClientCmd_Unrestricted(msg.c_str());
}
//Interfaces.pSurface->DrawSetColor(100, 100, 100, 255);
//Interfaces.pSurfaceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee->DrawFilledRect(0, 0, 1000, 1000);
if (firsttime /* SNIP!!, THIS WILL CAUSE ERRORS FFS! */)
{
/* Init Menu Here */
SetupMenu();
firsttime = false;
}
if (Menu.Opened)
{
if (!(GetAsyncKeyState(VK_LBUTTON) & 0x8000))
{
Holding_Mouse_1 = false;
}
if (GetAsyncKeyState(VK_LBUTTON) & 0x8000)
{
Clicked_This_Frame = true;
}
else
{
Clicked_This_Frame = false;
}
Menu.Update_Frame();
Interfaces.pSurface->DrawSetColor(BackgroundRed, BackgroundGreen, BackgroundBlue, BackgroundAlpha);
Interfaces.pSurface->DrawFilledRect(Menu.pos.x, Menu.pos.y, Menu.pos.x + 700, Menu.pos.y + 400);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawFilledRect(Menu.pos.x, Menu.pos.y, Menu.pos.x + 700, Menu.pos.y + 20);
Interfaces.pSurface->DrawSetColor(MenuRed, MenuGreen, MenuBlue, MenuAlpha);
Interfaces.pSurface->DrawOutlinedRect(Menu.pos.x, Menu.pos.y, Menu.pos.x + 700, Menu.pos.y + 400);
Interfaces.pSurface->DrawOutlinedRect(Menu.pos.x + 1, Menu.pos.y + 1, Menu.pos.x + 699, Menu.pos.y + 399);
Interfaces.pSurface->DrawT(Menu.pos.x + 350, Menu.pos.y + 5, CColor(0, 0, 0, 255), 39, true, "Aim Pulse");
for (CTab& Tab : Tabs)
Tab.Update();
for (CMenuBox& MenuBox : MenuBoxs)
MenuBox.Update();
for (CDropBox& Dropbox : Dropboxes)
Dropbox.Update();
for (CSlider& slider : Sliders)
slider.Update();
for (CButton& Button : Buttons)
Button.Update();
for (CKeyButton& KeyButton : KeyButtons)
KeyButton.Update();
for (CTab& Tab : Tabs)
Tab.Draw();
for (CMenuBox& MenuBox : MenuBoxs)
MenuBox.Draw();
for (CKeyButton& KeyButton : KeyButtons)
KeyButton.Draw();
for (CSlider& slider : Sliders)
slider.Draw();
for (CButton& Button : Buttons)
Button.Draw();
std::reverse(Dropboxes.begin(), Dropboxes.end());
for (CDropBox& Dropbox : Dropboxes)
Dropbox.Draw();
std::reverse(Dropboxes.begin(), Dropboxes.end());
DrawMouse();
if (Clicked_This_Frame)
{
Holding_Mouse_1 = true;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b77300ca6bb078c0c1cca9a153817771c8a70a5e | 49f271521563d5f7c24ffb942864cc9bec4a107a | /src/trajectory_follower.h | 3ad645b629ff622dd173cd2e237bfd797b03597e | [] | no_license | richard-robotics/mobile_planner | d6dae4761b247cd1c6e768dfaed1a5e6099cd5ad | 5f7d788cc762bd00fdecb511315fdb050fe5a9e3 | refs/heads/master | 2023-03-19T06:32:34.139523 | 2020-12-26T06:13:04 | 2020-12-26T06:13:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | h | #ifndef TRAJECTORY_FOLLOWER_H
#define TRAJECTORY_FOLLOWER_H
#include <Eigen/Dense>
#include "kinematics.h"
namespace kinematics {
class TrajectoryFollower {
public:
TrajectoryFollower(Trajectory initial_traj)
: initial_trajectory_(initial_traj),
timestep_(initial_traj.dt()),
robot_params_(initial_traj.robot_params()) {}
Trajectory Optimize(Eigen::Matrix4d Q, Eigen::Matrix2d R);
private:
Eigen::Matrix4d dfdx(const State& x, const Control& u);
Eigen::MatrixXd dfdu(const State& x, const Control& u);
Trajectory initial_trajectory_;
double timestep_;
RobotParams robot_params_;
};
} // namespace kinematics
#endif | [
"darkthecross@gmail.com"
] | darkthecross@gmail.com |
9ed64f741a0608c4edbc3d8d62235f4ce912e0d3 | 542bc1762dca1491017ce9bb60ca4ad92e4fdb75 | /MyMap.h | 6e5ad4bbcef113315d970b2006a41cb615183579 | [] | no_license | jennhuang/oogle | 6c067a8a233201820dae08c49aba0ac6d74fac2a | e6e5dd1a75ada25f65fa1f1ce0ddef0f6242a30b | refs/heads/master | 2020-05-27T10:06:43.850682 | 2013-03-17T05:08:05 | 2013-03-17T05:08:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,522 | h | #ifndef MYMAP_INCLUDED
#define MYMAP_INCLUDED
#include <queue>
#include <cstdlib>
template <class KeyType, class ValueType>
class MyMap
{
public:
MyMap()
{
m_size = 0;
m_root = NULL;
}
~MyMap()
{
deleteAll(m_root);
}
void clear()
{
deleteAll(m_root);
m_size = 0;
m_root = NULL;
while(!m_queue.empty())
m_queue.pop();
}
int size() const
{
return m_size;
}
void associate(const KeyType& key, const ValueType& value)
{
insert(m_root, key, value);
}
//*******************FIND***********************
//returns pointer to the value of the given key
//returns NULL if not found
const ValueType* find(const KeyType& key) const
{
//Node* n = search(m_root, key);
Node* ptr = m_root;
while (ptr != NULL)
{
if (ptr->m_key == key)
return &(ptr->m_value);
else if (ptr->m_key > key)
ptr = ptr->m_left;
else
ptr = ptr->m_right;
}
return NULL;
}
ValueType* find(const KeyType& key)
{
// Do not change the implementation of this overload of find
const MyMap<KeyType,ValueType>* constThis = this;
return const_cast<ValueType*>(constThis->find(key));
}
ValueType* getFirst(KeyType& key)
{
if(m_root == NULL)
return NULL;
else
{
//place the head node in the queue
if(m_root->m_left != NULL)
m_queue.push(m_root->m_left);
if(m_root->m_right != NULL)
m_queue.push(m_root->m_right);
key = m_root->m_key;
return &(m_root->m_value); //returns a pointer to the first value
}
}
ValueType* getNext(KeyType& key)
{
if(m_queue.empty())
return NULL;
m_cur = m_queue.front();
m_queue.pop();
key = m_cur->m_key; //stores key in the parameter
if(m_cur->m_left != NULL)
m_queue.push(m_cur->m_left);
if(m_cur->m_right != NULL)
m_queue.push(m_cur->m_right);
return &(m_cur->m_value); //returns a pointer to the next value
}
private:
MyMap(const MyMap &other);
MyMap &operator=(const MyMap &other);
struct Node
{
KeyType m_key;
ValueType m_value;
Node* m_left;
Node* m_right;
};
int m_size;
Node* m_root;
void insert(Node*& node, KeyType key, ValueType value)
{
//tree is empty
if(node == NULL)
{
node = new Node;
node->m_key = key;
node->m_value = value;
node->m_left = NULL;
node->m_right = NULL;
m_size++;
//set the root pointer
if(m_size == 1)
{
m_root = node;
}
}
//current node has the same key
//update the value
if(node->m_key == key)
{
node->m_value = value;
}
//current node has bigger key
//insert to the left
else if(node->m_key > key)
insert(node->m_left, key, value);
//current node has smaller key
//insert to the right
else
insert(node->m_right, key, value);
}
////////////////////////////////////////////////
//make a queue for my level order traversal
std::queue<Node*> m_queue;
//have a current node pointer
Node* m_cur;
void deleteAll(Node* node)
{
if(node == NULL)
return;
deleteAll(node->m_left);
deleteAll(node->m_right);
delete node;
}
Node* search(Node* node, KeyType key) const
{
if(node == NULL)
return NULL;
else if(node->m_key == key)
return node;
else if(node->m_key < key)
search(node->m_right, key);
else if(node->m_key > key)
search(node->m_left, key);
}
};
#endif // MYMAP_INCLUDED | [
"jennhuang8@gmail.com"
] | jennhuang8@gmail.com |
579fad4769269dc048c02b6c1a9a6e56dcc873f8 | fb9c70f790018da4e9b603396170f72010ece5a1 | /databaseHelper/hloghelper.cpp | f97061082b2842448cebba34e355fd3c46ebe89e | [] | no_license | mohistH/sqlite3_database_helper | cf2a28d7c49a3f9f4f10c2f3c492bc97f748b0cc | e50253e108aad82078900294a87f8669a3740bc7 | refs/heads/master | 2020-03-22T14:19:54.366327 | 2018-09-10T15:22:34 | 2018-09-10T15:22:34 | 140,170,730 | 1 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,697 | cpp | #include "hloghelper.h"
#include <QObject>
#include <QDir>
#include <QApplication>
#include <cstdarg>
#include <QByteArray>
HLogHelper::HLogHelper()
{
m_FileLogName = QString("");
}
// 初始化创建文件并打开文件
int HLogHelper::HInit(QString strFilePre)
{
int len = strFilePre.length();
QString fileName("");
// 设置文件名
// 1、若strFilePre不为空
if (0 < len)
{
// 获取当前日期
QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd_hh_mm_ss_zzz");
fileName = strFilePre + QString("_") + date;
}
else
{
//
QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd_hh_mm_ss_zzz");
fileName = date;
}
m_FileLogName = fileName + QString("_.log");
// 2、打开文件
// 若当前exe所在目录下不存在 HLog文件夹,则创建
QString logPath = QApplication::applicationDirPath() + QString("/HLog/");
QDir dir(logPath);
if (false == dir.exists())
{
dir.mkdir(logPath);
}
// 构造文件
m_FileLogName = logPath + m_FileLogName;
m_File.setFileName(m_FileLogName);
bool openFlag = m_File.open(QIODevice::Text | QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Append);
if (false == openFlag)
{
return 1;
}
m_LogTextStream.setDevice(&m_File);
return 0;
}
// 关闭文件
int HLogHelper::HUnInit()
{
bool isExist = m_File.exists(m_FileLogName);
// 若不存在
if (false == isExist)
{
return 1;
}
// 文件存在,检查文件是否已经打开
bool hasOepned = m_File.isOpen();
// 文件打开了
if (true == hasOepned)
{
m_File.flush();
m_File.close();
}
return 0;
}
// 日志记录前带日期
int HLogHelper::HLogTime(QString str...)
{
// 获取当前日期
QString date = m_DateTime.currentDateTime().toString("yyyy_MM_dd hh_mm_ss_zzz:");
QByteArray ba = (date + str).toLocal8Bit();
char *pArr = ba.data();
va_list al;
va_start(al, pArr);
QString strResult = QString::vasprintf(pArr, al);
va_end(al);
m_LogTextStream << strResult << endl;
m_LogTextStream.flush();
return 0;
}
// 日志前不带日期
int HLogHelper::HLog(QString str...)
{
QByteArray ba = str.toLocal8Bit();
char *pArr = ba.data();
va_list al;
va_start(al, pArr);
QString strResult = QString::vasprintf(pArr, al);
va_end(al);
m_LogTextStream << strResult << endl;
m_LogTextStream.flush();
return 0;
}
| [
"40952409+mohistH@users.noreply.github.com"
] | 40952409+mohistH@users.noreply.github.com |
b73f2a23b0f8adc30789d239819255d8306ebd8c | 7fb7d37a183fae068dfd78de293d4487977c241e | /content/browser/accessibility/browser_accessibility_gtk.h | 15dc88e177a3a71dd982c469ce4adb5df6c05081 | [
"BSD-3-Clause"
] | permissive | robclark/chromium | f643a51bb759ac682341e3bb82cc153ab928cd34 | f097b6ea775c27e5352c94ddddd264dd2af21479 | refs/heads/master | 2021-01-20T00:56:40.515459 | 2012-05-20T16:04:38 | 2012-05-20T18:56:07 | 4,587,416 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,871 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_GTK_H_
#define CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_GTK_H_
#pragma once
#include <atk/atk.h>
#include "base/compiler_specific.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "webkit/glue/webaccessibility.h"
using webkit_glue::WebAccessibility;
class BrowserAccessibilityGtk;
class BrowserAccessibilityManagerGtk;
G_BEGIN_DECLS
#define BROWSER_ACCESSIBILITY_TYPE (browser_accessibility_get_type())
#define BROWSER_ACCESSIBILITY(obj) \
(G_TYPE_CHECK_INSTANCE_CAST( \
(obj), BROWSER_ACCESSIBILITY_TYPE, BrowserAccessibilityAtk))
#define BROWSER_ACCESSIBILITY_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST( \
(klass), BROWSER_ACCESSIBILITY_TYPE, BrowserAccessibilityAtkClass))
#define IS_BROWSER_ACCESSIBILITY(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj), BROWSER_ACCESSIBILITY_TYPE))
#define IS_BROWSER_ACCESSIBILITY_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass), BROWSER_ACCESSIBILITY_TYPE))
#define BROWSER_ACCESSIBILITY_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS( \
(obj), BROWSER_ACCESSIBILITY_TYPE, BrowserAccessibilityAtkClass))
typedef struct _BrowserAccessibilityAtk BrowserAccessibilityAtk;
typedef struct _BrowserAccessibilityAtkClass BrowserAccessibilityAtkClass;
struct _BrowserAccessibilityAtk {
AtkObject parent;
BrowserAccessibilityGtk* m_object;
};
struct _BrowserAccessibilityAtkClass {
AtkObjectClass parent_class;
};
GType browser_accessibility_get_type (void) G_GNUC_CONST;
BrowserAccessibilityAtk* browser_accessibility_new(
BrowserAccessibilityGtk* object);
BrowserAccessibilityGtk* browser_accessibility_get_object(
BrowserAccessibilityAtk* atk_object);
void browser_accessibility_detach (BrowserAccessibilityAtk* atk_object);
AtkObject* browser_accessibility_get_focused_element(
BrowserAccessibilityAtk* atk_object);
G_END_DECLS
class BrowserAccessibilityGtk : public BrowserAccessibility {
public:
BrowserAccessibilityGtk();
virtual ~BrowserAccessibilityGtk();
AtkObject* GetAtkObject() const;
AtkRole atk_role() { return atk_role_; }
const std::string& atk_acc_name() { return atk_acc_name_; }
// BrowserAccessibility methods.
virtual void PreInitialize() OVERRIDE;
virtual bool IsNative() const OVERRIDE;
private:
virtual void InitRoleAndState();
// Give BrowserAccessibility::Create access to our constructor.
friend class BrowserAccessibility;
AtkObject* atk_object_;
AtkRole atk_role_;
std::string atk_acc_name_;
private:
DISALLOW_COPY_AND_ASSIGN(BrowserAccessibilityGtk);
};
#endif // CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_GTK_H_
| [
"dmazzoni@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98"
] | dmazzoni@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98 |
e4089289d2b4e3546ed6ee39e5d24f3373a952b7 | 166907c8fdf06553d61d379f936910217d6962c6 | /code_decode.cpp | bac049e737af96d4d4ec18a45234a010f5ddaead | [] | no_license | TobiasGarcia/DesafioEvaluativoV2 | ff15d66982adb989b3b6d42b68fb6f46db072cf8 | ae07a30fda1cf144532b2da8fd3b10771ba39719 | refs/heads/master | 2022-07-09T11:07:05.997673 | 2020-05-15T08:31:57 | 2020-05-15T08:31:57 | 262,444,579 | 1 | 0 | null | 2020-05-11T17:08:38 | 2020-05-08T22:52:22 | C++ | UTF-8 | C++ | false | false | 11,229 | cpp | #include "code_decode.h"
#include <iostream>
#include <fstream>
using namespace std;
//Esta libreria contiene todas las implementaciones de las funciones para codificar y decodificar texto.
//El método de codificación utilizado es el método 1 expuesto en la práctica 3 del laboratorio;
//como sabemos en este tipo de codificación hay que pasar el texto a binario, éste binario
//será almacenado en el arreglo de bools llamdado bin[].
//NOTA IMPORTANTE: La carpeta 'data' que contiene todos los .txt que sirven
//como bases de datos para el programa, debe estar dentro de la carpeta
//del proyecto que lleva el nombre de 'DesafioEvaluativoV2'. De lo contrario
//el programa no podrá encontrar esas bases de datos.
void char2bin(char chr, bool bin[], unsigned long long int pos) {
//Convertimos el carácter chr a binario y lo almacena en 8 posiciones
//contiguas del arreglo bin[] comenzando en el indice pos.
for (unsigned int i = 0; i < 8; i++) {
bin[(7 - i) + pos] = ((chr >> i) & 0x01);
}
}
void not_bin(bool bin[], unsigned long long int pos, unsigned int pass, unsigned int n) {
//Negamos un binario de n bits cada pass de digitos. El binario corresponde
//a las n posiciones contiguas de bin[] comenzando en el indice pos.
for (unsigned int i = 0; i < n; i++) {
if ((i + 1)%pass == 0) bin[pos + i] = !bin[pos + i];
}
}
void count_bin(bool bin[], unsigned long long int pos, unsigned int n, unsigned int &zeros, unsigned int &ones) {
//Contamos los ceros y unos del binario de n bits que se almacena en
//las n posiciones contiguas de bin[] comenzando en el indice pos.
//Los ceros y unos contados son almacenados en las variables zeros
//y ones, que son recibidas por referencia.
for (unsigned int i = 0; i < n; i++) {
if (bin[i + pos]) ones++;
else zeros++;
}
}
void code_method(bool bin[], unsigned long long int len, unsigned int n) {
//Ejecutamos el método de codificación 1 sobre el arreglo de bools bin[].
//La varibale len es la longitud de bin[] y n es la cantidad bits
//que tendrá cada bloque de bits según el método de codificación 1.
unsigned long long int pos = n;
unsigned int zeros = 0, ones = 0, pass;
//En el caso en que n sea mayor o igual a len, simplemente negamos los bits.
if (n >= len) not_bin(bin, 0, 1, len);
else {
//En caso contrario procedemos a recorrer los grupos de n bits,
//pero primero tenemos que negar los primeros n bits según dicta el método 1,
//aunque antes de hacerlo, contamos la cantidad de ceros y unos presentes
//para saber cada cuanto negar los bits del grupo de n bits posterior.
//Contamos los ceros y unos.
count_bin(bin, 0, n, zeros, ones);
//Negamos los bits.
not_bin(bin, 0, 1, n);
while(pos <= (len - n)) {
//Decidimos cada cuanto debemos negar los bits del grupo de n bits actual
//segun la cantidad de ceros y unos del grupo de n bits previo.
if (zeros > ones) pass = 2;
else if (zeros < ones) pass = 3;
else pass = 1;
//Reiniciamos las variables ya que son utilizadas por referencia.
zeros = 0;
ones = 0;
//Contamos los ceros y unos del grupo de n bits de la posición actual.
count_bin(bin, pos, n, zeros, ones);
//Modificamos el grupo de n bits según el valor de pass.
not_bin(bin, pos, pass, n);
pos += n;
}
//Al termianr el ciclo anterior, si la cantidad de bits no es multiplo de n,
//pos será diferente de len, por lo cual procesamos el último grupo de bits
//de longitud len - pos.
if (pos != len) {
if (zeros > ones) pass = 2;
else if (zeros < ones) pass = 3;
else pass = 1;
not_bin(bin, pos, pass, len - pos);
}
}
}
bool get_text(string path, string &text, unsigned long long int &len) {
//Leemos el archivo .txt de nombre file_name y almacenamos por referencia
//el texto contenido en él en el string text, además almacenamos su
//longitud en la variable len recibida por referencia. Retornamos
//true si el archivo pudo ser abirto, o false en caso contrario
//y no modificamos ni text ni len.
//El archivo file_name es abirto con ios::binary para leer los binarios
//almacenados sin que sean interpretados por el método get().
//NOTA IMPORTANTE: La carpeta 'data' que contiene todos los .txt que sirven
//como bases de datos para el programa, debe estar dentro de la carpeta
//del proyecto que lleva el nombre de 'DesafioEvaluativoV2'. De lo contrario
//el programa no podrá encontrar esas bases de datos.
fstream file(path, ios::in | ios::ate | ios::binary);
if (file.is_open()) {
char chr;
text = "";
//Recuperamos la longitud del texto.
len = file.tellg();
file.seekg(0);
while (file.get(chr)) text.push_back(chr);
file.close();
return true;
}
else return false;
}
void text2bin(string text, unsigned long long int len, bool *&bin) {
//Convertimos el texto del string text en binario, reservamos mediante
//memoria dinámica 8 veces la longitud del texto para almacenar
//el binario. Almacenamos la dirección de éste arreglo de bools
//en el puntero bin ingresado por referencia. La variable len
//es la longitud del string text.
bin = new bool[8*len];
unsigned long long int pos = 0;
for (unsigned long long int i = 0; i < len; i++) {
char2bin(text[i], bin, pos);
pos += 8;
}
}
short int bin2dec(bool bin[], unsigned long long pos) {
//Retornamos el entero correspondiente al binario almacenado en
//las 8 posiciones contiguas de bin[] comenzando en el índice pos.
short int num = 0, two_pow = 1;
for (unsigned int i = 0; i < 8; i++) {
if (bin[(7 - i) + pos]) num += two_pow;
two_pow *= 2;
}
return num;
}
void bin2text(bool bin[], unsigned long long len, string &text) {
//Convertimos los binarios de 8 bits almacenados en bin[] en carácteres
//y los concatena dentro del string text ingresado por referencia.
//La variable len es la londitud de text.
unsigned long long pos = 0;
for (unsigned long long i = 0; i < len; i += 8) {
text[pos] = char(bin2dec(bin, i));
pos++;
}
}
void save_text(string path, string text, unsigned long long int len) {
//Guardamos el texto del string text en el archivo de nombre file_name.
//La varibale len es la longitud de text.
//El archivo file_name es abirto con ios::binary para guardar los carácteres
//de text sin que sean interpretados.
//NOTA IMPORTANTE: La carpeta 'data' que contiene todos los .txt que sirven
//como bases de datos para el programa, debe estar dentro de la carpeta
//del proyecto que lleva el nombre de 'DesafioEvaluativoV2'. De lo contrario
//el programa no podrá encontrar esas bases de datos.
fstream file(path, ios::out | ios::binary);
for (unsigned long long int i = 0; i < len; i++) file << text[i];
file.close();
}
void decode_method(bool bin[], unsigned long long len, unsigned int n) {
//Ejecutamos el método de decodificación 1 sobre el arreglo de bools bin[].
//La varibale len es la longitud de bin[] y n es la cantidad bits
//que tendrá cada bloque de bits según el método de decodificación 1.
unsigned long long int pos = n;
unsigned int zeros = 0, ones = 0, pass;
//En el caso en que n sea mayor o igual a len, simplemente negamos los bits.
if (n >= len) not_bin(bin, 0, 1, len);
else {
//El proceso es similar a la codificación, sólo que ahora se cuentan
//los ceros y unos del grupo de n bits actual LUEGO de decodificarlos.
not_bin(bin, 0, 1, n);
count_bin(bin, 0, n, zeros, ones);
while(pos <= (len - n)) {
//Decidimos cada cuanto debemos negar los bits del grupo de n bits actual
//segun la cantidad de ceros y unos del grupo de n bits previo después de
//haber sido descodificado.
if (zeros > ones) pass = 2;
else if (zeros < ones) pass = 3;
else pass = 1;
//Reiniciamos las variables ya que son utilizadas por referencia.
zeros = 0;
ones = 0;
//Modificamos el grupo de n bits según el valor de pass.
not_bin(bin, pos, pass, n);
//Contamos los ceros y unos del grupo de n bits de la posición actual
//luego de ser decodificado.
count_bin(bin, pos, n, zeros, ones);
pos += n;
}
//De nuevo, si len no era multiplo de n, pos será diferente de len,
//por lo cual procesamos el último bloque de len - pos bits.
if (pos != len) {
if (zeros > ones) pass = 2;
else if (zeros < ones) pass = 3;
else pass = 1;
not_bin(bin, pos, pass, len - pos);
}
}
}
void code(string &text, unsigned long long int len, unsigned seed) {
//Codificamos el texto del string text recibido por referencia.
//La variable seed corresponde a la semilla de condificación,
//es decir, a el valor de n en el métodod 1. La variable len
//es la longitud de text.
bool *bin = nullptr;
text2bin(text, len, bin);
code_method(bin, 8*len, seed);
bin2text(bin, 8*len, text);
delete[] bin;
}
void decode(string &text, unsigned long long int len, unsigned seed) {
//Decodificamos el texto del string text recibido por referencia.
//La variable seed corresponde a la semilla de decondificación,
//es decir, a el valor de n en el métodod 1. La variable len
//es la longitud de text.
bool *bin = nullptr;
text2bin(text, len, bin);
decode_method(bin, 8*len, seed);
bin2text(bin, 8*len, text);
delete[] bin;
}
bool code_file(string path_nat, string path_code, unsigned int seed) {
//Codifica el texto del archivo de ruta path_nat y el resultado
//lo almacena en el archivo de ruta path_code. La codificación
//es realizada con la semilla seed.
string text;
unsigned long long int len;
if (get_text(path_nat, text, len)) {
code(text, len, seed);
save_text(path_code, text, len);
return true;
}
else {
cout << " Sorry, the native file could not be opened" << endl << endl;
return false;
}
}
bool decode_file(string path_code, string path_nat, unsigned int seed) {
//Decodifica el texto del archivo de ruta path_code y el resultado
//lo almacena en el archivo de ruta path_nat. La decodificación
//es realizada con la semilla seed.
string text;
unsigned long long int len;
if (get_text(path_code, text, len)) {
decode(text, len, seed);
save_text(path_nat, text, len);
return true;
}
else {
cout << " Sorry, the code file could not be opened" << endl << endl;
return false;
}
}
| [
"tobias.garcia@udea.edu.co"
] | tobias.garcia@udea.edu.co |
570ffd2fdb142eaa207a917e887019de69d2f3b0 | 1bf89fb4d5c624ab37c26cda4aff81d91159f159 | /word.h | 025b6251939ffcdf6d8c15dc9278af3270d4f168 | [] | no_license | mymxhdd/oop-code | 4a8b3b31dfaa6f0debd3cd08f26eab713a517d08 | 36b7c1ab512b292a04e8450c26af75eea91e26d8 | refs/heads/master | 2020-12-24T21:11:46.393767 | 2016-05-05T16:41:41 | 2016-05-05T16:41:41 | 58,139,857 | 0 | 0 | null | 2016-05-05T16:41:41 | 2016-05-05T15:11:12 | null | UTF-8 | C++ | false | false | 1,944 | h | #ifndef WORD_H
#define WORD_H
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//单词所需数据,根据需要可以进行修改
struct General
{
string _word;
string _translation;
string * _sentence;
General(string word, string translation, string * sentence = NULL) : _word(word),
_translation(translation), _sentence(NULL) { }
General() {}
};
//单词接口类
class Word
{
public:
virtual void show() = 0;
virtual void translate() = 0;
virtual void learn() = 0;
virtual void test() = 0;
virtual void addsentence() = 0;
virtual ~Word() {}
};
class Old_word : public Word {
General * oldword;
public:
Old_word(string tword, string translation, string * sentence = NULL) { oldword = new General(tword, translation, sentence); }
void show();
void translate();
void learn();
void test();
void addsentence();
};
class Rare_word : public Word {
General * rareword;
public:
Rare_word(string tword, string translation, string * sentence = NULL) { rareword = new General(tword, translation, sentence); }
void show();
void translate();
void learn();
void test();
void addsentence();
};
class Familiar_word : public Word {
General * familiarword;
public:
Familiar_word(string tword, string translation, string * sentence = NULL) { familiarword = new General(tword, translation, sentence); }
void show();
void translate();
void learn();
void test();
void addsentence();
};
class Forget_word : public Word {
General * forgetword;
public:
Forget_word(string tword, string translation, string * sentence = NULL) { forgetword = new General(tword, translation, sentence); }
void show();
void translate();
void learn();
void test();
void addsentence();
};
#endif | [
"845285227@qq.com"
] | 845285227@qq.com |
99f1230ae44c657d7a2d29dfcfea3fadc699a019 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/units/systems/si/length.hpp | 9b807f0602ffc2c655b0f83aa9259b754cf615cf | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:407f5a8e24514c09d371a4fee86150b2aa378dc80db0022f19841e7b1c7524d3
size 881
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
e4022c457124a17d39e451bddf772d0529ab5601 | f3c8d78b4f8af9a5a0d047fbae32a5c2fca0edab | /Qt/lib2/i2pd-0.1.0/src/Garlic.h | c514c52e29fb29df2af424566ec9fb3556f544b6 | [] | no_license | RinatB2017/mega_GIT | 7ddaa3ff258afee1a89503e42b6719fb57a3cc32 | f322e460a1a5029385843646ead7d6874479861e | refs/heads/master | 2023-09-02T03:44:33.869767 | 2023-08-21T08:20:14 | 2023-08-21T08:20:14 | 97,226,298 | 5 | 2 | null | 2022-12-09T10:31:43 | 2017-07-14T11:17:39 | C++ | UTF-8 | C++ | false | false | 4,355 | h | #ifndef GARLIC_H__
#define GARLIC_H__
#include <inttypes.h>
#include <map>
#include <list>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include <cryptopp/osrng.h>
#include "aes.h"
#include "I2NPProtocol.h"
#include "LeaseSet.h"
#include "Queue.h"
#include "Identity.h"
namespace i2p
{
namespace garlic
{
enum GarlicDeliveryType
{
eGarlicDeliveryTypeLocal = 0,
eGarlicDeliveryTypeDestination = 1,
eGarlicDeliveryTypeRouter = 2,
eGarlicDeliveryTypeTunnel = 3
};
#pragma pack(1)
struct ElGamalBlock
{
uint8_t sessionKey[32];
uint8_t preIV[32];
uint8_t padding[158];
};
#pragma pack()
const int INCOMING_TAGS_EXPIRATION_TIMEOUT = 900; // 15 minutes
const int OUTGOING_TAGS_EXPIRATION_TIMEOUT = 720; // 12 minutes
struct SessionTag: public i2p::data::Tag<32>
{
SessionTag (const uint8_t * buf, uint32_t ts = 0): Tag<32>(buf), creationTime (ts) {};
SessionTag () = default;
SessionTag (const SessionTag& ) = default;
SessionTag& operator= (const SessionTag& ) = default;
#ifndef _WIN32
SessionTag (SessionTag&& ) = default;
SessionTag& operator= (SessionTag&& ) = default;
#endif
uint32_t creationTime; // seconds since epoch
};
class GarlicDestination;
class GarlicRoutingSession
{
struct UnconfirmedTags
{
UnconfirmedTags (int n): numTags (n), tagsCreationTime (0) { sessionTags = new SessionTag[numTags]; };
~UnconfirmedTags () { delete[] sessionTags; };
int numTags;
SessionTag * sessionTags;
uint32_t tagsCreationTime;
};
public:
GarlicRoutingSession (GarlicDestination * owner, const i2p::data::RoutingDestination * destination, int numTags);
GarlicRoutingSession (const uint8_t * sessionKey, const SessionTag& sessionTag); // one time encryption
~GarlicRoutingSession ();
I2NPMessage * WrapSingleMessage (I2NPMessage * msg);
void TagsConfirmed (uint32_t msgID);
void SetLeaseSetUpdated () { m_LeaseSetUpdated = true; };
private:
size_t CreateAESBlock (uint8_t * buf, const I2NPMessage * msg);
size_t CreateGarlicPayload (uint8_t * payload, const I2NPMessage * msg, UnconfirmedTags * newTags);
size_t CreateGarlicClove (uint8_t * buf, const I2NPMessage * msg, bool isDestination);
size_t CreateDeliveryStatusClove (uint8_t * buf, uint32_t msgID);
UnconfirmedTags * GenerateSessionTags ();
private:
GarlicDestination * m_Owner;
const i2p::data::RoutingDestination * m_Destination;
uint8_t m_SessionKey[32];
std::list<SessionTag> m_SessionTags;
int m_NumTags;
std::map<uint32_t, UnconfirmedTags *> m_UnconfirmedTagsMsgs;
bool m_LeaseSetUpdated;
i2p::crypto::CBCEncryption m_Encryption;
CryptoPP::AutoSeededRandomPool m_Rnd;
};
class GarlicDestination: public i2p::data::LocalDestination
{
public:
GarlicDestination () {};
~GarlicDestination ();
GarlicRoutingSession * GetRoutingSession (const i2p::data::RoutingDestination& destination, int numTags);
I2NPMessage * WrapMessage (const i2p::data::RoutingDestination& destination,
I2NPMessage * msg, bool attachLeaseSet = false);
void AddSessionKey (const uint8_t * key, const uint8_t * tag); // one tag
void DeliveryStatusSent (GarlicRoutingSession * session, uint32_t msgID);
virtual void ProcessGarlicMessage (I2NPMessage * msg);
virtual void ProcessDeliveryStatusMessage (I2NPMessage * msg);
virtual void SetLeaseSetUpdated ();
virtual const i2p::data::LeaseSet * GetLeaseSet () = 0; // TODO
virtual void HandleI2NPMessage (const uint8_t * buf, size_t len, i2p::tunnel::InboundTunnel * from) = 0;
protected:
void HandleGarlicMessage (I2NPMessage * msg);
void HandleDeliveryStatusMessage (I2NPMessage * msg);
private:
void HandleAESBlock (uint8_t * buf, size_t len, std::shared_ptr<i2p::crypto::CBCDecryption> decryption,
i2p::tunnel::InboundTunnel * from);
void HandleGarlicPayload (uint8_t * buf, size_t len, i2p::tunnel::InboundTunnel * from);
private:
// outgoing sessions
std::mutex m_SessionsMutex;
std::map<i2p::data::IdentHash, GarlicRoutingSession *> m_Sessions;
// incoming
std::map<SessionTag, std::shared_ptr<i2p::crypto::CBCDecryption>> m_Tags;
// DeliveryStatus
std::map<uint32_t, GarlicRoutingSession *> m_CreatedSessions; // msgID -> session
};
}
}
#endif
| [
"tux4096@gmail.com"
] | tux4096@gmail.com |
2d452511fc305d4db14b2a05736555ba11edf079 | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/Quantity/Quantity_Consumption.hxx | 1b51fb67c86fe020c687e7bfe7ec0dcdf0658dfe | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | hxx | // Created on: 1994-02-08
// Created by: Gilles DEBARBOUILLE
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Quantity_Consumption_HeaderFile
#define _Quantity_Consumption_HeaderFile
#include <Standard_Real.hxx>
//! Defined as a measure of fuel used per unit distance
//! travelled, or distance travelled per unit of fuel.
//! It is measured in litres per 100 kilometres or in
//! miles per gallon (UK or US).
typedef double Quantity_Consumption;
#endif // _Quantity_Consumption_HeaderFile
| [
"salvatore.auriemma@opencascade.com"
] | salvatore.auriemma@opencascade.com |
f973e16859923f7daaa5f8483a57334d74ec67ee | 1af49694004c6fbc31deada5618dae37255ce978 | /android_webview/browser/gfx/surfaces_instance.cc | 94ce46cc4307826549b50dd760f1f44c0ccac39a | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 13,855 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/gfx/surfaces_instance.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "android_webview/browser/gfx/aw_render_thread_context_provider.h"
#include "android_webview/browser/gfx/deferred_gpu_command_service.h"
#include "android_webview/browser/gfx/gpu_service_web_view.h"
#include "android_webview/browser/gfx/output_surface_provider_webview.h"
#include "android_webview/browser/gfx/parent_output_surface.h"
#include "android_webview/browser/gfx/skia_output_surface_dependency_webview.h"
#include "android_webview/browser/gfx/task_queue_web_view.h"
#include "android_webview/common/aw_switches.h"
#include "base/android/build_info.h"
#include "base/command_line.h"
#include "base/stl_util.h"
#include "components/viz/common/display/renderer_settings.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/common/quads/compositor_render_pass_draw_quad.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/quads/surface_draw_quad.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "components/viz/service/display/display.h"
#include "components/viz/service/display/display_scheduler.h"
#include "components/viz/service/display/overlay_processor_stub.h"
#include "components/viz/service/display_embedder/skia_output_surface_impl.h"
#include "components/viz/service/frame_sinks/compositor_frame_sink_support.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
#include "gpu/command_buffer/service/sequence_id.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/presentation_feedback.h"
#include "ui/gfx/transform.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_share_group.h"
#include "ui/gl/init/gl_factory.h"
namespace android_webview {
namespace {
// The client_id used here should not conflict with the client_id generated
// from RenderWidgetHostImpl.
constexpr uint32_t kDefaultClientId = 0u;
SurfacesInstance* g_surfaces_instance = nullptr;
} // namespace
// static
scoped_refptr<SurfacesInstance> SurfacesInstance::GetOrCreateInstance() {
if (g_surfaces_instance)
return base::WrapRefCounted(g_surfaces_instance);
return base::WrapRefCounted(new SurfacesInstance);
}
SurfacesInstance::SurfacesInstance()
: frame_sink_id_allocator_(kDefaultClientId),
frame_sink_id_(AllocateFrameSinkId()),
output_surface_provider_(nullptr) {
// The SharedBitmapManager is null as we do not support or use software
// compositing on Android.
frame_sink_manager_ = std::make_unique<viz::FrameSinkManagerImpl>(
/*shared_bitmap_manager=*/nullptr);
parent_local_surface_id_allocator_ =
std::make_unique<viz::ParentLocalSurfaceIdAllocator>();
constexpr bool is_root = true;
support_ = std::make_unique<viz::CompositorFrameSinkSupport>(
this, frame_sink_manager_.get(), frame_sink_id_, is_root);
std::unique_ptr<viz::DisplayCompositorMemoryAndTaskController>
display_controller = output_surface_provider_.CreateDisplayController();
std::unique_ptr<viz::OutputSurface> output_surface =
output_surface_provider_.CreateOutputSurface(display_controller.get());
begin_frame_source_ = std::make_unique<viz::StubBeginFrameSource>();
auto scheduler = std::make_unique<viz::DisplayScheduler>(
begin_frame_source_.get(), nullptr /* current_task_runner */,
output_surface->capabilities().max_frames_pending);
auto overlay_processor = std::make_unique<viz::OverlayProcessorStub>();
// Android WebView has no overlay processor, and does not need to share
// gpu_task_scheduler, so it is passed in as nullptr.
// TODO(weiliangc): Android WebView should support overlays. Change
// initialize order to make this happen.
display_ = std::make_unique<viz::Display>(
nullptr /* shared_bitmap_manager */,
output_surface_provider_.renderer_settings(),
output_surface_provider_.debug_settings(), frame_sink_id_,
std::move(display_controller), std::move(output_surface),
std::move(overlay_processor), std::move(scheduler),
nullptr /* current_task_runner */);
display_->Initialize(this, frame_sink_manager_->surface_manager(),
output_surface_provider_.enable_shared_image());
frame_sink_manager_->RegisterBeginFrameSource(begin_frame_source_.get(),
frame_sink_id_);
display_->SetVisible(true);
DCHECK(!g_surfaces_instance);
g_surfaces_instance = this;
}
SurfacesInstance::~SurfacesInstance() {
DCHECK_EQ(g_surfaces_instance, this);
frame_sink_manager_->UnregisterBeginFrameSource(begin_frame_source_.get());
g_surfaces_instance = nullptr;
display_ = nullptr;
DCHECK(!output_surface_provider_.shared_context_state() ||
output_surface_provider_.shared_context_state()->HasOneRef());
DCHECK(child_ids_.empty());
}
void SurfacesInstance::DisplayOutputSurfaceLost() {
// Android WebView does not handle context loss.
LOG(FATAL) << "Render thread context loss";
}
viz::FrameSinkId SurfacesInstance::AllocateFrameSinkId() {
return frame_sink_id_allocator_.NextFrameSinkId();
}
viz::FrameSinkManagerImpl* SurfacesInstance::GetFrameSinkManager() {
return frame_sink_manager_.get();
}
void SurfacesInstance::DrawAndSwap(gfx::Size viewport,
gfx::Rect clip,
gfx::Transform transform,
const gfx::Size& frame_size,
const viz::SurfaceId& child_id,
float device_scale_factor,
const gfx::ColorSpace& color_space) {
DCHECK(base::Contains(child_ids_, child_id));
// Support for SkiaRenderer
if (output_surface_provider_.renderer_settings().use_skia_renderer) {
output_surface_provider_.gl_surface()->RecalculateClipAndTransform(
&viewport, &clip, &transform);
}
gfx::ColorSpace display_color_space =
color_space.IsValid() ? color_space : gfx::ColorSpace::CreateSRGB();
display_->SetDisplayColorSpaces(gfx::DisplayColorSpaces(display_color_space));
// Create a frame with a single SurfaceDrawQuad referencing the child
// Surface and transformed using the given transform.
auto render_pass = viz::CompositorRenderPass::Create();
render_pass->SetNew(viz::CompositorRenderPassId{1}, gfx::Rect(viewport), clip,
gfx::Transform());
render_pass->has_transparent_background = false;
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->quad_to_target_transform = transform;
quad_state->quad_layer_rect = gfx::Rect(frame_size);
quad_state->visible_quad_layer_rect = gfx::Rect(frame_size);
quad_state->clip_rect = clip;
quad_state->is_clipped = true;
quad_state->opacity = 1.f;
viz::SurfaceDrawQuad* surface_quad =
render_pass->CreateAndAppendDrawQuad<viz::SurfaceDrawQuad>();
surface_quad->SetNew(quad_state, gfx::Rect(quad_state->quad_layer_rect),
gfx::Rect(quad_state->quad_layer_rect),
viz::SurfaceRange(base::nullopt, child_id),
SK_ColorWHITE, /*stretch_content_to_fill_bounds=*/false);
surface_quad->allow_merge = !BackdropFiltersPreventMerge(child_id);
viz::CompositorFrame frame;
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.render_pass_list.push_back(std::move(render_pass));
frame.metadata.device_scale_factor = device_scale_factor;
frame.metadata.referenced_surfaces = GetChildIdsRanges();
frame.metadata.frame_token = ++next_frame_token_;
if (!root_local_surface_id_.is_valid() || viewport != surface_size_ ||
device_scale_factor != device_scale_factor_) {
parent_local_surface_id_allocator_->GenerateId();
root_local_surface_id_ =
parent_local_surface_id_allocator_->GetCurrentLocalSurfaceId();
surface_size_ = viewport;
device_scale_factor_ = device_scale_factor;
display_->SetLocalSurfaceId(root_local_surface_id_, device_scale_factor);
}
support_->SubmitCompositorFrame(root_local_surface_id_, std::move(frame));
if (output_surface_provider_.shared_context_state()) {
// GL state could be changed across frames, so we need reset GrContext.
output_surface_provider_.shared_context_state()
->PessimisticallyResetGrContext();
}
output_surface_provider_.gl_surface()->SetSize(viewport);
display_->Resize(viewport);
display_->DrawAndSwap(base::TimeTicks::Now());
// SkiaRenderer generates DidReceiveSwapBuffersAck calls.
if (!features::IsUsingSkiaRenderer()) {
// Metrics tracking in CompositorFrameReporter expects that every frame
// has non-null SwapTimings. We don't know the exact swap start/end times
// here so we use Now() as a filler.
base::TimeTicks now = base::TimeTicks::Now();
display_->DidReceiveSwapBuffersAck({now, now});
}
output_surface_provider_.gl_surface()->MaybeDidPresent(
gfx::PresentationFeedback(base::TimeTicks::Now(), base::TimeDelta(),
0 /* flags */));
}
void SurfacesInstance::AddChildId(const viz::SurfaceId& child_id) {
DCHECK(!base::Contains(child_ids_, child_id));
child_ids_.push_back(child_id);
if (root_local_surface_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::RemoveChildId(const viz::SurfaceId& child_id) {
auto itr = std::find(child_ids_.begin(), child_ids_.end(), child_id);
DCHECK(itr != child_ids_.end());
child_ids_.erase(itr);
if (root_local_surface_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::SetSolidColorRootFrame() {
DCHECK(!surface_size_.IsEmpty());
gfx::Rect rect(surface_size_);
bool is_clipped = false;
bool are_contents_opaque = true;
auto render_pass = viz::CompositorRenderPass::Create();
render_pass->SetNew(viz::CompositorRenderPassId{1}, rect, rect,
gfx::Transform());
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(), rect,
is_clipped, are_contents_opaque, 1.f,
SkBlendMode::kSrcOver, 0);
viz::SolidColorDrawQuad* solid_quad =
render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
solid_quad->SetNew(quad_state, rect, rect, SK_ColorBLACK, false);
viz::CompositorFrame frame;
frame.render_pass_list.push_back(std::move(render_pass));
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.metadata.referenced_surfaces = GetChildIdsRanges();
frame.metadata.device_scale_factor = device_scale_factor_;
frame.metadata.frame_token = ++next_frame_token_;
support_->SubmitCompositorFrame(root_local_surface_id_, std::move(frame));
}
void SurfacesInstance::DidReceiveCompositorFrameAck(
const std::vector<viz::ReturnedResource>& resources) {
ReclaimResources(resources);
}
std::vector<viz::SurfaceRange> SurfacesInstance::GetChildIdsRanges() {
std::vector<viz::SurfaceRange> child_ranges;
for (const viz::SurfaceId& surface_id : child_ids_)
child_ranges.emplace_back(surface_id);
return child_ranges;
}
void SurfacesInstance::OnBeginFrame(
const viz::BeginFrameArgs& args,
const viz::FrameTimingDetailsMap& timing_details) {}
void SurfacesInstance::ReclaimResources(
const std::vector<viz::ReturnedResource>& resources) {
// Root surface should have no resources to return.
CHECK(resources.empty());
}
void SurfacesInstance::OnBeginFramePausedChanged(bool paused) {}
base::TimeDelta SurfacesInstance::GetPreferredFrameIntervalForFrameSinkId(
const viz::FrameSinkId& id,
viz::mojom::CompositorFrameSinkType* type) {
return frame_sink_manager_->GetPreferredFrameIntervalForFrameSinkId(id, type);
}
bool SurfacesInstance::BackdropFiltersPreventMerge(
const viz::SurfaceId& surface_id) {
// TODO(ericrk): This function makes the pessemistic assumption that any
// backdrop filter prevents merging this surface. This is not true in a
// number of cases:
// - SkiaRenderer may handle framebuffer readback in some cases.
// - This is not needed if framebuffer format is not floating point.
//
// In the future we should optimize this more and avoid the intermediate
// in the cases listed above. crbug.com/996434
const viz::Surface* surface =
frame_sink_manager_->surface_manager()->GetSurfaceForId(surface_id);
if (!surface || !surface->HasActiveFrame())
return false;
const auto& frame = surface->GetActiveFrame();
base::flat_set<viz::CompositorRenderPassId> backdrop_filter_passes;
for (const auto& render_pass : frame.render_pass_list) {
if (!render_pass->backdrop_filters.IsEmpty())
backdrop_filter_passes.insert(render_pass->id);
}
if (backdrop_filter_passes.empty())
return false;
const auto* root_pass = frame.render_pass_list.back().get();
for (const auto* quad : root_pass->quad_list) {
if (quad->material != viz::DrawQuad::Material::kCompositorRenderPass)
continue;
const auto* pass_quad =
viz::CompositorRenderPassDrawQuad::MaterialCast(quad);
if (backdrop_filter_passes.find(pass_quad->render_pass_id) !=
backdrop_filter_passes.end()) {
return true;
}
}
return false;
}
} // namespace android_webview
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
075f23a6ea32bc9db6f8ad7fae28b79ab1048358 | 504897361f656d0cbc63a2817289983dcf9e1757 | /Bit_Strings.cpp | bc273ee658b9f57cbe4a66013f45d84a11548ff0 | [] | no_license | DIPJOY10/CSES-Introductory-Problemset | 6803b1bfd232b1c6a131aee94b23e1f2b0a7a11a | 067e60130f6803b41fa0abd5af1fdbf751bf4345 | refs/heads/main | 2023-04-03T00:13:41.714656 | 2021-03-26T13:01:45 | 2021-03-26T13:01:45 | 351,779,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | //author: Dipjoy Basak
//dip_10
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define pi pair<int, int>
#define vpi vector<pair<int, int>>
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define rrep(i, r, l) for (int i = r; i >= l; i--)
#define debug(x) cout << x << "debug" << endl;
#define maxn 1000005
void solve()
{
int n;
cin >> n;
int mod = 1e9 + 7;
int ans = 1;
rep(i, 1, n)
{
ans = (ans * 2) % mod;
}
cout << ans << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
t = 1;
// cin >> t;
while (t--)
{
solve();
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
157383ac95b60ac0ea1d93f1c5508a1edb2bf1fc | 70dca6815c2157a2ae49d3c6f7ab3bad879adddc | /leetcode/cpp/33.search-in-rotated-sorted-array.cpp | 83fc47663d259fd3f45eefd8818af8fe22d1e748 | [
"BSD-3-Clause"
] | permissive | phiysng/leetcode | 25229b829d2685f56ea3b58337136ebe7b810ca5 | a8ec1e598e92c2155f8abefa4c4bf5ce8c3838fa | refs/heads/master | 2023-03-03T08:30:19.677369 | 2023-02-19T10:32:17 | 2023-02-19T10:32:17 | 180,983,537 | 5 | 0 | BSD-3-Clause | 2019-12-03T10:24:18 | 2019-04-12T10:11:58 | C++ | UTF-8 | C++ | false | false | 2,094 | cpp | #include "oj_header.h"
class Solution {
public:
int search(vector<int>& nums, int target)
{
// 拓展的二分查找
// 不存在重复的元素
int l = 0, r = nums.size() - 1;
this->nums = nums;
this->target = target;
int n = nums.size();
if (n == 0)
return -1;
if (n == 1)
return nums[0] == target ? 0 : -1;
// n >= 2
// [0,n-1] 闭区间
int rotate_index = find_rotate_index(0, n - 1);
// 最小的点
if (nums[rotate_index] == target) {
return rotate_index;
}
// 顺序增加的情况
if (rotate_index == 0) {
return binary_search(0, n - 1);
}
// 搜索后半部分
if (target < nums[0]) {
return binary_search(rotate_index, n - 1);
}
return binary_search(0, rotate_index - 1);
}
// 寻找最小的分界点
int find_rotate_index(int left, int right)
{
//顺序的情况
if (nums[left] < nums[right]) {
return 0;
}
// 二分
while (left <= right) {
int mid = (left + right) / 2;
//mid + 1 是旋转后的nums[0]
if (nums[mid] > nums[mid + 1]) {
return mid + 1;
} else {
if (nums[mid] < nums[left]) {
// 在后半段
right = mid - 1;
} else {
left = mid + 1;
}
}
}
return 0;
}
// 标准的二分查找
int binary_search(int left, int right)
{
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target)
return mid;
else {
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
private:
int target;
vector<int> nums;
};
| [
"wuyuanshou@protonmail.com"
] | wuyuanshou@protonmail.com |
469b8334aff5671259aecc307062d8f6c2aadb4e | 77f8410a1b13402b33806ac45263a61d0c3aba90 | /v8/src/compiler/common-operator.cc | f7aa71e3dcdfc5e7763be3d95366ccc9e1c41668 | [] | no_license | ngot/libv8 | 93d5a874cffce7373bb13f4cba343d7e906524a5 | 34abbc81c745a896221918e75dc8658337c7a1f1 | refs/heads/master | 2021-06-26T07:31:23.672284 | 2017-09-15T16:22:01 | 2017-09-15T16:22:01 | 103,535,365 | 17 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 52,978 | cc | // Copyright 2014 the V8 project 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 "src/compiler/common-operator.h"
#include "src/assembler.h"
#include "src/base/lazy-instance.h"
#include "src/compiler/linkage.h"
#include "src/compiler/node.h"
#include "src/compiler/opcodes.h"
#include "src/compiler/operator.h"
#include "src/handles-inl.h"
#include "src/zone/zone.h"
namespace v8 {
namespace internal {
namespace compiler {
std::ostream& operator<<(std::ostream& os, BranchHint hint) {
switch (hint) {
case BranchHint::kNone:
return os << "None";
case BranchHint::kTrue:
return os << "True";
case BranchHint::kFalse:
return os << "False";
}
UNREACHABLE();
}
BranchHint BranchHintOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kBranch, op->opcode());
return OpParameter<BranchHint>(op);
}
int ValueInputCountOfReturn(Operator const* const op) {
DCHECK(op->opcode() == IrOpcode::kReturn);
// Return nodes have a hidden input at index 0 which we ignore in the value
// input count.
return op->ValueInputCount() - 1;
}
bool operator==(DeoptimizeParameters lhs, DeoptimizeParameters rhs) {
return lhs.kind() == rhs.kind() && lhs.reason() == rhs.reason();
}
bool operator!=(DeoptimizeParameters lhs, DeoptimizeParameters rhs) {
return !(lhs == rhs);
}
size_t hash_value(DeoptimizeParameters p) {
return base::hash_combine(p.kind(), p.reason());
}
std::ostream& operator<<(std::ostream& os, DeoptimizeParameters p) {
return os << p.kind() << ":" << p.reason();
}
DeoptimizeParameters const& DeoptimizeParametersOf(Operator const* const op) {
DCHECK(op->opcode() == IrOpcode::kDeoptimize ||
op->opcode() == IrOpcode::kDeoptimizeIf ||
op->opcode() == IrOpcode::kDeoptimizeUnless);
return OpParameter<DeoptimizeParameters>(op);
}
bool operator==(SelectParameters const& lhs, SelectParameters const& rhs) {
return lhs.representation() == rhs.representation() &&
lhs.hint() == rhs.hint();
}
bool operator!=(SelectParameters const& lhs, SelectParameters const& rhs) {
return !(lhs == rhs);
}
size_t hash_value(SelectParameters const& p) {
return base::hash_combine(p.representation(), p.hint());
}
std::ostream& operator<<(std::ostream& os, SelectParameters const& p) {
return os << p.representation() << "|" << p.hint();
}
SelectParameters const& SelectParametersOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kSelect, op->opcode());
return OpParameter<SelectParameters>(op);
}
CallDescriptor const* CallDescriptorOf(const Operator* const op) {
DCHECK(op->opcode() == IrOpcode::kCall ||
op->opcode() == IrOpcode::kCallWithCallerSavedRegisters ||
op->opcode() == IrOpcode::kTailCall);
return OpParameter<CallDescriptor const*>(op);
}
size_t ProjectionIndexOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kProjection, op->opcode());
return OpParameter<size_t>(op);
}
MachineRepresentation PhiRepresentationOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kPhi, op->opcode());
return OpParameter<MachineRepresentation>(op);
}
int ParameterIndexOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kParameter, op->opcode());
return OpParameter<ParameterInfo>(op).index();
}
const ParameterInfo& ParameterInfoOf(const Operator* const op) {
DCHECK_EQ(IrOpcode::kParameter, op->opcode());
return OpParameter<ParameterInfo>(op);
}
bool operator==(ParameterInfo const& lhs, ParameterInfo const& rhs) {
return lhs.index() == rhs.index();
}
bool operator!=(ParameterInfo const& lhs, ParameterInfo const& rhs) {
return !(lhs == rhs);
}
size_t hash_value(ParameterInfo const& p) { return p.index(); }
std::ostream& operator<<(std::ostream& os, ParameterInfo const& i) {
if (i.debug_name()) os << i.debug_name() << '#';
os << i.index();
return os;
}
std::ostream& operator<<(std::ostream& os, ObjectStateInfo const& i) {
return os << "id:" << i.object_id() << "|size:" << i.size();
}
size_t hash_value(ObjectStateInfo const& p) {
return base::hash_combine(p.object_id(), p.size());
}
std::ostream& operator<<(std::ostream& os, TypedObjectStateInfo const& i) {
return os << "id:" << i.object_id() << "|" << i.machine_types();
}
size_t hash_value(TypedObjectStateInfo const& p) {
return base::hash_combine(p.object_id(), p.machine_types());
}
bool operator==(RelocatablePtrConstantInfo const& lhs,
RelocatablePtrConstantInfo const& rhs) {
return lhs.rmode() == rhs.rmode() && lhs.value() == rhs.value() &&
lhs.type() == rhs.type();
}
bool operator!=(RelocatablePtrConstantInfo const& lhs,
RelocatablePtrConstantInfo const& rhs) {
return !(lhs == rhs);
}
size_t hash_value(RelocatablePtrConstantInfo const& p) {
return base::hash_combine(p.value(), p.rmode(), p.type());
}
std::ostream& operator<<(std::ostream& os,
RelocatablePtrConstantInfo const& p) {
return os << p.value() << "|" << p.rmode() << "|" << p.type();
}
SparseInputMask::InputIterator::InputIterator(
SparseInputMask::BitMaskType bit_mask, Node* parent)
: bit_mask_(bit_mask), parent_(parent), real_index_(0) {
#if DEBUG
if (bit_mask_ != SparseInputMask::kDenseBitMask) {
DCHECK_EQ(base::bits::CountPopulation(bit_mask_) -
base::bits::CountPopulation(kEndMarker),
parent->InputCount());
}
#endif
}
void SparseInputMask::InputIterator::Advance() {
DCHECK(!IsEnd());
if (IsReal()) {
++real_index_;
}
bit_mask_ >>= 1;
}
Node* SparseInputMask::InputIterator::GetReal() const {
DCHECK(IsReal());
return parent_->InputAt(real_index_);
}
bool SparseInputMask::InputIterator::IsReal() const {
return bit_mask_ == SparseInputMask::kDenseBitMask ||
(bit_mask_ & kEntryMask);
}
bool SparseInputMask::InputIterator::IsEnd() const {
return (bit_mask_ == kEndMarker) ||
(bit_mask_ == SparseInputMask::kDenseBitMask &&
real_index_ >= parent_->InputCount());
}
int SparseInputMask::CountReal() const {
DCHECK(!IsDense());
return base::bits::CountPopulation(bit_mask_) -
base::bits::CountPopulation(kEndMarker);
}
SparseInputMask::InputIterator SparseInputMask::IterateOverInputs(Node* node) {
DCHECK(IsDense() || CountReal() == node->InputCount());
return InputIterator(bit_mask_, node);
}
bool operator==(SparseInputMask const& lhs, SparseInputMask const& rhs) {
return lhs.mask() == rhs.mask();
}
bool operator!=(SparseInputMask const& lhs, SparseInputMask const& rhs) {
return !(lhs == rhs);
}
size_t hash_value(SparseInputMask const& p) {
return base::hash_value(p.mask());
}
std::ostream& operator<<(std::ostream& os, SparseInputMask const& p) {
if (p.IsDense()) {
return os << "dense";
} else {
SparseInputMask::BitMaskType mask = p.mask();
DCHECK_NE(mask, SparseInputMask::kDenseBitMask);
os << "sparse:";
while (mask != SparseInputMask::kEndMarker) {
if (mask & SparseInputMask::kEntryMask) {
os << "^";
} else {
os << ".";
}
mask >>= 1;
}
return os;
}
}
bool operator==(TypedStateValueInfo const& lhs,
TypedStateValueInfo const& rhs) {
return lhs.machine_types() == rhs.machine_types() &&
lhs.sparse_input_mask() == rhs.sparse_input_mask();
}
bool operator!=(TypedStateValueInfo const& lhs,
TypedStateValueInfo const& rhs) {
return !(lhs == rhs);
}
size_t hash_value(TypedStateValueInfo const& p) {
return base::hash_combine(p.machine_types(), p.sparse_input_mask());
}
std::ostream& operator<<(std::ostream& os, TypedStateValueInfo const& p) {
return os << p.machine_types() << "|" << p.sparse_input_mask();
}
size_t hash_value(RegionObservability observability) {
return static_cast<size_t>(observability);
}
std::ostream& operator<<(std::ostream& os, RegionObservability observability) {
switch (observability) {
case RegionObservability::kObservable:
return os << "observable";
case RegionObservability::kNotObservable:
return os << "not-observable";
}
UNREACHABLE();
}
RegionObservability RegionObservabilityOf(Operator const* op) {
DCHECK_EQ(IrOpcode::kBeginRegion, op->opcode());
return OpParameter<RegionObservability>(op);
}
ZoneHandleSet<Map> MapGuardMapsOf(Operator const* op) {
DCHECK_EQ(IrOpcode::kMapGuard, op->opcode());
return OpParameter<ZoneHandleSet<Map>>(op);
}
Type* TypeGuardTypeOf(Operator const* op) {
DCHECK_EQ(IrOpcode::kTypeGuard, op->opcode());
return OpParameter<Type*>(op);
}
std::ostream& operator<<(std::ostream& os,
const ZoneVector<MachineType>* types) {
// Print all the MachineTypes, separated by commas.
bool first = true;
for (MachineType elem : *types) {
if (!first) {
os << ", ";
}
first = false;
os << elem;
}
return os;
}
int OsrValueIndexOf(Operator const* op) {
DCHECK_EQ(IrOpcode::kOsrValue, op->opcode());
return OpParameter<int>(op);
}
SparseInputMask SparseInputMaskOf(Operator const* op) {
DCHECK(op->opcode() == IrOpcode::kStateValues ||
op->opcode() == IrOpcode::kTypedStateValues);
if (op->opcode() == IrOpcode::kTypedStateValues) {
return OpParameter<TypedStateValueInfo>(op).sparse_input_mask();
}
return OpParameter<SparseInputMask>(op);
}
ZoneVector<MachineType> const* MachineTypesOf(Operator const* op) {
DCHECK(op->opcode() == IrOpcode::kTypedObjectState ||
op->opcode() == IrOpcode::kTypedStateValues);
if (op->opcode() == IrOpcode::kTypedStateValues) {
return OpParameter<TypedStateValueInfo>(op).machine_types();
}
return OpParameter<TypedObjectStateInfo>(op).machine_types();
}
#define COMMON_CACHED_OP_LIST(V) \
V(Dead, Operator::kFoldable, 0, 0, 0, 1, 1, 1) \
V(IfTrue, Operator::kKontrol, 0, 0, 1, 0, 0, 1) \
V(IfFalse, Operator::kKontrol, 0, 0, 1, 0, 0, 1) \
V(IfSuccess, Operator::kKontrol, 0, 0, 1, 0, 0, 1) \
V(IfException, Operator::kKontrol, 0, 1, 1, 1, 1, 1) \
V(IfDefault, Operator::kKontrol, 0, 0, 1, 0, 0, 1) \
V(Throw, Operator::kKontrol, 0, 1, 1, 0, 0, 1) \
V(Terminate, Operator::kKontrol, 0, 1, 1, 0, 0, 1) \
V(OsrNormalEntry, Operator::kFoldable, 0, 1, 1, 0, 1, 1) \
V(OsrLoopEntry, Operator::kFoldable | Operator::kNoThrow, 0, 1, 1, 0, 1, 1) \
V(LoopExit, Operator::kKontrol, 0, 0, 2, 0, 0, 1) \
V(LoopExitValue, Operator::kPure, 1, 0, 1, 1, 0, 0) \
V(LoopExitEffect, Operator::kNoThrow, 0, 1, 1, 0, 1, 0) \
V(Checkpoint, Operator::kKontrol, 0, 1, 1, 0, 1, 0) \
V(FinishRegion, Operator::kKontrol, 1, 1, 0, 1, 1, 0) \
V(Retain, Operator::kKontrol, 1, 1, 0, 0, 1, 0)
#define CACHED_RETURN_LIST(V) \
V(1) \
V(2) \
V(3) \
V(4)
#define CACHED_END_LIST(V) \
V(1) \
V(2) \
V(3) \
V(4) \
V(5) \
V(6) \
V(7) \
V(8)
#define CACHED_EFFECT_PHI_LIST(V) \
V(1) \
V(2) \
V(3) \
V(4) \
V(5) \
V(6)
#define CACHED_INDUCTION_VARIABLE_PHI_LIST(V) \
V(4) \
V(5) \
V(6) \
V(7)
#define CACHED_LOOP_LIST(V) \
V(1) \
V(2)
#define CACHED_MERGE_LIST(V) \
V(1) \
V(2) \
V(3) \
V(4) \
V(5) \
V(6) \
V(7) \
V(8)
#define CACHED_DEOPTIMIZE_LIST(V) \
V(Eager, MinusZero) \
V(Eager, NoReason) \
V(Eager, WrongMap) \
V(Soft, InsufficientTypeFeedbackForGenericKeyedAccess) \
V(Soft, InsufficientTypeFeedbackForGenericNamedAccess)
#define CACHED_DEOPTIMIZE_IF_LIST(V) \
V(Eager, DivisionByZero) \
V(Eager, Hole) \
V(Eager, MinusZero) \
V(Eager, Overflow) \
V(Eager, Smi)
#define CACHED_DEOPTIMIZE_UNLESS_LIST(V) \
V(Eager, LostPrecision) \
V(Eager, LostPrecisionOrNaN) \
V(Eager, NoReason) \
V(Eager, NotAHeapNumber) \
V(Eager, NotANumberOrOddball) \
V(Eager, NotASmi) \
V(Eager, OutOfBounds) \
V(Eager, WrongInstanceType) \
V(Eager, WrongMap)
#define CACHED_TRAP_IF_LIST(V) \
V(TrapDivUnrepresentable) \
V(TrapFloatUnrepresentable)
// The reason for a trap.
#define CACHED_TRAP_UNLESS_LIST(V) \
V(TrapUnreachable) \
V(TrapMemOutOfBounds) \
V(TrapDivByZero) \
V(TrapDivUnrepresentable) \
V(TrapRemByZero) \
V(TrapFloatUnrepresentable) \
V(TrapFuncInvalid) \
V(TrapFuncSigMismatch)
#define CACHED_PARAMETER_LIST(V) \
V(0) \
V(1) \
V(2) \
V(3) \
V(4) \
V(5) \
V(6)
#define CACHED_PHI_LIST(V) \
V(kTagged, 1) \
V(kTagged, 2) \
V(kTagged, 3) \
V(kTagged, 4) \
V(kTagged, 5) \
V(kTagged, 6) \
V(kBit, 2) \
V(kFloat64, 2) \
V(kWord32, 2)
#define CACHED_PROJECTION_LIST(V) \
V(0) \
V(1)
#define CACHED_STATE_VALUES_LIST(V) \
V(0) \
V(1) \
V(2) \
V(3) \
V(4) \
V(5) \
V(6) \
V(7) \
V(8) \
V(10) \
V(11) \
V(12) \
V(13) \
V(14)
struct CommonOperatorGlobalCache final {
#define CACHED(Name, properties, value_input_count, effect_input_count, \
control_input_count, value_output_count, effect_output_count, \
control_output_count) \
struct Name##Operator final : public Operator { \
Name##Operator() \
: Operator(IrOpcode::k##Name, properties, #Name, value_input_count, \
effect_input_count, control_input_count, \
value_output_count, effect_output_count, \
control_output_count) {} \
}; \
Name##Operator k##Name##Operator;
COMMON_CACHED_OP_LIST(CACHED)
#undef CACHED
template <size_t kInputCount>
struct EndOperator final : public Operator {
EndOperator()
: Operator( // --
IrOpcode::kEnd, Operator::kKontrol, // opcode
"End", // name
0, 0, kInputCount, 0, 0, 0) {} // counts
};
#define CACHED_END(input_count) \
EndOperator<input_count> kEnd##input_count##Operator;
CACHED_END_LIST(CACHED_END)
#undef CACHED_END
template <size_t kValueInputCount>
struct ReturnOperator final : public Operator {
ReturnOperator()
: Operator( // --
IrOpcode::kReturn, Operator::kNoThrow, // opcode
"Return", // name
kValueInputCount + 1, 1, 1, 0, 0, 1) {} // counts
};
#define CACHED_RETURN(value_input_count) \
ReturnOperator<value_input_count> kReturn##value_input_count##Operator;
CACHED_RETURN_LIST(CACHED_RETURN)
#undef CACHED_RETURN
template <BranchHint kBranchHint>
struct BranchOperator final : public Operator1<BranchHint> {
BranchOperator()
: Operator1<BranchHint>( // --
IrOpcode::kBranch, Operator::kKontrol, // opcode
"Branch", // name
1, 0, 1, 0, 0, 2, // counts
kBranchHint) {} // parameter
};
BranchOperator<BranchHint::kNone> kBranchNoneOperator;
BranchOperator<BranchHint::kTrue> kBranchTrueOperator;
BranchOperator<BranchHint::kFalse> kBranchFalseOperator;
template <int kEffectInputCount>
struct EffectPhiOperator final : public Operator {
EffectPhiOperator()
: Operator( // --
IrOpcode::kEffectPhi, Operator::kKontrol, // opcode
"EffectPhi", // name
0, kEffectInputCount, 1, 0, 1, 0) {} // counts
};
#define CACHED_EFFECT_PHI(input_count) \
EffectPhiOperator<input_count> kEffectPhi##input_count##Operator;
CACHED_EFFECT_PHI_LIST(CACHED_EFFECT_PHI)
#undef CACHED_EFFECT_PHI
template <RegionObservability kRegionObservability>
struct BeginRegionOperator final : public Operator1<RegionObservability> {
BeginRegionOperator()
: Operator1<RegionObservability>( // --
IrOpcode::kBeginRegion, Operator::kKontrol, // opcode
"BeginRegion", // name
0, 1, 0, 0, 1, 0, // counts
kRegionObservability) {} // parameter
};
BeginRegionOperator<RegionObservability::kObservable>
kBeginRegionObservableOperator;
BeginRegionOperator<RegionObservability::kNotObservable>
kBeginRegionNotObservableOperator;
template <size_t kInputCount>
struct LoopOperator final : public Operator {
LoopOperator()
: Operator( // --
IrOpcode::kLoop, Operator::kKontrol, // opcode
"Loop", // name
0, 0, kInputCount, 0, 0, 1) {} // counts
};
#define CACHED_LOOP(input_count) \
LoopOperator<input_count> kLoop##input_count##Operator;
CACHED_LOOP_LIST(CACHED_LOOP)
#undef CACHED_LOOP
template <size_t kInputCount>
struct MergeOperator final : public Operator {
MergeOperator()
: Operator( // --
IrOpcode::kMerge, Operator::kKontrol, // opcode
"Merge", // name
0, 0, kInputCount, 0, 0, 1) {} // counts
};
#define CACHED_MERGE(input_count) \
MergeOperator<input_count> kMerge##input_count##Operator;
CACHED_MERGE_LIST(CACHED_MERGE)
#undef CACHED_MERGE
template <DeoptimizeKind kKind, DeoptimizeReason kReason>
struct DeoptimizeOperator final : public Operator1<DeoptimizeParameters> {
DeoptimizeOperator()
: Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimize, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"Deoptimize", // name
1, 1, 1, 0, 0, 1, // counts
DeoptimizeParameters(kKind, kReason)) {} // parameter
};
#define CACHED_DEOPTIMIZE(Kind, Reason) \
DeoptimizeOperator<DeoptimizeKind::k##Kind, DeoptimizeReason::k##Reason> \
kDeoptimize##Kind##Reason##Operator;
CACHED_DEOPTIMIZE_LIST(CACHED_DEOPTIMIZE)
#undef CACHED_DEOPTIMIZE
template <DeoptimizeKind kKind, DeoptimizeReason kReason>
struct DeoptimizeIfOperator final : public Operator1<DeoptimizeParameters> {
DeoptimizeIfOperator()
: Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimizeIf, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"DeoptimizeIf", // name
2, 1, 1, 0, 1, 1, // counts
DeoptimizeParameters(kKind, kReason)) {} // parameter
};
#define CACHED_DEOPTIMIZE_IF(Kind, Reason) \
DeoptimizeIfOperator<DeoptimizeKind::k##Kind, DeoptimizeReason::k##Reason> \
kDeoptimizeIf##Kind##Reason##Operator;
CACHED_DEOPTIMIZE_IF_LIST(CACHED_DEOPTIMIZE_IF)
#undef CACHED_DEOPTIMIZE_IF
template <DeoptimizeKind kKind, DeoptimizeReason kReason>
struct DeoptimizeUnlessOperator final
: public Operator1<DeoptimizeParameters> {
DeoptimizeUnlessOperator()
: Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimizeUnless, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"DeoptimizeUnless", // name
2, 1, 1, 0, 1, 1, // counts
DeoptimizeParameters(kKind, kReason)) {} // parameter
};
#define CACHED_DEOPTIMIZE_UNLESS(Kind, Reason) \
DeoptimizeUnlessOperator<DeoptimizeKind::k##Kind, \
DeoptimizeReason::k##Reason> \
kDeoptimizeUnless##Kind##Reason##Operator;
CACHED_DEOPTIMIZE_UNLESS_LIST(CACHED_DEOPTIMIZE_UNLESS)
#undef CACHED_DEOPTIMIZE_UNLESS
template <int32_t trap_id>
struct TrapIfOperator final : public Operator1<int32_t> {
TrapIfOperator()
: Operator1<int32_t>( // --
IrOpcode::kTrapIf, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"TrapIf", // name
1, 1, 1, 0, 0, 1, // counts
trap_id) {} // parameter
};
#define CACHED_TRAP_IF(Trap) \
TrapIfOperator<static_cast<int32_t>(Builtins::kThrowWasm##Trap)> \
kTrapIf##Trap##Operator;
CACHED_TRAP_IF_LIST(CACHED_TRAP_IF)
#undef CACHED_TRAP_IF
template <int32_t trap_id>
struct TrapUnlessOperator final : public Operator1<int32_t> {
TrapUnlessOperator()
: Operator1<int32_t>( // --
IrOpcode::kTrapUnless, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"TrapUnless", // name
1, 1, 1, 0, 0, 1, // counts
trap_id) {} // parameter
};
#define CACHED_TRAP_UNLESS(Trap) \
TrapUnlessOperator<static_cast<int32_t>(Builtins::kThrowWasm##Trap)> \
kTrapUnless##Trap##Operator;
CACHED_TRAP_UNLESS_LIST(CACHED_TRAP_UNLESS)
#undef CACHED_TRAP_UNLESS
template <MachineRepresentation kRep, int kInputCount>
struct PhiOperator final : public Operator1<MachineRepresentation> {
PhiOperator()
: Operator1<MachineRepresentation>( //--
IrOpcode::kPhi, Operator::kPure, // opcode
"Phi", // name
kInputCount, 0, 1, 1, 0, 0, // counts
kRep) {} // parameter
};
#define CACHED_PHI(rep, input_count) \
PhiOperator<MachineRepresentation::rep, input_count> \
kPhi##rep##input_count##Operator;
CACHED_PHI_LIST(CACHED_PHI)
#undef CACHED_PHI
template <int kInputCount>
struct InductionVariablePhiOperator final : public Operator {
InductionVariablePhiOperator()
: Operator( //--
IrOpcode::kInductionVariablePhi, Operator::kPure, // opcode
"InductionVariablePhi", // name
kInputCount, 0, 1, 1, 0, 0) {} // counts
};
#define CACHED_INDUCTION_VARIABLE_PHI(input_count) \
InductionVariablePhiOperator<input_count> \
kInductionVariablePhi##input_count##Operator;
CACHED_INDUCTION_VARIABLE_PHI_LIST(CACHED_INDUCTION_VARIABLE_PHI)
#undef CACHED_INDUCTION_VARIABLE_PHI
template <int kIndex>
struct ParameterOperator final : public Operator1<ParameterInfo> {
ParameterOperator()
: Operator1<ParameterInfo>( // --
IrOpcode::kParameter, Operator::kPure, // opcode
"Parameter", // name
1, 0, 0, 1, 0, 0, // counts,
ParameterInfo(kIndex, nullptr)) {} // parameter and name
};
#define CACHED_PARAMETER(index) \
ParameterOperator<index> kParameter##index##Operator;
CACHED_PARAMETER_LIST(CACHED_PARAMETER)
#undef CACHED_PARAMETER
template <size_t kIndex>
struct ProjectionOperator final : public Operator1<size_t> {
ProjectionOperator()
: Operator1<size_t>( // --
IrOpcode::kProjection, // opcode
Operator::kPure, // flags
"Projection", // name
1, 0, 1, 1, 0, 0, // counts,
kIndex) {} // parameter
};
#define CACHED_PROJECTION(index) \
ProjectionOperator<index> kProjection##index##Operator;
CACHED_PROJECTION_LIST(CACHED_PROJECTION)
#undef CACHED_PROJECTION
template <int kInputCount>
struct StateValuesOperator final : public Operator1<SparseInputMask> {
StateValuesOperator()
: Operator1<SparseInputMask>( // --
IrOpcode::kStateValues, // opcode
Operator::kPure, // flags
"StateValues", // name
kInputCount, 0, 0, 1, 0, 0, // counts
SparseInputMask::Dense()) {} // parameter
};
#define CACHED_STATE_VALUES(input_count) \
StateValuesOperator<input_count> kStateValues##input_count##Operator;
CACHED_STATE_VALUES_LIST(CACHED_STATE_VALUES)
#undef CACHED_STATE_VALUES
};
static base::LazyInstance<CommonOperatorGlobalCache>::type
kCommonOperatorGlobalCache = LAZY_INSTANCE_INITIALIZER;
CommonOperatorBuilder::CommonOperatorBuilder(Zone* zone)
: cache_(kCommonOperatorGlobalCache.Get()), zone_(zone) {}
#define CACHED(Name, properties, value_input_count, effect_input_count, \
control_input_count, value_output_count, effect_output_count, \
control_output_count) \
const Operator* CommonOperatorBuilder::Name() { \
return &cache_.k##Name##Operator; \
}
COMMON_CACHED_OP_LIST(CACHED)
#undef CACHED
const Operator* CommonOperatorBuilder::End(size_t control_input_count) {
switch (control_input_count) {
#define CACHED_END(input_count) \
case input_count: \
return &cache_.kEnd##input_count##Operator;
CACHED_END_LIST(CACHED_END)
#undef CACHED_END
default:
break;
}
// Uncached.
return new (zone()) Operator( //--
IrOpcode::kEnd, Operator::kKontrol, // opcode
"End", // name
0, 0, control_input_count, 0, 0, 0); // counts
}
const Operator* CommonOperatorBuilder::Return(int value_input_count) {
switch (value_input_count) {
#define CACHED_RETURN(input_count) \
case input_count: \
return &cache_.kReturn##input_count##Operator;
CACHED_RETURN_LIST(CACHED_RETURN)
#undef CACHED_RETURN
default:
break;
}
// Uncached.
return new (zone()) Operator( //--
IrOpcode::kReturn, Operator::kNoThrow, // opcode
"Return", // name
value_input_count + 1, 1, 1, 0, 0, 1); // counts
}
const Operator* CommonOperatorBuilder::Branch(BranchHint hint) {
switch (hint) {
case BranchHint::kNone:
return &cache_.kBranchNoneOperator;
case BranchHint::kTrue:
return &cache_.kBranchTrueOperator;
case BranchHint::kFalse:
return &cache_.kBranchFalseOperator;
}
UNREACHABLE();
}
const Operator* CommonOperatorBuilder::Deoptimize(DeoptimizeKind kind,
DeoptimizeReason reason) {
#define CACHED_DEOPTIMIZE(Kind, Reason) \
if (kind == DeoptimizeKind::k##Kind && \
reason == DeoptimizeReason::k##Reason) { \
return &cache_.kDeoptimize##Kind##Reason##Operator; \
}
CACHED_DEOPTIMIZE_LIST(CACHED_DEOPTIMIZE)
#undef CACHED_DEOPTIMIZE
// Uncached
DeoptimizeParameters parameter(kind, reason);
return new (zone()) Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimize, // opcodes
Operator::kFoldable | Operator::kNoThrow, // properties
"Deoptimize", // name
1, 1, 1, 0, 0, 1, // counts
parameter); // parameter
}
const Operator* CommonOperatorBuilder::DeoptimizeIf(DeoptimizeKind kind,
DeoptimizeReason reason) {
#define CACHED_DEOPTIMIZE_IF(Kind, Reason) \
if (kind == DeoptimizeKind::k##Kind && \
reason == DeoptimizeReason::k##Reason) { \
return &cache_.kDeoptimizeIf##Kind##Reason##Operator; \
}
CACHED_DEOPTIMIZE_IF_LIST(CACHED_DEOPTIMIZE_IF)
#undef CACHED_DEOPTIMIZE_IF
// Uncached
DeoptimizeParameters parameter(kind, reason);
return new (zone()) Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimizeIf, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"DeoptimizeIf", // name
2, 1, 1, 0, 1, 1, // counts
parameter); // parameter
}
const Operator* CommonOperatorBuilder::DeoptimizeUnless(
DeoptimizeKind kind, DeoptimizeReason reason) {
#define CACHED_DEOPTIMIZE_UNLESS(Kind, Reason) \
if (kind == DeoptimizeKind::k##Kind && \
reason == DeoptimizeReason::k##Reason) { \
return &cache_.kDeoptimizeUnless##Kind##Reason##Operator; \
}
CACHED_DEOPTIMIZE_UNLESS_LIST(CACHED_DEOPTIMIZE_UNLESS)
#undef CACHED_DEOPTIMIZE_UNLESS
// Uncached
DeoptimizeParameters parameter(kind, reason);
return new (zone()) Operator1<DeoptimizeParameters>( // --
IrOpcode::kDeoptimizeUnless, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"DeoptimizeUnless", // name
2, 1, 1, 0, 1, 1, // counts
parameter); // parameter
}
const Operator* CommonOperatorBuilder::TrapIf(int32_t trap_id) {
switch (trap_id) {
#define CACHED_TRAP_IF(Trap) \
case Builtins::kThrowWasm##Trap: \
return &cache_.kTrapIf##Trap##Operator;
CACHED_TRAP_IF_LIST(CACHED_TRAP_IF)
#undef CACHED_TRAP_IF
default:
break;
}
// Uncached
return new (zone()) Operator1<int>( // --
IrOpcode::kTrapIf, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"TrapIf", // name
1, 1, 1, 0, 0, 1, // counts
trap_id); // parameter
}
const Operator* CommonOperatorBuilder::TrapUnless(int32_t trap_id) {
switch (trap_id) {
#define CACHED_TRAP_UNLESS(Trap) \
case Builtins::kThrowWasm##Trap: \
return &cache_.kTrapUnless##Trap##Operator;
CACHED_TRAP_UNLESS_LIST(CACHED_TRAP_UNLESS)
#undef CACHED_TRAP_UNLESS
default:
break;
}
// Uncached
return new (zone()) Operator1<int>( // --
IrOpcode::kTrapUnless, // opcode
Operator::kFoldable | Operator::kNoThrow, // properties
"TrapUnless", // name
1, 1, 1, 0, 0, 1, // counts
trap_id); // parameter
}
const Operator* CommonOperatorBuilder::Switch(size_t control_output_count) {
return new (zone()) Operator( // --
IrOpcode::kSwitch, Operator::kKontrol, // opcode
"Switch", // name
1, 0, 1, 0, 0, control_output_count); // counts
}
const Operator* CommonOperatorBuilder::IfValue(int32_t index) {
return new (zone()) Operator1<int32_t>( // --
IrOpcode::kIfValue, Operator::kKontrol, // opcode
"IfValue", // name
0, 0, 1, 0, 0, 1, // counts
index); // parameter
}
const Operator* CommonOperatorBuilder::Start(int value_output_count) {
return new (zone()) Operator( // --
IrOpcode::kStart, Operator::kFoldable | Operator::kNoThrow, // opcode
"Start", // name
0, 0, 0, value_output_count, 1, 1); // counts
}
const Operator* CommonOperatorBuilder::Loop(int control_input_count) {
switch (control_input_count) {
#define CACHED_LOOP(input_count) \
case input_count: \
return &cache_.kLoop##input_count##Operator;
CACHED_LOOP_LIST(CACHED_LOOP)
#undef CACHED_LOOP
default:
break;
}
// Uncached.
return new (zone()) Operator( // --
IrOpcode::kLoop, Operator::kKontrol, // opcode
"Loop", // name
0, 0, control_input_count, 0, 0, 1); // counts
}
const Operator* CommonOperatorBuilder::Merge(int control_input_count) {
switch (control_input_count) {
#define CACHED_MERGE(input_count) \
case input_count: \
return &cache_.kMerge##input_count##Operator;
CACHED_MERGE_LIST(CACHED_MERGE)
#undef CACHED_MERGE
default:
break;
}
// Uncached.
return new (zone()) Operator( // --
IrOpcode::kMerge, Operator::kKontrol, // opcode
"Merge", // name
0, 0, control_input_count, 0, 0, 1); // counts
}
const Operator* CommonOperatorBuilder::Parameter(int index,
const char* debug_name) {
if (!debug_name) {
switch (index) {
#define CACHED_PARAMETER(index) \
case index: \
return &cache_.kParameter##index##Operator;
CACHED_PARAMETER_LIST(CACHED_PARAMETER)
#undef CACHED_PARAMETER
default:
break;
}
}
// Uncached.
return new (zone()) Operator1<ParameterInfo>( // --
IrOpcode::kParameter, Operator::kPure, // opcode
"Parameter", // name
1, 0, 0, 1, 0, 0, // counts
ParameterInfo(index, debug_name)); // parameter info
}
const Operator* CommonOperatorBuilder::OsrValue(int index) {
return new (zone()) Operator1<int>( // --
IrOpcode::kOsrValue, Operator::kNoProperties, // opcode
"OsrValue", // name
0, 0, 1, 1, 0, 0, // counts
index); // parameter
}
const Operator* CommonOperatorBuilder::Int32Constant(int32_t value) {
return new (zone()) Operator1<int32_t>( // --
IrOpcode::kInt32Constant, Operator::kPure, // opcode
"Int32Constant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::Int64Constant(int64_t value) {
return new (zone()) Operator1<int64_t>( // --
IrOpcode::kInt64Constant, Operator::kPure, // opcode
"Int64Constant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::Float32Constant(volatile float value) {
return new (zone()) Operator1<float>( // --
IrOpcode::kFloat32Constant, Operator::kPure, // opcode
"Float32Constant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::Float64Constant(volatile double value) {
return new (zone()) Operator1<double>( // --
IrOpcode::kFloat64Constant, Operator::kPure, // opcode
"Float64Constant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::ExternalConstant(
const ExternalReference& value) {
return new (zone()) Operator1<ExternalReference>( // --
IrOpcode::kExternalConstant, Operator::kPure, // opcode
"ExternalConstant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::NumberConstant(volatile double value) {
return new (zone()) Operator1<double>( // --
IrOpcode::kNumberConstant, Operator::kPure, // opcode
"NumberConstant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::PointerConstant(intptr_t value) {
return new (zone()) Operator1<intptr_t>( // --
IrOpcode::kPointerConstant, Operator::kPure, // opcode
"PointerConstant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::HeapConstant(
const Handle<HeapObject>& value) {
return new (zone()) Operator1<Handle<HeapObject>>( // --
IrOpcode::kHeapConstant, Operator::kPure, // opcode
"HeapConstant", // name
0, 0, 0, 1, 0, 0, // counts
value); // parameter
}
const Operator* CommonOperatorBuilder::RelocatableInt32Constant(
int32_t value, RelocInfo::Mode rmode) {
return new (zone()) Operator1<RelocatablePtrConstantInfo>( // --
IrOpcode::kRelocatableInt32Constant, Operator::kPure, // opcode
"RelocatableInt32Constant", // name
0, 0, 0, 1, 0, 0, // counts
RelocatablePtrConstantInfo(value, rmode)); // parameter
}
const Operator* CommonOperatorBuilder::RelocatableInt64Constant(
int64_t value, RelocInfo::Mode rmode) {
return new (zone()) Operator1<RelocatablePtrConstantInfo>( // --
IrOpcode::kRelocatableInt64Constant, Operator::kPure, // opcode
"RelocatableInt64Constant", // name
0, 0, 0, 1, 0, 0, // counts
RelocatablePtrConstantInfo(value, rmode)); // parameter
}
const Operator* CommonOperatorBuilder::ObjectId(uint32_t object_id) {
return new (zone()) Operator1<uint32_t>( // --
IrOpcode::kObjectId, Operator::kPure, // opcode
"ObjectId", // name
0, 0, 0, 1, 0, 0, // counts
object_id); // parameter
}
const Operator* CommonOperatorBuilder::Select(MachineRepresentation rep,
BranchHint hint) {
return new (zone()) Operator1<SelectParameters>( // --
IrOpcode::kSelect, Operator::kPure, // opcode
"Select", // name
3, 0, 0, 1, 0, 0, // counts
SelectParameters(rep, hint)); // parameter
}
const Operator* CommonOperatorBuilder::Phi(MachineRepresentation rep,
int value_input_count) {
DCHECK(value_input_count > 0); // Disallow empty phis.
#define CACHED_PHI(kRep, kValueInputCount) \
if (MachineRepresentation::kRep == rep && \
kValueInputCount == value_input_count) { \
return &cache_.kPhi##kRep##kValueInputCount##Operator; \
}
CACHED_PHI_LIST(CACHED_PHI)
#undef CACHED_PHI
// Uncached.
return new (zone()) Operator1<MachineRepresentation>( // --
IrOpcode::kPhi, Operator::kPure, // opcode
"Phi", // name
value_input_count, 0, 1, 1, 0, 0, // counts
rep); // parameter
}
const Operator* CommonOperatorBuilder::MapGuard(ZoneHandleSet<Map> maps) {
return new (zone()) Operator1<ZoneHandleSet<Map>>( // --
IrOpcode::kMapGuard, Operator::kEliminatable, // opcode
"MapGuard", // name
1, 1, 1, 0, 1, 0, // counts
maps); // parameter
}
const Operator* CommonOperatorBuilder::TypeGuard(Type* type) {
return new (zone()) Operator1<Type*>( // --
IrOpcode::kTypeGuard, Operator::kPure, // opcode
"TypeGuard", // name
1, 0, 1, 1, 0, 0, // counts
type); // parameter
}
const Operator* CommonOperatorBuilder::EffectPhi(int effect_input_count) {
DCHECK(effect_input_count > 0); // Disallow empty effect phis.
switch (effect_input_count) {
#define CACHED_EFFECT_PHI(input_count) \
case input_count: \
return &cache_.kEffectPhi##input_count##Operator;
CACHED_EFFECT_PHI_LIST(CACHED_EFFECT_PHI)
#undef CACHED_EFFECT_PHI
default:
break;
}
// Uncached.
return new (zone()) Operator( // --
IrOpcode::kEffectPhi, Operator::kKontrol, // opcode
"EffectPhi", // name
0, effect_input_count, 1, 0, 1, 0); // counts
}
const Operator* CommonOperatorBuilder::InductionVariablePhi(int input_count) {
DCHECK(input_count >= 4); // There must be always the entry, backedge,
// increment and at least one bound.
switch (input_count) {
#define CACHED_INDUCTION_VARIABLE_PHI(input_count) \
case input_count: \
return &cache_.kInductionVariablePhi##input_count##Operator;
CACHED_INDUCTION_VARIABLE_PHI_LIST(CACHED_INDUCTION_VARIABLE_PHI)
#undef CACHED_INDUCTION_VARIABLE_PHI
default:
break;
}
// Uncached.
return new (zone()) Operator( // --
IrOpcode::kInductionVariablePhi, Operator::kPure, // opcode
"InductionVariablePhi", // name
input_count, 0, 1, 1, 0, 0); // counts
}
const Operator* CommonOperatorBuilder::BeginRegion(
RegionObservability region_observability) {
switch (region_observability) {
case RegionObservability::kObservable:
return &cache_.kBeginRegionObservableOperator;
case RegionObservability::kNotObservable:
return &cache_.kBeginRegionNotObservableOperator;
}
UNREACHABLE();
}
const Operator* CommonOperatorBuilder::StateValues(int arguments,
SparseInputMask bitmask) {
if (bitmask.IsDense()) {
switch (arguments) {
#define CACHED_STATE_VALUES(arguments) \
case arguments: \
return &cache_.kStateValues##arguments##Operator;
CACHED_STATE_VALUES_LIST(CACHED_STATE_VALUES)
#undef CACHED_STATE_VALUES
default:
break;
}
}
#if DEBUG
DCHECK(bitmask.IsDense() || bitmask.CountReal() == arguments);
#endif
// Uncached.
return new (zone()) Operator1<SparseInputMask>( // --
IrOpcode::kStateValues, Operator::kPure, // opcode
"StateValues", // name
arguments, 0, 0, 1, 0, 0, // counts
bitmask); // parameter
}
const Operator* CommonOperatorBuilder::TypedStateValues(
const ZoneVector<MachineType>* types, SparseInputMask bitmask) {
#if DEBUG
DCHECK(bitmask.IsDense() ||
bitmask.CountReal() == static_cast<int>(types->size()));
#endif
return new (zone()) Operator1<TypedStateValueInfo>( // --
IrOpcode::kTypedStateValues, Operator::kPure, // opcode
"TypedStateValues", // name
static_cast<int>(types->size()), 0, 0, 1, 0, 0, // counts
TypedStateValueInfo(types, bitmask)); // parameters
}
const Operator* CommonOperatorBuilder::ArgumentsElementsState(
ArgumentsStateType type) {
return new (zone()) Operator1<ArgumentsStateType>( // --
IrOpcode::kArgumentsElementsState, Operator::kPure, // opcode
"ArgumentsElementsState", // name
0, 0, 0, 1, 0, 0, // counts
type); // parameter
}
const Operator* CommonOperatorBuilder::ArgumentsLengthState(
ArgumentsStateType type) {
return new (zone()) Operator1<ArgumentsStateType>( // --
IrOpcode::kArgumentsLengthState, Operator::kPure, // opcode
"ArgumentsLengthState", // name
0, 0, 0, 1, 0, 0, // counts
type); // parameter
}
ArgumentsStateType ArgumentsStateTypeOf(Operator const* op) {
DCHECK(op->opcode() == IrOpcode::kArgumentsElementsState ||
op->opcode() == IrOpcode::kArgumentsLengthState);
return OpParameter<ArgumentsStateType>(op);
}
const Operator* CommonOperatorBuilder::ObjectState(int object_id,
int pointer_slots) {
return new (zone()) Operator1<ObjectStateInfo>( // --
IrOpcode::kObjectState, Operator::kPure, // opcode
"ObjectState", // name
pointer_slots, 0, 0, 1, 0, 0, // counts
ObjectStateInfo{object_id, pointer_slots}); // parameter
}
const Operator* CommonOperatorBuilder::TypedObjectState(
int object_id, const ZoneVector<MachineType>* types) {
return new (zone()) Operator1<TypedObjectStateInfo>( // --
IrOpcode::kTypedObjectState, Operator::kPure, // opcode
"TypedObjectState", // name
static_cast<int>(types->size()), 0, 0, 1, 0, 0, // counts
TypedObjectStateInfo(object_id, types)); // parameter
}
uint32_t ObjectIdOf(Operator const* op) {
switch (op->opcode()) {
case IrOpcode::kObjectState:
return OpParameter<ObjectStateInfo>(op).object_id();
case IrOpcode::kTypedObjectState:
return OpParameter<TypedObjectStateInfo>(op).object_id();
case IrOpcode::kObjectId:
return OpParameter<uint32_t>(op);
default:
UNREACHABLE();
}
}
const Operator* CommonOperatorBuilder::FrameState(
BailoutId bailout_id, OutputFrameStateCombine state_combine,
const FrameStateFunctionInfo* function_info) {
FrameStateInfo state_info(bailout_id, state_combine, function_info);
return new (zone()) Operator1<FrameStateInfo>( // --
IrOpcode::kFrameState, Operator::kPure, // opcode
"FrameState", // name
5, 0, 0, 1, 0, 0, // counts
state_info); // parameter
}
const Operator* CommonOperatorBuilder::Call(const CallDescriptor* descriptor) {
class CallOperator final : public Operator1<const CallDescriptor*> {
public:
explicit CallOperator(const CallDescriptor* descriptor)
: Operator1<const CallDescriptor*>(
IrOpcode::kCall, descriptor->properties(), "Call",
descriptor->InputCount() + descriptor->FrameStateCount(),
Operator::ZeroIfPure(descriptor->properties()),
Operator::ZeroIfEliminatable(descriptor->properties()),
descriptor->ReturnCount(),
Operator::ZeroIfPure(descriptor->properties()),
Operator::ZeroIfNoThrow(descriptor->properties()), descriptor) {}
void PrintParameter(std::ostream& os, PrintVerbosity verbose) const {
os << "[" << *parameter() << "]";
}
};
return new (zone()) CallOperator(descriptor);
}
const Operator* CommonOperatorBuilder::CallWithCallerSavedRegisters(
const CallDescriptor* descriptor) {
class CallOperator final : public Operator1<const CallDescriptor*> {
public:
explicit CallOperator(const CallDescriptor* descriptor)
: Operator1<const CallDescriptor*>(
IrOpcode::kCallWithCallerSavedRegisters, descriptor->properties(),
"CallWithCallerSavedRegisters",
descriptor->InputCount() + descriptor->FrameStateCount(),
Operator::ZeroIfPure(descriptor->properties()),
Operator::ZeroIfEliminatable(descriptor->properties()),
descriptor->ReturnCount(),
Operator::ZeroIfPure(descriptor->properties()),
Operator::ZeroIfNoThrow(descriptor->properties()), descriptor) {}
void PrintParameter(std::ostream& os, PrintVerbosity verbose) const {
os << "[" << *parameter() << "]";
}
};
return new (zone()) CallOperator(descriptor);
}
const Operator* CommonOperatorBuilder::TailCall(
const CallDescriptor* descriptor) {
class TailCallOperator final : public Operator1<const CallDescriptor*> {
public:
explicit TailCallOperator(const CallDescriptor* descriptor)
: Operator1<const CallDescriptor*>(
IrOpcode::kTailCall,
descriptor->properties() | Operator::kNoThrow, "TailCall",
descriptor->InputCount() + descriptor->FrameStateCount(), 1, 1, 0,
0, 1, descriptor) {}
void PrintParameter(std::ostream& os, PrintVerbosity verbose) const {
os << "[" << *parameter() << "]";
}
};
return new (zone()) TailCallOperator(descriptor);
}
const Operator* CommonOperatorBuilder::Projection(size_t index) {
switch (index) {
#define CACHED_PROJECTION(index) \
case index: \
return &cache_.kProjection##index##Operator;
CACHED_PROJECTION_LIST(CACHED_PROJECTION)
#undef CACHED_PROJECTION
default:
break;
}
// Uncached.
return new (zone()) Operator1<size_t>( // --
IrOpcode::kProjection, // opcode
Operator::kPure, // flags
"Projection", // name
1, 0, 1, 1, 0, 0, // counts
index); // parameter
}
const Operator* CommonOperatorBuilder::ResizeMergeOrPhi(const Operator* op,
int size) {
if (op->opcode() == IrOpcode::kPhi) {
return Phi(PhiRepresentationOf(op), size);
} else if (op->opcode() == IrOpcode::kEffectPhi) {
return EffectPhi(size);
} else if (op->opcode() == IrOpcode::kMerge) {
return Merge(size);
} else if (op->opcode() == IrOpcode::kLoop) {
return Loop(size);
} else {
UNREACHABLE();
}
}
const FrameStateFunctionInfo*
CommonOperatorBuilder::CreateFrameStateFunctionInfo(
FrameStateType type, int parameter_count, int local_count,
Handle<SharedFunctionInfo> shared_info) {
return new (zone()->New(sizeof(FrameStateFunctionInfo)))
FrameStateFunctionInfo(type, parameter_count, local_count, shared_info);
}
} // namespace compiler
} // namespace internal
} // namespace v8
| [
"zhuanghengfei@gmail.com"
] | zhuanghengfei@gmail.com |
40f36919939596edb3699891a0c2fd9cf75fe1af | 44327fab57d0a9bc714dd8b44f0c9b66286fd2cf | /FloChater/TxtProc/CodeBlocks/stateextractor.cpp | 651924688085ebbed06594df9cf2c5be7eeff711 | [] | no_license | XieXiongShawn/FlowCharter | 44a801b86d878b775eb4446a28c682acb1ff136e | 9b66a7a75016fb14b04125e6970d707489e0f727 | refs/heads/master | 2020-07-28T06:37:35.584896 | 2020-03-14T18:27:26 | 2020-03-14T18:27:26 | 209,340,027 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,593 | cpp | #include "stateextractor.h"
#include <QDebug>
/* Construct an object */
StateExtractor::StateExtractor()
{
myProcessFinished = false;
}
/* Set txt content with given QByteArray */
void StateExtractor::SetTxtContent(QByteArray &txtCntnt)
{
myTxtCntnt = txtCntnt;
myHuntMaster.SetTxt(myTxtCntnt); // Transmit content to myHuntMaster
myProcessFinished = false;
myTxtProxer();
return;
}
/* Return the case count */
int StateExtractor::CaseCount()
{
return (Cases.size());
}
/* Return the statement count */
int StateExtractor::StatementCount()
{
return (Statements.size());
}
/* Return whether the process is finished */
bool StateExtractor::ProcessFinished()
{
return myProcessFinished;
}
/* The first step to process the txt content */
void StateExtractor::myTxtProxer()
{
myProcessFinished = false;
Cases.clear();
Statements.clear();
if (myTxtCntnt.contains("case"))
{
myCaseHunter();
}
else
{
myFCallHunter();
}
myProcessFinished = true;
return;
}
/* Search and Store all the "case" in txt content */
void StateExtractor::myCaseHunter()
{
int posTemp = 0;
do
{
States rs;
rs.SetL1Pos(myTxtCntnt.indexOf("case", posTemp));
if (posTemp > rs.L1Pos()) // Finish search after one txt process cycle
{
break;
}
posTemp = (rs.L1Pos() + 9);
char ch;
do
{
ch = myTxtCntnt.at(++posTemp); // To find out the start of "_x_x_x_x"
}
while (ch != '_');
QByteArray strTemp = "_f";
do
{
strTemp.append(myTxtCntnt.at(posTemp++)); // To get the entire state number *_f_x_x_x_x
}
while (((myTxtCntnt.at(posTemp)) != ':') && ((myTxtCntnt.at(posTemp)) != ' '));
//qDebug() << strTemp;
rs.SetL1Cntnt(strTemp);
myStateHunter(rs);
Cases.append(rs);
}
while (myTxtCntnt.indexOf("case", posTemp));
return;
}
/* Search and store all the state and its code */
void StateExtractor::myStateHunter(States &src)
{
States rs;
rs.SetL1Pos(myTxtCntnt.lastIndexOf(src.L1Cntnt(), src.L1Pos()));
rs.SetL1Cntnt(myHuntMaster.ExtractCode(rs.L1Pos()));
rs.SetStateSuffix(src.L1Cntnt());
Statements.append(rs);
return;
}
/* Search and store the code of ..f_Call */
void StateExtractor::myFCallHunter()
{
States rs;
rs.SetL1Pos(myTxtCntnt.indexOf("f_Call"));
rs.SetL1Cntnt(myHuntMaster.ExtractCode(rs.L1Pos()));
Statements.append(rs);
return;
}
| [
"noreply@github.com"
] | noreply@github.com |
3628a6b81b4b9f78091b0d744702e1d4b9bdde09 | 00b540b486c40918731142b987fa667cca1c4599 | /settings.h | 09300dfc24effb09d50488dd9f9d9bcd0e984ce7 | [] | no_license | KyleSanderson/admintool | 0d064007f6aae0fefef0b554a5eb9081d3be780a | d7b7f8a5c787b788a7a515040ebd55449d04cb64 | refs/heads/master | 2021-01-19T07:54:44.034893 | 2015-07-17T14:33:03 | 2015-07-17T14:33:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | #ifndef SETTINGS
#define SETTINGS
#include "mainwindow.h"
#include <QSettings>
#include <QMAp>
class Settings : public QSettings
{
public:
Settings(MainWindow *main);
~Settings();
void SetDefaultSettings();
void ReadSettings();
void SaveSettings();
void GetAppIDListMap();
QSettings *pSettings;
private:
QSettings *pAppIds;
MainWindow *pMain;
};
#endif // SETTINGS
| [
"drifter01620@gmail.com"
] | drifter01620@gmail.com |
16216d0018ad05b75f62384ce6df6484a4f7c797 | 0bb9ee0b177495624dafe4c15597891832147b74 | /VirtualWar/SynapseEngine/Octree.h | 0ae33ededfe41b6ced48c7641bf18ee35216a95c | [] | no_license | wangscript007/SynapseEngine | 7fcec62b50ba70c9cfc64c06719a2ae170a27a7b | 3e0499181aaadf5244b7810ef2449a09f5aad1a6 | refs/heads/main | 2023-06-11T01:46:26.603230 | 2021-07-10T08:28:58 | 2021-07-10T08:28:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | h | #pragma once
//#include "GameWorld.h"
#include "WorldChunk.h"
#include <fstream>>
#include <ostream>
class GameWorld;
class Octree
{
public:
Octree(const char* path);
Octree(GameWorld* w);
void Optimize();
void ProcessWorld();
void RenderShadows();
void RenderWorld();
void Save(const char* path);
void SetWorld(GameWorld* w) {
world = w;
worldChunk->SetWorld(w);
}
private:
GameWorld* world;
int TriLimit = 6000;
WorldChunk* worldChunk;
};
| [
"reverselogicdeveloper@gmail.com"
] | reverselogicdeveloper@gmail.com |
155bb098b2bf785ea87764c3294ad4251e1ad00f | 5b5245db71a8beb866b5d2284a642ee2fa36482b | /src/core/hw/gfxip/computePipeline.cpp | e9c9692c13d76dc0e22c7d8f65505e338919beee | [
"MIT"
] | permissive | jfactory07/pal | 4fffef4d3b34eb3a8c6491ee31c710f55dab0320 | 7ce51b199c72021b8d027c50b55da515fd9b2e0b | refs/heads/master | 2020-03-27T21:43:36.953005 | 2018-08-30T01:57:46 | 2018-08-30T02:15:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,077 | cpp | /*
***********************************************************************************************************************
*
* Copyright (c) 2014-2018 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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 "core/hw/gfxip/computePipeline.h"
#include "palMetroHash.h"
#include "palPipelineAbiProcessorImpl.h"
using namespace Util;
namespace Pal
{
// =====================================================================================================================
ComputePipeline::ComputePipeline(
Device* pDevice,
bool isInternal) // True if this is a PAL-owned pipeline (i.e., an RPM pipeline).
:
Pipeline(pDevice, isInternal),
m_threadsPerTgX(0),
m_threadsPerTgY(0),
m_threadsPerTgZ(0)
{
memset(&m_stageInfo, 0, sizeof(m_stageInfo));
m_stageInfo.stageId = Abi::HardwareStage::Cs;
}
// =====================================================================================================================
// Initialize this compute pipeline based on the provided creation info.
Result ComputePipeline::Init(
const ComputePipelineCreateInfo& createInfo)
{
Result result = Result::Success;
if ((createInfo.pPipelineBinary != nullptr) && (createInfo.pipelineBinarySize != 0))
{
m_pipelineBinaryLen = createInfo.pipelineBinarySize;
m_pPipelineBinary = PAL_MALLOC(m_pipelineBinaryLen, m_pDevice->GetPlatform(), AllocInternal);
if (m_pPipelineBinary == nullptr)
{
result = Result::ErrorOutOfMemory;
}
else
{
memcpy(m_pPipelineBinary, createInfo.pPipelineBinary, m_pipelineBinaryLen);
}
}
else
{
result = Result::ErrorInvalidPointer;
}
if (result == Result::Success)
{
PAL_ASSERT(m_pPipelineBinary != nullptr);
result = InitFromPipelineBinary();
}
return result;
}
// =====================================================================================================================
// Initializes this pipeline from the pipeline binary data stored in this object.
Result ComputePipeline::InitFromPipelineBinary()
{
PAL_ASSERT((m_pPipelineBinary != nullptr) && (m_pipelineBinaryLen != 0));
AbiProcessor abiProcessor(m_pDevice->GetPlatform());
Result result = abiProcessor.LoadFromBuffer(m_pPipelineBinary, m_pipelineBinaryLen);
if (result == Result::Success)
{
ExtractPipelineInfo(abiProcessor, ShaderType::Compute, ShaderType::Compute);
DumpPipelineElf(abiProcessor, "PipelineCs");
Abi::PipelineSymbolEntry symbol = { };
if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::CsDisassembly, &symbol))
{
m_stageInfo.disassemblyLength = static_cast<size_t>(symbol.size);
}
result = HwlInit(abiProcessor);
}
return result;
}
} // Pal
| [
"jacob.he@amd.com"
] | jacob.he@amd.com |
b072ae56825589b67e419f16a66ad86b10d37654 | 2c4b52ca014fb4b25e73c071258f24118f10cd8a | /samples/tls/main.cpp | 7261e620e1f53273da14f23fbd666593894974b5 | [
"MIT"
] | permissive | zlatko-michailov/abc | eeee56b88828e8d1f6c64f3b5a84b17564899f08 | f136285f54aac1036a976d6b2ba6f684baf8f7a6 | refs/heads/master | 2023-08-23T13:20:41.215497 | 2023-07-05T04:07:36 | 2023-07-05T04:07:36 | 155,765,578 | 4 | 1 | MIT | 2020-11-08T07:26:44 | 2018-11-01T19:30:16 | C++ | UTF-8 | C++ | false | false | 5,412 | cpp | /*
MIT License
Copyright (c) 2018-2023 Zlatko Michailov
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 <cstring>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "../../src/log.h"
#include "../../src/openssl_socket.h"
using log_ostream = abc::log_ostream<abc::debug_line_ostream<>, abc::log_filter>;
void server(const char* cert_path, const char* pkey_path, const char* password, log_ostream* log, std::condition_variable* scenario_cond) {
const char* port = "31241";
bool verify_client = false;
int queue_size = 5;
abc::openssl_tcp_server_socket<log_ostream> openssl_server(cert_path, pkey_path, password, verify_client, abc::socket::family::ipv4, log);
openssl_server.bind(port);
openssl_server.listen(queue_size);
// accept() blocks. Unblock the client thread now.
scenario_cond->notify_one();
abc::openssl_tcp_client_socket<log_ostream> openssl_connection = openssl_server.accept();
const char hello[] = ">>> Welcome to abc!\n";
uint len = sizeof(hello) - 1;
openssl_connection.send(&len, 2);
openssl_connection.send(hello, len);
char message[100 + 1];
std::memset(message, 0, sizeof(message));
len = 0;
openssl_connection.receive(&len, 2);
openssl_connection.receive(message, len);
log->put_any(abc::category::abc::samples, abc::severity::important, 0x1075e, "SERVER: %u:%s", len, message);
std::cout << "Press ENTER to shut down server socket..." << std::endl;
std::cin.get();
}
void client(log_ostream* log, std::mutex* scenario_mutex, std::condition_variable* scenario_cond) {
const char* port = "31241";
bool verify_server = false;
const char* host = "localhost";
// Block until the server starts listening.
std::unique_lock<std::mutex> lock(*scenario_mutex);
scenario_cond->wait(lock);
abc::openssl_tcp_client_socket<log_ostream> openssl_client(verify_server, abc::socket::family::ipv4, log);
openssl_client.connect(host, port);
uint len = 0;
openssl_client.receive(&len, 2);
char message[100 + 1];
std::memset(message, 0, sizeof(message));
openssl_client.receive(message, len);
log->put_any(abc::category::abc::samples, abc::severity::important, 0x1075f, "CLIENT: %u:%s", len, message);
const char hi[] = "<<< Thanks.";
len = sizeof(hi) - 1;
openssl_client.send(&len, 2);
openssl_client.send(hi, len);
std::cout << "Press ENTER to close client socket..." << std::endl;
std::cin.get();
}
int main(int /*argc*/, const char* argv[]) {
// Create a log.
abc::log_filter filter(abc::severity::abc::debug);
log_ostream log(std::cout.rdbuf(), &filter);
// Use the path to this program to build the path to the pool file.
constexpr std::size_t max_path = abc::size::k1;
char cert_path[max_path];
cert_path[0] = '\0';
char pkey_path[max_path];
pkey_path[0] = '\0';
constexpr const char cert_file[] = "cert.pem";
std::size_t cert_file_len = std::strlen(cert_file);
constexpr const char pkey_file[] = "pkey.pem";
std::size_t pkey_file_len = std::strlen(pkey_file);
const char* prog_last_separator = std::strrchr(argv[0], '/');
std::size_t prog_path_len = 0;
std::size_t prog_path_len_1 = 0;
if (prog_last_separator != nullptr) {
prog_path_len = prog_last_separator - argv[0];
prog_path_len_1 = prog_path_len + 1;
std::size_t full_path_len = prog_path_len_1 + std::max(cert_file_len, pkey_file_len);
if (full_path_len >= max_path) {
log.put_any(abc::category::abc::samples, abc::severity::critical, 0x10760,
"This sample allows paths up to %zu chars. The path to this process is %zu chars. To continue, either move the current dir closer to the process, or increase the path limit in main.cpp.",
max_path, full_path_len);
return 1;
}
std::strncpy(cert_path, argv[0], prog_path_len_1);
std::strncpy(pkey_path, argv[0], prog_path_len_1);
}
std::strcpy(cert_path + prog_path_len_1, cert_file);
log.put_any(abc::category::abc::samples, abc::severity::optional, 0x10761, "cert_path='%s'", cert_path);
std::strcpy(pkey_path + prog_path_len_1, pkey_file);
log.put_any(abc::category::abc::samples, abc::severity::optional, 0x10762, "pkey_path='%s'", pkey_path);
std::mutex scenario_mutex;
std::condition_variable scenario_cond;
std::thread server_thread(server, cert_path, pkey_path, "server", &log, &scenario_cond);
std::thread client_thread(client, &log, &scenario_mutex, &scenario_cond);
server_thread.join();
client_thread.join();
return 0;
}
| [
"zlatko@michailov.org"
] | zlatko@michailov.org |
ed9f536da56abf7265c3dbc0079b5d341b09042f | 8f371898748676912ce3d109c76a800fefc69abc | /code/InitialVector.hpp | 58b407cf90600f8f6e1ff0ccab7fd87e45ade34d | [] | no_license | cigani/NonLinearSolver | 65315c74292067cd6be973d89ff0be0021a2c139 | 757f8428dec79a8c8deda1894ee129a464a5a678 | refs/heads/master | 2021-01-13T14:48:49.324615 | 2016-12-28T18:53:36 | 2016-12-28T18:53:36 | 76,557,150 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,331 | hpp | //
// Created by Alexander Lorkowski on 12/15/16.
//
#ifndef INITIALVECTOR_HPP_
#define INITIALVECTOR_HPP_
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
class InitialVector {
private:
/// System of <doubles> expressions.
std::vector<double> mInitialVector;
/// Filename to load our matrix from.
std::string filename;
/// Method to read files called in the constructor.
void read();
/// Number of rows present in the matrix
int rows;
/// Number of columns present in the matrix
int columns;
public:
/// \brief Constructor to generate the system of equations
/// \param input - The file name containing equations.
InitialVector(std::string input);
///Constructor to generate the system of equations
InitialVector();
//! A virtual destructor for the Initial Vector class.
virtual ~InitialVector();
/// Method to return the values contained in the vector.
std::vector<double> getValues();
/// Method to print out the equations
void print();
/// \brief Method to return an individual equation from the system matrix
/// \param i The index of the value to be returned.
/// \return Returns a Expression which contains a single equation.
double getValue(int i);
};
#endif //INITIALVECTOR_HPP_
| [
"alexander.lorkowski@epfl.ch"
] | alexander.lorkowski@epfl.ch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.