blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32ef73054cc8a4cbec4c905ea770d6d0cd6ccf7f
|
da16754e5fb7d43db986d94d1642a5a9a8213c03
|
/net/third_party/quic/core/quic_packet_writer_wrapper.h
|
734e4c05d245478fd7de51996be366c94b5b69c6
|
[
"BSD-3-Clause"
] |
permissive
|
tigercosmos/labium
|
8fd6c91f2d956c8e838c4991723b41f55fafab8f
|
6be29d13da321139520e860d9aff958592d42552
|
refs/heads/master
| 2020-03-19T05:23:51.854102
| 2018-06-03T17:46:56
| 2018-06-03T18:08:41
| 135,926,710
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,929
|
h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
#define NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
#include <stddef.h>
#include <memory>
#include "base/macros.h"
#include "net/third_party/quic/core/quic_packet_writer.h"
namespace quic {
// Wraps a writer object to allow dynamically extending functionality. Use
// cases: replace writer while dispatcher and connections hold on to the
// wrapper; mix in monitoring; mix in mocks in unit tests.
class QuicPacketWriterWrapper : public QuicPacketWriter {
public:
QuicPacketWriterWrapper();
~QuicPacketWriterWrapper() override;
// Default implementation of the QuicPacketWriter interface. Passes everything
// to |writer_|.
WriteResult WritePacket(const char* buffer,
size_t buf_len,
const QuicIpAddress& self_address,
const QuicSocketAddress& peer_address,
PerPacketOptions* options) override;
bool IsWriteBlockedDataBuffered() const override;
bool IsWriteBlocked() const override;
void SetWritable() override;
QuicByteCount GetMaxPacketSize(
const QuicSocketAddress& peer_address) const override;
// Takes ownership of |writer|.
void set_writer(QuicPacketWriter* writer);
// Does not take ownership of |writer|.
void set_non_owning_writer(QuicPacketWriter* writer);
virtual void set_peer_address(const QuicSocketAddress& peer_address) {}
QuicPacketWriter* writer() { return writer_; }
private:
void unset_writer();
QuicPacketWriter* writer_ = nullptr;
bool owns_writer_ = false;
DISALLOW_COPY_AND_ASSIGN(QuicPacketWriterWrapper);
};
} // namespace quic
#endif // NET_THIRD_PARTY_QUIC_CORE_QUIC_PACKET_WRITER_WRAPPER_H_
|
[
"b04209032@ntu.edu.tw"
] |
b04209032@ntu.edu.tw
|
d66d73b422967ab59186c0338e142d371b09053d
|
34f14572584c440cf92aeffb10debf20b10eca8f
|
/app/src/main/cpp/nbbook/tools/constant/XMLNamespace.h
|
e000616f90c1656e3b6966b400e79c7b552ab447
|
[
"Apache-2.0"
] |
permissive
|
Fozei/NBReader
|
1624ce14569d23ede6d98eef54f095189cb52113
|
e423b13915578ab95c1683bfa7a70e59f19f2eab
|
refs/heads/master
| 2022-04-06T07:30:34.916915
| 2020-03-12T17:30:02
| 2020-03-12T17:30:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,740
|
h
|
/*
* Copyright (C) 2008-2015 FBReader.ORG Limited <contact@fbreader.org>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* FBReader 中支持的匹配的 namesapce
*/
#ifndef __ZLXMLNAMESPACE_H__
#define __ZLXMLNAMESPACE_H__
#include <string>
class XMLNamespace {
private:
XMLNamespace();
public:
static const std::string DublinCore;
static const std::string DublinCoreLegacy;
static const std::string DublinCoreTerms;
static const std::string XLink;
static const std::string XHTML;
static const std::string OpenPackagingFormat;
static const std::string Atom;
static const std::string OpenSearch;
static const std::string CalibreMetadata;
static const std::string Opds;
static const std::string DaisyNCX;
static const std::string Svg;
static const std::string MarlinEpub;
static const std::string XMLEncryption;
static const std::string XMLDigitalSignature;
static const std::string EpubContainer;
static const std::string FBReaderXhtml;
};
#endif /* __ZLXMLNAMESPACE_H__ */
|
[
"newbiechen@gmail.com"
] |
newbiechen@gmail.com
|
2c8a9fc6aaa48edace4bddb9c11bda61ebfa343b
|
1815b64a60fa9d0ccd3270d53cd176536558153f
|
/chrome/browser/ui/webui/settings/chromeos/os_apps_page/app_notification_handler_unittest.cc
|
366cb910f9c6119bd96f8923ef0403145650181e
|
[
"BSD-3-Clause"
] |
permissive
|
violetForeden/chromium
|
ae8c65739de96dd141136e6523b4a2c5978491d9
|
43f3ea874caca29eead4dc4dfb1c8ce6f11fa5da
|
refs/heads/main
| 2023-06-29T09:43:21.454580
| 2021-09-12T08:27:01
| 2021-09-12T08:27:01
| 405,598,541
| 1
| 0
|
BSD-3-Clause
| 2021-09-12T09:22:55
| 2021-09-12T09:22:55
| null |
UTF-8
|
C++
| false
| false
| 6,864
|
cc
|
// Copyright 2021 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 "chrome/browser/ui/webui/settings/chromeos/os_apps_page/app_notification_handler.h"
#include <memory>
#include <utility>
#include <vector>
#include "ash/public/cpp/message_center_ash.h"
#include "base/logging.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
#include "chrome/test/base/testing_profile.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace settings {
namespace {
class FakeMessageCenterAsh : public ash::MessageCenterAsh {
public:
FakeMessageCenterAsh() = default;
~FakeMessageCenterAsh() override = default;
// MessageCenterAsh override:
void SetQuietMode(bool in_quiet_mode) override {
if (in_quiet_mode != in_quiet_mode_) {
in_quiet_mode_ = in_quiet_mode;
NotifyOnQuietModeChanged(in_quiet_mode);
}
}
bool IsQuietMode() const override { return in_quiet_mode_; }
private:
bool in_quiet_mode_ = false;
};
} // namespace
class AppNotificationHandlerTest : public testing::Test {
public:
AppNotificationHandlerTest()
: task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD),
profile_(std::make_unique<TestingProfile>()) {}
~AppNotificationHandlerTest() override = default;
void SetUp() override {
ash::MessageCenterAsh::SetForTesting(&message_center_ash_);
app_service_proxy_ =
std::make_unique<apps::AppServiceProxyChromeOs>(profile_.get());
handler_ =
std::make_unique<AppNotificationHandler>(app_service_proxy_.get());
}
void TearDown() override {
handler_.reset();
app_service_proxy_.reset();
ash::MessageCenterAsh::SetForTesting(nullptr);
}
protected:
bool GetHandlerQuietModeState() { return handler_->in_quiet_mode_; }
void SetQuietModeState(bool quiet_mode_enabled) {
handler_->SetQuietMode(quiet_mode_enabled);
}
void CreateAndStoreFakeApp(
std::string fake_id,
apps::mojom::AppType app_type,
std::uint32_t permission_type,
apps::mojom::PermissionValueType permission_value_type) {
std::vector<apps::mojom::PermissionPtr> fake_permissions;
apps::mojom::PermissionPtr fake_permission = apps::mojom::Permission::New();
fake_permission->permission_id = permission_type;
fake_permission->value_type = permission_value_type;
fake_permission->value = /*True=*/1;
fake_permission->is_managed = false;
fake_permissions.push_back(fake_permission.Clone());
std::vector<apps::mojom::AppPtr> fake_apps;
apps::mojom::AppPtr fake_app = apps::mojom::App::New();
fake_app->app_type = app_type;
fake_app->app_id = fake_id;
fake_app->show_in_management = apps::mojom::OptionalBool::kTrue;
fake_app->readiness = apps::mojom::Readiness::kReady;
fake_app->permissions = std::move(fake_permissions);
fake_apps.push_back(fake_app.Clone());
UpdateAppRegistryCache(fake_apps, app_type);
}
void UpdateAppRegistryCache(std::vector<apps::mojom::AppPtr>& fake_apps,
apps::mojom::AppType app_type) {
app_service_proxy_->AppRegistryCache().OnApps(std::move(fake_apps),
app_type, false);
}
bool CheckIfFakeAppInList(std::string fake_id) {
bool app_found = false;
for (app_notification::mojom::AppPtr const& app : handler_->apps_) {
if (app->id.compare(fake_id) == 0) {
app_found = true;
break;
}
}
return app_found;
}
private:
std::unique_ptr<AppNotificationHandler> handler_;
content::BrowserTaskEnvironment task_environment_;
std::unique_ptr<TestingProfile> profile_;
std::unique_ptr<apps::AppServiceProxyChromeOs> app_service_proxy_;
FakeMessageCenterAsh message_center_ash_;
};
// Tests for update of in_quiet_mode_ variable by MessageCenterAsh observer
// OnQuietModeChange() after quiet mode state change between true and false.
TEST_F(AppNotificationHandlerTest, TestOnQuietModeChanged) {
ash::MessageCenterAsh::Get()->SetQuietMode(true);
EXPECT_TRUE(GetHandlerQuietModeState());
ash::MessageCenterAsh::Get()->SetQuietMode(false);
EXPECT_FALSE(GetHandlerQuietModeState());
}
// Tests for update of in_quiet_mode_ variable after setting state
// with MessageCenterAsh SetQuietMode() true and false.
TEST_F(AppNotificationHandlerTest, TestSetQuietMode) {
SetQuietModeState(true);
EXPECT_TRUE(GetHandlerQuietModeState());
SetQuietModeState(false);
EXPECT_FALSE(GetHandlerQuietModeState());
}
// Tests the filtering of the GetApps() function
// by creating multiple fake apps with different parameters
// and confirming that GetApps() only adds the correct ones.
// GetApps() should only add kArc and kWeb apps
// with the NOTIFICATIONS permission.
TEST_F(AppNotificationHandlerTest, TestGetAppsFiltering) {
CreateAndStoreFakeApp(
"arcAppWithNotifications", apps::mojom::AppType::kArc,
static_cast<std::uint32_t>(
app_management::mojom::ArcPermissionType::NOTIFICATIONS),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"webAppWithNotifications", apps::mojom::AppType::kWeb,
static_cast<std::uint32_t>(
app_management::mojom::PwaPermissionType::NOTIFICATIONS),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp("arcAppWithCamera", apps::mojom::AppType::kArc,
static_cast<std::uint32_t>(
app_management::mojom::ArcPermissionType::CAMERA),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"webAppWithGeolocation", apps::mojom::AppType::kWeb,
static_cast<std::uint32_t>(
app_management::mojom::PwaPermissionType::GEOLOCATION),
apps::mojom::PermissionValueType::kBool);
CreateAndStoreFakeApp(
"pluginVmAppWithPrinting", apps::mojom::AppType::kPluginVm,
static_cast<std::uint32_t>(
app_management::mojom::PluginVmPermissionType::PRINTING),
apps::mojom::PermissionValueType::kBool);
EXPECT_TRUE(CheckIfFakeAppInList("arcAppWithNotifications"));
EXPECT_TRUE(CheckIfFakeAppInList("webAppWithNotifications"));
EXPECT_FALSE(CheckIfFakeAppInList("arcAppWithCamera"));
EXPECT_FALSE(CheckIfFakeAppInList("webAppWithGeolocation"));
EXPECT_FALSE(CheckIfFakeAppInList("pluginVmAppWithPrinting"));
}
} // namespace settings
} // namespace chromeos
|
[
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] |
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
|
fe2b0e2d59c12629fabfbbab8ba88c0b8bc06a3e
|
9d48363a6125dce5a5def1ac148c4a5bd678ae3b
|
/Sourcecode/private/mx/core/elements/Step.h
|
f387ba2203fe9237c801643137fef25acb58457e
|
[
"MIT"
] |
permissive
|
rphaeh/mx
|
4cac321c5b55ce657e07e2e6ed01f0d8cd045757
|
cdf1c97c5ebffaa81de5db77cfc6d2b06b9a94fb
|
refs/heads/master
| 2021-10-26T00:36:24.084974
| 2019-04-09T00:11:04
| 2019-04-09T00:11:04
| 198,191,333
| 2
| 0
| null | 2019-07-22T09:30:20
| 2019-07-22T09:30:20
| null |
UTF-8
|
C++
| false
| false
| 1,403
|
h
|
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/ElementInterface.h"
#include "mx/core/Enums.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ELEMENT( Step )
inline StepPtr makeStep() { return std::make_shared<Step>(); }
inline StepPtr makeStep( const StepEnum& value ) { return std::make_shared<Step>( value ); }
inline StepPtr makeStep( StepEnum&& value ) { return std::make_shared<Step>( std::move( value ) ); }
class Step : public ElementInterface
{
public:
Step();
Step( const StepEnum& value );
virtual bool hasAttributes() const;
virtual bool hasContents() const;
virtual std::ostream& streamAttributes( std::ostream& os ) const;
virtual std::ostream& streamName( std::ostream& os ) const;
virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;
StepEnum getValue() const;
void setValue( const StepEnum& value );
private:
virtual bool fromXElementImpl( std::ostream& message, xml::XElement& xelement );
private:
StepEnum myValue;
};
}
}
|
[
"matthew.james.briggs@gmail.com"
] |
matthew.james.briggs@gmail.com
|
df002f949d23b9ef91fbdf27365130b99f3b75b8
|
9a67cb9bf1c2f684ebb230edf995fd808cf21b4e
|
/input_parser.h
|
f99c6bd45d63b863adb845e95f3f979b5b1a7ad1
|
[] |
no_license
|
nrmynitasr/playfair-1
|
e6a121ad83a9d96cc9bf03fe2e48e4e3ecb7344d
|
e57f8f8a3fc6646c5afba7ef419399e263c1de11
|
refs/heads/master
| 2022-03-14T05:32:27.446548
| 2019-11-27T15:35:27
| 2019-11-27T15:35:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,525
|
h
|
#ifndef INPUT_PARSER_H
#define INPUT_PARSER_H
#include <iostream>
using namespace std;
#include <vector>
#include <string>
#include <cctype>
#include "validation_result.h"
#include "pair.h"
using std::vector;
using std::string;
class InputParser{
public:
static ValidationResult validate(string operation, string message, string key)
{
if(operation != "e" && operation != "d" && operation != "E" && operation != "D")
return ValidationResult(false, "Operation not recognised");
// check if the input contains invalid characters
string validCharacters = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < message.size(); i++)
{
if(validCharacters.find(message[i]) == string::npos)
return ValidationResult(false, "The input contains invalid characters");
}
for(int i = 0; i < key.size(); i++)
{
if(validCharacters.find(key[i]) == string::npos)
return ValidationResult(false, "The input contains invalid characters");
}
return ValidationResult(true);
}
static vector<Pair<char>> parseMessage(string messageIn)
{
messageIn = stringToLower(messageIn);
messageIn = separateDuplicates(messageIn);
// add padding if needed
if(messageIn.size() % 2 != 0)
{
if(messageIn.back() != 'x')
messageIn += "x";
else
messageIn += "q";
}
messageIn = replaceJ(messageIn);
// parse for letter pairs
vector<Pair<char>> message;
for(int i = 0; i < messageIn.size() - 1; i += 2)
{
message.push_back(Pair<char>(messageIn[i], messageIn[i + 1]));
// cout << pairS.getFirst() << "-" << pairS.getSecond() << " ";
}
return message;
}
static string parseKey(string key)
{
key = stringToLower(key);
key = removeDuplicates(key);
key = replaceJ(key);
//cout << key << endl;
return key;
}
private:
static string stringToLower(string text)
{
for(int i = 0; i < text.size(); i++)
text[i] = tolower(text[i]);
return text;
}
static string removeDuplicates(string text)
{
//cout << "Remove duplicates" << endl;
int i = 0;
while(i < text.size())
{
if(text.substr(0, i).find(text[i]) != string::npos)
text.erase(i, 1);
else
i++;
}
//cout << "Removing complete" << endl;
return text;
}
static string separateDuplicates(string text)
{
// cout << "Separating string" << endl;
int i = 0;
while(i < text.size() - 1)
{
// cout << "Comparing: " << text[i] << " " << text[i+1] << endl;
if(text[i] == text[i + 1])
{
if(text[i] != 'x')
{
text.insert(i + 1, "x");
i++;
}
else
text.erase(i, 1);
}
else
i++;
}
return text;
}
static string replaceJ(string text)
{
//cout << "Replace js" << endl;
for(int i = 0; i < text.size(); i++)
if(text[i] == 'j')
text[i] = 'i';
//cout << "Replacing complete" << endl;
return text;
}
};
#endif
|
[
"kamilkuzara@gmail.com"
] |
kamilkuzara@gmail.com
|
4245a8b6c851775c69897125dd9630f2e634bab0
|
f9dc12e822ff8b505bc776daefd190b3dd2a8f4e
|
/CivilisedDiscussion/MsgStructure.cpp
|
3e6a692020678f79bc1a5a4afbd0bc8dacfb315f
|
[] |
no_license
|
Seshien/CivilizedDiscussion
|
d943d592177d27fad29528c185ef213615e3408e
|
354c31b4c9f5ae7dd8e997767a40075e02bfc9a5
|
refs/heads/master
| 2023-06-04T01:40:32.189637
| 2021-06-17T18:46:42
| 2021-06-17T18:46:42
| 368,569,775
| 0
| 1
| null | 2021-06-14T20:29:49
| 2021-05-18T14:55:54
|
C++
|
UTF-8
|
C++
| false
| false
| 26
|
cpp
|
#include "MsgStructure.h"
|
[
"maciek22999@wp.pl"
] |
maciek22999@wp.pl
|
6a7ac8bad0a5e88b86b2c25a045ef836ebc30e89
|
ca4d70080ced49e6c9d5110a8563eafdbe79eec4
|
/src/basis/structures/intervaltree.cpp
|
66aa201ba6e90a038ef69ad88011a957a063c144
|
[] |
no_license
|
It4innovations/espreso
|
f6b038dcd77f7f3677694e160a984bc45f4a4850
|
5acb7651287bd5114af736abc97c84de8a6ede99
|
refs/heads/master
| 2023-01-28T13:35:52.731234
| 2022-05-24T14:24:05
| 2022-06-26T06:35:31
| 66,345,061
| 18
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,759
|
cpp
|
#include "intervaltree.h"
#include <algorithm>
#include <numeric>
#include <cstring>
#include <cstdio>
using namespace espreso;
IntervalTree::IntervalTree(const std::vector<Point> &start, const std::vector<Point> &end)
: istart(start), iend(end)
{
if (end.size()) {
min = start.front();
max = end.front();
for (size_t i = 1; i < end.size(); ++i) {
min.x = std::min(start[i].x, min.x);
min.y = std::min(start[i].y, min.y);
min.z = std::min(start[i].z, min.z);
max.x = std::max(end[i].x, max.x);
max.y = std::max(end[i].y, max.y);
max.z = std::max(end[i].z, max.z);
}
}
build();
}
void IntervalTree::build()
{
struct comp {
comp(const std::vector<Point> &vals, int d): vals(vals), d(d) {}
bool operator()(esint i, esint j) { return vals[i][d] < vals[j][d]; }
const std::vector<Point> &vals;
int d;
};
size_t bucketsize = 8;
size = max - min;
permutation.resize(iend.size());
std::iota(permutation.begin(), permutation.end(), 0);
levels = iend.size() < bucketsize ? 0 : std::floor(std::log2(iend.size() / bucketsize));
splitters.resize(std::exp2(levels));
Point box = size; // uniform division (denoted by the level)
for (esint ll = 0, intervals = 1; ll < levels; ++ll, intervals *= 2) {
int splitter = box.x < box.y ? box.y < box.z ? 2 : 1 : box.x < box.z ? 2 : 0;
box[splitter] /= 2;
#pragma omp parallel for
for (esint i = 0; i < intervals; ++i) {
esint index = std::exp2(ll) + i;
esint begin = this->begin(index);
esint end = this->end(index);
splitters[index].d = splitter;
splitters[index].index = begin + (end - begin) / 2;
std::nth_element(permutation.begin() + begin, permutation.begin() + splitters[index].index, permutation.begin() + end, [&] (esint i, esint j) {
return iend[i][splitters[index].d] < iend[j][splitters[index].d];
});
if (end - begin) {
splitters[index].end = iend[permutation[splitters[index].index]][splitters[index].d];
}
while ( // move to the last coordinate with the same value as mid
splitters[index].index + 1 < end &&
splitters[index].end == iend[permutation[splitters[index].index + 1]][splitters[index].d]) {
++splitters[index].index;
}
for (esint c = splitters[index].index + 2; c < end; ++c) { // there can be another in the rest of array
if (splitters[index].end == iend[permutation[c]][splitters[index].d]) {
std::swap(permutation[++splitters[index].index], permutation[c--]);
}
}
splitters[index].index = std::min(splitters[index].index + 1, end);
splitters[index].start = splitters[index].end;
for (esint c = splitters[index].index; c < end; ++c) {
splitters[index].start = std::min(splitters[index].start, istart[permutation[c]][splitters[index].d]);
}
}
}
}
|
[
"ondrej.meca@gmail.com"
] |
ondrej.meca@gmail.com
|
e36f7d16ee47a21d421588ab328e778f7b599ec0
|
8fb45ccb0212a1fa116e8fcc57247d5853ee853a
|
/CrosswordCreator/crossword_type.h
|
396d583f74ebf7412f13b7e58eb698b405aeeb2e
|
[] |
no_license
|
hunterknepshield/CrosswordCreator
|
9c751e035ee75ffffcefcc5881e7b7379509fcae
|
e5478b0e72bbafc5ed0864025497aed376d10707
|
refs/heads/master
| 2021-01-19T07:05:56.302442
| 2017-04-07T07:51:16
| 2017-04-07T07:51:16
| 87,519,712
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,027
|
h
|
//
// crossword_type.h
// CrosswordCreator
//
// Created by Hunter Knepshield on 4/2/17.
// Copyright © 2017 Hunter Knepshield. All rights reserved.
//
#ifndef crossword_type_h
#define crossword_type_h
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
/// A representation of a crossword puzzle.
class Crossword {
public:
/// A specification for a word's direction.
enum WordDirection { ACROSS, DOWN };
/// A character in a word that is unknown as of right now.
static const char WILDCARD;
/// The character representing a black square in the grid.
static const char BLACK_SQUARE;
/// A type representing a starting location and direction of a word.
typedef std::tuple<int, int, WordDirection> WordBeginning;
/// A tuple denoting a starting row and column, direction, and current
/// values of a particular word in the puzzle.
typedef std::tuple<WordBeginning, std::vector<char>> Word;
/// A tuple denoting the across word and down word that this cell is a part
/// of. If either value is INVALID_{DIRECTION}, that implies an absence of
/// word in that particular direction.
typedef std::tuple<char, WordBeginning, WordBeginning> Cell;
/// An value indicating no across word in this cell.
static const WordBeginning INVALID_ACROSS;
/// An value indicating no down word in this cell.
static const WordBeginning INVALID_DOWN;
/// Wrapper around the nasty nested tuple initialization.
static Word MakeWord(int row, int column, WordDirection direction,
const std::vector<char>& characters) {
return std::make_tuple(std::make_tuple(row, column, direction),
characters);
}
/// Takes a list of words, copies them into the instance and generates a
/// grid from the words.
static std::unique_ptr<Crossword> Create(int height, int width,
const std::vector<Word>& words);
/// Takes a pre-populated grid and derives the word locations from that.
static std::unique_ptr<Crossword> Create(
const std::vector<std::string>& rawGrid);
/// Takes a partially solved instance and uses a heuristic that attempts to
/// fill in the most-constrained word first using the supplied word list.
static std::pair<bool, Crossword> Solve(
Crossword puzzle, const std::set<std::string>& wordlist,
bool randomWordlistSelection, int verbosity = 0);
/// Tells this instance to dump its entire contents, including words, the
/// next time it is sent to an output stream.
const Crossword& printEverything() const {
printEverything_ = true;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const Crossword& cw);
private:
/// An intermediate value that is the default for a not-yet-populated grid.
/// Should never appear in a valid Crossword instance.
static const Cell DEFAULT_CELL;
Crossword(int height, int width, const std::map<WordBeginning, Word>& words,
const std::vector<std::vector<Cell>>& grid)
: height_(height), width_(width), words_(words), grid_(grid) {}
/// Finds the word that is the most constrained in the given puzzle. If no
/// unconstrained words are present in the puzzle, returns false.
bool mostConstrained(Word* out);
/// Sets the specified cell in the board to be the specified character.
/// Returns false if the operation failed for some reason. Normalizes all
/// characters to uppercase.
bool setCharacter(char value, int row, int column);
/// Resets the specified cell in the board to be the wildcard character.
inline bool clearCharacter(int row, int column) {
return setCharacter(WILDCARD, row, column);
}
int height_, width_;
std::map<WordBeginning, Word> words_;
std::vector<std::vector<Cell>> grid_;
mutable bool printEverything_;
};
// Custom stream operators to make debugging prettier.
std::ostream& operator<<(std::ostream& os,
const Crossword::WordBeginning& wordBeginning);
std::ostream& operator<<(std::ostream& os, const Crossword::Word& word);
#endif /* crossword_type_h */
|
[
"theragingfatcat@gmail.com"
] |
theragingfatcat@gmail.com
|
0f68ea9a3e981e9ccb92fd6ad1621e8524565319
|
4eb6f8b2705289308005487fc5376a50b0a4b562
|
/interactiveLettersMidterm_final/src/ParticleSystemTop.hpp
|
8d8ff5e3a8513c50a2cfac34db70e7c40c060a2d
|
[] |
no_license
|
Nedelstein/edeln591_dtOF_2018
|
53d8190b2719c5179e38d0aa08614312278d3936
|
e836915653bde5798b81c7a36ea21559477d325f
|
refs/heads/master
| 2021-07-06T22:51:24.771923
| 2019-04-22T23:24:11
| 2019-04-22T23:24:11
| 146,637,683
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 789
|
hpp
|
#pragma once
#include "ofMain.h"
#include "Particle.hpp"
#include "Letters.hpp"
class ParticleSystemTop{
public:
ParticleSystemTop();
// ParticleSystemTop(glm::vec2 _pos);
void setup();
void update();
void attract(glm::vec2 toPos, float strength);
void applyDistanceDamping(glm::vec2 toPos, float minDist, float maxDist, float minDamp, float maxDamp);
void applyForce(glm::vec2 force);
void draw();
void applyElasticForce(float strength);
void applyDampingForce(float strength);
void init();
glm::vec2 pos;
glm::vec2 center = glm::vec2(ofGetWidth()/2, ofGetHeight()/2);
vector<Particle> particles;
int numParticles = 300;
Letters letter;
bool oForce;
bool collision;
};
|
[
"Noedelstein@gmail.com"
] |
Noedelstein@gmail.com
|
ed99fb55985c88872af5429c2f26c3d1b1b9608e
|
0dca3325c194509a48d0c4056909175d6c29f7bc
|
/voicenavigator/include/alibabacloud/voicenavigator/model/SilenceTimeoutRequest.h
|
ed9b1ccb340521e3798bdefacc98747d9de8c6d8
|
[
"Apache-2.0"
] |
permissive
|
dingshiyu/aliyun-openapi-cpp-sdk
|
3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62
|
4edd799a79f9b94330d5705bb0789105b6d0bb44
|
refs/heads/master
| 2023-07-31T10:11:20.446221
| 2021-09-26T10:08:42
| 2021-09-26T10:08:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,671
|
h
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_
#define ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/voicenavigator/VoiceNavigatorExport.h>
namespace AlibabaCloud
{
namespace VoiceNavigator
{
namespace Model
{
class ALIBABACLOUD_VOICENAVIGATOR_EXPORT SilenceTimeoutRequest : public RpcServiceRequest
{
public:
SilenceTimeoutRequest();
~SilenceTimeoutRequest();
std::string getConversationId()const;
void setConversationId(const std::string& conversationId);
std::string getInitialContext()const;
void setInitialContext(const std::string& initialContext);
std::string getInstanceId()const;
void setInstanceId(const std::string& instanceId);
private:
std::string conversationId_;
std::string initialContext_;
std::string instanceId_;
};
}
}
}
#endif // !ALIBABACLOUD_VOICENAVIGATOR_MODEL_SILENCETIMEOUTREQUEST_H_
|
[
"sdk-team@alibabacloud.com"
] |
sdk-team@alibabacloud.com
|
a9cf1ed117bde36c5e156d6a63f183f1a61609be
|
6079670a82f3b92a3e6c6ed180aa498b78baca9a
|
/zxq/cpp/357-count-numbers-with-unique-digits.cpp
|
b490abf423304f69d37405b70dce114e641a4856
|
[] |
no_license
|
sing-dance-rap-basketball/leetcode
|
97d59d923dfe6a48dd5adba3fa3137a684c0b3ca
|
d663d8093d4547ab1c6a24203255dba004b1e067
|
refs/heads/master
| 2022-08-07T15:17:47.059875
| 2022-07-23T15:59:36
| 2022-07-23T15:59:36
| 194,498,806
| 0
| 1
| null | 2019-07-12T08:28:39
| 2019-06-30T09:35:12
|
C++
|
UTF-8
|
C++
| false
| false
| 769
|
cpp
|
/*
* @lc app=leetcode id=357 lang=cpp
*
* [357] Count Numbers with Unique Digits
*/
// @lc code=start
/**
* Accepted
9/9 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 100 % of cpp submissions (6 MB)
*/
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 10;
}
int ans = 10;
for (int i = 1; i < n; ++i) {
ans *= (10 - i);
}
int temp = 9;
for (int i = 1; i < n-2; ++i) {
temp *= (9 - i);
}
temp *= (n - 2);
return ans + temp + countNumbersWithUniqueDigits(n-2);
}
};
// @lc code=end
|
[
"zxqaiycx@qq.com"
] |
zxqaiycx@qq.com
|
45d385d3c7d2af181ec76e1c7869ce72632aee52
|
227b4701bbc342c56a1f78afee4b233c9a692581
|
/Classes/About.cpp
|
cd305f34fc0edf4a337c3339f4ab2ac52b04728b
|
[] |
no_license
|
zyjisdog/XPlane
|
6941099bec263482ed88130efffe63560c833e29
|
f953f44446958a3793c36941bf64d8a77f12e8e7
|
refs/heads/master
| 2021-01-20T05:58:41.444633
| 2014-12-05T23:41:57
| 2014-12-05T23:41:57
| 27,600,170
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,746
|
cpp
|
#include "About.h"
#include "AppMacros.h"
#include "HelloWorldScene.h"
#include "Chinese.h"
USING_NS_CC;
Scene* About::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
About *layer = About::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool About::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"SpookyPeas.png",
"Pea.png",
CC_CALLBACK_1(About::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height*0.2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
CCDictionary* strings = CCDictionary::createWithContentsOfFile("Chinese.plist");
const CCString* zuozhe = ((CCString*)strings->objectForKey("zuozhe"));
auto label1 = LabelTTF::create(zuozhe->getCString()/*ChineseWord("zuozhe") + ":" + zhangyunjin->getCString()
ChineseWord("zhangyunjin")*/, "fonts\\Marker Felt.ttf", TITLE_FONT_SIZE);
// position the label on the center of the screen
label1->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label1->getContentSize().height));
// add the label as a child to this layer
this->addChild(label1, 1);
// add "About" splash screen" 创建一个精灵
const CCString* xuehao = ((CCString*)strings->objectForKey("xuehao"));
auto label2 = LabelTTF::create(xuehao->getCString()/*ChineseWord("xuehao") + ":2012226010020"*/, "fonts\\Marker Felt.ttf", TITLE_FONT_SIZE);
// position the sprite on the center of the screen 设置精灵的位置
label2->setPosition(Vec2(visibleSize / 2) + origin);
// add the sprite as a child to this layer 把精灵添加到layer
this->addChild(label2);
return true;
}
void About::menuCloseCallback(Ref* sender)
{
//场景切换到游戏场景
auto scene = HelloWorld::createScene();
//增加场景特效
auto tr = TransitionFade::create(0.5, scene);
//场景切换
Director::getInstance()->replaceScene(tr);
}
|
[
"vegetable2005@gmail.com"
] |
vegetable2005@gmail.com
|
dd4fef9faf7e49ab1ed7814e07c035265d9036f7
|
ea373baee35667a5f817b1f1683a8f56a58f1664
|
/8L_Beizer_Curve.cpp
|
90b57f86c406e421b151d790b2fa6709c029ad12
|
[] |
no_license
|
NamrathaHV/Computer_Graphics
|
3ce457a4c907e3c45d17bb2b565f76d4e68dc4ed
|
80f32f68f71567d5a67119a63ea9604d37f4c231
|
refs/heads/master
| 2023-07-14T14:11:42.274422
| 2021-08-26T12:29:14
| 2021-08-26T12:29:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,039
|
cpp
|
// 8L. Develop a menu driven program to animate a flag using Bezier Curve algorithm.
#include<gl/glut.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define PI 3.1416
GLsizei winwidth = 600, winheight = 600;
GLfloat xwcMin = 0.0, xwcMax = 130.0;
GLfloat ywcMin = 0.0, ywcMax = 130.0;
typedef struct wcPt3D
{
GLfloat x, y, z;
};
void bino(GLint n, GLint* C)
{
GLint k, j;
for (k = 0; k <= n; k++)
{
C[k] = 1;
for (j = n; j >= k + 1; j--)
C[k] *= j;
for (j = n - k; j >= 2; j--)
C[k] /= j;
}
}
void computeBezPt(GLfloat u, wcPt3D* bezPt, GLint nCtrlPts, wcPt3D* ctrlPts, GLint* C)
{
GLint k, n = nCtrlPts - 1;
GLfloat bezBlendFcn;
bezPt->x = bezPt->y = bezPt->z = 0.0;
for (k = 0; k < nCtrlPts; k++)
{
bezBlendFcn = C[k] * pow(u, k) * pow(1 - u, n - k);
bezPt->x += ctrlPts[k].x * bezBlendFcn;
bezPt->y += ctrlPts[k].y * bezBlendFcn;
bezPt->z += ctrlPts[k].z * bezBlendFcn;
}
}
void beizer(wcPt3D* ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)
{
wcPt3D bezCurvePt;
GLfloat u;
GLint *C, k;
C = new GLint[nCtrlPts];
bino(nCtrlPts - 1, C);
glBegin(GL_LINE_STRIP);
for (k = 0; k <= nBezCurvePts; k++)
{
u = GLfloat(k) / GLfloat(nBezCurvePts);
computeBezPt(u, &bezCurvePt, nCtrlPts, ctrlPts, C);
glVertex2f(bezCurvePt.x, bezCurvePt.y);
}
glEnd();
delete[]C;
}
void displayFcn()
{
GLint nCtrlPts = 4, nBezCurvePts = 20;
static float theta = 0;
wcPt3D ctrlPts[4] = { {20,100,0},{30,110,0},{50,90,0},{60,100,0} };
ctrlPts[1].x += 10 * sin(theta * PI / 180.0);
ctrlPts[1].y += 5 * sin(theta * PI / 180.0);
ctrlPts[2].x -= 10 * sin((theta + 30) * PI / 180.0);
ctrlPts[2].y -= 10 * sin((theta + 30) * PI / 180.0);
ctrlPts[3].x -= 4 * sin(theta * PI / 180.0);
ctrlPts[3].y += sin((theta - 30) * PI / 180.0);
theta += 0.1;
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5);
glPushMatrix();
glLineWidth(5);
for (int i = 0; i < 24; i++)
{
glTranslatef(0, -0.8, 0);
beizer(ctrlPts, nCtrlPts, nBezCurvePts);
}
glPopMatrix();
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20, 100);
glVertex2f(20, 40);
glEnd();
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void winReshapeFun(GLint newWidth, GLint newHeight)
{
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);
glClear(GL_COLOR_BUFFER_BIT);
}
void d_menu(int op)
{
if (op == 1)
glColor3f(1.0, 0.0, 0.0);
else if (op == 2)
glColor3f(0.0, 1.0, 0.0);
else if (op == 3)
glColor3f(0.0, 0.0, 1.0);
else if (op == 4)
exit(0);
glutPostRedisplay();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(winwidth, winheight);
glutCreateWindow("Bezier Curve");
glutCreateMenu(d_menu);
glutAddMenuEntry("Red", 1);
glutAddMenuEntry("Green", 2);
glutAddMenuEntry("Blue", 3);
glutAddMenuEntry("Quit", 4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshapeFun);
glutMainLoop();
}
|
[
"1rn18cs067.namratha.h.v@gmail.com"
] |
1rn18cs067.namratha.h.v@gmail.com
|
99619cba99ddfaddf7d24906595a093f8d01a556
|
fec8934c49e6527505669fe9e2c753477a530850
|
/Makefile/main.cpp
|
cdb78e741d7b42092dfc72b34a056ceed96b2821
|
[] |
no_license
|
OlenkaKornak/FindFile
|
e81434e5e2c5620bd68db159ab786279a8a0fd47
|
9158febe7c4eb16e884ee86ce8720797eaec7413
|
refs/heads/master
| 2022-11-25T19:08:01.888662
| 2020-08-05T11:08:40
| 2020-08-05T11:08:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 772
|
cpp
|
// I could not find the file on the C disk, maybe it's because there is no access to any folders,
// so I searched on the disk E
// There are my efforts to do something that works according to the task here
// Without multithreading everything works right, but I couldn`t fully implement it with multithreading
#include <iostream>
#include "function.hpp"
int main()
{
try {
path myPath = "E:";
string myFile;
cout << "Enter filename with an extension: ";
cin >> myFile;
path myfound;
find_file(myPath, myFile, myfound);
cout << myfound << endl;
auto current_thread = myThreads->begin();
while (current_thread != myThreads->end()) {
current_thread->join();
current_thread++;
}
}
catch (...)
{
cout << "Some error with file" << endl;
}
}
|
[
"olenkakornak@gmail.com"
] |
olenkakornak@gmail.com
|
b1436d8dd67d1f821cf3c27a494aea0f10e59e25
|
69b0dd68ce4a6975636909d5dae74f5229615c85
|
/FinalVersioncpp02/wywidget.cpp
|
8e938313be32964f0827de89c9098bf1e07c55a8
|
[] |
no_license
|
ZeroneJerrymo/QtCodeDemo
|
5600ace3c83b04f8438a0897b47dd83a32ab9fe6
|
0c08798273f06622454531ce8230efa0e0d690a0
|
refs/heads/master
| 2020-04-23T00:54:32.937028
| 2019-02-15T03:52:46
| 2019-02-15T03:52:46
| 170,796,207
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 15,602
|
cpp
|
#include "wyface.h"
#include "wywidget.h"
#include "ui_wywidget.h"
#include <QUdpSocket>
#include <QHostInfo>
#include <QMessageBox>
#include <QScrollBar>
#include <QDateTime>
#include <QNetworkInterface>
#include <QProcess>
#include <QFileDialog>
#include <QColorDialog>
#include <QFileDialog>
#include <QColorDialog>
#include "wytcpserver.h"
#include "wytcpclient.h"
#include <QImageReader>
#include <QImageWriter>
WyWidget::WyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::WyWidget)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
port = 45454;
udpSocket->bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
server = new WyTcpServer(this);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
sendMessage(WyNewParticipant);
connect(server, SIGNAL(sendFileName(QString)), this, SLOT(getFileName(QString)));
}
WyWidget::~WyWidget()
{
delete ui;
}
// 使用UDP广播发送信息
void WyWidget::sendMessage(WyMessageType type, QString serverAddress)
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
QString localHostName = QHostInfo::localHostName();
QString address = getIP();
out << type << getUserName() << localHostName;
switch(type)
{
case WyMessage :
// if (ui->messageTextEdit->toPlainText() == "") {
// QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
// return;
// }
out << address << getMessage();
ui->messageBrowser->verticalScrollBar()
->setValue(ui->messageBrowser->verticalScrollBar()->maximum());
break;
case WyNewParticipant :
out << address;
break;
case WyParticipantLeft :
break;
case WyFileName :
{
int row = ui->userTableWidget->currentRow();
QString clientAddress = ui->userTableWidget->item(row, 2)->text();
out << address << clientAddress << fileName;
break;
}
case WyRefuse :
out << serverAddress;
break;
case Image:
{
qDebug()<<imageName<<tr("未发送");
out << address << imageName;
qDebug()<<tr("准备发送")<<imageName;
out << QFileInfo(imageName).fileName();
//qDebug()<<tr("开始写入UDP数据报");
QImageReader imageReader(imageName);
imageReader.setFormat(QFileInfo(imageName).suffix().toLatin1());
out << imageReader.read();
ui->messageBrowser->verticalScrollBar()
->setValue(ui->messageBrowser->verticalScrollBar()->maximum());
ui->messageTextEdit->clear();
}break;
}
udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
// 接收UDP信息
void WyWidget::processPendingDatagrams()
{
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size());
QDataStream in(&datagram, QIODevice::ReadOnly);
int messageType;
in >> messageType;
QString userName,localHostName,ipAddress,message;
QString time = QDateTime::currentDateTime()
.toString("yyyy-MM-dd hh:mm:ss");
switch(messageType)
{
case WyMessage:
in >> userName >> localHostName >> ipAddress >> message;
ui->messageBrowser->setTextColor(Qt::blue);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",12));
ui->messageBrowser->append("[ " +userName+" ] "+ time);
ui->messageBrowser->append(message);
break;
case WyNewParticipant:
in >>userName >>localHostName >>ipAddress;
newParticipant(userName,localHostName,ipAddress);
break;
case WyParticipantLeft:
in >>userName >>localHostName;
participantLeft(userName,localHostName,time);
break;
case WyFileName:
{
in >> userName >> localHostName >> ipAddress;
QString clientAddress, fileName;
in >> clientAddress >> fileName;
hasPendingFile(userName, ipAddress, clientAddress, fileName);
break;
}
case WyRefuse:
{
in >> userName >> localHostName;
QString serverAddress;
in >> serverAddress;
QString ipAddress = getIP();
/*if(ipAddress == serverAddress)
{
server->refused();
}break;*/
}
case Image:
{
in >> userName >> localHostName >> ipAddress >> message;
ui->messageBrowser->setTextColor(Qt::blue);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",12));
ui->messageBrowser->append("[ " +userName+" ] "+ time);
QString tempFileName;
in >> tempFileName;
//是图像文件UDP数据包,保存图片到文件夹 temp-image/下
createTempimageDir();
tempFileName = QString(("temp-image/") + tempFileName);
QImage image;
in >> image;
QImageWriter imageWrite(tempFileName);
imageWrite.setFormat(QFileInfo(tempFileName).suffix().toLatin1());
imageWrite.write(image);
qDebug() << tr("已存放至temp-image1文件夹内");
QPixmap* pic = new QPixmap(tempFileName);
int width = 100;
int newwidth = width*(pic->size().width())/(pic->size().height());
QString imgPath = QString("<img src=\"%1\" height=\"%2\" width=\"%3\" />").arg(tempFileName)
.arg(QString::number(width,10)).arg(QString::number(newwidth,10));
//"<img src=\":"+imgFileName+"\" />";
ui->messageBrowser->append(imgPath);
//continue;
}break;
}
}
}
// 处理新用户加入
void WyWidget::newParticipant(QString userName, QString localHostName, QString ipAddress)
{
bool isEmpty = ui->userTableWidget->findItems(localHostName, Qt::MatchExactly).isEmpty();
if (isEmpty) {
QTableWidgetItem *user = new QTableWidgetItem(userName);
QTableWidgetItem *host = new QTableWidgetItem(localHostName);
QTableWidgetItem *ip = new QTableWidgetItem(ipAddress);
ui->userTableWidget->insertRow(0);
ui->userTableWidget->setItem(0,0,user);
ui->userTableWidget->setItem(0,1,host);
ui->userTableWidget->setItem(0,2,ip);
ui->messageBrowser->setTextColor(Qt::gray);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman",10));
ui->messageBrowser->append(tr("%1 在线!").arg(userName));
ui->userNumLabel->setText(tr("在线人数:%1").arg(ui->userTableWidget->rowCount()));
sendMessage(WyNewParticipant);
}
}
// 处理用户离开
void WyWidget::participantLeft(QString userName, QString localHostName, QString time)
{
int rowNum = ui->userTableWidget->findItems(localHostName, Qt::MatchExactly).first()->row();
ui->userTableWidget->removeRow(rowNum);
ui->messageBrowser->setTextColor(Qt::gray);
ui->messageBrowser->setCurrentFont(QFont("Times New Roman", 10));
ui->messageBrowser->append(tr("%1 于 %2 离开!").arg(userName).arg(time));
ui->userNumLabel->setText(tr("在线人数:%1").arg(ui->userTableWidget->rowCount()));
}
// 获取ip地址
QString WyWidget::getIP()
{
// QList<QHostAddress> list = QNetworkInterface::allAddresses();
// foreach (QHostAddress address, list) {
// if(address.protocol() == QAbstractSocket::IPv4Protocol)
// return address.toString();
// }
// return 0;
QString localHostName = QHostInfo::localHostName();
QHostInfo info = QHostInfo::fromName(localHostName);
foreach(QHostAddress address, info.addresses())
{
if(address.protocol() == QAbstractSocket::IPv4Protocol)
return address.toString();
}
return NULL;
}
// 获取用户名
QString WyWidget::getUserName()
{
QStringList envVariables;
envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
<< "HOSTNAME.*" << "DOMAINNAME.*";
QStringList environment = QProcess::systemEnvironment();
foreach (QString string, envVariables) {
int index = environment.indexOf(QRegExp(string));
if (index != -1) {
QStringList stringList = environment.at(index).split('=');
if (stringList.size() == 2) {
return stringList.at(1);
break;
}
}
}
return "unknown";
}
// 获得要发送的消息
QString WyWidget::getMessage()
{
QString msg = ui->messageTextEdit->toHtml();
ui->messageTextEdit->clear();
ui->messageTextEdit->setFocus();
return msg;
}
// 发送消息
void WyWidget::on_sendButton_clicked()
{
if (ui->messageTextEdit->toPlainText() == "") {
QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
return;
}
QString msg = ui->messageTextEdit->toHtml();
if(msg.contains("<img src=")){
if(msg.contains("<img src=\":/images")){
sendMessage(WyMessage);
}else{
sendMessage(Image);
}
}else{
sendMessage(WyMessage);
}
}
//更改字体族
void WyWidget::on_fontComboBox_currentFontChanged(const QFont &f)
{
//获取了当前选择的字体,然后在消息文本中使用该字体
ui->messageTextEdit->setCurrentFont(f);
ui->messageTextEdit->setFocus();
}
//更改字体大小
void WyWidget::on_sizeComboBox_currentIndexChanged(const QString &arg1)
{
ui->messageTextEdit->setFontPointSize(arg1.toDouble());
ui->messageTextEdit->setFocus();
}
//字体加粗
void WyWidget::on_boldToolBtn_clicked(bool checked)
{
if(checked)
ui->messageTextEdit->setFontWeight((QFont::Bold));
else
ui->messageTextEdit->setFontWeight(QFont::Normal);
ui->messageTextEdit->setFocus();
}
//字体倾斜
void WyWidget::on_italicToolBtn_clicked(bool checked)
{
ui->messageTextEdit->setFontItalic(checked);
ui->messageTextEdit->setFocus();
}
//下划线
void WyWidget::on_underlineToolBtn_clicked(bool checked)
{
ui->messageTextEdit->setFontUnderline(checked);
ui->messageTextEdit->setFocus();
}
//颜色设置
void WyWidget::on_colorToolBtn_clicked()
{
color = QColorDialog::getColor(color, this);
if (color.isValid()) {
ui->messageTextEdit->setTextColor(color);
ui->messageTextEdit->setFocus();
}
}
//保存聊天记录
void WyWidget::on_saveToolBtn_clicked()
{
if (ui->messageBrowser->document()->isEmpty()) {
QMessageBox::warning(0, tr("警告"), tr("聊天记录为空,无法保存!"), QMessageBox::Ok);
} else {
QString fileName = QFileDialog::getSaveFileName(this,
tr("保存聊天记录"), tr("聊天记录"), tr("文本(*.txt);;All File(*.*)"));
if(!fileName.isEmpty())
saveFile(fileName);
}
}
//保存聊天记录
bool WyWidget::saveFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("保存文件"),
tr("无法保存文件 %1:\n %2").arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream out(&file);
out << ui->messageBrowser->toPlainText();
return true;
}
//清空聊天记录
void WyWidget::on_clearToolBtn_clicked()
{
ui->messageBrowser->clear();
}
//关闭程序的时候,发送用户离开的广播,让其他端点的用户在用户列表中删除其用户
void WyWidget::closeEvent(QCloseEvent *e)
{
sendMessage(WyParticipantLeft);
QWidget::closeEvent(e);
}
//获取要发送的文件名
void WyWidget::getFileName(QString name)
{
fileName = name;
sendMessage(WyFileName);
}
//传输文件按钮
void WyWidget::on_sendToolBtn_clicked()
{
if(ui->userTableWidget->selectedItems().isEmpty())
{
QMessageBox::warning(0, tr("选择用户"),
tr("请先从用户列表选择要传送的用户!"), QMessageBox::Ok);
return;
}
server->show();
server->initServer();
}
//是否接收文件
void WyWidget::hasPendingFile(QString userName, QString serverAddress,
QString clientAddress, QString fileName)
{
QString ipAddress = getIP();
if(ipAddress == clientAddress)
{
int btn = QMessageBox::information(this,tr("接受文件"),
tr("来自%1(%2)的文件:%3,是否接收?")
.arg(userName).arg(serverAddress).arg(fileName),
QMessageBox::Yes,QMessageBox::No);
if (btn == QMessageBox::Yes) {
QString name = QFileDialog::getSaveFileName(0,tr("保存文件"),fileName);
if(!name.isEmpty())
{
WyTcpClient *client = new WyTcpClient(this);
client->setFileName(name);
client->setHostAddress(QHostAddress(serverAddress));
client->show();
}
} else {
sendMessage(WyRefuse, serverAddress);
}
}
}
//表情添加按钮的实现
void WyWidget::on_biaoqing_Button_clicked()
{
QString str;
WyFace *face = new WyFace();
face->show();
QString pth = "<img src=\":";
face->exec();
str = face->getPth();
qDebug()<<str;
pth += str;
//delete face;
pth += "\" />";
qDebug()<<pth;
const QString lujing = pth;
ui->messageTextEdit->append(lujing);
}
void WyWidget::on_tupian_clicked()
{
//实现图像同步的策略为,先复制图像到自己和别人机器的 temp-image/ 下,然后在数据包中加入HTML的显示本地图像代码
QString image = QFileDialog::getOpenFileName(this, tr("打开图片"),QDir::currentPath(), tr("Images (*.png *.bmp *.jpg)"));
imageName = image;
createTempimageDir();
QFile::copy(image, QString("temp-image/") + QFileInfo(image).fileName());
if (image.isEmpty())
{
return;
}
QPixmap* pic = new QPixmap(image);
int width = 100;
int newwidth = width*(pic->size().width())/(pic->size().height());
QString imgPath = QString("<img src=\"%1\" height=\"%2\" width=\"%3\" />").arg(image)
.arg(QString::number(width,10)).arg(QString::number(newwidth,10));
//"<img src=\":"+imgFileName+"\" />";
ui->messageTextEdit->append(imgPath);
//ui->messageTextEdit->append("<img src='temp-image/" + QFileInfo(image).fileName() + "' />");
}
void WyWidget::createTempimageDir()
{
QDir *temp = new QDir;
bool exist = temp->exists("temp-image");
if(exist)
return;
else
{
temp->mkdir("temp-image");
}
}
|
[
"ybc87238@163.com"
] |
ybc87238@163.com
|
121126532232ef703e2e64c8cc405ac5b4d067a3
|
ac8c5a26e336f7a9ac88cd0dbf7aae6d9d7042fe
|
/src/core/plate_locate.cpp
|
f7e668b6895059417a0751df8761f18e7ec7cc64
|
[
"Apache-2.0"
] |
permissive
|
tomturing/MyEasyPR
|
9911d6b4cb229d87126753f1ae17b95b1a8f29ab
|
091d580d2aa2b68dfe9667754c73db1e755b10be
|
refs/heads/master
| 2021-01-10T02:43:48.306822
| 2016-03-14T08:09:35
| 2016-03-14T08:09:35
| 53,832,560
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 28,831
|
cpp
|
#include "easypr/plate_locate.h"
#include "easypr/util.h"
using namespace std;
/*! \namespace easypr
Namespace where all the C++ EasyPR functionality resides
*/
namespace easypr {
const float DEFAULT_ERROR = 0.9f; // 0.6
const float DEFAULT_ASPECT = 3.75f; // 3.75
CPlateLocate::CPlateLocate() {
// cout << "CPlateLocate" << endl;
m_GaussianBlurSize = DEFAULT_GAUSSIANBLUR_SIZE;
m_MorphSizeWidth = DEFAULT_MORPH_SIZE_WIDTH;
m_MorphSizeHeight = DEFAULT_MORPH_SIZE_HEIGHT;
m_error = DEFAULT_ERROR;
m_aspect = DEFAULT_ASPECT;
m_verifyMin = DEFAULT_VERIFY_MIN;
m_verifyMax = DEFAULT_VERIFY_MAX;
m_angle = DEFAULT_ANGLE;
m_debug = DEFAULT_DEBUG;
}
//! 生活模式与工业模式切换
//!
//如果为真,则设置各项参数为定位生活场景照片(如百度图片)的参数,否则恢复默认值。
void CPlateLocate::setLifemode(bool param) {
if (param == true) {
setGaussianBlurSize(5);
setMorphSizeWidth(10);
setMorphSizeHeight(3);
setVerifyError(0.75);
setVerifyAspect(4.0);
setVerifyMin(1);
setVerifyMax(200);
} else {
setGaussianBlurSize(DEFAULT_GAUSSIANBLUR_SIZE);
setMorphSizeWidth(DEFAULT_MORPH_SIZE_WIDTH);
setMorphSizeHeight(DEFAULT_MORPH_SIZE_HEIGHT);
setVerifyError(DEFAULT_ERROR);
setVerifyAspect(DEFAULT_ASPECT);
setVerifyMin(DEFAULT_VERIFY_MIN);
setVerifyMax(DEFAULT_VERIFY_MAX);
}
}
//! 对minAreaRect获得的最小外接矩形,用纵横比进行判断
bool CPlateLocate::verifySizes(RotatedRect mr) {
float error = m_error;
// Spain car plate size: 52x11 aspect 4,7272
// China car plate size: 440mm*140mm,aspect 3.142857
// Real car plate size: 136 * 32, aspect 4
float aspect = m_aspect;
// Set a min and max area. All other patchs are discarded
// int min= 1*aspect*1; // minimum area
// int max= 2000*aspect*2000; // maximum area
int min = 34 * 8 * m_verifyMin; // minimum area
int max = 34 * 8 * m_verifyMax; // maximum area
// Get only patchs that match to a respect ratio.
float rmin = aspect - aspect * error;
float rmax = aspect + aspect * error;
float area = mr.size.height * mr.size.width;
float r = (float)mr.size.width / (float)mr.size.height;
if (r < 1) r = (float)mr.size.height / (float)mr.size.width;
// cout << "area:" << area << endl;
// cout << "r:" << r << endl;
if ((area < min || area > max) || (r < rmin || r > rmax))
return false;
else
return true;
}
// !基于HSV空间的颜色搜索方法
int CPlateLocate::colorSearch(const Mat& src, const Color r, Mat& out,
vector<RotatedRect>& outRects, int index) {
Mat match_grey;
// width值对最终结果影响很大,可以考虑进行多次colorSerch,每次不同的值
// 另一种解决方案就是在结果输出到SVM之前,进行线与角的再纠正
const int color_morph_width = 10;
const int color_morph_height = 2;
// 进行颜色查找
colorMatch(src, match_grey, r, false);
if (m_debug) {
utils::imwrite("resources/image/tmp/match_grey.jpg", match_grey);
}
Mat src_threshold;
threshold(match_grey, src_threshold, 0, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY);
Mat element = getStructuringElement(
MORPH_RECT, Size(color_morph_width, color_morph_height));
morphologyEx(src_threshold, src_threshold, MORPH_CLOSE, element);
if (m_debug) {
utils::imwrite("resources/image/tmp/color.jpg", src_threshold);
}
src_threshold.copyTo(out);
// 查找轮廓
vector<vector<Point>> contours;
// 注意,findContours会改变src_threshold
// 因此要输出src_threshold必须在这之前使用copyTo方法
findContours(src_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
// 需要进行大小尺寸判断
if (!verifySizes(mr))
itc = contours.erase(itc);
else {
++itc;
outRects.push_back(mr);
}
}
return 0;
}
//! Sobel第一次搜索
//! 不限制大小和形状,获取的BoundRect进入下一步
int CPlateLocate::sobelFrtSearch(const Mat& src,
vector<Rect_<float>>& outRects) {
Mat src_threshold;
// soble操作,得到二值图像
sobelOper(src, src_threshold, m_GaussianBlurSize, m_MorphSizeWidth,
m_MorphSizeHeight);
if (0) {
imshow("sobelFrtSearch", src_threshold);
waitKey(0);
destroyWindow("sobelFrtSearch");
}
vector<vector<Point>> contours;
findContours(src_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> first_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
// 需要进行大小尺寸判断
if (verifySizes(mr)) {
first_rects.push_back(mr);
float area = mr.size.height * mr.size.width;
float r = (float)mr.size.width / (float)mr.size.height;
if (r < 1) r = (float)mr.size.height / (float)mr.size.width;
/*cout << "area:" << area << endl;
cout << "r:" << r << endl;*/
}
++itc;
}
for (size_t i = 0; i < first_rects.size(); i++) {
RotatedRect roi_rect = first_rects[i];
Rect_<float> safeBoundRect;
if (!calcSafeRect(roi_rect, src, safeBoundRect)) continue;
outRects.push_back(safeBoundRect);
}
return 0;
}
//! Sobel第二次搜索,对断裂的部分进行再次的处理
//! 对大小和形状做限制,生成参考坐标
int CPlateLocate::sobelSecSearchPart(Mat& bound, Point2f refpoint,
vector<RotatedRect>& outRects) {
Mat bound_threshold;
////!
///第二次参数比一次精细,但针对的是得到的外接矩阵之后的图像,再sobel得到二值图像
sobelOperT(bound, bound_threshold, 3, 6, 2);
////二值化去掉两边的边界
// Mat mat_gray;
// cvtColor(bound,mat_gray,CV_BGR2GRAY);
// bound_threshold = mat_gray.clone();
////threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU +
/// CV_THRESH_BINARY);
// int w = mat_gray.cols;
// int h = mat_gray.rows;
// Mat tmp = mat_gray(Rect(w*0.15,h*0.2,w*0.6,h*0.6));
// int threadHoldV = ThresholdOtsu(tmp);
// threshold(mat_gray, bound_threshold,threadHoldV, 255, CV_THRESH_BINARY);
Mat tempBoundThread = bound_threshold.clone();
////
clearLiuDingOnly(tempBoundThread);
int posLeft = 0, posRight = 0;
if (bFindLeftRightBound(tempBoundThread, posLeft, posRight)) {
//找到两个边界后进行连接修补处理
if (posRight != 0 && posLeft != 0 && posLeft < posRight) {
int posY = int(bound_threshold.rows * 0.5);
for (int i = posLeft + (int)(bound_threshold.rows * 0.1);
i < posRight - 4; i++) {
bound_threshold.data[posY * bound_threshold.cols + i] = 255;
}
}
utils::imwrite("resources/image/tmp/repaireimg1.jpg", bound_threshold);
//两边的区域不要
for (int i = 0; i < bound_threshold.rows; i++) {
bound_threshold.data[i * bound_threshold.cols + posLeft] = 0;
bound_threshold.data[i * bound_threshold.cols + posRight] = 0;
}
utils::imwrite("resources/image/tmp/repaireimg2.jpg", bound_threshold);
}
vector<vector<Point>> contours;
findContours(bound_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> second_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
second_rects.push_back(mr);
++itc;
}
for (size_t i = 0; i < second_rects.size(); i++) {
RotatedRect roi = second_rects[i];
if (verifySizes(roi)) {
Point2f refcenter = roi.center + refpoint;
Size2f size = roi.size;
float angle = roi.angle;
RotatedRect refroi(refcenter, size, angle);
outRects.push_back(refroi);
}
}
return 0;
}
//! Sobel第二次搜索
//! 对大小和形状做限制,生成参考坐标
int CPlateLocate::sobelSecSearch(Mat& bound, Point2f refpoint,
vector<RotatedRect>& outRects) {
Mat bound_threshold;
//!
//第二次参数比一次精细,但针对的是得到的外接矩阵之后的图像,再sobel得到二值图像
sobelOper(bound, bound_threshold, 3, 10, 3);
// Mat tempBoundThread = bound_threshold.clone();
//////
// tempBoundThread = clearLiuDing(tempBoundThread);
// int posLeft = 0,posRight = 0;
// if (bFindLeftRightBound2(tempBoundThread,posLeft,posRight))
//{
// //找到两个边界后进行连接修补处理
// if (posRight !=0 && posLeft != 0 && posLeft < posRight)
// {
// int posY = bound_threshold.rows*0.5;
// for (int i=posLeft+bound_threshold.rows*0.1;i<posRight-4;i++)
// {
// bound_threshold.data[posY*bound_threshold.step[0]+i] =
// 255;
// }
// }
// imwrite("resources/image/tmp/repaireimg1.jpg",bound_threshold);
// //两边的区域不要
// for (int i=0;i<bound_threshold.rows;i++)
// {
// bound_threshold.data[i*bound_threshold.step[0]+posLeft] = 0;
// bound_threshold.data[i*bound_threshold.step[0]+posRight] = 0;
// }
// imwrite("resources/image/tmp/repaireimg2.jpg",bound_threshold);
//}
utils::imwrite("resources/image/tmp/sobelSecSearch.jpg", bound_threshold);
vector<vector<Point>> contours;
findContours(bound_threshold,
contours, // a vector of contours
CV_RETR_EXTERNAL, // 提取外部轮廓
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> second_rects;
while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc));
second_rects.push_back(mr);
++itc;
}
for (size_t i = 0; i < second_rects.size(); i++) {
RotatedRect roi = second_rects[i];
if (verifySizes(roi)) {
Point2f refcenter = roi.center + refpoint;
Size2f size = roi.size;
float angle = roi.angle;
RotatedRect refroi(refcenter, size, angle);
outRects.push_back(refroi);
}
}
return 0;
}
//! Sobel运算//对图像分割,腐蚀和膨胀的操作
//! 输入彩色图像,输出二值化图像
int CPlateLocate::sobelOper(const Mat& in, Mat& out, int blurSize, int morphW,
int morphH) {
Mat mat_blur;
mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
Mat mat_gray;
if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_RGB2GRAY);
else
mat_gray = mat_blur;
// equalizeHist(mat_gray, mat_gray);
int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
// 对X soble
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
// 对Y soble
// Sobel(mat_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
// convertScaleAbs(grad_y, abs_grad_y);
// 在两个权值组合
// 因为Y方向的权重是0,因此在此就不再计算Y方向的sobel了
Mat grad;
addWeighted(abs_grad_x, SOBEL_X_WEIGHT, 0, 0, 0, grad);
// 分割
Mat mat_threshold;
double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
// 腐蚀和膨胀
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
out = mat_threshold;
if (0) {
imshow("sobelOper", out);
waitKey(0);
destroyWindow("sobelOper");
}
return 0;
}
void DeleteNotArea(Mat& inmat) {
Mat input_grey;
cvtColor(inmat, input_grey, CV_BGR2GRAY);
int w = inmat.cols;
int h = inmat.rows;
Mat tmpMat = inmat(Rect_<double>(w * 0.15, h * 0.1, w * 0.7, h * 0.7));
//判断车牌颜色以此确认threshold方法
Color plateType = getPlateType(tmpMat, true);
Mat img_threshold;
if (BLUE == plateType) {
img_threshold = input_grey.clone();
Mat tmp = input_grey(Rect_<double>(w * 0.15, h * 0.15, w * 0.7, h * 0.7));
int threadHoldV = ThresholdOtsu(tmp);
threshold(input_grey, img_threshold, threadHoldV, 255, CV_THRESH_BINARY);
// threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY);
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
} else if (YELLOW == plateType) {
img_threshold = input_grey.clone();
Mat tmp = input_grey(Rect_<double>(w * 0.1, h * 0.1, w * 0.8, h * 0.8));
int threadHoldV = ThresholdOtsu(tmp);
threshold(input_grey, img_threshold, threadHoldV, 255,
CV_THRESH_BINARY_INV);
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
// threshold(input_grey, img_threshold, 10, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY_INV);
} else
threshold(input_grey, img_threshold, 10, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY);
int posLeft = 0;
int posRight = 0;
int top = 0;
int bottom = img_threshold.rows - 1;
clearLiuDing(img_threshold, top, bottom);
if (bFindLeftRightBound1(img_threshold, posLeft, posRight)) {
inmat = inmat(Rect(posLeft, top, w - posLeft, bottom - top));
/*int posY = inmat.rows*0.5*inmat.cols;
for (int i=posLeft;i<posRight;i++)
{
inmat.data[posY+i] = 255;
}
*/
/*roiRect.x += posLeft;
roiRect.width -=posLeft;*/
}
}
//! 抗扭斜处理
int CPlateLocate::deskew(const Mat& src, const Mat& src_b,
vector<RotatedRect>& inRects,
vector<CPlate>& outPlates) {
Mat mat_debug;
src.copyTo(mat_debug);
for (size_t i = 0; i < inRects.size(); i++) {
RotatedRect roi_rect = inRects[i];
float r = (float)roi_rect.size.width / (float)roi_rect.size.height;
float roi_angle = roi_rect.angle;
Size roi_rect_size = roi_rect.size;
if (r < 1) {
roi_angle = 90 + roi_angle;
swap(roi_rect_size.width, roi_rect_size.height);
}
if (m_debug) {
Point2f rect_points[4];
roi_rect.points(rect_points);
for (int j = 0; j < 4; j++)
line(mat_debug, rect_points[j], rect_points[(j + 1) % 4],
Scalar(0, 255, 255), 1, 8);
}
// m_angle=60
if (roi_angle - m_angle < 0 && roi_angle + m_angle > 0) {
Rect_<float> safeBoundRect;
bool isFormRect = calcSafeRect(roi_rect, src, safeBoundRect);
if (!isFormRect) continue;
Mat bound_mat = src(safeBoundRect);
Mat bound_mat_b = src_b(safeBoundRect);
Point2f roi_ref_center = roi_rect.center - safeBoundRect.tl();
Mat deskew_mat;
if ((roi_angle - 3 < 0 && roi_angle + 3 > 0) || 90.0 == roi_angle ||
-90.0 == roi_angle) {
deskew_mat = bound_mat;
} else {
// 角度在5到60度之间的,首先需要旋转 rotation
Mat rotated_mat;
Mat rotated_mat_b;
if (!rotation(bound_mat, rotated_mat, roi_rect_size, roi_ref_center,
roi_angle))
continue;
if (!rotation(bound_mat_b, rotated_mat_b, roi_rect_size, roi_ref_center,
roi_angle))
continue;
// 如果图片偏斜,还需要视角转换 affine
double roi_slope = 0;
// imshow("1roated_mat",rotated_mat);
// imshow("rotated_mat_b",rotated_mat_b);
if (isdeflection(rotated_mat_b, roi_angle, roi_slope)) {
affine(rotated_mat, deskew_mat, roi_slope);
} else
deskew_mat = rotated_mat;
}
Mat plate_mat;
plate_mat.create(HEIGHT, WIDTH, TYPE);
// haitungaga添加,删除非区域,这个函数影响了25%的完整定位率
DeleteNotArea(deskew_mat);
// 这里对deskew_mat进行了一个筛选
// 使用了经验数值:2.3和6
if (0) {
imshow("deskew_mat", deskew_mat);
waitKey(0);
destroyWindow("deskew_mat");
}
//
if (deskew_mat.cols * 1.0 / deskew_mat.rows > 2.3 &&
deskew_mat.cols * 1.0 / deskew_mat.rows < 6) {
//如果图像大于我们所要求的图像,对图像进行一个大小变更
if (deskew_mat.cols >= WIDTH || deskew_mat.rows >= HEIGHT)
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_AREA);
else
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_CUBIC);
if (0) {
imshow("plate_mat", plate_mat);
waitKey(0);
destroyWindow("plate_mat");
}
CPlate plate;
plate.setPlatePos(roi_rect);
plate.setPlateMat(plate_mat);
outPlates.push_back(plate);
}
}
}
if (0) {
imshow("mat_debug", mat_debug);
waitKey(0);
destroyWindow("mat_debug");
}
return 0;
}
//! 旋转操作
bool CPlateLocate::rotation(Mat& in, Mat& out, const Size rect_size,
const Point2f center, const double angle) {
Mat in_large;
in_large.create(int(in.rows * 1.5), int(in.cols * 1.5), in.type());
float x = in_large.cols / 2 - center.x > 0 ? in_large.cols / 2 - center.x : 0;
float y = in_large.rows / 2 - center.y > 0 ? in_large.rows / 2 - center.y : 0;
float width = x + in.cols < in_large.cols ? in.cols : in_large.cols - x;
float height = y + in.rows < in_large.rows ? in.rows : in_large.rows - y;
/*assert(width == in.cols);
assert(height == in.rows);*/
if (width != in.cols || height != in.rows) return false;
Mat imageRoi = in_large(Rect_<float>(x, y, width, height));
addWeighted(imageRoi, 0, in, 1, 0, imageRoi);
Point2f center_diff(in.cols / 2.f, in.rows / 2.f);
Point2f new_center(in_large.cols / 2.f, in_large.rows / 2.f);
Mat rot_mat = getRotationMatrix2D(new_center, angle, 1);
/*imshow("in_copy", in_large);
waitKey(0);*/
Mat mat_rotated;
warpAffine(in_large, mat_rotated, rot_mat, Size(in_large.cols, in_large.rows),
CV_INTER_CUBIC);
/*imshow("mat_rotated", mat_rotated);
waitKey(0);*/
Mat img_crop;
getRectSubPix(mat_rotated, Size(rect_size.width, rect_size.height),
new_center, img_crop);
out = img_crop;
/*imshow("img_crop", img_crop);
waitKey(0);*/
return true;
}
//! 是否偏斜
//! 输入二值化图像,输出判断结果
bool CPlateLocate::isdeflection(const Mat& in, const double angle,
double& slope) { /*imshow("in",in);
waitKey(0);*/
int nRows = in.rows;
int nCols = in.cols;
assert(in.channels() == 1);
int comp_index[3];
int len[3];
comp_index[0] = nRows / 4;
comp_index[1] = nRows / 4 * 2;
comp_index[2] = nRows / 4 * 3;
const uchar* p;
for (int i = 0; i < 3; i++) {
int index = comp_index[i];
p = in.ptr<uchar>(index);
int j = 0;
int value = 0;
while (0 == value && j < nCols) value = int(p[j++]);
len[i] = j;
}
// cout << "len[0]:" << len[0] << endl;
// cout << "len[1]:" << len[1] << endl;
// cout << "len[2]:" << len[2] << endl;
// len[0]/len[1]/len[2]这三个应该是取车牌边线的值,来计算车牌边线的斜率
double maxlen = max(len[2], len[0]);
double minlen = min(len[2], len[0]);
double difflen = abs(len[2] - len[0]);
// cout << "nCols:" << nCols << endl;
double PI = 3.14159265;
// angle是根据水平那根直线的斜率转换过来的角度
double g = tan(angle * PI / 180.0);
if (maxlen - len[1] > nCols / 32 || len[1] - minlen > nCols / 32) {
// 如果斜率为正,则底部在下,反之在上
double slope_can_1 =
double(len[2] - len[0]) / double(comp_index[1]); //求直线的斜率
double slope_can_2 = double(len[1] - len[0]) / double(comp_index[0]);
double slope_can_3 = double(len[2] - len[1]) / double(comp_index[0]);
// cout<<"angle:"<<angle<<endl;
// cout<<"g:"<<g<<endl;
// cout << "slope_can_1:" << slope_can_1 << endl;
// cout << "slope_can_2:" << slope_can_2 << endl;
// cout << "slope_can_3:" << slope_can_3 << endl;
// if(g>=0)
slope = abs(slope_can_1 - g) <= abs(slope_can_2 - g) ? slope_can_1
: slope_can_2;
// cout << "slope:" << slope << endl;
return true;
} else {
slope = 0;
}
return false;
}
//! 扭变操作//通过opencv的仿射变换
void CPlateLocate::affine(const Mat& in, Mat& out, const double slope) {
// imshow("in", in);
// waitKey(0);
//这里的slope是通过判断是否倾斜得出来的倾斜率
Point2f dstTri[3];
Point2f plTri[3];
float height = (float)in.rows; //行
float width = (float)in.cols; //列
float xiff = (float)abs(slope) * height;
if (slope > 0) {
//右偏型,新起点坐标系在xiff/2位置
plTri[0] = Point2f(0, 0);
plTri[1] = Point2f(width - xiff - 1, 0);
plTri[2] = Point2f(0 + xiff, height - 1);
dstTri[0] = Point2f(xiff / 2, 0);
dstTri[1] = Point2f(width - 1 - xiff / 2, 0);
dstTri[2] = Point2f(xiff / 2, height - 1);
} else {
//左偏型,新起点坐标系在 -xiff/2位置
plTri[0] = Point2f(0 + xiff, 0);
plTri[1] = Point2f(width - 1, 0);
plTri[2] = Point2f(0, height - 1);
dstTri[0] = Point2f(xiff / 2, 0);
dstTri[1] = Point2f(width - 1 - xiff + xiff / 2, 0);
dstTri[2] = Point2f(xiff / 2, height - 1);
}
Mat warp_mat = getAffineTransform(plTri, dstTri);
Mat affine_mat;
affine_mat.create((int)height, (int)width, TYPE);
if (in.rows > HEIGHT || in.cols > WIDTH)
warpAffine(in, affine_mat, warp_mat, affine_mat.size(),
CV_INTER_AREA); //仿射变换
else
warpAffine(in, affine_mat, warp_mat, affine_mat.size(), CV_INTER_CUBIC);
out = affine_mat;
// imshow("out", out);
// waitKey(0);
}
//! 计算一个安全的Rect
//! 如果不存在,返回false
bool CPlateLocate::calcSafeRect(const RotatedRect& roi_rect, const Mat& src,
Rect_<float>& safeBoundRect) {
Rect_<float> boudRect = roi_rect.boundingRect();
// boudRect的左上的x和y有可能小于0
float tl_x = boudRect.x > 0 ? boudRect.x : 0;
float tl_y = boudRect.y > 0 ? boudRect.y : 0;
// boudRect的右下的x和y有可能大于src的范围
float br_x = boudRect.x + boudRect.width < src.cols
? boudRect.x + boudRect.width - 1
: src.cols - 1;
float br_y = boudRect.y + boudRect.height < src.rows
? boudRect.y + boudRect.height - 1
: src.rows - 1;
float roi_width = br_x - tl_x;
float roi_height = br_y - tl_y;
if (roi_width <= 0 || roi_height <= 0) return false;
// 新建一个mat,确保地址不越界,以防mat定位roi时抛异常
safeBoundRect = Rect_<float>(tl_x, tl_y, roi_width, roi_height);
return true;
}
// !基于颜色信息的车牌定位
int CPlateLocate::plateColorLocate(Mat src, vector<CPlate>& candPlates,
int index) {
vector<RotatedRect> rects_color_blue;
vector<RotatedRect> rects_color_yellow;
vector<CPlate> plates;
Mat src_b;
// 查找蓝色车牌
// 查找颜色匹配车牌
colorSearch(src, BLUE, src_b, rects_color_blue, index);
// 进行抗扭斜处理
deskew(src, src_b, rects_color_blue, plates);
// 查找黄色车牌
colorSearch(src, YELLOW, src_b, rects_color_yellow, index);
deskew(src, src_b, rects_color_yellow, plates);
for (size_t i = 0; i < plates.size(); i++) {
candPlates.push_back(plates[i]);
}
return 0;
}
//! Sobel运算
//! 输入彩色图像,输出二值化图像
int CPlateLocate::sobelOperT(const Mat& in, Mat& out, int blurSize, int morphW,
int morphH) {
Mat mat_blur;
mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
Mat mat_gray;
if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_BGR2GRAY);
else
mat_gray = mat_blur;
utils::imwrite("resources/image/tmp/grayblure.jpg", mat_gray);
// equalizeHist(mat_gray, mat_gray);
int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
//因为Y方向的权重是0,因此在此就不再计算Y方向的sobel了
Mat grad;
addWeighted(abs_grad_x, 1, 0, 0, 0, grad);
utils::imwrite("resources/image/tmp/graygrad.jpg", grad);
Mat mat_threshold;
double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
utils::imwrite("resources/image/tmp/grayBINARY.jpg", mat_threshold);
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
utils::imwrite("resources/image/tmp/phologyEx.jpg", mat_threshold);
out = mat_threshold;
return 0;
}
// !基于垂直线条的车牌定位
int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate>& candPlates,
int index) {
vector<RotatedRect> rects_sobel;
vector<RotatedRect> rects_sobel_sel;
vector<CPlate> plates;
vector<Rect_<float>> bound_rects;
// Sobel第一次粗略搜索
sobelFrtSearch(src, bound_rects);
vector<Rect_<float>> bound_rects_part;
//对不符合要求的区域进行扩展
for (size_t i = 0; i < bound_rects.size(); i++) {
float fRatio = bound_rects[i].width * 1.0f / bound_rects[i].height;
if (fRatio < 3.0 && fRatio > 1.0 && bound_rects[i].height < 120) {
Rect_<float> itemRect = bound_rects[i];
//宽度过小,进行扩展
itemRect.x = itemRect.x - itemRect.height * (4 - fRatio);
if (itemRect.x < 0) {
itemRect.x = 0;
}
itemRect.width = itemRect.width + itemRect.height * 2 * (4 - fRatio);
if (itemRect.width + itemRect.x >= src.cols) {
itemRect.width = src.cols - itemRect.x;
}
itemRect.y = itemRect.y - itemRect.height * 0.08f;
itemRect.height = itemRect.height * 1.16f;
bound_rects_part.push_back(itemRect);
}
}
//对断裂的部分进行二次处理
for (size_t i = 0; i < bound_rects_part.size(); i++) {
Rect_<float> bound_rect = bound_rects_part[i];
Point2f refpoint(bound_rect.x, bound_rect.y);
float x = bound_rect.x > 0 ? bound_rect.x : 0;
float y = bound_rect.y > 0 ? bound_rect.y : 0;
float width =
x + bound_rect.width < src.cols ? bound_rect.width : src.cols - x;
float height =
y + bound_rect.height < src.rows ? bound_rect.height : src.rows - y;
Rect_<float> safe_bound_rect(x, y, width, height);
Mat bound_mat = src(safe_bound_rect);
// Sobel第二次精细搜索(部分)
sobelSecSearchPart(bound_mat, refpoint, rects_sobel);
}
for (size_t i = 0; i < bound_rects.size(); i++) {
Rect_<float> bound_rect = bound_rects[i];
Point2f refpoint(bound_rect.x, bound_rect.y);
float x = bound_rect.x > 0 ? bound_rect.x : 0;
float y = bound_rect.y > 0 ? bound_rect.y : 0;
float width =
x + bound_rect.width < src.cols ? bound_rect.width : src.cols - x;
float height =
y + bound_rect.height < src.rows ? bound_rect.height : src.rows - y;
Rect_<float> safe_bound_rect(x, y, width, height);
Mat bound_mat = src(safe_bound_rect);
// Sobel第二次精细搜索
sobelSecSearch(bound_mat, refpoint, rects_sobel);
// sobelSecSearchPart(bound_mat, refpoint, rects_sobel);
}
Mat src_b;
sobelOper(src, src_b, 3, 10, 3);
// 进行抗扭斜处理
deskew(src, src_b, rects_sobel, plates);
for (size_t i = 0; i < plates.size(); i++) candPlates.push_back(plates[i]);
return 0;
}
// !车牌定位
// !把颜色与Sobel定位的车牌全部输出
int CPlateLocate::plateLocate(Mat src, vector<Mat>& resultVec, int index) {
vector<CPlate> all_result_Plates;
plateColorLocate(src, all_result_Plates, index);
plateSobelLocate(src, all_result_Plates, index);
for (size_t i = 0; i < all_result_Plates.size(); i++) {
CPlate plate = all_result_Plates[i];
resultVec.push_back(plate.getPlateMat());
}
return 0;
}
} /*! \namespace easypr*/
|
[
"2568101222@qq.com"
] |
2568101222@qq.com
|
3fd30d86cbc935588895376f7135579011a28568
|
99d0d18688b17e802f952b64f85e8ce836fdc94f
|
/Practice Comp code/yetAnotherMinMaxProblem.cpp
|
67a8c42d25e2e934e8b530d4e42e98c7ed0a8bbe
|
[] |
no_license
|
suyash0103/Competitive-Coding
|
b8be47d6c5a5c8e63ba4dc30a0cf39f6165a0531
|
af24966916aa5dc4d39b5dbdf51bad3bd102895d
|
refs/heads/master
| 2018-09-21T20:24:14.188721
| 2018-07-22T19:06:31
| 2018-07-22T19:06:31
| 100,601,783
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 327
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int a[10000];
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
int max = a[0] ^ a[1];
for(int i = 0; i < n - 1; i++)
//if(a[i] ^ a[i + 1] > max)
// max = a[i] ^ a[i + 1];
cout << (a[i]) ^ (a[i + 1]);
//cout << max;
}
|
[
"Suyash Ghuge"
] |
Suyash Ghuge
|
337d156f1b7dbbd47e2019e54752d52ef28218a0
|
2fec3c84e6b2fa675857e00cc6dc0aaacc8dc969
|
/ObjectARX 2016/samples/database/ARXDBG/Inc/ArxDbgSelSet.h
|
b1ab43e2afacc34786c00f43ce1ef296243fa536
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
presscad/AutoCADPlugin-HeatSource
|
7feb3c26b31814e0899bd10ff39a2e7c72bc764d
|
ab0865402b41fe45d3b509c01c6f114d128522a8
|
refs/heads/master
| 2020-08-27T04:22:23.237379
| 2016-06-24T07:30:15
| 2016-06-24T07:30:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,536
|
h
|
//
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
//
#ifndef ARXDBGSELSET_H
#define ARXDBGSELSET_H
/****************************************************************************
**
** CLASS ArxDbgSelSet:
** Thin wrapper around an AutoCAD selection set.
** The constructor creates a "NULL" set. If you want to
** actually create an AutoCAD selection set, you must use one
** of the selection mechanisms, or explicitly call createEmptySet().
**
** **jma
**
****************************/
class ArxDbgSelSet {
public:
enum SelSetStatus {
kSelected,
kNone,
kCanceled,
kRejected,
};
ArxDbgSelSet();
virtual ~ArxDbgSelSet();
// selection mechanisms
SelSetStatus createEmptySet();
SelSetStatus userSelect(const resbuf* filter = NULL);
SelSetStatus userSelect(LPCTSTR selectPrompt, LPCTSTR removePrompt, const resbuf* filter = NULL);
SelSetStatus impliedSelect(const resbuf* filter = NULL);
SelSetStatus crossingSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
SelSetStatus crossingPolygonSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus fenceSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus lastSelect(const resbuf* filter = NULL);
SelSetStatus pointSelect(const AcGePoint3d& pt1, const resbuf* filter = NULL);
SelSetStatus previousSelect(const resbuf* filter = NULL);
SelSetStatus windowSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
SelSetStatus windowPolygonSelect(const AcGePoint3dArray& ptArray, const resbuf* filter = NULL);
SelSetStatus filterOnlySelect(const resbuf* filter = NULL);
SelSetStatus allSelect(const resbuf* filter = NULL);
SelSetStatus boxSelect(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const resbuf* filter = NULL);
// inquiry
SelSetStatus lastStatus() const;
// options
void setFilterLockedLayers(bool filterThem);
void setAllowDuplicates(bool dups);
void setAllAtPickBox(bool pickBox);
void setAllowSingleOnly(bool single, bool allowLast);
void setRejectNonCurrentSpace(bool rejectIt);
void setRejectPaperSpaceViewport(bool rejectId);
void setKeywordCallback(LPCTSTR extraKwords, struct resbuf* (*pFunc) (const TCHAR*));
void setOtherCallback(struct resbuf* (*pFunc) (const TCHAR*));
// operations on the selection set (backward compatibility with ADS)
long length();
void add(ads_name ent);
void add(const AcDbObjectId& objId);
void remove(ads_name ent);
void remove(const AcDbObjectId& objId);
bool member(ads_name ent);
bool member(const AcDbObjectId& objId);
bool subEntMarkerAt(long index, AcDbObjectId& objId, int& gsMarker);
// conversion to AcDbObjectIdArray, ads_name
void asArray(AcDbObjectIdArray& objIds);
void asAdsName(ads_name ss);
private:
// data members
ads_name m_ss;
SelSetStatus m_lastStatus;
bool m_allowDuplicates;
bool m_allAtPickBox;
bool m_singleOnly;
bool m_allowLast;
bool m_filterLockedLayers;
bool m_rejectNonCurrentSpace;
bool m_rejectPaperSpaceViewport;
CString m_flags;
CString m_extraKwords;
struct resbuf* (*m_kwordFuncPtr)(const TCHAR*);
struct resbuf* (*m_otherFuncPtr)(const TCHAR*);
// helper functions
bool isInitialized() const; // has the set been allocated by AutoCAD?
void clear(); // free up ss and reinitialize
SelSetStatus handleResult(int result); // common ads_ssget() return action
void setFlags(bool hasPrompts);
// outlawed functions (move these up when implemented)
ArxDbgSelSet(const ArxDbgSelSet&);
ArxDbgSelSet& operator=(const ArxDbgSelSet&);
};
#endif // ARXDBGSELSET_H
|
[
"liheng301@126.com"
] |
liheng301@126.com
|
a6cd60569613115d6bd2d50799dc8bb027e93ab1
|
3fabd73eb8974c540fe310668b7fddfbdf70d740
|
/src/qt/bitcoin.cpp
|
7a15e94c3c7de75d56a2454ad7f7a02a83ad6095
|
[
"MIT"
] |
permissive
|
litecoinscrypt/litecoinscrypt
|
55ad4ea0e83e364ad30d87e76121993d263c86fb
|
ee73b432b6e2aa93de602df016ed1f37d472e472
|
refs/heads/master
| 2020-05-03T01:36:18.815315
| 2014-04-02T04:11:06
| 2014-04-02T04:11:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,022
|
cpp
|
/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/algorithm/string/predicate.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. LiteCoinScrypt can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "litecoinscrypt:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
// if URI could be sent to the message queue exit here
exit(0);
else
// if URI could not be sent to the message queue do a normal Bitcoin-Qt startup
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("LiteCoinScrypt");
app.setOrganizationDomain("we-have-no-domain-yet.nex");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("litecoinscrypt-qt-testnet");
else
app.setApplicationName("litecoinscrypt-qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "litecoinscrypt:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
|
[
"root@ltcs.(none)"
] |
root@ltcs.(none)
|
4069c4a5cfff6e0b57e28fcdb03a10813fc822b6
|
73a457af0da833c743601866d046ab2d5956f603
|
/src/fm/scene/graphics/OverlayRenderer.cpp
|
5d6462d34aa617f5ce57f1c2c2c834f1a09f0555
|
[] |
no_license
|
Zylann/SnowfeetFramework
|
41b30ac5fb9ce6847210ee7ed7f1da35f35d2cce
|
4dc36d0cec0144088dfd457b26dc4f6db3d761b6
|
refs/heads/master
| 2020-09-22T11:41:55.080212
| 2014-11-03T12:37:10
| 2014-11-03T12:37:10
| 13,676,066
| 6
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,236
|
cpp
|
#include <fm/scene/graphics/OverlayRenderer.hpp>
#include <fm/asset/AssetBank.hpp>
#include <fm/scene/core/Scene.hpp>
namespace zn
{
ZN_OBJECT_IMPL(zn::OverlayRenderer)
//------------------------------------------------------------------------------
OverlayRenderer::OverlayRenderer() : Renderer(),
r_texture(nullptr),
m_color(255,255,255)
{
}
//------------------------------------------------------------------------------
void OverlayRenderer::setTexture(const sf::Texture* texture)
{
r_texture = texture;
}
//------------------------------------------------------------------------------
void OverlayRenderer::setColor(sf::Color color)
{
m_color = color;
}
//------------------------------------------------------------------------------
sf::FloatRect OverlayRenderer::localBounds() const
{
return sf::FloatRect(-99999, -99999, 199999, 199999);
}
//------------------------------------------------------------------------------
void OverlayRenderer::serializeData(JsonBox::Value& o)
{
Renderer::serializeData(o);
zn::serialize(o["color"], m_color);
if(r_texture != nullptr)
{
std::string textureName = AssetBank::current()->textures.findName(r_texture);
o["texture"] = textureName;
}
else
{
o["texture"].setNull();
}
}
//------------------------------------------------------------------------------
void OverlayRenderer::unserializeData(JsonBox::Value& o)
{
Renderer::unserialize(o);
zn::unserialize(o["color"], m_color);
std::string textureName = o["texture"].getString();
if(textureName.empty())
{
log.err() << "OverlayRenderer::unserialize: texture name is empty" << log.endl();
}
else
{
const sf::Texture * texture = AssetBank::current()->textures.get(textureName);
if(texture != nullptr)
{
setTexture(texture);
}
else
{
log.err() << "OverlayRenderer::unserializeData: "
"texture not found \"" << textureName << '"' << log.endl();
}
}
}
//------------------------------------------------------------------------------
void OverlayRenderer::postUnserialize()
{
}
//------------------------------------------------------------------------------
void OverlayRenderer::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform = sf::Transform::Identity;
states.texture = r_texture;
//states.transform.combine(entity().transform.matrix());
const sf::View & view = entity().scene().renderSystem.activeCamera()->internalView();
sf::FloatRect viewBounds(view.getCenter()-view.getSize()*0.5f, view.getSize());
sf::Vector2u ts = r_texture->getSize();
sf::VertexArray mesh;
mesh.setPrimitiveType(sf::PrimitiveType::Quads);
mesh.resize(4);
mesh[0] = sf::Vertex(sf::Vector2f(viewBounds.left, viewBounds.top), m_color, sf::Vector2f(0, 0));
mesh[1] = sf::Vertex(sf::Vector2f(viewBounds.left+viewBounds.width, viewBounds.top), m_color, sf::Vector2f(ts.x, 0));
mesh[2] = sf::Vertex(sf::Vector2f(viewBounds.left+viewBounds.width, viewBounds.top+viewBounds.height), m_color, sf::Vector2f(ts.x, ts.y));
mesh[3] = sf::Vertex(sf::Vector2f(viewBounds.left, viewBounds.top+viewBounds.height), m_color, sf::Vector2f(0, ts.y));
target.draw(mesh, states);
//target.draw(sf::RectangleShape(sf::Vector2f(10,10)), states);
}
} // namespace zn
|
[
"marc.gilleron@gmail.com"
] |
marc.gilleron@gmail.com
|
40845feb01ce46fd7cd9e2ad14086734a3dcf02d
|
2ca688cb5d4b9befa21d3e1282c33b5445cc0618
|
/LabTradingGame/cTileMap.h
|
ac8264f9d3e60cf700814b575504136dfab05737
|
[] |
no_license
|
Tendoi/Trading_Game_Coursework
|
67f5b3427cf2808ec286ef06da58e4748177cd57
|
fde238aa96d9d295e84d4eb530850920facd3818
|
refs/heads/master
| 2020-06-11T00:58:57.683994
| 2016-12-07T11:35:15
| 2016-12-07T11:35:15
| 75,827,830
| 0
| 0
| null | 2016-12-07T11:38:02
| 2016-12-07T11:04:22
|
C++
|
UTF-8
|
C++
| false
| false
| 1,086
|
h
|
/*
=================
cTileMap.h
- Header file for class definition - SPECIFICATION
- Header file for the tileMap class which is a child of cSprite class
=================
*/
#ifndef _CTILEMAP_H
#define _CTILEMAP_H
#include "MazeMakerEditor.h"
#include <sstream>
class cTileMap: public cSprite
{
protected:
int tileMap[12][16];
private:
SDL_Point mapStartXY;
SDL_Point tileClickedRC;
cSprite aTile;
void initialiseMap(); // Set the initial values for the map
public:
cTileMap();
cTileMap(cFileHandler* aFile);
void initialiseMapFromFile(cFileHandler* aFile); // Set the initial values for the map from file input
void render(SDL_Window* theSDLWND, SDL_Renderer* theRenderer, cTextureMgr* theTxtMgr, vector<LPCSTR> theTxt); // Default render function
void renderGridLines(SDL_Renderer* theRenderer, SDL_Rect theRect, SDL_Color theColour); // Draw grid lines
void update(SDL_Point theMapAreaClicked, int theTileToPlace);
void setMapStartXY(SDL_Point startPosXY);
SDL_Point getMapStartXY();
string getMapData();
void writeMapDataToFile(cFileHandler* aFile);
};
#endif
|
[
"Tendoi.Tony@gmail.com"
] |
Tendoi.Tony@gmail.com
|
e81ecd91325768afb391fa2f27565e1893d94b10
|
bb34fff90c9e688155c3d530966b06f5a52f04c9
|
/qcril-data-hal/datamodule/module/src/DataModule.cpp
|
14b6518952b80fea101e86c2afb74a8c1d6d19c2
|
[] |
no_license
|
pkm774/vendor_qcom_proprietary
|
27f90ae736c031497a9a26d7ebb4cf0dde62063b
|
00578532a2e2e308ebcf26cf3b7c0c89b4f4cf02
|
refs/heads/master
| 2022-04-15T13:11:12.061157
| 2020-04-09T04:03:54
| 2020-04-09T04:03:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 127,900
|
cpp
|
/**
* Copyright (c) 2017-2020 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
**/
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <cutils/properties.h>
#include "dlfcn.h"
#include "qmi_client.h"
#include "wireless_data_service_v01.h"
/* Framework includes */
#include "framework/Dispatcher.h"
#include "framework/Looper.h"
#include "framework/ModuleLooper.h"
#include "framework/QcrilInitMessage.h"
#include "framework/TimeKeeper.h"
#include "modules/android/ril_message_factory.h"
#include "modules/qmi/QmiIndMessage.h"
#include "modules/qmi/EndpointStatusIndMessage.h"
#include "modules/qmi/ModemEndPointFactory.h"
#include "modules/qmi/QmiSetupRequestCallback.h"
#include "qtibus/Messenger.h"
#include "data_system_determination_v01.h"
/* Module includes */
#include "local/DataModule.h"
#include "UnSolMessages/DataInitMessage.h"
#include "request/RilRequestSetupDataCallMessage.h"
#include "request/RilRequestDataCallListMessage.h"
#include "request/RilRequestGetDataCallProfileMessage.h"
#include "request/RilRequestDeactivateDataCallMessage.h"
#include "request/RilRequestEmbmsActivateDeactivateTmgiMessage.h"
#include "request/RilRequestEmbmsActivateTmgiMessage.h"
#include "request/RilRequestEmbmsContentDescUpdateMessage.h"
#include "request/RilRequestEmbmsDeactivateTmgiMessage.h"
#include "request/EmbmsEnableDataReqMessage.h"
#include "request/RilRequestEmbmsGetActiveTmgiMessage.h"
#include "request/RilRequestEmbmsGetAvailTmgiMessage.h"
#include "request/RilRequestEmbmsSendIntTmgiListMessage.h"
#include "request/RilRequestGoDormantMessage.h"
#include "request/RilRequestLastDataCallFailCauseMessage.h"
#include "request/ProcessScreenStateChangeMessage.h"
#include "request/ProcessStackSwitchMessage.h"
#include "request/RilRequestPullLceDataMessage.h"
#include "request/SetApnInfoMessage.h"
#include "request/RilRequestSetDataProfileMessage.h"
#include "request/SetIsDataEnabledMessage.h"
#include "request/SetIsDataRoamingEnabledMessage.h"
#include "request/SetLteAttachProfileMessage.h"
#include "request/SetQualityMeasurementMessage.h"
#include "request/RilRequestStartLceMessage.h"
#include "request/RilRequestStopLceMessage.h"
#include "request/ToggleDormancyIndMessage.h"
#include "request/ToggleLimitedSysIndMessage.h"
#include "request/UpdateMtuMessage.h"
#include "request/GetDdsSubIdMessage.h"
#include "request/RequestDdsSwitchMessage.h"
#include "request/RilRequestStartKeepaliveMessage.h"
#include "request/RilRequestStopKeepaliveMessage.h"
#include "request/RilRequestSetCarrierInfoImsiEncryptionMessage.h"
#include "request/SetLinkCapRptCriteriaMessage.h"
#include "request/SetLinkCapFilterMessage.h"
#include "request/SetInitialAttachApnRequestMessage.h"
#include "request/RegisterBearerAllocationUpdateRequestMessage.h"
#include "request/GetBearerAllocationRequestMessage.h"
#include "request/GetAllBearerAllocationsRequestMessage.h"
#include "request/IWLANCapabilityHandshake.h"
#include "request/GetAllQualifiedNetworkRequestMessage.h"
#include "UnSolMessages/IntentToChangeApnPreferredSystemMessage.h"
#include "request/SetupDataCallRequestMessage.h"
#include "request/DeactivateDataCallRequestMessage.h"
#include "request/GetRadioDataCallListRequestMessage.h"
#include "request/GetIWlanDataCallListRequestMessage.h"
#include "request/GetIWlanDataRegistrationStateRequestMessage.h"
#include "request/StartKeepAliveRequestMessage.h"
#include "request/StopKeepAliveRequestMessage.h"
#include "request/SetCarrierInfoImsiEncryptionMessage.h"
#include "event/RilEventDataCallback.h"
#include "request/SetDataProfileRequestMessage.h"
#include "request/SetPreferredDataModemRequestMessage.h"
#include "event/DataGetMccMncCallback.h"
#include "sync/RilDataEmbmsActiveMessage.h"
#include "UnSolMessages/SetRadioClientCapUnSolMessage.h"
#include "UnSolMessages/SetLteAttachPdnListActionResultMessage.h"
#include "UnSolMessages/SetApnPreferredSystemResultMessage.h"
#include "UnSolMessages/DataAllBearerTypeChangedMessage.h"
#include "UnSolMessages/DataBearerTypeChangedMessage.h"
#include "UnSolMessages/DsdSystemStatusPerApnMessage.h"
#include "UnSolMessages/CallStatusMessage.h"
#include "UnSolMessages/CurrentDDSIndMessage.h"
#include "UnSolMessages/DDSSwitchResultIndMessage.h"
#include "UnSolMessages/DDSSwitchIPCMessage.h"
#include "UnSolMessages/DDSSwitchTimeoutMessage.h"
#include "UnSolMessages/RadioConfigClientConnectedMessage.h"
#include "UnSolMessages/HandoverInformationIndMessage.h"
#include "UnSolMessages/DataCallTimerExpiredMessage.h"
#include "UnSolMessages/VoiceIndMessage.h"
#include "UnSolMessages/NewDDSInfoMessage.h"
#include "UnSolMessages/KeepAliveIndMessage.h"
#include "UnSolMessages/CleanDataCallStateMessage.h"
#include "UnSolMessages/VoiceCallOrigTimeoutMessage.h"
#include "event/CallBringupFallbackMessage.h"
#include "UnSolMessages/DeregisterWdsIndCompletedMessage.h"
#include "legacy/qcril_data_qmi_wds.h"
#include "legacy/qcril_data.h"
#include "AuthModemEndPoint.h"
#include "WDSModemEndPoint.h"
#include "DSDModemEndPoint.h"
#include "VoiceCallModemEndPoint.h"
#include "ProfileHandler.h"
#include "NetworkServiceHandler.h"
#include "qcril_reqlist.h"
#include "telephony/ril.h"
#include "modules/nas/NasSrvDomainPrefIndMessage.h"
#include "modules/nas/NasRequestDataShutdownMessage.h"
#include "modules/nas/NasPhysChanConfigMessage.h"
#ifndef QCRIL_RIL_VERSION
#error "undefined QCRIL_RIL_VERSION!"
#endif
#define INVALID_MSG_TOKEN -1
#define PROPERTY_MAX_PARTIAL_RETRY_TIMEOUT "persist.vendor.radio.max_retry_timeout"
#define PROPERTY_DISABLE_PARTIAL_RETRY "persist.vendor.radio.disable_retry"
#define PROPERTY_DISABLE_PARTIAL_RETRY_DEFAULT "false"
extern pthread_mutex_t ddsSubMutex;
#include "modules/uim/UimCardAppStatusIndMsg.h"
#include "modules/uim/UimGetMccMncRequestMsg.h"
#include "modules/uim/UimGetCardStatusRequestSyncMsg.h"
#define MCC_LENGTH 4
#define MNC_LENGTH 4
static load_module<rildata::DataModule> dataModule;
ProfileHandler::RilRespParams ProfileHandler::m_resp_params={ QCRIL_DEFAULT_INSTANCE_ID, QCRIL_DEFAULT_MODEM_ID, 0,0};
extern DDSSubIdInfo currentDDSSUB;
namespace rildata {
DataModule& getDataModule() {
return dataModule.get_module();
}
bool clearTimeoutForMessage( std::shared_ptr<Message> msg );
DataModule::DataModule() : mMessageList("DataModule") {
mName = "DataModule";
mLooper = std::unique_ptr<ModuleLooper>(new ModuleLooper);
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
wds_endpoint = ModemEndPointFactory<WDSModemEndPoint>::getInstance().buildEndPoint();
dsd_endpoint = ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint();
auth_endpoint = ModemEndPointFactory<AuthModemEndPoint>::getInstance().buildEndPoint();
#ifdef FEATURE_DATA_LQE
ott_endpoint = ModemEndPointFactory<OTTModemEndPoint>::getInstance().buildEndPoint();
#endif /* FEATURE_DATA_LQE */
preferred_data_sm = std::make_unique<PreferredDataStateMachine>();
preferred_data_state_info = std::make_shared<PreferredDataInfo_t>();
if(preferred_data_state_info != nullptr)
{
preferred_data_state_info->isRilIpcNotifier = false;
}
else
{
Log::getInstance().d("[DataModule]: preferred_data_state_info is NULL");
}
preferred_data_state_info->mVoiceCallInfo.voiceSubId = SubId::UNSPECIFIED;
preferred_data_sm->initialize(preferred_data_state_info);
preferred_data_sm->setCurrentState(Initial);
voiceCallEndPointSub0 = nullptr;
voiceCallEndPointSub1 = nullptr;
auth_manager = nullptr;
call_manager = nullptr;
profile_handler = nullptr;
networkavailability_handler = nullptr;
network_service_handler = nullptr;
keep_alive = std::make_shared<KeepAliveHandler>();
using std::placeholders::_1;
mMessageHandler = {
{QcrilInitMessage::get_class_message_id(), std::bind(&DataModule::handleQcrilInitMessage, this, _1)},
{RilRequestDataCallListMessage::get_class_message_id(), std::bind(&DataModule::handleDataCallListMessage, this, _1)},
{RilRequestGetDataCallProfileMessage::get_class_message_id(), std::bind(&DataModule::handleGetDataCallProfileMessage, this, _1)},
{RilRequestDeactivateDataCallMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestDeactivateDataCallMessage, this, _1)},
{RilRequestEmbmsActivateDeactivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsActivateDeactivateTmgiMessage, this, _1)},
{RilRequestEmbmsActivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsActivateTmgiMessage, this, _1)},
{RilRequestEmbmsContentDescUpdateMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsContentDescUpdateMessage, this, _1)},
{RilRequestEmbmsDeactivateTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsDeactivateTmgiMessage, this, _1)},
{EmbmsEnableDataReqMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsEnableDataReqMessage, this, _1)},
{RilRequestEmbmsGetActiveTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsGetActiveTmgiMessage, this, _1)},
{RilRequestEmbmsGetAvailTmgiMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsGetAvailTmgiMessage, this, _1)},
{RilRequestEmbmsSendIntTmgiListMessage::get_class_message_id(), std::bind(&DataModule::handleEmbmsSendIntTmgiListMessage, this, _1)},
{RilRequestGoDormantMessage::get_class_message_id(), std::bind(&DataModule::handleGoDormantMessage, this, _1)},
{RilRequestLastDataCallFailCauseMessage::get_class_message_id(), std::bind(&DataModule::handleLastDataCallFailCauseMessage, this, _1)},
{ProcessScreenStateChangeMessage::get_class_message_id(), std::bind(&DataModule::handleProcessScreenStateChangeMessage, this, _1)},
{ProcessStackSwitchMessage::get_class_message_id(), std::bind(&DataModule::handleProcessStackSwitchMessage, this, _1)},
{RilRequestPullLceDataMessage::get_class_message_id(), std::bind(&DataModule::handlePullLceDataMessage, this, _1)},
{SetApnInfoMessage::get_class_message_id(), std::bind(&DataModule::handleSetApnInfoMessage, this, _1)},
{SetIsDataEnabledMessage::get_class_message_id(), std::bind(&DataModule::handleSetIsDataEnabledMessage, this, _1)},
{SetIsDataRoamingEnabledMessage::get_class_message_id(), std::bind(&DataModule::handleSetIsDataRoamingEnabledMessage, this, _1)},
{SetQualityMeasurementMessage::get_class_message_id(), std::bind(&DataModule::handleSetQualityMeasurementMessage, this, _1)},
{RilRequestSetupDataCallMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetupDataCallMessage, this, _1)},
{RilRequestStartLceMessage::get_class_message_id(), std::bind(&DataModule::handleStartLceMessage, this, _1)},
{RilRequestStopLceMessage::get_class_message_id(), std::bind(&DataModule::handleStopLceMessage, this, _1)},
{ToggleDormancyIndMessage::get_class_message_id(), std::bind(&DataModule::handleToggleDormancyIndMessage, this, _1)},
{ToggleLimitedSysIndMessage::get_class_message_id(), std::bind(&DataModule::handleToggleLimitedSysIndMessage, this, _1)},
{UpdateMtuMessage::get_class_message_id(), std::bind(&DataModule::handleUpdateMtuMessage, this, _1)},
{RilDataEmbmsActiveMessage::get_class_message_id(), std::bind(&DataModule::handleDataEmbmsActiveMessage, this, _1)},
{GetDdsSubIdMessage::get_class_message_id(), std::bind(&DataModule::handleGetDdsSubIdMessage, this, _1)},
{RequestDdsSwitchMessage::get_class_message_id(), std::bind(&DataModule::handleDataRequestDDSSwitchMessage, this, _1)},
{VoiceIndMessage::get_class_message_id(), std::bind(&DataModule::handleVoiceIndMessage, this, _1)},
{DeregisterWdsIndCompletedMessage::get_class_message_id(),std::bind(&DataModule::handleDeregisterWdsIndCompletedMessage, this, _1)},
{VoiceCallOrigTimeoutMessage::get_class_message_id(), std::bind(&DataModule::handleVoiceCallOrigTimeoutMessage, this, _1)},
#if (QCRIL_RIL_VERSION >= 15)
{SetLteAttachProfileMessage_v15::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachProfileMessage_v15, this, _1)},
{RilRequestSetDataProfileMessage_v15::get_class_message_id(), std::bind(&DataModule::handleSetDataProfileMessage_v15, this, _1)},
{RilRequestStartKeepaliveMessage::get_class_message_id(), std::bind(&DataModule::handleStartKeepaliveMessage, this, _1)},
{RilRequestStopKeepaliveMessage::get_class_message_id(), std::bind(&DataModule::handleStopKeepaliveMessage, this, _1)},
{RilRequestSetCarrierInfoImsiEncryptionMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetCarrierInfoImsiEncryptionMessage, this, _1)},
{REG_MSG("AUTH_QMI_IND"), std::bind(&DataModule::handleQmiAuthServiceIndMessage, this, _1)},
{REG_MSG("AUTH_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiAuthEndpointStatusIndMessage, this, _1)},
{SetLinkCapFilterMessage::get_class_message_id(), std::bind(&DataModule::handleSetLinkCapFilterMessage, this, _1)},
{SetLinkCapRptCriteriaMessage::get_class_message_id(), std::bind(&DataModule::handleSetLinkCapRptCriteriaMessage, this, _1)},
{SetDataProfileRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetDataProfileRequestMessage, this, _1)},
{KeepAliveIndMessage::get_class_message_id(), std::bind(&DataModule::handleKeepAliveIndMessage, this, _1)},
{CleanDataCallStateMessage::get_class_message_id(), std::bind(&DataModule::handleCleanDataCallStateMessage, this, _1)},
{StartKeepAliveRequestMessage::get_class_message_id(), std::bind(&DataModule::handleStartKeepAliveRequestMessage, this, _1)},
{StopKeepAliveRequestMessage::get_class_message_id(), std::bind(&DataModule::handleStopKeepAliveRequestMessage, this, _1)},
#else
{SetLteAttachProfileMessage::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachProfileMessage, this, _1)},
{RilRequestSetDataProfileMessage::get_class_message_id(), std::bind(&DataModule::handleRilRequestSetDataProfileMessage, this, _1)},
#endif /* QCRIL_RIL_VERSION >= 15 */
{SetInitialAttachApnRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetInitialAttachApn, this, _1)},
{SetLteAttachPdnListActionResultMessage::get_class_message_id(), std::bind(&DataModule::handleSetLteAttachPdnListActionResult, this, _1)},
{NasSrvDomainPrefIndMessage::get_class_message_id(), std::bind(&DataModule::handleNasSrvDomainPrefInd, this, _1)},
{NasRequestDataShutdownMessage::get_class_message_id(), std::bind(&DataModule::handleNasRequestDataShutdown, this, _1)},
{DataBearerTypeChangedMessage::get_class_message_id(), std::bind(&DataModule::handleDataBearerTypeUpdate, this, _1)},
{DataAllBearerTypeChangedMessage::get_class_message_id(), std::bind(&DataModule::handleDataAllBearerTypeUpdate, this, _1)},
{RegisterBearerAllocationUpdateRequestMessage::get_class_message_id(), std::bind(&DataModule::handleToggleBearerAllocationUpdate, this, _1)},
{GetBearerAllocationRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetBearerAllocation, this, _1)},
{GetAllBearerAllocationsRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetAllBearerAllocations, this, _1)},
{REG_MSG("WDSModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiWdsEndpointStatusIndMessage, this, _1)},
{SetPreferredDataModemRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetPreferredDataModem, this, _1)},
{CurrentDDSIndMessage::get_class_message_id(), std::bind(&DataModule::handleCurrentDDSIndMessage, this, _1)},
{DDSSwitchResultIndMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchResultIndMessage, this, _1)},
{RadioConfigClientConnectedMessage::get_class_message_id(), std::bind(&DataModule::handleRadioConfigClientConnectedMessage, this, _1)},
{DDSSwitchTimeoutMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchTimeoutMessage, this, _1)},
{DDSSwitchIPCMessage::get_class_message_id(), std::bind(&DataModule::handleDDSSwitchIPCMessage, this, _1)},
{CallStatusMessage::get_class_message_id(), std::bind(&DataModule::handleDataConnectionStateChangedMessage, this, _1)},
{REG_MSG("DSDModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiDsdEndpointStatusIndMessage, this, _1)},
{IWLANCapabilityHandshake::get_class_message_id(), std::bind(&DataModule::handleIWLANCapabilityHandshake, this, _1)},
{GetAllQualifiedNetworkRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetAllQualifiedNetworksMessage, this, _1)},
{DsdSystemStatusMessage::get_class_message_id(), std::bind(&DataModule::handleDsdSystemStatusInd, this, _1)},
{DsdSystemStatusPerApnMessage::get_class_message_id(), std::bind(&DataModule::handleDsdSystemStatusPerApn, this, _1)},
{IntentToChangeApnPreferredSystemMessage::get_class_message_id(), std::bind(&DataModule::handleIntentToChangeInd, this, _1)},
{RilEventDataCallback::get_class_message_id(), std::bind(&DataModule::handleRilEventDataCallback, this, _1)},
{SetupDataCallRequestMessage::get_class_message_id(), std::bind(&DataModule::handleSetupDataCallRequestMessage, this, _1)},
{DeactivateDataCallRequestMessage::get_class_message_id(), std::bind(&DataModule::handleDeactivateDataCallRequestMessage, this, _1)},
{GetRadioDataCallListRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetRadioDataCallListRequestMessage, this, _1)},
{GetIWlanDataCallListRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetIWlanDataCallListRequestMessage, this, _1)},
{GetIWlanDataRegistrationStateRequestMessage::get_class_message_id(), std::bind(&DataModule::handleGetIWlanDataRegistrationStateRequestMessage, this, _1)},
{SetApnPreferredSystemResultMessage::get_class_message_id(), std::bind(&DataModule::handleSetApnPreferredSystemResult, this, _1)},
{HandoverInformationIndMessage::get_class_message_id(), std::bind(&DataModule::handleHandoverInformationIndMessage, this, _1)},
{DataCallTimerExpiredMessage::get_class_message_id(), std::bind(&DataModule::handleDataCallTimerExpiredMessage, this, _1)},
{SetRadioClientCapUnSolMessage::get_class_message_id(), std::bind(&DataModule::handleSetRadioClientCapUnSolMessage, this, _1)},
{NasPhysChanConfigReportingStatus::get_class_message_id(), std::bind(&DataModule::handleNasPhysChanConfigReportingStatusMessage, this, _1)},
{NasPhysChanConfigMessage::get_class_message_id(), std::bind(&DataModule::handleNasPhysChanConfigMessage, this, _1)},
{UimCardAppStatusIndMsg::get_class_message_id(), std::bind(&DataModule::handleUimCardAppStatusIndMsg, this, _1)},
#ifdef FEATURE_DATA_LQE
{REG_MSG("OTTModemEndPoint_ENDPOINT_STATUS_IND"), std::bind(&DataModule::handleQmiOttEndpointStatusIndMessage, this, _1)},
#endif /* FEATURE_DATA_LQE */
{CallManagerEventMessage::get_class_message_id(), std::bind(&DataModule::handleCallManagerEventMessage, this, _1)},
{CallBringupFallbackMessage::get_class_message_id(), std::bind(&DataModule::handleCallBringupFallbackMessage, this, _1)},
{SetCarrierInfoImsiEncryptionMessage::get_class_message_id(), std::bind(&DataModule::handleSetCarrierInfoImsiEncryptionMessage, this, _1)},
};
//Read system property to determine IWLAN mode
//TODO:: change default value to "1" or legacy mode before initial checkin
//TODO:: change default value to "0" or default mode when we have code in place
//to determine Radio hal version
string propValue = readProperty("ro.telephony.iwlan_operation_mode", "default");
Log::getInstance().d("[" + mName + "]: IWLAN mode system property is " + propValue);
if(propValue.compare("default") == 0) {
propValue = "0";
}
else if(propValue.compare("legacy") == 0) {
propValue = "1";
}
else if(propValue.compare("AP-assisted") == 0) {
propValue = "2";
}
else {
Log::getInstance().d("ro.telephony.iwlan_operation_mode is configured with ["+
propValue + "], configuring it to default mode");
propValue = "0";
}
#ifdef QMI_RIL_UTF
mInitTracker.setIWLANMode(rildata::IWLANOperationMode::AP_ASSISTED);
#else
mInitTracker.setIWLANMode((rildata::IWLANOperationMode)atoi(propValue.c_str()));
#endif
propValue = readProperty(PROPERTY_DISABLE_PARTIAL_RETRY, PROPERTY_DISABLE_PARTIAL_RETRY_DEFAULT);
Log::getInstance().d("[" + mName + "]: Partial retry disabled property is " + propValue);
std::transform( propValue.begin(), propValue.end(), propValue.begin(),
[](char c) -> char { return std::tolower(c); });
if ("true" == propValue) {
mInitTracker.setPartialRetryEnabled(false);
}
}
DataModule::~DataModule() {
mLooper = nullptr;
//mDsdEndPoint = nullptr;
}
PendingMessageList& DataModule::getPendingMessageList() {
return mMessageList;
}
void DataModule::init() {
/* Call base init before doing any other stuff.*/
Module::init();
}
void DataModule::broadcastReady()
{
std::shared_ptr<DataInitMessage> data_init_msg =
std::make_shared<DataInitMessage>(global_instance_id);
Dispatcher::getInstance().broadcast(data_init_msg);
}
string DataModule::readProperty(string name, string defaultValue) {
char cPropValue[256] = {'\0'};
property_get(name.c_str(), cPropValue, defaultValue.c_str());
return string(cPropValue);
}
void DataModule::dump(int fd)
{
std::ostringstream ss;
if (call_manager != nullptr) {
call_manager->dump("", ss);
}
ss << "NetworkAvailabilityHandler:" << endl;
if (networkavailability_handler != nullptr) {
networkavailability_handler->dump(" ", ss);
}
ss << "NetworkServiceHandler:" << endl;
if (network_service_handler != nullptr) {
network_service_handler->dump(" ", ss);
}
ss << "InitTracker:" << endl;
mInitTracker.dump(" ", ss);
ss << " IWlanHandshakeMsgToken=" << iwlanHandshakeMsgToken << endl;
ss << " CurrentDDS=" << currentDDSSUB.dds_sub_id << endl;
ss << " SwitchType=" << currentDDSSUB.switch_type << endl;
ss << endl << "Logs:" << endl;
vector<string> logs = networkAvailabilityLogBuffer.getLogs();
ss << "NetworkAvailability:" << endl;
for (const string& msg: logs) {
ss << msg << endl;
}
ss << endl << "DataModule:" << endl;
logs = logBuffer.getLogs();
for (const string& msg: logs) {
ss << msg << endl;
}
#ifdef QMI_RIL_UTF
logBuffer.toLogcat();
cout << ss.str();
#else
LocalLogBuffer::toFd(ss.str(), fd);
#endif
}
void DataModule::handleQcrilInitMessage(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
#ifdef QMI_RIL_UTF
usleep(500000);
#endif
auto qcril_init_msg = std::static_pointer_cast<QcrilInitMessage>(msg);
if( qcril_init_msg != NULL )
{
global_instance_id = qcril_init_msg->get_instance_id();
logBuffer.setName("RIL" + std::to_string(global_instance_id));
QmiSetupRequestCallback callback("data-token");
dsd_endpoint->requestSetup("data-token-client-server", &callback);
wds_endpoint->requestSetup("data-token-client-server", &callback);
auth_endpoint->requestSetup("data-token-client-server", &callback);
#ifdef FEATURE_DATA_LQE
ott_endpoint->requestSetup("data-token-client-server", &callback);
#endif /* FEATURE_DATA_LQE */
broadcastReady();
Log::getInstance().d("[" + mName + "]: Done msg = " + msg->dump());
} else {
Log::getInstance().d("[" + mName + "]: Improper message received. =" + msg->dump() + "QCRIL DATA Init not triggered!!!");
}
}
void DataModule::handleDataCallListMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
qcril_request_return_type ret;
auto m = std::static_pointer_cast<RilRequestDataCallListMessage>(msg);
if( m != NULL ) {
qcril_data_request_data_call_list(&(m->get_params()), &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetDataCallProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestGetDataCallProfileMessage> m = std::static_pointer_cast<RilRequestGetDataCallProfileMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_omh_profile_info(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestDeactivateDataCallMessage(std::shared_ptr<Message> msg) {
if( msg == NULL ) {
Log::getInstance().d("[" + mName + "]: ERROR!!! Msg received is NULL");
return;
}
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
// Cancel the default timer
clearTimeoutForMessage(msg);
//Add a new timeout handler
setTimeoutForMsg(msg, msg->getMessageExpiryTimer());
std::shared_ptr<RilRequestDeactivateDataCallMessage> m = std::static_pointer_cast<RilRequestDeactivateDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_deactivate_data_call(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
void DataModule::handleEmbmsActivateDeactivateTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsActivateDeactivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsActivateDeactivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsActivateDeactivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsActivateTmgiMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[Riddhi] DataModule Activate Embms request");
std::shared_ptr<RilRequestEmbmsActivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsActivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsActivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsContentDescUpdateMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsContentDescUpdateMessage> m = std::static_pointer_cast<RilRequestEmbmsContentDescUpdateMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsContentDescUpdate(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsDeactivateTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsDeactivateTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsDeactivateTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsDeactivateTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsEnableDataReqMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<EmbmsEnableDataReqMessage> m = std::static_pointer_cast<EmbmsEnableDataReqMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsEnableDataRequestMessage(req.instance_id);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsGetActiveTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsGetActiveTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsGetActiveTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsGetActiveTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsGetAvailTmgiMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsGetAvailTmgiMessage> m = std::static_pointer_cast<RilRequestEmbmsGetAvailTmgiMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsGetAvailableTmgi(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleEmbmsSendIntTmgiListMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestEmbmsSendIntTmgiListMessage> m = std::static_pointer_cast<RilRequestEmbmsSendIntTmgiListMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
call_manager->handleEmbmsSendInterestedList(&req);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGoDormantMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestGoDormantMessage> m = std::static_pointer_cast<RilRequestGoDormantMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_resp_params_type resp;
resp.instance_id = req.instance_id;
resp.t = req.t;
resp.request_id = req.event_id;
resp.resp_pkt = NULL;
resp.resp_len = 0;
resp.logstr = NULL;
resp.rild_sock_oem_req = 0;
resp.ril_err_no = RIL_E_SUCCESS;
if(call_manager != nullptr)
{
bool status = call_manager->handleGoDormantRequest(req.data, req.datalen);
if (status == false) {
resp.ril_err_no = RIL_E_OEM_ERROR_3;
}
qcril_send_request_response(&resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleLastDataCallFailCauseMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestLastDataCallFailCauseMessage> m = std::static_pointer_cast<RilRequestLastDataCallFailCauseMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_last_data_call_fail_cause(&req,&ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleProcessScreenStateChangeMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ProcessScreenStateChangeMessage> m = std::static_pointer_cast<ProcessScreenStateChangeMessage>(msg);
if( m != NULL ) {
int ret = qcril_data_process_screen_state_change(m->screenState);
Message::Callback::Status status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleProcessStackSwitchMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ProcessStackSwitchMessage> m = std::static_pointer_cast<ProcessStackSwitchMessage>(msg);
if( m != NULL ) {
ProcessStackSwitchMessage::StackSwitchReq info = m->getParams();
qcril_data_process_stack_switch( info.oldStackId, info.newStackId, info.instanceId);
auto resp = std::make_shared<int>(QCRIL_DS_SUCCESS);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handlePullLceDataMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestPullLceDataMessage> m = std::static_pointer_cast<RilRequestPullLceDataMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_get_info(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetApnInfoMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetApnInfoMessage> m = std::static_pointer_cast<SetApnInfoMessage>(msg);
if( m != NULL ) {
RIL_Errno ret = qcril_data_set_apn_info(&m->mParams, m->mApnType, m->mApnName, m->mIsApnValid);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetIsDataEnabledMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetIsDataEnabledMessage> m = std::static_pointer_cast<SetIsDataEnabledMessage>(msg);
if ( m != NULL ) {
qcril_request_params_type req = m->get_params();
RIL_Errno ret = qcril_data_set_is_data_enabled( &req, m->is_data_enabled);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetIsDataRoamingEnabledMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetIsDataRoamingEnabledMessage> m = std::static_pointer_cast<SetIsDataRoamingEnabledMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
RIL_Errno ret = qcril_data_set_is_data_roaming_enabled(&req, m->is_data_roaming_enabled);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#if (QCRIL_RIL_VERSION >= 15)
void DataModule::handleSetLteAttachProfileMessage_v15(std::shared_ptr<Message> msg) {
std::shared_ptr<SetLteAttachProfileMessage_v15> reqMsg = std::static_pointer_cast<SetLteAttachProfileMessage_v15>(msg);
if( reqMsg != NULL ) {
RIL_Errno ret = qcril_data_request_set_lte_attach_profile_v15 ( reqMsg->get_params() );
auto resp = std::make_shared<RIL_Errno>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetDataProfileMessage_v15(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestSetDataProfileMessage_v15> m = std::static_pointer_cast<RilRequestSetDataProfileMessage_v15>(msg);
if ( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_set_data_profile(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetDataProfileRequestMessage
===========================================================================*/
/*!
@brief
Handler to handle SetDataProfileRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetDataProfileRequestMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetDataProfileRequestMessage> m =
std::static_pointer_cast<SetDataProfileRequestMessage>(msg);
if( m != NULL ) {
if(profile_handler != nullptr) {
profile_handler->handleSetDataProfileRequestMessage(msg);
}
else {
RIL_Errno result = RIL_E_INTERNAL_ERR;
auto resp = std::make_shared<RIL_Errno>(result);
m->sendResponse(msg, Message::Callback::Status::FAILURE, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
if (m != NULL && networkavailability_handler != nullptr) {
networkavailability_handler->processSetDataProfileRequest(msg);
}
}
#else
void DataModule::handleSetLteAttachProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetLteAttachProfileMessage> reqMsg = std::static_pointer_cast<SetLteAttachProfileMessage>(msg);
if( reqMsg != NULL ) {
RIL_Errno ret = qcril_data_request_set_lte_attach_profile ( reqMsg->get_params() );
auto resp = std::make_shared<RIL_Errno>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetDataProfileMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestSetDataProfileMessage> m = std::static_pointer_cast<RilRequestSetDataProfileMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_set_data_profile(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#endif /* #if QCRIL_RIL_VERSION >= 15 */
void DataModule::handleSetQualityMeasurementMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetQualityMeasurementMessage> reqMsg = std::static_pointer_cast<SetQualityMeasurementMessage>(msg);
if( reqMsg != NULL ) {
dsd_set_quality_measurement_info_req_msg_v01 info = reqMsg->getInfo();
qmi_response_type_v01 ret= qcril_data_set_quality_measurement(&info);
auto resp = std::make_shared<qmi_response_type_v01>(ret);
reqMsg->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetRadioClientCapUnSolMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<SetRadioClientCapUnSolMessage> m = std::static_pointer_cast<SetRadioClientCapUnSolMessage>(msg);
if( m != NULL ) {
bool isAPAssistCapable = m->getParams();
if (!mInitTracker.isModeDetermined()) {
mInitTracker.setIWLANMode(isAPAssistCapable ? IWLANOperationMode::AP_ASSISTED : IWLANOperationMode::LEGACY);
performDataModuleInitialization();
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetupDataCallMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestSetupDataCallMessage> m = std::static_pointer_cast<RilRequestSetupDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_request_setup_data_call(&req, &ret);
// We don't return response here. It will be sent upon
// success/failure at a later point in time.
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStartLceMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestStartLceMessage> m = std::static_pointer_cast<RilRequestStartLceMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_start(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopLceMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilRequestStopLceMessage> m = std::static_pointer_cast<RilRequestStopLceMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_lqe_stop(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleToggleDormancyIndMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ToggleDormancyIndMessage> m = std::static_pointer_cast<ToggleDormancyIndMessage>(msg);
if( m != NULL ) {
int ret;
Message::Callback::Status status;
if (call_manager) {
ret = qcril_data_toggle_dormancy_indications(m->dormIndSwitch);
mLinkStatusReportEnabled = (m->dormIndSwitch == DORMANCY_INDICATIONS_ON)?true:false;
ret = call_manager->toggleLinkActiveStateChangeReport(mLinkStatusReportEnabled);
status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
}
else {
Log::getInstance().d("call_manager is null");
status = Message::Callback::Status::SUCCESS;
ret = QCRIL_DS_ERROR;
}
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleToggleLimitedSysIndMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<ToggleLimitedSysIndMessage> m = std::static_pointer_cast<ToggleLimitedSysIndMessage>(msg);
if( m != NULL ) {
int ret = qcril_data_toggle_limited_sys_indications(m->sysIndSwitch);
if (dsd_endpoint) {
mLimitedIndReportEnabled = (m->sysIndSwitch == LIMITED_SYS_INDICATIONS_ON)?true:false;
ret = dsd_endpoint->toggleLimitedSysIndicationChangeReport(mLimitedIndReportEnabled);
}
Message::Callback::Status status = (ret == QCRIL_DS_SUCCESS ?
Message::Callback::Status::SUCCESS : Message::Callback::Status::FAILURE);
auto resp = std::make_shared<int>(ret);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleUpdateMtuMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<UpdateMtuMessage> m = std::static_pointer_cast<UpdateMtuMessage>(msg);
if( m != NULL ) {
qcril_data_update_mtu(m->Mtu);
auto resp = std::make_shared<int>(QCRIL_DS_SUCCESS);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDataEmbmsActiveMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RilDataEmbmsActiveMessage> m = std::static_pointer_cast<RilDataEmbmsActiveMessage>(msg);
if( m != NULL ) {
int is_Embms_Active = qcril_data_is_embms_active();
auto resp = std::make_shared<bool>(is_Embms_Active);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetDdsSubIdMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetDdsSubIdMessage> m = std::static_pointer_cast<GetDdsSubIdMessage>(msg);
if( m != NULL ) {
DDSSubIdInfo ddsInfo = qcril_data_get_dds_sub_info();
LOCK_MUTEX(ddsSubMutex);
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]:Current DDS is on SUB ="+std::to_string(currentDDSSUB.dds_sub_id)+
"switch type = "+std::to_string(currentDDSSUB.switch_type));
auto resp = std::make_shared<DDSSubIdInfo>(ddsInfo);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleVoiceIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<VoiceIndMessage> m = std::static_pointer_cast<VoiceIndMessage>(msg);
if(m != NULL)
{
preferred_data_state_info->mVoiceCallInfo.voiceSubId = m->getSubId();
preferred_data_state_info->mVoiceCallInfo.voiceCallState = m->getCallState();
preferred_data_state_info->mVoiceCallInfo.voiceCallType = m->getCallType();
preferred_data_state_info->mVoiceCallInfo.voiceCallRat = m->getCallRat();
if(m->getSubId() == SubId::PRIMARY && voiceCallEndPointSub0->mIsVoiceCallOrigTimer)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = FALSE;
TimeKeeper::getInstance().clear_timer(voiceCallEndPointSub0->mVoiceCallOrigTimer);
}
if(m->getSubId() == SubId::SECONDARY && voiceCallEndPointSub1->mIsVoiceCallOrigTimer)
{
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = FALSE;
TimeKeeper::getInstance().clear_timer(voiceCallEndPointSub1->mVoiceCallOrigTimer);
}
//Temporary switch
if((int)m->getSubId() != preferred_data_state_info->dds && m->getCallState() != VoiceCallStateEnum::CALL_STATE_END)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_TEMPORARY_V01;
Log::getInstance().d("Temporary DDS switch on sub" + std::to_string((int)preferred_data_state_info->mVoiceCallInfo.voiceSubId));
if(m->getCallState() == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
if(m->getSubId() == SubId::PRIMARY)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = TRUE;
voiceCallEndPointSub0->mVoiceCallOrigTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleVoiceCallOrigTimerExpired, this, std::placeholders::_1), nullptr, VOICEIND_WAITING_TIMEOUT);
}
else
{
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = TRUE;
voiceCallEndPointSub1->mVoiceCallOrigTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleVoiceCallOrigTimerExpired, this, std::placeholders::_1), nullptr, VOICEIND_WAITING_TIMEOUT);
}
}
}
else
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
Log::getInstance().d("Permanent DDS switch on sub" + std::to_string((int)preferred_data_state_info->mVoiceCallInfo.voiceSubId));
}
if(m->getCallState() == VoiceCallStateEnum::CALL_STATE_END && preferred_data_state_info->switch_type == DSD_DDS_SWITCH_TEMPORARY_V01)
{
TempddsSwitchRequestPending = true;
tempDDSSwitchRequestTimer = TimeKeeper::getInstance().set_timer(std::bind(&DataModule::handleTempDDSSwitchTimerExpired, this, std::placeholders::_1), nullptr, TempDDS_SWITCH_REQUEST_TIMEOUT);
}
}
}
void DataModule::handleTempDDSSwitchTimerExpired(void *) {
Log::getInstance().d("Datamodule: onTempDDSSwitchRequestExpired ENTRY");
DDSTimeOutSwitchType type = DDSTimeOutSwitchType::TempDDSTimeOutSwitch;
auto msg = std::make_shared<DDSSwitchTimeoutMessage>(type);
msg->broadcast();
}
void DataModule::handleVoiceCallOrigTimerExpired(void *) {
Log::getInstance().d("DataModule: handleVoiceCallOrigTimerExpired");
auto msg = std::make_shared<VoiceCallOrigTimeoutMessage>();
msg->broadcast();
}
void DataModule::handleVoiceCallOrigTimeoutMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("DataModule: handleVoiceCallOrigTimeoutMessage");
std::shared_ptr<VoiceCallOrigTimeoutMessage> m = std::static_pointer_cast<VoiceCallOrigTimeoutMessage>(msg);
if( m != nullptr)
{
bool isCallActive = false;
if(preferred_data_state_info->mVoiceCallInfo.voiceSubId == SubId::PRIMARY)
{
voiceCallEndPointSub0->mIsVoiceCallOrigTimer = FALSE;
isCallActive = voiceCallEndPointSub0->isVoiceCall();
if(!isCallActive || preferred_data_state_info->mVoiceCallInfo.voiceCallState == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
}
} else {
voiceCallEndPointSub1->mIsVoiceCallOrigTimer = FALSE;
isCallActive = voiceCallEndPointSub1->isVoiceCall();
if(!isCallActive || preferred_data_state_info->mVoiceCallInfo.voiceCallState == VoiceCallStateEnum::CALL_STATE_CC_IN_PROGRESS)
{
preferred_data_state_info->switch_type = DSD_DDS_SWITCH_PERMANENT_V01;
}
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDataRequestDDSSwitchMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<RequestDdsSwitchMessage> m = std::static_pointer_cast<RequestDdsSwitchMessage>(msg);
if( m != NULL ) {
RIL_Errno ret = qcril_data_request_dds_switch(m->dds_sub_info);
auto resp = std::make_shared<RIL_Errno>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#if (QCRIL_RIL_VERSION >= 15)
void DataModule::handleStartKeepaliveMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestStartKeepaliveMessage> m = std::static_pointer_cast<RilRequestStartKeepaliveMessage>(msg);
if( m != NULL) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_start_modem_assist_keepalive(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopKeepaliveMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestStopKeepaliveMessage> m = std::static_pointer_cast<RilRequestStopKeepaliveMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_return_type ret;
qcril_data_stop_modem_assist_keepalive(&req, &ret);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleKeepAliveIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<KeepAliveIndMessage> m = std::static_pointer_cast<KeepAliveIndMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
keep_alive_ind ind;
ind.status = m->get_status();
ind.handle = m->get_handle();
eve.event = KeepAliveInd;
eve.data = &ind ;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleCleanDataCallStateMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CleanDataCallStateMessage> m = std::static_pointer_cast<CleanDataCallStateMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
eve.event = KeepAliveCleanCallState;
int cid = m->getcid();
eve.data = &cid;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStartKeepAliveRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<StartKeepAliveRequestMessage> m = std::static_pointer_cast<StartKeepAliveRequestMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
KeepaliveRequest_t request = m->getKeepaliveRequest();
keep_alive_start_request ka_start_req;
if (call_manager) {
if((call_manager->findCallInfo(request.cid)) != nullptr)
{
ka_start_req.apn = call_manager->getApnByCid(request.cid);
ka_start_req.ril_ka_req = &request;
eve.data = &ka_start_req;
} else {
Log::getInstance().d("There is no call with given cid " + std::to_string(request.cid));
eve.data = nullptr;
}
eve.event = KeepAliveStartReq;
eve.msg = msg;
keep_alive->processEvent(eve);
}
else {
Log::getInstance().d("call_manager is null");
StartKeepAliveResp_t res;
res.error = ResponseError_t::INTERNAL_ERROR;
auto resp = std::make_shared<StartKeepAliveResp_t>(res);
m->sendResponse(m, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleStopKeepAliveRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<StopKeepAliveRequestMessage> m = std::static_pointer_cast<StopKeepAliveRequestMessage>(msg);
if( m!= NULL ) {
KeepAliveEventType eve;
eve.event = KeepAliveStopReq;
eve.data = m->getHandle();
eve.msg = msg;
keep_alive->processEvent(eve);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleRilRequestSetCarrierInfoImsiEncryptionMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<RilRequestSetCarrierInfoImsiEncryptionMessage> m = std::static_pointer_cast<RilRequestSetCarrierInfoImsiEncryptionMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
qcril_request_resp_params_type resp;
resp.instance_id = QCRIL_DEFAULT_INSTANCE_ID;
resp.t = req.t;
resp.request_id = req.event_id;
resp.request_id_android = RIL_REQUEST_SET_CARRIER_INFO_IMSI_ENCRYPTION;
resp.resp_pkt = NULL;
resp.resp_len = 0;
resp.logstr = NULL;
resp.rild_sock_oem_req = 0;
if (auth_manager) {
auth_manager->setCarrierInfoImsiEncryption(&req);
resp.ril_err_no = RIL_E_SUCCESS;
}
else {
Log::getInstance().d("auth_manager is null");
resp.ril_err_no = RIL_E_INTERNAL_ERR;
}
qcril_send_request_response( &resp );
}else {
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
void DataModule::handleQmiAuthServiceIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<QmiIndMessage>(msg));
QmiIndMsgDataStruct *indData = shared_indMsg->getData();
if (indData != nullptr && auth_manager!= nullptr) {
auth_manager->qmiAuthServiceIndicationHandler(indData->msgId, indData->indData,
indData->indSize);
} else {
Log::getInstance().d("[" + mName + "] Unexpected, null data from message");
}
}
void DataModule::handleQmiAuthEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getAuthServiceReady()) {
mInitTracker.setAuthServiceReady(true);
performDataModuleInitialization();
}
}
else {
mInitTracker.setAuthServiceReady(false);
Log::getInstance().d("[" + mName + "]: ModemEndPoint is not operational");
}
}
void DataModule::handleQmiDsdEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if( !mInitTracker.getDsdServiceReady() ) {
mInitTracker.setDsdServiceReady(true);
performDataModuleInitialization();
}
DDSSubIdInfo ddsInfo;
Log::getInstance().d("[" + mName + "]:dispatching currentDDSSync message");
auto status = ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint()->getCurrentDDSSync(ddsInfo);
if(status == Message::Callback::Status::SUCCESS)
{
LOCK_MUTEX(ddsSubMutex);
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]:Current DDS is on Sub ="+std::to_string(currentDDSSUB.dds_sub_id)+
" and Switch type = "+std::to_string(currentDDSSUB.switch_type));
//posting currentDDS
PreferredDataEventType currentDdsEvent;
DDSSwitchInfo_t eventData;
eventData.subId = ddsInfo.dds_sub_id;
currentDdsEvent.event = CurrentDDSInd;
currentDdsEvent.data = &eventData;
preferred_data_sm->processEvent(currentDdsEvent);
}
else
{
Log::getInstance().d("Failed to get the current DDS information");
}
}
else {
//Reset all interested handlers
Log::getInstance().d("[" + mName + "]: ModemEndPoint is not operational");
mInitTracker.setDsdServiceReady(false);
}
}
bool DataModule::loadDatactl() {
bool ret = false;
void *datactlLib;
do {
datactlLib = dlopen("libqcrildatactl.so", RTLD_LAZY);
if( NULL == datactlLib ) {
Log::getInstance().d("[" + mName + "]: Unable to load libqcrildatactl.so");
break;
}
dlerror();
dcSymbols.datactlInit = (datactlInitFnPtr)dlsym(datactlLib, "datactlInit");
const char *dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlInit symbol");
break;
}
dcSymbols.datactlEnableIWlan = (datactlEnableIWlanFnPtr)dlsym(datactlLib, "datactlEnableIWlan");
dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlEnableIWlan symbol");
break;
}
dcSymbols.datactlDisableIWlan = (datactlDisableIWlanFnPtr)dlsym(datactlLib, "datactlDisableIWlan");
dlsym_error = dlerror();
if( dlsym_error ) {
Log::getInstance().d("[" + mName + "]: Cannot find datactlDisableIWlan symbol");
break;
}
//Successfully reached the end
ret = true;
}
while( 0 );
if( ret == false ) {
if( datactlLib ) {
dlclose(datactlLib);
memset(&dcSymbols, 0, sizeof(dcSymbols)); //Reset all fn ptrs to 0
}
}
return ret;
}
void DataModule::logFn(std::string logStr) {
Log::getInstance().d(logStr);
}
//Perform initialization that are common to services being initialized
//and mode being determined
void DataModule::performDataModuleInitialization() {
if( mInitTracker.allServicesReady() && mInitTracker.isModeDetermined()) {
if( mInitTracker.servicesReadyAfterBootup() || !mInitCompleted) {
logBuffer.addLogWithTimestamp("[" + mName + "]: performDataModuleInitialization");
auth_manager = std::make_unique<AuthManager>();
profile_handler = std::make_unique<ProfileHandler>();
call_manager = std::make_unique<CallManager>(logBuffer);
string propValue = readProperty(PROPERTY_MAX_PARTIAL_RETRY_TIMEOUT, "");
Log::getInstance().d("[" + mName + "]: Partial retry max timeout property is " + propValue);
unsigned long maxTimeout = DEFAULT_MAX_PARTIAL_RETRY_TIMEOUT;
if (!propValue.empty()) {
maxTimeout = stoul(propValue);
}
call_manager->init(mInitTracker.isAPAssistMode(),
mInitTracker.isPartialRetryEnabled(), maxTimeout);
profile_handler->init(mInitTracker.isAPAssistMode());
qcril_data_init(mInitTracker.isAPAssistMode());
auth_manager->qmiAuthServiceRegisterIndications(true);
dsd_endpoint->setV2Capabilities();
dsd_endpoint->generateDsdSystemStatusInd();
dsd_endpoint->registerForSystemStatusSync();
dsd_endpoint->toggleLimitedSysIndicationChangeReport(mLimitedIndReportEnabled);
#if (QCRIL_RIL_VERSION >= 15)
/* Register for QMI_WDS_MODEM_ASSISTED_KA_STATUS_IND_V01 */
Message::Callback::Status status = wds_endpoint->registerForKeepAliveInd(TRUE);
Log::getInstance().d("[DataModule] getKeepAliveMessageSync request "
"result = " + std::to_string((int) status));
#endif
preferred_data_state_info->sub = global_instance_id;
Messenger::get().registerForMessage(DDSSwitchIPCMessage::get_class_message_id(),
std::bind(&DataModule::constructDDSSwitchIPCMessage,
this, std::placeholders::_1));
PreferredDataEventType initEvent;
initEvent.event = InitializeSM;
preferred_data_sm->processEvent(initEvent);
if( mInitTracker.isAPAssistMode() ) {
//Create AP assist variant of NetworkServiceHandler
network_service_handler = std::make_unique<ApAssistNetworkServiceHandler>();
Message::Callback::Status status = dsd_endpoint->sendAPAssistIWLANSupportedSync();
Log::getInstance().d("[DataModule] sendAPAssistIWLANSupportedSync request "
" result = " + std::to_string((int) status));
if (status == Message::Callback::Status::SUCCESS)
{
mInitTracker.setModemCapability(true);
//call datactl to enable/disable IWLAN
if (loadDatactl()) {
dcSymbols.datactlInit(global_instance_id, logFn);
if( mInitTracker.isIWLANEnabled() ) {
initializeIWLAN();
}
else {
dcSymbols.datactlDisableIWlan();
}
}
#ifdef QMI_RIL_UTF
else {
if( mInitTracker.isIWLANEnabled() ) {
initializeIWLAN();
}
}
#endif
}
else
{
//This should never happen
mInitTracker.setModemCapability(false);
if(iwlanHandshakeMsgToken != INVALID_MSG_TOKEN) {
Log::getInstance().d("[DataModule] Look for IWLANCapabilityHandshake msg "+
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
std::shared_ptr<Message> mmm = getDataModule().getPendingMessageList().find((uint16_t)iwlanHandshakeMsgToken);
if(mmm!=nullptr) {
std::shared_ptr<IWLANCapabilityHandshake> iwlanHsMsg = std::static_pointer_cast<IWLANCapabilityHandshake>(mmm);
if(iwlanHsMsg != nullptr) {
auto resp = std::make_shared<rildata::ModemIWLANCapability_t>(rildata::ModemIWLANCapability_t::not_present);
iwlanHsMsg->sendResponse(mmm, Message::Callback::Status::SUCCESS, resp);
getDataModule().getPendingMessageList().erase(mmm);
getDataModule().getPendingMessageList().print();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
} else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandShake msg. Not sending response");
}
}
else {
Log::getInstance().d("[DataModule] No IWLANCapabilityHandshake msg found");
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
}
}
else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandshake msg token");
}
}
}
else { //Legacy mode
//Create legacy mode variant of NetworkServiceHandler
network_service_handler = std::make_unique<NetworkServiceHandler>();
network_service_handler->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
call_manager->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
mInitCompleted = TRUE;
}
else { //Services ready after SSR
if(auth_manager != nullptr)
{
auth_manager->qmiAuthServiceRegisterIndications(true);
auth_manager->updateModemWithCarrierImsiKeyCache();
} else {
Log::getInstance().d(" auth_manager is NULL");
}
dsd_endpoint->setV2Capabilities();
dsd_endpoint->generateDsdSystemStatusInd();
dsd_endpoint->registerForSystemStatusSync();
auto status = dsd_endpoint->registerForCurrentDDSInd();
if (status == Message::Callback::Status::SUCCESS) {
Log::getInstance().d(": Successfully registered for current DDS indication");
} else {
Log::getInstance().d(": Failed to register for current DDS indication");
}
if( mInitTracker.isAPAssistMode() ) {
Message::Callback::Status status = dsd_endpoint->sendAPAssistIWLANSupportedSync();
Log::getInstance().d("[DataModule] sendAPAssistIWLANSupportedSync request "
" result = " + std::to_string((int) status));
//send message to datactl to enable/disable IWLAN
if( mInitTracker.isIWLANEnabled() ) {
if (dcSymbols.datactlEnableIWlan) {
dcSymbols.datactlEnableIWlan();
}
status = dsd_endpoint->registerForAPAsstIWlanIndsSync(true);
Log::getInstance().d("[DataModule] registerForAPAsstPrefSysChgSync request "
" result = " + std::to_string((int) status));
}
else {
if (dcSymbols.datactlDisableIWlan) {
dcSymbols.datactlDisableIWlan();
}
}
}
}
}
}
//Perform intializations that are common to services being initialized, mode
//being determined and IWLAN being enabled
void DataModule::initializeIWLAN() {
if(iwlanHandshakeMsgToken != INVALID_MSG_TOKEN) {
Log::getInstance().d("[DataModule] Look for IWLANCapabilityHandshake msg "+
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
std::shared_ptr<Message> mmm = getDataModule().getPendingMessageList().find((uint16_t)iwlanHandshakeMsgToken);
if(mmm!=nullptr) {
std::shared_ptr<IWLANCapabilityHandshake> iwlanHsMsg = std::static_pointer_cast<IWLANCapabilityHandshake>(mmm);
if(iwlanHsMsg != nullptr)
{
auto resp = std::make_shared<rildata::ModemIWLANCapability_t>(
mInitTracker.getModemCapability() ?
rildata::ModemIWLANCapability_t::present:
rildata::ModemIWLANCapability_t::not_present);
iwlanHsMsg->sendResponse(mmm, Message::Callback::Status::SUCCESS, resp);
getDataModule().getPendingMessageList().erase(mmm);
getDataModule().getPendingMessageList().print();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
} else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandShake msg. Not sending response");
}
}
else {
Log::getInstance().d("[DataModule] No IWLANCapabilityHandshake msg found");
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
}
}
else {
Log::getInstance().d("[DataModule] Invalid IWLANCapabilityHandshake msg token");
}
Message::Callback::Status status = dsd_endpoint->registerForAPAsstIWlanIndsSync(true);
Log::getInstance().d("[DataModule] registerForIndications requst"
" result = "+ std::to_string((int) status));
networkavailability_handler = std::make_unique<NetworkAvailabilityHandler>(networkAvailabilityLogBuffer);
if (mCachedSystemStatus.apn_avail_sys_info_valid) {
networkavailability_handler->processQmiDsdSystemStatusInd(mCachedSystemStatus.apn_avail_sys_info,
mCachedSystemStatus.apn_avail_sys_info_len);
}
#ifndef QMI_RIL_UTF
//send message to datactl to enable IWLAN
if (dcSymbols.datactlEnableIWlan) dcSymbols.datactlEnableIWlan();
#endif
}
void DataModule::deinitializeIWLAN() {
Message::Callback::Status status = dsd_endpoint->registerForAPAsstIWlanIndsSync(false);
if (status != Message::Callback::Status::SUCCESS)
{
Log::getInstance().d("[DataModule] deregisterForIndications requst failed,"
" result = "+ std::to_string((int) status));
}
else
{
Log::getInstance().d("[DataModule] deregisterForIndications request successful"
", result = "+ std::to_string((int) status));
}
networkavailability_handler.reset();
networkavailability_handler = nullptr;
//Send message on datactl to disable IWLAN
if (dcSymbols.datactlDisableIWlan) dcSymbols.datactlDisableIWlan();
}
void DataModule::handleSetLinkCapFilterMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLinkCapFilterMessage> m = std::static_pointer_cast<SetLinkCapFilterMessage>(msg);
if( m != NULL ) {
auto rf = m->getParams();
int result = -1;
if (lceHandler.toggleReporting(rf)) {
result = 0;
}
auto resp = std::make_shared<int>(result);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
}
else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleSetLinkCapRptCriteriaMessage(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLinkCapRptCriteriaMessage> m = std::static_pointer_cast<SetLinkCapRptCriteriaMessage>(msg);
if( m != NULL ) {
auto rf = m->getParams();
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
LinkCapCriteriaResult_t result = lceHandler.setCriteria(rf);
if (result != rildata::LinkCapCriteriaResult_t::success) {
status = Message::Callback::Status::FAILURE;
}
auto resp = std::make_shared<rildata::LinkCapCriteriaResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
#endif
void DataModule::handleRilEventDataCallback(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
if (call_manager) {
call_manager->handleRilEventDataCallback(msg);
}
else {
Log::getInstance().d("call_manager is null");
}
}
void DataModule::handleDeregisterWdsIndCompletedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DeregisterWdsIndCompletedMessage> m = std::static_pointer_cast<DeregisterWdsIndCompletedMessage>(msg);
if( m!= NULL )
{
if(call_manager) {
call_manager->deleteWdsCallEndPoint(m->getCid(), m->getIpFamilyType());
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetInitialAttachApn
===========================================================================*/
/*!
@brief
Handler to handle SetInitialAttachApnRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetInitialAttachApn(std::shared_ptr<Message> msg)
{
RIL_Errno res = RIL_E_SUCCESS;
qcril_request_resp_params_type resp;
qcril_reqlist_public_type qcril_req_info;
IxErrnoType reqlist_status = E_SUCCESS;
std::shared_ptr<SetInitialAttachApnRequestMessage> m =
std::static_pointer_cast<SetInitialAttachApnRequestMessage>(msg);
memset(&resp,0,sizeof(qcril_request_resp_params_type));
memset(&qcril_req_info,0,sizeof(qcril_reqlist_public_type));
if (m!= nullptr)
{
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
const qcril_request_params_type *params_ptr = m->get_params();
if( params_ptr == NULL )
{
Log::getInstance().d("ERROR!!params_ptr is NULL . Returning error response to telephony");
return;
}
do
{
Log::getInstance().d("[DataModule]: Inserting"
" QCRIL_EVT_QMI_REQUEST_INIT_ATTACH_APN event in reqlist ");
qcril_reqlist_default_entry( params_ptr->t,
params_ptr->event_id,
params_ptr->modem_id,
QCRIL_REQ_AWAITING_MORE_AMSS_EVENTS,
QCRIL_EVT_QMI_REQUEST_INIT_ATTACH_APN,
NULL,
&qcril_req_info );
if (( reqlist_status = qcril_reqlist_new( params_ptr->instance_id,
&qcril_req_info )) != E_SUCCESS)
{
Log::getInstance().d("Reqlist entry failure..status: "+ std::to_string(reqlist_status));
res = map_internalerr_from_reqlist_new_to_ril_err(reqlist_status);
break;
}
ProfileHandler::RilRespParams resp_params{ params_ptr->instance_id,
params_ptr->modem_id,
params_ptr->event_id,
params_ptr->t
};
Log::getInstance().d("[DataModule]: Handling token = " + std::to_string((long long)params_ptr->t)) ;
if( profile_handler )
{
profile_handler->handleInitialAttachRequest(m->get_attach_params(), resp_params);
} else
{
Log::getInstance().d("[DataModule]: Profile Handler is NULL. Returning ERROR response") ;
qcril_default_request_resp_params( params_ptr->instance_id,
params_ptr->t,
params_ptr->event_id,
RIL_E_INTERNAL_ERR,
&resp );
qcril_send_request_response( &resp );
}
} while(0);
if (res != RIL_E_SUCCESS)
{
Log::getInstance().d("[DataModule]:handleSetInitialAttachApn:"
" Sending Error response");
qcril_default_request_resp_params( params_ptr->instance_id,
params_ptr->t,
params_ptr->event_id,
res,
&resp );
qcril_send_request_response( &resp );
}
} else
{
Log::getInstance().d("[" + mName + "]: Improper message received for handleSetInitialAttachApn");
}
}
/*===========================================================================
FUNCTION: handleSetLteAttachPdnListActionResult
===========================================================================*/
/*!
@brief
Handler to handle SetInitialAttachApnRequestMessage message request
@return
*/
/*=========================================================================*/
void DataModule::handleSetLteAttachPdnListActionResult(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetLteAttachPdnListActionResultMessage> m = std::static_pointer_cast<SetLteAttachPdnListActionResultMessage>(msg);
if( m != NULL && profile_handler != NULL ) {
Log::getInstance().d("[DataModule]::Invoking handleWdsUnSolInd" );
profile_handler->handleWdsUnSolInd(&(m->getParams()));
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleNasSrvDomainPrefInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when NasSrvDomainPrefIndMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleNasSrvDomainPrefInd(std::shared_ptr<Message> m)
{
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
std::shared_ptr<NasSrvDomainPrefIndMessage> msg = std::static_pointer_cast<NasSrvDomainPrefIndMessage>(m);
if (msg != NULL)
{
uint8_t domainPrefValid;
nas_srv_domain_pref_enum_type_v01 domainPref;
msg->getDomainPref(domainPrefValid,domainPref);
if(profile_handler)
{
Log::getInstance().d("[DataModule]::Invoking qcril_data_nas_detach_attach_ind_hdlr" );
profile_handler->qcril_data_nas_detach_attach_ind_hdlr(domainPrefValid, domainPref);
} else
{
Log::getInstance().d("[DataModule]::Invalid nas_helper object. Returning");
}
Log::getInstance().d("[DataModule]::handleNasSrvDomainPrefInd EXIT" );
}
}
/*===========================================================================
FUNCTION: handleNasRequestDataShutdown
===========================================================================*/
/*!
@brief
Handler which gets invoked when NasRequestDataShutdownMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleNasRequestDataShutdown(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<NasRequestDataShutdownMessage> m = std::static_pointer_cast<NasRequestDataShutdownMessage>(msg);
if (m != NULL)
{
NasRequestDataShutdownResponse ret = NasRequestDataShutdownResponse::FAILURE;
if(qcril_data_device_shutdown()) {
ret = NasRequestDataShutdownResponse::SUCCESS;
}
auto resp = std::make_shared<NasRequestDataShutdownResponse>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDataAllBearerTypeUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when DataBearerTypeChangedMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleDataAllBearerTypeUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DataAllBearerTypeChangedMessage> m = std::static_pointer_cast<DataAllBearerTypeChangedMessage>(msg);
if (m != NULL)
{
AllocatedBearer_t bearerInfo = m->getBearerInfo();
if (call_manager) {
call_manager->handleDataAllBearerTypeUpdate(bearerInfo);
}
else {
Log::getInstance().d("call_manager is null");
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDataBearerTypeUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when DataBearerTypeChangedMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleDataBearerTypeUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DataBearerTypeChangedMessage> m = std::static_pointer_cast<DataBearerTypeChangedMessage>(msg);
if (m != NULL)
{
int32_t cid = m->getCid();
BearerInfo_t bearer = m->getBearerInfo();
if (call_manager) {
call_manager->handleDataBearerTypeUpdate(cid, bearer);
}
else {
Log::getInstance().d("call_manager is null");
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleToggleBearerAllocationUpdate
===========================================================================*/
/*!
@brief
Handler which gets invoked when RegisterBearerAllocationUpdateRequestMessage is received
@return
*/
/*=========================================================================*/
void DataModule::handleToggleBearerAllocationUpdate(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<RegisterBearerAllocationUpdateRequestMessage> m =
std::static_pointer_cast<RegisterBearerAllocationUpdateRequestMessage>(msg);
if (m != NULL)
{
bool enable = m->getToggleSwitch();
ResponseError_t ret;
if (call_manager) {
ret = call_manager->handleToggleBearerAllocationUpdate(enable);
}
else {
Log::getInstance().d("call_manager is null");
ret = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<ResponseError_t>(ret);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleGetBearerAllocation
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetBearerAllocationRequestMessage is received
Invokes the callback with the allocated bearers that were retrieved
@return
*/
/*=========================================================================*/
void DataModule::handleGetBearerAllocation(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetBearerAllocationRequestMessage> m =
std::static_pointer_cast<GetBearerAllocationRequestMessage>(msg);
if (m != NULL)
{
int32_t cid = m->getCallId();
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
AllocatedBearerResult_t bearerAllocations;
if (call_manager) {
bearerAllocations = call_manager->handleGetBearerAllocation(cid);
}
else {
Log::getInstance().d("call_manager is null");
bearerAllocations.error = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<AllocatedBearerResult_t>(bearerAllocations);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*============================================================================
retrieveUIMAppStatusFromAppInfo
============================================================================*/
/*!
@brief
Retrieve aid buffer application info
@return
None
*/
/*=========================================================================*/
int DataModule::retrieveUIMAppStatusFromAppInfo(RIL_UIM_AppStatus *application, string &aid_buffer, RIL_UIM_AppType *app_type)
{
int res = E_FAILURE;
Log::getInstance().d("[Datamodule]: handling retrieveUIMAppStatusFromAppInfo");
if (application && app_type)
{
Log::getInstance().d("app type " + std::to_string(application->app_type));
Log::getInstance().d("app State " + std::to_string(application->app_state));
if ((application->app_state == RIL_UIM_APPSTATE_READY) &&
!application->aid_ptr.empty())
{
aid_buffer = application->aid_ptr;
Log::getInstance().d("aid buffer " + aid_buffer);
*app_type = application->app_type;
res = E_SUCCESS;
}
}
return res;
}
/*============================================================================
retrieveUIMCardStatus
============================================================================*/
/*!
@brief
Retrieve aid buffer card status info
@return
None
*/
/*=========================================================================*/
int DataModule::retrieveUIMCardStatus( std::shared_ptr<RIL_UIM_CardStatus> ril_card_status, string &aid_buffer, RIL_UIM_AppType *app_type)
{
int res = E_FAILURE;
int index;
Log::getInstance().d("[Datamodule]: handling retrieveUIMCardStatus");
if (ril_card_status)
{
if (ril_card_status->card_state == RIL_UIM_CARDSTATE_PRESENT)
{
Log::getInstance().d("card is present");
if (ril_card_status->gsm_umts_subscription_app_index != -1)
{
index = ril_card_status->gsm_umts_subscription_app_index;
/* retrieve aid from gsm umts subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
Log::getInstance().d("res " + std::to_string(res));
}
if ((res == E_FAILURE) &&
(ril_card_status->cdma_subscription_app_index != -1))
{
index = ril_card_status->cdma_subscription_app_index;
/* retrieve aid from cdma subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
}
if ((res == E_FAILURE) &&
(ril_card_status->ims_subscription_app_index != -1))
{
index = ril_card_status->ims_subscription_app_index;
/* retrieve aid from ims subscription app info */
res = retrieveUIMAppStatusFromAppInfo(
&ril_card_status->applications[index],
aid_buffer, app_type);
}
}
}
return res;
}
/*===========================================================================
qcrilDataUimEventAppStatusUpdate
============================================================================*/
/*!
@brief
Handles QCRIL_EVT_CM_CARD_APP_STATUS_CHANGED
@return
None
*/
/*=========================================================================*/
void DataModule::qcrilDataUimEventAppStatusUpdate ( const qcril_request_params_type *const params_ptr, qcril_request_return_type *const ret_ptr)
{
RIL_UIM_AppStatus *card_app_info;
string aid = {};
RIL_UIM_AppType request_app_type;
qcril_modem_id_e_type modem_id;
Log::getInstance().d("qcrilDataUimEventAppStatusUpdate:: ENTRY");
QCRIL_NOTUSED(ret_ptr);
if (!params_ptr)
{
Log::getInstance().d("PARAMS ptr is NULL");
return;
}
modem_id = params_ptr->modem_id;
card_app_info = (RIL_UIM_AppStatus *)(params_ptr->data);
/* Process only this slots SIM card applications */
if (card_app_info != NULL &&
card_app_info->app_state == RIL_UIM_APPSTATE_READY)
{
Log::getInstance().d("app type"+std::to_string(card_app_info->app_type)+
"app state"+std::to_string(card_app_info->app_state));
auto card_status = std::make_shared<UimGetCardStatusRequestSyncMsg>(qmi_ril_get_process_instance_id());
std::shared_ptr<RIL_UIM_CardStatus> ril_card_status = nullptr;
/* retrieve card status info */
if (card_status != nullptr && (card_status->dispatchSync(ril_card_status) != Message::Callback::Status::SUCCESS))
{
Log::getInstance().d("Get card status request failed");
return;
}
if(ril_card_status != nullptr && ril_card_status->err != RIL_UIM_E_SUCCESS)
{
Log::getInstance().d("ril card status failed");
return;
}
/* retrieve aid from card status */
if ((retrieveUIMCardStatus(ril_card_status, aid, &request_app_type))!= E_SUCCESS)
{
Log::getInstance().d("Retrieval of AID from card status failed");
return;
}
Log::getInstance().d("Received SIM aid_buffer="+aid);
qcril_uim_app_type app_type = QCRIL_UIM_APP_UNKNOWN;
//proceed only when memory is allocated
if(aid.empty())
{
Log::getInstance().d("AID Memory allocation failed");
return;
}
switch(request_app_type)
{
case RIL_UIM_APPTYPE_SIM:
app_type = QCRIL_UIM_APP_SIM;
break;
case RIL_UIM_APPTYPE_USIM:
app_type = QCRIL_UIM_APP_USIM;
break;
case RIL_UIM_APPTYPE_RUIM:
app_type = QCRIL_UIM_APP_RUIM;
break;
case RIL_UIM_APPTYPE_CSIM:
app_type = QCRIL_UIM_APP_CSIM;
break;
default:
app_type = QCRIL_UIM_APP_UNKNOWN;
break;
}
DataGetMccMncCallback Cb("set-cb-token");
std::shared_ptr<UimGetMccMncRequestMsg> req =
std::make_shared<UimGetMccMncRequestMsg>(aid, app_type, &Cb);
if(req)
{
Log::getInstance().d("Dispatching UimGetMccMncRequestMsg Message");
req->dispatch();
}
} else {
Log::getInstance().d("Card APP info is NULL or slot id mismatch or Card APP status isn't READY");
}
}
void DataModule::handleUimCardAppStatusIndMsg(std::shared_ptr<Message> m)
{
qcril_request_return_type ret_ptr;
qcril_request_params_type params_ptr;
Log::getInstance().d("[DataModule]: Handling msg = " + m->dump());
std::shared_ptr<UimCardAppStatusIndMsg> msg =
std::static_pointer_cast<UimCardAppStatusIndMsg>(m);
std::memset(¶ms_ptr, 0, sizeof(params_ptr));
std::memset(&ret_ptr, 0, sizeof(ret_ptr));
if( msg != NULL )
{
params_ptr.data = static_cast<void *>(new char[sizeof(RIL_UIM_AppStatus)]);
if(params_ptr.data)
{
std::memcpy(params_ptr.data, &msg->get_app_info(), sizeof(RIL_UIM_AppStatus));
params_ptr.datalen = sizeof(RIL_UIM_AppStatus);
params_ptr.modem_id = QCRIL_DEFAULT_MODEM_ID;
#ifndef QMI_RIL_UTF
qcrilDataUimEventAppStatusUpdate (¶ms_ptr, &ret_ptr);
#endif
} else
{
Log::getInstance().d("[DataModule]: Memory allocation failure");
}
} else
{
Log::getInstance().d("[" + mName + "]: Improper message received");
}
}
/*===========================================================================
FUNCTION: handleGetAllBearerAllocations
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetAllBearerAllocationsRequestMessage is received
Invokes the callback with the allocated bearers that were retrieved
@return
*/
/*=========================================================================*/
void DataModule::handleGetAllBearerAllocations(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetBearerAllocationRequestMessage> m =
std::static_pointer_cast<GetBearerAllocationRequestMessage>(msg);
if (m != NULL)
{
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
AllocatedBearerResult_t bearerAllocations;
if (call_manager) {
bearerAllocations = call_manager->handleGetAllBearerAllocations();
}
else {
Log::getInstance().d("call_manager is null");
bearerAllocations.error = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<AllocatedBearerResult_t>(bearerAllocations);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleQmiWdsEndpointStatusIndMessage
===========================================================================*/
/*!
@brief
Handler which gets invoked when QMI WDS modem endpoint status is changed
@return
*/
/*=========================================================================*/
void DataModule::handleQmiWdsEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getWdsServiceReady()) {
mInitTracker.setWdsServiceReady(true);
performDataModuleInitialization();
}
} else if (shared_indMsg->getState() == ModemEndPoint::State::NON_OPERATIONAL) {
if (call_manager) {
call_manager->cleanUpAllBearerAllocation();
} else {
Log::getInstance().d("call_manager is null");
}
//Reset all interested handlers
mInitTracker.setWdsServiceReady(false);
// release QDP attach profile
if(profile_handler) {
profile_handler->releaseQdpAttachProfile();
}
Log::getInstance().d("[" + mName + "]: WDSModemEndPoint is not operational");
}
}
#ifdef FEATURE_DATA_LQE
/*===========================================================================*/
/*!
@brief
Handler which gets invoked when QMI OTT modem endpoint status is changed
@return
*/
/*=========================================================================*/
void DataModule::handleQmiOttEndpointStatusIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
auto shared_indMsg(std::static_pointer_cast<EndpointStatusIndMessage>(msg));
if (shared_indMsg->getState() == ModemEndPoint::State::OPERATIONAL) {
if (!mInitTracker.getOttServiceReady()) {
mInitTracker.setOttServiceReady(true);
qcril_data_ott_lqe_init();
}
} else if (shared_indMsg->getState() == ModemEndPoint::State::NON_OPERATIONAL) {
mInitTracker.setOttServiceReady(false);
Log::getInstance().d("[" + mName + "]: OTTModemEndPoint is not operational");
}
}
#endif /* FEATURE_DATA_LQE */
/*===========================================================================
FUNCTION: handleDataConnectionStateChangedMessage
===========================================================================*/
/*!
@brief
Handler when data connection state is changed
@return
*/
/*=========================================================================*/
void DataModule::handleDataConnectionStateChangedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CallStatusMessage> m = std::static_pointer_cast<CallStatusMessage>(msg);
if (m != NULL) {
const CallStatusParams callParams = m->getCallParams();
if (callParams.evt == QCRIL_DATA_EVT_CALL_RELEASED) {
if (call_manager) {
call_manager->cleanUpBearerAllocation((int32_t)m->getCallId());
} else {
Log::getInstance().d("call_manager is null");
}
}
}
}
/*===========================================================================
FUNCTION: handleIWLANCapabilityHandshake
===========================================================================*/
/*!
@brief
Handler which gets invoked when IWLANCapabilityHandshake is received.
@return
*/
/*=========================================================================*/
void DataModule::handleIWLANCapabilityHandshake(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<IWLANCapabilityHandshake> m = std::static_pointer_cast<IWLANCapabilityHandshake>(msg);
if (m != NULL) {
Log::getInstance().d("[ getPendingMessageList test ]: insert message = " +
msg->get_message_name());
std::pair<uint16_t, bool> result = getDataModule().getPendingMessageList().insert(msg);
iwlanHandshakeMsgToken = (int32_t)result.first;
Log::getInstance().d("[ getPendingMessageList test ]: insert result token = " +
std::to_string((int)iwlanHandshakeMsgToken));
getDataModule().getPendingMessageList().print();
if (m->isIWLANEnabled()) {
mInitTracker.setIWLANEnabled(true);
if (mInitTracker.allServicesReady() && mInitTracker.isModeDetermined()) {
initializeIWLAN();
}
} else {
mInitTracker.setIWLANEnabled(false); //TODO: handled disabled
deinitializeIWLAN();
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleGetAllQualifiedNetworksMessage
===========================================================================*/
/*!
@brief
Handler which gets invoked when GetAllQualifiedNetworkRequestMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleGetAllQualifiedNetworksMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<GetAllQualifiedNetworkRequestMessage> m = std::static_pointer_cast<GetAllQualifiedNetworkRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
QualifiedNetworkResult_t result;
if (!mInitTracker.isAPAssistMode()) {
result.respErr = ResponseError_t::NOT_SUPPORTED;
} else if (!mInitTracker.isIWLANEnabled() || !mInitTracker.allServicesReady()) {
result.respErr = ResponseError_t::NOT_AVAILABLE;
} else {
if (networkavailability_handler) {
result.respErr = ResponseError_t::NO_ERROR;
networkavailability_handler->getQualifiedNetworks(result.qualifiedNetwork);
}
else {
Log::getInstance().d("networkavailability_handler is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
}
auto resp = std::make_shared<QualifiedNetworkResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleDsdSystemStatusInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when DsdSystemStatusMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleDsdSystemStatusInd(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DsdSystemStatusMessage> m = std::static_pointer_cast<DsdSystemStatusMessage>(msg);
if (m != NULL) {
mCachedSystemStatus = m->getParams();
if (network_service_handler) {
network_service_handler->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
if (networkavailability_handler) {
if (mCachedSystemStatus.apn_avail_sys_info_valid) {
networkavailability_handler->processQmiDsdSystemStatusInd(mCachedSystemStatus.apn_avail_sys_info,
mCachedSystemStatus.apn_avail_sys_info_len);
}
}
if (call_manager) {
call_manager->processQmiDsdSystemStatusInd(&mCachedSystemStatus);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDsdSystemStatusPerApn(std::shared_ptr<Message> msg)
{
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<DsdSystemStatusPerApnMessage> m = std::static_pointer_cast<DsdSystemStatusPerApnMessage>(msg);
if (m != NULL)
{
if ( networkavailability_handler ) {
auto apnAvailSys = m->getAvailSys();
networkavailability_handler->processQmiDsdSystemStatusInd(apnAvailSys.data(), apnAvailSys.size());
}
}
else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleIntentToChangeInd
===========================================================================*/
/*!
@brief
Handler which gets invoked when IntentToChangeApnPreferredSystemMessage is received.
@return
*/
/*=========================================================================*/
void DataModule::handleIntentToChangeInd(std::shared_ptr<Message> msg) {
Log::getInstance().d("[DataModule]: Handling msg = " + msg->dump());
std::shared_ptr<IntentToChangeApnPreferredSystemMessage> m =
std::static_pointer_cast<IntentToChangeApnPreferredSystemMessage>(msg);
if (m != NULL) {
dsd_intent_to_change_apn_pref_sys_ind_msg_v01 intent = m->getParams();
if (networkavailability_handler) {
networkavailability_handler->processQmiDsdIntentToChangeApnPrefSysInd(&intent);
}
if (call_manager) {
call_manager->processQmiDsdIntentToChangeApnPrefSysInd(&intent);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
/*===========================================================================
FUNCTION: handleSetPreferredDataModem
===========================================================================*/
/*!
@brief
Handler for AP triggered DDS switch
@return
*/
/*=========================================================================*/
void DataModule::handleSetPreferredDataModem(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetPreferredDataModemRequestMessage> m = std::static_pointer_cast<SetPreferredDataModemRequestMessage>(msg);
if (m != NULL) {
if (TempddsSwitchRequestPending) {
TimeKeeper::getInstance().clear_timer(tempDDSSwitchRequestTimer);
}
PreferredDataEventType setPreferredDataEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getModemId();
eventData.msg = m;
setPreferredDataEvent.event = SetPreferredDataModem;
setPreferredDataEvent.data = &eventData;
preferred_data_sm->processEvent(setPreferredDataEvent);
}
}
/*===========================================================================
FUNCTION: handleCurrentDDSIndMessage
===========================================================================*/
/*!
@brief
Handler for MP triggered DDS switch
@return
*/
/*=========================================================================*/
void DataModule::handleCurrentDDSIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CurrentDDSIndMessage> m = std::static_pointer_cast<CurrentDDSIndMessage>(msg);
if (m != NULL) {
DDSSubIdInfo ddsInfo;
ddsInfo.dds_sub_id = m->getSubId();
ddsInfo.switch_type = m->getSwitchType();
LOCK_MUTEX(ddsSubMutex)
currentDDSSUB.dds_sub_id = ddsInfo.dds_sub_id;
currentDDSSUB.switch_type = ddsInfo.switch_type;
UNLOCK_MUTEX(ddsSubMutex);
Log::getInstance().d("[" + mName + "]: Sending response to qcril common");
auto msg = std::make_shared<rildata::NewDDSInfoMessage>(global_instance_id, ddsInfo);
msg->broadcast();
Log::getInstance().d("[" + mName + "]:Current DDS is on SUB =" + std::to_string(currentDDSSUB.dds_sub_id) + "with switch type = " + std::to_string(currentDDSSUB.switch_type));
// only listen for current DDS indication on main ril
if (preferred_data_state_info != nullptr &&
preferred_data_state_info->isRilIpcNotifier) {
PreferredDataEventType currentDdsEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getSubId();
currentDdsEvent.event = CurrentDDSInd;
currentDdsEvent.data = &eventData;
preferred_data_sm->processEvent(currentDdsEvent);
}
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchResultIndMessage
===========================================================================*/
/*!
@brief
Handler when DDS switch started by modem
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchResultIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchResultIndMessage> m = std::static_pointer_cast<DDSSwitchResultIndMessage>(msg);
if (m != NULL) {
PreferredDataEventType ddsSwitchEvent;
DDSSwitchInfo_t eventData;
eventData.msg = m;
eventData.switchAllowed = DDSSwitchRes::FAIL;
if (m->getAllowed()) {
eventData.switchAllowed = DDSSwitchRes::ALLOWED;
}
if (m->getError() != TriggerDDSSwitchError::NO_ERROR) {
eventData.switchAllowed = DDSSwitchRes::ERROR;
}
ddsSwitchEvent.event = DDSSwitchInd;
ddsSwitchEvent.data = &eventData;
preferred_data_sm->processEvent(ddsSwitchEvent);
}
}
/*===========================================================================
FUNCTION: handleRadioConfigClientConnectedMessage
===========================================================================*/
/*!
@brief
Handler when client registers response functions with RadioConfig HAL
@return
*/
/*=========================================================================*/
void DataModule::handleRadioConfigClientConnectedMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
Log::getInstance().d("Client connected to ril instance " + std::to_string(global_instance_id));
// this flag indicates that the current ril instance will be broadcasting IPC messages
preferred_data_state_info->isRilIpcNotifier = true;
QmiSetupRequestCallback callback("voice-token");
if (voiceCallEndPointSub0 == nullptr) {
voiceCallEndPointSub0 = std::shared_ptr<VoiceCallModemEndPoint>(new VoiceCallModemEndPoint("VoiceSub0EndPoint", SubId::PRIMARY));
voiceCallEndPointSub0->requestSetup("voice-token-client-server", &callback);
}
if (voiceCallEndPointSub1 == nullptr) {
voiceCallEndPointSub1 = std::shared_ptr<VoiceCallModemEndPoint>(new VoiceCallModemEndPoint("VoiceSub1EndPoint", SubId::SECONDARY));
voiceCallEndPointSub1->requestSetup("voice-token-client-server", &callback);
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchTimeoutMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchTimeoutMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchTimeoutMessage> m = std::static_pointer_cast<DDSSwitchTimeoutMessage>(msg);
if (m != NULL) {
PreferredDataEventType timeoutEvent;
DDSSwitchInfo_t eventData;
eventData.msg = m;
switch (m->getType()) {
case DDSTimeOutSwitchType::DDSTimeOutSwitch:
timeoutEvent.event = DDSSwitchTimerExpired;
break;
case DDSTimeOutSwitchType::TempDDSTimeOutSwitch:
timeoutEvent.event = TempDDSSwitchTimerExpired;
break;
}
timeoutEvent.data = &eventData;
preferred_data_sm->processEvent(timeoutEvent);
}
}
/*===========================================================================
FUNCTION: handleDDSSwitchIPCMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
void DataModule::handleDDSSwitchIPCMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DDSSwitchIPCMessage> m = std::static_pointer_cast<DDSSwitchIPCMessage>(msg);
if (m != NULL) {
// do not listen for IPC messages on main ril
if (preferred_data_state_info != nullptr &&
!preferred_data_state_info->isRilIpcNotifier) {
PreferredDataEventType ipcEvent;
DDSSwitchInfo_t eventData;
eventData.subId = m->getSubId();
ipcEvent.data = &eventData;
switch (m->getState()) {
case DDSSwitchIPCMessageState::ApStarted:
ipcEvent.event = DDSSwitchApStarted;
preferred_data_sm->processEvent(ipcEvent);
break;
case DDSSwitchIPCMessageState::Completed:
ipcEvent.event = DDSSwitchCompleted;
preferred_data_sm->processEvent(ipcEvent);
break;
case DDSSwitchIPCMessageState::MpStarted:
ipcEvent.event = DDSSwitchMpStarted;
preferred_data_sm->processEvent(ipcEvent);
break;
default:
Log::getInstance().d("Invalid DDSSwitchIPCMessage state = " + std::to_string(static_cast<int>(m->getState())));
break;
}
} else {
Log::getInstance().d("Ignoring IPC message on self");
}
}
}
/*===========================================================================
FUNCTION: constructDDSSwitchIPCMessage
===========================================================================*/
/*!
@brief
@return
*/
/*=========================================================================*/
std::shared_ptr<IPCMessage> DataModule::constructDDSSwitchIPCMessage(IPCIStream& is) {
// The message will have its members initialized in deserialize
std::shared_ptr<DDSSwitchIPCMessage> ipcMessage = std::make_shared<DDSSwitchIPCMessage>(
DDSSwitchIPCMessageState::ApStarted, -1);
if (ipcMessage != nullptr) {
ipcMessage->deserialize(is);
} else {
Log::getInstance().d("[DataModule] Invalid DDSSwitchIPCMessage");
}
return ipcMessage;
}
/*===========================================================================
FUNCTION: map_internalerr_from_reqlist_new_to_ril_err
===========================================================================*/
/*!
@brief
Helper API to convert data of IxErrnoType type to RIL_Errno type
input: data of IxErrnoType type
@return
*/
/*=========================================================================*/
RIL_Errno DataModule::map_internalerr_from_reqlist_new_to_ril_err(IxErrnoType error) {
RIL_Errno ret;
switch (error) {
case E_SUCCESS:
ret = RIL_E_SUCCESS;
break;
case E_NOT_ALLOWED:
ret = RIL_E_INVALID_STATE; //needs to be changed after internal discussion
break;
case E_NO_MEMORY:
ret = RIL_E_NO_MEMORY;
break;
case E_NO_RESOURCES:
ret = RIL_E_NO_RESOURCES;
break;
case E_RADIO_NOT_AVAILABLE:
ret = RIL_E_RADIO_NOT_AVAILABLE;
break;
case E_INVALID_ARG:
ret = RIL_E_INVALID_ARGUMENTS;
break;
default:
ret = RIL_E_INTERNAL_ERR;
break;
}
return ret;
}
void DataModule::handleSetupDataCallRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetupDataCallRequestMessage> m = std::static_pointer_cast<SetupDataCallRequestMessage>(msg);
if (m != NULL) {
logBuffer.addLogWithTimestamp("[" + mName + "]: " + std::to_string(m->getSerial()) + "> setupDataCallRequest");
if (call_manager) {
call_manager->handleSetupDataCallRequestMessage(msg);
} else {
Log::getInstance().d("call_manager is null");
SetupDataCallResponse_t result;
result.respErr = ResponseError_t::INTERNAL_ERROR;
result.call.cause = DataCallFailCause_t::ERROR_UNSPECIFIED;
result.call.suggestedRetryTime = -1;
auto resp = std::make_shared<SetupDataCallResponse_t>(result);
m->sendResponse(m, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleDeactivateDataCallRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DeactivateDataCallRequestMessage> m = std::static_pointer_cast<DeactivateDataCallRequestMessage>(msg);
if (m != NULL) {
logBuffer.addLogWithTimestamp("[" + mName + "]: " + std::to_string(m->getSerial()) + "> deactivateDataCallRequest");
if (call_manager) {
call_manager->handleDeactivateDataCallRequestMessage(msg);
} else {
Log::getInstance().d("call_manager is null");
ResponseError_t result = ResponseError_t::INTERNAL_ERROR;
auto resp = std::make_shared<ResponseError_t>(result);
m->sendResponse(msg, Message::Callback::Status::SUCCESS, resp);
}
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetRadioDataCallListRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetRadioDataCallListRequestMessage> m = std::static_pointer_cast<GetRadioDataCallListRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
DataCallListResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
if (call_manager) {
call_manager->getRadioDataCallList(result.call);
} else {
Log::getInstance().d("call_manager is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<DataCallListResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetIWlanDataCallListRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetIWlanDataCallListRequestMessage> m = std::static_pointer_cast<GetIWlanDataCallListRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
DataCallListResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
if (call_manager) {
call_manager->getIWlanDataCallList(result.call);
} else {
Log::getInstance().d("call_manager is null");
result.respErr = ResponseError_t::INTERNAL_ERROR;
}
auto resp = std::make_shared<DataCallListResult_t>(result);
m->sendResponse(msg, status, resp);
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleGetIWlanDataRegistrationStateRequestMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<GetIWlanDataRegistrationStateRequestMessage> m = std::static_pointer_cast<GetIWlanDataRegistrationStateRequestMessage>(msg);
if (m != NULL) {
Message::Callback::Status status = Message::Callback::Status::SUCCESS;
IWlanDataRegistrationStateResult_t result;
result.respErr = ResponseError_t::NO_ERROR;
result.regState = DataRegState_t::NOT_REG_AND_NOT_SEARCHING;
result.reasonForDenial = 0;
if (network_service_handler && mInitTracker.isAPAssistMode()) {
result.regState = static_cast<ApAssistNetworkServiceHandler *>(network_service_handler.get())->getIWlanDataRegistrationState();
}
auto resp = std::make_shared<IWlanDataRegistrationStateResult_t>(result);
m->sendResponse(msg, status, resp);
}
}
void DataModule::handleSetApnPreferredSystemResult(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetApnPreferredSystemResultMessage> m = std::static_pointer_cast<SetApnPreferredSystemResultMessage>(msg);
if (m != NULL && call_manager != NULL) {
Log::getInstance().d("[DataModule]::Invoking processQmiDsdApnPreferredSystemResultInd");
call_manager->processQmiDsdApnPreferredSystemResultInd(&(m->getParams()));
} else {
Log::getInstance().d("[" + mName + "]: Improper message received = " + msg->dump());
}
}
void DataModule::handleHandoverInformationIndMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<HandoverInformationIndMessage> m = std::static_pointer_cast<HandoverInformationIndMessage>(msg);
if (m != NULL && call_manager != NULL) {
call_manager->handleHandoverInformationIndMessage(m);
}
}
void DataModule::handleCallBringupFallbackMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<CallBringupFallbackMessage> m = std::static_pointer_cast<CallBringupFallbackMessage>(msg);
if (m != NULL && call_manager != NULL) {
call_manager->handleCallBringupFallbackMessage(m);
}
}
void DataModule::handleDataCallTimerExpiredMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<DataCallTimerExpiredMessage> m = std::static_pointer_cast<DataCallTimerExpiredMessage>(msg);
if (m != NULL && call_manager != NULL) {
switch (m->getType()) {
case DataCallTimerType::Handover:
call_manager->handleHandoverTimeout(m->getCid());
break;
case DataCallTimerType::SetupDataCall:
call_manager->handleSetupDataCallTimeout(m->getCid());
break;
case DataCallTimerType::PartialRetry:
call_manager->handlePartialRetryTimeout(m->getCid());
break;
case DataCallTimerType::PartialRetryResponse:
call_manager->handlePartialRetryResponseTimeout(m->getCid());
break;
case DataCallTimerType::DeactivateDataCall:
call_manager->handleDeactivateDataCallTimeout(m->getCid());
break;
default:
break;
}
}
}
void DataModule::handleNasPhysChanConfigReportingStatusMessage(std::shared_ptr<Message> msg) {
std::shared_ptr<NasPhysChanConfigReportingStatus> m = std::static_pointer_cast<NasPhysChanConfigReportingStatus>(msg);
if (m != nullptr && call_manager != nullptr) {
call_manager->enablePhysChanConfigReporting(m->isPhysChanConfigReportingEnabled());
} else {
Log::getInstance().d("No call_manager created");
}
}
void DataModule::handleNasPhysChanConfigMessage(std::shared_ptr<Message> msg) {
if (call_manager != nullptr) {
call_manager->handleNasPhysChanConfigMessage(msg);
} else {
Log::getInstance().d("No call_manager created");
}
}
void DataModule::handleCallManagerEventMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
if (call_manager) {
call_manager->handleCallManagerEventMessage(msg);
}
else {
Log::getInstance().d("call_manager is null");
}
}
void DataModule::handleSetCarrierInfoImsiEncryptionMessage(std::shared_ptr<Message> msg) {
Log::getInstance().d("[" + mName + "]: Handling msg = " + msg->dump());
std::shared_ptr<SetCarrierInfoImsiEncryptionMessage> m = std::static_pointer_cast<SetCarrierInfoImsiEncryptionMessage>(msg);
if (auth_manager) {
auth_manager->setCarrierInfoImsiEncryption(m->getImsiEncryptionInfo());
}
else {
Log::getInstance().d("auth_manager is null");
}
}
/*===========================================================================
FUNCTION: setTimeoutForMsg
===========================================================================*/
/*!
@brief
API to set the timeout for message
@return
TimeKeeper::timer_id value
*/
/*=========================================================================*/
TimeKeeper::timer_id DataModule::setTimeoutForMsg
(
std::shared_ptr<Message> msg, TimeKeeper::millisec maxTimeout
) {
if (msg == NULL) {
Log::getInstance().d("[" + mName + "]: ERROR!!! Msg received is NULL");
return 0; /*'0' is the init value of timer_id parameter */
}
Log::getInstance().d("[DataModule: set timeout for " + msg->dump());
TimeKeeper::timer_id tid = TimeKeeper::getInstance().set_timer(
[this, msg](void *user_data){
QCRIL_NOTUSED(user_data);
if (!(msg->isCallbackExecuting() || msg->isCallbackExecuted()))
{
Log::getInstance().d("[DataModule:: Timer expired for " +
msg->dump());
msg->cancelling();
Log::getInstance().d("[DataModule]: calling dispatcher inform fun");
Dispatcher::getInstance().informMessageDispatchFailure(
msg, Message::Callback::Status::TIMEOUT);
Log::getInstance().d("Finished");
msg->cancelled();
deleteEntryInReqlist(msg);
}
},
nullptr,
maxTimeout);
Log::getInstance().d("[" + msg->to_string() + "]: timer_id = " + std::to_string(tid));
msg->setTimerId(tid);
return tid;
}
/*===========================================================================
FUNCTION: deleteEntryInReqlist
===========================================================================*/
/*!
@brief
API to delete request from reqlist
===========================================================================*/
/*!
@brief
API to delete request from reqlist
@return
None
*/
/*=========================================================================*/
void DataModule::deleteEntryInReqlist
(
std::shared_ptr<Message> msg
)
{
/* Remove entry from reqlist */
std::shared_ptr<RilRequestDeactivateDataCallMessage> m = std::static_pointer_cast<RilRequestDeactivateDataCallMessage>(msg);
if( m != NULL ) {
qcril_request_params_type req = m->get_params();
IxErrnoType reqlistErrno = qcril_data_reqlist_free(&req);
if( reqlistErrno == E_SUCCESS)
{
Log::getInstance().d("qcril_data_deactivate_timeout_handle::Reqlist Free SUCCESS");
}
else
{
Log::getInstance().d("qcril_data_deactivate_timeout_handler::Reqlist Free failed!!! with Error code "+ std::to_string(reqlistErrno));
}
} else {
Log::getInstance().d("[" + mName + "]: Message received is not DeactivateDataCall message!!!");
}
}
/*===========================================================================
FUNCTION: clearTimeoutForMsg
===========================================================================*/
/*!
@brief
API to clear the existing timeout for message
@return
TimeKeeper::timer_id value
*/
/*=========================================================================*/
bool clearTimeoutForMessage
(
std::shared_ptr<Message> msg
)
{
return TimeKeeper::getInstance().clear_timer(msg->getTimerId());
}
/*============================================================================
qcrilDataprocessMccMncInfo
============================================================================*/
/*!
@brief
Process mcc mnc info
@return
None
*/
/*=========================================================================*/
void qcrilDataprocessMccMncInfo
(
const qcril_request_params_type *const params_ptr,
qcril_request_return_type *const ret_ptr
)
{
qcril_uim_mcc_mnc_info_type *uim_mcc_mnc_info = NULL;
Log::getInstance().d("qcrilDataprocessMccMncInfo: ENTRY");
if ((params_ptr == NULL) || (ret_ptr == NULL))
{
Log::getInstance().d("ERROR!! Invalid input, cannot process request");
return;
}
uim_mcc_mnc_info = (qcril_uim_mcc_mnc_info_type*)params_ptr->data;
if (uim_mcc_mnc_info == NULL)
{
Log::getInstance().d("NULL uim_mcc_mnc_info");
return;
}
if (uim_mcc_mnc_info->err_code != RIL_UIM_E_SUCCESS)
{
Log::getInstance().d("uim_get_mcc_mnc_info error:"+ std::to_string(uim_mcc_mnc_info->err_code));
return;
}
//According to the declaration of size in 'UimGetMccMncRequestMsg.h'
//each of mcc & mnc is 4 bytes, adding the error check based on this size
if ( (uim_mcc_mnc_info->mcc[MCC_LENGTH - 1] != '\0')
|| (uim_mcc_mnc_info->mnc[MNC_LENGTH - 1] != '\0') )
{
Log::getInstance().d("ERROR!! Improper input received. Either of MCC or MNC is not NULL terminated");
return;
}
std::string str = uim_mcc_mnc_info->mcc;
std::string str1 = uim_mcc_mnc_info->mnc;
Log::getInstance().d("mcc:"+ str+"mnc="+ str1);
qdp_compare_and_update(uim_mcc_mnc_info->mcc,
uim_mcc_mnc_info->mnc);
}
#ifdef QMI_RIL_UTF
void qcril_qmi_hal_data_module_cleanup() {
getDataModule().cleanup();
}
void DataModule::cleanup()
{
std::shared_ptr<DSDModemEndPoint> mDsdModemEndPoint =
ModemEndPointFactory<DSDModemEndPoint>::getInstance().buildEndPoint();
DSDModemEndPointModule* mDsdModemEndPointModule =
(DSDModemEndPointModule*)mDsdModemEndPoint->mModule;
mDsdModemEndPointModule->cleanUpQmiSvcClient();
std::shared_ptr<AuthModemEndPoint> mAuthModemEndPoint =
ModemEndPointFactory<AuthModemEndPoint>::getInstance().buildEndPoint();
AuthModemEndPointModule* mAuthModemEndPointModule =
(AuthModemEndPointModule*)mAuthModemEndPoint->mModule;
mAuthModemEndPointModule->cleanUpQmiSvcClient();
std::shared_ptr<WDSModemEndPoint> mWDSModemEndPoint =
ModemEndPointFactory<WDSModemEndPoint>::getInstance().buildEndPoint();
WDSModemEndPointModule* mWDSModemEndPointModule =
(WDSModemEndPointModule*)mWDSModemEndPoint->mModule;
mWDSModemEndPointModule->cleanUpQmiSvcClient();
mInitTracker = InitTracker();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
preferred_data_sm = std::make_unique<PreferredDataStateMachine>();
preferred_data_state_info = std::make_shared<PreferredDataInfo_t>();
preferred_data_state_info->isRilIpcNotifier = false;
preferred_data_state_info->mVoiceCallInfo.voiceSubId = INVALID_VOICE_SUB_ID;
preferred_data_sm->initialize(preferred_data_state_info);
preferred_data_sm->setCurrentState(Initial);
voiceCallEndPointSub0 = nullptr;
voiceCallEndPointSub1 = nullptr;
currentDDSSUB = { QCRIL_INVALID_MODEM_STACK_ID, DSD_DDS_DURATION_PERMANANT_V01 };
auth_manager = nullptr;
profile_handler = nullptr;
call_manager = nullptr;
network_service_handler = nullptr;
keep_alive = std::make_shared<KeepAliveHandler>();
iwlanHandshakeMsgToken = INVALID_MSG_TOKEN;
getPendingMessageList().clear();
mInitTracker.setIWLANMode(rildata::IWLANOperationMode::AP_ASSISTED);
qcril_data_qmi_wds_release();
// dump(0);
}
#endif
}//namespace
|
[
"priyabratofficial1717@gmail.com"
] |
priyabratofficial1717@gmail.com
|
a9571997e8c013f6b1ec297d920d70daa5032d4f
|
48793c310d1f9027d6aa2aacedad1e1bdc50a0de
|
/album.h
|
4cc3a87255f8bf30f98f51bb2634614348a32510
|
[] |
no_license
|
williamdewitt95/B-Tree
|
b555b3ea642403997c673547c74d65b6d14928e8
|
b9bdbf0443ee38d1eb42e16b864715f76d21057b
|
refs/heads/master
| 2021-01-19T19:54:13.565774
| 2017-04-22T22:45:59
| 2017-04-22T22:45:59
| 88,459,390
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 640
|
h
|
#ifndef ALBUM
#define ALBUM
#include "btree.hpp"
using namespace std;
const int UpTo = 50;
typedef char String[UpTo];
class Album
{
public :
Album (const Album& otherAlbum);
Album (String upc, String artist,
String title);
Album(String Key);
Album ();
Album & operator = (const Album& otherAlbum);
bool operator < (const Album& b);
friend istream & operator >> (istream & stream, Album&C);
friend ostream & operator << (ostream & stream, Album&C);
string getStringKey ();
int recordSize();
private :
String Key, Artist, Title;
};
#endif
|
[
"william.dewitt@live.mercer.edu"
] |
william.dewitt@live.mercer.edu
|
79067a0b5a5acbb85819e35b34126006c6394e84
|
2922cdf91069fba6d8620bbc804d432dd665e59d
|
/src/MsvcAppender.cpp
|
103110931e7a5527ab6788a756238e225da39c5a
|
[
"MIT"
] |
permissive
|
michaelstein/ProtoInfo
|
b1c3707d1fba0caa7d81f227c536e839a9bed1a6
|
32fbf4a44241ca80f5ad2281754ef8398dd33a14
|
refs/heads/master
| 2022-06-11T16:24:50.083874
| 2022-05-29T15:57:29
| 2022-05-29T15:57:29
| 174,380,796
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 464
|
cpp
|
#include "MsvcAppender.h"
#include "humblelogging/formatter.h"
#ifdef _WIN32
#include "Windows.h"
#endif
using namespace humble::logging;
MsvcAppender::MsvcAppender()
: Appender()
{
}
MsvcAppender::~MsvcAppender() = default;
void MsvcAppender::log(const humble::logging::LogEvent& logEvent)
{
#ifdef _WIN32
MutexLockGuard lock(_mutex);
if (!_formatter)
return;
const auto msg = _formatter->format(logEvent);
OutputDebugStringA(msg.c_str());
#endif
}
|
[
"m.stein@h3-ms.com"
] |
m.stein@h3-ms.com
|
1628e7dc364729c2566d8ce363d2cdef4c28cad6
|
8eeef5237d7b5e2a6322bdbea667a4cdaaa7ee0d
|
/Engine/Code/Engine/Math/Plane2.hpp
|
ec1943bb6eea32e1a1032b137d1ab9a6aacfb7c0
|
[
"MIT"
] |
permissive
|
sam830917/TenNenDemon
|
28a07f066b0d627026bd96859e2e71a3547938e2
|
a5f60007b73cccc6af8675c7f3dec597008dfdb4
|
refs/heads/main
| 2023-03-19T00:34:48.742275
| 2021-03-12T01:36:54
| 2021-03-12T01:36:54
| 282,079,878
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 411
|
hpp
|
#pragma once
#include "Engine/Math/Vec2.hpp"
#include "Engine/Math/MathUtils.hpp"
class Plane2
{
Vec2 normal;
float distance;
public:
// methods
Plane2()
: normal( 0, 1 )
, distance( 0 ) {}
Plane2( Vec2 n, Vec2 pointOnPlane )
: normal( n )
, distance( DotProduct2D( pointOnPlane, n ) ) {}
bool GetPointIsInFront( Vec2 point ) const;
float GetSignedDistanceFromPlane( Vec2 point ) const;
};
|
[
"sam830917@gmail.com"
] |
sam830917@gmail.com
|
b18a5e6efedaae9e597ab42b3a7656370db26e40
|
030730ffbeeaae0082b8b04c878d737b2a3a8713
|
/C++/Maze/MazePerson.cpp
|
c4198c1ab421ca24f294b7230818ec46860d2f89
|
[] |
no_license
|
whjkm/project
|
fcdc3a738e8006e9dfa54a751895dc6575bf19e2
|
29cdf1f572584f13c812935de2c4c78e9868b2f6
|
refs/heads/master
| 2021-01-18T15:21:39.349185
| 2018-08-14T01:58:37
| 2018-08-14T01:58:37
| 21,820,281
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 107
|
cpp
|
#include "MazePerson.h"
MazePerson::MazePerson()
{
//ctor
}
MazePerson::~MazePerson()
{
//dtor
}
|
[
"452422845@qq.com"
] |
452422845@qq.com
|
d1deeac06d0cfc7d6bfefdeb281f8d29596995f7
|
8d5f28c1d46e284bb2badb923d32ccfa7696b4e2
|
/darkstar/Ted/Code/simTed.cpp
|
9144d6d995fd1e8afea76fcd4bd60a5e2144cb39
|
[] |
no_license
|
jasonmit/TribesRebirth
|
0ba87778deeb86047842bcc559f232ab7ceb07fb
|
1105fd0890c19c13f816b91e51b9cf0658ffc63c
|
refs/heads/master
| 2023-03-17T01:41:03.663946
| 2015-07-20T21:12:37
| 2015-07-20T21:12:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 111,553
|
cpp
|
#include <limits.h>
#include "simAction.h"
#include "simTed.h"
#include "grdCollision.h"
#include "simSetIterator.h"
#include "simguitsctrl.h"
#include "simmoveobj.h"
#include "console.h"
#include "simGame.h"
#include "simconsoleevent.h"
static SimTerrain::Visibility DefTerrainVisibility =
{
1500.0f, // visible distance
600.0f, // haze distance
};
static SimTerrain::Detail DefTerrainDetail =
{
200.0f, // perspective distance
0.02f, // Pixel Size
};
static const char * stripPath( const char* fname )
{
// Return the file name portion without the path
const char* ptr = fname + strlen(fname) - 1;
for (; ptr != fname; ptr--)
if (*ptr == '\\' || *ptr == '/' || *ptr == ':')
return ptr + 1;
return fname;
}
SimTed::SimTed() :
scaleShift( 0 ),
blockShift( 0 ),
mouseHandler( NULL ),
mouseStartPt( 0.0, 0.0, 0.0 ),
mouseDirection( 0.0, 0.0, 0.0 ),
terrain( NULL ),
landscaper( NULL ),
focused( false ),
surface( NULL ),
pointArray( NULL ),
currentUndo( NULL ),
size( -1, -1 ),
regionSelect( false ),
selectStartPnt( -1, -1 ),
selectCanceled( false ),
selectLastPnt( -1, -1 ),
mouseLButtonAction( -1 ),
mouseRButtonAction( -1 ),
mouseProcessAction(-1),
feather( true ),
snap( true ),
brushPos( 0, 0 ),
brushDetail( 0 ),
hilightFillColor( 8 ),
hilightFrameColor( 2 ),
selectFillColor( 4 ),
selectFrameColor( 3 ),
shadowFillColor( 12 ),
shadowFrameColor( 6 ),
heightVal( 200.0 ),
adjustVal( 5.0 ),
materialIndex( 0 ),
flagVal( set ),
pasteVal( Material | Height ),
smoothVal( 0.5 ),
terrainType( 0 ),
drawNotch( true ),
scaleVal( 1.0 ),
grabMode( false ),
grabPoint( 0, 0 ),
grabDist( 0.0 ),
grabHeight( 0.0 ),
drawNeighbors(false),
blockOutline( false ),
blockFrameColor( 14 ),
pinDetail( 0 ),
selFloating( false ),
avgHeight( 0.0 ),
mouseMoved( false ),
cursorPos( 0, 0 ),
lastCursorPos( 0, 0 ),
cursorDif( 0, 0 ),
hilightShow( Frame | Fill ),
selectShow( Frame | Fill ),
shadowShow( Frame | Fill )
{
}
SimTed::~SimTed()
{
// delete the objects that this has control of
if( currentUndo )
delete currentUndo;
// delete the version string
}
void SimTed::flushTextures()
{
if( surface )
surface->flushTextureCache();
}
void SimTed::setVars()
{
scaleShift = getGridFile()->getScale();
blockShift = getGridFile()->getDetailCount()-1;
size = getGridFile()->getSize();
}
int SimTed::getActionIndex( String name )
{
for( int i = 0; i < actions.size(); i++ )
if( name == actions[i]->name )
return( i );
return( -1 );
}
void SimTed::setLButtonAction( String name )
{
mouseLButtonAction = getActionIndex( name );
}
void SimTed::setRButtonAction( String name )
{
mouseRButtonAction = getActionIndex( name );
}
void SimTed::init()
{
// add the actions
// there is the potential that an end event will never occur... design
// the mouse actions to be independant of end events
addAction( "adjustControlPoint", &SimTed::adjustControlPointAction, true, "Adjust the control point for this brush" );
addAction( "adjustCorner", &SimTed::adjustCornerAction, false, "Adjust the corner of a brush" );
addAction( "adjustHeight", &SimTed::adjustHeightAction, true, "Adjust the height of terrain" );
addAction( "clearFlags", &SimTed::clearFlagsAction, true, "Clear masked flags" );
addAction( "clearPin", &SimTed::clearPinAction, true, "Clear terrain pinning" );
addAction( "copy", &SimTed::copyAction, false, "Copy terrain info" );
addAction( "deselect", &SimTed::deselectAction, true, "Deselect terrain" );
addAction( "depress", &SimTed::depressAction, true, "Depress height" );
addAction( "elevate", &SimTed::elevateAction, true, "Elevate height" );
addAction( "getAvgHeight", &SimTed::getAvgHeightAction, false, "" );
addAction( "lowerHeight", &SimTed::lowerHeightAction, true, "Lower height" );
addAction( "noise", &SimTed::noiseAction, false, "Add noise to terrain" );
addAction( "paste", &SimTed::pasteAction, false, "Paste using paste mask" );
addAction( "pin", &SimTed::pinAction, true, "Pin down the terrain" );
addAction( "raiseHeight", &SimTed::raiseHeightAction, true, "Raise height" );
addAction( "redo", &SimTed::redoAction, true, "Redo last undo operation" );
addAction( "relight", &SimTed::relightAction, true, "Relight the terrain" );
addAction( "rotateLeft", &SimTed::rotateLeftAction, true, "Rotate terrain textures" );
addAction( "rotateRight", &SimTed::rotateRightAction, true, "Rotate terrain textures" );
addAction( "scale", &SimTed::scaleAction, true, "Scale height values" );
addAction( "select", &SimTed::selectAction, true, "Select terrain" );
addAction( "setControlHeight", &SimTed::setControlHeightAction, true, "Set control point height" );
addAction( "setCornerHeight", &SimTed::setCornerHeightAction, true, "Set the height of a corner" );
addAction( "setFlags", &SimTed::setFlagsAction, true, "Set masked flags" );
addAction( "setHeight", &SimTed::setHeightAction, true, "Set terrain height" );
addAction( "setMaterial", &SimTed::setMaterialAction, true, "Set terrain material index" );
addAction( "setTerrainType", &SimTed::setTerrainTypeAction, true, "Set terrain type using terrainValue" );
addAction( "smooth", &SimTed::smoothAction, true, "Smooth terrain" );
addAction( "undo", &SimTed::undoAction, true, "Undo last operation" );
// set the l/r mouse button actions
setLButtonAction( "select" );
setRButtonAction( "deselect" );
// need to get rid of the simted object on server deletion
SimObject * notifyObj = static_cast<SimObject*>(SimGame::get()->getManager(SimGame::SERVER)->findObject("ConsoleScheduler"));
if(notifyObj)
deleteNotify(notifyObj);
}
void SimTed::onDeleteNotify(SimObject * obj)
{
// just check if it's a SimConsoleScheduler object (already removed from the manager)
if(dynamic_cast<SimConsoleScheduler*>(obj))
deleteObject();
}
bool SimTed::getActionInfo( int index, TedAction & info )
{
if( index >= getNumActions() )
return( false );
// copy it
info = *actions[index];
return( true );
}
// set the corner height to the current height val
void SimTed::setCornerHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
// adjust this corner - darn.. the naming is all backwards!!!
// adjustControlPoint( pos, height, undo, top, left, true );
setBrushCornerHeight( brushPos, undo, heightVal, true );
break;
}
}
void SimTed::adjustCornerAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
{
// enter into grab mode
grabMode = true;
drawNeighbors = true;
grabPoint = brushPos;
grabHeight = getHeight( grabPoint );
// save off the info into the undo buffer
setBrushCornerHeight( grabPoint, undo, grabHeight, true );
break;
}
case update:
{
// save off the info into the undo buffer
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
grabHeight -= ( ( float )cursorDif.y ) * mouseAdj;
setBrushCornerHeight( grabPoint, undo, grabHeight, false );
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
void SimTed::setControlHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
switch( action )
{
case begin:
// set it
setBrushCornerHeight( brushPos, undo, heightVal, true );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
void SimTed::adjustHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
static Selection initialSel;
if(!sel.points.getSize())
return;
unsigned int i;
switch(action)
{
// add to undo on begin
case begin:
initialSel.points.clear();
// enter into grab mode
grabMode = true;
drawNeighbors = false;
grabPoint = brushPos;
grabHeight = getHeight(grabPoint);
// copy the current selection into undo and initial
for(i = 0; i < sel.points.getSize(); i++)
{
Selection::Info info;
if(getInfo(sel.points[i].pos, info))
{
initialSel.addPoint(info);
undo.addPoint(info);
}
}
break;
case update:
{
if(cursorDif.y == 0)
break;
// get the adjust value
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
float adjVal = ((float)-cursorDif.y) * mouseAdj;
for(i = 0; i < initialSel.points.getSize(); i++)
{
float height = getHeight(initialSel.points[i].pos) + adjVal;
setHeight(initialSel.points[i].pos, height);
}
// do the feathering
if(feather)
featherAction(action, initialSel, undo, true, adjVal);
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
// control adjustment mode
void SimTed::adjustControlPointAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
if( !sel.points.getSize() )
return;
if( !getSnap() )
return;
int brushDim = ( 1 << brushDetail );
switch( action )
{
case begin:
{
grabPoint = brushPos;
grabHeight = getHeight( grabPoint );
grabMode = true;
drawNeighbors = true;
// save all the heights...
for( int y = 0; y < brushDim; y++ )
for( int x = 0; x < brushDim; x++ )
for( int i = -1; i <=0; i++ )
for( int j = -1; j <=0; j++ )
{
Selection::Info info;
Point2I pos( brushPos );
pos.x += brushDim * i;
pos.y += brushDim * j;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
break;
}
case update:
{
if( cursorDif.y == 0 )
break;
float mouseAdj = CMDConsole::getLocked()->getFloatVariable("$TED::mouseAdjustValue", 0.25);
float diff = ((float)-cursorDif.y) * mouseAdj;
// do the zero'th lvl
Selection::Info info;
if( getInfo( grabPoint, info ) )
{
info.height.height += diff;
setInfo( info );
}
for( int i = 1; i < brushDim; i++ )
{
// get the amount to adjust at each level
float adjAmt = float( float(brushDim) - float(i) ) / float(brushDim) * diff;
// just grab the outside points
for( int x = -i; x <= i; x++ )
for( int a = 0; a < 2; a++ )
if( getInfo( Point2I( grabPoint.x + x, grabPoint.y + ( a ? -i : i ) ), info ) )
{
info.height.height += adjAmt;
setInfo( info );
}
// do the sides - skip the corners...
for( int y = (-i + 1); y <= (i - 1); y++ )
for( int a = 0; a < 2; a++ )
if( getInfo( Point2I( grabPoint.x + ( a ? -i : i ), grabPoint.y + y ), info ) )
{
info.height.height += adjAmt;
setInfo( info );
}
}
break;
}
case end:
grabMode = false;
getGridFile()->updateHeightRange();
break;
}
}
// scale the terrain by a value
void SimTed::scaleAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// go through the heights and scale them
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to undo
undo.addPoint( info );
// scale the value
info.height.height *= scaleVal;
// set the value
setInfo( info );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// pin down the terrain to the current detail
void SimTed::pinAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case end:
// go though all of the selection
undo.pinArray.clear();
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
Point2I pos = sel.points[i].pos;
// get the info
if( getInfo( pos, info ) )
{
// add to the undo
undo.addPoint( info );
undo.undoFlags = Selection::pin;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock * block = getGridFile()->getBlock( bpos ) )
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
// pin it - position is in current detail coords
spos.x >>= pinDetail;
spos.y >>= pinDetail;
// fill in the callback info
GridBlock::pinCallbackInfo callback;
callback.obj = this;
callback.func = SimTed::pinSquareCallback;
callback.gridBlock = block;
block->pinSquare( pinDetail, spos, pinDetailMax, true, &callback );
}
}
}
}
break;
}
}
// used to collect info for an undo/redo operation
void SimTed::pinSquareCallback( GridBlock::pinCallbackInfo * info )
{
SimTed * ted = ( SimTed * )info->obj;
Selection * undo = ted->getCurrentUndo();
Selection::pinInfo pin;
// need to check if this one already exists
for( int i = 0; i < undo->pinArray.size(); i++ )
{
// check if the same
pin = undo->pinArray[i];
if( ( pin.detail == info->detail ) && ( pin.pos == info->pos ) && ( pin.gridBlock == info->gridBlock ) )
return;
}
// add a pin info
pin.detail = info->detail;
pin.pos = info->pos;
pin.val = info->val;
pin.gridBlock = info->gridBlock;
undo->pinArray.push_back( pin );
}
// clear the entire map in the current block
void SimTed::clearPinMaps()
{
GridBlockList * blockList = getGridFile()->getBlockList();
for( int i = 0; i < blockList->size(); i++ )
{
GridBlock * block = ( * blockList )[i]->block;
if( block )
block->clearPinMaps();
}
}
// clear the pin from the current brush - goes from pinDetail on up to pinDetailMax
void SimTed::clearPinAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case end:
// go though all of the selection
undo.pinArray.clear();
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
Point2I pos = sel.points[i].pos;
// get the info
if( getInfo( pos, info ) )
{
// add to the undo
undo.addPoint( info );
undo.undoFlags = Selection::unpin;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock * block = getGridFile()->getBlock( bpos ) )
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
// pin it - position is in current detail coords
spos.x >>= pinDetail;
spos.y >>= pinDetail;
// fill in the callback info
GridBlock::pinCallbackInfo callback;
callback.obj = this;
callback.func = SimTed::pinSquareCallback;
callback.gridBlock = block;
block->pinSquare( pinDetail, spos, pinDetailMax, false, &callback );
}
}
}
}
break;
}
}
// just calls relight ( so can be mapped to a mouse key )
void SimTed::relightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
relight(false);
break;
}
}
// just calls undo ( so we can use the mouse with this )
void SimTed::undoAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
SimTed::undo();
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just calls redo ( so we can use the mouse with this )
void SimTed::redoAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
sel; undo;
switch( action )
{
case begin:
SimTed::redo();
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the terrain type for the selected terrain
void SimTed::setTerrainTypeAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
{
// clear the hilight selection
hilightSel.clear();
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
break;
}
case update:
{
// add to the hilight selection
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
break;
}
case end:
{
Vector<Point2I> pntList;
// add to the hilight selection
for( i = 0; i < sel.points.getSize(); i++ )
hilightSel.addPoint( sel.points[i] );
// create the pnt list
for( i = 0; i < hilightSel.points.getSize(); i++ )
{
// add to list
pntList.push_back( hilightSel.points[i].pos );
Selection::Info info;
// add to undo
if( getInfo( hilightSel.points[i].pos, info ) )
undo.addPoint( info );
}
// save the flags
UInt8 flagSave = flagVal;
// clear the edit flag
flagVal = GridBlock::Material::Edit | GridBlock::Material::Corner;
setFlagsAction( action, hilightSel, undo );
// apply the textures
landscaper->applyTextures( &pntList, terrainType );
// flush them textures
flushTextures();
// set the relight flag for this undo
undo.undoFlags = Selection::landscape | Selection::flushTextures;
// set the edit flag
flagVal = GridBlock::Material::Edit | GridBlock::Material::Corner;
setFlagsAction( action, hilightSel, undo );
// clear the hilight selection
hilightSel.clear();
// reset the flag mask
flagVal = flagSave;
break;
}
}
if( hilightShow.test( Outline ) )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// copy info
void SimTed::copyAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
switch( action )
{
case begin:
{
// clear the copy selection
copySel.clear();
if( !sel.points.getSize() )
return;
// use the first point as the one for reference
Point2I startPnt = sel.points[0].pos;
// go though all of the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// adjust the point
info.pos.x -= startPnt.x;
info.pos.y -= startPnt.y;
// add to the copy selection
copySel.addPoint( info );
}
}
// clusterize this selection in case we want it later
clusterizeSelection( copyClusterSel, copySel );
break;
}
}
}
// paste info
void SimTed::pasteAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;sel;
switch( action )
{
case begin:
{
// get the start point and check if there is something to paste
if( !copySel.points.getSize() )
return;
Point2I startPnt = brushPos;
// go though all of the copy buffer
for( unsigned int i = 0; i < copySel.points.getSize(); i++ )
{
// get the point we are going to be working with
Point2I pnt( startPnt.x + copySel.points[i].pos.x,
startPnt.y + copySel.points[i].pos.y );
if( !pointValid( pnt ) )
continue;
// get the info for this point
Selection::Info info;
undo.undoFlags = Selection::flushTextures;
UInt8 paste = selFloating ? floatPasteVal : pasteVal;
if( getInfo( pnt, info ) )
{
// add to the undo
undo.addPoint( info );
// check for material change
if( paste & Material )
info.material = copySel.points[i].material;
// check for height change
if( paste & Height )
info.height = copySel.points[i].height;
// add the info
setInfo( info );
}
// fjush the textures
flushTextures();
}
break;
}
case end:
selFloating = false;
getGridFile()->updateHeightRange();
break;
}
}
// set the material of the selections
void SimTed::setMaterialAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// go though all of the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to the undo
undo.addPoint( info );
// set the material index
info.material.index = materialIndex;
// set the edit flag
info.material.flags |= GridBlock::Material::Edit;
// store back
setInfo( info );
}
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
}
// raise the terrain as a smooth operation about the center of the
// selection
void SimTed::elevateAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
if( !getBrushDetail() )
raiseHeightAction( action, sel, undo );
switch( action )
{
case begin:
case update:
{
RectI bound;
Point2F center;
float radius;
// get the selection info
setSelectionVars( sel, bound, center, radius );
// walk through the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
float dx = p.x - center.x;
float dy = p.y - center.y;
float distance = sqrt( ( dx * dx ) + ( dy *dy ) );
float scaledDelta = adjustVal * ( radius - distance );
// get the info at this point
Selection::Info info;
if( getInfo( p, info ) )
{
// add to the undo
undo.addPoint( info );
// adjust the height
setHeight( p, info.height.height + scaledDelta );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// lower the terrain as a smooth operation about the center of the
// selection
void SimTed::depressAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
if( !getBrushDetail() )
lowerHeightAction( action, sel, undo );
switch( action )
{
case begin:
case update:
{
RectI bound;
Point2F center;
float radius;
// get the selection info
setSelectionVars( sel, bound, center, radius );
// walk through the selection
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
float dx = p.x - center.x;
float dy = p.y - center.y;
float distance = sqrt( ( dx * dx ) + ( dy *dy ) );
float scaledDelta = -adjustVal * ( radius - distance );
// get the info at this point
Selection::Info info;
if( getInfo( p, info ) )
{
// add to the undo
undo.addPoint( info );
// adjust the height
setHeight( p, info.height.height + scaledDelta );
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just call into the rotate action
void SimTed::rotateRightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
rotateAction( action, sel, undo, true );
}
// just call into the rotate action
void SimTed::rotateLeftAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
rotateAction( action, sel, undo, false );
}
// rotate the selected terrain by 90 deg
void SimTed::rotateAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, bool rotRight )
{
unsigned int i;
switch( action )
{
case begin:
case update:
// go through the selection
for( i = 0; i < sel.points.getSize(); i++ )
{
// get the info at this position
Selection::Info info;
if( !getInfo( sel.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
const int rot = GridBlock::Material::Rotate;
const int flipx = GridBlock::Material::FlipX;
const int flipy = GridBlock::Material::FlipY;
int f = info.material.flags;
// set all the flags
info.material.flags |= ( rot | flipx | flipy );
// this kinda sucks, but the way this was done before
// was corrupting the flags!
if( rotRight )
{
if( !( f & rot ) )
{
if( !( f & flipx ) )
info.material.flags &= ~( flipx | flipy );
}
else
{
if( !( f & flipx ) )
info.material.flags &= ~( rot );
else
info.material.flags &= ~( rot | flipx | flipy );
}
}
else
{
if( !( f & rot ) )
{
if( f & flipx )
info.material.flags &= ~( flipx | flipy );
}
else
{
if( !( f & flipx ) )
info.material.flags &= ~( rot | flipx | flipy );
else
info.material.flags &= ~( rot );
}
}
// set the info
setInfo( info );
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
// set the flags on the selected terrain through the flagVal mask
void SimTed::setFlagsAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
flagAction( action, sel, undo, set );
}
// reset the flags on the selected terrain through the flagVal mask
void SimTed::clearFlagsAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
flagAction( action, sel, undo, clear );
}
// carry out the particular flag operation
void SimTed::flagAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, SimTed::FlagOps flagOp )
{
unsigned int i;
switch( action )
{
case begin:
case update:
case end:
// go through the selection
for( i = 0; i < sel.points.getSize(); i++ )
{
// get the info at this position
Selection::Info info;
if( !getInfo( sel.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
// adjust the flags
switch( flagOp )
{
case clear:
info.material.flags &= ~( flagVal );
break;
case set:
info.material.flags |= flagVal;
break;
}
// set the info
setInfo( info );
}
// flush them textures
flushTextures();
undo.undoFlags = Selection::flushTextures;
break;
}
}
// raise the height of the selection by adjustVal amount
void SimTed::raiseHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
for( i = 0; i < sel.points.getSize(); i++ )
{
float height = getHeight( sel.points[i].pos ) + adjustVal;
// add to the undo before changing
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
undo.addPoint( info );
setHeight( sel.points[i].pos, height );
}
}
// check for feathering
if( feather )
featherAction( action, sel, undo, true, adjustVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// lower the height of the selection by adjustVal amount
void SimTed::lowerHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
for( i = 0; i < sel.points.getSize(); i++ )
{
float height = getHeight( sel.points[i].pos ) - adjustVal;
// add to the undo before changing
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
undo.addPoint( info );
setHeight( sel.points[i].pos, height );
}
}
// check for feathering
if( feather )
featherAction( action, sel, undo, true, -adjustVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the height for the selected terrain
void SimTed::setHeightAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
unsigned int i;
switch( action )
{
case begin:
case update:
// go through and set the heights
for( i = 0; i < sel.points.getSize(); i++ )
{
Selection::Info info;
if( getInfo( sel.points[i].pos, info ) )
{
// add to the undo
undo.addPoint( info );
setHeight( sel.points[i].pos, heightVal );
}
}
// check if we should smooth this
if( feather )
featherAction( action, sel, undo, false, heightVal );
break;
case end:
getGridFile()->updateHeightRange();
break;
}
}
// just force to fit
void SimTed::setSmoothVal( float smooth )
{
if( smooth < 0.0f )
smooth = 0.0f;
if( smooth > 1.0f )
smooth = 1.0f;
smoothVal = smooth;
}
// smooth the selected terrain
void SimTed::smoothAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
switch( action )
{
case begin:
case update:
{
// how do you smooth a single point?
if( !getBrushDetail() )
return;
//get some information about the current selection
RectI bound;
Point2F center;
float radius;
setSelectionVars( sel, bound, center, radius );
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I pnt = sel.points[i].pos;
float dx = pnt.x - center.x;
float dy = pnt.y - center.y;
float distance = sqrt( float( ( dx * dx ) + ( dy * dy ) ) );
Selection::Info info;
if( !getInfo( pnt, info ) )
continue;
// add to info
undo.addPoint( info );
float oldHeight = info.height.height;
float sum = 0.0;
int count = 0;
if( pointValid( Point2I( pnt.x - 1, pnt.y ) ) )
{
sum += getHeight( Point2I( pnt.x - 1, pnt.y ) );
count++;
}
if( pointValid( Point2I( pnt.x + 1, pnt.y ) ) )
{
sum += getHeight( Point2I( pnt.x + 1, pnt.y ) );
count++;
}
if( pointValid( Point2I( pnt.x, pnt.y - 1 ) ) )
{
sum += getHeight( Point2I( pnt.x, pnt.y - 1 ) );
count++;
}
if( pointValid( Point2I( pnt.x, pnt.y + 1) ) )
{
sum += getHeight( Point2I( pnt.x, pnt.y + 1 ) );
count++;
}
sum /= count;
float increment = ( sum - oldHeight ) /
( ( 10 - ( smoothVal * 9.999f ) ) );
float adjust = increment - ( ( increment / 2 ) *
distance / radius );
if( fabs( adjust ) > fabs( sum - oldHeight ) )
adjust = ( sum - oldHeight );
oldHeight += adjust;
setHeight( pnt, oldHeight);
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// add noise to terrain
void SimTed::noiseAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
action;sel;undo;
}
// adjust the terrain around the selected terrain to create smooth
// transition for the heights
void SimTed::featherAction( SimTed::BrushAction action, Selection & sel,
Selection & undo, bool raise, float height )
{
switch( action )
{
case begin:
case update:
{
Selection touched;
unsigned int i;
// check at which detail we should feather things
if( !brushDetail || !snap )
{
for( i = 0; i < sel.points.getSize(); i++ )
{
int j, k;
// walk around this point and add the ones touching
for( j = -1; j <= 1; j++ )
{
for( k = -1; k <= 1; k++ )
{
if( j || k )
{
Point2I pnt;
pnt.x = sel.points[i].pos.x + k;
pnt.y = sel.points[i].pos.y + j;
if( pointValid( pnt ) && !touched.pointInSel( pnt ) &&
!sel.pointInSel( pnt ) )
touched.addPoint( pnt );
}
}
}
}
Vector < float > heights;
// go through all the points in the touched list and get an average height
for( i = 0; i < touched.points.getSize(); i++ )
{
int j, k;
int count = 0;
float sum = 0.0;
// walk around this point and sum the surrounding ones
for( j = -1; j <= 1; j++ )
{
for( k = -1; k <= 1; k++ )
{
Point2I pnt;
pnt.x = touched.points[i].pos.x + k;
pnt.y = touched.points[i].pos.y + j;
// add to the sum
if( pointValid( pnt ) )
{
count++;
sum += getHeight( pnt );
}
}
}
float height = sum / count;
heights.push_back( height );
}
// now set these heights
for( i = 0; i < touched.points.getSize(); i++ )
{
Selection::Info info;
if( !getInfo( touched.points[i].pos, info ) )
continue;
// add to the undo
undo.addPoint( info );
setHeight( touched.points[ i ].pos, heights[ i ] );
}
return;
}
for( int n = -1; n <= 1; n++ )
{
for( int m = -1; m <= 1; m++ )
{
// skip this brush
if( !m && !n )
continue;
// get the position
Point2I pos;
pos.x = brushPos.x + m * ( 1 << brushDetail );
pos.y = brushPos.y + n * ( 1 << brushDetail );
// check that the brush exists
if( !pointValid( pos ) )
continue;
// check for raising an edge or a corner
if( !m || !n )
{
SimTed::Side side;
if( !m )
side = ( n == -1 ) ? bottom : top;
else
side = ( m == -1 ) ? right : left;
// adjust the edge
raiseEdgeHeight( pos, undo, side, height, raise );
}
else
{
bool top = true;
bool left = true;
// figure out which corners to adjust to/from
if( m == -1 )
left = false;
if( n == -1 )
top = false;
// raise a corner
Point2I src;
src.x = left ? brushPos.x + ( 1 << brushDetail ) - 1 :
brushPos.x;
src.y = left ? brushPos.y + ( 1 << brushDetail ) - 1 :
brushPos.y;
if( !pointValid( src ) )
continue;
float height = getHeight( src );
adjustControlPoint( pos, height, undo, top, left, true );
}
}
}
break;
}
case end:
getGridFile()->updateHeightRange();
break;
}
}
// set the height for an edge of the terrain
void SimTed::raiseEdgeHeight( const Point2I brush, Selection & undo, SimTed::Side side, float height, bool raise )
{
int brushDim = ( 1 << brushDetail );
// go along the edge
for( int i = 0; i < brushDim; i++ )
{
Point2I destPnt;
// look at side
switch( side )
{
case right:
destPnt.x = brush.x + brushDim - 1;
destPnt.y = brush.y + i;
break;
case bottom:
destPnt.x = brush.x + i;
destPnt.y = brush.y + brushDim - 1;
break;
case left:
destPnt.x = brush.x;
destPnt.y = brush.y + i;
break;
case top:
destPnt.x = brush.x + i;
destPnt.y = brush.y;
break;
}
// get the amount we need to adjust to
float heightStep;
if( raise )
heightStep = height / ( float )( brushDim - 1 );
else
heightStep = ( height - getHeight( destPnt ) ) / ( float )brushDim;
for( int j = 0; j < brushDim; j++ )
{
Point2I currentPnt;
// look at side
switch( side )
{
case right:
currentPnt.x = brush.x + j;
currentPnt.y = destPnt.y;
break;
case bottom:
currentPnt.x = destPnt.x;
currentPnt.y = brush.y + j;
break;
case left:
currentPnt.x = brush.x + brushDim - j - 1;
currentPnt.y = destPnt.y;
break;
case top:
currentPnt.x = destPnt.x;
currentPnt.y = brush.y + brushDim - j - 1;
break;
}
Selection::Info info;
if( !getInfo( currentPnt, info ) )
continue;
undo.addPoint( info );
setHeight( currentPnt, info.height.height + heightStep * j );
}
}
}
// adjust the corner of a brush
void SimTed::setBrushCornerHeight( const Point2I pnt, Selection & undo,
float height, bool setUndo )
{
int brushDim = ( 1 << getBrushDetail() );
// go through them
for( int i = -1; i <= 0; i++ )
{
for( int j = -1; j <= 0; j++ )
{
bool top = true;
bool left = true;
Point2I pos( pnt.x + j * brushDim, pnt.y + i * brushDim );
// check that there is a brush here
if( !pointValid( pos ) )
continue;
// get the corner pos and directions
if( j == -1 )
left = false;
if( i == -1 )
top = false;
// adjust this corner
adjustControlPoint( pos, height, undo, top, left, setUndo );
}
}
}
// adjust the height value for a corner of a brush selection
// assumes that a brush really exists at this coordinate
void SimTed::adjustControlPoint( const Point2I brush, float height, Selection & undo,
bool top, bool left, bool setUndo )
{
int brushHeight, brushWidth;
Point2I control;
Point2F endPnt;
// get the brush dimensions
brushHeight = brushWidth = ( 1 << brushDetail );
// get the control point
control.y = top ? 0 : ( brushHeight - 1 );
control.x = left ? 0 : ( brushWidth - 1 );
// get the height for this control point
Point2I pnt( control.x + brush.x, control.y + brush.y );
float controlHeight = getHeight( pnt );
for( int y = 0; y < brushHeight; y++ )
{
for( int x = 0; x < brushWidth; x++ )
{
Point2I pos( x, y );
if( pos == control )
{
pos.x += brush.x;
pos.y += brush.y;
// add to the undo
if( setUndo )
{
Selection::Info info;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
setHeight( pos, height );
continue;
}
else if( pos.x == control.x )
{
endPnt.x = ( float )control.x;
endPnt.y = ( float )( top ? ( brushHeight - 1 ) : 0 );
}
else if( pos.y == control.y )
{
endPnt.x = ( float )( left ? ( brushWidth - 1 ) : 0 );
endPnt.y = ( float )control.y;
}
else
{
// get the slope
double slope;
slope = fabs( float( pos.y - control.y ) ) / fabs( float( pos.x - control.x ) );
if( slope <= 1.0 )
{
endPnt.x = ( float )( left ? ( brushWidth - 1 ) : 0 );
endPnt.y = ( float )( top ? ( slope * float( brushHeight - 1 ) ) :
float( ( brushHeight - 1 ) ) - ( slope * float( brushHeight - 1 ) ) );
}
else
{
endPnt.x = ( float )( left ? ( float( brushWidth - 1 ) / slope ) :
float( brushWidth - 1 ) - ( float( brushWidth - 1 ) / slope ) );
endPnt.y = ( float )( top ? ( brushHeight - 1 ) : 0 );
}
}
double targetD;
double endD;
// get the distances
targetD = sqrtf( ( control.x - x ) * ( control.x - x ) +
( control.y - y ) * ( control.y - y ) );
endD = sqrtf( ( endPnt.x - control.x ) * ( endPnt.x - control.x ) +
( endPnt.y - control.y ) * ( endPnt.y - control.y ) );
// adjust the coords
pos.x += brush.x;
pos.y += brush.y;
float stepInc = ( height - controlHeight ) / endD;
float posHeight = getHeight( pos );
posHeight += ( height - controlHeight ) - ( stepInc * targetD );
// add to the undo
if( setUndo )
{
Selection::Info info;
if( getInfo( pos, info ) )
undo.addPoint( info );
}
setHeight( pos, posHeight );
}
}
}
// adds the selection to the current selection ( allows for
// mass selection with the shift key )
void SimTed::selectAction( SimTed::BrushAction action, Selection & sel, Selection & undo )
{
undo;
unsigned int i;
switch( action )
{
case begin:
// check for ctrl button
if( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )
{
// clear out the highlight selection
hilightSel.clear();
regionSelect = true;
selectCanceled = false;
selectStartPnt = brushPos;
}
else
{
regionSelect = false;
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.addPoint( sel.points[i].pos );
}
break;
case update:
if( regionSelect && !selectCanceled )
{
hilightSel.clear();
if( GetAsyncKeyState( VK_ESCAPE ) & 0x8000 )
{
selectCanceled = true;
return;
}
Point2I tlPnt;
Point2I dim;
int length = 1 << brushDetail;
// get the coords for the box
tlPnt.x = min( selectStartPnt.x, brushPos.x );
tlPnt.y = min( selectStartPnt.y, brushPos.y );
dim.x = max( selectStartPnt.x + length, brushPos.x + length ) - tlPnt.x;
dim.y = max( selectStartPnt.y + length, brushPos.y + length ) - tlPnt.y;
int i, j;
// fill the region select with the info
for( i = 0; i < dim.y; i++ )
for( j = 0; j < dim.x; j++ )
{
Point2I pnt( tlPnt.x + j, tlPnt.y + i );
if( pointValid( pnt ) )
hilightSel.addPoint( pnt );
}
}
else
{
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.addPoint( sel.points[i].pos );
}
break;
case end:
if( regionSelect )
{
for( i = 0; i < hilightSel.points.getSize(); i++ )
currentSel.addPoint( hilightSel.points[i].pos );
hilightSel.clear();
}
break;
}
// clusterize the stuff
if( selectShow.test( Outline ) )
clusterizeSelection( currentClusterSel, currentSel );
if( hilightShow.test( Outline ) && regionSelect )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// gets the average height for the selection
void SimTed::getAvgHeightAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
switch( action )
{
case begin:
case update:
unsigned int i;
int numPoints = sel.points.getSize();
float sum = 0.0;
for( i = 0; i < sel.points.getSize(); i++ )
sum += getHeight( sel.points[i].pos );
avgHeight = sum / numPoints;
break;
}
}
// remove the selected blocks from the current selection
void SimTed::deselectAction( SimTed::BrushAction action, Selection & sel,
Selection & undo )
{
undo;
unsigned int i;
switch( action )
{
case begin:
// check for ctrl button
if( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )
{
// clear out the highlight selection
hilightSel.clear();
regionSelect = true;
selectCanceled = false;
selectStartPnt = brushPos;
}
else
{
regionSelect = false;
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.removePoint( sel.points[i].pos );
}
break;
case update:
if( regionSelect && !selectCanceled )
{
hilightSel.clear();
if( GetAsyncKeyState( VK_ESCAPE ) & 0x8000 )
{
selectCanceled = true;
return;
}
Point2I tlPnt;
Point2I dim;
int length = 1 << brushDetail;
// get the coords for the box
tlPnt.x = min( selectStartPnt.x, brushPos.x );
tlPnt.y = min( selectStartPnt.y, brushPos.y );
dim.x = max( selectStartPnt.x + length, brushPos.x + length ) - tlPnt.x;
dim.y = max( selectStartPnt.y + length, brushPos.y + length ) - tlPnt.y;
int i, j;
// fill the region select with the info
for( i = 0; i < dim.y; i++ )
for( j = 0; j < dim.x; j++ )
{
Point2I pnt( tlPnt.x + j, tlPnt.y + i );
if( pointValid( pnt ) )
hilightSel.addPoint( pnt );
}
}
else
{
for( i = 0; i < sel.points.getSize(); i++ )
currentSel.removePoint( sel.points[i].pos );
}
break;
case end:
if( regionSelect )
{
for( i = 0; i < hilightSel.points.getSize(); i++ )
currentSel.removePoint( hilightSel.points[i].pos );
hilightSel.clear();
}
break;
}
// clusterize the stuff
if( selectShow.test( Outline ) )
clusterizeSelection( currentClusterSel, currentSel );
if( hilightShow.test( Outline ) && regionSelect )
clusterizeSelection( hilightClusterSel, hilightSel );
}
// add an action to the internal table
void SimTed::addAction( const char * name, void ( SimTed::*callback )
( SimTed::BrushAction, Selection & sel, Selection & undo ), bool mouseAction,
const char * description )
{
TedAction * newAction = new TedAction;
newAction->name = name;
newAction->callback = callback;
newAction->mouseAction = mouseAction;
newAction->description = description;
// add to the vector
actions.push_back( newAction );
}
// call an action routine
bool SimTed::processAction( const char * name )
{
int actionIndex = getActionIndex( name );
// check that it got a good action
if( actionIndex == -1 )
return( false );
// check if there is something selected
if( !currentSel.points.getSize() )
return( true );
// create an undo selection
Selection * undo = new Selection;
// save the brush detail size
int detail = getBrushDetail();
// go into detail mode 0 for this
setBrushDetail( 0 );
// call the callback twice ( begin then end )
( this->*actions[actionIndex]->callback )( begin, currentSel, *undo );
( this->*actions[actionIndex]->callback )( end, currentSel, *undo );
// reset the detail mode
setBrushDetail( detail );
// do the undo stuff
if( undo->points.getSize() )
{
// add to the undo stack and remove the redo stack
undoStack.push( undo );
redoStack.clear();
}
else
delete undo;
dataChanged = true;
return( true );
}
void SimTed::floatCurrent()
{
// fill with info ( just has positions )
fillInfo( currentSel );
// float it
floatSelection( currentSel );
floatPasteVal = pasteVal;
currentSel.clear();
}
void SimTed::floatSelection( Selection & sel )
{
if( selFloating || !sel.points.getSize() )
return;
// grab the first position, rest are offset from this
Point2I origin = sel.points[0].pos;
// clear the copy selection
copySel.clear();
// add all the points as an offset to the first point from the sel
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I pos( sel.points[i].pos.x - origin.x,
sel.points[i].pos.y - origin.y );
Selection::Info info;
info = sel.points[i];
info.pos = pos;
copySel.addPoint( info );
}
// clusterize if wanted to
clusterizeSelection( copyClusterSel, copySel );
selFloating = true;
}
void SimTed::setBrushPos( const Point2I & pos )
{
brushPos = pos;
// check for snap
if( snap )
{
brushPos.x >>= brushDetail;
brushPos.x <<= brushDetail;
brushPos.y >>= brushDetail;
brushPos.y <<= brushDetail;
}
}
void SimTed::mouseAction( int button, SimTed::BrushAction action )
{
Point2I hitPnt;
cursorPos = getCanvas()->getCursorPos();
cursorDif = cursorPos - lastCursorPos;
lastCursorPos = cursorPos;
if( action == begin )
cursorDif.set( 0, 0 );
setVars();
if( !getInterceptCoord( hitPnt ) && ( action != end ) )
{
selectLastPnt.x = -1;
selectLastPnt.y = -1;
return;
}
// set the brush position ( will snap here if requested )
setBrushPos( hitPnt );
// check which button was pressed
if(!button)
{
// make sure the other button is not pressed
if( ::GetAsyncKeyState( ( ::GetSystemMetrics( SM_SWAPBUTTON ) ) ?
VK_LBUTTON : VK_RBUTTON ) & 0x8000 )
return;
if(action == begin)
{
// protect against multiple begins (can happen when
// lost the mouse and the mouse up event)..
if(mouseProcessAction != -1)
return;
mouseProcessAction = mouseLButtonAction;
}
}
else
{
// make sure the other button is not pressed
if( ::GetAsyncKeyState( ( ::GetSystemMetrics( SM_SWAPBUTTON ) ) ?
VK_RBUTTON : VK_LBUTTON ) & 0x8000 )
return;
if(action == begin)
{
if(mouseProcessAction != -1)
return;
mouseProcessAction = mouseRButtonAction;
}
}
// check if floating
if( selFloating )
{
// check for cancel
if( button )
{
selFloating = false;
return;
}
else if(action == begin)
mouseProcessAction = getActionIndex( "paste" );
}
// only do the comman on new position
if( ( brushPos == selectLastPnt ) && ( action == update ) && !grabMode )
return;
// update the last mouse position so that we do not apply the same action
selectLastPnt = brushPos;
// check if cool
if( ( mouseProcessAction != -1 ) && ( actions.size() > mouseProcessAction ) &&
( actions[mouseProcessAction]->callback != 0 ) )
{
Selection sel;
fillSelection( sel );
// create a new undo selection that spans the entire command
if( ( action == begin ) && currentUndo )
{
delete currentUndo;
currentUndo = NULL;
}
// create a new selection
if( !currentUndo )
currentUndo = new Selection;
// call the callback
( this->*actions[mouseProcessAction]->callback )( action, sel, *currentUndo );
// do the undo stuff
if( action == end )
{
// add to the undo if points were actually changed
if( currentUndo->points.getSize() )
{
// add to the undo but flush the redo
undoStack.push( currentUndo );
redoStack.clear();
}
else
delete currentUndo;
// reset the ptr ( the stack will deal with it )
currentUndo = NULL;
dataChanged = true;
// update the toolbar
Console->evaluate( "Ted::updateToolBar();", false );
mouseProcessAction = -1;
}
}
}
void SimTed::fillSelection( Selection & sel )
{
int i,j;
int length = 1 << brushDetail;
// add 2^detailLevelx2^detailLevel points
for( i = 0; i < length; i++ )
for( j = 0; j < length; j++ )
{
Point2I pnt( brushPos.x + j, brushPos.y + i );
if( pointValid( pnt ) )
sel.addPoint( pnt );
}
}
// apply an action to the entire terrain block.. only
// works with oneBlockmapstoall....
bool SimTed::terrainAction(const char * action)
{
if(getGridFile()->getBlockPattern() != GridFile::OneBlockMapsToAll)
return(false);
// get the width of a blcok
int n = 1 << (getMaxBrushDetail() - 1);
int actionIndex = getActionIndex(action);
if(actionIndex == -1)
return(false);
// create a selection of the entire terrain
Selection sel;
sel.createMap(n,n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
sel.addPoint(Point2I(i,j));
// create an undo selection
Selection * undo = new Selection;
undo->createMap(n,n);
// call the function
int detail = getBrushDetail();
setBrushDetail(0);
( this->*actions[actionIndex]->callback )( begin, sel, *undo );
( this->*actions[actionIndex]->callback )( end, sel, *undo );
setBrushDetail(detail);
undo->deleteMap();
// add to the undo stack and remove the redo stack
undoStack.push( undo );
redoStack.clear();
dataChanged = true;
return(true);
}
// this will mirror the terrain according the flags... only
// mirrors the center block of a oneblockmapstoall pattern
bool SimTed::mirrorTerrain(UInt32 sides)
{
if(getGridFile()->getBlockPattern() != GridFile::OneBlockMapsToAll)
return(false);
// check the sides
if((sides & top) && (sides & bottom))
return(false);
if((sides & left) && (sides & right))
return(false);
// get the width of a blcok
int n = 1 << (getMaxBrushDetail() - 1);
Point2I src((sides & right) ? (n - 1) : 0, (sides & bottom) ? (n - 1) : 0);
Point2I dest((sides & left) ? (n - 1) : 0, (sides & top) ? (n - 1) : 0);
Point2I origSrc(src);
Point2I origDest(dest);
// check if diag...
bool diag = ((sides & right)||(sides & left)) && ((sides & top)||(sides & bottom));
// determine the run length
int minStride = ((sides & top) || (sides & bottom)) ? n : n / 2;
int majStride = ((sides & left) || (sides & right)) ? n : n / 2;
Point2I srcStep((sides & right) ? -1 : 1, (sides & bottom) ? -1 : 1);
Point2I destStep((sides & left) ? -1 : 1, (sides & top) ? -1 : 1);
// create an undo stack for this operation
Selection * undo = new Selection;
// walk through all the positions
for(int i = 0; i < majStride; i++)
{
for(int j = 0; j < minStride; j++)
{
// skip the same position
if(src != dest)
{
// set only the height...
SimTed::Selection::Info info;
if(getInfo(dest, info))
{
undo->addPoint(info);
float height = getHeight(src);
setHeight(dest, height);
}
}
// get to the new position
src.x += srcStep.x;
diag ? (dest.y += destStep.y) : (dest.x += destStep.x);
}
// get the next position for a run
src.y += srcStep.y;
diag ? (dest.x += destStep.x) : (dest.y += destStep.y);
// reset the minor run
src.x = origSrc.x;
diag ? (dest.y = origDest.y) : (dest.x = origDest.x);
// shorten the run length for diag runs
if(diag)
minStride--;
}
// add to the undo stack
undoStack.push(undo);
redoStack.clear();
dataChanged = true;
return(true);
}
bool SimTed::pointValid( const Point2I & pnt )
{
if( ( pnt.x >= 0 ) && ( pnt.x < ( size.x << blockShift ) ) &&
( pnt.y >= 0 ) && ( pnt.y < ( size.y << blockShift ) ) )
return( true );
return( false );
}
bool SimTed::onSim3DMouseEvent( const Sim3DMouseEvent * event )
{
if( !focused )
return( false );
switch( event->meType )
{
case Sim3DMouseEvent::MouseUp:
case Sim3DMouseEvent::RightMouseUp:
AssertFatal( mouseHandler, "SimTed::processEvent:: mouse handler not set" );
// send off to the tedplugin
mouseHandler->mouseCallback( true, ( event->meType == Sim3DMouseEvent::RightMouseDown ) );
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseUp ), end );
break;
case Sim3DMouseEvent::RightMouseDown:
case Sim3DMouseEvent::MouseDown:
AssertFatal( mouseHandler, "SimTed::processEvent:: mouse handler not set" );
// send to ted
mouseHandler->mouseCallback( false, ( event->meType == Sim3DMouseEvent::RightMouseDown ) );
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseDown ), begin );
break;
case Sim3DMouseEvent::MouseDragged:
case Sim3DMouseEvent::RightMouseDragged:
case Sim3DMouseEvent::MouseMove:
// update the current position and start point for the mouse
mouseStartPt = event->startPt;
mouseDirection = event->direction;
// call the drag routine
if( event->meType != Sim3DMouseEvent::MouseMove )
mouseAction( ( event->meType == Sim3DMouseEvent::RightMouseDragged ), update );
else
{
Point2I hitPnt;
setVars();
if( getInterceptCoord( hitPnt ) )
{
setBrushPos( hitPnt );
mouseMoved = true;
}
}
break;
}
return( false );
}
int SimTed::getMaxBrushDetail()
{
return( getGridFile()->getDetailCount() );
}
void SimTed::setBrushDetail( int detail )
{
// check that we are not trying to change detail too high
if( detail > ( getGridFile()->getDetailCount() ) )
return;
brushDetail = detail;
}
bool SimTed::getInterceptCoord( Point2I & pnt )
{
TMat3F tmat = getInvTransform();
LineSeg3F line;
line.start = mouseStartPt;
line.end = mouseDirection;
line.end *= 100000;
line.end += line.start;
LineSeg3F tline;
m_mul( line.start, tmat, &tline.start );
m_mul( line.end, tmat, &tline.end );
GridCollision coll( getGridFile(), 0 );
if( coll.collide( tline.start, tline.end, false, true ) )
{
Point3F potenIcept = coll.surface.position;
setVars();
Point2I potenIceptI( potenIcept.x,potenIcept.y );
potenIceptI >>= scaleShift;
if ( ( potenIceptI.x >= 0 ) && ( potenIceptI.x < ( size.x << blockShift ) ) &&
( potenIceptI.y >= 0 ) && ( potenIceptI.y < ( size.y << blockShift ) ) )
{
pnt = potenIceptI;
return( true );
}
}
return( false );
}
bool SimTed::processEvent( const SimEvent * event )
{
switch( event->type )
{
onEvent( Sim3DMouseEvent );
case SimGainFocusEventType:
focused = TRUE;
break;
case SimLoseFocusEventType:
focused = FALSE;
break;
// let the parent class handle this event
default:
return( SimObject::processEvent( event ) );
}
return( true );
}
bool SimTed::processQuery( SimQuery* query )
{
switch( query->type )
{
case SimRenderQueryImageType:
{
if( !focused )
return( false );
// setup for an overlay render
SimRenderQueryImage * queryImage =
static_cast< SimRenderQueryImage* >( query );
queryImage->count = 1;
queryImage->image[0] = this;
itype = SimRenderImage::Overlay;
break;
}
case SimInputPriorityQueryType:
// set slightly higher than normal priority
( ( SimInputPriorityQuery * )query )->priority = SI_PRIORITY_NORMAL + 2;
break;
default:
return( SimObject::processQuery( query ) );
}
return( true );
}
bool SimTed::onAdd()
{
if( !SimObject::onAdd() )
return( false );
addToSet( SimInputConsumerSetId );
addToSet( SimRenderSetId );
return( true );
}
void SimTed::onRemove()
{
removeFromSet( SimInputConsumerSetId );
removeFromSet( SimRenderSetId );
focused = false;
SimObject::onRemove();
}
void SimTed::render( TSRenderContext &rc )
{
setVars();
rc.getCamera()->pushTransform( getTransform() );
surface = rc.getSurface();
surface->setHazeSource(GFX_HAZE_NONE);
surface->setShadeSource(GFX_SHADE_NONE);
surface->setAlphaSource(GFX_ALPHA_NONE);
surface->setFillMode(GFX_FILL_CONSTANT);
surface->setTexturePerspective(FALSE);
surface->setTransparency(FALSE);
pointArray = rc.getPointArray();
pointArray->reset();
pointArray->useIntensities(false);
pointArray->useTextures(false);
pointArray->useHazes(false);
pointArray->useBackFaceTest(false);
pointArray->setVisibility( TS::ClipMask );
unsigned int i;
int fillCol, frameCol;
Selection * sel;
// turn off flipping of colors
flipColors = false;
// draw our stuff
if( selectShow.test( Outline ) )
{
sel = ¤tClusterSel;
// check if should clear
if( currentSel.points.getSize() < currentClusterSel.points.getSize() )
currentClusterSel.clear();
// check if should fill
if( currentSel.points.getSize() && !currentClusterSel.points.getSize() )
clusterizeSelection( currentClusterSel, currentSel );
}
else
{
sel = ¤tSel;
currentClusterSel.clear();
}
// set the colors
fillCol = flipColors ? selectFrameColor : selectFillColor;
frameCol = flipColors ? selectFillColor : selectFrameColor;
for( i = 0; i < sel->points.getSize(); i++ )
{
if( selectShow.test( Fill ) )
drawSquareFilled( sel->points[i].pos, rc, fillCol );
if( selectShow.test( Frame ) )
drawSquare( sel->points[i].pos, rc, frameCol );
}
// do the hilight now
if( hilightShow.test( Outline ) )
sel = &hilightClusterSel;
else
sel = &hilightSel;
// set the colors
fillCol = flipColors ? hilightFrameColor : hilightFillColor;
frameCol = flipColors ? hilightFillColor : hilightFrameColor;
for( i = 0; i < sel->points.getSize(); i++ )
{
if( hilightShow.test( Fill ) )
drawSquareFilled( sel->points[i].pos, rc, fillCol );
if( hilightShow.test( Frame ))
drawSquare( sel->points[i].pos, rc, frameCol );
}
// check for grab mode
drawMouseShadow( rc );
// check if drawing the frame around the current block
if( blockOutline )
{
// grab the first block - just need to get dimensions
Point2I size( 0, 0 );
GridBlock * block = getGridFile()->getBlock( size );
// get the size
size = block->getSize();
Point2I begin, end;
// set the start point
begin.x = brushPos.x & ~( size.x - 1 );
begin.y = brushPos.y & ~( size.y - 1 );
// set the end point
end.x = begin.x + size.x;
end.y = begin.y + size.y;
drawSquareOutline( begin, end, rc, blockFrameColor );
}
rc.getCamera()->popTransform();
}
void SimTed::drawSquareOutline( Point2I & begin, Point2I & end, TSRenderContext & rc, UInt8 col )
{
int width, height;
width = end.x - begin.x;
height = end.y - begin.y;
surface->setFillColor( col );
Point2F p1, p2;
float scale = ( float )(1 << scaleShift);
// draw the top and bottom
for( int x = 0; x < ( width - 1 ); x++ )
{
// fill in the point info
p1.x = begin.x + x;
p2.x = p1.x + 1;
p1.y = p2.y = begin.y;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
// do again for fill in the point info
p1.x = begin.x + x;
p2.x = p1.x + 1;
p1.y = p2.y = end.y;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
}
// draw the sides
for( int y = 0; y < height; y++ )
{
// fill in the point info for the left side
p1.x = p2.x = begin.x;
p1.y = begin.y + y;
p2.y = p1.y + 1;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
// fill in the point info for the right side
p1.x = p2.x = end.x;
p1.y = begin.y + y;
p2.y = p1.y + 1;
p1 *= scale;
p2 *= scale;
drawLine( p1, p2, rc, col );
}
}
// draw the mouse shadow, can change shapes depending on mode
void SimTed::drawMouseShadow( TSRenderContext & rc )
{
// check if floating the selection
if( selFloating )
{
int fillCol = flipColors ? shadowFrameColor : shadowFillColor;
int frameCol = flipColors ? shadowFillColor : shadowFrameColor;
Selection * sel;
if( shadowShow.test(Outline) )
sel = ©ClusterSel;
else
sel = ©Sel;
// go through and draw the squares
for( unsigned i = 0; i < sel->points.getSize(); i++ )
{
Point2I pos( sel->points[i].pos.x + brushPos.x,
sel->points[i].pos.y + brushPos.y );
// make sure a valid point
if( !pointValid( pos ) )
continue;
if( shadowShow.test( Fill ) )
drawSquareFilled( pos, rc, fillCol );
if( shadowShow.test( Frame ) )
drawSquare( pos, rc, frameCol );
}
return;
}
// create a shadow selection
Selection brushSel;
if( grabMode )
{
int brushDim = ( 1 << brushDetail );
// set the current brush position
brushPos = grabPoint;
// add all the brush edges only
addBrushEdgePoints( brushPos, brushSel );
if(drawNeighbors)
{
// walk around and add the surrounding brushes
Point2I pos( brushPos.x - brushDim, brushPos.y );
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
pos.y = brushPos.y - brushDim;
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
pos.x = brushPos.x;
// add it
if( pointValid( pos ) )
addBrushEdgePoints( pos, brushSel );
}
}
else
{
fillSelection( brushSel );
// check if the mouse has moved
if( mouseMoved )
{
// get the avg height for the brush ( undo param is not used )
getAvgHeightAction( begin, brushSel, brushSel );
Point2I center;
// get the center location
getBrushCenter( center, brushPos );
// write the info in the status bar
char buffer[ 128 ];
sprintf( buffer, "Ted::setStatusText(2,\"Center - ( %d, %d ) AvgHeight: %.3f\");",
center.x, center.y, avgHeight );
Console->evaluate( buffer, false );
}
// check for outline mode
if( shadowShow.test( Outline ) )
{
brushSel.clear();
addBrushEdgePoints( brushPos, brushSel );
}
}
int fillCol = flipColors ? shadowFrameColor : shadowFillColor;
int frameCol = flipColors ? shadowFillColor : shadowFrameColor;
// go through and draw the squares
for( unsigned i = 0; i < brushSel.points.getSize(); i++ )
{
if( shadowShow.test(Fill) )
drawSquareFilled( brushSel.points[i].pos, rc, fillCol );
if( shadowShow.test(Frame) )
drawSquare( brushSel.points[i].pos, rc, frameCol );
}
// draw the corner piece inverted
if( getSnap() )
{
if( shadowShow.test( Fill ) )
drawSquareFilled( brushPos, rc, shadowFrameColor );
if( shadowShow.test(Frame) )
drawSquare( brushPos, rc, shadowFillColor );
}
// check if the mouse has moved
if( mouseMoved )
{
// get the info for the brush position
Selection::Info info;
if( getInfo( brushPos, info ) )
{
char buffer[ 128 ];
sprintf( buffer, "Ted::setStatusText(1,\"Corner - ( %d, %d ) Height: %.3f\");",
brushPos.x, brushPos.y, info.height.height );
Console->evaluate( buffer, false );
}
}
// reset the mouse moved flag
mouseMoved = false;
}
void SimTed::getBrushCenter( Point2I & center, Point2I & origin )
{
int brushDim = ( 1 << brushDetail );
center.x = ( origin.x * 2 + brushDim ) / 2;
center.y = ( origin.y * 2 + brushDim ) / 2;
}
void SimTed::clusterizeSelection( Selection & dest, Selection & src )
{
dest.clear();
for( unsigned int i = 0; i < src.points.getSize(); i++ )
{
Point2I pos = src.points[i].pos;
// check the corners
if( !src.pointInSel( Point2I( pos.x - 1, pos.y ) ) ||
!src.pointInSel( Point2I( pos.x, pos.y - 1 ) ) ||
!src.pointInSel( Point2I( pos.x + 1, pos.y ) ) ||
!src.pointInSel( Point2I( pos.x, pos.y + 1) ) )
dest.addPoint( src.points[i].pos );
}
}
void SimTed::addBrushEdgePoints( const Point2I & pos, Selection & sel )
{
int brushDim = ( 1 << brushDetail );
for( int i = 0; i < brushDim; i++ )
{
Point2I newPnt;
// add all 4 points around the edge
// top row
newPnt.x = pos.x + i;
newPnt.y = pos.y;
sel.addPoint( newPnt );
// bottom row
newPnt.y += ( brushDim - 1 );
sel.addPoint( newPnt );
// left column
newPnt.x = pos.x;
newPnt.y = pos.y + i;
sel.addPoint( newPnt );
// right column
newPnt.x += ( brushDim - 1 );
sel.addPoint( newPnt );
}
}
void SimTed::drawSquareFilled( Point2I pos, TSRenderContext& rc, UInt8 col )
{
rc;
surface->setFillColor( col );
// create the points CCW
Point3F p1( pos.x, pos.y, 0.0 );
Point3F p2( pos.x, pos.y + 1, 0.0 );
Point3F p3( pos.x + 1, pos.y + 1, 0.0 );
Point3F p4( pos.x + 1, pos.y, 0.0 );
float scale = (float)( 1 << scaleShift );
p1 *= scale;
p2 *= scale;
p3 *= scale;
p4 *= scale;
// get the heights
p1.z = getHeight( pos ); pos.y++;
p2.z = getHeight( pos ); pos.x++;
p3.z = getHeight( pos ); pos.y--;
p4.z = getHeight( pos );
TS::VertexIndexPair vertexPairs[5];
vertexPairs[0].fVertexIndex = pointArray->addPoint( p1 ) ;
vertexPairs[0].fTextureIndex = 0;
vertexPairs[1].fVertexIndex = pointArray->addPoint( p2 );
vertexPairs[1].fTextureIndex = 0;
vertexPairs[2].fVertexIndex = pointArray->addPoint( p3 );
vertexPairs[2].fTextureIndex = 0;
vertexPairs[3].fVertexIndex = pointArray->addPoint( p4 );
vertexPairs[3].fTextureIndex = 0;
vertexPairs[4] = vertexPairs[0];
pointArray->drawPoly( 5, vertexPairs, 0 );
}
void SimTed::drawLine( Point2F start, Point2F end, TSRenderContext& rc,
UInt8 col )
{
rc;
Point2I st( start.x, start.y );
Point2I en( end.x, end.y );
st >>= scaleShift;
en >>= scaleShift;
float sheight = getHeight( st );
float eheight = getHeight( en );
Point3F ulft, urt, llft, lrt;
ulft = Point3F( start.x, start.y, sheight );
urt = Point3F( end.x, end.y, eheight );
pointArray->drawLine( pointArray->addPoint( ulft ),
pointArray->addPoint( urt ), col);
}
void SimTed::drawSquare( Point2I pos, TSRenderContext& rc, UInt8 col )
{
surface->setFillColor( col );
Point2F p1( pos.x, pos.y );
Point2F p2( pos.x + 1, pos.y );
Point2F p3( pos.x, pos.y + 1 );
Point2F p4( pos.x + 1, pos.y + 1 );
float scale = ( float )(1 << scaleShift);
p1 *= scale;
p2 *= scale;
p3 *= scale;
p4 *= scale;
drawLine( p3, p1, rc, col );
drawLine( p1, p2, rc, col );
drawLine( p4, p2, rc, col );
drawLine( p3, p4, rc, col );
if( drawNotch )
{
Point2F p5 = p4;
p5 -= p1;
p5 *= 0.25f;
p5 += p1;
drawLine( p1, p5, rc, col );
}
}
bool SimTed::setHeight( const Point2I& pos, const float& ht )
{
//this method assumes coords are already shifted down by scale
// and that setVars was called prior
GridBlock::Height h;
h.height = ht;
bool success = false;
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
Point2I block_coords[ 4 ];
int cnt = 0;
int blockMask = (1 << blockShift) - 1;
block_coords[ cnt++ ] = bpos;
// Also set heights of adjacent blocks, if on the border...
if ( bpos.x >= 1 && !(pos.x & blockMask) )
block_coords[ cnt++ ] = Point2I( bpos.x - 1, bpos.y );
if ( bpos.y >= 1 && !(pos.y & blockMask) )
{
block_coords[ cnt++ ] = Point2I( bpos.x, bpos.y - 1 );
if ( bpos.x >= 1 && !(pos.x & blockMask) )
block_coords[ cnt++ ] = Point2I( bpos.x - 1, bpos.y - 1 );
}
Point2I *blpos = block_coords;
for ( int i = 0; i < cnt; i++, blpos++ )
if ( GridBlock* block = getGridFile()->getBlock( *blpos ) )
{
// get remainders on coords so they are in block space
Point2I spos;
spos.x = (pos.x - (blpos->x << blockShift));
spos.y = (pos.y - (blpos->y << blockShift));
//set the height
int index = (spos.y << blockShift) + spos.y + spos.x;
int mapwid = block->getHeightMapWidth();
if (index < mapwid*mapwid )
{
block->setDirtyFlag();
GridBlock::Height* heightMap = block->getHeightMap();
if (heightMap )
heightMap[index] = h;
success = TRUE;
}
}
}
return ( success );
}
bool SimTed::setMaterial( const Point2I& pos, const GridBlock::Material & material )
{
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
if( GridBlock* block = getGridFile()->getBlock( bpos ) )
{
//get coords into block
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
//set the Material
int index = ( spos.y << blockShift ) + spos.x;
int mapwid = block->getMaterialMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Material *currMat = block->getMaterialMap();
if ( !currMat )
return ( false );
currMat[index] = material;
block->setDirtyFlag();
}
return ( true );
}
return ( false );
}
float SimTed::getHeight(const Point2I& pos)
{
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = pos.y >> blockShift;
if( bpos.x >= 0 && bpos.x < size.x && bpos.y >= 0 && bpos.y < size.y )
{
if( GridBlock* block = getGridFile()->getBlock( bpos ))
{
//get remainders
Point2I spos;
spos.x = ( pos.x - ( bpos.x << blockShift ) );
spos.y = ( pos.y - ( bpos.y << blockShift ) );
//get the height
int index = ( spos.y << blockShift )+ spos.y + spos.x;
int mapwid = block->getHeightMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Height* heightMap = block->getHeightMap();
if( !heightMap )
return( 0 );
return heightMap[index].height;
}
}
}
return( 0 );
}
GridBlock::Material * SimTed::getMaterial( const Point2I& pos )
{
// coords should already be shifted down by ground scale
Point2I bpos;
bpos.x = pos.x >> blockShift;
bpos.y = (pos.y) >> blockShift;
if( bpos.x >=0 && bpos.x < size.x && bpos.y >=0 && bpos.y < size.y )
if( GridBlock* block = getGridFile()->getBlock( bpos ) )
{
//get remainders on coords
Point2I spos;
spos.x = ( pos.x - (bpos.x << blockShift ) );
spos.y = ( ( pos.y ) - ( bpos.y << blockShift ) );
//get a ptr to the material
int index = (spos.y << blockShift) + spos.x;
int mapwid = block->getMaterialMapWidth();
if( index < mapwid*mapwid )
{
GridBlock::Material* matMap = block->getMaterialMap();
if( !matMap )
return ( NULL );
return ( &matMap[index] );
}
}
return ( NULL );
}
TSMaterialList * SimTed::getMaterialList()
{
if( getGridFile() )
return( getGridFile()->getMaterialList() );
return( NULL );
}
bool SimTed::open( const char * terrainName )
{
// close down this one
if( terrain )
deleteTerrain();
// create a new terrain
if( ( terrain = new SimTerrain ) != 0 )
{
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
serverManager->addObject( terrain );
serverManager->assignName( terrain, terrainName );
deleteNotify( terrain );
terrain->load( terrainName );
if( getGridFile() )
{
newLandscaper();
loadMatList( getGridFile()->getMaterialListName() );
terrain->setContext(EulerF(.0f,.0f,.0f),Point3F(.0f,.0f,.0f));
terrain->setVisibility( &DefTerrainVisibility );
terrain->setDetail( &DefTerrainDetail );
SimGainFocusEvent::post( this );
return( true );
}
}
dataChanged = false;
return( false );
}
// create a new file
bool SimTed::newFile( int scale, int blocksWide, int blocksHigh, int blockDim,
const char * terrName, GridFile::GBPatternMap blockPattern )
{
blocksHigh;
// create a new terrain
terrain = new SimTerrain;
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
serverManager->addObject( terrain );
serverManager->assignName( terrain, terrName );
deleteNotify( terrain );
terrain->create( terrName, blocksWide, scale, blockDim, 0, blockPattern );
newLandscaper();
dataChanged = true;
return true;
}
void SimTed::checkSaveChanges()
{
if( terrain && dataChanged )
{
int res = MessageBox( NULL, "save changes?", "close", MB_YESNO );
if( res == IDYES )
{
Console->evaluate( "Ted::save();", false );
}
dataChanged = false;
}
}
bool SimTed::save( const char * fileName )
{
bool success = false;
if( terrain )
{
getGridFile()->updateHeightRange();
success = terrain->save( fileName );
// save off the named selections
char selName[1024];
sprintf(selName, "temp\\%s.sel", getGridFile()->getFileName());
namedSelections.save( selName );
if( !success )
MessageBox( NULL, "Failed to save changes. File write protected?", "Warning!", MB_OK );
}
dataChanged = false;
return( success );
}
bool SimTed::attachToTerrain( const char * terrainName )
{
SimObject * obj;
SimTerrain * terr = 0;
SimManager * serverManager = SimGame::get()->getManager(SimGame::SERVER);
if( terrainName )
{
// locate the terrain
obj = serverManager->findObject( terrainName );
if( obj )
terr = dynamic_cast< SimTerrain * >( obj );
}
else
{
// find the first simterrain object
for( SimSetIterator i( serverManager ); *i; ++i )
if( ( terr = dynamic_cast< SimTerrain * >( * i ) ) != 0 )
break;
}
if( terr )
{
// check if attaching a new terain
if( terr != terrain )
{
deleteTerrain();
terrain = terr;
deleteNotify( terrain );
if( !getGridFile() )
return( false );
newLandscaper();
// load in the named selections associated with this grid file
// create the selection name ( just tack on a .sel )
char * selName = new char[ strlen( getGridFile()->getFileName() ) +
strlen( ".sel" ) + 1 ];
sprintf( selName, "%s.sel", getGridFile()->getFileName() );
// save off the named selections
namedSelections.load( selName );
delete [] selName;
loadMatList( getGridFile()->getMaterialListName() );
}
setVars();
currentSel.createMap( size.x << blockShift,
size.y << blockShift );
// set the max detail
pinDetailMax = getMaxBrushDetail() - 1;
// set the current filename
ResourceManager * resManager = SimResource::get( manager );
ResourceObject * obj = resManager ? resManager->find( getGridFile()->getFileName() ) : NULL;
if( !obj )
return( false );
CMDConsole::getLocked()->setVariable( "$TED::currFile", avar("%s\\%s", obj->filePath, obj->fileName ) );
return( true );
}
return( false );
}
// lock the material list
void SimTed::lockMatList()
{
TSMaterialList *mList = getGridFile()->getMaterialList();
if( mList && (! mList->isLocked() ) )
mList->lock( *SimResource::get( manager ), true );
}
void SimTed::deleteTerrain()
{
if( terrain )
{
clearNotify( terrain );
terrain->deleteObject();
terrain = NULL;
}
}
void SimTed::newLandscaper()
{
AssertFatal( terrain != 0, "Terrain cannot be null!" );
// remove current landscaper
if( landscaper )
{
clearNotify( landscaper );
landscaper->deleteObject( );
}
// create a new landscaper object
landscaper = new LSMapper;
manager->addObject( landscaper );
manager->assignName( landscaper, "LandScapeMapper" );
deleteNotify( landscaper );
landscaper->create( terrain );
}
bool SimTed::loadMatList( const char * matListName )
{
if ( !matListName )
return ( false );
const char *mname = extendName( matListName, ".dml" );
const char *gname = fixName( matListName, ".grid.dat" );
const char *rname = fixName( matListName, ".plr" );
// this function changes the material list name, which will
// free 'matListName' out from under us - must re-get material
// list name
landscaper->setTextures( mname, gname );
matListName = const_cast<char*>(getGridFile()->getMaterialListName());
// attemp to load the plr file, then attempt to load a dat file
if( !landscaper->setRules( rname ) )
{
// delete the string and recreate
delete [] const_cast<char *>( rname );
rname = fixName( matListName, ".rules.dat" );
// attempt load as a dat file
landscaper->setRules( rname );
}
getGridFile()->setMaterialListName( matListName );
delete [] const_cast<char*>( rname );
delete [] const_cast<char*>( gname );
delete [] const_cast<char*>( mname );
return( true );
}
// set the extension - requires that first char of extn is a '.'
// to work correctly
char * SimTed::extendName( const char * fname, const char * extn )
{
if( fname )
{
char * current = const_cast<char*>(fname) + strlen(fname);
while(current-- != fname)
if(*current == '.')
break;
int len = current - fname;
int extnLen = extn ? strlen(extn) : 0;
char * retStr = new char[ len + extnLen + 1 ];
memcpy(retStr,fname,len);
if(extn)
memcpy(retStr+len,extn,extnLen);
retStr[len+extnLen] = '\0';
return(retStr);
}
return (NULL);
}
// copys the extension onto the first part of a base name
// -- fixName( "mars.terrain.dml", "grid.dat" ) will return "mars.grid.dat"
char * SimTed::fixName( const char * fname, const char * extn )
{
if( fname )
{
// get a large enough buffer
int len = strlen( fname ) + 1;
if( extn )
len += strlen( extn );
char * retStr = new char[ len ];
strcpy( retStr, fname );
char * curr = retStr;
// get to a place to cut to
while( *curr && ( *curr != '.' ) )
curr++;
// add the extension or terminate the string
if( extn )
sprintf( curr, extn );
else
*curr = 0;
return( retStr );
}
return( NULL );
}
void SimTed::relight( bool hires )
{
// make sure terrain exists
if( terrain )
{
SimActionEvent *ev = new SimActionEvent;
ev->action = hires ? MoveDown : MoveUp;
manager->postCurrentEvent( terrain, ev );
}
}
// ------------------
// undo/redo stuff
// ------------------
bool SimTed::SelectionStack::load( const char * file )
{
FileRStream stream;
// clear the stack
clear();
// open the file
if( !stream.open( file ) )
return( false );
// read the size
int numSelections;
if( !stream.read( sizeof( int ), &numSelections ) )
return( false );
// go through the selections
for( int i = 0; i < numSelections; i++ )
{
// read the name len
int nameLen;
if( !stream.read( sizeof( int ), &nameLen ) )
return( false );
// allocate some space
char * name = new char[ nameLen + 1 ];
if( !name )
return( false );
memset( name, 0, nameLen + 1 );
// read the name
if( !stream.read( nameLen, name ) )
{
delete [] name;
return( false );
}
// create a selection
SimTed::Selection * sel = new SimTed::Selection;
if( !sel )
{
delete [] name;
return( false );
}
// assign the name and delete our allocated one
sel->name = name;
delete [] name;
// read in the number of poins
int numPoints;
if( !stream.read( sizeof( int ), &numPoints ) )
{
delete sel;
return( false );
}
// read in all the points
for( int j = 0; j < numPoints; j++ )
{
Point2I pos;
if( !stream.read( sizeof( Point2I ), &pos ) )
{
delete sel;
return( false );
}
// add to the selection
sel->addPoint( pos );
}
// add the selection to the stack
push( sel );
}
return( true );
}
void SimTed::SelectionStack::clear()
{
SimTed::Selection * sel;
while( 1 )
{
// grab the first selection and delete it
sel = pop();
if( !sel )
return;
delete sel;
}
}
bool SimTed::SelectionStack::save( const char * file )
{
FileWStream stream;
// open the file
if( !stream.open( file ) )
return( false );
// write out the size
int numSelections = getSize();
if( !stream.write( sizeof( int ), &numSelections ) )
return( false );
// go through the selections
for( int i = 0; i < numSelections; i++ )
{
// get the length of the name of this selection
int nameLen = strlen( selections[i]->name.c_str() );
if( !stream.write( sizeof( int ), &nameLen ) )
return( false );
// write out the name
if( !stream.write( nameLen, selections[i]->name.c_str() ) )
return( false );
// get the number of points and write out
int numPoints = selections[i]->points.getSize();
if( !stream.write( sizeof( int ), &numPoints ) )
return( false );
// go through the points
for( int j = 0; j < numPoints; j++ )
{
if( !stream.write( sizeof( Point2I ), &selections[i]->points[j].pos ) )
return( false );
}
}
return( true );
}
void SimTed::SelectionStack::setLimit( int num )
{
if( num > 0 )
{
// remove some if needed
while( selections.size() > num )
{
delete selections[ 0 ];
selections.erase( 0 );
}
limit = num;
}
}
SimTed::Selection * SimTed::SelectionStack::pop()
{
// make sure has some stuff in it
if( selections.size() )
{
SimTed::Selection * sel = selections[ selections.size() - 1 ];
selections.pop_back();
return( sel );
}
return( NULL );
}
void SimTed::SelectionStack::push( SimTed::Selection * sel )
{
// add to the stack
selections.push_back( sel );
if( selections.size() >= limit )
{
delete selections[ 0 ];
selections.erase( 0 );
}
}
SimTed::SelectionStack::SelectionStack() :
limit( 100 )
{
}
SimTed::SelectionStack::~SelectionStack()
{
for( int i = 0; i < selections.size(); i++ )
delete selections[i];
}
void SimTed::undo()
{
SimTed::Selection * selection;
// get the selection
selection = undoStack.pop();
if( !selection )
return;
// add to the redo stack
SimTed::Selection * redoSel = new SimTed::Selection;
// go throught the selection and set each of the info's
for( unsigned int i = 0; i < selection->points.getSize(); i++ )
{
// add to the redo
SimTed::Selection::Info info;
if( getInfo( selection->points[i].pos, info ) )
redoSel->addPoint( info );
setInfo( selection->points[i] );
}
// copy the pin info
redoSel->pinArray = selection->pinArray;
// set the flags
redoSel->undoFlags = selection->undoFlags;
processUndo( *selection, true );
delete selection;
// put into the redo stack
redoStack.push( redoSel );
}
void SimTed::redo()
{
SimTed::Selection * selection;
// get the selection
selection = redoStack.pop();
if( !selection )
return;
// add a undo selection
SimTed::Selection * undoSel = new SimTed::Selection;
// go throught the selection and set each of the info's
for( unsigned int i = 0; i < selection->points.getSize(); i++ )
{
// add to the undo
SimTed::Selection::Info info;
if( getInfo( selection->points[i].pos, info ) )
undoSel->addPoint( info );
setInfo( selection->points[i] );
}
// copy the pin info
undoSel->pinArray = selection->pinArray;
// set the flags
undoSel->undoFlags = selection->undoFlags;
processUndo( *selection, false );
delete selection;
// add to the undo stack
undoStack.push( undoSel );
}
// usually does not need to know if this is an undo or a redo operation
void SimTed::processUndo( Selection & sel, bool undo )
{
// look at the flags
if( sel.undoFlags & Selection::relight )
relight(false);
if( ( sel.undoFlags & Selection::landscape ) && landscaper )
landscaper->applyTextures();
if( sel.undoFlags & Selection::flushTextures )
flushTextures();
// go through and un/pin all the pieces
if( ( sel.undoFlags & Selection::pin ) || ( sel.undoFlags & Selection::unpin ) )
{
for( int i = 0; i < sel.pinArray.size(); i++ )
{
Selection::pinInfo info = sel.pinArray[i];
// undo resets back to last value, redo just sets the flag according to the action
if( undo )
info.gridBlock->pinSquare( info.detail, info.pos, info.detail, info.val, NULL );
else
info.gridBlock->pinSquare( info.detail, info.pos, info.detail,
( sel.undoFlags & Selection::pin ) ? true : false, NULL );
}
}
}
// ---------------------------------------------------------
// selection stuff
// ---------------------------------------------------------
bool SimTed::loadSel( const char * name )
{
Selection sel;
// load the selection
if( !sel.load( name ) )
return( false );
// float it
floatSelection( sel );
floatPasteVal = pasteVal;
return( true );
}
bool SimTed::saveCurrentSel( const char * name )
{
Selection sel;
// check if there are points
if( !currentSel.points.getSize() )
return( false );
Point2I offset = currentSel.points[0].pos;
// go though all of the selection
for( unsigned int i = 0; i < currentSel.points.getSize(); i++ )
{
// get the info ( the current selection only has pos as valid )
Selection::Info info;
if( getInfo( currentSel.points[i].pos, info ) )
{
// adjust the point
info.pos.x -= offset.x;
info.pos.y -= offset.y;
// add to the copy selection
sel.addPoint( info );
}
}
// save it off
return( sel.save( name ) );
}
SimTed::Selection::Selection() :
name( "" ),
undoFlags( 0 ),
mapped( false ),
map( NULL ),
mapWidth( 0 ),
mapHeight( 0 ),
mapSize( 0 )
{
points.setSize( 0, 256 );
}
SimTed::Selection::~Selection()
{
// delete the map if it exists
if( mapped )
deleteMap();
}
void SimTed::Selection::createMap( int width, int height )
{
if( mapped )
deleteMap();
// get the width/height
mapWidth = width;
mapHeight = height;
mapSize = ( width * height );
// allocate the space
map = new int[ mapSize ];
AssertFatal( map, "Failed to allocate memory for selection map." );
// set the flag
mapped = true;
// reset the map
clearMap();
fillMap();
}
void SimTed::Selection::deleteMap()
{
if( map )
{
delete [] map;
map = NULL;
}
mapped = false;
}
void SimTed::Selection::clearMap()
{
if( !mapped || !map )
return;
// just go through
for( int i = 0; i < mapSize; i++ )
map[i] = -1;
}
void SimTed::Selection::fillMap()
{
if( !mapped || !map )
return;
// set the map location
for( unsigned int i = 0; i < points.getSize(); i++ )
{
// set the index
map[ points[i].pos.x +
( points[i].pos.y * mapWidth ) ] = i;
}
}
void SimTed::Selection::addPoint( const Info & info )
{
// check if mapped or not
if( mapped )
{
int index = info.pos.x + ( info.pos.y * mapWidth );
if( map[index] >= 0 )
return;
// set the index
map[index] = ( int )points.getSize();
// add the point
points.add( info );
}
else
{
if( !pointInSel( info.pos ) )
points.add( info );
}
}
void SimTed::Selection::addPoint( const Point2I & pnt )
{
// check if mapped or not
if( mapped )
{
int index = pnt.x + ( pnt.y * mapWidth );
if( map[index] >= 0 )
return;
map[index] = ( int )points.getSize();
Info info;
info.pos = pnt;
points.add( info );
}
else
{
if( !pointInSel( pnt ) )
{
Info info;
info.pos = pnt;
points.add( info );
}
}
}
void SimTed::Selection::removePoint( const Point2I & pnt )
{
// a tad tricky if mapped - is EXTREMELY tied to
// the infoarray class
if( mapped )
{
unsigned int index = pnt.x + ( pnt.y * mapWidth );
// check if exists
if( map[index] < 0 )
return;
// check if not the last element, and then move the
// index's
if( map[index] < ( int )( points.getSize() - 1 ) )
{
Point2I pos = points[ points.getSize() - 1 ].pos;
int lastIndex = pos.x + ( pos.y * mapWidth );
map[lastIndex] = ( int )map[index];
// remove it
points.remove( map[index] );
// clear this position
map[index] = -1;
}
else
{
// remove the last pnt
points.remove( map[index] );
map[index] = -1;
}
}
else
{
for( unsigned int i = 0; i < points.getSize(); i++ )
{
if( points[i].pos == pnt )
{
points.remove( i );
return;
}
}
}
}
void SimTed::fillInfo( Selection & sel )
{
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Selection::Info info;
getInfo( sel.points[i].pos, info );
sel.points[i] = info;
}
}
void SimTed::Selection::clear()
{
if( mapped )
clearMap();
points.clear();
}
bool SimTed::Selection::save( const char * file )
{
FileWStream stream;
// open the file
if( !stream.open( file ) )
return( false );
int numPoints = ( int )points.getSize();
// write the number of points
if( !stream.write( sizeof( int ), &numPoints ) )
return( false );
// go through and write the info out
for( unsigned int i = 0; i < points.getSize(); i++ )
{
if( !stream.write( sizeof( Selection::Info ), &points[i] ) )
return( false );
}
return( true );
}
bool SimTed::Selection::load( const char * file )
{
FileRStream stream;
// clear out the file
clear();
// open the file
if( !stream.open( file ) )
return( false );
int numPoints;
// read the number of points
if( !stream.read( sizeof( int ), &numPoints ) )
return( false );
// go through the points
for( int i = 0; i < numPoints; i++ )
{
Info info;
if( !stream.read( sizeof( Selection::Info ), &info ) )
return( false );
addPoint( info );
}
return( true );
}
bool SimTed::Selection::pointInSel( const Point2I & pnt )
{
// if( ( pnt.x == -1 ) || ( pnt.y == -1 ) )
// return( false );
// check if mapped or not
if( mapped )
{
int index = pnt.x + ( pnt.y * mapWidth );
if( map[index] >= 0 )
return( true );
}
else
{
for( unsigned int i = 0; i < points.getSize(); i++ )
if( points[i].pos == pnt )
return( true );
}
return( false );
}
bool SimTed::setInfo( const SimTed::Selection::Info & info )
{
// set the stuff
if( !setHeight( info.pos, info.height.height ) )
return( false );
if( !setMaterial( info.pos, info.material ) )
return( false );
return( true );
}
bool SimTed::getInfo( const Point2I& pos, SimTed::Selection::Info & info )
{
GridBlock::Material * mat = getMaterial( pos );
GridBlock::Height height;
height.height = getHeight( pos );
// check if got the material information
if( mat )
{
// set the info
info.pos = pos;
info.height = height;
info.material = *mat;
return( true );
}
return( false );
}
void SimTed::setSelectionVars( SimTed::Selection & sel, RectI & bound,
Point2F & center, float & radius )
{
// reset the info
bound = NULLRECT;
center.x = center.y = -1;
radius = 0.0;
// make sure there exist some points
if( !sel.points.getSize() )
return;
int left, right, top, bottom;
// set the initial val
left = right = sel.points[0].pos.x;
top = bottom = sel.points[0].pos.y;
// go through all the points
for( unsigned int i = 0; i < sel.points.getSize(); i++ )
{
Point2I p = sel.points[i].pos;
// set the bounds
if( p.x < left )
left = p.x;
else if( p.x > right )
right = p.x;
if( p.y < top )
top = p.y;
else if( p.y > bottom )
bottom = p.y;
}
// set the bound dimensions
bound.upperL = Point2I( left, top );
bound.lowerR = Point2I( right, bottom );
// setup the center pnt
center.x = ( float )( left + right ) / 2.0;
center.y = ( float )( top + bottom ) / 2.0;
// get the radius
float rx = float( right - left ) / 2.0;
float ry = float( bottom - top ) / 2.0;
radius = sqrt( ( rx * rx ) + ( ry * ry ) );
}
const char * SimTed::getNamedSelection( int index )
{
// check for invalid
if( index >= getNumNamedSelections() )
return( NULL );
// get it
return( namedSelections.selections[index]->name.c_str() );
}
bool SimTed::addNamedSelection( const char * name )
{
// check the name
if( !name )
return( false );
// grow in needed
if( namedSelections.getSize() >= namedSelections.getLimit() )
namedSelections.setLimit( namedSelections.getLimit() + 1 );
SimTed::Selection * selection;
selection = new SimTed::Selection;
// set the name
selection->name = name;
// go through and add all of the currently selected points to this
for( unsigned int i = 0; i < currentSel.points.getSize(); i++ )
selection->points.add( currentSel.points[i] );
// add to the stack
namedSelections.push( selection );
return( true );
}
bool SimTed::removeNamedSelection( const char * name )
{
if( !name )
return( false );
Selection * sel;
// go through all the selections and find this one..
// if cannot just return with no error
for( int i = 0; i < namedSelections.getSize(); i++ )
{
sel = namedSelections.selections[i];
// is this the $$$?
if( sel->name == name )
{
// remove this one
delete namedSelections.selections[ i ];
namedSelections.selections.erase( i );
return( true );
}
}
return( true );
}
bool SimTed::selectNamedSelection( const char * name )
{
if( !name )
return( false );
Selection * sel;
// go through all the selections and find this one..
// if cannot just return with no error
for( int i = 0; i < namedSelections.getSize(); i++ )
{
sel = namedSelections.selections[i];
// is this the $$$?
if( sel->name == name )
{
// clear the current selection
currentSel.clear();
// select all the ones in this named selection to the current
for( unsigned int j = 0; j < sel->points.getSize(); j++ )
currentSel.addPoint( sel->points[j] );
return( true );
}
}
return( true );
}
void SimTed::Selection::InfoArray::setSize( unsigned int size, unsigned int grow )
{
growSize = grow;
if( !arraySize || ( size >= arraySize ) )
{
arraySize = size + growSize;
Info * newElements = new Info[ arraySize ];
// copy the elements
for( unsigned int i = 0; i < numElements; i++ )
newElements[i] = elements[i];
delete [] elements;
elements = newElements;
}
numElements = size;
}
void SimTed::Selection::InfoArray::remove( unsigned int index )
{
if( index < numElements )
{
numElements--;
// check for removal of last item
if( index < numElements )
elements[ index ] = elements[ numElements ];
}
}
void SimTed::Selection::InfoArray::add( Info item )
{
// adjust the size
setSize( numElements + 1, growSize );
// add to the last item
elements[ numElements - 1 ] = item;
}
|
[
"altimormc@gmail.com"
] |
altimormc@gmail.com
|
a32bac06e6b41e4a46fd017322bdd8ece8dec98a
|
95f4f325d36d52b4950455fd8b05e8932c5c4273
|
/src/Player.h
|
3be304476c738ef380950893bc702e7db75b6ae8
|
[
"MIT"
] |
permissive
|
Ma5onic/PlaySK-Piano-Roll-Reader
|
4c5d3b9d008f2cf111249beec72a31349665c931
|
80197316e58b350620dc6862a59308c421cc1593
|
refs/heads/master
| 2023-07-27T16:46:26.495898
| 2020-02-15T13:59:37
| 2020-02-15T13:59:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,921
|
h
|
#pragma once
#include <mmsystem.h>
#include <opencv2/core/core.hpp>
#include "json11.hpp"
#define KeyNum 88
#define MAXNoteOnFrames 10
typedef struct tagTRACKER_HOLE {
int x;
int y;
int w;
int h;
int th_on; // hole on thereshold
int th_off; // hole off thereshold
} TRACKER_HOLE;
class Player{
public:
Player();
virtual ~Player();
int Emulate(cv::Mat &frame, const HMIDIOUT &hm);
virtual int LoadPlayerSettings();
virtual int NoteAllOff(const HMIDIOUT &hm);
virtual int GetMinVelocity();
virtual int GetMaxVelocity();
int GetBassVelocity() { return m_iBassStackVelo; }
int GetTrebleVelocity() { return m_iTrebleStackVelo; }
void SetEmulateOn() { m_bEmulateOn = true; }
void SetEmulateOff() { m_bEmulateOn = false; }
void SetRollOffset(int iOffset) { m_iTrackingOffset = iOffset; }
int GetRollOffset() { return m_iTrackingOffset; }
void SetNoteOnFrames(int iFrames) { m_iNoteOnFrames = iFrames; }
int GetNoteOnFrames() { return m_iNoteOnFrames; }
void SetFrameRate(double dfps) { m_dFrameRate = dfps; }
protected:
// tracker hole status // -2:on->off -1:off 1:off->on 2:on
enum NoteState {
offTriger = -2,
off = -1,
onTriger = 1,
on = 2,
};
NoteState m_NoteOn[KeyNum];
NoteState m_SusteinPedalOn, m_SoftPedalOn;
// tracker hole
TRACKER_HOLE m_rcSustainPedal, m_rcSoftPedal;
TRACKER_HOLE m_rcNote[KeyNum];
// split point
// bass < [split point] <= treble, with 0 start index
UINT m_uiStackSplitPoint;
// note-on delay
int m_iNoteOnFrames;
int m_iNoteOnCnt[KeyNum];
int m_iTrackingOffset;
double m_dFrameRate;
int m_iBassStackVelo, m_iTrebleStackVelo;
bool m_bEmulateOn;
virtual void EmulateVelocity(cv::Mat &frame);
void EmulatePedal(cv::Mat &frame);
void EmulateNote(cv::Mat &frame);
double GetAvgHoleBrightness(cv::Mat &frame, const TRACKER_HOLE &hole);
void DrawHole(cv::Mat &frame, const TRACKER_HOLE &hole, bool hole_on);
void SendMidiMsg(const HMIDIOUT &hm);
void SetHoleRectFromJsonObj(const json11::Json json, TRACKER_HOLE &rcSetHole);
void SetHoleRectListFromJsonObj(const json11::Json json, TRACKER_HOLE *prcSetHole, UINT rect_cnt);
void inline NoteOnMsg(int key, int velocity, const HMIDIOUT &g_hMidiOut) const{
DWORD dwMsg = velocity << 16 | key << 8 | 0x90;
midiOutShortMsg(g_hMidiOut, dwMsg);
}
void inline NoteOffMsg(int key, const HMIDIOUT &g_hMidiOut) const{
static const int iNoteOffVelocity = 90;
DWORD dwMsg = iNoteOffVelocity << 16 | key << 8 | 0x80;
midiOutShortMsg(g_hMidiOut, dwMsg);
}
void inline SusteinP(bool status, const HMIDIOUT &g_hMidiOut) const{
if (status) midiOutShortMsg(g_hMidiOut, 127 << 16 | 64 << 8 | 0xb0);
else midiOutShortMsg(g_hMidiOut, 64 << 8 | 0xb0);
}
void inline SoftP(bool status, const HMIDIOUT &g_hMidiOut) const{
if (status) midiOutShortMsg(g_hMidiOut, 127 << 16 | 67 << 8 | 0xb0);
else midiOutShortMsg(g_hMidiOut, 67 << 8 | 0xb0);
}
};
|
[
"fxtch686@yahoo.co.jp"
] |
fxtch686@yahoo.co.jp
|
df7ee0d9b03ead708380db03634c05109f6f133a
|
3ff1fe3888e34cd3576d91319bf0f08ca955940f
|
/dsgc/src/v20190723/model/DescribeDSPAAssessmentRiskLevelTrendRequest.cpp
|
786b9f22d72eb5a023ebe8d1a58b90d30e772aee
|
[
"Apache-2.0"
] |
permissive
|
TencentCloud/tencentcloud-sdk-cpp
|
9f5df8220eaaf72f7eaee07b2ede94f89313651f
|
42a76b812b81d1b52ec6a217fafc8faa135e06ca
|
refs/heads/master
| 2023-08-30T03:22:45.269556
| 2023-08-30T00:45:39
| 2023-08-30T00:45:39
| 188,991,963
| 55
| 37
|
Apache-2.0
| 2023-08-17T03:13:20
| 2019-05-28T08:56:08
|
C++
|
UTF-8
|
C++
| false
| false
| 4,131
|
cpp
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dsgc/v20190723/model/DescribeDSPAAssessmentRiskLevelTrendRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Dsgc::V20190723::Model;
using namespace std;
DescribeDSPAAssessmentRiskLevelTrendRequest::DescribeDSPAAssessmentRiskLevelTrendRequest() :
m_dspaIdHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_templateIdHasBeenSet(false)
{
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_dspaIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DspaId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_dspaId.c_str(), allocator).Move(), allocator);
}
if (m_startTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_templateIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TemplateId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_templateId.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetDspaId() const
{
return m_dspaId;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetDspaId(const string& _dspaId)
{
m_dspaId = _dspaId;
m_dspaIdHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::DspaIdHasBeenSet() const
{
return m_dspaIdHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetStartTime() const
{
return m_startTime;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetStartTime(const string& _startTime)
{
m_startTime = _startTime;
m_startTimeHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetEndTime() const
{
return m_endTime;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
string DescribeDSPAAssessmentRiskLevelTrendRequest::GetTemplateId() const
{
return m_templateId;
}
void DescribeDSPAAssessmentRiskLevelTrendRequest::SetTemplateId(const string& _templateId)
{
m_templateId = _templateId;
m_templateIdHasBeenSet = true;
}
bool DescribeDSPAAssessmentRiskLevelTrendRequest::TemplateIdHasBeenSet() const
{
return m_templateIdHasBeenSet;
}
|
[
"tencentcloudapi@tencent.com"
] |
tencentcloudapi@tencent.com
|
22c5f99701e09f637a33e660f4027984a3a8bfcf
|
14ce793aedf5fcc1a685ee7173e1333210b46553
|
/src/qtest/abuild-basic/data/msvc/main.cc
|
a8c8b471d572e37841515afc09ac8e3a78cfb510
|
[
"Apache-2.0",
"Artistic-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-1.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
abuild-org/abuild
|
a569fca784b1a113f65c510233b9d97773c84674
|
54c003b2bf2e544bb25d7727fb4ba6297bc4a61e
|
refs/heads/master
| 2020-11-27T07:39:14.413974
| 2019-12-20T23:38:41
| 2019-12-20T23:38:41
| 229,351,827
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 422
|
cc
|
#include <iostream>
#include <cstring>
int main(int argc, char* argv[])
{
if ((argc == 2) && (std::strcmp(argv[1], "ver") == 0))
{
std::cout << _MSC_VER << std::endl;
return 0;
}
try
{
#ifdef _MANAGED
std::cout << "managed" << std::endl;
#else
std::cout << "not managed" << std::endl;
#endif
throw 5;
}
catch (int x)
{
std::cout << "threw " << x << std::endl;
}
return 0;
}
|
[
"ejb@ql.org"
] |
ejb@ql.org
|
24748b0bd213c5e46c480b492502be9f6aa0efb2
|
7ccf448165ef01b8c70fc084e2c767a6971c1a5e
|
/lexis_syntax.cpp
|
2aa64f711ea8dcedbe778c1791bd7fb4e6e2ecb1
|
[] |
no_license
|
kolomeytsev/game-manager
|
a650a12d3e19790f7bf64d45e7d0a1a3ea560789
|
21634484e1533771374881152db980c5e30db14e
|
refs/heads/master
| 2021-05-31T19:04:38.670128
| 2016-03-27T11:04:56
| 2016-03-27T11:04:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 24,816
|
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <typeinfo>
enum type_of_lex
{ keyword, function, function_with_param, function_without_param,
label, variable, number, string, assignment, separator,
error_funct, error_keyword, error };
enum type_of_state { H, N, F, L, V, K, A, S, ERR };
struct Lexeme_list {
int num_str;
type_of_lex type;
char* lex;
struct Lexeme_list* next;
};
class PolizElem;
struct PolizItem {
PolizElem* elem;
struct PolizItem* next;
};
struct StructVar {
char *name;
int value;
};
struct VarTable { // table->elem->name
StructVar* elem;
struct VarTable* next;
};
struct LabelTable {
char* name;
PolizItem* pointer;
struct LabelTable* next;
};
class PolizEx {
};
class PolizExNotInt: public PolizEx {
public:
PolizExNotInt(PolizElem *elem) {}
};
class PolizExNotLabel: public PolizEx {
public:
PolizExNotLabel(PolizElem *elem) {}
};
class PolizExNotConst: public PolizEx {
public:
PolizExNotConst(PolizElem *elem) {}
};
class PolizElem {
public:
virtual ~PolizElem() {}
virtual void Evaluate(PolizItem **stack,
PolizItem **cur_cmd) const = 0;
protected:
static void Push(PolizItem **stack, PolizElem *elem);
static PolizElem* Pop(PolizItem **stack);
};
void PolizElem::Push(PolizItem **stack, PolizElem *elem)
{
//printf("push\n");
PolizItem* tmp = new PolizItem;
tmp->elem = elem;
tmp->next = *stack;
*stack = tmp;
}
PolizElem* PolizElem::Pop(PolizItem **stack)
{
//printf("pop\n");
PolizItem* tmp = *stack;
PolizElem* tmp_elem = tmp->elem;
*stack = (*stack)->next;
delete tmp;
return tmp_elem;
}
class PolizConst: public PolizElem {
public:
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
Push(stack, Clone());
*cur_cmd = (*cur_cmd)->next;
}
virtual PolizElem* Clone() const = 0;
};
class PolizInt: public PolizConst {
int value;
public:
PolizInt(int a) { value = a; }
virtual ~PolizInt() {}
virtual PolizElem* Clone()const {
return new PolizInt(value);
}
int Get() const {
return value;
}
};
class PolizString: public PolizConst {
char *str;
public:
PolizString(char *s) { str = s; }
virtual ~PolizString() { delete str;}
virtual PolizElem* Clone() const {
int len;
len = strlen(str);
char *s = new char[len+1];
for (int i = 0; i < len + 1; i++)
s[i] = str[i];
return new PolizString(s);
}
char *Get() const {
return str;
}
};
class PolizVarAddr: public PolizConst {
VarTable* addr;
public:
PolizVarAddr(VarTable* a) { addr = a; }
virtual ~PolizVarAddr() {}
virtual PolizElem* Clone() const {
return new PolizVarAddr(addr);
}
VarTable* Get() const {
return addr;
}
};
class PolizLabel: public PolizConst {
char *name;
PolizItem* value;
public:
PolizLabel(char *s, PolizItem* a) {
name = s;
value = a;
}
virtual ~PolizLabel() {}
virtual PolizElem* Clone() const {
return new PolizLabel(name, value);
}
PolizItem* Get() const {
return value;
}
char* Get_name() const {
return name;
}
void set_addr(PolizItem *ptr) {
value = ptr;
}
};
class PolizFunction: public PolizElem {
public:
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
PolizElem *res = EvaluateFun(stack);
if (res)
Push(stack, res);
*cur_cmd = (*cur_cmd)->next;
}
virtual PolizElem* EvaluateFun(PolizItem **stack) const = 0;
};
class PolizVar: public PolizFunction {
public:
};
class PolizSell: public PolizFunction {
public:
PolizSell() {}
virtual ~PolizSell() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
printf("sell %d, %d\n", i2->Get(), i1->Get());
delete operand1;
delete operand2;
return 0;
}
};
class PolizBuy: public PolizFunction {
public:
PolizBuy() {}
virtual ~PolizBuy() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
printf("buy %d, %d\n", i2->Get(), i1->Get());
delete operand1;
delete operand2;
return 0;
}
};
class PolizProd: public PolizFunction {
public:
PolizProd() {}
virtual ~PolizProd() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
printf("prod %d\n", i1->Get());
delete operand1;
return 0;
}
};
class PolizBuild: public PolizFunction {
public:
PolizBuild() {}
virtual ~PolizBuild() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
printf("build %d\n", i1->Get());
delete operand1;
return 0;
}
};
class PolizEndTurn: public PolizFunction {
public:
PolizEndTurn() {}
virtual ~PolizEndTurn() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
printf("end turn\n");
return 0;
}
};
class PolizPrint: public PolizFunction {
public:
PolizPrint() {}
virtual ~PolizPrint() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) {
PolizString *i1 = dynamic_cast<PolizString*>(operand1);
if (!i1) throw PolizExNotConst(operand1);
printf("<%s>\n", i1->Get());
} else {
printf("<%d>\n", i1->Get());
}
delete operand1;
return 0;
}
};
class PolizFunNOP: public PolizFunction {
int a;
public:
PolizFunNOP() { a = 505; }
virtual ~PolizFunNOP() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const {
return 0;
}
};
class PolizFunPlus: public PolizFunction {
public:
PolizFunPlus() {}
virtual ~PolizFunPlus() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i1->Get() + i2->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMinus: public PolizFunction {
public:
PolizFunMinus() {}
virtual ~PolizFunMinus() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get() - i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMult: public PolizFunction {
public:
PolizFunMult() {}
virtual ~PolizFunMult() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i1->Get() * i2->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunDiv: public PolizFunction {
public:
PolizFunDiv() {}
virtual ~PolizFunDiv() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get()/i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunMod: public PolizFunction {
public:
PolizFunMod() {}
virtual ~PolizFunMod() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
int res = i2->Get()%i1->Get();
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunGreater: public PolizFunction {
public:
PolizFunGreater() {}
virtual ~PolizFunGreater() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() > i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunLess: public PolizFunction {
public:
PolizFunLess() {}
virtual ~PolizFunLess() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() < i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
class PolizFunEqual: public PolizFunction {
public:
PolizFunEqual() {}
virtual ~PolizFunEqual() {}
virtual PolizElem* EvaluateFun(PolizItem **stack) const
{
PolizElem *operand1 = Pop(stack);
PolizInt *i1 = dynamic_cast<PolizInt*>(operand1);
if (!i1) throw PolizExNotInt(operand1);
PolizElem *operand2 = Pop(stack);
PolizInt *i2 = dynamic_cast<PolizInt*>(operand2);
if (!i2) throw PolizExNotInt(operand2);
bool t = i2->Get() == i1->Get();
int res;
if (t) res = 1;
else res = 0;
delete operand1;
delete operand2;
return new PolizInt(res);
}
};
void lprint(PolizItem* lst);
class PolizOpGo: public PolizElem {
public:
PolizOpGo() {}
virtual ~PolizOpGo() {}
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
printf("OpGO!\n");
PolizElem *operand1 = Pop(stack);
PolizLabel *lab = dynamic_cast<PolizLabel*>(operand1);
if (!lab) throw PolizExNotLabel(operand1);
PolizItem *addr = lab->Get();
//lprint(addr->next); //print string
*cur_cmd = addr;
delete operand1;
}
};
class PolizOpGoFalse: public PolizElem {
public:
PolizOpGoFalse() {}
virtual ~PolizOpGoFalse() {}
virtual void Evaluate(PolizItem **stack, PolizItem **cur_cmd) const
{
PolizElem *operand1 = Pop(stack);
PolizLabel *lab = dynamic_cast<PolizLabel*>(operand1);
if (!lab) throw PolizExNotLabel(operand1);
PolizItem *addr = lab->Get();
PolizElem *operand2 = Pop(stack);
PolizInt *val = dynamic_cast<PolizInt*>(operand2);
if (!val) throw PolizExNotInt(operand2);
if (val==0)
*cur_cmd = addr;
else
*cur_cmd = (*cur_cmd)->next;
delete operand1;
delete operand2;
}
};
class SyntaxAnalizer {
Lexeme_list *cur;
Lexeme_list *list;
Lexeme_list *pointer;
void S();
void assignment_statement();
void goto_statement();
void if_statement();
void game_statement();
void print_statement();
void expression();
void op1();
void ending1();
void op2();
void ending2();
void op3();
void ending3();
void funct();
void var();
void index();
void element();
void add_poliz_list(PolizElem* element) {
PolizItem *t = new PolizItem;
PolizItem *temp;
temp = poliz_list;
t->elem = element;
t->next = 0;
if (poliz_list == 0)
poliz_list = t;
else {
while (temp->next!=0)
temp = temp->next;
temp->next = t;
}
}
void add_label_list(PolizItem* p, char* s) {
LabelTable* t = new LabelTable;
LabelTable* temp;
temp = label_list;
t->name = s;
t->pointer = p;
t->next = 0;
if (label_list==0)
label_list = t;
else {
while (temp->next!=0)
temp = temp->next;
temp->next = t;
}
}
void next()
{
cur = pointer;
if ((pointer->next!=0)&&(strcmp(pointer->lex, ".")!=0))
pointer = pointer->next;
}
PolizItem* search_address(char *name);
bool is_first_label(char *name);
void add_address(PolizItem *p, char *name);
void add_address_poliz(PolizItem *p, char *name);
public:
void set_list(Lexeme_list *lst)
{
list = lst;
pointer = list;
poliz_list = 0;
label_list = 0;
var_list = 0;
}
void analyze();
PolizItem* poliz_list;
LabelTable* label_list;
VarTable* var_list;
};
class Exeption {
char *comment;
int nstr;
char *lexeme;
public:
Exeption(const char *cmt, int num, const char *lex);
Exeption(const Exeption& other);
~Exeption();
const char *GetComment() const
{
return comment;
}
int GetNstr() const
{
return nstr;
}
const char *GetLexeme() const
{
return lexeme;
}
private:
static char *strdup(const char *str);
};
Exeption::Exeption(const char *cmt, int num, const char *lex) {
comment = strdup(cmt);
nstr = num;
lexeme = strdup(lex);
}
Exeption::Exeption(const Exeption& other) {
comment = strdup(other.comment);
nstr = other.nstr;
lexeme = strdup(other.lexeme);
}
Exeption::~Exeption() {
delete[] comment;
}
char* Exeption::strdup(const char *str) {
char *res;
res = new char [strlen(str)+1];
strcpy(res, str);
return res;
}
void SyntaxAnalizer::analyze()
{
next();
S();
if (strcmp(cur->lex, ".")!=0)
throw Exeption("dot expected", cur->num_str, cur->lex);
}
void SyntaxAnalizer::S()
{
if ((cur->type == keyword)&&
(strcmp(cur->lex, "end")!=0)) {
if (strcmp(cur->lex, "if")==0) {
next();
if_statement();
S();
}
else
if (strcmp(cur->lex, "goto")==0) {
next();
goto_statement();
PolizOpGo* tmp = new PolizOpGo;
add_poliz_list(tmp);
S();
}
else
if (strcmp(cur->lex, "print")==0) {
next();
print_statement();
PolizPrint* tmp = new PolizPrint;
add_poliz_list(tmp);
S();
}
else
if (strcmp(cur->lex, "then")!=0) {
game_statement();
S();
}
else
throw Exeption("unexpected then", cur->num_str, cur->lex);
}
else
if (cur->type == variable) {
next();
assignment_statement();
S();
}
else
if (cur->type == label) {
PolizFunNOP* tmp = new PolizFunNOP;
add_poliz_list(tmp);
PolizItem* p = poliz_list;
while (p->next!=0)
p = p->next;
if (is_first_label(cur->lex))
add_label_list(p, cur->lex);
else {
add_address(p, cur->lex);
add_address_poliz(p, cur->lex); //doesn't work FUCK!!!!!!!
}
next();
if (strcmp(cur->lex, ">")!=0)
throw Exeption("'>' expected", cur->num_str, cur->lex);
next();
S();
}
else {
if (strcmp(cur->lex, "end")!=0)
throw Exeption("end expected", cur->num_str, cur->lex);
else
next();
}
}
void SyntaxAnalizer::if_statement()
{
expression();
if (strcmp(cur->lex, "then") != 0)
throw Exeption("then expected", cur->num_str, cur->lex);
next();
S();
if (strcmp(cur->lex, ";") != 0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::goto_statement()
{
if (cur->type != label)
throw Exeption("label expected", cur->num_str, cur->lex);
PolizItem* item = search_address(cur->lex);
PolizLabel* tmp = new PolizLabel(cur->lex, item); // 0 if goto @m...@m>
add_poliz_list(tmp);
if (item == 0)
add_label_list(0, cur->lex);
next();
if (strcmp(cur->lex, ";") !=0 )
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::print_statement()
{
if (cur->type == string) {
PolizString* tmp = new PolizString(cur->lex);
add_poliz_list(tmp);
next();
}
else
expression();
if (strcmp(cur->lex, ";") !=0 )
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::game_statement()
{
if (strcmp(cur->lex, "endturn")==0) {
PolizEndTurn* tmp = new PolizEndTurn();
add_poliz_list(tmp);
next();
} else
if ((strcmp(cur->lex,"prod")==0)||(strcmp(cur->lex,"build")==0)) {
bool is_prod = false;
if (strcmp(cur->lex, "prod")==0) is_prod = true;
next();
expression();
if (is_prod) {
PolizProd* tmp = new PolizProd();
add_poliz_list(tmp);
} else {
PolizBuild* tmp = new PolizBuild();
add_poliz_list(tmp);
}
}
else
if ((strcmp(cur->lex,"buy")==0)||(strcmp(cur->lex,"sell")==0)) {
bool is_buy = false;
if (strcmp(cur->lex, "buy")==0) is_buy = true;
next();
expression();
expression();
if (is_buy) {
PolizBuy* tmp = new PolizBuy();
add_poliz_list(tmp);
} else {
PolizSell* tmp = new PolizSell();
add_poliz_list(tmp);
}
}
if (strcmp(cur->lex,";")!=0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::assignment_statement()
{
if (cur->type == assignment)
next();
else
if (strcmp(cur->lex, "[")==0) { //index
next();
expression();
if (strcmp(cur->lex, "]")!=0)
throw Exeption("']' expected", cur->num_str, cur->lex);
next();
if (cur->type != assignment)
throw Exeption("':=' expected", cur->num_str, cur->lex);
next();
}
else
throw Exeption("':=' or index expected", cur->num_str, cur->lex);
expression();
if (strcmp(cur->lex,";")!=0)
throw Exeption("';' expected", cur->num_str, cur->lex);
next();
}
void SyntaxAnalizer::expression()
{
op1();
ending1();
}
void SyntaxAnalizer::op1()
{
op2();
ending2();
}
void SyntaxAnalizer::op2()
{
op3();
ending3();
}
void SyntaxAnalizer::op3()
{
if (cur->type==number) {
PolizInt* tmp = new PolizInt(atoi(cur->lex));
add_poliz_list(tmp);
next();
} else
if (cur->type==variable) {
next();
if (strcmp(cur->lex, "[")==0) { //index
next();
expression();
if (strcmp(cur->lex, "]")!=0)
throw Exeption("']' expected", cur->num_str, cur->lex);
next();
}
}
else
if (cur->type==function_without_param)
next();
else
if (cur->type==function_with_param) {
next();
if (strcmp(cur->lex, "(")!=0)
throw Exeption("'(' expected in funct",
cur->num_str, cur->lex);
next();
expression();
if (strcmp(cur->lex, ")")!=0)
throw Exeption("')' expected in funct",
cur->num_str, cur->lex);
next();
}
else
{
if (strcmp(cur->lex, "(")!=0)
throw Exeption("'(' expected", cur->num_str, cur->lex);
next();
expression();
if (strcmp(cur->lex, ")")!=0)
throw Exeption("')' expected", cur->num_str, cur->lex);
next();
}
}
void SyntaxAnalizer::ending3()
{
if ((strcmp(cur->lex, "*")==0)||
(strcmp(cur->lex, "/")==0)||
(strcmp(cur->lex, "%")==0)) {
bool is_mult = false;
bool is_div = false;
bool is_mod = false;
if (strcmp(cur->lex, "*")==0) is_mult = true;
if (strcmp(cur->lex, "/")==0) is_div = true;
if (strcmp(cur->lex, "%")==0) is_mod = true;
next();
op2();
if (is_mult) {
PolizFunMult* tmp = new PolizFunMult();
add_poliz_list(tmp);
}
if (is_div) {
PolizFunDiv* tmp = new PolizFunDiv();
add_poliz_list(tmp);
}
if (is_mod) {
PolizFunMod* tmp = new PolizFunMod();
add_poliz_list(tmp);
}
}
}
void SyntaxAnalizer::ending2()
{
if ((strcmp(cur->lex, "+")==0)||
(strcmp(cur->lex, "-")==0)) {
bool is_plus = false;
if (strcmp(cur->lex, "+")==0) is_plus = true;
next();
op1();
if (is_plus) {
PolizFunPlus* tmp = new PolizFunPlus();
add_poliz_list(tmp);
} else {
PolizFunMinus* tmp = new PolizFunMinus();
add_poliz_list(tmp);
}
}
}
void SyntaxAnalizer::ending1()
{
if ((strcmp(cur->lex, "=")==0)||
(strcmp(cur->lex, ">")==0)||
(strcmp(cur->lex, "<")==0)) {
bool is_greater = false;
bool is_less = false;
bool is_equal = false;
if (strcmp(cur->lex, ">")==0) is_greater = true;
if (strcmp(cur->lex, "<")==0) is_less = true;
if (strcmp(cur->lex, "=")==0) is_equal = true;
next();
expression();
if (is_greater) {
PolizFunGreater* tmp = new PolizFunGreater();
add_poliz_list(tmp);
}
if (is_less) {
PolizFunLess* tmp = new PolizFunLess();
add_poliz_list(tmp);
}
if (is_equal) {
PolizFunEqual* tmp = new PolizFunEqual();
add_poliz_list(tmp);
}
}
}
PolizItem* SyntaxAnalizer::search_address(char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("found1 %s\n", tmp->name);
return tmp->pointer;
}
tmp = tmp->next;
}
return 0;
}
bool SyntaxAnalizer::is_first_label(char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("found2 %s\n", tmp->name);
return false;
}
tmp = tmp->next;
}
printf("name first\n");
return true;
}
void SyntaxAnalizer::add_address(PolizItem *p, char *name)
{
LabelTable* tmp = label_list;
while (tmp!=0) {
if (strcmp(tmp->name, name)==0) {
printf("name was found\n");
tmp->pointer = p;
lprint(tmp->pointer);
return;
}
tmp = tmp->next;
}
}
void SyntaxAnalizer::add_address_poliz(PolizItem *p, char *name)
{
PolizItem *tmp;
while (tmp!=0) {
printf("xui\n");
PolizLabel *ptr = dynamic_cast<PolizLabel*>(tmp->elem);
if (ptr) {
printf("xui2\n");
if (strcmp(ptr->Get_name(), name)==0)
ptr->set_addr(p);
}
tmp = tmp->next;
}
}
class Executer {
PolizItem* stack;
PolizItem* prog;
public:
Executer(PolizItem *lst) {
prog = lst;
stack = 0;
}
void execute();
};
void lprint(PolizItem* lst)
{
while (lst!=0) {
PolizPrint* p2 = dynamic_cast<PolizPrint*>(lst->elem);
if (p2) printf("print\n");
PolizString* p1 = dynamic_cast<PolizString*>(lst->elem);
if (p1) printf("string: %s\n", p1->Get());
PolizInt* p3 = dynamic_cast<PolizInt*>(lst->elem);
if (p3) printf("int: %d\n", p3->Get());
PolizEndTurn* p4 = dynamic_cast<PolizEndTurn*>(lst->elem);
if (p4) printf("end_turn\n");
PolizBuild* p5 = dynamic_cast<PolizBuild*>(lst->elem);
if (p5) printf("build\n");
PolizProd* p6 = dynamic_cast<PolizProd*>(lst->elem);
if (p6) printf("prod\n");
PolizBuy* p7 = dynamic_cast<PolizBuy*>(lst->elem);
if (p7) printf("buy\n");
PolizSell* p8 = dynamic_cast<PolizSell*>(lst->elem);
if (p8) printf("sell\n");
PolizFunPlus* p9 = dynamic_cast<PolizFunPlus*>(lst->elem);
if (p9) printf("+\n");
PolizFunMinus* p10 = dynamic_cast<PolizFunMinus*>(lst->elem);
if (p10) printf("-\n");
PolizFunMult* p11 = dynamic_cast<PolizFunMult*>(lst->elem);
if (p11) printf("*\n");
PolizFunDiv* p12 = dynamic_cast<PolizFunDiv*>(lst->elem);
if (p12) printf("/\n");
PolizFunMod* p13 = dynamic_cast<PolizFunMod*>(lst->elem);
if (p13) printf("mod\n");
PolizFunGreater* p14= dynamic_cast<PolizFunGreater*>(lst->elem);
if (p14) printf(">\n");
PolizFunLess* p15= dynamic_cast<PolizFunLess*>(lst->elem);
if (p15) printf("<\n");
PolizFunEqual* p16= dynamic_cast<PolizFunEqual*>(lst->elem);
if (p16) printf("=\n");
PolizFunNOP* p17 = dynamic_cast<PolizFunNOP*>(lst->elem);
if (p17) printf("NOP\n");
PolizOpGo* p18 = dynamic_cast<PolizOpGo*>(lst->elem);
if (p18) printf("goto\n");
PolizLabel* p19 = dynamic_cast<PolizLabel*>(lst->elem);
if (p19) printf("label: %s\n", p19->Get_name());
lst = lst->next;
}
printf("\n");
}
void delete_poliz_list(PolizItem* lst)
{
if (lst!=0) {
delete_poliz_list(lst->next);
delete lst->elem;
delete lst;
}
}
void print_table_list(LabelTable *lst)
{
int t =0;
while (lst!=0) {
printf("label: %s\n", lst->name);
if (t==0) {
PolizInt* p5 = dynamic_cast<PolizInt*>(lst->pointer->next->elem);
if (p5) printf("label->next -> int\n");
}
t = 1;
lst = lst->next;
}
}
void Executer::execute() {
//lprint(prog);
while (prog!=0) {
prog->elem->Evaluate(&stack, &prog);
}
}
int main()
{
Automat a;
int c;
Lexeme_list *list;
c = getchar();
try {
for (;;) {
if (c==EOF) break;
a.feed_char(c);
a.run();
if (a.full_lex())
a.add_new_elem();
if (a.use_prev==0) {
if (c=='\n')
a.inc_nstr();
c = getchar();
}
if (a.is_long())
throw "too long name";
}
}
catch (const char *s) {
printf("Error: %s\n", s);
return 1;
}
a.print_list();
if (a.is_any_errors()) {
printf("Some lexical errors detected!\n");
return 1;
}
list = a.get_list();
PolizItem *lst; // PolizItem *lst
LabelTable *table_lst;
SyntaxAnalizer s;
s.set_list(list);
try {
s.analyze();
printf("SUCCESS!!!\n");
lst = s.poliz_list;
table_lst = s.label_list;
lprint(lst); // print poliz list:
}
catch (const Exeption &ex) {
printf("Error: %s\nbut found %s\nstr# %d\n",
ex.GetComment(), ex.GetLexeme(), ex.GetNstr());
return 1;
}
Executer e(lst);
e.execute();
printf("\n");
print_table_list(table_lst);
delete_poliz_list(lst);
return 0;
}
|
[
"yura603@mail.ru"
] |
yura603@mail.ru
|
d681b826277d421d4daedd46b0a8443bf01cd154
|
da2fac467da6cb1b0cc420d02f72b30bfd87eefc
|
/semantics-parser/main.cc
|
0efe7b97b5f6abfc5ca4ecb5d0dc91bb16dbdb12
|
[] |
no_license
|
dyninst/tools
|
f500ba1b3900345fc2fb760db7710232be7a7a37
|
801dc122b706834cefa673ad15579c179cb2943c
|
refs/heads/master
| 2023-07-31T22:36:46.141775
| 2023-03-15T04:22:11
| 2023-03-15T04:22:11
| 58,003,524
| 27
| 18
| null | 2023-03-15T04:22:12
| 2016-05-03T21:44:32
|
C
|
UTF-8
|
C++
| false
| false
| 6,236
|
cc
|
/*
* See the dyninst/COPYRIGHT file for copyright information.
*
* We provide the Paradyn Tools (below described as "Paradyn")
* on an AS IS basis, and do not warrant its validity or performance.
* We reserve the right to update, modify, or discontinue this
* software at any time. We shall have no obligation to supply such
* updates or modifications or any other form of support to you.
*
* By your use of Paradyn, you understand and agree that we (or any
* other person or entity with proprietary rights in Paradyn) are
* under no obligation to provide either maintenance services,
* update services, notices of latent defects, or correction of
* defects for Paradyn.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "driver.h"
#include "scanner.h"
#include <sys/stat.h>
bool file_exists(const char *fname) {
struct stat buf;
return stat(fname, &buf) == 0;
}
int main() {
/*
* List of files that need to be parsed. Currently roughly organized categorically.
*
* This would ideally contain all files under ISA_ps. However, currently, only a subset is included since I wanted to be selective about
* what to parse. It is possible to just include all files and later choose which ones to parse - shouldn't be too hard to implement; this
* solution works fine though for now.
*
* Even in this subset, comment the ones you don't need to filter parsing further.
*/
const char *fnames[] = {/*"add_addsub_imm", "adds_addsub_imm", "sub_addsub_imm", "subs_addsub_imm",
"add_addsub_ext", "adds_addsub_ext", "sub_addsub_ext", "subs_addsub_ext",
"add_addsub_shift", "adds_addsub_shift", "sub_addsub_shift", "subs_addsub_shift",
"adc", "adcs", "adr", "adrp", "tbz", "tbnz", "b_uncond", "b_cond", "br", "blr", "bl", "cbz", "cbnz",
"cmp_subs_addsub_imm", "cmp_subs_addsub_ext", "cmp_subs_addsub_shift",
"cmn_adds_addsub_imm", "cmn_adds_addsub_ext", "cmn_adds_addsub_shift",
"ccmn_reg", "ccmn_imm",
"ldr_imm_gen", "str_imm_gen", "ldrb_imm", "strb_imm", "ldrh_imm", "ldrsb_imm", "ldrsh_imm", "ldrsw_imm", "strh_imm",
"ldr_reg_gen", "ldrb_reg", "ldrh_reg", "ldrsb_reg", "ldrsh_reg", "ldrsw_reg", "str_reg_gen", "strb_reg", "strh_reg",
"ldr_lit_gen", "ldrsw_lit",
"ubfm", "uxtb_ubfm", "uxth_ubfm", "ubfiz_ubfm", "ubfx_ubfm", "sbfm", "sxth_sbfm", "sxtb_sbfm", "sbfiz_sbfm", "sbfx_sbfm", "sxtw_sbfm",
"movz", "mov_movz", "movn", "mov_movn", "movk",
"orr_log_shift", "mov_orr_log_shift", "mov_orr_log_imm", "orn_log_shift", "orr_log_imm",
"and_log_imm", "and_log_shift", "ands_log_imm", "ands_log_shift", "eor_log_shift", "eor_log_imm", "eon",
"lsl_ubfm", "lsr_ubfm", "asr_sbfm",
"bfm", "bfxil_bfm", "bfi_bfm", "bic_log_shift", "bics", "stp_gen", "ldp_gen", "stnp_gen", "ldpsw", "ldnp_gen", "stnp_gen",
"ldtr", "ldtrb", "ldtrh", "ldtrsb", "ldtrsh", "sttr", "sttrb", "sttrh",
"ldur_gen", "ldurb", "ldurh", "ldursb", "ldursh", "ldursw", "sturb", "sturh", "stur_gen",
"asr_asrv", "asrv", "lsl_lslv", "lslv", "lsr_lsrv", "lsrv", "ror_rorv", "rorv"
"tst_ands_log_imm", "tst_ands_log_shift", "sbc", "sbcs", "ngc_sbc", "ngcs_sbcs", "neg_sub_addsub_shift", "negs_subs_addsub_shift",
"mvn_orn_log_shift", "mov_add_addsub_imm",
"csinv", "csinc", "csneg", "csel",
"cls_int", "clz_int",
"madd", "msub", "mneg_msub", "mul_madd", "smaddl", "smsubl", "smnegl_smsubl","smulh", "smull_smaddl","umaddl", "umsubl", "umnegl_umsubl", "umulh", "umull_umaddl",
"ldar", "ldarb", "ldarh", "stlr", "stlrb", "stlrh",
"udiv", */"sdsiv"};
/** Root folder containing the pseudocode files created by the pseudocode extractor script. Change as necessary. */
std::string pcode_files_dir("/u/s/s/ssunny/dev-home/dyninst/dyninst-code/instructionAPI/ISA_ps/");
/** Iterate over all files in the list above and parse them. */
Dyninst_aarch64::Driver driver;
std::map<const char *, bool> notExists;
for(int fidx = 0; fidx < sizeof(fnames)/sizeof(char *); fidx++) {
if(file_exists(fnames[fidx]))
driver.pcode_parse(pcode_files_dir + std::string(fnames[fidx]));
else
notExists[fnames[fidx]] = true;
}
/** For each file above, output the iproc_set statement for the corresponding instruction.
* This needs to go into the iproc_init method of the Dispatcher. */
for(int idx = 0; idx < sizeof(fnames)/sizeof(char *); idx++)
if(!notExists.count(fnames[idx]))
std::cout<<"iproc_set (rose_aarch64_op_"<<fnames[idx]<<", new ARM64::IP_"<<fnames[idx]<<"_execute);"<<std::endl;
if(notExists.size()) {
std::cout<<std::endl;
std::cout<<"### Some files not found:"<<std::endl;
for (std::map<const char *, bool>::iterator itr = notExists.begin(); itr != notExists.end(); itr++) {
std::cout << "Could not find file " << itr->first << "." << std::endl;
}
}
return 0;
}
|
[
"shah28@wisc.edu"
] |
shah28@wisc.edu
|
56dc4622a9353efded63c843cddefced664cd5d1
|
cb7fec3b5e18c64cedf39857daceb2bc561eef78
|
/src/lr0-items.h
|
78c01afb01c93874c7f6e1925607d1bccdadc71e
|
[] |
no_license
|
voyagerok/text-processor
|
8826a445202da02a0afbeb8c891ec05074879aae
|
c1dbcfb4640cfbbe0a633e633cbd09ede27895c8
|
refs/heads/master
| 2021-01-19T17:55:01.074808
| 2017-06-15T05:09:54
| 2017-06-15T05:09:54
| 88,347,284
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,231
|
h
|
#ifndef LRO_ITEMS_H_
#define LRO_ITEMS_H_
#include "grammar.h"
#include "grammar-rule.h"
#include <memory>
#include <iostream>
namespace tproc {
struct LR0Item {
GRuleWordPtr rule;
// int position;
WordIndex wordIndex;
GRuleWordPtr getWordAtCurrentPosition();
// bool atEndPosition() { return rule-> <= position; }
bool atEndPosition() {
return rule->getChildWords().at(wordIndex.ruleIndex).size() <= wordIndex.position;
}
bool operator==(const LR0Item &other);
bool operator!=(const LR0Item &other);
friend std::ostream &operator<<(std::ostream &os, const LR0Item &item);
};
struct LR0ItemSet {
using iter = std::vector<LR0Item>::iterator;
using const_iter = std::vector<LR0Item>::const_iterator;
// UnicodeString incomingWord;
GRuleWordPtr incomingWord = nullptr;
int itemsetIndex = 0;
std::vector<LR0Item> items;
std::map<GRuleWordPtr, int> transitions;
void addItem(const LR0Item &item) { items.push_back(item); }
void addItem(LR0Item &&item) { items.push_back(std::move(item)); }
template<class ...Args>
void emplaceItem(Args&&...args) { items.emplace_back(&args...); }
int getNextStateForWord(const GRuleWordPtr &word);
std::map<GRuleWordPtr, int> getTransitions() const { return transitions; }
iter begin() { return items.begin(); }
iter end() { return items.end(); }
const_iter begin() const { return items.begin(); }
const_iter end() const { return items.end(); }
bool operator==(const LR0ItemSet &other);
friend std::ostream &operator<<(std::ostream &os, const LR0ItemSet &itemSet);
};
class LR0ItemSetCollection {
public:
LR0ItemSetCollection();
bool build(const Grammar &grammar);
std::vector<LR0ItemSet> getItemSetCollection() const { return itemSetCollection; }
int size() const { return itemSetCollection.size(); }
private:
void build(const Grammar &grammar, LR0ItemSet &itemSet, int itemSetIndex);
void closure(LR0ItemSet &itemSet, const LR0Item ¤tItem);
void addItemSetToHistory(const LR0ItemSet &itemSet);
std::vector<LR0ItemSet> itemSetCollection;
std::map<GRuleWordPtr, std::vector<LR0ItemSet>> history;
};
}
#endif //LR0_ITEMS_H_
|
[
"shepard1010@gmail.com"
] |
shepard1010@gmail.com
|
1b6568a08e44ec57534da8b78ba4292aa511fac8
|
08bdd164c174d24e69be25bf952322b84573f216
|
/opencores/client/foundation classes/j2sdk-1_4_2-src-scsl/j2se/src/share/native/sun/awt/font/opentype/ArabicShaping.cpp
|
c01ab2281e9c7128320e4ea33a97875ca501d878
|
[] |
no_license
|
hagyhang/myforthprocessor
|
1861dcabcf2aeccf0ab49791f510863d97d89a77
|
210083fe71c39fa5d92f1f1acb62392a7f77aa9e
|
refs/heads/master
| 2021-05-28T01:42:50.538428
| 2014-07-17T14:14:33
| 2014-07-17T14:14:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,681
|
cpp
|
/*
* @(#)ArabicShaping.cpp 1.15 01/10/09
*
* (C) Copyright IBM Corp. 1998, 1999, 2000 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "OpenTypeTables.h"
#include "ArabicShaping.h"
enum {
_c_ = ArabicShaping::ST_NOSHAPE_DUAL,
_d_ = ArabicShaping::ST_DUAL,
_n_ = ArabicShaping::ST_NONE,
_r_ = ArabicShaping::ST_RIGHT,
_t_ = ArabicShaping::ST_TRANSPARENT,
_x_ = ArabicShaping::ST_NOSHAPE_NONE
};
const ArabicShaping::ShapeType ArabicShaping::shapeTypes[] =
{
_n_, _r_, _r_, _r_, _r_, _d_, _r_, _d_, _r_, _d_, _d_, _d_, _d_, _d_, _r_, _r_, // 0x621 - 0x630
_r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _x_, _x_, _x_, _x_, _x_, _c_, // 0x631 - 0x640
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _r_, _d_, _d_, _t_, _t_, _t_, _t_, _t_, _t_, // 0x641 - 0x650
_t_, _t_, _t_, _t_, _t_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _x_, _n_, // 0x651 - 0x660
_n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _x_, _x_, _t_, // 0x661 - 0x670
_r_, _r_, _r_, _x_, _r_, _r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x671 - 0x680
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, // 0x681 - 0x690
_r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x691 - 0x6a0
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, _d_, // 0x6a1 - 0x6b0
_d_, _d_, _d_, _d_, _d_, _d_, _d_, _x_, _x_, _d_, _d_, _d_, _d_, _d_, _x_, _r_, // 0x6b1 - 0x6c0
_d_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _r_, _d_, _r_, _d_, _x_, _d_, // 0x6c1 - 0x6d0
_d_, _r_, _r_, _x_, _x_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, _t_, // 0x6d1 - 0x6e0
_t_, _t_, _t_, _t_, _n_, _n_, _t_, _t_, _n_, _t_, _t_, _t_, _t_, _x_, _x_, _n_, // 0x6e1 - 0x6f0
_n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _n_, _x_, _x_, _x_, _x_, _x_, _x_ // 0x6f1 - 0x6ff
};
/*
shaping array holds types for arabic chars between 0621 and 0700
other values are either unshaped, or transparent if a mark or format
code, except for format codes 200c (zero-width non-joiner) and 200d
(dual-width joiner) which are both unshaped and non_joining or
dual-joining, respectively.
*/
ArabicShaping::ShapeType ArabicShaping::getShapeType(LEUnicode c)
{
if (c >= 0x0621 && c <= 0x206f) {
if (c < 0x0700) {
return shapeTypes[c - 0x0621];
} else if (c == 0x200c) { // ZWNJ
return ST_NOSHAPE_NONE;
} else if (c == 0x200d) { // ZWJ
return ST_NOSHAPE_DUAL;
} else if (c >= 0x202a && c <= 0x202e) { // LRE - RLO
return ST_TRANSPARENT;
} else if (c >= 0x206a && c <= 0x206f) { // Inhibit Symmetric Swapping - Nominal Digit Shapes
return ST_TRANSPARENT;
}
}
return ST_NOSHAPE_NONE;
}
const LETag GlyphShaper::isolFeatureTag = 0x69736F6C; // 'isol'
const LETag GlyphShaper::initFeatureTag = 0x696E6974; // 'init'
const LETag GlyphShaper::mediFeatureTag = 0x6D656469; // 'medi'
const LETag GlyphShaper::finaFeatureTag = 0x66696E61; // 'fina'
const LETag GlyphShaper::ligaFeatureTag = 0x6C696761; // 'liga'
const LETag GlyphShaper::msetFeatureTag = 0x6D736574; // 'mset'
const LETag GlyphShaper::markFeatureTag = 0x6D61726B; // 'mark'
const LETag GlyphShaper::emptyTag = 0x00000000; // ''
const LETag GlyphShaper::tagArray[] =
{
isolFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
finaFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
initFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag,
mediFeatureTag, ligaFeatureTag, msetFeatureTag, markFeatureTag, emptyTag
};
#define TAGS_PER_GLYPH (sizeof GlyphShaper::tagArray / sizeof(LETag) / 4)
void ArabicShaping::shape(const LEUnicode *chars, le_int32 offset, le_int32 charCount, le_int32 charMax,
le_bool rightToLeft, Shaper &shaper)
{
// iterate in logical order, store tags in visible order
//
// the effective right char is the most recently encountered
// non-transparent char
//
// four boolean states:
// the effective right char shapes
// the effective right char causes left shaping
// the current char shapes
// the current char causes right shaping
//
// if both cause shaping, then
// shaper.shape(errout, 2) (isolate to initial, or final to medial)
// shaper.shape(out, 1) (isolate to final)
ShapeType rightType = ST_NOSHAPE_NONE, leftType = ST_NOSHAPE_NONE;
le_int32 i;
for (i = offset - 1; i >= 0; i -= 1) {
rightType = getShapeType(chars[i]);
if (rightType != ST_TRANSPARENT) {
break;
}
}
for (i = offset + charCount; i < charMax; i += 1) {
leftType = getShapeType(chars[i]);
if (leftType != ST_TRANSPARENT) {
break;
}
}
// erout is effective right logical index
le_int32 erout = -1;
le_bool rightShapes = false;
le_bool rightCauses = (rightType & MASK_SHAPE_LEFT) != 0;
le_int32 in, e, out = 0, dir = 1;
if (rightToLeft) {
out = charCount - 1;
erout = charCount;
dir = -1;
}
for (in = offset, e = offset + charCount; in < e; in += 1, out += dir) {
LEUnicode c = chars[in];
ShapeType t = getShapeType(c);
shaper.init(c, out, (t & (MASK_TRANSPARENT | MASK_NOSHAPE)) == 0);
if ((t & MASK_TRANSPARENT) != 0) {
continue;
}
le_bool curShapes = (t & MASK_NOSHAPE) == 0;
le_bool curCauses = (t & MASK_SHAPE_RIGHT) != 0;
if (rightCauses && curCauses) {
if (rightShapes) {
shaper.shape(erout, 2);
}
if (curShapes) {
shaper.shape(out, 1);
}
}
rightShapes = curShapes;
rightCauses = (t & MASK_SHAPE_LEFT) != 0;
erout = out;
}
if (rightShapes && rightCauses && (leftType & MASK_SHAPE_RIGHT) != 0) {
shaper.shape(erout, 2);
}
}
GlyphShaper::GlyphShaper(const LETag **outputTags)
{
charTags = outputTags;
}
GlyphShaper::~GlyphShaper()
{
// nothing to do
}
void GlyphShaper::init(LEUnicode ch, le_int32 outIndex, le_bool isloate)
{
charTags[outIndex] = tagArray;
}
void GlyphShaper::shape(le_int32 outIndex, le_int32 shapeOffset)
{
charTags[outIndex] = &charTags[outIndex][TAGS_PER_GLYPH * shapeOffset];
}
CharShaper::CharShaper(LEUnicode *outputChars)
{
chars = outputChars;
}
CharShaper::~CharShaper()
{
// nothing to do
}
void CharShaper::init(LEUnicode ch, le_int32 outIndex, le_bool isloate)
{
if (isloate) {
chars[outIndex] = getToIsolateShape(ch);
} else {
chars[outIndex] = ch;
}
}
void CharShaper::shape(le_int32 outIndex, le_int32 shapeOffset)
{
chars[outIndex] += (LEUnicode) shapeOffset;
}
LEUnicode CharShaper::isolateShapes[] =
{
0xfe80, 0xfe81, 0xfe83, 0xfe85, 0xfe87, 0xfe89, 0xfe8d, 0xfe8f, 0xfe93, 0xfe95,
0xfe99, 0xfe9d, 0xfea1, 0xfea5, 0xfea9, 0xfeab, 0xfead, 0xfeaf, 0xfeb1, 0xfeb5,
0xfeb9, 0xfebd, 0xfec1, 0xfec5, 0xfec9, 0xfecd, 0x063b, 0x063c, 0x063d, 0x063e,
0x063f, 0x0640, 0xfed1, 0xfed5, 0xfed9, 0xfedd, 0xfee1, 0xfee5, 0xfee9, 0xfeed,
0xfeef, 0xfef1, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, 0x0650, 0x0651, 0x0652,
0x0653, 0x0654, 0x0655, 0x0656, 0x0657, 0x0658, 0x0659, 0x065a, 0x065b, 0x065c,
0x065d, 0x065e, 0x065f, 0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666,
0x0667, 0x0668, 0x0669, 0x066a, 0x066b, 0x066c, 0x066d, 0x066e, 0x066f, 0x0670,
0xfb50, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0xfbdd, 0x0678, 0xfb66, 0xfb5e,
0xfb52, 0x067c, 0x067d, 0xfb56, 0xfb62, 0xfb5a, 0x0681, 0x0682, 0xfb76, 0xfb72,
0x0685, 0xfb7a, 0xfb7e, 0xfb88, 0x0689, 0x068a, 0x068b, 0xfb84, 0xfb82, 0xfb86,
0x068f, 0x0690, 0xfb8c, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0xfb8a,
0x0699, 0x069a, 0x069b, 0x069c, 0x069d, 0x069e, 0x069f, 0x06a0, 0x06a1, 0x06a2,
0x06a3, 0xfb6a, 0x06a5, 0xfb6e, 0x06a7, 0x06a8, 0xfb8e, 0x06aa, 0x06ab, 0x06ac,
0xfbd3, 0x06ae, 0xfb92, 0x06b0, 0xfb9a, 0x06b2, 0xfb96, 0x06b4, 0x06b5, 0x06b6,
0x06b7, 0x06b8, 0x06b9, 0xfb9e, 0xfba0, 0x06bc, 0x06bd, 0xfbaa, 0x06bf, 0xfba4,
0xfba6, 0x06c2, 0x06c3, 0x06c4, 0xfbe0, 0xfbd9, 0xfbd7, 0xfbdb, 0xfbe2, 0x06ca,
0xfbde, 0xfbfc, 0x06cd, 0x06ce, 0x06cf, 0xfbe4, 0x06d1, 0xfbae, 0xfbb0
};
LEUnicode CharShaper::getToIsolateShape(LEUnicode ch)
{
if (ch < 0x0621 || ch > 0x06d3) {
return ch;
}
return isolateShapes[ch - 0x0621];
}
|
[
"blue@cmd.nu"
] |
blue@cmd.nu
|
021525bf1d1e34f38dc382064d775506c4069988
|
bb7e1ee8c50d76252290f244d0a8172562a73ee3
|
/mmtk.cpp
|
364b0601047fdc6e5a65a5519df308de99314ad5
|
[] |
no_license
|
vkc12uec/temp-prgs
|
d2441181c9c74abd817a046444fd7feaa9e31ae9
|
821d14ec259c62eee7ed75b84d4095d37b276a78
|
refs/heads/master
| 2021-01-15T16:57:42.116352
| 2013-07-08T17:11:59
| 2013-07-08T17:11:59
| 32,124,746
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
cpp
|
int cricBinsearch (int *a, int l, int h, int find) {
if (h < l) return -1;
int mid = (l+h)/2;
if (a[l] < a[mid]) //sorted
{
if (find < a[mid])
h = mid-1;
else
l = mid+1; // in bad part
}
else if (a[mid] < a[h]) //sorted
{
if (find > a[mid])
l = mid+1;
else
h = mid-1;
}
return cricBinsearch (a, l, h, find);
}
int main () {
int a [] = {4, 5 , 6, 7, 8, 9, 1, 2,3};
int find = 3;
if (searchincircularsorterlist(a,9, find) == 1)
cout << "\nfound";
//if (cricBinsearch(a, 0, 8, find) == 1)
else cout << "\nnot -found";
return 0;
}
|
[
"vivekchaurasiya@gmail.com"
] |
vivekchaurasiya@gmail.com
|
2da759cc2cfc9cca70035efa421cb690d401a8b1
|
071896f5b8d9034a3874c3d43d0c0f5fb4ef9b61
|
/AvidApplicationManager.app/Contents/Frameworks/QtCore.framework/Versions/4/Headers/qmimedata.h
|
77f59cf270acd2e2d701d080090dc3b689983caa
|
[] |
no_license
|
s10331/Application-Manager
|
b591e6e60f8e3b05936b0b8d7456fcfbc959f950
|
89faca8db246f28bef1b9847c483c0b79e0ead7d
|
refs/heads/master
| 2021-01-10T03:54:46.660443
| 2016-03-17T01:45:45
| 2016-03-17T01:45:45
| 54,079,669
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,495
|
h
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMIMEDATA_H
#define QMIMEDATA_H
#include <QtCore/qvariant.h>
#include <QtCore/qobject.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Core)
class QUrl;
class QMimeDataPrivate;
class Q_CORE_EXPORT QMimeData : public QObject
{
Q_OBJECT
public:
QMimeData();
~QMimeData();
QList<QUrl> urls() const;
void setUrls(const QList<QUrl> &urls);
bool hasUrls() const;
QString text() const;
void setText(const QString &text);
bool hasText() const;
QString html() const;
void setHtml(const QString &html);
bool hasHtml() const;
QVariant imageData() const;
void setImageData(const QVariant &image);
bool hasImage() const;
QVariant colorData() const;
void setColorData(const QVariant &color);
bool hasColor() const;
QByteArray data(const QString &mimetype) const;
void setData(const QString &mimetype, const QByteArray &data);
void removeFormat(const QString &mimetype);
virtual bool hasFormat(const QString &mimetype) const;
virtual QStringList formats() const;
void clear();
bool getDropped() const;
Qt::KeyboardModifiers getDroppedModifiers() const;
void setDropped(bool dropped, Qt::KeyboardModifiers modifiers = Qt::NoModifier);
protected:
virtual QVariant retrieveData(const QString &mimetype,
QVariant::Type preferredType) const;
private:
Q_DISABLE_COPY(QMimeData)
Q_DECLARE_PRIVATE(QMimeData)
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // QMIMEDATA_H
|
[
"P410@P410-69.local"
] |
P410@P410-69.local
|
98a29a5429645a9da996e4e682f57ef8332e6721
|
15d85f364067b7f1820bf69b3f17eaf6a3e4b1ce
|
/year_1/lab2/2C/code.cpp
|
7c7dc24f1b9534513c4db883b8f675dbe7284325
|
[] |
no_license
|
iilnar/algo
|
e8d79022b1c03064c4f4a1837a6f2c9278a520eb
|
6814bff22c3bb3ada1751c51f4b1a084789970f4
|
refs/heads/master
| 2021-01-20T21:07:00.963386
| 2016-05-28T20:56:09
| 2016-05-28T20:56:09
| 59,911,736
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,323
|
cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
using namespace std;
#define FILENAME "num2choose"
long long n, k, m;
vector <int> ans;
vector <int> num2perm (int n, long long k) {
vector <int> res(n), able;
vector <long long> fact(n + 1);
int j;
fact[0] = 1;
for (long long i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i;
able.push_back(i);
}
for (int i = 0; i < n; i++) {
j = k / fact[n - i - 1];
k %= fact[n - i - 1];
res[i] = able[j];
able.erase(able.begin() + j, able.begin() + j + 1);
}
return res;
}
long long perm2num (int n, vector <int> v) {
vector <long long> fact(n + 1);
vector <int> able;
fact[0] = 1;
long long res = 0;
for (long long i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i; able.push_back(i);}
for (int i = 0; i < v.size(); i++) {
int j = 0;
while (able[j] != v[i]) j++;
able.erase(able.begin() + j, able.begin() + j + 1);
res += fact[n - i - 1] * j;
}
return res;
}
vector <vector <long long> > Pascal (int n) {
vector <vector <long long> > p;
p.resize(n);
p[0].push_back(1);
for (int i = 1; i < n; i++) {
p[i].push_back(1);
for (int j = 1; j < p[i - 1].size(); j++) {
p[i].push_back(p[i - 1][j - 1] + p[i - 1][j]);
}
p[i].push_back(1);
}
return p;
}
vector <int> num2choose (int n, int k, long long m) {
vector <vector <long long> > pas = Pascal(n);
vector <int> res(k);
int j = 0, last = 0;
for (int i = 0; i < k; i++) {
j = last + 1;
while (k - i - 1 >= 0 && m >= pas[n - j][k - i - 1]) {
m -= pas[n - j][k - i - 1];
j++;
}
res[i] = j;
last = j;
}
return res;
}
int main () {
//freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
freopen(FILENAME".in", "r", stdin); freopen(FILENAME".out", "w", stdout);
cin >> n >> k >> m;
ans = num2choose(n, k, m);
for (int i = 0; i < k; i++) {
cout << ans[i] << ' ';
}
return 0;
}
|
[
"sabirzyanovilnar@gmail.com"
] |
sabirzyanovilnar@gmail.com
|
645ebb15d33e5a8e009796f04f5009bb3e314ee9
|
342aedc6768d530d0d1a8496e5a36bb07ceaca92
|
/Classes/Utility/SpriteUtils.h
|
d17ddd2e488eb2a45fda91a3acf9dab266974d4a
|
[
"MIT"
] |
permissive
|
Riyaaaaa/Cocos2dxAdvLuaEngine
|
4e4d88010cb290672a22fdbbcbee0002d10a886a
|
f00ff97b44b25198bc02dc24411245448d81845f
|
refs/heads/master
| 2021-01-25T11:33:38.925331
| 2017-07-30T09:22:53
| 2017-07-30T09:22:53
| 93,933,227
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 314
|
h
|
//
// SpriteUtils.hpp
// Cocos2dxAdvLuaEngine
//
// Created by Riya.Liel on 2017/06/19.
//
//
#ifndef SpriteUtils_h
#define SpriteUtils_h
#include "cocos2d.h"
namespace SpriteUtils {
void fadeIn(cocos2d::Sprite* sprite, float duration, std::function<void()> endCallback);
}
#endif /* SpriteUtils_hpp */
|
[
"s113111@edu.asahikawa-nct.ac.jp"
] |
s113111@edu.asahikawa-nct.ac.jp
|
bf154c9926e85b71046b0d14b2e4b73693d7298a
|
8d8701540dd968681f82eb9294f71376d6512abe
|
/src/experiment_async_rdma/rdma_environment.cpp
|
734084f9fcfa2695d55c13770e724e326a4c84b0
|
[] |
no_license
|
xiaobaidemu/ATI
|
1ba9bf74dc56587a0f6143f8978847f7828023d0
|
12e71bd14e97e857a4006a5be5c53216aaa6c5b9
|
refs/heads/master
| 2020-03-17T10:05:26.006279
| 2018-05-15T10:45:40
| 2018-05-15T10:45:40
| 133,499,782
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,706
|
cpp
|
#include "rdma_header.h"
#include <net.h>
#include <sys/epoll.h>
#define CQ_SIZE 100
rdma_environment::rdma_environment()
{
_dispose_required.store(false);
env_ec = rdma_create_event_channel();
_efd_rdma_fd = CCALL(epoll_create1(EPOLL_CLOEXEC));
_notification_event_rdma_fd = CCALL(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
_notification_event_rdma_fddata = rdma_fd_data(this, _notification_event_rdma_fd);
MAKE_NONBLOCK(env_ec->fd);
_rdma_channel_fddata = rdma_fd_data(this, env_ec->fd, true);
epoll_add(&_rdma_channel_fddata, EPOLLIN|EPOLLET);
epoll_add(&_notification_event_rdma_fddata, EPOLLIN | EPOLLET);
_loop_thread = new std::thread([this](){
main_loop();
CCALL(close(_notification_event_rdma_fd));
_notification_event_rdma_fd = INVALID_FD;
CCALL(close(_efd_rdma_fd));
_efd_rdma_fd = INVALID_FD;
rdma_destroy_event_channel(env_ec);
DEBUG("main_loop have already closed.\n");
});
}
/*void rdma_environment::sighandler(int)
{
printf("xxxxxxxxxxxxxxxxxx %d\n", pthread_self());
}*/
rdma_environment::~rdma_environment()
{
}
void rdma_environment::epoll_add(rdma_fd_data* fddata, const uint32_t events) const
{
ASSERT(fddata); ASSERT_RESULT(fddata->fd);
epoll_event event; event.events = events; event.data.ptr = fddata;
CCALL(epoll_ctl(_efd_rdma_fd, EPOLL_CTL_ADD, fddata->fd, &event));
}
void rdma_environment::push_and_trigger_notification(const rdma_event_data& notification)
{
const size_t new_size = _notification_rdma_queue.push(notification);
TRACE("push a rdma_event_data into the _notification_rdma_queue(size:%ld).\n", new_size);
ASSERT_RESULT(_notification_event_rdma_fd);
if(new_size == 1){
uint64_t value = 1;
CCALL(write(_notification_event_rdma_fd, &value, sizeof(value)));
}
else{
DEBUG("skip write(_notification_event_rdma_fd): queued notification count = %lld\n",(long long)new_size);
}
}
void rdma_environment::dispose()
{
// for all_debug
DEBUG("environment begin close.\n");
push_and_trigger_notification(rdma_event_data::rdma_environment_dispose(this));
_loop_thread->join();
DEBUG("environment is closeing.\n");
}
void rdma_environment::build_params(struct rdma_conn_param *params)
{
memset(params, 0, sizeof(*params));
params->retry_count = 10;
params->rnr_retry_count = 10;
}
void rdma_environment::process_rdma_channel(const uint32_t events)
{
ASSERT(events & EPOLLIN);
struct rdma_cm_event *event = nullptr;
struct rdma_conn_param cm_params;
build_params(&cm_params);
while(rdma_get_cm_event(env_ec, &event) == 0){
struct rdma_cm_event event_copy;
memcpy(&event_copy, event, sizeof(*event));
rdma_ack_cm_event(event);
switch(event_copy.event){
case RDMA_CM_EVENT_ADDR_RESOLVED:{
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->build_conn_res();
CCALL(rdma_resolve_route(event_copy.id, TIMEOUT_IN_MS));
break;
}
case RDMA_CM_EVENT_ROUTE_RESOLVED:{
CCALL(rdma_connect(event_copy.id, &cm_params));
TRACE("Finish rdma_cm_event_rout_resolved event.\n");
break;
}
case RDMA_CM_EVENT_CONNECT_REQUEST:{
rdma_connection *new_conn = create_rdma_connection_passive(event_copy.id, event_copy.listen_id);
//if(((rdma_fd_data*)(event_copy.listen_id->context))->owner) printf("------------------\n");
//event_copy.id->context = new_conn;
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
map_id_conn[(intptr_t)(event_copy.id)] = new_conn;
}
else{
FATAL("Cannot fix bug when handle rdma_cm_event_connect_request.\n");
ASSERT(0);
}
//记录id和
CCALL(rdma_accept(event_copy.id, &cm_params));
TRACE("Listener finish rdma_cm_event_connect_request event.\n");
break;
}
case RDMA_CM_EVENT_ESTABLISHED:{
//DEBUG("handle rdma_cm_event_established event.\n");
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established();
NOTICE("%s to %s active connection established.\n",
conn->local_endpoint().to_string().c_str(),
conn->remote_endpoint().to_string().c_str());
}
else{
rdma_connection *new_passive_conn = map_id_conn[(intptr_t)(event_copy.id)];
rdma_listener *listen = new_passive_conn->conn_lis;
listen->process_accept_success(new_passive_conn);
NOTICE("%s from %s passive connection established.\n",
new_passive_conn->local_endpoint().to_string().c_str(),
new_passive_conn->remote_endpoint().to_string().c_str());
}
break;
}
case RDMA_CM_EVENT_DISCONNECTED:{
DEBUG("handle rdma_cm_event_disconnected event.\n");
rdma_connection *conn = nullptr;
if(map_id_conn.find((intptr_t)(event_copy.id)) == map_id_conn.end()){
conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->_status.store(CONNECTION_CLOSED);
DEBUG("Active connection is disconneting.\n");
}
else{
conn = map_id_conn[(intptr_t)(event_copy.id)];
conn->_status.store(CONNECTION_CLOSED);
map_id_conn.erase((intptr_t)(event_copy.id));
DEBUG("Passive connection is disconnecting.\n");
}
conn->close_rdma_conn();
break;
}
case RDMA_CM_EVENT_ADDR_ERROR:
case RDMA_CM_EVENT_ROUTE_ERROR:
case RDMA_CM_EVENT_UNREACHABLE:
case RDMA_CM_EVENT_REJECTED:{
if(event_copy.id && event_copy.id->context){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established_error();
}
break;
}
case RDMA_CM_EVENT_CONNECT_ERROR:{
if(event_copy.listen_id && event_copy.listen_id->context){
rdma_listener* lis = (rdma_listener*)(((rdma_fd_data*)(event_copy.listen_id->context))->owner);
lis->process_accept_fail();
}
else if(event_copy.id && event_copy.id->context){
rdma_connection *conn = (rdma_connection*)(((rdma_fd_data*)(event_copy.id->context))->owner);
conn->process_established_error();
}
else{
FATAL("BUG: Cannot handle error event %s because cannot find conn/listen object.\n", rdma_event_str(event_copy.event));
ASSERT(0);break;
}
break;
}
default:{
FATAL("BUG: Cannot handle event:%s\n",rdma_event_str(event_copy.event));
ASSERT(0);
break;
}
}
}
return;
}
void rdma_environment::main_loop()
{
DEBUG("ENVIRONMENT start main_loop.\n");
const int EVENT_BUFFER_COUNT = 256;
epoll_event* events_buffer = new epoll_event[EVENT_BUFFER_COUNT];
struct ibv_wc ret_wc_array[CQE_MIN_NUM];
while(true){
// DEBUG("---------------------------------------------\n");
const int readyCnt = epoll_wait(_efd_rdma_fd, events_buffer, EVENT_BUFFER_COUNT, -1);
if(readyCnt<0){
const int error = errno;
if(error == EINTR) continue;
ERROR("[rdma_environment] epoll_wait failed with %d (%s)\n",
error, strerror(error));
break;
}
for(int i = 0;i < readyCnt;++i){
const uint32_t curr_events = events_buffer[i].events;
const rdma_fd_data* curr_rdmadata = (rdma_fd_data*)events_buffer[i].data.ptr;
switch(curr_rdmadata->type){
case rdma_fd_data::RDMATYPE_CHANNEL_EVENT:{
TRACE("trigger rdma_channel fd = %d.\n", env_ec->fd);
ASSERT(this == curr_rdmadata->owner);
ASSERT(curr_rdmadata->fd == env_ec->fd);
this->process_rdma_channel(curr_events);
break;
}
case rdma_fd_data::RDMATYPE_NOTIFICATION_EVENT:{
TRACE("trigger rdma_eventfd = %d %d\n", curr_rdmadata->fd, _notification_event_rdma_fd);
ASSERT(this == curr_rdmadata->owner);
ASSERT(curr_rdmadata->fd == _notification_event_rdma_fd);
this->process_epoll_env_notificaton_event_rdmafd(curr_events);
break;
}
case rdma_fd_data::RDMATYPE_ID_CONNECTION:{
//表示当前已经有完成任务发生了,可以通过ibv_get_cq_event获取
struct ibv_cq *ret_cq; void *ret_ctx; struct ibv_wc wc;
rdma_connection *conn = (rdma_connection*)curr_rdmadata->owner;
CCALL(ibv_get_cq_event(conn->conn_comp_channel, &ret_cq, &ret_ctx));
conn->ack_num++;
//此处会有坑
if(conn->ack_num == ACK_NUM_LIMIT){
ibv_ack_cq_events(ret_cq, conn->ack_num);
TRACE("ibv_ack_cq_events %d\n", ACK_NUM_LIMIT);
conn->ack_num = 0;
}
CCALL(ibv_req_notify_cq(ret_cq, 0));
int num_cqe;
while(num_cqe = ibv_poll_cq(ret_cq, CQE_MIN_NUM, ret_wc_array)){
TRACE("ibv_poll_cq() get %d cqe.\n", num_cqe);
conn->process_poll_cq(ret_cq, ret_wc_array, num_cqe);
}
break;
}
default:{
FATAL("BUG: Unknown rdma_fd_data: %d\n", (int)curr_rdmadata->type);
ASSERT(0);break;
}
}
}
if(_dispose_required.load()){
DEBUG("ready to close the main_loop.\n");
break;
}
}
delete[] events_buffer;
return;
}
long long rdma_environment::get_curtime(){
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000000 + tv.tv_usec;
}
void rdma_environment::process_close_queue(){
while(true){
close_conn_info *conn_info;
bool issuc = _ready_close_queue.try_front(&conn_info);
if(!issuc) break;
else{
if(get_curtime() - (conn_info->time_ready_close) >= 0){
if(conn_info->closing_conn->_status.load() == CONNECTION_CONNECTED){
WARN("ready to rdma_disconnection.\n");
conn_info->closing_conn->close_rdma_conn();
//rdma_destroy_qp(conn_info->closing_conn->conn_id);
//conn_info->closing_conn->conn_id = nullptr;
//rdma_disconnect(conn_info->closing_conn->conn_id);
}
else{
ASSERT(conn_info->closing_conn->_status.load() == CONNECTION_CLOSED);
}
_ready_close_queue.pop();
continue;
}
else break;
}
}
if(_ready_close_queue.size() > 0){
push_and_trigger_notification(rdma_event_data::rdma_connection_close());
}
}
//目前要处理的内容只有发送操作
void rdma_environment::process_epoll_env_notificaton_event_rdmafd(const uint32_t events)
{
uint64_t dummy; ASSERT(events & EPOLLIN);
CCALL(read(_notification_event_rdma_fd, &dummy, sizeof(dummy)));
//处理_notification_rdma_queue中的事物
rdma_event_data evdata;
while(_notification_rdma_queue.try_pop(&evdata)){
switch(evdata.type){
case rdma_event_data::RDMA_EVENTTYPE_ASYNC_SEND:{
rdma_connection* conn = (rdma_connection*)evdata.owner;
conn->process_rdma_async_send();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_CONNECTION_CLOSE:{
//rdma_connection* conn = (rdma_connection*)evdata.owner;
//conn->_rundown.release();
this->process_close_queue();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_FAILED_CONNECTION_CLOSE:{
WARN("ready to close failed_connected connectioni......\n");
rdma_connection* conn = (rdma_connection*)evdata.owner;
conn->close_rdma_conn();
conn->_rundown.release();
}
case rdma_event_data::RDMA_EVENTTYPE_LISTENER_CLOSE:{
rdma_listener* lis = (rdma_listener*)evdata.owner;
lis->_rundown.release();
break;
}
case rdma_event_data::RDMA_EVENTTYPE_ENVIRONMENT_DISPOSE:{
_dispose_required.store(true);
TRACE("trigger RDMA_EVENTTYPE_ENVIRONMENT_DISPOSE .\n");
break;
}
default: {
FATAL("BUG: Unknown rdma_environment event_type: %d\n", (int)evdata.type);
ASSERT(0);break;
}
}
}
}
rdma_connection* rdma_environment::create_rdma_connection(const char* connect_ip, const uint16_t port)
{
return new rdma_connection(this, connect_ip, port);
}
rdma_listener* rdma_environment::create_rdma_listener(const char* bind_ip, const uint16_t port)
{
return new rdma_listener(this, bind_ip, port);
}
rdma_connection* rdma_environment::create_rdma_connection_passive(struct rdma_cm_id *new_conn, struct rdma_cm_id *listen_id)
{
return new rdma_connection(this, new_conn, listen_id);
}
|
[
"heboxin@pku.edu.cn"
] |
heboxin@pku.edu.cn
|
587741e225d64b743f13fea5d0b4d3b5fc109d1b
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/com/oleutest/cachetst/genenum.h
|
0734cf7e8ce6c16d4e37f9db81b9d1fde52a2f65
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,898
|
h
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1993.
//
// File: genenum.hxx
//
// Contents: Declaration of a generic enum object and test object.
//
// Classes: CGenEnumObject
//
// Functions:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author! author!
//
//--------------------------------------------------------------------------
#ifndef _GENENUM_H
#define _GENENUM_H
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <ole2.h>
//
// This macro allows the code to use a different outputstring function.
//
EXTERN_C HRESULT TestEnumerator(
void *penum,
size_t ElementSize,
LONG ElementCount,
BOOL (*verify)(void*),
BOOL (*verifyall)(void*,LONG),
void (*cleanup)(void*));
//
// Classes are exposed for C++ clients only
//
#ifdef __cplusplus
//+-------------------------------------------------------------------------
//
// Class: IGenEnum
//
// Purpose: generic enumerator
//
// Interface: Abstract class
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
// Notes:
//
//--------------------------------------------------------------------------
class IGenEnum
{
public:
STDMETHOD(QueryInterface)(REFIID riid, void **ppvObj) = 0;
STDMETHOD_(ULONG,AddRef)(void) = 0;
STDMETHOD_(ULONG,Release)(void) = 0;
STDMETHOD(Next) (ULONG celt, void *rgelt,
ULONG *pceltFetched) = 0;
STDMETHOD(Skip) (ULONG celt) = 0;
STDMETHOD(Reset) (void) = 0;
STDMETHOD(Clone) (void **ppenum) = 0;
};
//+-------------------------------------------------------------------------
//
// Class: CEnumeratorTest
//
// Purpose: enumerator test class
//
// Interface:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
// Notes:
//
//--------------------------------------------------------------------------
class CEnumeratorTest
{
public:
//
// Constructor
//
CEnumeratorTest(IGenEnum * enumtest, size_t elementsize, LONG elementcount);
//
// Test for each enumerator object
//
HRESULT TestAll(void);
HRESULT TestNext(void);
HRESULT TestSkip(void);
HRESULT TestClone(void);
HRESULT TestRelease(void);
//
// Verification functions
//
virtual BOOL Verify(void *);
virtual BOOL VerifyAll(void*, LONG);
virtual void Cleanup(void *);
protected:
CEnumeratorTest();
BOOL GetNext(ULONG celt, ULONG* pceltFetched, HRESULT* phresult);
IGenEnum * m_pEnumTest;
size_t m_ElementSize;
LONG m_ElementCount;
};
#endif
#endif // !_GENENUM_H
|
[
"support@cryptoalgo.cf"
] |
support@cryptoalgo.cf
|
56de8778468991181376e8746c8c7ada8d31f380
|
f5d87ed79a91f17cdf2aee7bea7c15f5b5258c05
|
/MDE/GME/paradigms/CHAOS/interpreters/codegen/BE_Workspace_Generators_T.inl
|
71edcdfacfd1b162b5b741ea035a19637a07c454
|
[] |
no_license
|
SEDS/CUTS
|
a4449214a894e2b47bdea42090fa6cfc56befac8
|
0ad462fadcd3adefd91735aef6d87952022db2b7
|
refs/heads/master
| 2020-04-06T06:57:35.710601
| 2016-08-16T19:37:34
| 2016-08-16T19:37:34
| 25,653,522
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,603
|
inl
|
// -*- C++ -*-
// $Id$
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_File_Open_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Open_T <CONTEXT>::
CUTS_BE_Workspace_File_Open_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Open_T <CONTEXT>::~CUTS_BE_Workspace_File_Open_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_File_Open_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_Begin_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_Begin_T <CONTEXT>::
CUTS_BE_Workspace_Begin_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_Begin_T <CONTEXT>::~CUTS_BE_Workspace_Begin_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_Begin_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_Project_Include_T
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
CUTS_BE_Workspace_Project_Include_T (CONTEXT & context)
{
}
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
~CUTS_BE_Workspace_Project_Include_T (void)
{
}
template <typename CONTEXT, typename NODE_TYPE>
CUTS_INLINE
void CUTS_BE_Workspace_Project_Include_T <CONTEXT, NODE_TYPE>::
generate (const NODE_TYPE & node)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_End_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_End_T <CONTEXT>::
CUTS_BE_Workspace_End_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_End_T <CONTEXT>::~CUTS_BE_Workspace_End_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_End_T <CONTEXT>::generate (const std::string & name)
{
}
///////////////////////////////////////////////////////////////////////////////
// CUTS_BE_Workspace_File_Close_T
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Close_T <CONTEXT>::
CUTS_BE_Workspace_File_Close_T (CONTEXT & context)
{
}
template <typename CONTEXT>
CUTS_INLINE
CUTS_BE_Workspace_File_Close_T <CONTEXT>::~CUTS_BE_Workspace_File_Close_T (void)
{
}
template <typename CONTEXT>
CUTS_INLINE
void CUTS_BE_Workspace_File_Close_T <CONTEXT>::generate (void)
{
}
|
[
"hillj@cs.iupui.edu"
] |
hillj@cs.iupui.edu
|
2b57f2e03cc674f87dae1430e91771ec81d4a552
|
ef8e28a7b0648d3e09e39d037c0d313a98ef3cea
|
/D3/3456. 직사각형 길이 찾기.cpp
|
d9a7bb27dee695d5b55b130dc768372397692f4d
|
[] |
no_license
|
RBJH/SWExpertAcademy
|
07eecf6039e8178797e0a9ac3b0e9c8aa43f0c3e
|
3b3cb2f71ce33e8f748831e4cb8c5b032551f846
|
refs/heads/master
| 2020-07-03T09:12:44.652707
| 2019-10-25T12:33:55
| 2019-10-25T12:33:55
| 201,862,798
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 331
|
cpp
|
#include <iostream>
using namespace std;
int T;
int result;
int main() {
cin >> T;
for (int t = 1; t <= T; t++) {
int a, b, c;
cin >> a >> b >> c;
if (a == b)
result = c;
else if (b == c)
result = a;
else
result = b;
cout << '#' << t << ' ' << result << '\n';
}
return 0;
}
|
[
"46277703+RBJH@users.noreply.github.com"
] |
46277703+RBJH@users.noreply.github.com
|
30599d3311bf95f06c167072c49f27d202f68cd0
|
5bae9cd60b37145ebdb7555eeda44610fd8b2451
|
/MultiCameraTrafficSignDetection/KalmanFilterTracker.cpp
|
308f66b1a35a387df1b35aa1a8217c90d127cb9c
|
[] |
no_license
|
JayYangSS/ResearchMaster
|
1097674bd5d62a433108471f128496ab94d1481a
|
87ca8571e2c5272b49a69c227a1f38708214ae4f
|
refs/heads/master
| 2021-01-15T08:30:59.835558
| 2015-02-27T19:20:16
| 2015-02-27T19:20:16
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 8,697
|
cpp
|
#include "stdafx.h"
using namespace cv;
using namespace std;
const int stateNum = 8; //x,y,width,height,detax,detay,deta width,deta height
const int measureNum = 4; //detax,detay,deta width,deta height
KalmanFilterTracker::KalmanFilterTracker()
{
KF = KalmanFilter(stateNum, measureNum, 0);
statePostMat = Mat (stateNum, measureNum, CV_32F);
statePreMat = Mat(measureNum, 1, CV_32F);
precessNoise = Mat(stateNum, 1, CV_32F);
measurement = Mat (measureNum, 1, CV_32F);
measurement.setTo(Scalar::all(0));
init = false;
}
void KalmanFilterTracker::initKF(int x, int y, int width, int height)
{
cout<<"KalmanFilterTrackerInitialization"<<endl;
if(!measureRectVector.empty() )
{
measureRectVector.clear();
cout << "clear measureRectVector"<<endl;
}
if(!predictRectVector.empty() )
{
predictRectVector.clear();
cout << "clear predictRectVector"<<endl;
}
KF.statePost.at<float>(0) = x;
KF.statePost.at<float>(1) = y;
KF.statePost.at<float>(2) = width;
KF.statePost.at<float>(3) = height;
KF.statePost.at<float>(4) = 0;
KF.statePost.at<float>(5) = 0;
KF.statePost.at<float>(6) = 0;
KF.statePost.at<float>(7) = 0;
KF.transitionMatrix = *(Mat_<float>(8, 8) << 1,0,0,0,1,0,0,0, //initialize post state of kalman filter at random
0,1,0,0,0,1,0,0, //state(x,y,width,height,detaX,detaY,detawidth,detaheight), the bigger value of detaX and detaY,
0,0,1,0,0,0,1,0, //the faster tracking speed,original 1,1
0,0,0,1,0,0,0,1,
0,0,0,0,1,0,0,0,
0,0,0,0,0,1,0,0,
0,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,1);
//setIdentity(KF.measurementMatrix);
//setIdentity(KF.processNoiseCov, Scalar::all(1e-4));
//setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
//setIdentity(KF.errorCovPost, Scalar::all(.1));
//measurement matrix (H) 观测模型
setIdentity(KF.measurementMatrix); //setIdentity: initializes a scaled identity matrix; 缩放的单位对角矩阵;
//process noise covariance matrix (Q)
setIdentity(KF.processNoiseCov, Scalar::all(1e-5)); // wk 是过程噪声,并假定其符合均值为零,协方差矩阵为Qk(Q)的多元正态分布;
//measurement noise covariance matrix (R)
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1)); //vk 是观测噪声,其均值为零,协方差矩阵为Rk,且服从正态分布;
//priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ A代表F: transitionMatrix
setIdentity(KF.errorCovPost, Scalar::all(1)); //预测估计协方差矩阵;
//corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
initRect = Rect(x, y, width, height);
predictRectVector.push_back(initRect);
init = true;
counter = 0;
}
void KalmanFilterTracker::updateKF(int x, int y, int width, int height)
{
cout<<"KalmanFilterTrackerUpdateKF"<<endl;
if ( !init )
initKF(x, y, width, height);
//step 1: predit next position based on former position
Mat predictionb = KF.predict(); //prediction before update
Rect predictRect(predictionb.at<float>(0), predictionb.at<float>(1),predictionb.at<float>(2),predictionb.at<float>(3));
//step 2: update measurement
measurement.at<float>(0) = x;
measurement.at<float>(1) = y;
measurement.at<float>(2) = width;
measurement.at<float>(3) = height;
Rect measureRect(measurement.at<float>(0), measurement.at<float>(1),measurement.at<float>(2),measurement.at<float>(3));
measureRectVector.push_back(measureRect); //update measurement
if(measureRectVector.size() > 20) //keep 10 point to draw line
measureRectVector.erase(measureRectVector.begin()); //delete first element
//step 3: give corrected position based on updated measurement and prediction
Mat correct = KF.correct(measurement); //update statepost
Rect stateRect( correct.at<float>(0), correct.at<float>(1), correct.at<float>(2), correct.at<float>(3) );
predictRectVector.push_back(stateRect); //keep 10 point to draw line
if(predictRectVector.size() > 20)
predictRectVector.erase(predictRectVector.begin()); //delete first element
}
void KalmanFilterTracker::updateWithoutMeasurement()
{
cout<<"KalmanFilterTrackerUpdateWithoutMeasurement"<<endl;
//step 1: predit next position based on former position
Mat predictionb = KF.predict(); //prediction before update
Rect predictRect(predictionb.at<float>(0), predictionb.at<float>(1),predictionb.at<float>(2),predictionb.at<float>(3));
//step 2: update measurement
measurement.at<float>(0) = predictionb.at<float>(0);
measurement.at<float>(1) = predictionb.at<float>(1);
measurement.at<float>(2) = predictionb.at<float>(2);
measurement.at<float>(3) = predictionb.at<float>(3);
Rect measureRect(measurement.at<float>(0), measurement.at<float>(1),measurement.at<float>(2),measurement.at<float>(3));
measureRectVector.push_back(measureRect); //update measurement
if(measureRectVector.size() > 20) //keep 10 point to draw line
measureRectVector.erase(measureRectVector.begin()); //delete first element
//step 3: give corrected position based on updated measurement and prediction
Mat correct = KF.correct(measurement); //update statepost
Rect stateRect( correct.at<float>(0), correct.at<float>(1), correct.at<float>(2), correct.at<float>(3) );
predictRectVector.push_back(stateRect); //keep 10 point to draw line
if(predictRectVector.size() > 20)
predictRectVector.erase(predictRectVector.begin()); //delete first element
}
void KalmanFilterTracker::changeStatus(Mat& img)
{
size_t i,j;
warningStatus = ("");
dangerStatus = ("");
space = (" + ");
if( predictRectVector.size() > 0 && predictRectVector.size() < 3)
{
warningStatus = string("Tracking Initialized");
}
else if( predictRectVector.size() > 3 )
{
j = predictRectVector.size() - 1;
i = predictRectVector.size()/2;
if( abs((predictRectVector[j].x+(predictRectVector[j].width/2)) - (img.cols/2)) <
abs((predictRectVector[i].x+(predictRectVector[i].width/2)) - (img.cols/2)) )
{
warningStatus = string("Warning");
if( (predictRectVector[j].y+predictRectVector[j].height) > (img.rows/2) )
{
dangerStatus = string("DANGER!");
}
}
}
}
void KalmanFilterTracker::putStatusText(Mat& img)
{
size_t j;
if(predictRectVector.size() > 0)
{
j = predictRectVector.size() - 1;
putText(img, warningStatus, Point( predictRectVector[j].br().x, predictRectVector[j].br().y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 255), 1, 8, false);//rbg,255,255,0
putText(img, dangerStatus, Point( predictRectVector[j].x, predictRectVector[j].y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1, 8, false);//scalar:bgr
}
}
void KalmanFilterTracker::drawPredictLine(Mat& img)
{
size_t j = predictRectVector.size() - 1;
for (size_t i=0; i<predictRectVector.size()-1; ++i)
{
line(img, Point((predictRectVector.at(i).x + predictRectVector.at(i).width/2),(predictRectVector.at(i).y + predictRectVector.at(i).height)),
Point((predictRectVector.at(i+1).x + predictRectVector.at(i+1).width/2),(predictRectVector.at(i+1).y + predictRectVector.at(i+1).height)), Scalar(0,255,0), 2, 8);//green line
}
rectangle(img, predictRectVector.at(j).tl(), predictRectVector.at(j).br(),Scalar(0,255,0), 2, 8);//green rectangle
cout<<"predictRectVector.size() : "<< j <<endl;
}
void KalmanFilterTracker::drawMeasureLine(Mat& img)
{
size_t j = measureRectVector.size() - 1;
for (size_t i=0; i<measureRectVector.size()-1; ++i)
{
line(img, Point((measureRectVector.at(i).x + measureRectVector.at(i).width/2),(measureRectVector.at(i).y + measureRectVector.at(i).height)),
Point((measureRectVector.at(i+1).x + measureRectVector.at(i+1).width/2),(measureRectVector.at(i+1).y + measureRectVector.at(i+1).height)), Scalar(255,0,0), 2, 8);
}
rectangle(img, measureRectVector.at(j).tl(), measureRectVector.at(j).br(),Scalar(255,0,0), 2, 8);//blue rectangle
cout<<"measureRectVector.size() : "<< j <<endl;
}
void KalmanFilterTracker::addcounter()
{
counter += 1;
}
int KalmanFilterTracker::getcounter()
{
return counter;
}
void KalmanFilterTracker::drawPretictLinelns(Mat img, double ratio, int resx, int resy, int tempx, int tempy)
{
}
void KalmanFilterTracker::drawMeasureLinelns(Mat img, double ratio, int resx, int resy, int tempx, int tempy)
{
}
|
[
"terryzuoty@gmail.com"
] |
terryzuoty@gmail.com
|
4f8f74686682f975ecb1419fbcdb1747c9dcdf1e
|
948f4e13af6b3014582909cc6d762606f2a43365
|
/testcases/juliet_test_suite/testcases/CWE134_Uncontrolled_Format_String/s01/CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G.cpp
|
325ffff5528105ccb4cc14db3ff2ec165f8e7004
|
[] |
no_license
|
junxzm1990/ASAN--
|
0056a341b8537142e10373c8417f27d7825ad89b
|
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
|
refs/heads/master
| 2022-08-02T15:38:56.286555
| 2022-06-16T22:19:54
| 2022-06-16T22:19:54
| 408,238,453
| 74
| 13
| null | 2022-06-16T22:19:55
| 2021-09-19T21:14:59
| null |
UTF-8
|
C++
| false
| false
| 2,411
|
cpp
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-83_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: console Read input from the console
* GoodSource: Copy a fixed string into data
* Sinks: vprintf
* GoodSink: vprintf with a format string
* BadSink : vprintf without a format string
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_console_vprintf_83.h"
namespace CWE134_Uncontrolled_Format_String__char_console_vprintf_83
{
CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G::CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G(char * dataCopy)
{
data = dataCopy;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
static void goodB2GVaSink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* FIX: Specify the format disallowing a format string vulnerability */
vprintf("%s", args);
va_end(args);
}
}
CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G::~CWE134_Uncontrolled_Format_String__char_console_vprintf_83_goodB2G()
{
goodB2GVaSink(data, data);
}
}
#endif /* OMITGOOD */
|
[
"yzhang0701@gmail.com"
] |
yzhang0701@gmail.com
|
46fd2bdc5974730302844cf0a395fe4d7772676b
|
088f6b9c903359167ab92422d869b5a7bd0f1521
|
/src/bll/AgendaService.h
|
c1ef509ba0d9ea6e217d3204f3aef880cd062a83
|
[
"MIT"
] |
permissive
|
donydchen/Agenda
|
ccc3a7a1e0f404bf94df08f5235562bed028b973
|
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
|
refs/heads/master
| 2021-06-17T00:33:08.344625
| 2017-05-26T16:54:24
| 2017-05-26T16:54:24
| 58,138,327
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,516
|
h
|
#ifndef AGENDASERVICE_H
#define AGENDASERVICE_H
#include "../entity/User.h"
#include "../entity/Meeting.h"
#include <list>
#include <string>
class AgendaService {
public:
virtual bool userLogIn(std::string userName, std::string password) = 0;
virtual bool userRegister(std::string userName, std::string password,
std::string email, std::string phone) = 0;
virtual bool deleteUser(std::string userName, std::string password) = 0;
// a user can only delete itself
virtual std::list<User> listAllUsers(void) const = 0;
virtual bool createMeeting(std::string userName, std::string title,
std::string participator,
std::string startDate, std::string endDate) = 0;
virtual std::list<Meeting> meetingQuery(std::string userName, std::string title) const = 0;
virtual std::list<Meeting> meetingQuery(std::string userName, std::string startDate,
std::string endDate) const = 0;
virtual std::list<Meeting> listAllMeetings(std::string userName) const = 0;
virtual std::list<Meeting> listAllSponsorMeetings(std::string userName) const = 0;
virtual std::list<Meeting> listAllParticipateMeetings(std::string userName) const = 0;
virtual bool deleteMeeting(std::string userName, std::string title) = 0;
virtual bool deleteAllMeetings(std::string userName) = 0;
std::string getServiceName(void) {return serviceName_;}
protected:
std::string serviceName_;
};
#endif
|
[
"chenyvehtung@163.com"
] |
chenyvehtung@163.com
|
40ee8a170d90789e7c8f5ba48366dfebbd99d0e6
|
a947e018ec7036b98520aefea01d3ade68fafa92
|
/src/CommandLineParser.hpp
|
e29c0aeb25179c729d88432b3c86d85d32d76e5d
|
[] |
no_license
|
qutab/ata_identify
|
1db9885a3c6c31c8562dc5f33895e7734b45190f
|
755a82ec9f632ad4a2159b8dd2d2fd570d446af6
|
refs/heads/master
| 2020-04-08T06:08:30.810334
| 2018-11-26T00:09:17
| 2018-11-26T00:09:17
| 159,086,893
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 630
|
hpp
|
#pragma once
#include <string>
#include <vector>
namespace utils {
/** Parser for command line arguments */
class CommandLineParser final
{
public:
/**
* @param argc number of command line args
* @param argv array of command line args
*/
CommandLineParser(int argc, char* argv[]);
~CommandLineParser();
/** @return upstream endpoint parsed from command line */
std::string getFilename() const;
/** @return whether verbose logging is requested */
bool isVerbose() const;
std::string getUsageMsg() const;
private:
std::vector<std::string> argsM;
};
} /* namespace utils */
|
[
"qazi_qutab@hotmail.com"
] |
qazi_qutab@hotmail.com
|
674ec817498caa5ae04f180e05fde9d58e2b7b20
|
18c95cc0e34c1a77e46774feb939762aca390d73
|
/src/GraphicAPI.cpp
|
09716f091e06965cfe6fb60912eae8c88ba3f7a0
|
[] |
no_license
|
aleiii/GraphicAPI
|
d8d5c506bc6e355bb0f5f48f8cc24cd4146949f5
|
ffc3c144d99d679f2ad83b8381faffe72551206c
|
refs/heads/master
| 2022-07-11T23:02:02.372103
| 2020-05-07T05:19:28
| 2020-05-07T05:19:28
| 261,947,129
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,026
|
cpp
|
// GraphicAPI.cpp : 定义应用程序的入口点。
//
//#include "framework.h"
#include "GraphicAPI.h"
#include "GraphicDraw.h"
#define MAX_LOADSTRING 100
#define WIN_WIDTH 1200
#define WIN_HEIGHT 800
using namespace ALEI;
// 全局变量:
HINSTANCE hInst; // 当前实例
WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
// 此代码模块中包含的函数的前向声明:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int, HWND&);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void MY_PAINT_MISSION(HDC hdc);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
//HINSTANCE hInstance = GetModuleHandle(0);
//int nCmdShow = 10;
// 初始化全局字符串
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_GRAPHICAPI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
HWND hWnd;
// 执行应用程序初始化:
if (!InitInstance (hInstance, nCmdShow, hWnd))
{
return FALSE;
}
HDC hdc = GetDC(hWnd);
// TODO: 在此处放置代码。
// MY_PAINT_MISSION(hdc);
//ALEI::line(hdc, 100, 100, 200, 300);
//ALEI::circle(hdc, 150, 150, 100, 3*pi/4, 2*pi);
//ALEI::ellipse(hdc, 400, 400, 100, 50);
//用线段画一个矩形
ALEI::line(hdc, 500, 200, 600, 200);
ALEI::line(hdc, 500, 250, 600, 250);
ALEI::line(hdc, 500, 200, 500, 250);
ALEI::line(hdc, 600, 200, 600, 250);
ALEI::Flood_Fill_4(hdc, 550, 210, RGB(255,255,255), RGB(255,0,0));
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GRAPHICAPI));
MSG msg;
// 主消息循环:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 函数: MyRegisterClass()
//
// 目标: 注册窗口类。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GRAPHICAPI));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
// wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GRAPHICAPI);
// 菜单栏
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// 函数: InitInstance(HINSTANCE, int)
//
// 目标: 保存实例句柄并创建主窗口
//
// 注释:
//
// 在此函数中,我们在全局变量中保存实例句柄并
// 创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow, HWND &hWnd)
{
hInst = hInstance; // 将实例句柄存储在全局变量中
hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, WIN_WIDTH, WIN_HEIGHT, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 目标: 处理主窗口的消息。
//
// WM_COMMAND - 处理应用程序菜单
// WM_PAINT - 绘制主窗口
// WM_DESTROY - 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
//case WM_COMMAND:
// {
// int wmId = LOWORD(wParam);
// // 分析菜单选择:
// switch (wmId)
// {
// case IDM_ABOUT:
// DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
// break;
// case IDM_EXIT:
// DestroyWindow(hWnd);
// break;
// default:
// return DefWindowProc(hWnd, message, wParam, lParam);
// }
// }
// break;
//case WM_PAINT:
// {
// //PAINTSTRUCT ps;
// //HDC hdc = BeginPaint(hWnd, &ps);
// //// TODO: 在此处添加使用 hdc 的任何绘图代码...
// //EndPaint(hWnd, &ps);
// }
// break;
case WM_ERASEBKGND:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
//// “关于”框的消息处理程序。
//INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
//{
// UNREFERENCED_PARAMETER(lParam);
// switch (message)
// {
// case WM_INITDIALOG:
// return (INT_PTR)TRUE;
//
// case WM_COMMAND:
// if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
// {
// EndDialog(hDlg, LOWORD(wParam));
// return (INT_PTR)TRUE;
// }
// break;
// }
// return (INT_PTR)FALSE;
//}
// 此处为绘图任务内容
void MY_PAINT_MISSION(HDC hdc) {
for (int i = 0; i < 400; i++)
{
for (int j = 0; j < 400; j++)
SetPixel(hdc, i, j, RGB(255, 182, 193));
}
SetPixel(hdc, 200, 200, RGB(255, 0, 0));
}
|
[
"lightning6327@gmail.com"
] |
lightning6327@gmail.com
|
cc195c69a4b9b99274016030db3d9aea92fda2a5
|
b43f60bde4985a855e880822085e8c47c1c8b0ed
|
/moses/FF/SoftMatchingFeature.h
|
5f0268e81b7d45d8ca0b164635a3d0814c0863d1
|
[] |
no_license
|
BinaryBlob/mosesdecoder
|
2cf806c579cbe0b8b4769f2273d2a134ba8271ad
|
4488d97629017a644681e008168c891c46fc95b6
|
refs/heads/master
| 2021-04-18T18:41:05.452146
| 2014-02-14T11:22:53
| 2014-02-14T11:22:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,329
|
h
|
#pragma once
#include <stdexcept>
#include "moses/Util.h"
#include "moses/Word.h"
#include "StatelessFeatureFunction.h"
#include "moses/TranslationModel/PhraseDictionaryNodeMemory.h"
#ifdef WITH_THREADS
#include <boost/thread/shared_mutex.hpp>
#endif
namespace Moses
{
class SoftMatchingFeature : public StatelessFeatureFunction
{
public:
SoftMatchingFeature(const std::string &line);
bool IsUseable(const FactorMask &mask) const {
return true;
}
virtual void EvaluateChart(const ChartHypothesis& hypo,
ScoreComponentCollection* accumulator) const;
void Evaluate(const Phrase &source
, const TargetPhrase &targetPhrase
, ScoreComponentCollection &scoreBreakdown
, ScoreComponentCollection &estimatedFutureScore) const {};
void Evaluate(const InputType &input
, const InputPath &inputPath
, const TargetPhrase &targetPhrase
, ScoreComponentCollection &scoreBreakdown
, ScoreComponentCollection *estimatedFutureScore = NULL) const {};
void Evaluate(const Hypothesis& hypo,
ScoreComponentCollection* accumulator) const {};
bool Load(const std::string &filePath);
std::map<Word, std::set<Word> >& Get_Soft_Matches() {
return m_soft_matches;
}
std::map<Word, std::set<Word> >& Get_Soft_Matches_Reverse() {
return m_soft_matches_reverse;
}
const std::string& GetFeatureName(const Word& LHS, const Word& RHS) const;
void SetParameter(const std::string& key, const std::string& value);
private:
std::map<Word, std::set<Word> > m_soft_matches; // map LHS of old rule to RHS of new rle
std::map<Word, std::set<Word> > m_soft_matches_reverse; // map RHS of new rule to LHS of old rule
typedef std::pair<Word, Word> NonTerminalMapKey;
#if defined(BOOST_VERSION) && (BOOST_VERSION >= 104200)
typedef boost::unordered_map<NonTerminalMapKey,
std::string,
NonTerminalMapKeyHasher,
NonTerminalMapKeyEqualityPred> NonTerminalSoftMatchingMap;
#else
typedef std::map<NonTerminalMapKey, std::string> NonTerminalSoftMatchingMap;
#endif
mutable NonTerminalSoftMatchingMap m_soft_matching_cache;
#ifdef WITH_THREADS
//reader-writer lock
mutable boost::shared_mutex m_accessLock;
#endif
};
}
|
[
"rico.sennrich@gmx.ch"
] |
rico.sennrich@gmx.ch
|
1864bd86b85e71d76929ec0ac108937c8962779e
|
bd3915c51fb828204db56f61151314dc3fc7cb8e
|
/appointments_manage/task_management_tool.cpp
|
da19d50bd38474b347565e4dc6b394afb7ac3f49
|
[] |
no_license
|
kayduemre/DataStructurs
|
731b5c2fc80a0e5f4745edb8f9ab0444912d6015
|
e5554c7e685d0d325f90c9e519d88fef54a2371e
|
refs/heads/master
| 2020-04-12T10:00:15.736845
| 2019-12-09T22:20:42
| 2019-12-09T22:20:42
| 162,415,714
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,856
|
cpp
|
/* @Author
Student Name: Emre KAYDU
Student ID : 150160552
Date: 4.11.2019 */
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include "task_management_tool.h"
using namespace std;
void WorkPlan::display(bool verbose,bool testing)
{
string inone="***";
if (head!=NULL)
{
Task *pivot =new Task;
Task *compeer =new Task;
pivot=head;
do
{
if(testing)
inone+=" ";
else
cout << pivot->day <<". DAY"<< endl;
compeer=pivot;
while(compeer!=NULL)
{
string PREV= compeer->previous!=NULL?compeer->previous->name:"NULL";
string NEXT=compeer->next!=NULL?compeer->next->name:"NULL";
string CONT=compeer->counterpart!=NULL?compeer->counterpart->name:"NULL";
if (testing)
inone+=compeer->name;
else
if(verbose)
cout<<"\t"<<setw(2)<< compeer->time <<":00\t"<< PREV<<"\t<- "<< compeer->name <<"("<< compeer->priority <<")->\t"<<NEXT <<"\t |_"<<CONT<<endl;
else
cout<<"\t"<<setw(2)<< compeer->time <<":00\t"<< compeer->name <<"("<< compeer->priority <<")"<<endl;
compeer=compeer->counterpart;
}
pivot=pivot->next;
}while(pivot!=head);
if(testing)
{
cout<<inone<<endl;
cout<<"(checking cycled list:";
if (checkCycledList())
cout<<" PASS)"<<endl;
else
cout<<" FAIL)"<<endl;
}
}
else
cout<<"There is no task yet!"<<endl;
}
void WorkPlan::delaytask(int day, int time)
{
Task *oldone=new Task();
Task *newone=new Task();
if (day>0 and time>0)
{
oldone=getTask(day, time);
if (oldone!=NULL)
{
newone->name=new char [strlen(oldone->name)];
newone->name=oldone->name;
newone->priority=oldone->priority;
checkAvailableNextTimesFor(oldone);
cout<<getUsableDay()<<".day and "<<std::setw(2)<<getUsableTime()<<":00 is the first available day and hour for delaying the task "<<oldone->name<<" that is on "<<oldone->day<<".day at "<<std::setw(2)<< oldone->time <<":00"<<endl;
newone->day=getUsableDay();
newone->time=getUsableTime();
remove(oldone);
add(newone);
}
}
else
cout<<"Invalid input!"<<endl;
}
bool WorkPlan::checkavailabletime(Task *receive)
{
Task *traverse;
traverse = receive;
int time = 8;
bool flag = false;
if (traverse->time > 8)
{
usable_time = time;
flag = true;
return flag;
}
while (traverse)
{
if((traverse->time != time) && (time !=17))
{
usable_time = time;
flag = true;
return flag;
}
if( traverse->counterpart == NULL && time !=17)
{
time++;
usable_time = time;
flag = true;
return flag;
}
traverse = traverse->counterpart;
time++;
}
return flag;
}
void WorkPlan::checkavailableday(Task *receive)
{
Task *traverse = receive;
do
{
traverse = traverse->next;
if (checkavailabletime(traverse))
{
usable_day = traverse->day;
return;
}
}while (traverse != traverse->previous);
}
void WorkPlan::make_node(Task *node)
{
Task *newnode = new Task;
*newnode = *node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = newnode;
newnode->previous = newnode;
newnode->counterpart = NULL;
head = newnode;
}
void WorkPlan::insertbegin(Task *node)
{
Task *last = head->previous;
Task *newnode = new Task;
*newnode = *node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = head;
newnode->previous = last;
last->next = newnode;
head->previous = newnode;
head = newnode;
newnode->counterpart = NULL;
}
void WorkPlan::insertend(Task *node)
{
Task *last = head->previous;
Task *newnode = new Task;
*newnode =*node;
newnode->name = new char[strlen(node->name)];
strcpy(newnode->name, node->name);
newnode->next = head;
head->previous = newnode;
newnode->previous = last;
last->next = newnode;
newnode->counterpart =NULL;
}
int WorkPlan::getUsableDay()
{
return usable_day;
}
int WorkPlan::getUsableTime()
{
return usable_time;
}
void WorkPlan::create()
{
head = NULL;
}
void WorkPlan::close()
{
/*
Task *p, *q;
while (head)
{
p = head;
head = head->next;
q = p->counterpart;
while (q)
{
p->counterpart = p->counterpart->counterpart;
delete q;
q = p->counterpart;
}
delete p;
}
*/
}
void WorkPlan::add(Task *task)
{
Task *last, *begin;
Task *newnode = new Task;
*newnode = *task;
newnode->name = new char[strlen(task->name)];
strcpy(newnode->name, task->name);
newnode->counterpart = NULL;
newnode->next = NULL;
newnode->previous = NULL;
if(head == NULL)
{
make_node(newnode);
return;
}
else if(head->day > newnode->day)
{
insertbegin(newnode);
return;
}
else if(head->previous->day < newnode->day)
{
insertend(newnode);
return;
}
else if (head->day == newnode->day)
{
Task *traverse, *tail;
traverse = head;
tail = head;
begin = traverse;
if ((traverse->time > newnode->time))
{
last = head->previous;
newnode->counterpart = traverse;
traverse = traverse->next;
newnode->next = traverse;
traverse->previous = newnode;
newnode->previous = last;
last->next = newnode;
newnode->counterpart->next = NULL;
newnode->counterpart->previous = NULL;
head = newnode;
return;
}
while (traverse && (traverse->time < newnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if(traverse && (traverse->time > newnode->time))
{
newnode->counterpart = traverse;
tail->counterpart = newnode;
return;
}
if (traverse && (traverse->time == newnode->time))
{
if ((traverse->priority > newnode->priority) || (traverse->priority == newnode->priority))
{
if (checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
else if (traverse->priority < newnode->priority)
{
Task *node = new Task;
node->name = new char[strlen(traverse->name)];
node->name = traverse->name;
node->priority = traverse->priority;
node->time = traverse->time;
traverse->name = new char[strlen(newnode->name)];
traverse->name = newnode->name;
traverse->priority = newnode->priority;
newnode->name = new char[strlen(node->name)];
newnode->name = node->name;
newnode->priority = node->priority;
delete node;
if (checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
}
else
{
tail->counterpart = newnode;
return;
}
}
else
{
Task *traverse, *tail, *last;
traverse = head;
last = head;
while((traverse != last->previous) && (traverse->day < newnode->day))
{
tail = traverse;
traverse = traverse->next;
}
if ((traverse != traverse->previous) && (traverse->day > newnode->day))
{
newnode->next = traverse;
tail->next = newnode;
traverse->previous = newnode;
newnode->previous = tail;
return;
}
if((traverse->day == newnode->day))
{
if ((traverse->time > newnode->time))
{
newnode->counterpart = traverse;
traverse = traverse->next;
newnode->next = traverse;
tail->next = newnode;
traverse->previous = newnode;
newnode->previous = tail;
return;
}
begin = traverse;
while ((traverse) && (traverse->time < newnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if(traverse && (traverse->time > newnode->time))
{
newnode->counterpart = traverse;
tail->counterpart = newnode;
return;
}
if (traverse && (traverse->time == newnode->time))
{
if ((traverse->priority > newnode->priority) || (traverse->priority == newnode->priority) )
{
if(checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
else if(traverse->priority < newnode->priority)
{
Task *node = new Task;
node->name = new char[strlen(traverse->name)];
node->name = traverse->name;
node->priority = traverse->priority;
traverse->name = new char[strlen(newnode->name)];
traverse->name = newnode->name;
traverse->priority = newnode->priority;
newnode->name = new char[strlen(node->name)];
newnode->name = node->name;
newnode->priority = node->priority;
delete node;
if(checkavailabletime(begin))
{
int time = getUsableTime();
newnode->time = time;
add(newnode);
}
else
{
checkavailableday(begin);
int time = getUsableTime();
int day = getUsableDay();
newnode->time = time;
newnode->day = day;
add(newnode);
}
}
}
else
{
tail->counterpart = newnode;
return;
}
}
else
{
insertend(newnode);
}
}
}
Task * WorkPlan::getTask(int day, int time)
{
Task *traverse = head, *tail;;
while (traverse)
{
if(traverse->day == day)
{
while (traverse && (traverse->time != time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse)
{
return traverse;
}
else
{
return tail;
}
}
traverse = traverse->next;
}
return traverse;
}
void WorkPlan::last_time(Task *day)
{
Task *traverse = head,*tail;
while (traverse->day != day->day)
{
cout<<traverse->day;
traverse = traverse->next;
}
while (traverse)
{
tail = traverse;
traverse = traverse->counterpart;
}
last_Time = tail->time;
}
void WorkPlan::checkAvailableNextTimesFor(Task *delayed)
{
Task *traverse = head, *node,*checkhead;
node = delayed;
while (traverse->day != node->day)
{
traverse = traverse->next;
}
traverse = traverse->next;
checkhead = traverse->next;
//while (traverse)
//{
// tail = traverse;
// traverse = traverse->counterpart;
//}
//int lasttime = tail->time;
//traverse = checkhead;
int time = 8;
if (traverse->time > 8)
{
usable_time = time;
usable_day = traverse->day;
return;
}
while (traverse)
{
time = 8;
if (traverse->time > 8)
{
usable_time = time;
usable_day = traverse->day;
return;
}
while (traverse)
{
last_time(traverse);
if((traverse->time != time) && (time !=17) && (traverse->time != last_Time))
{
usable_time = time;
usable_day = traverse->day;
return;
}
if( traverse->counterpart == NULL && (time !=17) && (traverse->time != last_Time))
{
usable_time = time;
usable_day = traverse->day;
return;
}
traverse = traverse->counterpart;
time++;
}
traverse = checkhead;
traverse = traverse->next;
}
}
void WorkPlan::delayAllTasksOfDay(int day)
{
Task *traverse = head;
while (traverse->day != day)
{
traverse = traverse->next;
}
while (traverse)
{
int day = traverse->day;
int time = traverse->time;
delaytask(day, time);
traverse = traverse->counterpart;
}
}
void WorkPlan::remove(Task *target)
{
Task *tail, *traverse, *targetnode, *last;
targetnode = new Task;
*targetnode = *target;
traverse = head;
tail = traverse;
last = head->previous;
if ((traverse->day == targetnode->day))
{
if ((traverse->counterpart == NULL))
{
last = traverse->previous;
traverse = traverse->next;
last->next = head;
head->previous = last;
delete traverse;
return;
}
else if (traverse->time == targetnode->time)
{
//Task *del = traverse;
last = head->previous;
traverse = traverse->counterpart;
//delete del;
traverse->next = head->next;
head->next->previous = traverse;
traverse->previous = last;
head = traverse;
last->next = head;
return;
}
else
{
while (traverse && traverse->time !=targetnode->time)
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse->counterpart != NULL)
{
tail->counterpart = traverse->counterpart;
delete traverse;
}
else
{
//Task *del = traverse;
tail->counterpart = NULL;
//delete del;
}
}
}
else if (last->day == targetnode->day)
{
if ((last->counterpart == NULL))
{
Task *temp= last;
last = last->previous;
last->next = head;
head->previous = last;
delete temp;
}
else if (last->time == targetnode->time)
{
Task *temp= last;
Task *tail = last->previous;
last = last->counterpart;
tail->next = last;
last->previous = tail;
last->next = head;
head->previous = last;
delete temp;
}
else
{
traverse = last;
if (traverse->time ==targetnode->time)
{
Task *temp = traverse;
traverse = traverse->counterpart;
traverse->next = temp->next;
temp->next->previous = traverse;
traverse->previous = tail;
tail->next = traverse;
return;
}
while (traverse && traverse->time !=targetnode->time)
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse->counterpart != NULL)
{
tail->counterpart = traverse->counterpart;
delete traverse;
}
else
{
tail->counterpart = NULL;
delete traverse;
}
}
}
else
{
while (traverse->day != targetnode->day)
{
tail = traverse;
traverse = traverse->next;
}
if (traverse->counterpart == NULL)
{
traverse = traverse->next;
tail->next = traverse;
traverse->previous = tail;
//delete temp;
return;
}
if (traverse->time == targetnode->time)
{
Task *temp = traverse;
traverse = traverse->counterpart;
traverse->next = temp->next;
temp->next->previous = traverse;
traverse->previous = tail;
tail->next = traverse;
return;
}
while (traverse && (traverse->time != targetnode->time))
{
tail = traverse;
traverse = traverse->counterpart;
}
if (traverse != NULL)
{
tail->counterpart = traverse->counterpart;
return;
//delete traverse;
}
else
{
tail->counterpart = NULL;
//delete traverse;
}
}
}
bool WorkPlan::checkCycledList()
{
Task *pivot=new Task();
pivot=head;
int patient=100;
bool r=false;
while (pivot!=NULL&&patient>0)
{
patient--;
pivot=pivot->previous;
if(pivot==head)
{
r=true;
break;
}
}
cout<<"("<<100-patient<<")";
patient=100;
bool l=false;
while (pivot!=NULL&&patient>0)
{
patient--;
pivot=pivot->next;
if(pivot==head)
{
l=true;
break;
}
}
return r&l;
}
|
[
"emre.kyd11@gmail.com"
] |
emre.kyd11@gmail.com
|
7ca817811ec94d06cc2d31ce3ad0dc17b4f228eb
|
3f1dc92ed9d39ee93f8d3895f71b12623efd4f4f
|
/WLModBus/CMyComObject.h
|
7c23fbe9173db1eb90d55a89b6d801a46fdd872b
|
[] |
no_license
|
Junkg/ModBusProtocol
|
6202abb63dccbec515b285aeb1713f1b0821b734
|
fae57d8b4f0dd7481c64ffdfbcdf35aa71fafb72
|
refs/heads/master
| 2020-06-13T23:50:48.183078
| 2019-07-02T08:57:41
| 2019-07-02T08:57:41
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 6,202
|
h
|
#ifndef __CMYCOMOBJECT_H__
#define __CMYCOMOBJECT_H__
#pragma once
#include "MBInterface.h"
extern "C" ULONG g_ObjNumber;
// {33C2DAE3-6F89-4318-9F06-9820C87DE202}
extern "C" CLSID CLSID_MODBUS;
class CModBus
{
public:
CModBus();
virtual ~CModBus();
//PDU
/*检查功能吗是否正确*/
ModbusStatus CheckFunctionCode(FunctionCode fc);
/*作为RTU主站或TCP客户端)时,生成读写RTU从站或TCP服务器)对象的命令*/
uint16_t GenerateReadWriteCommand(ObjAccessInfo objInfo, bool* statusList, uint16_t* registerList, uint8_t* commandBytes);
/*解析RTU主站或 TCP客户端)从服务器读取的数据 */
void TransformClientReceivedData(uint8_t* receivedMessage, uint16_t quantity, bool* statusList, uint16_t* registerLister);
//RTU
/*通过CRC校验校验接收的信息是否正确*/
bool CheckRTUMessageIntegrity(uint8_t* message, uint16_t length);
/*生成CRC-16/MODBUS 校验码 多项式: x16 + x15 + x2 + 1 */
uint16_t GenerateCRC16CheckCode(uint8_t* puckData, uint16_t usDataLen);
//COMMON
/*将接收到的写单个Coil值转化为布尔量,对应0x05功能码*/
bool CovertSingleCommandCoilToBoolStatus(uint16_t coilValue, bool value);
/*将布尔量(线圈和输入状态)数组转化为MB字节数组,返回最终数组的长度 */
static uint8_t ConvertBoolArrayToMBByteArray(bool* sData, uint16_t length, uint8_t* oData);
/*将寄存器(输入寄存器和保持寄存器)数组转化为MB字节数组,返回最终数组的长度*/
static uint8_t ConvertRegisterArrayToMBByteArray(uint16_t* sData, uint16_t length, uint8_t* oData);
/*将接收到的写Coil字节数组转化为布尔数组*/
static void ConvertMBByteArrayTotBoolArray(uint8_t* sData, bool* oData);
/*将接收到的写保持寄存器的字节数组专为寄存器数组*/
static void ConvertMBByteArrayToRegisterArray(uint8_t* sData, uint16_t* oData);
/*获取字节中某一个位的值 从0开始*/
bool GetBitValue(uint8_t nData, char nChar);
/*设置某一位上的值,返回原来的值*/
void SetBitValue(uint8_t& nData, char nChar, bool value);
protected:
public:
ModbusStatus m_status;
};
class CModBusStorage
{
public:
/*初始化数据存储区域(创建线圈量、输入状态量、保持寄存器、输入寄存器的存储区域) 输入为结构体数组,在应用程序中定义*/
void InitializeDataStorageStructure(DataObject dataObject[], int length);
protected:
/*获取想要读取的Coil量的值*/
void GetCoilStatus(uint16_t startAddress, uint16_t quantity, bool* statusList);
/*获取想要读取的InputStatus量的值*/
void GetInputStatus(uint16_t startAddress, uint16_t quantity, bool* statusValue);
/*获取想要读取的保持寄存器的值*/
void GetHoldingRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
/*获取想要读取的输入寄存器的值*/
void GetInputRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
/*设置单个线圈的值*/
bool SetSingleCoil(uint16_t coilAddress, bool coilValue);
/*设置单个寄存器的值*/
void SetSingleRegister(uint16_t registerAddress, uint16_t registerValue);
/*设置多个线圈的值*/
void SetMultipleCoil(uint16_t startAddress, uint16_t quantity, bool* statusValue);
/*设置多个寄存器的值*/
void SetMultipleRegister(uint16_t startAddress, uint16_t quantity, uint16_t* registerValue);
private:
/*重置线圈对象的值*/
void ResetCoilStructure();
/*重置输入状态对象的值*/
void ResetInputStatusStructure();
/*重置输入寄存器对象的值*/
void ResetInputRegisterStructure();
/*重置保持对象的值*/
void ResetHoldingRegisterStructure();
private:
StatusObject m_coilObject;
StatusObject m_inputStatusObject;
RegisterObject m_inputRegisterObject;
RegisterObject m_holdingRegisterObject;
private:
CRITICAL_SECTION m_csCoil;
CRITICAL_SECTION m_csInputStatus;
CRITICAL_SECTION m_csInputRegister;
CRITICAL_SECTION m_csHodingRegister;
};
class INodelegationUnknown
{
public:
virtual HRESULT __stdcall NodelegationQueryInyterface(const IID& iid, void** ppv) = 0;
virtual ULONG __stdcall NodelegationAddRef() = 0;
virtual ULONG __stdcall NodelegationRelease() = 0;
};
class CMyComObject : public INodelegationUnknown , public IModBusTCPServer , public IModBusTCPClient , public IModBusRTUServer , public IModBusRTUClient
{
public:
CMyComObject(IUnknown* pUnknownOuter = NULL);
~CMyComObject();
public:
// IUnKnown
virtual HRESULT STDMETHODCALLTYPE QueryInterface(_In_opt_ REFIID riid, _COM_Outptr_ void __RPC_FAR* __RPC_FAR* ppv);
virtual ULONG STDMETHODCALLTYPE AddRef(void);
virtual ULONG STDMETHODCALLTYPE Release(void);
//INodelegationUnknown
virtual HRESULT STDMETHODCALLTYPE NodelegationQueryInyterface(const IID& iid, void** ppv);
virtual ULONG STDMETHODCALLTYPE NodelegationAddRef(void) ;
virtual ULONG STDMETHODCALLTYPE NodelegationRelease(void) ;
//IModBusTCPServer
/*解析接收到的信息,返回响应命令的长度*/
virtual uint16_t STDMETHODCALLTYPE ParsingClientAccessCommand(uint8_t* receivedMessage, uint8_t* respondBytes) ;
//IModBusTCPClient
/*生成访问服务器的命令*/
virtual uint16_t STDMETHODCALLTYPE CreateAccessServerCommand(ObjAccessInfo objInfo, void* dataList, uint8_t* commandBytes) ;
/*解析收到的服务器相应信息*/
virtual void STDMETHODCALLTYPE ParsingServerRespondMessage(uint8_t* recievedMessage, void* dataList) ;
//IModBusRTUServer
/*解析接收到的信息,并返回合成的回复信息和信息的字节长度,通过回调函数*/
virtual uint16_t STDMETHODCALLTYPE ParsingMasterAccessCommand(uint8_t* receivedMesasage, uint8_t* respondBytes, uint16_t rxLength) ;
//IModBusRTUClient
/*生成访问服务器的命令*/
virtual uint16_t STDMETHODCALLTYPE CreateAccessSlaveCommand(ObjAccessInfo objInfo, void* dataList, uint8_t* commandBytes);
/*解析收到的服务器相应信息*/
virtual void STDMETHODCALLTYPE ParsingSlaveRespondMessage(uint8_t* recievedMessage, uint8_t* command) ;
private:
ULONG m_Ref;
IUnknown* m_pUnknownOuter;
};
#endif //__CMYCOMOBJECT_H__
|
[
"yunjieKG@163.com"
] |
yunjieKG@163.com
|
98e60c687ddd4b87f50735b00d2f1aea3a1c4bf6
|
f4bafe2eadf7c541d70278aa57c70dd902e954bd
|
/Source/TowerDefence/Turrets/TDFlamethrowerTurret.h
|
e3aa6f8e1799fb40efa2a924f0b9fca073856d6c
|
[] |
no_license
|
MelnichenkoDA/UE4_TowerDefence
|
3aea920d91168252ff60012f45e389ed3472aacc
|
0f4a2a6dae0744b152e5aa6ae3640b6c54fb348d
|
refs/heads/master
| 2022-03-12T14:55:54.598260
| 2019-11-06T14:57:46
| 2019-11-06T14:57:46
| 213,161,355
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,608
|
h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Animation/AnimSequence.h"
#include "UI/TDConstructionBarWidget.h"
#include "DamageTypes/TDDamageTypeFlame.h"
#include "Components/BoxComponent.h"
#include "TDFlamethrowerTurret.generated.h"
UCLASS()
class TOWERDEFENCE_API ATDFlamethrowerTurret : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ATDFlamethrowerTurret();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void Initialise(const float & Timer);
private:
UFUNCTION()
void OnFlameBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult);
UFUNCTION()
void OnFlameEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult);
UPROPERTY(EditAnywhere)
USkeletalMeshComponent* TurretMeshComponent;
UPROPERTY(EditAnywhere)
UTDConstructionBarWidget* ConstructionBarWidget;
UPROPERTY(EditAnywhere)
UStaticMeshComponent* FlameMeshComponent;
UPROPERTY(EditAnywhere)
UBoxComponent* CollisionComponent;
UParticleSystemComponent* ParticleComponentCreation;
float ConstructionTimer;
UPROPERTY(EditAnywhere)
float Damage;
bool bConstructed;
};
|
[
"thrustdrip@gmail.com"
] |
thrustdrip@gmail.com
|
c6d56491a85ed3964e3d3e05c3cdbeac824ccf15
|
b6ed2145ed73919ec42f3d34ccb67a7ecc621b3a
|
/algorithm/Codeforces/ECRound53/a.cpp
|
5ae57362243361d728317b6cdc0117aff480621c
|
[] |
no_license
|
gilsaia/college-study
|
26d9813ab5e5f125618aec787c942e442b0fb630
|
66d2dda1b322077fd58abe56ba602da5260856be
|
refs/heads/master
| 2021-06-03T06:23:05.770868
| 2019-09-22T14:22:22
| 2019-09-22T14:22:22
| 138,689,516
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,018
|
cpp
|
#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
int num[240];
int main()
{
int n;
scanf("%d",&n);
string s;
cin>>s;
int flag=1;
for(int i=0;i<s.size();++i)
{
for(int j=s.size()-1;j>=i;--j)
{
int pan=0;
string tmp=s.substr(i,j-i+1);
memset(num,0,sizeof(num));
int len=tmp.size();
for(int t=0;t<len;++t)
{
num[tmp[t]]++;
}
for(int t=0;t<150;++t)
{
if(num[t]>len/2)
{
pan=1;
break;
}
}
if(pan==0)
{
printf("YES\n");
cout<<tmp<<endl;
flag=0;
break;
}
}
if(flag==0)
{
break;
}
}
if(flag)
{
printf("NO\n");
}
return 0;
}
|
[
"794433219@qq.com"
] |
794433219@qq.com
|
4201e04e517e4197a374132fa38ec0a4a5fe22f6
|
d556a95cded3a906cf4acd06e92daf4701d80c9a
|
/Level 2/Lab3/TransactionAccount.cpp
|
e30f05a2e5eb481498173163bca362657147b549
|
[] |
no_license
|
Hergeirs/Cpp-Obj
|
4402fb6db7664908760b3962774086fb33d201f0
|
7b968b0463cc56e1bc9e0d27be3eb6e3e49acdf2
|
refs/heads/master
| 2021-01-17T12:26:15.478314
| 2017-11-01T19:47:33
| 2017-11-01T19:47:33
| 84,065,899
| 1
| 0
| null | 2017-03-07T18:25:59
| 2017-03-06T11:33:04
|
C++
|
UTF-8
|
C++
| false
| false
| 624
|
cpp
|
#include "TransactionAccount.hpp"
TransactionAccount::TransactionAccount(const unsigned int accountNo,const double amount,const double pCredit)
:Account(accountNo,amount,TRANSACTION),credit(pCredit)
{
//
}
const bool TransactionAccount::withdraw(const double amount)
{
return balance+credit < amount ? false : (balance-=amount);
}
const bool TransactionAccount::setCredit(const double newCredit)
{
return balance+newCredit < 0 ? false : (credit=newCredit);
}
const double TransactionAccount::getUsableBalance() const
{
return balance+credit;
}
const double TransactionAccount::getCredit() const
{
return credit;
}
|
[
"hergeirs@gmail.com"
] |
hergeirs@gmail.com
|
6c35b31836f4223aa440417d0cb4eec077bf1849
|
6562bf42f158ac2e16d4b90fe12a8c815fced159
|
/openshares-node/libraries/chain/include/capricorn/chain/balance_evaluator.hpp
|
6e20f39036ee7ec42145cda4598a891232cc8525
|
[
"MIT"
] |
permissive
|
moonstonedac/openshares
|
3c302211bfa8e8e8194a2b43b61b06c8c3a55bbe
|
c6ecee64bd36cb473f24d34669401e712365f2da
|
refs/heads/master
| 2021-01-11T22:21:37.470987
| 2017-01-27T14:53:14
| 2017-01-27T14:53:14
| 78,952,910
| 0
| 0
| null | 2017-01-27T14:53:14
| 2017-01-14T16:49:35
|
C++
|
UTF-8
|
C++
| false
| false
| 1,952
|
hpp
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <capricorn/chain/protocol/transaction.hpp>
#include <capricorn/chain/database.hpp>
#include <capricorn/chain/balance_object.hpp>
#include <capricorn/chain/evaluator.hpp>
#include <capricorn/chain/exceptions.hpp>
namespace capricorn { namespace chain {
class balance_claim_evaluator : public evaluator<balance_claim_evaluator>
{
public:
typedef balance_claim_operation operation_type;
const balance_object* balance = nullptr;
void_result do_evaluate(const balance_claim_operation& op);
/**
* @note the fee is always 0 for this particular operation because once the
* balance is claimed it frees up memory and it cannot be used to spam the network
*/
void_result do_apply(const balance_claim_operation& op);
};
} } // capricorn::chain
|
[
"moonstonedac@gmail.com"
] |
moonstonedac@gmail.com
|
bfaebbfa1a5ecfcc3e1ec91cb2ee5c0b3ae531d8
|
b32b94b936f87d8b2fcc823040a4df43f6590614
|
/Codeforces/Round231/A.cpp
|
1eeb0374349a8e9b8235a5111f957534cf7478d1
|
[] |
no_license
|
nitish1402/OPC
|
e856e9d00664741f2f533706cd4c6702b9ff1759
|
98f2e8dfe78ca8b5bc09a92bcbed1a5d4304a71f
|
refs/heads/master
| 2016-09-06T08:14:04.967108
| 2014-03-26T09:01:40
| 2014-03-26T09:01:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,905
|
cpp
|
/* @author :nitish bhagat */
//header files
#include <cstdlib>
#include <stdio.h>
#include <cstring>
#include <complex>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include <numeric>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <iomanip>
#include <utility>
#include <locale>
#include <sstream>
#include <string> // this should be already included in <sstream>
using namespace std;
//short lazieeeeeee
#define FOR(i,n) for(i=0;i<n;i++)
#define FORI(i,a,n) for(i=a;i<n;i++)
#define FORC(it,C) for(it=C.begin();it!=C.end();it++)
#define scanI(x) scanf("%d",&x)
#define scanD(x) scanf("%lf",&x)
#define print(x) printf("%d\n",x)
#define ll long long
#define number32 4294967296ull
#define MAX 1000005
#define len(s) s.length()
#define MOD 1000000007
#define ff first
#define ss second
#define all(C) (C.begin(),C.end())
#define pb(k) push_back(k)
#define mp(i,j) make_pair(i,j)
//shorter Containers
#define Mii map<int,int>
#define Mci map<char,int>
#define Msi map<string,int>
#define Si set<int>
#define Sc set<char>
#define Ss set<string>
#define Pii pair<int,int>
#define PLL pair<ll,ll>
#define Pci pair<char,int>
#define Psi pair<string,int>
#define vi vector<int>
#define vl vector<ll>
#define vc vector<int>
//iterators
#define Miii map<int,int>::iterator
#define Mcii map<char,int>::iterator
#define Msii map<string,int>::iterator
#define Sii set<int>::iterator
#define Sci set<char>::iterator
#define Ssi set<string>::iterator
#define Piii pair<int,int>::iterator
#define Pcii pair<char,int>::iterator
#define Psii pair<string,int>::iterator
#define PLLi pair<ll,ll>::iterator
#define vii vector<int>::iterator
#define vli vector<ll> :: iterator
#define vci vector<int>::iterator
///cout<<(double)(clock() - tStart)/CLOCKS_PER_SEC<<endl;
///clock_t tStart = clock();
int main()
{
return 0;
}
|
[
"princeladdak@gmail.com"
] |
princeladdak@gmail.com
|
d2eb986dd64833b946474fc1d72e0c8b5a759757
|
df3e6c2f276ef80ea6dd260ea8ff1f6ff65246db
|
/MEXUM.cpp
|
4f5bd413473e7417fd98aa21e06e44ea22a5def9
|
[
"MIT"
] |
permissive
|
sachanakshat/Competitive_Practice
|
a3e1a77894d5ca1811debdc4304fcbe5a80f3ff3
|
63170d87398bf5bd163febecdcfef8db21c632c7
|
refs/heads/main
| 2023-03-28T08:20:00.347713
| 2021-03-30T10:10:17
| 2021-03-30T10:10:17
| 352,952,307
| 0
| 0
|
MIT
| 2021-03-30T10:10:18
| 2021-03-30T09:57:34
| null |
UTF-8
|
C++
| false
| false
| 714
|
cpp
|
#include <iostream>
#include <algorithm>
#include <vector>
#include<bits/stdc++.h>
using namespace std;
int* subsum(int a[], int index, int subindex, int sub[], int N)
{
if(index == N)
{
return sub;
}
int sub[subindex] = a[index] + subsum(a, index+1, subindex+1, sub, N);
int sum[subindex] = subsum(a, index+1, subindex, sub, N);
return sum1+sum2;
}
int main()
{
int T,N,i,j,k,l,power;
cin>>T;
for(i=0; i<T; i++)
{
cin>>N;
int a[N],sub[N];
for(j=0; j<N; j++)
{
cin>>a[j];
sub[j] = 0;
}
// power = pow(2,N);
// int ss[power];
sol = subsum(a,0,0,sub,N);
}
return 0;
}
|
[
"sachanakshat@gmail.com"
] |
sachanakshat@gmail.com
|
d5c39ee96f0ca0d6432b774da2764b04566e8e68
|
965bb5b0652e62900c1c4494ca741d3a1f845b88
|
/ObstacleAvoid/LocalizationManager.h
|
565b6e3c99e16507e14edc65a051ef54a72d0ba3
|
[] |
no_license
|
adielbaz25/ObstacleAvoid
|
6c1509d0a37c93b5e117c43def28f9e3bafa6de4
|
789cfd833124d2bf99cae26bf7e045eac69c6ce1
|
refs/heads/master
| 2021-01-01T20:20:42.002061
| 2017-08-03T22:07:45
| 2017-08-03T22:07:45
| 98,818,989
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,900
|
h
|
#ifndef LOCALIZATIONMANAGER_H_
#define LOCALIZATIONMANAGER_H_
#include "LocalizationParticle.h"
#include <vector>
#include <HamsterAPIClientCPP/Hamster.h>
#include "Constants.h"
#include "Structs.h"
#include "MapMatrix.h"
#define NUM_OF_PARTICALES 350
#define TRY_TO_BACK 20
#define TOP_PARTICALES 80
#define BAD_PARTICALES 80
using namespace std;
using namespace HamsterAPI;
//this class manage all the particals in the map
class LocalizationManager
{
public:
void Update(float deltaX, float deltaY, float deltaYaw, LidarScan* lidarHandler, MapMatrix* map);
LocalizationParticle* BestParticle(LidarScan* lidar, float x, float y);
bool CreateParticle(float xDelta, float yDelta, float yawDelta, float belief);
bool CreateParticle(float xDelta, float yDelta, float yawDelta, float belief, float expansionRadius, float yawRange, int childsCount);
void DuplicateParticle(LocalizationParticle* particle, int childCount, vector<LocalizationParticle*>& childs);
void DuplicateParticle(LocalizationParticle* particle, int childCount, float expansionRadius, float yawRange, vector<LocalizationParticle*>& childs);
void ChildsToParticles(vector<LocalizationParticle*> childs);
vector<LocalizationParticle *> particles;
public:
MapMatrix* map;
Robot* robot;
Hamster *hamster;
//return back the particales which out of the free cells range to free cells range
bool tryReturnBackOutOfRangeParticle(LocalizationParticle *particle);
//update the particale's belief
double updateBelief(LocalizationParticle *particle);
//create a random particale
void createRandomParticle(LocalizationParticle *particle);
//close the bad particale near to a particale with a high belief
void createNeighborParticales(LocalizationParticle *prevP, LocalizationParticle *newP);
void initSourceParticle(positionState * ps);
double randNumberFactor(int level);
double randNumberFactorYaw(int level);
void calculateRealPos(LocalizationParticle* p,
double deltaX,
double deltaY,
double deltaYaw);
void calculateYaw(LocalizationParticle* p, double deltaYaw);
void calculatePositionOnMap(LocalizationParticle* p);
void replaceBadOutOfRangeParticle(LocalizationParticle* p, int size);
double computeBelief(LocalizationParticle *particle, LidarScan& scan);
public:
OccupancyGrid *ogrid;
//constructor
LocalizationManager( OccupancyGrid *ogrid, Hamster *hamster, Robot* amnon, MapMatrix* map);
//getter
vector<LocalizationParticle *>* getParticles();
//print the particale's vector
void printParticles() ;
//create new random particals on the map
void InitParticalesOnMap(positionState * ps);
//move the particales according to the robot's movement
void moveParticales(double deltaX, double deltaY, double deltaYaw);
positionState getPosition();
double getBestBelief();
//distructor
virtual ~LocalizationManager();
};
#endif /* LOCALIZATIONMANAGER_H_ */
|
[
"adielbaz25@gmail.com"
] |
adielbaz25@gmail.com
|
e612362e41aecddbce0e4c097cbc1dccef14f3f2
|
e142a836c4c4956004d68eda44168be27ed97e7b
|
/LeetCodeCNExplore/leetcodeCNmedium/Others/621leastInterval.cpp
|
28ae1532b64be815f4b396ba4dfe13f710e1f5fb
|
[] |
no_license
|
usernamegenerator/leetcode
|
966e7e55f098850295886cb89dc9c97a4fa8099a
|
7aa47b1f8aad2ccc2f4d9fe83a8a4e1921c22aea
|
refs/heads/master
| 2021-11-17T17:34:55.754554
| 2021-09-10T04:10:04
| 2021-09-10T04:10:04
| 212,457,582
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,662
|
cpp
|
/*
任务调度器
给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 :
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
提示:
任务的总个数为 [1, 10000]。
n 的取值范围为 [0, 100]。
*/
//https://leetcode-cn.com/problems/task-scheduler/solution/python-xiang-jie-by-jalan/
class Solution
{
public:
int leastInterval(vector<char> &tasks, int n)
{
vector<int> count(26, 0);
for (int i = 0; i < tasks.size(); i++)
{
count[tasks[i] - 'A']++;
}
sort(count.begin(), count.end(), greater);
int total = (count[0] - 1) * (n + 1) + 1;
for (int i = 1; i < count.size(); i++)
{
if (count[i] == count[0])
{
total = total + 1;
}
}
return total > tasks.size() ? total : tasks.size();
}
};
|
[
"bigship1990@gmail.com"
] |
bigship1990@gmail.com
|
e232da49934a42ca9c44c03e990b3b55ebb80a5e
|
20fc58fb946302e700f03ee0b20c8da07eb42563
|
/code/Motor2D/UI_Scrollbar.h
|
d5ae9f27247d5069947351707b0a844afb49a927
|
[
"MIT"
] |
permissive
|
paupedra/Sprite-Ordering-and-Camera-Culling
|
78a54976003884ef2359e4341f4c3d3738391b3c
|
2774bad9d751df665dc78fbf8c34a27393efa35f
|
refs/heads/master
| 2022-08-30T03:46:36.092765
| 2020-05-22T15:59:18
| 2020-05-22T15:59:18
| 254,883,181
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,647
|
h
|
#ifndef __UI_SCROLLBAR_H__
#define __UI_SCROLLBAR_H__
#include "UI.h"
class UI_Image;
class UI_Scrollbar : public UI
{
public:
UI_Scrollbar(UI_ELEMENT element, int x, int y, SDL_Rect hitbox, SDL_Rect thumbSize, iPoint thumbOffset, SDL_Rect dragArea, float dragFactor, bool dragXAxis = false, bool dragYAxis = true,
bool invertedScrolling = false, bool isVisible = true, bool isInteractible = false, bool isDraggable = false, Module* listener = nullptr, UI* parent = nullptr,
SDL_Rect* scrollMask = nullptr, iPoint maskOffset = iPoint(0, 0), bool emptyElements = false);
bool Draw();
void CheckInput();
public:
void DrawScrollbarElements();
void LinkScroll(UI* element);
void UpdateLinkedElements();
bool LinkedElementsBeingHovered();
bool MouseWithinDragArea();
float GetDragFactor(UI* element);
bool GetDragXAxis() const;
bool GetDragYAxis() const;
iPoint GetThumbLocalPos();
SDL_Rect GetThumbHitbox();
void SetThumbHitbox(SDL_Rect hitbox);
void PlaceThumbOnMousePos();
void CheckKeyboardInputs();
void DragThumbWithMousewheel();
bool ThumbIsWithinVerticalScrollbarBounds();
bool ThumbIsAtUpperBound();
bool ThumbIsAtLowerBound();
bool ThumbIsWithinHorizontalScrollbarBounds();
bool ThumbIsAtLeftBound();
bool ThumbIsAtRightBound();
void CheckScrollbarBounds();
private:
UI_Image* bar;
UI_Image* thumb;
UI_Image* scrollMask;
int scrollbarWidth;
int scrollbarHeight;
SDL_Rect dragArea;
float dragFactor;
iPoint dragDisplacement;
iPoint mouseWheelScroll;
bool invertedScrolling;
float arrowPosFactor;
iPoint newThumbPos;
std::vector<UI*> linkedElements;
};
#endif // !__UI_SCROLLBAR_H__
|
[
"paupe200@gmail.com"
] |
paupe200@gmail.com
|
09730ad175241ca2c15ca80fc62753167e9b0e4e
|
e1826894c8e2aca01f04829e0b797654ca72c38f
|
/cpp/Lynx3-patterns.cpp
|
6b1c6b46b2dc9d9ed8f397b1395a38df41a601df
|
[] |
no_license
|
maksverver/lynx
|
01df0cdc3282972e020c330e164ba498b20469d4
|
4db3d375d8b1cbca6752ccc1461034b3d95fd938
|
refs/heads/master
| 2023-05-11T12:00:23.239704
| 2014-05-26T13:10:36
| 2014-05-26T13:10:36
| 20,185,503
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 37,566
|
cpp
|
#include <vector>
// Patterns for the monte carlo simulation
// patterns[i] encodes the patterns that must be checked when the opponent has played position i in the previous simulation step
// The patterns for a position are encoded in an array, where one pattern consists of four long longs:
// 1 & 2: A bit mask encoding a set of positions that all must belong long to us
// 3 & 4: A bit mask encoding a set of positions of which none may belong long to the opponent
// The high 16 bits of the last long long encode the position that we must play if the pattern matches
// Currently there are two patterns encoded:
// Bridges: If the opponent plays in a bridge belong longing to us, we will defend that bridge by connecting it
// A primitive edge connection pattern: If a position of us is less than three steps away from the edge and the opponent plays below us (a neighbour of our position that is one step away from the edge),
// then we play next to the position of the opponent below our move, but only if the two positions below the move that we play do not belong long to the opponent
// Note that we have experimented with more 'correct' edge connection patterns, but we found that this only resulted in weaker play
extern const std::vector<unsigned long long> patterns[107] = {{},
{8ULL,0ULL,16ULL,1125899906842624ULL,8ULL,0ULL,4ULL,562949953421312ULL},
{64ULL,0ULL,32ULL,1407374883553280ULL,8ULL,0ULL,2ULL,281474976710656ULL},
{128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,66ULL,0ULL,4ULL,562949953421312ULL,132ULL,0ULL,64ULL,1688849860263936ULL,320ULL,0ULL,128ULL,1970324836974592ULL,144ULL,0ULL,256ULL,2251799813685248ULL,258ULL,0ULL,16ULL,1125899906842624ULL,20ULL,0ULL,2ULL,281474976710656ULL},
{256ULL,0ULL,512ULL,2533274790395904ULL,8ULL,0ULL,2ULL,281474976710656ULL},
{2048ULL,0ULL,1024ULL,2814749767106560ULL,64ULL,0ULL,4ULL,562949953421312ULL},
{128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,4096ULL,0ULL,100ULL,1688849860263936ULL,4096ULL,0ULL,3104ULL,3096224743817216ULL,132ULL,0ULL,8ULL,844424930131968ULL,4104ULL,0ULL,128ULL,1970324836974592ULL,2176ULL,0ULL,4096ULL,3377699720527872ULL,4128ULL,0ULL,2048ULL,3096224743817216ULL,2052ULL,0ULL,32ULL,1407374883553280ULL,40ULL,0ULL,4ULL,562949953421312ULL},
{8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,4104ULL,0ULL,64ULL,1688849860263936ULL,8256ULL,0ULL,4096ULL,3377699720527872ULL,20480ULL,0ULL,8192ULL,3659174697238528ULL,8448ULL,0ULL,16384ULL,3940649673949184ULL,16392ULL,0ULL,256ULL,2251799813685248ULL,320ULL,0ULL,8ULL,844424930131968ULL},
{16384ULL,0ULL,784ULL,2251799813685248ULL,16384ULL,0ULL,98816ULL,4222124650659840ULL,128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,520ULL,0ULL,16ULL,1125899906842624ULL,32784ULL,0ULL,512ULL,2533274790395904ULL,16896ULL,0ULL,32768ULL,4222124650659840ULL,32896ULL,0ULL,16384ULL,3940649673949184ULL,16392ULL,0ULL,128ULL,1970324836974592ULL,144ULL,0ULL,8ULL,844424930131968ULL},
{256ULL,0ULL,16ULL,1125899906842624ULL,32768ULL,0ULL,65536ULL,4503599627370496ULL},
{2048ULL,0ULL,32ULL,1407374883553280ULL,262144ULL,0ULL,131072ULL,4785074604081152ULL},
{524288ULL,0ULL,394240ULL,5066549580791808ULL,524288ULL,0ULL,3104ULL,3096224743817216ULL,4096ULL,0ULL,100ULL,1688849860263936ULL,4096ULL,0ULL,3104ULL,3096224743817216ULL,525312ULL,0ULL,262144ULL,5066549580791808ULL,262176ULL,0ULL,1024ULL,2814749767106560ULL,1088ULL,0ULL,32ULL,1407374883553280ULL,4128ULL,0ULL,64ULL,1688849860263936ULL,524352ULL,0ULL,4096ULL,3377699720527872ULL,266240ULL,0ULL,524288ULL,5348024557502464ULL},
{1048576ULL,0ULL,788480ULL,5348024557502464ULL,1048576ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,532480ULL,0ULL,1048576ULL,5629499534213120ULL,1048704ULL,0ULL,8192ULL,3659174697238528ULL,8256ULL,0ULL,128ULL,1970324836974592ULL,2176ULL,0ULL,64ULL,1688849860263936ULL,524352ULL,0ULL,2048ULL,3096224743817216ULL,1050624ULL,0ULL,524288ULL,5348024557502464ULL},
{2101248ULL,0ULL,1048576ULL,5629499534213120ULL,1048704ULL,0ULL,4096ULL,3377699720527872ULL,20480ULL,0ULL,128ULL,1970324836974592ULL,4194432ULL,0ULL,16384ULL,3940649673949184ULL,2113536ULL,0ULL,4194304ULL,6192449487634432ULL,5242880ULL,0ULL,2097152ULL,5910974510923776ULL},
{4194304ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,49408ULL,3940649673949184ULL,8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,8396800ULL,0ULL,4194304ULL,6192449487634432ULL,4194432ULL,0ULL,8192ULL,3659174697238528ULL,8448ULL,0ULL,128ULL,1970324836974592ULL,32896ULL,0ULL,256ULL,2251799813685248ULL,8388864ULL,0ULL,32768ULL,4222124650659840ULL,4227072ULL,0ULL,8388608ULL,6473924464345088ULL},
{8388608ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,98816ULL,4222124650659840ULL,16384ULL,0ULL,784ULL,2251799813685248ULL,16384ULL,0ULL,98816ULL,4222124650659840ULL,8454144ULL,0ULL,16777216ULL,6755399441055744ULL,16793600ULL,0ULL,8388608ULL,6473924464345088ULL,8388864ULL,0ULL,16384ULL,3940649673949184ULL,16896ULL,0ULL,256ULL,2251799813685248ULL,65792ULL,0ULL,512ULL,2533274790395904ULL,16777728ULL,0ULL,65536ULL,4503599627370496ULL},
{32768ULL,0ULL,512ULL,2533274790395904ULL,16777216ULL,0ULL,33554432ULL,7036874417766400ULL},
{134217728ULL,0ULL,67108864ULL,7318349394477056ULL,262144ULL,0ULL,1024ULL,2814749767106560ULL},
{268435456ULL,0ULL,394240ULL,5066549580791808ULL,268435456ULL,0ULL,201457664ULL,7599824371187712ULL,524288ULL,0ULL,394240ULL,5066549580791808ULL,524288ULL,0ULL,3104ULL,3096224743817216ULL,268566528ULL,0ULL,134217728ULL,7599824371187712ULL,134742016ULL,0ULL,268435456ULL,7881299347898368ULL,268437504ULL,0ULL,524288ULL,5348024557502464ULL,525312ULL,0ULL,2048ULL,3096224743817216ULL,133120ULL,0ULL,1024ULL,2814749767106560ULL,134218752ULL,0ULL,131072ULL,4785074604081152ULL},
{1048576ULL,0ULL,788480ULL,5348024557502464ULL,1048576ULL,0ULL,6208ULL,3377699720527872ULL,536870912ULL,0ULL,788480ULL,5348024557502464ULL,536870912ULL,0ULL,402915328ULL,7881299347898368ULL,266240ULL,0ULL,2048ULL,3096224743817216ULL,1050624ULL,0ULL,4096ULL,3377699720527872ULL,536875008ULL,0ULL,1048576ULL,5629499534213120ULL,269484032ULL,0ULL,536870912ULL,8162774324609024ULL,537133056ULL,0ULL,268435456ULL,7881299347898368ULL,268437504ULL,0ULL,262144ULL,5066549580791808ULL},
{1074266112ULL,0ULL,536870912ULL,8162774324609024ULL,538968064ULL,0ULL,1073741824ULL,8444249301319680ULL,1073750016ULL,0ULL,2097152ULL,5910974510923776ULL,2101248ULL,0ULL,8192ULL,3659174697238528ULL,532480ULL,0ULL,4096ULL,3377699720527872ULL,536875008ULL,0ULL,524288ULL,5348024557502464ULL},
{4294975488ULL,0ULL,4194304ULL,6192449487634432ULL,5242880ULL,0ULL,8192ULL,3659174697238528ULL,1073750016ULL,0ULL,1048576ULL,5629499534213120ULL,2148532224ULL,0ULL,1073741824ULL,8444249301319680ULL,5368709120ULL,0ULL,2147483648ULL,8725724278030336ULL,2151677952ULL,0ULL,4294967296ULL,9007199254740992ULL},
{4303355904ULL,0ULL,8589934592ULL,9288674231451648ULL,8589950976ULL,0ULL,8388608ULL,6473924464345088ULL,8396800ULL,0ULL,16384ULL,3940649673949184ULL,2113536ULL,0ULL,8192ULL,3659174697238528ULL,4294975488ULL,0ULL,2097152ULL,5910974510923776ULL,8592031744ULL,0ULL,4294967296ULL,9007199254740992ULL},
{8589934592ULL,0ULL,51556384768ULL,9570149208162304ULL,8589934592ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,49408ULL,3940649673949184ULL,17184063488ULL,0ULL,8589934592ULL,9288674231451648ULL,8589950976ULL,0ULL,4194304ULL,6192449487634432ULL,4227072ULL,0ULL,16384ULL,3940649673949184ULL,16793600ULL,0ULL,32768ULL,4222124650659840ULL,17179901952ULL,0ULL,16777216ULL,6755399441055744ULL,8606711808ULL,0ULL,17179869184ULL,9570149208162304ULL},
{17179869184ULL,0ULL,103112769536ULL,9851624184872960ULL,17179869184ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,98816ULL,4222124650659840ULL,17213423616ULL,0ULL,34359738368ULL,9851624184872960ULL,34359803904ULL,0ULL,33554432ULL,7036874417766400ULL,33587200ULL,0ULL,65536ULL,4503599627370496ULL,8454144ULL,0ULL,32768ULL,4222124650659840ULL,17179901952ULL,0ULL,8388608ULL,6473924464345088ULL,34368126976ULL,0ULL,17179869184ULL,9570149208162304ULL},
{34359738368ULL,0ULL,68719476736ULL,10133099161583616ULL,16777216ULL,0ULL,65536ULL,4503599627370496ULL},
{274877906944ULL,0ULL,137438953472ULL,10414574138294272ULL,134217728ULL,0ULL,131072ULL,4785074604081152ULL},
{268435456ULL,0ULL,394240ULL,5066549580791808ULL,268435456ULL,0ULL,201457664ULL,7599824371187712ULL,549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,268566528ULL,0ULL,262144ULL,5066549580791808ULL,549756076032ULL,0ULL,268435456ULL,7881299347898368ULL,275146342400ULL,0ULL,549755813888ULL,10977524091715584ULL,549822922752ULL,0ULL,274877906944ULL,10696049115004928ULL,274878038016ULL,0ULL,67108864ULL,7318349394477056ULL,67371008ULL,0ULL,131072ULL,4785074604081152ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,536870912ULL,0ULL,788480ULL,5348024557502464ULL,536870912ULL,0ULL,402915328ULL,7881299347898368ULL,134742016ULL,0ULL,262144ULL,5066549580791808ULL,549756076032ULL,0ULL,134217728ULL,7599824371187712ULL,1099645845504ULL,0ULL,549755813888ULL,10977524091715584ULL,550292684800ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099512152064ULL,0ULL,536870912ULL,8162774324609024ULL,537133056ULL,0ULL,524288ULL,5348024557502464ULL},
{1074266112ULL,0ULL,1048576ULL,5629499534213120ULL,2199024304128ULL,0ULL,1073741824ULL,8444249301319680ULL,1100585369600ULL,0ULL,2199023255552ULL,11540474045136896ULL,2199291691008ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099512152064ULL,0ULL,268435456ULL,7881299347898368ULL,269484032ULL,0ULL,524288ULL,5348024557502464ULL},
{538968064ULL,0ULL,1048576ULL,5629499534213120ULL,2199024304128ULL,0ULL,536870912ULL,8162774324609024ULL,4398583382016ULL,0ULL,2199023255552ULL,11540474045136896ULL,2201170739200ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398048608256ULL,0ULL,2147483648ULL,8725724278030336ULL,2148532224ULL,0ULL,2097152ULL,5910974510923776ULL},
{5368709120ULL,0ULL,2097152ULL,5910974510923776ULL,4398048608256ULL,0ULL,1073741824ULL,8444249301319680ULL,8797166764032ULL,0ULL,4398046511104ULL,11821949021847552ULL,21990232555520ULL,0ULL,8796093022208ULL,12103423998558208ULL,8800387989504ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592188141568ULL,0ULL,4294967296ULL,9007199254740992ULL},
{8592031744ULL,0ULL,4194304ULL,6192449487634432ULL,2151677952ULL,0ULL,2097152ULL,5910974510923776ULL,17592188141568ULL,0ULL,2147483648ULL,8725724278030336ULL,35186519572480ULL,0ULL,17592186044416ULL,12384898975268864ULL,17600775979008ULL,0ULL,35184372088832ULL,12666373951979520ULL,35184376283136ULL,0ULL,8589934592ULL,9288674231451648ULL},
{17184063488ULL,0ULL,8388608ULL,6473924464345088ULL,4303355904ULL,0ULL,4194304ULL,6192449487634432ULL,35184376283136ULL,0ULL,4294967296ULL,9007199254740992ULL,70373039144960ULL,0ULL,35184372088832ULL,12666373951979520ULL,35201551958016ULL,0ULL,70368744177664ULL,12947848928690176ULL,70368752566272ULL,0ULL,17179869184ULL,9570149208162304ULL},
{8589934592ULL,0ULL,51556384768ULL,9570149208162304ULL,8589934592ULL,0ULL,25198592ULL,6473924464345088ULL,70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,34368126976ULL,0ULL,16777216ULL,6755399441055744ULL,8606711808ULL,0ULL,8388608ULL,6473924464345088ULL,70368752566272ULL,0ULL,8589934592ULL,9288674231451648ULL,140746078289920ULL,0ULL,70368744177664ULL,12947848928690176ULL,70403103916032ULL,0ULL,140737488355328ULL,13229323905400832ULL,140737505132544ULL,0ULL,34359738368ULL,9851624184872960ULL},
{17179869184ULL,0ULL,103112769536ULL,9851624184872960ULL,17179869184ULL,0ULL,50397184ULL,6755399441055744ULL,140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,17213423616ULL,0ULL,16777216ULL,6755399441055744ULL,68736253952ULL,0ULL,33554432ULL,7036874417766400ULL,281475010265088ULL,0ULL,68719476736ULL,10133099161583616ULL,140806207832064ULL,0ULL,281474976710656ULL,13510798882111488ULL,281492156579840ULL,0ULL,140737488355328ULL,13229323905400832ULL,140737505132544ULL,0ULL,17179869184ULL,9570149208162304ULL},
{34359738368ULL,0ULL,33554432ULL,7036874417766400ULL,281474976710656ULL,0ULL,562949953421312ULL,13792273858822144ULL},
{274877906944ULL,0ULL,67108864ULL,7318349394477056ULL,274877906944ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,2251937252638720ULL,0ULL,1125899906842624ULL,14073748835532800ULL,1125899973951488ULL,0ULL,137438953472ULL,10414574138294272ULL,137573171200ULL,0ULL,67108864ULL,7318349394477056ULL,549822922752ULL,0ULL,134217728ULL,7599824371187712ULL,2251799947902976ULL,0ULL,549755813888ULL,10977524091715584ULL,1126449662656512ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,2251799947902976ULL,0ULL,274877906944ULL,10696049115004928ULL,275146342400ULL,0ULL,134217728ULL,7599824371187712ULL,1099645845504ULL,0ULL,268435456ULL,7881299347898368ULL,4503599895805952ULL,0ULL,1099511627776ULL,11258999068426240ULL,2252899325313024ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4503874505277440ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{9007749010554880ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4505798650626048ULL,0ULL,9007199254740992ULL,14918173765664768ULL,9007199791611904ULL,0ULL,2199023255552ULL,11540474045136896ULL,2199291691008ULL,0ULL,536870912ULL,8162774324609024ULL,550292684800ULL,0ULL,268435456ULL,7881299347898368ULL,4503599895805952ULL,0ULL,549755813888ULL,10977524091715584ULL},
{18015498021109760ULL,0ULL,9007199254740992ULL,14918173765664768ULL,9007199791611904ULL,0ULL,1099511627776ULL,11258999068426240ULL,1100585369600ULL,0ULL,536870912ULL,8162774324609024ULL,4398583382016ULL,0ULL,1073741824ULL,8444249301319680ULL,18014399583223808ULL,0ULL,4398046511104ULL,11821949021847552ULL,9011597301252096ULL,0ULL,18014398509481984ULL,15199648742375424ULL},
{36030996042219520ULL,0ULL,18014398509481984ULL,15199648742375424ULL,18014399583223808ULL,0ULL,2199023255552ULL,11540474045136896ULL,2201170739200ULL,0ULL,1073741824ULL,8444249301319680ULL,8797166764032ULL,0ULL,2147483648ULL,8725724278030336ULL,36028799166447616ULL,0ULL,8796093022208ULL,12103423998558208ULL,18023194602504192ULL,0ULL,36028797018963968ULL,15481123719086080ULL},
{36028799166447616ULL,0ULL,4398046511104ULL,11821949021847552ULL,21990232555520ULL,0ULL,2147483648ULL,8725724278030336ULL,72057596185411584ULL,0ULL,17592186044416ULL,12384898975268864ULL,36046389205008384ULL,0ULL,72057594037927936ULL,15762598695796736ULL,72061992084439040ULL,0ULL,36028797018963968ULL,15481123719086080ULL},
{8800387989504ULL,0ULL,2147483648ULL,8725724278030336ULL,72057596185411584ULL,0ULL,8796093022208ULL,12103423998558208ULL,144123984168878080ULL,0ULL,72057594037927936ULL,15762598695796736ULL,72092778410016768ULL,0ULL,144115188075855872ULL,16044073672507392ULL,144115192370823168ULL,0ULL,35184372088832ULL,12666373951979520ULL,35186519572480ULL,0ULL,4294967296ULL,9007199254740992ULL},
{70373039144960ULL,0ULL,8589934592ULL,9288674231451648ULL,288230384741646336ULL,0ULL,70368744177664ULL,12947848928690176ULL,144185556820033536ULL,0ULL,288230376151711744ULL,16325548649218048ULL,288247968337756160ULL,0ULL,144115188075855872ULL,16044073672507392ULL,144115192370823168ULL,0ULL,17592186044416ULL,12384898975268864ULL,17600775979008ULL,0ULL,4294967296ULL,9007199254740992ULL},
{35201551958016ULL,0ULL,8589934592ULL,9288674231451648ULL,288230384741646336ULL,0ULL,35184372088832ULL,12666373951979520ULL,576495936675512320ULL,0ULL,288230376151711744ULL,16325548649218048ULL,288371113640067072ULL,0ULL,576460752303423488ULL,16607023625928704ULL,576460769483292672ULL,0ULL,140737488355328ULL,13229323905400832ULL,140746078289920ULL,0ULL,17179869184ULL,9570149208162304ULL},
{70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,281492156579840ULL,0ULL,34359738368ULL,9851624184872960ULL,1152921538966585344ULL,0ULL,281474976710656ULL,13510798882111488ULL,576742227280134144ULL,0ULL,1152921504606846976ULL,16888498602639360ULL,1152991873351024640ULL,0ULL,576460752303423488ULL,16607023625928704ULL,576460769483292672ULL,0ULL,70368744177664ULL,12947848928690176ULL,70403103916032ULL,0ULL,17179869184ULL,9570149208162304ULL},
{140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,562984313159680ULL,0ULL,68719476736ULL,10133099161583616ULL,2305843077933170688ULL,0ULL,562949953421312ULL,13792273858822144ULL,1153484454560268288ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,2305983746702049280ULL,0ULL,1152921504606846976ULL,16888498602639360ULL,1152921538966585344ULL,0ULL,140737488355328ULL,13229323905400832ULL,140806207832064ULL,0ULL,34359738368ULL,9851624184872960ULL},
{281474976710656ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,281474976710656ULL,0ULL,68719476736ULL,10133099161583616ULL},
{2251799813685248ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,274877906944ULL,0ULL,137438953472ULL,10414574138294272ULL},
{549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,4503599627370496ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,4503599627370496ULL,0ULL,-4611686018427387904ULL,17732923532771840ULL,1126449662656512ULL,0ULL,274877906944ULL,10696049115004928ULL,4503874505277440ULL,0ULL,549755813888ULL,10977524091715584ULL,-9223371487098961920ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4616189618054758400ULL,0ULL,-9223372036854775808ULL,17732923532771328ULL,-9222246136947933184ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,4611686293305294848ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,9007199254740992ULL,0ULL,-9223372036854775808ULL,18014398509483009ULL,9007199254740992ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,2252899325313024ULL,0ULL,549755813888ULL,10977524091715584ULL,9007749010554880ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099511627776ULL,1ULL,9007199254740992ULL,14918173765664768ULL,-9214364837600034816ULL,0ULL,0ULL,18014398509481985ULL,2251799813685248ULL,1ULL,-9223372036854775808ULL,17732923532771328ULL,-9223371487098961920ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{18014398509481984ULL,1ULL,0ULL,18295873486192642ULL,2199023255552ULL,2ULL,18014398509481984ULL,15199648742375424ULL,18015498021109760ULL,0ULL,2199023255552ULL,11540474045136896ULL,4505798650626048ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099511627776ULL,1ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,2ULL,0ULL,18014398509481985ULL},
{36028797018963968ULL,2ULL,0ULL,18577348462903300ULL,9007199254740992ULL,4ULL,0ULL,18295873486192642ULL,2199023255552ULL,2ULL,9007199254740992ULL,14918173765664768ULL,9011597301252096ULL,0ULL,2199023255552ULL,11540474045136896ULL,36030996042219520ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398046511104ULL,4ULL,36028797018963968ULL,15481123719086080ULL},
{18014398509481984ULL,8ULL,0ULL,18577348462903300ULL,72057594037927936ULL,4ULL,0ULL,18858823439613960ULL,8796093022208ULL,8ULL,72057594037927936ULL,15762598695796736ULL,72061992084439040ULL,0ULL,8796093022208ULL,12103423998558208ULL,18023194602504192ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398046511104ULL,4ULL,18014398509481984ULL,15199648742375424ULL},
{36028797018963968ULL,16ULL,0ULL,18858823439613960ULL,8796093022208ULL,8ULL,36028797018963968ULL,15481123719086080ULL,36046389205008384ULL,0ULL,8796093022208ULL,12103423998558208ULL,144123984168878080ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592186044416ULL,16ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,8ULL,0ULL,19140298416324624ULL},
{288230376151711744ULL,16ULL,0ULL,19421773393035296ULL,35184372088832ULL,32ULL,288230376151711744ULL,16325548649218048ULL,288247968337756160ULL,0ULL,35184372088832ULL,12666373951979520ULL,72092778410016768ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592186044416ULL,16ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,32ULL,0ULL,19140298416324624ULL},
{576460752303423488ULL,32ULL,0ULL,19703248369745984ULL,70368744177664ULL,64ULL,576460752303423488ULL,16607023625928704ULL,576495936675512320ULL,0ULL,70368744177664ULL,12947848928690176ULL,144185556820033536ULL,0ULL,35184372088832ULL,12666373951979520ULL,35184372088832ULL,32ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,64ULL,0ULL,19421773393035296ULL},
{70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,288230376151711744ULL,0ULL,0ULL,19703248369877184ULL,288230376151711744ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,1152921504606846976ULL,64ULL,0ULL,19984723346456704ULL,140737488355328ULL,128ULL,1152921504606846976ULL,16888498602639360ULL,1152991873351024640ULL,0ULL,140737488355328ULL,13229323905400832ULL,288371113640067072ULL,0ULL,70368744177664ULL,12947848928690176ULL,70368744177664ULL,64ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,128ULL,0ULL,19703248369745984ULL},
{576460752303423488ULL,0ULL,0ULL,19984723346719104ULL,576460752303423488ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,140737488355328ULL,128ULL,576460752303423488ULL,16607023625928704ULL,576742227280134144ULL,0ULL,140737488355328ULL,13229323905400832ULL,2305983746702049280ULL,0ULL,281474976710656ULL,13510798882111488ULL,281474976710656ULL,256ULL,2305843009213693952ULL,17169973579350016ULL,2305843009213693952ULL,128ULL,0ULL,20266198323167488ULL,576460752303423488ULL,256ULL,0ULL,19984723346456704ULL},
{1152921504606846976ULL,0ULL,0ULL,20266198323167488ULL,281474976710656ULL,0ULL,562949953421312ULL,13792273858822144ULL},
{-9223372036854775808ULL,0ULL,0ULL,20547673299878400ULL,2251799813685248ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{4503599627370496ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,4503599627370496ULL,0ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,0ULL,20829148277114368ULL,2251799813685248ULL,1ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,1024ULL,0ULL,18014398509481985ULL,0ULL,513ULL,0ULL,20829148276589568ULL,4611686018427387904ULL,1024ULL,0ULL,20547673299878400ULL,2251799813685248ULL,512ULL,4611686018427387904ULL,17451448556060672ULL,4616189618054758400ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{0ULL,2ULL,-9223372036854775808ULL,18014398509483009ULL,0ULL,2ULL,0ULL,21110623254350848ULL,9007199254740992ULL,0ULL,-9223372036854775808ULL,18014398509483009ULL,9007199254740992ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,4503599627370496ULL,2ULL,9007199254740992ULL,14918173765664768ULL,-9214364837600034816ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,1024ULL,-9223372036854775808ULL,17732923532771328ULL,-9223372036854775808ULL,2048ULL,0ULL,20829148276589568ULL,0ULL,1026ULL,0ULL,21110623253301248ULL,9007199254740992ULL,2048ULL,0ULL,18295873486192642ULL},
{18014398509481984ULL,1ULL,9007199254740992ULL,14918173765664768ULL,9007199254740992ULL,4ULL,18014398509481984ULL,15199648742375424ULL,18014398509481984ULL,4096ULL,0ULL,18577348462903300ULL,0ULL,2052ULL,0ULL,21392098230013952ULL,0ULL,4097ULL,0ULL,21110623253301248ULL,9007199254740992ULL,2048ULL,0ULL,18014398509481985ULL},
{36028797018963968ULL,2ULL,18014398509481984ULL,15199648742375424ULL,18014398509481984ULL,4096ULL,0ULL,18295873486192642ULL,0ULL,8194ULL,0ULL,21392098230013952ULL,0ULL,4104ULL,0ULL,21673573206728704ULL,36028797018963968ULL,8192ULL,0ULL,18858823439613960ULL,18014398509481984ULL,8ULL,36028797018963968ULL,15481123719086080ULL},
{0ULL,8208ULL,0ULL,21955048183447552ULL,0ULL,16388ULL,0ULL,21673573206728704ULL,36028797018963968ULL,8192ULL,0ULL,18577348462903300ULL,72057594037927936ULL,4ULL,36028797018963968ULL,15481123719086080ULL,36028797018963968ULL,16ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,16384ULL,0ULL,19140298416324624ULL},
{72057594037927936ULL,32ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,8ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,16384ULL,0ULL,18858823439613960ULL,0ULL,32776ULL,0ULL,21955048183447552ULL,0ULL,16416ULL,0ULL,22236523160174592ULL,144115188075855872ULL,32768ULL,0ULL,19421773393035296ULL},
{288230376151711744ULL,16ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,64ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,65536ULL,0ULL,19703248369745984ULL,0ULL,32832ULL,0ULL,22517998136918016ULL,0ULL,65552ULL,0ULL,22236523160174592ULL,144115188075855872ULL,32768ULL,0ULL,19140298416324624ULL},
{0ULL,32ULL,0ULL,19703248369877184ULL,0ULL,32ULL,0ULL,22517998204157952ULL,288230376151711744ULL,0ULL,0ULL,19703248369877184ULL,288230376151711744ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,0ULL,131104ULL,0ULL,22517998136918016ULL,0ULL,65664ULL,0ULL,22799473113694208ULL,576460752303423488ULL,131072ULL,0ULL,19984723346456704ULL,288230376151711744ULL,128ULL,576460752303423488ULL,16607023625928704ULL,576460752303423488ULL,32ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,65536ULL,0ULL,19421773393035296ULL},
{0ULL,64ULL,0ULL,19984723346719104ULL,0ULL,64ULL,0ULL,22799473248174080ULL,576460752303423488ULL,0ULL,0ULL,19984723346719104ULL,576460752303423488ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,0ULL,262208ULL,0ULL,22799473113694208ULL,0ULL,131328ULL,0ULL,23080948090535936ULL,1152921504606846976ULL,262144ULL,0ULL,20266198323167488ULL,576460752303423488ULL,256ULL,1152921504606846976ULL,16888498602639360ULL,1152921504606846976ULL,64ULL,576460752303423488ULL,16607023625928704ULL,576460752303423488ULL,131072ULL,0ULL,19703248369745984ULL},
{1152921504606846976ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,0ULL,128ULL,0ULL,23080948090535936ULL},
{-9223372036854775808ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,0ULL,1024ULL,0ULL,23362423067508736ULL},
{0ULL,1ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,0ULL,20829148277114368ULL,0ULL,2048ULL,0ULL,23643898313703424ULL,0ULL,2048ULL,0ULL,20829148277114368ULL,0ULL,1049088ULL,0ULL,23362423067508736ULL,-9223372036854775808ULL,524288ULL,0ULL,20547673299878400ULL,0ULL,513ULL,-9223372036854775808ULL,17732923532771328ULL,-9223372036854775808ULL,2048ULL,0ULL,18014398509481985ULL,0ULL,1048577ULL,0ULL,21110623253301248ULL,0ULL,526336ULL,0ULL,23643898044743680ULL},
{0ULL,2ULL,-9223372036854775808ULL,18014398509483009ULL,0ULL,2ULL,0ULL,21110623254350848ULL,0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,2098176ULL,0ULL,23643898044743680ULL,0ULL,1048577ULL,0ULL,20829148276589568ULL,0ULL,1026ULL,0ULL,18014398509481985ULL,0ULL,4097ULL,0ULL,18295873486192642ULL,0ULL,2097154ULL,0ULL,21392098230013952ULL,0ULL,1052672ULL,0ULL,23925373022502912ULL},
{0ULL,2105344ULL,0ULL,24206848001310720ULL,0ULL,4194308ULL,0ULL,21673573206728704ULL,0ULL,8194ULL,0ULL,18577348462903300ULL,0ULL,2052ULL,0ULL,18295873486192642ULL,0ULL,2097154ULL,0ULL,21110623253301248ULL,0ULL,4196352ULL,0ULL,23925373022502912ULL},
{0ULL,8392704ULL,0ULL,24206848001310720ULL,0ULL,4194308ULL,0ULL,21392098230013952ULL,0ULL,4104ULL,0ULL,18577348462903300ULL,0ULL,16388ULL,0ULL,18858823439613960ULL,0ULL,8388616ULL,0ULL,21955048183447552ULL,0ULL,4210688ULL,0ULL,24488322982215680ULL},
{0ULL,8208ULL,0ULL,18858823439613960ULL,0ULL,8388616ULL,0ULL,21673573206728704ULL,0ULL,16785408ULL,0ULL,24488322982215680ULL,0ULL,8421376ULL,0ULL,24769797967314944ULL,0ULL,16777232ULL,0ULL,22236523160174592ULL,0ULL,32776ULL,0ULL,19140298416324624ULL},
{0ULL,65552ULL,0ULL,19421773393035296ULL,0ULL,33554464ULL,0ULL,22517998136918016ULL,0ULL,16842752ULL,0ULL,25051272960802816ULL,0ULL,33570816ULL,0ULL,24769797967314944ULL,0ULL,16777232ULL,0ULL,21955048183447552ULL,0ULL,16416ULL,0ULL,19140298416324624ULL},
{0ULL,32ULL,0ULL,19703248369877184ULL,0ULL,32ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,131104ULL,0ULL,19703248369745984ULL,0ULL,67108928ULL,0ULL,22799473113694208ULL,0ULL,33685504ULL,0ULL,25332747971067904ULL,0ULL,67141632ULL,0ULL,25051272960802816ULL,0ULL,33554464ULL,0ULL,22236523160174592ULL,0ULL,32832ULL,0ULL,19421773393035296ULL},
{0ULL,64ULL,0ULL,19984723346719104ULL,0ULL,64ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,25332782465024000ULL,0ULL,262208ULL,0ULL,19984723346456704ULL,0ULL,134217856ULL,0ULL,23080948090535936ULL,0ULL,67371008ULL,0ULL,25614223014887424ULL,0ULL,134283264ULL,0ULL,25332747971067904ULL,0ULL,67108928ULL,0ULL,22517998136918016ULL,0ULL,65664ULL,0ULL,19703248369745984ULL},
{0ULL,131072ULL,0ULL,25614223014887424ULL,0ULL,128ULL,0ULL,20266198323167488ULL},
{0ULL,1024ULL,0ULL,20547673299878400ULL,0ULL,1048576ULL,0ULL,25895698125815808ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,2048ULL,0ULL,23643898313703424ULL,0ULL,2048ULL,0ULL,20829148277114368ULL,0ULL,270532608ULL,0ULL,26177173370961920ULL,0ULL,537395200ULL,0ULL,25895698125815808ULL,0ULL,268436480ULL,0ULL,23362423067508736ULL,0ULL,526336ULL,0ULL,20829148276589568ULL,0ULL,2098176ULL,0ULL,21110623253301248ULL,0ULL,536872960ULL,0ULL,23925373022502912ULL},
{0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,1074790400ULL,0ULL,26177173370961920ULL,0ULL,541065216ULL,0ULL,26458648884543488ULL,0ULL,1073745920ULL,0ULL,24206848001310720ULL,0ULL,4196352ULL,0ULL,21392098230013952ULL,0ULL,1052672ULL,0ULL,21110623253301248ULL,0ULL,536872960ULL,0ULL,23643898044743680ULL},
{0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,8192ULL,0ULL,24488329424666624ULL,0ULL,8192ULL,0ULL,24206851222536192ULL,0ULL,2105344ULL,0ULL,21392098230013952ULL,0ULL,8392704ULL,0ULL,21673573206728704ULL,0ULL,2147491840ULL,0ULL,24488322982215680ULL,0ULL,1082130432ULL,0ULL,26740124934995968ULL,0ULL,2149580800ULL,0ULL,26458648884543488ULL,0ULL,1073745920ULL,0ULL,23925373022502912ULL},
{0ULL,8192ULL,0ULL,24488329424666624ULL,0ULL,8192ULL,0ULL,24206851222536192ULL,0ULL,16384ULL,0ULL,24488329424666624ULL,0ULL,16384ULL,0ULL,24769810852216832ULL,0ULL,4210688ULL,0ULL,21673573206728704ULL,0ULL,16785408ULL,0ULL,21955048183447552ULL,0ULL,4294983680ULL,0ULL,24769797967314944ULL,0ULL,2164260864ULL,0ULL,27021602059190272ULL,0ULL,4299161600ULL,0ULL,26740124934995968ULL,0ULL,2147491840ULL,0ULL,24206848001310720ULL},
{0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,16384ULL,0ULL,24488329424666624ULL,0ULL,16384ULL,0ULL,24769810852216832ULL,0ULL,8598323200ULL,0ULL,27021602059190272ULL,0ULL,4328521728ULL,0ULL,27303081330868224ULL,0ULL,8589967360ULL,0ULL,25051272960802816ULL,0ULL,33570816ULL,0ULL,22236523160174592ULL,0ULL,8421376ULL,0ULL,21955048183447552ULL,0ULL,4294983680ULL,0ULL,24488322982215680ULL},
{0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,17196646400ULL,0ULL,27303081330868224ULL,0ULL,8589967360ULL,0ULL,24769797967314944ULL,0ULL,16842752ULL,0ULL,22236523160174592ULL,0ULL,67141632ULL,0ULL,22517998136918016ULL,0ULL,17179934720ULL,0ULL,25332747971067904ULL,0ULL,8657043456ULL,0ULL,27584564897513472ULL},
{0ULL,65536ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,25332782465024000ULL,0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,17314086912ULL,0ULL,27866057054093312ULL,0ULL,34359869440ULL,0ULL,25614223014887424ULL,0ULL,134283264ULL,0ULL,22799473113694208ULL,0ULL,33685504ULL,0ULL,22517998136918016ULL,0ULL,17179934720ULL,0ULL,25051272960802816ULL,0ULL,34393292800ULL,0ULL,27584564897513472ULL},
{0ULL,131072ULL,0ULL,23080948090535936ULL,0ULL,67108864ULL,0ULL,27866057054093312ULL},
{0ULL,1048576ULL,0ULL,23362423067508736ULL,0ULL,536870912ULL,0ULL,28147566390542336ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,270532608ULL,0ULL,23643898044743680ULL,0ULL,68720525312ULL,0ULL,25895698125815808ULL,0ULL,137707388928ULL,0ULL,28147566390542336ULL,0ULL,69793218560ULL,0ULL,28429110086729728ULL,0ULL,137441050624ULL,0ULL,26458648884543488ULL,0ULL,1074790400ULL,0ULL,23925373022502912ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,4194304ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26459061201403904ULL,0ULL,2149580800ULL,0ULL,24206848001310720ULL,0ULL,274882101248ULL,0ULL,26740124934995968ULL,0ULL,139586437120ULL,0ULL,28710722502393856ULL,0ULL,275414777856ULL,0ULL,28429110086729728ULL,0ULL,137441050624ULL,0ULL,26177173370961920ULL,0ULL,541065216ULL,0ULL,23925373022502912ULL},
{0ULL,8388608ULL,0ULL,27023251326631936ULL,0ULL,8388608ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26459061201403904ULL,0ULL,279172874240ULL,0ULL,28992472357011456ULL,0ULL,549764202496ULL,0ULL,27021602059190272ULL,0ULL,4299161600ULL,0ULL,24488322982215680ULL,0ULL,1082130432ULL,0ULL,24206848001310720ULL,0ULL,274882101248ULL,0ULL,26458648884543488ULL,0ULL,550829555712ULL,0ULL,28710722502393856ULL},
{0ULL,8388608ULL,0ULL,27023251326631936ULL,0ULL,8388608ULL,0ULL,26740949568716800ULL,0ULL,16777216ULL,0ULL,27023251326631936ULL,0ULL,16777216ULL,0ULL,27306379865751552ULL,0ULL,549764202496ULL,0ULL,26740124934995968ULL,0ULL,2164260864ULL,0ULL,24488322982215680ULL,0ULL,8598323200ULL,0ULL,24769797967314944ULL,0ULL,1099528404992ULL,0ULL,27303081330868224ULL,0ULL,558345748480ULL,0ULL,29274497089536000ULL,0ULL,1101659111424ULL,0ULL,28992472357011456ULL},
{0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,16777216ULL,0ULL,27023251326631936ULL,0ULL,16777216ULL,0ULL,27306379865751552ULL,0ULL,17196646400ULL,0ULL,25051272960802816ULL,0ULL,4328521728ULL,0ULL,24769797967314944ULL,0ULL,1099528404992ULL,0ULL,27021602059190272ULL,0ULL,2203318222848ULL,0ULL,29274497089536000ULL,0ULL,1116691496960ULL,0ULL,29557071577874432ULL,0ULL,2199056809984ULL,0ULL,27584564897513472ULL},
{0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,2233382993920ULL,0ULL,29840745577840640ULL,0ULL,4406636445696ULL,0ULL,29557071577874432ULL,0ULL,2199056809984ULL,0ULL,27303081330868224ULL,0ULL,8657043456ULL,0ULL,25051272960802816ULL,0ULL,34393292800ULL,0ULL,25332747971067904ULL,0ULL,4398113619968ULL,0ULL,27866057054093312ULL},
{0ULL,67108864ULL,0ULL,25614223014887424ULL,0ULL,17179869184ULL,0ULL,29840745577840640ULL},
{0ULL,536870912ULL,0ULL,25895698125815808ULL,0ULL,536870912ULL,0ULL,28429110086729728ULL},
{0ULL,536870912ULL,0ULL,28147566390542336ULL,0ULL,1073741824ULL,0ULL,28710722502393856ULL},
{0ULL,1073741824ULL,0ULL,28429110086729728ULL,0ULL,2147483648ULL,0ULL,28992472357011456ULL},
{0ULL,4294967296ULL,0ULL,29274497089536000ULL,0ULL,2147483648ULL,0ULL,28710722502393856ULL},
{0ULL,8589934592ULL,0ULL,29557071577874432ULL,0ULL,4294967296ULL,0ULL,28992472357011456ULL},
{0ULL,8589934592ULL,0ULL,29274497089536000ULL,0ULL,17179869184ULL,0ULL,29840745577840640ULL},
{0ULL,17179869184ULL,0ULL,29557071577874432ULL,0ULL,17179869184ULL,0ULL,27866057054093312ULL}};
|
[
"maksverver@geocities.com"
] |
maksverver@geocities.com
|
614ec6dfbb9d10d1bef6281d242fc7f1ad2fde26
|
b4660cc8fa3ce045508105fa52228a98fa19a87d
|
/src/gui/post_install_dialog/post_install_dialog.h
|
efd4222a68f02b55fb045c2c62c83c05e0530280
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-public-domain"
] |
permissive
|
hnakamur/mozc-deb
|
81e9b561863e57da73aa9ba90d24ff5d0bca480b
|
a0d6db21786ae7fc54806714cbeca6c7c74cbd36
|
refs/heads/master
| 2021-04-15T09:32:03.635220
| 2018-05-04T10:09:23
| 2018-05-04T10:09:23
| 126,575,465
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,616
|
h
|
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef MOZC_GUI_POST_INSTALL_DIALOG_H_
#define MOZC_GUI_POST_INSTALL_DIALOG_H_
#include <memory>
#include "base/port.h"
#include "gui/post_install_dialog/ui_post_install_dialog.h"
namespace mozc {
namespace gui {
class SetupUtil;
// Shows additional information to the user after installation.
// This dialog also set Mozc as the default IME if it is closed
// with the check box marekd.
class PostInstallDialog : public QDialog,
private Ui::PostInstallDialog {
Q_OBJECT;
public:
PostInstallDialog();
virtual ~PostInstallDialog();
protected slots:
virtual void OnOk();
virtual void OnsetAsDefaultCheckBoxToggled(int state);
virtual void reject();
private:
// - Sets Mozc as the default IME if the check box on the
// dialog is marked.
// - Imports MS-IME's user dictionary to Mozc' dictionary if
// the checkbox on the dialog is marked.
void ApplySettings();
std::unique_ptr<SetupUtil> setuputil_;
};
} // namespace gui
} // namespace mozc
#endif // MOZC_GUI_POST_INSTALL_DIALOG_H_
|
[
"hnakamur@gmail.com"
] |
hnakamur@gmail.com
|
87d18d90b40ea0ce78371fc959061d30be0fff03
|
e5a078e8d7f1da417da6315f7f4080fee16dac0e
|
/huffmanCode/huffman_code.cpp
|
8d1fc135e6a38325cf1acaf2f24996e44f01927b
|
[] |
no_license
|
Aierhaimian/data-structures
|
2fcdab5a31b9d910e39d558ff83918b71d378c27
|
7b3bfbd7f9b12104a2f899258830c05114c0ec22
|
refs/heads/master
| 2020-04-01T14:24:12.688295
| 2019-09-08T07:33:19
| 2019-09-08T07:33:19
| 153,292,819
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,456
|
cpp
|
//
// Created by scu_d on 2017/11/17.
//
#include <iostream>
#include <climits>
#include <cstring>
#include <algorithm>
#include <functional>
#include <fstream>
#include "huffman_code.h"
// 选择最小和次小的两个结点,建立哈夫曼树调用
void huffman_code::select(HufNode *huf_tree, unsigned int n, int &s1, int &s2){
unsigned long min = ULONG_MAX;
//find the minimum node
for (int i = 0; i < n; ++i) {
if (huf_tree[i].parent == 0 && huf_tree[i].weight <min){
min = huf_tree[i].weight;
s1 = i;
}
}
huf_tree[s1].parent = 1;// Ok, it's the minimum node now.
//find the second minimum node
min = ULONG_MAX;
for (int i = 0; i < n; ++i) {
if (huf_tree[i].parent == 0 && huf_tree[i].weight < min){
min = huf_tree[i].weight;
s2 = i;
}
}
}
// 建立哈夫曼树
void huffman_code::CreateTree(HufNode *huf_tree, unsigned int char_kinds, unsigned int node_num){
int s1, s2;
for (int i = char_kinds; i < node_num; ++i) {
select(huf_tree, i, s1, s2);//选择最小的两个结点
huf_tree[s1].parent = i;
huf_tree[s2].parent = i;
huf_tree[i].lchild = s1;
huf_tree[i].rchild = s2;
huf_tree[i].weight = huf_tree[s1].weight + huf_tree[s2].weight;
}
}
// 生成哈夫曼编码
void huffman_code::HufCode(HufNode *huf_tree, unsigned char_kinds){
int cur, next, index;
char *code_tmp;
code_tmp = new char[256];//Temporary code, up to 256 leaves, coding length does not exceed 255
code_tmp[256-1] = '\0';
for (int i = 0; i < char_kinds; ++i) {
index = 256 - 1;//Encoding temporary space index initialization
//Reverse traversal from leaf to root for encoding
for (cur = i, next = huf_tree[i].parent; next != 0; cur = next, next = huf_tree[next].parent) {
if (huf_tree[next].lchild == cur)
code_tmp[--index] = '0';//left '0'
else
code_tmp[--index] = '1';//right '1
}
huf_tree[i].code = new char[256-index];//The i_th character encoding dynamic allocation of memory space
strcpy(huf_tree[i].code, &code_tmp[index]);//Forward save encoding to the corresponding node in the tree
}
delete [] code_tmp;
}
// 压缩函数
int huffman_code::compress(std::string file_name, std::string out_filename){
unsigned int char_kinds;// 字符种类
unsigned long file_len = 0;
unsigned char char_temp;// 暂存8bits字符
TmpNode node_temp;
unsigned int node_num;
HufTree huf_tree;
char code_buf[256] = "\0";// 待存编码缓冲区
unsigned int code_len;
//Dynamically allocate 256 nodes, temporary storage character frequency,
// statistics and copied to the tree node immediately after the release
TmpNode *tmp_nodes = new TmpNode[256];
//Init temporary node
for (int i = 0; i < 256; ++i) {
tmp_nodes[i].weight = 0;
tmp_nodes[i].uch = i;//The 256 subscripts of the array correspond to 256 characters
}
//Traverse the file, get the character frequency
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
while (!in_file.eof()){
++tmp_nodes[char_temp].weight;
++file_len;
in_file.read((char *)&char_temp, sizeof(unsigned char));
}
in_file.close();
//Sort, the frequency of zero put last, remove
for (int i = 0; i < 256-1; ++i) {
for (int j = i + 1; j < 256; ++j) {
if (tmp_nodes[i].weight < tmp_nodes[j].weight) {
node_temp = tmp_nodes[i];
tmp_nodes[i] = tmp_nodes[j];
tmp_nodes[j] = node_temp;
}
}
}
//Statistics of the actual character types (the number of occurrences is not 0)
for (unsigned int i = 0; i < 256; ++i) {
if(tmp_nodes[i].weight == 0){
char_kinds = i;
break;
}
}
std::cout<<"writing compressed file..."<<std::endl;
if (char_kinds == 1){
std::cout<<"char_kinds == 1"<<std::endl;
std::ofstream out_file(out_filename);
out_file.write((char *)&char_kinds, sizeof(unsigned int));
out_file.write((char *)&tmp_nodes[0].uch, sizeof(unsigned char));
out_file.write((char *)&tmp_nodes[0].weight, sizeof(unsigned long));
delete[] tmp_nodes;
out_file.close();
}
else{
//According to the number of characters, calculate the number of nodes needed to establish Huffman tree
node_num = 2 * char_kinds -1;
//Dynamically establish the necessary nodes of the Huffman tree
huf_tree = new HufNode[node_num];
//init the 0 to char_kinds-1 nodes
for (int i = 0; i < char_kinds; ++i) {
//Copy the characters and frequency of the temporary node to the tree node
huf_tree[i].uch = tmp_nodes[i].uch;
huf_tree[i].weight = tmp_nodes[i].weight;
huf_tree[i].parent = 0;
}
delete[] tmp_nodes;
//init the char_kinds to node_num nodes
for (int i = char_kinds; i < node_num; ++i) {
huf_tree[i].parent = 0;
}
//Create the Huffman Tree
huffman_code::CreateTree(huf_tree, char_kinds, node_num);
//Create the Huffman Encode
huffman_code::HufCode(huf_tree,char_kinds);
//write char and weight, for extract process to rebuild Huffman Tree
std::ofstream out_file(out_filename);
out_file.write((char *)&char_kinds, sizeof(unsigned int));
for (int i = 0; i < char_kinds; ++i) {
out_file.write((char *)&huf_tree[i].uch, sizeof(unsigned char));
out_file.write((char *)&huf_tree[i].weight, sizeof(unsigned long));
}
//write file length and weight information
out_file.write((char *)&file_len, sizeof(unsigned long));
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
while (!in_file.eof()){
//匹配字符对应编码
for (int i = 0; i < char_kinds; ++i) {
if (char_temp == huf_tree[i].uch){
strcat(code_buf, huf_tree[i].code);
}
}
//以8位(1Byte)为处理单元
while (strlen(code_buf) >= 8){
char_temp = '\0';//清空字符暂存空间,改为暂存字符对应编码
for (int k = 0; k < 8; ++k) {
char_temp <<= 1;//左移一位,为下一个bit腾出位置
if (code_buf[k] == '1')
char_temp |= 1;//当编码为"1",通过或操作符将其添加到字节的最低位
}
out_file.write((char *)&char_temp, sizeof(unsigned char));// 将字节对应编码存入文件
strcpy(code_buf, code_buf+8);//编码缓存去除已处理的前八位
}
in_file.read((char *)&char_temp, sizeof(unsigned char));
}
//处理最后不足8bits编码
code_len = strlen(code_buf);
if(code_len > 0){
char_temp = '\0';
for (int i = 0; i < code_len; ++i) {
if(code_buf[i] == '1'){
char_temp |= 1;
}
}
char_temp <<=8-code_len;
out_file.write((char *)&char_temp, sizeof(unsigned char));
}
in_file.close();
out_file.close();
delete [] huf_tree;
}
double rsize_d,dsize_d;
std::ifstream rfile(file_name);
if(!rfile.is_open()) return -1;
rfile.seekg(0,std::ios_base::end);
std::streampos rsize = rfile.tellg();
rfile.close();
std::ifstream dfile(out_filename);
if(!dfile.is_open()) return -1;
dfile.seekg(0,std::ios_base::end);
std::streampos dsize = dfile.tellg();
dfile.close();
rsize_d = rsize;
dsize_d = dsize;
std::cout<<"The "<<file_name<<" is: "<<rsize/1024<<" KB."<<std::endl;
std::cout<<"The compressed file "<<out_filename<<" is: "<<dsize/1024<<" KB."<<std::endl;
std::cout<<"The compression ratio is: "<<(rsize_d - dsize_d)/rsize_d *100<<"%"<<std::endl;
return 1;
}//compress
// 解压函数
int huffman_code::extract(std::string file_name, std::string out_filename){
unsigned long writen_len = 0;// 控制文件写入长度
unsigned long file_len;
unsigned int char_kinds;
unsigned int node_num;
HufTree huf_tree;
unsigned char code_temp;
unsigned int root;// 保存根节点索引,供匹配编码使用
std::ifstream in_file(file_name, std::ios::in|std::ios::binary);
if(!in_file){
return -1;
}
in_file.read((char *)&char_kinds, sizeof(unsigned int));
if (char_kinds == 1){
in_file.read((char *)&code_temp, sizeof(unsigned char));
in_file.read((char *)&file_len, sizeof(unsigned long));
std::ofstream out_file(out_filename);
while (file_len--){
out_file.write((char *)&code_temp, sizeof(unsigned char));
}
in_file.close();
out_file.close();
}else{
node_num = 2*char_kinds - 1;
huf_tree = new HufNode[node_num];
//读取字符及对应权重,存入哈夫曼树结点
//buffer[1]~buffer[152]
for (int i = 0; i < char_kinds; ++i) {
in_file.read((char *)&huf_tree[i].uch, sizeof(unsigned char));
in_file.read((char *)&huf_tree[i].weight, sizeof(unsigned long));
huf_tree[i].parent = 0;
}
//初始化后node_num-char_kins个结点的parent
for (int i = char_kinds; i < node_num; ++i) {
huf_tree[i].parent = 0;
}
//重建哈夫曼树
huffman_code::CreateTree(huf_tree, char_kinds, node_num);
//读完字符和权重信息,紧接着读取文件长度和编码,进行解码
in_file.read((char *)&file_len, sizeof(unsigned long));
std::ofstream out_file(out_filename);
root = node_num-1;
int cnt = 154;
while(1) {
in_file.read((char *)&code_temp, sizeof(unsigned char));
for (int i = 0; i < 8; ++i) {
if (code_temp & 128)
root = huf_tree[root].rchild;
else
root = huf_tree[root].lchild;
if (root < char_kinds){
out_file.write((char *)&huf_tree[root].uch, sizeof(unsigned char));
++writen_len;
if (writen_len == file_len)
break;
root = node_num - 1;
}
code_temp <<= 1;
}
if (writen_len == file_len)
break;
++cnt;
}
in_file.close();
out_file.close();
delete [] huf_tree;
}
return 1;
}//extract
|
[
"scu_duzexu@163.com"
] |
scu_duzexu@163.com
|
307f7aca6d80cbb4c174debf0567a5be42016025
|
3181b69e42860996b019d71ff956cc1a69c00127
|
/caleb.hpp
|
2367723aaf1890778e4ac2c3e9c23522dfba7844
|
[] |
no_license
|
amcalhoun84/Group-Mu-The-Summerworth-Horror
|
4737dc375f841b802cd6158a418999dd39bd9749
|
a3e8b36f5d9719841f50f2f273518279bf78c592
|
refs/heads/master
| 2020-04-05T18:32:21.249738
| 2016-06-09T20:55:12
| 2016-06-09T20:55:12
| 55,563,848
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 295
|
hpp
|
#ifndef _CALEB_HPP
#define _CALEB_HPP
#include "creature.hpp"
class Caleb : public Creature
{
private:
string insults;
string response;
public:
Caleb();
~Caleb();
std::string conversation(string cmd);
std::string randomInsult();
int attackPlayerHP();
};
#endif
|
[
"calhouna@onid.oregonstate.edu"
] |
calhouna@onid.oregonstate.edu
|
98ac9d660780fca490a2ad762f2930118f8f05d3
|
b8c8a7c9747d4ded741e6aa7465e954d676d3cba
|
/my.cpp
|
5f2a51ab8ebb51b9d11a57e4df61d8781b27ee9e
|
[] |
no_license
|
BinwuPeng/ECE551-C-Course-Work
|
f0ac812726eea3a7cde5655838273cce8d6ef126
|
885b3a7291479a28623299a00661122504a1dc25
|
refs/heads/master
| 2020-04-22T19:39:11.364974
| 2019-08-20T20:12:38
| 2019-08-20T20:12:38
| 170,614,744
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 376
|
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
extern char **environ;
int main(int argc, char **argv, char** env) {
system("env");
//printf("%s\n", " ");
//printf("%s\n", " ");
//char *argt[] = {"env", NULL};
//execve("env", {"env",NULL}, environ);
}
|
[
"Binwu.peng@duke.edu"
] |
Binwu.peng@duke.edu
|
96454b51922a36b5045c892e2a169f758cc457b5
|
1f7f599da6cbf91f4afd8abfb497c465f7663c8b
|
/emscripten-arch/hello.cpp
|
fb0de74fdceefb470c7f45c6c27c3a48b1ee5b54
|
[] |
no_license
|
cjxgm/emscripten-arch
|
7853ecd6f66245743c0643ca02f0a8726997c56b
|
bd4c14ae295e4937d9971243d0f6f5832aa04408
|
refs/heads/master
| 2021-05-09T22:50:32.935849
| 2018-10-06T09:48:01
| 2018-10-06T09:48:01
| 118,765,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 179
|
cpp
|
#include <iostream>
#include <stdexcept>
int main() try
{
throw std::runtime_error{"hello world"};
}
catch (std::exception const& ex) {
std::cerr << ex.what() << "\n";
}
|
[
"cjxgm2@gmail.com"
] |
cjxgm2@gmail.com
|
12f3c848c92f087d6d2a1c6284373bd1ff664d19
|
337f830cdc233ad239a5cc2f52c6562fbb671ea8
|
/case5cells/6.6/polyMesh/pointZones
|
bc3a89f1e0b994f6b16c3c775ba0e6499adc04bf
|
[] |
no_license
|
j-avdeev/laplacianFoamF
|
dba31d0941c061b2435532cdfbd5a5b337e6ffe9
|
6e1504dc84780dc86076145c18862f1882078da5
|
refs/heads/master
| 2021-06-25T23:52:36.435909
| 2017-02-05T17:28:45
| 2017-02-05T17:28:45
| 26,997,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 873
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class regIOobject;
location "6.6/polyMesh";
object pointZones;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
0
()
// ************************************************************************* //
|
[
"j-avdeev@ya.ru"
] |
j-avdeev@ya.ru
|
|
8706e867bbf866ca372015be551852844ef99ce2
|
915c7ea66fc5d6ea3f38c4f84296a285fd95ae5f
|
/src/stats.cpp
|
59a76bd48d51c78e5685d994aafd57515add6354
|
[
"MIT",
"LicenseRef-scancode-llnl",
"BSD-3-Clause",
"LicenseRef-scancode-hdf5",
"BSL-1.0",
"BSD-2-Clause"
] |
permissive
|
matq007/kEDM
|
ba602306d3454329465e960c629d10fe28ef24a2
|
e7f08b6488d76d06b52bbc60fa34a79469349c30
|
refs/heads/master
| 2023-09-05T06:32:33.860993
| 2021-11-16T07:24:06
| 2021-11-16T07:24:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,887
|
cpp
|
#include "stats.hpp"
namespace edm
{
float corrcoef(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
using std::sqrt;
#endif
CorrcoefState state;
Kokkos::parallel_reduce(
"EDM::stats::corrcef", min(x.size(), y.size()),
KOKKOS_LAMBDA(int i, CorrcoefState &upd) {
upd += CorrcoefState(x(i), y(i));
},
Kokkos::Sum<CorrcoefState>(state));
return state.rho();
}
void corrcoef(CrossMap rho, Dataset ds, TimeSeries x)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
using std::sqrt;
#endif
Kokkos::parallel_for(
"EDM::stats::corrcef", Kokkos::TeamPolicy<>(ds.extent(1), Kokkos::AUTO),
KOKKOS_LAMBDA(const Kokkos::TeamPolicy<>::member_type &member) {
const int j = member.league_rank();
CorrcoefState state;
Kokkos::parallel_reduce(
Kokkos::TeamThreadRange(member, min(x.extent(0), ds.extent(0))),
[=](int i, CorrcoefState &upd) {
upd += CorrcoefState(x(i), ds(i, j));
},
Kokkos::Sum<CorrcoefState>(state));
rho(j) = state.rho();
});
}
float mae(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::abs;
using std::min;
#endif
int n = min(x.size(), y.size());
float sum;
Kokkos::parallel_reduce(
"EDM::stats::mae", n,
KOKKOS_LAMBDA(int i, float &upd) { upd += abs(x(i) - y(i)); }, sum);
return sum / n;
}
float mse(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
#endif
int n = min(x.size(), y.size());
float sum;
Kokkos::parallel_reduce(
"EDM::stats::mse", n,
KOKKOS_LAMBDA(int i, float &upd) {
upd += (x(i) - y(i)) * (x(i) - y(i));
},
sum);
return sum / n;
}
} // namespace edm
|
[
"keichi.t@me.com"
] |
keichi.t@me.com
|
561155b40a9c18ece8471d14c539338bbc1ccfe7
|
48db44cdc74f8452b606e78bbbac2ef9eca8b1c1
|
/cbz2pdf/cbz2pdf.cpp
|
a727dfcd78f61d3156d02e68c402d0323f630f6a
|
[] |
no_license
|
fryn3/cbz2pdf
|
92d2f915c3282de6685c056d3612c2ecd32a15ca
|
19aeb72844e66fbe3da06f51b7d3b23a6eb79c20
|
refs/heads/master
| 2023-04-05T01:01:54.248002
| 2021-04-15T16:02:23
| 2021-04-15T16:02:23
| 356,853,304
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,185
|
cpp
|
#include "cbz2pdf.h"
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <cbz2pdfprivate.h>
Cbz2pdf::Cbz2pdf(QObject *parent)
: QObject(parent),
_worker(new Cbz2pdfWorker()),
_private(new Cbz2pdfPrivate(_worker, this)) {
_worker->moveToThread(&_thread);
connect(&_thread, &QThread::finished, _worker, &QObject::deleteLater);
_thread.start();
}
Cbz2pdf::~Cbz2pdf() {
stop();
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect( _worker, &Cbz2pdfWorker::stoped, &loop, &QEventLoop::quit );
connect( &timer, &QTimer::timeout, &loop, &QEventLoop::quit );
timer.start(2000);
loop.exec();
if (timer.isActive()) {
_thread.quit();
_thread.wait();
} else {
qDebug() << __PRETTY_FUNCTION__ << "timeout";
_thread.terminate();
}
}
void Cbz2pdf::setK(double k) { _private->setK(k); }
void Cbz2pdf::setDirOrZipName(QString dirOrZipName) { _private->setDirOrZipName(dirOrZipName); }
void Cbz2pdf::start() { _private->start(); }
void Cbz2pdf::stop() { _private->stop(); }
|
[
"karapetyan@inftest.ru"
] |
karapetyan@inftest.ru
|
7d29492616733c839f6b96c5999f642c4148712f
|
edfc92a7df8d8ce526324f8e21d603450bec6c23
|
/editors/ComponentEditor/general/desceditor.h
|
19187634f3736859befbd3f68cb068a3362c635b
|
[] |
no_license
|
shrimpdede/kactus2
|
97be5f47918c99c7a3b3c4e17cf89f1cba267588
|
401b9dc80c2f4f3d081a639e498b08a50c89de71
|
refs/heads/master
| 2021-01-21T20:30:09.864195
| 2015-09-14T12:42:14
| 2015-09-14T12:42:14
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,756
|
h
|
//-----------------------------------------------------------------------------
// File: desceditor.h
//-----------------------------------------------------------------------------
// Project: Kactus 2
// Author: Joni-Matti Määttä
// Date: 7.2.2011
//
// Description:
// Description editor for the component editor.
//-----------------------------------------------------------------------------
#ifndef DESCEDITOR_H
#define DESCEDITOR_H
#include <QGroupBox>
#include <QPlainTextEdit>
//-----------------------------------------------------------------------------
//! DescEditor class.
//-----------------------------------------------------------------------------
class DescEditor : public QGroupBox
{
Q_OBJECT
public:
/*!
* Constructor.
*
* @param [in] parent The parent widget.
*/
DescEditor(QWidget* parent = 0);
/*!
* Destructor.
*/
virtual ~DescEditor();
/*!
* Sets the description to the widget.
*
* @param [in] The description string.
*/
void setDescription(QString const& desc);
/*!
* Returns the description string.
*/
QString getDescription() const;
signals:
//! Emitted when the contents of the editor have changed.
void contentChanged();
private:
// Disable copying.
DescEditor(DescEditor const& rhs);
DescEditor& operator=(DescEditor const& rhs);
//-----------------------------------------------------------------------------
// Data.
//-----------------------------------------------------------------------------
//! The text edit for the description.
QPlainTextEdit* m_descEdit;
};
#endif // DESCEDITOR_H
|
[
"jonim@f0aa6db5-7f46-43cc-a8a5-a31efdaafa67"
] |
jonim@f0aa6db5-7f46-43cc-a8a5-a31efdaafa67
|
cf9db6b3e46b96cf4f3caa364512ed73127181f6
|
bb842de9543d666b66ca8f7b292a43174ac1c76c
|
/Teensy/teensy_drive_Flex_MA/Timer0.hpp
|
bcbc3b364a5d329582055fc6052111e10ac3f239
|
[] |
no_license
|
jensdehoog95/MAP2017
|
fa4bc686a357cffa514893c617e2aebe1dbfdc8d
|
85be1b162f67a78a5d5373cbc4ba9aac018ad82d
|
refs/heads/master
| 2021-03-19T05:57:46.629773
| 2017-06-26T13:47:14
| 2017-06-26T13:47:14
| 88,791,020
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,418
|
hpp
|
/*
* Interrupt and PWM utilities for 16 bit Timer0 on ATmega168/328
* Original code by Jesse Tane for http://labs.ideo.com August 2008
* Modified March 2009 by Jérôme Despatis and Jesse Tane for ATmega328 support
* Modified June 2009 by Michael Polli and Jesse Tane to fix a bug in setPeriod() which caused the timer to stop
* Modified April 2012 by Paul Stoffregen - portable to other AVR chips, use inline functions
* Modified again, June 2014 by Paul Stoffregen - support Teensy 3.x & even more AVR chips
*
*
* This is free software. You can redistribute it and/or modify it under
* the terms of Creative Commons Attribution 3.0 United States License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/us/
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
*
*/
#ifndef TimerZero_h_
#define TimerZero_h_
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "config/known_16bit_timers.h"
#define TIMER1_RESOLUTION 65536UL // Timer0 is 16 bit
// Placing nearly all the code in this .h file allows the functions to be
// inlined by the compiler. In the very common case with constant values
// the compiler will perform all calculations and simply write constants
// to the hardware registers (for example, setPeriod).
class TimerZero
{
#if defined(__AVR__)
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
TCCR1B = _BV(WGM13); // set mode as phase and frequency correct pwm, stop the timer
TCCR1A = 0; // clear control register A
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_CPU / 2000000) * microseconds;
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = _BV(CS10);
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = _BV(CS11);
pwmPeriod = cycles / 8;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 64;
} else
if (cycles < TIMER1_RESOLUTION * 256) {
clockSelectBits = _BV(CS12);
pwmPeriod = cycles / 256;
} else
if (cycles < TIMER1_RESOLUTION * 1024) {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = cycles / 1024;
} else {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = TIMER1_RESOLUTION - 1;
}
ICR1 = pwmPeriod;
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
TCCR1B = 0;
TCNT1 = 0; // TODO: does this cause an undesired interrupt?
resume();
}
void stop() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13);
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) OCR1A = dutyCycle;
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) OCR1B = dutyCycle;
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) OCR1C = dutyCycle;
#endif
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) { pinMode(TIMER1_A_PIN, OUTPUT); TCCR1A |= _BV(COM1A1); }
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) { pinMode(TIMER1_B_PIN, OUTPUT); TCCR1A |= _BV(COM1B1); }
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) { pinMode(TIMER1_C_PIN, OUTPUT); TCCR1A |= _BV(COM1C1); }
#endif
setPwmDuty(pin, duty);
TCCR1B = _BV(WGM13) | clockSelectBits;
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) TCCR1A &= ~_BV(COM1A1);
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) TCCR1A &= ~_BV(COM1B1);
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) TCCR1A &= ~_BV(COM1C1);
#endif
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
TIMSK1 = _BV(TOIE1);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
TIMSK1 = 0;
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#elif defined(__arm__) && defined(CORE_TEENSY)
#if defined(KINETISK)
#define F_TIMER F_BUS
#elif defined(KINETISL)
#define F_TIMER (F_PLL/2)
#endif
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_TIMER / 2000000) * microseconds;
// A much faster if-else
// This is like a binary serch tree and no more than 3 conditions are evaluated.
// I haven't checked if this becomes significantly longer ASM than the simple ladder.
// It looks very similar to the ladder tho: same # of if's and else's
/*
// This code does not work properly in all cases :(
// https://github.com/PaulStoffregen/TimerOne/issues/17
if (cycles < TIMER0_RESOLUTION * 16) {
if (cycles < TIMER0_RESOLUTION * 4) {
if (cycles < TIMER0_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
}else{
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
}
}else{
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
}else{
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
}
}
}else{
if (cycles > TIMER1_RESOLUTION * 64) {
if (cycles > TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}else{
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
}
}
else{
if (cycles > TIMER1_RESOLUTION * 32) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
}else{
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
}
}
}
*/
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 2) {
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
} else
if (cycles < TIMER1_RESOLUTION * 4) {
clockSelectBits = 2;
pwmPeriod = cycles >> 2;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
} else
if (cycles < TIMER1_RESOLUTION * 16) {
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
} else
if (cycles < TIMER1_RESOLUTION * 32) {
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
} else
if (cycles < TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
} else {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}
uint32_t sc = FTM0_SC;
FTM0_SC = 0;
FTM0_MOD = pwmPeriod;
FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_CPWMS | clockSelectBits | (sc & FTM_SC_TOIE);
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
stop();
FTM0_CNT = 0;
resume();
}
void stop() __attribute__((always_inline)) {
FTM0_SC = FTM0_SC & (FTM_SC_TOIE | FTM_SC_CPWMS | FTM_SC_PS(7));
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
FTM0_SC = (FTM0_SC & (FTM_SC_TOIE | FTM_SC_PS(7))) | FTM_SC_CPWMS | FTM_SC_CLKS(1);
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) {
FTM0_C0V = dutyCycle;
} else if (pin == TIMER1_B_PIN) {
FTM0_C1V = dutyCycle;
}
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
setPwmDuty(pin, duty);
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
}
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = 0;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = 0;
}
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
FTM0_SC |= FTM_SC_TOIE;
NVIC_ENABLE_IRQ(IRQ_FTM0);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
FTM0_SC &= ~FTM_SC_TOIE;
NVIC_DISABLE_IRQ(IRQ_FTM0);
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#undef F_TIMER
#endif
};
extern TimerZero Timer0;
#endif
|
[
"jens.dehoog@student.uantwerpen.be"
] |
jens.dehoog@student.uantwerpen.be
|
851decc822a0bed1058a1b10a685929b45775be3
|
800184441b1bc983e851a5b19ada981916379d32
|
/libraries/chain/include/graphene/chain/transaction_object.hpp
|
06ed0e743e477055c2fe642f67c5bd824a0a236f
|
[] |
no_license
|
0xae/graphene
|
83d441382b3df331a35da9407522d586f997ecc0
|
49fb41c440339121a066a33dc97069a5144bdf93
|
refs/heads/master
| 2020-12-02T23:01:07.614739
| 2015-07-08T03:47:27
| 2015-07-08T03:47:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,287
|
hpp
|
/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <fc/io/raw.hpp>
#include <graphene/chain/transaction.hpp>
#include <graphene/db/index.hpp>
#include <graphene/db/generic_index.hpp>
#include <fc/uint128.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
namespace graphene { namespace chain {
using namespace graphene::db;
using boost::multi_index_container;
using namespace boost::multi_index;
/**
* The purpose of this object is to enable the detection of duplicate transactions. When a transaction is included
* in a block a transaction_object is added. At the end of block processing all transaction_objects that have
* expired can be removed from the index.
*/
class transaction_object : public abstract_object<transaction_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_transaction_object_type;
signed_transaction trx;
time_point_sec expiration;
transaction_id_type trx_id;
};
struct by_expiration;
struct by_id;
struct by_trx_id;
typedef multi_index_container<
transaction_object,
indexed_by<
hashed_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
hashed_unique< tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER(transaction_object, transaction_id_type, trx_id), std::hash<transaction_id_type> >,
ordered_non_unique< tag<by_expiration>, BOOST_MULTI_INDEX_MEMBER(transaction_object, time_point_sec, expiration)>
>
> transaction_multi_index_type;
typedef generic_index<transaction_object, transaction_multi_index_type> transaction_index;
} }
FC_REFLECT_DERIVED( graphene::chain::transaction_object, (graphene::db::object), (trx)(expiration) )
|
[
"nat.hourt@gmail.com"
] |
nat.hourt@gmail.com
|
06d7d449c82012931a285549002f14e25dc247d5
|
f5b593692f3b54f051cd23397d09eac69e38ee9a
|
/powerplay 7/Object.cpp
|
fa58585398bfb51487d333673245fada02fb1114
|
[] |
no_license
|
AustinJesse/Power-Play-7
|
5520256c89e52dcf2cbc801ee0f38507c03f0be9
|
e66267d6bbc75e378a37f6b17be0b36c84ff01a6
|
refs/heads/master
| 2022-11-06T10:42:09.211783
| 2020-06-24T04:35:17
| 2020-06-24T04:35:17
| 274,575,498
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,195
|
cpp
|
#include <random>
#include <iostream>
#include "Monster.h"
#include "Object.h"
std::random_device Object::seed;
std::default_random_engine Object::engine(seed());
Object::Object(Type name, int strength, int health, int level) : name{ name }, strength{ strength }, health{ health }, level{ level }
{
}
bool Object::isDead()
{
if (health <= 0) {return true;}
else {return false;}
}
Object::Type Object::getName() const
{
return name;
}
int Object::getLevel() const
{
return level;
}
int Object::getHealth() const
{
return health;
}
std::ostream& operator<<(std::ostream& o, const Object& src)
{
o << "L:" << src.getLevel() << " ";
switch (src.getName())
{
case Object::Type::player:
std::cout << "Player";
break;
case Object::Type::slime:
std::cout << "Slime";
break;
case Object::Type::orc:
std::cout << "Orc";
break;
case Object::Type::sprite:
std::cout << "Sprite";
break;
case Object::Type::dragon:
std::cout << "Dragon";
break;
}
o << " h:" << src.getHealth();
return o;
}
//int Object::damageDone(int modification) const
//{
// int potentialDamage{ strength + modification };
// std::normal_distribution<double> damageDealt(potentialDamage, 2.0);
// std::cout << *this << " deals ";
// return std::max(1, (int)damageDealt(engine));
//}
int Object::damageDone(int modification) const
{
int potentialDamage{ strength + modification };
std::normal_distribution<double> damageDealt(potentialDamage, 2.0);
int damage = std::max(1, (int)damageDealt(engine));
//std::cout << *this << " deals " << damage << " damage!" << std::endl;
return damage;
}
//int Object::damageTaken(int damageDone, int AC)
//{
// return this->health -= (damageDone + AC);
//}
int Object::damageTaken(int damageDone, int AC)
{
//std::normal_distribution<double> defense(AC, 1.0 / level);
//damageDone = std::max(0, damageDone - (int)defense(engine));
//damageDone = 1; // damage is always 1...
//std::cout << damageDone << " damage to ";
//std::cout << *this << "!!!" << std::endl;
//health -= (damageDone + AC);
//return health;
std::cout << *this << " takes " << damageDone + AC << " damage!" << std::endl;
return this->health -= (damageDone + AC);
}
|
[
"aajesse@ualr.edu"
] |
aajesse@ualr.edu
|
3d576e267fd66e9d496b500d6ea38aa407d3982d
|
f2598ff3ddeee3686360567682bf5eddd8ba1ab5
|
/src/crypto/hmac_sha512.h
|
ec5f2213ceb838aba44c3a3faa62f55601974f5c
|
[
"MIT"
] |
permissive
|
MyProductsKft/Vitalcoin
|
c4566dca1b9a60cbb39de25faa7251e3a3786735
|
492306908ee457362f2ba777cbd235d417f6d3b5
|
refs/heads/master
| 2020-03-21T02:15:27.776360
| 2018-10-31T17:32:15
| 2018-10-31T19:14:54
| 137,989,832
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 757
|
h
|
// Copyright (c) 2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VITALCOIN_CRYPTO_HMAC_SHA512_H
#define VITALCOIN_CRYPTO_HMAC_SHA512_H
#include "crypto/sha512.h"
#include <stdint.h>
#include <stdlib.h>
/** A hasher class for HMAC-SHA-512. */
class CHMAC_SHA512 {
private:
CSHA512 outer;
CSHA512 inner;
public:
static const size_t OUTPUT_SIZE = 64;
CHMAC_SHA512(const unsigned char *key, size_t keylen);
CHMAC_SHA512 &Write(const unsigned char *data, size_t len) {
inner.Write(data, len);
return *this;
}
void Finalize(unsigned char hash[OUTPUT_SIZE]);
};
#endif // VITALCOIN_CRYPTO_HMAC_SHA512_H
|
[
"40405254+LeslieDombi@users.noreply.github.com"
] |
40405254+LeslieDombi@users.noreply.github.com
|
559b6871162434517e9881d1284e8d76539471f1
|
f816c668c0a43c702884558867300db94651269d
|
/StoreFrontEnd/Views/CollectionView/VCollectionView.cpp
|
f7d3eaa42a5890634cb6fadc00129da1d13fab06
|
[] |
no_license
|
MRobertEvers/Card-Collection-Manager
|
a77de7df7d80e712d1318b2a8abed1a6492454f7
|
8ff77956c70bbbaa803f88061208e681a4533917
|
refs/heads/master
| 2021-07-11T23:43:26.051644
| 2018-12-09T01:17:56
| 2018-12-09T01:17:56
| 114,420,990
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,510
|
cpp
|
#include "VCollectionView.h"
#include "CCollectionView.h"
#include "CubeRenderer.h"
#include "../Views/CardView/VCardView.h"
#include "../Views/CollectionEditor/viCollectionEditor.h"
wxBEGIN_EVENT_TABLE( VCollectionView, wxPanel )
//EVT_BUTTON( viCardEditor::Changes_Submit, vCollectionCube::onCardChanged )
//EVT_BUTTON( viCardEditor::Image_Changed, vCollectionCube::onNewItemSelectView )
EVT_GRID_CELL_LEFT_CLICK( VCollectionView::onItemClicked )
EVT_BUTTON( VCollectionView::COLLECTION_EDITED, VCollectionView::onCollectionEditorAccept )
EVT_BUTTON( viCollectionEditor::Changes_Accept, VCollectionView::onCollectionEditorAccept )
wxEND_EVENT_TABLE()
VCollectionView::VCollectionView( wxFrame* aParent, wxWindowID aiWID )
: wxPanel(aParent, aiWID)
{
m_mgr.SetManagedWindow( this );
this->GetParent()->SetMinSize( wxSize( 550, 500 ) );
auto pTargetFrame = this->GetParent();
if( pTargetFrame->GetSize().GetWidth() < pTargetFrame->GetMinSize().GetWidth() ||
pTargetFrame->GetSize().GetHeight() < pTargetFrame->GetMinSize().GetHeight() )
{
pTargetFrame->SetSize( pTargetFrame->GetMinSize() );
}
this->GetParent()->Layout();
}
VCollectionView::~VCollectionView()
{
// Don't need to destroy this because wxwidgets will.
//m_ptRenderer->Destroy();
m_mgr.UnInit();
}
void
VCollectionView::SetController( CCollectionView* aptController )
{
m_ptController = aptController;
}
// Takes ownership
void
VCollectionView::SetRenderer( FlexibleGroupRenderer* aptRenderer )
{
m_ptRenderer = aptRenderer;
// TODO: this is ugly;
auto panel = dynamic_cast<wxPanel*>(aptRenderer);
if( panel != nullptr )
{
m_mgr.AddPane( panel,
wxAuiPaneInfo().CenterPane() );
m_mgr.Update();
//GetSizer()->Add( panel, wxSizerFlags( 1 ).Expand() );
//uiPrepareSidePanel();
}
}
void
VCollectionView::Draw( std::vector<CardInterface*> avecItemData )
{
if( m_ptRenderer != nullptr )
{
std::vector<std::shared_ptr<IRendererItem>> vecItems;
for( auto& ptr : avecItemData )
{
vecItems.push_back( std::shared_ptr<IRendererItem>(new RendererItem(ptr) ) );
}
m_ptRenderer->Draw( vecItems );
}
}
void
VCollectionView::Undraw( const wxString & aszDisplay, const wxString & aszUID )
{
auto iter_item = m_ptRenderer->LookupItem( aszDisplay.ToStdString(), aszUID.ToStdString() );
if( iter_item != nullptr )
{
m_ptRenderer->RemoveItem( iter_item );
}
}
void
VCollectionView::Draw( CardInterface* apNew )
{
for( auto& uid : apNew->GetRepresentingUIDs() )
{
Undraw( apNew->GetName(), uid );
}
m_ptRenderer->AddItem( std::shared_ptr<IRendererItem>( new RendererItem( apNew ) ) );
}
void
VCollectionView::ShowCardViewer( IViewFactory* aptViewer )
{
auto view = aptViewer->GetView( this );
m_mgr.AddPane( view,
wxAuiPaneInfo().Right().CaptionVisible( false ).CloseButton( false ).Floatable(false).Fixed().BestSize( view->GetBestSize()) );
m_mgr.Update();
//m_ptSidePanel->GetSizer()->Add( aptViewer->GetView( m_ptSidePanel ), wxSizerFlags( 0 ).Align(wxTOP | wxCenter) );
//this->Layout();
}
void
VCollectionView::ShowCardInventoryViewer( IViewFactory* aptViewer )
{
auto view = aptViewer->GetView( this );
m_mgr.AddPane( view,
wxAuiPaneInfo().Right().CaptionVisible(false).CloseButton(false).Floatable(false).BestSize( view->GetBestSize() ) );
m_mgr.Update();
//m_ptSidePanel->GetSizer()->Add( aptViewer->GetView(m_ptSidePanel), wxSizerFlags( 1 ).Expand() );
//this->Layout();
}
void
VCollectionView::onCollectionEditorAccept( wxCommandEvent& awxEvt )
{
// m_ptController->OnCollectionEdited();
CollectionDelta* delta = dynamic_cast<CollectionDelta*>((CollectionDelta*)awxEvt.GetClientData());
if( delta == nullptr )
{
m_ptController->OnCollectionEdited();
}
else
{
auto myDelta = std::shared_ptr<CollectionDelta>( delta );
// Take ownership of the data.
m_ptController->OnCollectionEdited( myDelta );
}
}
void
VCollectionView::onItemClicked( wxGridEvent& awxEvt )
{
auto pItem = dynamic_cast<RendererItem*>((RendererItem*)awxEvt.GetClientData());
if( pItem != nullptr )
{
m_ptController->ViewItem( pItem->GetBase() );
}
awxEvt.Skip();
}
void
FlexibleGroupRenderer::InitRenderer( std::vector<std::shared_ptr<IRendererItem>> avecItemData )
{
for( auto& item : avecItemData )
{
m_mapLookup.insert( std::make_pair( item->GetName(), item ) );
}
}
std::shared_ptr<IRendererItem>
FlexibleGroupRenderer::LookupItem( const std::string & aszDisplay, const std::string & aszUID )
{
auto pair_item_range = m_mapLookup.equal_range( aszDisplay );
for( auto iter_named = pair_item_range.first;
iter_named != pair_item_range.second;
iter_named++ )
{
if( iter_named->second->RepresentsUID( aszUID ) )
{
return iter_named->second;
}
}
return std::shared_ptr<IRendererItem>();
}
void
FlexibleGroupRenderer::ItemRemoved( std::shared_ptr<IRendererItem> apAdded )
{
auto pair_item_range = m_mapLookup.begin();
for( ;
pair_item_range != m_mapLookup.end();
pair_item_range++ )
{
if( pair_item_range->second == apAdded )
{
m_mapLookup.erase( pair_item_range );
break;
}
}
}
void
FlexibleGroupRenderer::ItemAdded( std::shared_ptr<IRendererItem> apAdded )
{
m_mapLookup.insert( std::make_pair( apAdded->GetName(), apAdded ) );
}
|
[
"mroberteverssci@gmail.com"
] |
mroberteverssci@gmail.com
|
b66cc8ebb6f2f590f221cda99ecc387edf6e9294
|
fa4a1fd904955489d9e44969bdc968df917f7fa9
|
/Test2/상속.cpp
|
604dc8c1b79ac33de43409607cfd226d3cd357e4
|
[] |
no_license
|
WhiteHair-H/Study-C-PLUS
|
9b4461a050b082c940b1e29c79b96dd7d312a9d7
|
b45e17e2030b442aa3e54176759cc394936ad71b
|
refs/heads/main
| 2023-05-22T18:47:16.051846
| 2021-06-10T07:47:20
| 2021-06-10T07:47:20
| 372,756,097
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,101
|
cpp
|
//#include <stdio.h>
//#include <iostream>
//using namespace std;
//
//class Human
//{
//private:
// char* name;
//public:
// Human(const char* aname)
// {
// int len = strlen(aname) + 1;
// name = new char[len];
// //strcpy(name, aname);
// strcpy_s(name, len, aname); // strcpy 보단 안정적
// }
// ~Human() { delete[] name; }
// void printName()
// {
// cout << "My name is " << name << endl;
// }
// const char* getName() { return name; }
//};
//
//class Student : public Human
//{
//private:
// char* major;
//public:
// Student(const char* aname, const char* amajor) : Human(aname)
// {
// int len = strlen(amajor) + 1;
// major = new char[len];
// strcpy_s(major, len, amajor);
// /*int len1 = strlen(aname) + 1;
// aname = new char[len1];
// strcpy_s(major, len1, aname);*/
// }
//
// void printMajor()
// {
// cout << "My name is " << getName() << " End My major is " << major << "입니다." << endl;
// }
// ~Student() { delete[] major; }
//};
//
//int main()
//{
// Human h("jinwoo");
// h.printName();
//
// Student s("jinwoo", "Iot");
// s.printMajor();
// return 0;
//}
|
[
"https://github.com/WhiteHair-H/BasicSetting.git"
] |
https://github.com/WhiteHair-H/BasicSetting.git
|
d7b8df404510d4d94de12d6ccacd12cd41bfaa1a
|
7595abb601d1f75749ceec4013ce440f5f035ff2
|
/defaulted.h
|
4f57ca0c2bb6031180c640c36d7af199853852b9
|
[] |
no_license
|
sv1990/Defaulted
|
d5bb426a0d8fc9cd0616d1c0d27088def54e6a82
|
b7bfafee74a4557259bf39f814f08f95a6a7b280
|
refs/heads/master
| 2021-05-05T09:55:11.070922
| 2017-09-17T20:54:01
| 2017-09-17T20:54:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 816
|
h
|
#ifndef defaulted_h
#define defaulted_h
namespace fluent
{
struct DefaultValue{};
static const DefaultValue defaultValue;
template<typename T, T... DefaultedParameters>
class Defaulted
{
public:
Defaulted(T t) : value_(std::move(t)){}
Defaulted(DefaultValue) : value_(DefaultedParameters...) {}
T const& get() const { return value_; }
T & get() { return value_; }
private:
T value_;
};
template<typename T, typename GetValue>
class DefaultedF
{
public:
DefaultedF(T t) : value_(std::move(t)){}
DefaultedF(DefaultValue) : value_(GetValue::get()) {}
T const& get() const { return value_; }
T & get() { return value_; }
private:
T value_;
};
}
#endif /* defaulted_h */
|
[
"boccaraj@gmail.com"
] |
boccaraj@gmail.com
|
a7a11f15efab15c8d4481ab898d8d8a622bbb699
|
44313c3267c1b694970a7cffd50a486930fea285
|
/OgreNewt 2/src/OgreNewt_Joint.cpp
|
559070516191b169dc3e9a6fc54a77132eac34eb
|
[] |
no_license
|
ehei1/maze-client
|
3bd08b40d8a02c760e0da631c9680a8375b514d8
|
3ca195e0cf21d2cf0c9c75b1374ffdaae3f88245
|
refs/heads/master
| 2022-10-28T13:38:27.971161
| 2020-06-15T12:33:24
| 2020-06-15T12:33:24
| 272,433,103
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,094
|
cpp
|
#include "OgreNewt_Joint.h"
#include "OgreNewt_Body.h"
#include "OgreNewt_World.h"
namespace OgreNewt
{
Joint::Joint()
{
// nothing here
}
Joint::~Joint()
{
if(m_joint)
{
if (NewtonJointGetUserData(m_joint))
{
NewtonJointSetDestructor( m_joint, NULL );
NewtonDestroyJoint( m_world->getNewtonWorld(), m_joint );
}
}
}
void _CDECL Joint::destructor( const NewtonJoint* me )
{
Joint* jnt;
jnt = (Joint*)NewtonJointGetUserData( me );
NewtonJointSetDestructor( me, NULL );
NewtonJointSetUserData( me, NULL );
delete jnt;
}
CustomJoint::CustomJoint( unsigned int maxDOF, const Body* body0, const Body* body1 ) : Joint()
{
m_maxDOF = maxDOF;
m_body0 = body0;
m_body1 = body1;
m_world = m_body0->getWorld();
if (body1)
m_joint = NewtonConstraintCreateUserJoint( m_world->getNewtonWorld(), m_maxDOF,
CustomJoint::newtonSubmitConstraint, CustomJoint::newtonGetInfo,
m_body0->getNewtonBody(), m_body1->getNewtonBody() );
else
m_joint = NewtonConstraintCreateUserJoint( m_world->getNewtonWorld(), m_maxDOF,
CustomJoint::newtonSubmitConstraint, CustomJoint::newtonGetInfo,
m_body0->getNewtonBody(), NULL );
NewtonJointSetUserData (m_joint, this);
NewtonJointSetDestructor (m_joint, destructor);
NewtonUserJointSetFeedbackCollectorCallback( m_joint, CustomJoint::newtonFeedbackCollector );
}
CustomJoint::~CustomJoint()
{
}
void CustomJoint::pinAndDirToLocal( const Ogre::Vector3& pinpt, const Ogre::Vector3& pindir,
Ogre::Quaternion& localOrient0, Ogre::Vector3& localPos0, Ogre::Quaternion& localOrient1, Ogre::Vector3& localPos1 ) const
{
localOrient0 = localOrient1 = Ogre::Quaternion::IDENTITY;
localPos0 = localPos1 = Ogre::Vector3::ZERO;
Ogre::Quaternion bodyOrient0 = Ogre::Quaternion::IDENTITY;
Ogre::Quaternion bodyOrient1 = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos0 = Ogre::Vector3::ZERO;
Ogre::Vector3 bodyPos1 = Ogre::Vector3::ZERO;
Ogre::Quaternion pinOrient = grammSchmidt(pindir);
m_body0->getPositionOrientation( bodyPos0, bodyOrient0 );
if (m_body1)
m_body1->getPositionOrientation( bodyPos1, bodyOrient1 );
localPos0 = bodyOrient0.Inverse() * (pinpt - bodyPos0);
localOrient0 = pinOrient * bodyOrient0.Inverse();
localPos1 = bodyOrient1.Inverse() * (pinpt - bodyPos1);
localOrient1 = pinOrient * bodyOrient1.Inverse();
}
void CustomJoint::localToGlobal( const Ogre::Quaternion& localOrient, const Ogre::Vector3& localPos, Ogre::Quaternion& globalOrient, Ogre::Vector3& globalPos, int bodyIndex ) const
{
globalOrient = Ogre::Quaternion::IDENTITY;
globalPos= Ogre::Vector3::ZERO;
const Body* bdy = NULL;
if (bodyIndex == 0)
bdy = m_body0;
else if (m_body1)
bdy = m_body1;
Ogre::Quaternion bodyOrient = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos = Ogre::Vector3::ZERO;
if (bdy)
bdy->getPositionOrientation( bodyPos, bodyOrient );
globalPos = (bodyOrient * localPos) + bodyPos;
globalOrient = bodyOrient * localOrient;
}
void CustomJoint::globalToLocal( const Ogre::Quaternion& globalOrient, const Ogre::Vector3& globalPos, Ogre::Quaternion& localOrient, Ogre::Vector3& localPos, int bodyIndex ) const
{
localOrient = Ogre::Quaternion::IDENTITY;
localPos= Ogre::Vector3::ZERO;
const Body* bdy = NULL;
if (bodyIndex == 0)
bdy = m_body0;
else if (m_body1)
bdy = m_body1;
Ogre::Quaternion bodyOrient = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos = Ogre::Vector3::ZERO;
if (bdy)
bdy->getPositionOrientation( bodyPos, bodyOrient );
Ogre::Quaternion bodyOrientInv = bodyOrient.Inverse();
localOrient = bodyOrientInv * globalOrient;
localPos = bodyOrientInv * (globalPos - bodyPos);
}
void CustomJoint::addLinearRow( const Ogre::Vector3& pt0, const Ogre::Vector3& pt1, const Ogre::Vector3& dir ) const
{
NewtonUserJointAddLinearRow( m_joint, &pt0.x, &pt1.x, &dir.x );
}
void CustomJoint::addAngularRow( Ogre::Radian relativeAngleError, const Ogre::Vector3& dir ) const
{
NewtonUserJointAddAngularRow( m_joint, relativeAngleError.valueRadians(), &dir.x );
}
void CustomJoint::addGeneralRow(const Ogre::Vector3& linear0, const Ogre::Vector3& angular0, const Ogre::Vector3& linear1, const Ogre::Vector3& angular1) const
{
float jacobian0[6], jacobian1[6];
jacobian0[0] = linear0.x;
jacobian0[1] = linear0.y;
jacobian0[2] = linear0.z;
jacobian0[3] = angular0.x;
jacobian0[4] = angular0.y;
jacobian0[5] = angular0.z;
jacobian1[0] = linear1.x;
jacobian1[1] = linear1.y;
jacobian1[2] = linear1.z;
jacobian1[3] = angular1.x;
jacobian1[4] = angular1.y;
jacobian1[5] = angular1.z;
NewtonUserJointAddGeneralRow( m_joint, jacobian0, jacobian1 );
}
void CustomJoint::setRowMinimumFriction( Ogre::Real friction ) const
{
NewtonUserJointSetRowMinimumFriction( m_joint, friction );
}
void CustomJoint::setRowMaximumFriction( Ogre::Real friction ) const
{
NewtonUserJointSetRowMaximumFriction( m_joint, friction );
}
void CustomJoint::setRowAcceleration( Ogre::Real accel ) const
{
NewtonUserJointSetRowAcceleration( m_joint, accel );
}
void CustomJoint::setRowStiffness( Ogre::Real stiffness ) const
{
NewtonUserJointSetRowStiffness( m_joint, stiffness );
}
void CustomJoint::setRowSpringDamper(Ogre::Real springK, Ogre::Real springD) const
{
NewtonUserJointSetRowSpringDamperAcceleration( m_joint, springK, springD );
}
void _CDECL CustomJoint::newtonSubmitConstraint( const NewtonJoint* me, float timeStep, int threadIndex )
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
j->submitConstraint( (Ogre::Real)timeStep, threadIndex );
}
void _CDECL CustomJoint::newtonFeedbackCollector( const NewtonJoint* me, float timeStep, int threadIndex )
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
j->feedbackCollector( (Ogre::Real)timeStep, threadIndex );
}
void _CDECL CustomJoint::newtonGetInfo(const NewtonJoint *me, NewtonJointRecord *info)
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
}
Ogre::Quaternion CustomJoint::grammSchmidt( const Ogre::Vector3& pin ) const
{
Ogre::Vector3 front, up, right;
front = pin;
front.normalise();
if (Ogre::Math::Abs( front.z ) > 0.577f)
right = front.crossProduct( Ogre::Vector3(-front.y, front.z, 0.0f) );
else
right = front.crossProduct( Ogre::Vector3(-front.y, front.x, 0.0f) );
right.normalise();
up = right.crossProduct( front );
Ogre::Matrix3 ret;
ret.FromAxes( front, up, right );
Ogre::Quaternion quat;
quat.FromRotationMatrix( ret );
return quat;
}
} // end NAMESPACE OgreNewt
|
[
"ehei0001@gmail.com"
] |
ehei0001@gmail.com
|
366e0a2f67f1e2364182102ec7ff1b575e15a59c
|
034d8e28730a6d8b8fb9cb403791f8693c8fd619
|
/Hashing/Hashing/Main.cpp
|
0af633ef41e61f9f7e4884ea5239f692ac0880b4
|
[] |
no_license
|
MisterMew/4-CodeDesignandDataStructures
|
7173db768e24d15db950cbe5866494e79e2e623f
|
ca1878658b9cb5e372c6c3ac28bdf0fe5450f387
|
refs/heads/main
| 2023-09-02T18:33:15.197430
| 2021-10-09T04:54:04
| 2021-10-09T04:54:04
| 378,316,284
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,551
|
cpp
|
#include "MainCore.h"
bool FileExists(string filepath) {
struct stat buffer;
return (stat(filepath.c_str(), &buffer) == 0);
}
#pragma region [ MENU Functions ]
/// HASH MENU: View Menu
/* View menu options for hashtable */
void HashMenuOptions() {
cout <<
"\n HASHING OPTIONS"
"\n [1] Check List"
"\n [2] Insert Item"
"\n [3] Remove Item"
"\n [4] Print Table"
"\n [0] EXIT"
<< endl;
}
/// HASH MENU: Validat Input
/* Validate user input for insert/remove */
void ValidateKey() {
/// INSERT Item
// Validate user input when inserting an item to the table
if (optSelected == OptSelect::InsertItem) {
cout << "\n [2]TIP!> If nothing happenes, the input was illegal.";
cout << "\n [2]INSERT> Please enter a key. (EG: Alpha, Bravo2, CH4RL13)" << "\n /: ";
cin >> gKey;
cout << "\n [2]INSERT> Please enter some data. (EG: 905, 247, 390)" << "\n /: ";
cin >> gData;
while (!cin) { //Validate for integer input
cin.clear();
cin.ignore();
cout << "\n /: ";
cin >> gData;
}
return;
}
/// REMOVE Item
// Validate user input when removing an item from the table
if (optSelected == OptSelect::RemoveItem) {
cout << "\n [3]DELETE> Please enter a key. (EG: Alpha, Bravo2, CH4RL13)" << "\n /: ";
getline(cin, gKey);
return;
}
}
/// HASH MENU: Validate Menu Input
/* Validate user input for selecting a menu option */
void MenuValidation() {
bool flag = true;
while (flag) {
cout << "\n //: ";
cin >> userInput;
switch (userInput) {
///CHECK TABLE
// Check if the hashtable is empty or not
case OptSelect::CheckTable:
flag = false;
HT.isEmpty();
continue;
///INSERT ITEM
// Insert an item to the hashtable
case OptSelect::InsertItem:
optSelected = OptSelect::InsertItem;
flag = false;
ValidateKey();
HT.InsertItem(gKey, gData);
continue;
///REMOVE ITEM
// Remove an item from the hashtable
case OptSelect::RemoveItem:
optSelected = OptSelect::RemoveItem;
flag = false;
ValidateKey();
HT.RemoveItem(gKey);
continue;
///PRINT TABLE
// Prints the hash table to the console
case OptSelect::PrintTable:
flag = false;
HT.PrintTable();
continue;
///EXIT CONSOLE
// Ends the program
case OptSelect::Exit:
flag = false;
exitConsole = true;
exit(0);
continue;
default: cout << "[]> Invalid.\n"; continue; //Loops until a valid input is recieved.
}
}
}
#pragma endregion
int main() {
HashTable hashTable;
HashMenuOptions();
while (!exitConsole) {
MenuValidation();
}
return 0;
}
|
[
"thebesteccentric@gmail.com"
] |
thebesteccentric@gmail.com
|
ff608a81e09795f297539e02ffbab184e030da15
|
2e02f4a1333b593cd45ea6e8aadb21e1fb4b3e2f
|
/CodeForces/C/1530 C.cpp
|
b5764a2967a99f71fcf4192b5c3b591b16bb8cd8
|
[] |
no_license
|
rahul-goel/CompetitiveProgramming
|
33c42145a5807ce1e1b94334faeeb960ad381edb
|
7c042b81dd9208137bbbd34e397baa55c85ff793
|
refs/heads/master
| 2022-09-25T04:26:16.173096
| 2022-09-05T18:26:23
| 2022-09-05T18:26:23
| 231,899,837
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,119
|
cpp
|
/*
Created by Rahul Goel.
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
/*******************************************************************************/
using namespace std;
using namespace __gnu_pbds;
template < typename T >
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
/*******************************************************************************/
using ll = long long;
using ld = long double;
const ll MOD = 1000000007;
// const ll MOD = 998244353;
const int INF = 1e9;
const ll LINF = 1e18;
/*******************************************************************************/
ll mod_sum() { return 0LL; }
template < typename T, typename... Args >
T mod_sum(T a, Args... args) { return ((a + mod_sum(args...))%MOD + MOD)%MOD; }
/*******************************************************************************/
ll mod_prod() { return 1LL; }
template< typename T, typename... Args >
T mod_prod(T a, Args... args) { return (a * mod_prod(args...))%MOD; }
/*******************************************************************************/
#ifdef ONLINE_JUDGE
#define endl '\n'
#endif
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define all(c) (c).begin(), (c).end()
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define uniq(c) (c).resize(distance((c).begin(), unique(all(c))))
#define min_pq(t) priority_queue < t, vector < t >, greater < t > >
#define max_pq(t) priority_queue < t >
#define pb push_back
#define ff first
#define ss second
/*******************************************************************************/
using pii = pair < ll, ll >;
using vi = vector < ll >;
using vb = vector < bool >;
using vvi = vector < vector < ll > >;
using vvb = vector < vector < bool > >;
using vpii = vector < pii >;
using vvpii = vector < vector < pii > >;
/*******************************************************************************/
//.-.. . -. -.- .- .. ... .-.. --- ...- .
/*
Code begins after this.
*/
ll solve() {
ll n;
cin >> n;
vector<ll> a(n), b(n);
for (ll &x : a) cin >> x;
for (ll &x : b) cin >> x;
sort(all(a));
reverse(all(a));
sort(all(b));
reverse(all(b));
ll x = 0, y = 0;
for (ll i = 0; i < n; i++) x += a[i], y += b[i];
for (ll i = 1; i < n; i++) a[i] += a[i - 1], b[i] += b[i - 1];
ll left = 0, right = INF, mid;
ll ans = -1;
while (left <= right) {
mid = (left + right) >> 1;
ll takex = (n + mid) - (n + mid) / 4;
ll takey = (n + mid) - (n + mid) / 4;
ll xx = 0, yy = 0;
// x
ll tx = min(mid, takex);
xx += tx * 100;
takex -= tx;
if (takex - 1 >= 0) xx += a[takex - 1];
// y
ll ty = min(n, takey);
yy += b[ty - 1];
takey -= ty;
yy += takey * 0;
if (xx >= yy) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
cout << ans << endl;
return 0;
}
signed main() {
fastio;
ll t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
[
"rahulgoellko@gmail.com"
] |
rahulgoellko@gmail.com
|
6ddad8dd5b2465130cd16fc1469dc4cbb61cbaaf
|
35a0f73a51d65b24470876f51353b18a8a7937ff
|
/source/game/entity/Blood.cpp
|
10dac799fe0f9c520b44b95438a01be052a4d591
|
[
"MIT"
] |
permissive
|
edeksumo/carpg
|
a7c3f90a31649b056bc18dda45448791d51739d7
|
7801960e05358c797ec968fda3cc0722d7421f6b
|
refs/heads/master
| 2021-01-21T03:37:42.802907
| 2015-05-17T09:40:01
| 2015-05-17T09:40:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 559
|
cpp
|
#include "Pch.h"
#include "Base.h"
#include "Blood.h"
#include "SaveState.h"
//=================================================================================================
void Blood::Save(File& f) const
{
f.Write<byte>(type);
f << pos;
f << normal;
f << size;
f << rot;
}
//=================================================================================================
void Blood::Load(File& f)
{
if(LOAD_VERSION >= V_0_3)
type = (BLOOD)f.Read<byte>();
else
type = (BLOOD)f.Read<int>();
f >> pos;
f >> normal;
f >> size;
f >> rot;
}
|
[
"tomash4my@gmail.com"
] |
tomash4my@gmail.com
|
985f447c11bc2a917c256822ffa5621cf7054c0f
|
905b2f9a603058acce7c0f498a3d077a16dad4c1
|
/src/sqlite/backup.cpp
|
a730581c1c485d3e592788540468d7bbd5a8e958
|
[
"BSD-3-Clause"
] |
permissive
|
vinzenz/vsqlite--
|
eae5585df125f81e05eea44a15a73cd108c33d89
|
ea77afd29f5112663353f63c725c3c8bf29c00e4
|
refs/heads/master
| 2021-01-22T03:05:39.314441
| 2020-11-11T10:09:46
| 2020-11-12T20:51:26
| 5,426,635
| 21
| 18
|
NOASSERTION
| 2020-11-12T20:51:27
| 2012-08-15T13:56:03
|
C++
|
UTF-8
|
C++
| false
| false
| 1,642
|
cpp
|
#include <sqlite/backup.hpp>
#include <sqlite/connection.hpp>
#include <sqlite/private/private_accessor.hpp>
#include <sqlite/database_exception.hpp>
#include <sqlite3.h>
namespace sqlite {
backup::backup(connection& conn_to, connection& conn_from)
: m_pBackup(NULL), m_conn_to(conn_to) {
private_accessor::acccess_check(conn_to);
private_accessor::acccess_check(conn_from);
m_pBackup = sqlite3_backup_init(get_to_handle(), "main",
private_accessor::get_handle(conn_from), "main");
if(!m_pBackup) {
throw database_exception_code(sqlite3_errmsg(get_to_handle()),
sqlite3_errcode(get_to_handle()));
}
}
backup::~backup() {
try {
finish();
} catch(...) {
}
}
bool backup::step(int nPage) {
if(!m_pBackup) {
throw database_exception("Backup object is already destroyed");
}
int err = sqlite3_backup_step(m_pBackup, nPage);
switch(err) {
case SQLITE_OK:
return true;
case SQLITE_DONE:
return false;
default:
throw database_exception_code(sqlite3_errmsg(get_to_handle()), err);
}
}
void backup::finish() {
if(!m_pBackup) {
return;
}
int err = sqlite3_backup_finish(m_pBackup);
if(err != SQLITE_OK) {
throw database_exception_code(sqlite3_errmsg(get_to_handle()), err);
}
m_pBackup = NULL;
}
sqlite3* backup::get_to_handle() const {
return private_accessor::get_handle(m_conn_to);
}
}
|
[
"yan12125@gmail.com"
] |
yan12125@gmail.com
|
ec31a517ee7116aff97a5790e3c77ca5103a2133
|
9d364070c646239b2efad7abbab58f4ad602ef7b
|
/platform/external/chromium_org/ui/events/linux/text_edit_key_bindings_delegate_auralinux.h
|
9344bcb6c50d2a4465ed0f7c9ddf54f34661065c
|
[
"BSD-3-Clause"
] |
permissive
|
denix123/a32_ul
|
4ffe304b13c1266b6c7409d790979eb8e3b0379c
|
b2fd25640704f37d5248da9cc147ed267d4771c2
|
refs/heads/master
| 2021-01-17T20:21:17.196296
| 2016-08-16T04:30:53
| 2016-08-16T04:30:53
| 65,786,970
| 0
| 2
| null | 2020-03-06T22:00:52
| 2016-08-16T04:15:54
| null |
UTF-8
|
C++
| false
| false
| 892
|
h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_
#define UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_
#include <vector>
#include "ui/events/events_export.h"
namespace ui {
class Event;
class TextEditCommandAuraLinux;
class EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux {
public:
virtual bool MatchEvent(const ui::Event& event,
std::vector<TextEditCommandAuraLinux>* commands) = 0;
protected:
virtual ~TextEditKeyBindingsDelegateAuraLinux() {}
};
EVENTS_EXPORT void SetTextEditKeyBindingsDelegate(
TextEditKeyBindingsDelegateAuraLinux* delegate);
EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux*
GetTextEditKeyBindingsDelegate();
}
#endif
|
[
"allegrant@mail.ru"
] |
allegrant@mail.ru
|
ce88bec82a0fc311bdd2b2a190c19e42da0e18be
|
0a64bfcfd943372df11eb47c7a037db606d06da0
|
/cs12/Assignment 4/intvector.cpp
|
c7f86889bf22c395b0edb517109edf2d0cb71f51
|
[] |
no_license
|
zacharysells/school
|
9e09c00e4a3e87cd798ca21813edc11ac4eeb4b7
|
e59270018cb3d4752c618d410d7f2af8f921aac8
|
refs/heads/master
| 2021-01-10T19:31:01.721574
| 2015-06-05T18:57:29
| 2015-06-05T18:57:29
| 27,702,632
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,366
|
cpp
|
// Course: CS 12 <Winter 2012r>
//
// First Name: Zachary
// Last Name: Sells
// Course username: zsell001
// email address: zsell001@ucr.edu
//
// Lecture Section: 001
// Lab Section: 025
// TA: Mirebrahim, Seyed Hamid
//
// Assignment: assn4
//
// I hereby certify that the code in this file
// is ENTIRELY my own original work.
//
// =================================================================
#include <iostream>
#include "intvector.h"
#include <cstdlib>
using namespace std;
//Constructors/Destructors
IntVector::IntVector()
:vsize(0),vcapacity(0),data(NULL)//Default constructor.
{}
IntVector::IntVector(unsigned s)
:vsize(s),vcapacity(s),data(NULL)
{
data = new int[s];
for(unsigned i = 0; i < vcapacity; i++)
{
data[i] = 0;//Set all elements to zero.
}
}
IntVector::IntVector(unsigned s, int value)
:vsize(s),vcapacity(s),data(NULL)
{
data = new int[s];
for(unsigned i = 0; i < vsize; i++)
{
data[i] = value;//Set elements according to 'value' parameter
}
}
IntVector::~IntVector()
{
delete[] data;//Deconstructor
}
void IntVector::expand()
{
int * temp = new int[vcapacity * 2];//Double vector's capacity
for(unsigned i = 0; i < vsize; i++)
{
temp[i] = data[i];
}
vcapacity = vcapacity * 2;
delete[] data;
data = temp;
}
void IntVector::expand(unsigned amount)//Expand vector's capacity by 'amount' parameter
{
int * temp = new int[vcapacity + amount];
for(unsigned i = 0; i < vsize; i++)
{
temp[i] = data[i];
}
vcapacity = vcapacity + amount;
delete[] data;
data = temp;
}
unsigned IntVector::size() const
{
return vsize;//Return size of vector.
}
unsigned IntVector::capacity() const
{
return vcapacity;//Return capacity of vector.
}
bool IntVector::empty() const
{
return (vsize == 0);//Check if vector's size is zero.
}
const int & IntVector::operator[](unsigned index)const
{
return data[index];
}
const int& IntVector::front() const
{
return data[0];// Return value of last element.
}
const int& IntVector::back() const
{
return *(data + (vsize - 1));//Return value of last element.
}
const int & IntVector::at(unsigned index) const
{
if(index > vsize)
exit(0);//Exit program if index is out of range of vector
return data[index];//Return by value as R-value.
}
int & IntVector::at(unsigned index)
{
if(index > vsize)
exit(0);// Exit program if index is out of range of vector
return data[index];//Return by reference as L-value.
}
void IntVector::insert(unsigned index, int data)
{
if(index > vsize)//Make sure index isnt bigger than size.
{
exit(1);
}
if(vcapacity == 0)
{
expand(1);
}
if(vsize == vcapacity)//Increase capacity if size is equal to capacity.
{
expand();
}
for(unsigned i = vsize; i > index ; i--)
{
this->data[i] = this->data[i-1];//Shift all values up one.
}
this->data[index] = data;//Input 'data' parameter into new element.
vsize++;//Increase size by one.
}
void IntVector::erase(unsigned index)
{
if(index > vsize)//Make sure index isnt bigger than size.
{
exit(0);
}
for(unsigned i = index; i < vsize; i++)
{
data[i] = data[i+1];//Move all elements down one position.
}
vsize--;//Decrease size by one.
}
void IntVector::push_back(int data)
{
if(vcapacity == 0)
{
expand(1);//If vector is empty, set capacity to 1.
}
else if (vsize == vcapacity)
{
expand();//Increase capacity if size is equal to capacity.
}
this->data[vsize] = data;//Input 'data' parameter into new element.
vsize++;//Increase size by one.
}
void IntVector::pop_back()
{
if(vsize == 0)
exit(0);//Exit program if size is zero
vsize--;//Decrease size by one.
}
void IntVector::clear()
{
vsize = 0;//Reduce size to zero.
}
void IntVector::resize(unsigned sz)
{
if(sz < vsize)
{
vsize = sz;//Just reduce size to 'sz' parameter
}
else
{
if(sz > vcapacity)
{
if(vcapacity * 2 > sz)//Increase capacity by the bigger of the two.
{
expand();
}
else
{
expand(sz - vcapacity);
}
}
vsize = sz;//Set new size.
}
}
void IntVector::resize(unsigned sz, int value)
{
if(sz < vsize)
{
vsize = sz;//Just change size to 'sz' parameter
}
else
{
if(sz > vcapacity)
{
if(vcapacity * 2 > sz)//Set capacity to greater of the two.
{
expand();
}
else
{
expand(sz - vcapacity);
}
}
for(unsigned i = vsize; i < vcapacity; i++)
{
data[i] = value;//Assign elements to 'value' parameter
}
vsize = sz;//Set new size.
}
}
void IntVector::reserve(unsigned n)
{
if(n < vcapacity)
return;
if(vcapacity * 2 > n)//Change capacity to greater of the two.
expand();
else
expand(n-vcapacity);
}
void IntVector::assign(unsigned n, int value)
{
if(n > vcapacity)
{
if(vcapacity * 2 > n)//Change capacity to greater of two.
expand();
else
expand(n-vcapacity);
vsize = n;
//Set all values in newly assigned size to 'value' paramater.
for(unsigned i = 0; i < vsize; i++)
{
data[i] = value;
}
}
else
{
vsize = n;//set new size and assign new values according to parameter 'value'
for(unsigned i = 0; i <vsize; i++)
{
data[i] = value;
}
}
}
int & IntVector::front()//L-value
{
return data[0];
}
int & IntVector::back()//L-value
{
return data[vsize - 1];
}
int & IntVector::operator[](unsigned index)//L-value
{
return data[index];
}
|
[
"zacharysells@gmail.com"
] |
zacharysells@gmail.com
|
0e0f8e4afdc60ca0fcb33231153dd5673ac477dd
|
f982e7cb8c3a80cc5f460a91dbf95b52ff71170f
|
/CommandString/appendcommand.h
|
9c7499f5b1ddccbc0c62311bcf1594d0cc7e3b7e
|
[] |
no_license
|
EliakinCosta/CommandPattern
|
096a2abcf63508e671c5865ae06476576e635da6
|
e5db8aa13137ccc77aa6ff6859a80d47f5b5ce11
|
refs/heads/master
| 2021-01-19T04:48:05.487617
| 2016-09-24T14:31:35
| 2016-09-24T14:31:35
| 69,101,710
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 355
|
h
|
#ifndef APPENDCOMMAND_H
#define APPENDCOMMAND_H
#include "icommand.h"
#include <QString>
class AppendCommand : public ICommand
{
public:
AppendCommand(QString *document, QString text);
virtual ~AppendCommand();
virtual void redo();
virtual void undo();
private:
QString *m_document;
QString m_text;
};
#endif // APPENDCOMMAND_H
|
[
"eliakim170@gmail.com"
] |
eliakim170@gmail.com
|
10705ac73a59b7068b0f460a7d8da3dfd7ea292c
|
9a74de3dfe4288323ddb0d5b57a74aedc3ca63da
|
/ch14/14-38.cpp
|
51d212fcf9e98a9033086e9bf65c643cb8c2d7fc
|
[] |
no_license
|
ss-haze/cpp_primer
|
afd56dc810278f728c7d462ada009d1f179c36fa
|
917b99845e80a36c4d82345864ceef3f8628fcac
|
refs/heads/main
| 2023-06-05T14:00:38.343255
| 2021-06-28T15:22:27
| 2021-06-28T15:22:27
| 321,345,987
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,033
|
cpp
|
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using std::cout;
using std::ifstream;
using std::string;
class string_limit
{
public:
string_limit(size_t upper, size_t lower)
: bound_upper_(upper),
bound_lower_(lower) {}
bool operator()(string &str_length) const
{
return str_length.size() <= bound_upper_ &&
str_length.size() >= bound_lower_;
}
private:
size_t bound_lower_;
size_t bound_upper_;
};
int main()
{
ifstream ifs("input.txt");
if (!ifs)
{
std::cerr << "Error. Could not open file";
return 1;
}
std::vector<string> vs;
for (string s; ifs >> s; vs.push_back(s))
;
size_t bound_upper, bound_lower;
std::cout << "Input upper bound: ";
std::cin >> bound_upper;
std::cout << "Input lower bound: ";
std::cin >> bound_lower;
auto count = std::count_if(vs.begin(), vs.end(), string_limit(bound_upper, bound_lower));
std::cout << "Total words within specified bounds: " << count;
return 0;
}
|
[
"ss-haze@users.no-reply.github.com"
] |
ss-haze@users.no-reply.github.com
|
80896c34c0bdc6e5c84950aece842f54c4a23e36
|
b01889a9d9c438bd5f7e1a56707027cf67644fdf
|
/include/hermes/VM/HermesValueTraits.h
|
8d0410037caded1d7bed888b243b3733856f7d7c
|
[
"MIT"
] |
permissive
|
Dhruvdd/hermes
|
f71eede552b02458a5717e1611c55ab09784c06b
|
dec2d951b8d20cf7fc30e324c3d2bafa0e6b12a8
|
refs/heads/master
| 2022-11-20T23:25:11.980557
| 2020-07-25T07:00:34
| 2020-07-25T07:00:34
| 282,389,948
| 0
| 0
|
MIT
| 2020-07-25T07:00:35
| 2020-07-25T06:59:41
| null |
UTF-8
|
C++
| false
| false
| 7,616
|
h
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_VM_HERMESVALUETRAITS_H
#define HERMES_VM_HERMESVALUETRAITS_H
#include "hermes/VM/CellKind.h"
#include "hermes/VM/HermesValue.h"
#include "hermes/VM/SymbolID.h"
#include <cassert>
#include <type_traits>
namespace hermes {
namespace vm {
/// White-list classes than can be managed by a HermesValue.
template <class T>
struct IsGCObject : public std::false_type {};
#define HERMES_VM_GCOBJECT(name) \
class name; \
template <> \
struct IsGCObject<name> : public std::true_type {}
// White-list objects that can be managed by HermesValue.
HERMES_VM_GCOBJECT(StringPrimitive);
HERMES_VM_GCOBJECT(JSObject);
HERMES_VM_GCOBJECT(Callable);
HERMES_VM_GCOBJECT(BoundFunction);
HERMES_VM_GCOBJECT(NativeFunction);
HERMES_VM_GCOBJECT(FinalizableNativeFunction);
HERMES_VM_GCOBJECT(NativeConstructor);
HERMES_VM_GCOBJECT(JSFunction);
HERMES_VM_GCOBJECT(JSGeneratorFunction);
HERMES_VM_GCOBJECT(GeneratorInnerFunction);
HERMES_VM_GCOBJECT(ArrayImpl);
HERMES_VM_GCOBJECT(Arguments);
HERMES_VM_GCOBJECT(Environment);
HERMES_VM_GCOBJECT(DictPropertyMap);
HERMES_VM_GCOBJECT(HiddenClass);
HERMES_VM_GCOBJECT(PropertyAccessor);
HERMES_VM_GCOBJECT(ArrayStorage);
HERMES_VM_GCOBJECT(JSArray);
HERMES_VM_GCOBJECT(PrimitiveBox);
HERMES_VM_GCOBJECT(JSArrayBuffer);
HERMES_VM_GCOBJECT(JSDataView);
HERMES_VM_GCOBJECT(JSTypedArrayBase);
HERMES_VM_GCOBJECT(JSString);
HERMES_VM_GCOBJECT(JSNumber);
HERMES_VM_GCOBJECT(JSBoolean);
HERMES_VM_GCOBJECT(JSSymbol);
HERMES_VM_GCOBJECT(JSRegExp);
HERMES_VM_GCOBJECT(JSDate);
HERMES_VM_GCOBJECT(JSError);
HERMES_VM_GCOBJECT(JSGenerator);
HERMES_VM_GCOBJECT(Domain);
HERMES_VM_GCOBJECT(RequireContext);
HERMES_VM_GCOBJECT(HashMapEntry);
HERMES_VM_GCOBJECT(OrderedHashMap);
HERMES_VM_GCOBJECT(JSWeakMapImplBase);
HERMES_VM_GCOBJECT(JSArrayIterator);
HERMES_VM_GCOBJECT(JSStringIterator);
HERMES_VM_GCOBJECT(JSProxy);
HERMES_VM_GCOBJECT(JSCallableProxy);
HERMES_VM_GCOBJECT(DecoratedObject);
HERMES_VM_GCOBJECT(HostObject);
#ifdef UNIT_TEST
HERMES_VM_GCOBJECT(TestCell);
#endif
// Typed arrays use templates and cannot use the macro above
template <typename T, CellKind C>
class JSTypedArray;
template <typename T, CellKind C>
struct IsGCObject<JSTypedArray<T, C>> : public std::true_type {};
template <CellKind C>
class JSMapImpl;
template <CellKind C>
struct IsGCObject<JSMapImpl<C>> : public std::true_type {};
template <CellKind C>
class JSMapIteratorImpl;
template <CellKind C>
struct IsGCObject<JSMapIteratorImpl<C>> : public std::true_type {};
template <CellKind C>
class JSWeakMapImpl;
template <CellKind C>
struct IsGCObject<JSWeakMapImpl<C>> : public std::true_type {};
template <typename T, bool Uniqued>
class DynamicStringPrimitive;
template <typename T, bool Uniqued>
struct IsGCObject<DynamicStringPrimitive<T, Uniqued>> : public std::true_type {
};
template <typename T>
class ExternalStringPrimitive;
template <typename T>
struct IsGCObject<ExternalStringPrimitive<T>> : public std::true_type {};
template <typename T>
class BufferedStringPrimitive;
template <typename T>
struct IsGCObject<BufferedStringPrimitive<T>> : public std::true_type {};
template <typename T, bool isGCObject = IsGCObject<T>::value>
struct HermesValueTraits;
class SegmentedArray;
template <>
struct IsGCObject<SegmentedArray> : public std::true_type {};
template <>
struct HermesValueTraits<HermesValue> {
/// The type to be returned by Handle<T>::get().
using value_type = HermesValue;
/// The type to be returned by Handle<T>::operator->().
using arrow_type = const HermesValue *;
/// Whether this type is a GCCell
static constexpr bool is_cell = false;
/// The default initialization value of this type.
static constexpr value_type defaultValue() {
return HermesValue::encodeUndefinedValue();
};
/// Encode a \c HermesValue into the type.
static value_type encode(HermesValue value) {
return value;
}
/// Decode a \c HermesValue from the type.
static HermesValue decode(value_type value) {
return value;
}
static const HermesValue *arrow(const HermesValue &value) {
return &value;
}
private:
// arrow() must be called with a reference to a non-temporary object, as it
// returns the address of its parameter. Forbid calls to arrow() with a
// temporary object through this unimplemented overload.
static void arrow(HermesValue &&value);
};
template <>
struct HermesValueTraits<SymbolID> {
/// The type to be returned by Handle<T>::get().
using value_type = SymbolID;
/// The type to be returned by Handle<T>::operator->().
using arrow_type = const SymbolID *;
/// Whether this type is a GCCell
static constexpr bool is_cell = false;
/// The default initialization value of this type.
static value_type defaultValue() {
return SymbolID{};
};
static HermesValue encode(SymbolID value) {
return HermesValue::encodeSymbolValue(value);
}
static value_type decode(HermesValue value) {
return value.getSymbol();
}
};
template <class T>
struct StringTraitsImpl {
using value_type = T *;
using arrow_type = value_type;
static constexpr bool is_cell = true;
static constexpr value_type defaultValue() {
return value_type{};
}
static HermesValue encode(T *value) {
return HermesValue::encodeStringValue(value);
}
static T *decode(HermesValue value) {
return (T *)value.getString();
}
static arrow_type arrow(const HermesValue &value) {
auto *res = decode(value);
assert(res && "dereferencing null handle");
return res;
}
static arrow_type arrow(value_type ptr) {
assert(ptr && "dereferencing null handle");
return ptr;
}
};
template <>
struct HermesValueTraits<StringPrimitive, true>
: public StringTraitsImpl<StringPrimitive> {};
template <>
struct HermesValueTraits<BufferedStringPrimitive<char>, true>
: public StringTraitsImpl<BufferedStringPrimitive<char>> {};
template <>
struct HermesValueTraits<BufferedStringPrimitive<char16_t>, true>
: public StringTraitsImpl<BufferedStringPrimitive<char16_t>> {};
template <class T>
struct HermesValueTraits<T, true> {
using value_type = T *;
using arrow_type = value_type;
static constexpr bool is_cell = true;
static constexpr value_type defaultValue() {
return value_type{};
}
static HermesValue encode(T *value) {
return HermesValue::encodeObjectValue(value);
}
static T *decode(HermesValue value) {
return static_cast<T *>(value.getObject());
}
static arrow_type arrow(const HermesValue &value) {
auto *res = decode(value);
assert(res && "dereferencing null handle");
return res;
}
static arrow_type arrow(value_type ptr) {
assert(ptr && "dereferencing null handle");
return ptr;
}
};
/// A helper class to deduce whether it is safe to assign Handle<From> into
/// Handle<To>.
template <class From, class To>
struct IsHermesValueConvertible {
using FromTraits = HermesValueTraits<From>;
using ToTraits = HermesValueTraits<To>;
static constexpr bool value =
// Anything is convertable to HermesValue.
std::is_same<To, HermesValue>::value ||
// A type is convertable to itself.
std::is_same<From, To>::value ||
// An object can be converted to its base class.
(FromTraits::is_cell && ToTraits::is_cell &&
std::is_base_of<To, From>::value);
};
} // namespace vm
} // namespace hermes
#endif // HERMES_VM_HERMESVALUETRAITS_H
|
[
"facebook-github-bot@users.noreply.github.com"
] |
facebook-github-bot@users.noreply.github.com
|
d91d8dbaf61a1aa426444237090d2d83edee2ec6
|
9c1c77f33cc17042c09dde624f9f56a24b2a9094
|
/Classes/PauseLayer.h
|
a7de73fa57c0ccbbfa160e01eb71d7b727f846a0
|
[] |
no_license
|
spocklin/spockTower
|
9601fda1aa0df3b23176adffb505f99e1ba4ef1c
|
da20117b3615fd22fab73a9a00c587557c95399b
|
refs/heads/master
| 2020-04-06T06:28:03.646344
| 2016-09-30T10:05:51
| 2016-09-30T10:05:51
| 69,004,890
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 730
|
h
|
//
// PauseLayer.h
// CarrotFantasy
//
// Created by Yan on 14-9-21.
//
//
#ifndef __CarrotFantasy__PauseLayer__
#define __CarrotFantasy__PauseLayer__
#include "PublicDefine.h"
class PauseLayer:public Layer
{
public:
CREATE_FUNC(PauseLayer);
virtual void setFuncFlagPauseLayerIsClose(const std::function<void ()> & rFuncFlagPauseLayerIsClose);
protected:
virtual bool init();
virtual void onEnter()override;
virtual void onExit()override;
virtual void createMenu();
virtual void createSharedMenu();
virtual void closeTouchEvent();
std::function<void ()> _funcFlagPauseLayerIsClose;
};
#endif /* defined(__CarrotFantasy__PauseLayer__) */
|
[
"mac@macdeMac-Pro-5.local"
] |
mac@macdeMac-Pro-5.local
|
8109ae58145d455808935722a19c545d390c51a0
|
bf5ce4d5c5996d8e9cfa340811140bd193c55d3d
|
/set_stl.h
|
364102a4e0542bae4170fd835afa3c7e46bb5e24
|
[] |
no_license
|
zhaofeng-shu33/set
|
6b24cb4b2f9d646eda5d781122220710251d16f7
|
100b6fefd8b22e4e681e328e29451b6e1ee8a742
|
refs/heads/master
| 2022-11-16T15:47:03.598954
| 2022-10-20T02:39:45
| 2022-10-20T02:39:45
| 194,417,898
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,127
|
h
|
# pragma once
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
namespace stl{
template <class T>
class Set {
public:
using element_type = T;
using value_type = element_type;
typedef typename std::set<element_type>::iterator iterator;
typedef typename std::set<element_type>::reverse_iterator reverse_iterator;
typedef typename std::set<element_type>::const_iterator const_iterator;
//! empty set
Set() {}
std::size_t Cardinality() const {
return s.size();
}
bool HasElement(element_type i) const {
return static_cast<bool>(s.count(i));
}
bool IsSubSet(const Set& X) const {
for (element_type i : s) {
if (!X.HasElement(i))
return false;
}
return true;
}
void AddElement(element_type i) {
s.insert(i);
}
void push_back(element_type i) {
s.insert(i);
}
iterator insert(iterator position, const element_type& val) {
return s.insert(position, val);
}
void clear() {
s.clear();
}
iterator begin() {
return s.begin();
}
reverse_iterator rbegin() {
return s.rbegin();
}
iterator end() {
return s.end();
}
const_iterator begin() const {
return s.begin();
}
const_iterator end() const {
return s.end();
}
bool IsEmpty() { return s.size() == 0; }
friend std::ostream& operator << (std::ostream& stream, const Set& X) {
stream << "{";
std::size_t cnt = 0, limiter = X.Cardinality();
for (Set::iterator i = X.begin(); i != X.end(); i++) {
stream << *i;
cnt++;
if (cnt != limiter) {
stream << ", ";
}
}
stream << "}";
return stream;
}
friend bool operator==(const Set& a, const Set& b) {
return a.s == b.s;
}
friend bool operator!=(const Set& a, const Set& b) {
return a.s != b.s;
}
Set Union(const Set& X) const {
Set a;
std::set_union(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
Set Intersection(const Set& X) const {
Set a;
std::set_intersection(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
private:
std::set<element_type> s;
};
//! a thin wrapper around std::set
class CSet : public Set<std::size_t> {
public:
CSet(){}
CSet(const std::string& str);
//! construct a CSet from bitmask of val, for example if val = 14(0b1110), the set is {1,1,1,0}
//! n is the maximal size of the set
CSet(std::size_t n, unsigned long val);
//! generate a set $\{0, 1, \dots, n-1\}$
static CSet MakeDense(element_type n);
//! generate an empty set, the parameter is not used, reserved for compatibility consideration
static CSet MakeEmpty(element_type n);
// return self
CSet GetMembers() const;
CSet Complement(std::size_t n) const;
CSet Union(const CSet& X) const {
CSet a;
std::set_union(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
CSet Intersection(const CSet& X) const {
CSet a;
std::set_intersection(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
CSet Difference(const CSet& X) const {
CSet a;
std::set_difference(begin(), end(), X.begin(), X.end(), std::inserter(a, a.begin()));
return a;
}
friend bool operator<(const CSet& X, const CSet& Y) {
//alphabetical order
iterator it_x = X.begin(), it_y = Y.begin();
while (it_x != X.end() && it_y != Y.end()) {
if (*it_x > *it_y)
return false;
else if (*it_x < *it_y)
return true;
it_x++;
it_y++;
}
return false;
}
};
class Partition : public stl::Set<stl::CSet> {
public:
static Partition makeFine(int size);
static Partition makeDense(int size);
Partition() {}
Partition expand(const stl::CSet& A);
};
}
|
[
"616545598@qq.com"
] |
616545598@qq.com
|
255d8edcaf92e958df0c53dddf0f75d253f44e37
|
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
|
/Sinelnikov/lab4/code/Interaction.cpp
|
11f3d742ad20df9781a2a2a302e7a9d84dc0ad42
|
[] |
no_license
|
moevm/oop
|
64a89677879341a3e8e91ba6d719ab598dcabb49
|
faffa7e14003b13c658ccf8853d6189b51ee30e6
|
refs/heads/master
| 2023-03-16T15:48:35.226647
| 2020-06-08T16:16:31
| 2020-06-08T16:16:31
| 85,785,460
| 42
| 304
| null | 2023-03-06T23:46:08
| 2017-03-22T04:37:01
|
C++
|
UTF-8
|
C++
| false
| false
| 8,951
|
cpp
|
//
// Created by max on 31.03.20.
//
#include "Interaction.h"
void Interaction::setBase(Field *f) {
int x,y;
while (1){
cout << "Введите координаты базы 1" << "\n";
cin >> x >> y;
if(x < f->getXsize() && y < f->getYsize() && x >= 0 && y>= 0 && !f->field[x][y].getIfOccupiedByBuilding()){
if(f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "water" \
&& f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "mountain") {
f->createBase(x, y);
f->getLog()->write("База установлена\n");
break;
} else{
f->getLog()->write("В данных природных условиях базу не поставить!!!\n");
}
} else
if(x < f->getXsize() && y < f->getYsize()) {
f->getLog()->write("На это место базу поставить нельзя! Поле занято ");
f->getLog()->write(f->getNeutralObjectName(f->field[x][y].getNeutralObject()->getObjectId()));
f->getLog()->write("\n");
}
else
f->getLog()->write("Выход за пределы поля!!!\n");
}
while (1){
cout << "Введите координаты базы 2" << "\n";
cin >> x >> y;
if(x < f->getXsize() && y < f->getYsize() && x >= 0 && y>= 0 && !f->field[x][y].getIfOccupiedByBuilding()){
if(f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "water" \
&& f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "mountain") {
f->createBase(x, y);
f->getLog()->write("База установлена\n");
break;
} else{
f->getLog()->write("В данных природных условиях базу не поставить!!!\n");
}
} else {
f->getLog()->write("На это место базу поставить нельзя! Поле занято ");
f->getLog()->write(f->getNeutralObjectName(f->field[x][y].getNeutralObject()->getObjectId()));
f->getLog()->write("\n");
}
}
}
void Interaction::services(Field* f,Unit *unit, NeutralObject *object, bool &check) {
object->operator+(unit);
f->getLog()->write("услуга оказана\n");
check = true;
}
void Interaction::repair(Field* f, Base* base, bool &check) {
base->increaseXp(2);
f->getLog()->write("Прочность базы улучшена\n");
check = true;
}
void Interaction::killUnit(Field* f, Unit *unit, int x, int y) {
f->field[f->getBaseXCoordinateById(f->field[x][y].getUnit()->getId())][f->getBaseYCoordinateById(f->field[x][y].getUnit()->getId())].getBase()->decreaseNumberOfUnits(1);
f->deleteUnit(x,y);
f->deleteUnitFromArray(unit->getNumberInArray());
}
void Interaction::battleWithUnit(Field* f,bool &check,Unit* unit1,Unit* unit2,int x1,int y1,int x2,int y2){
check = true;
if(unit1->getAttack() + unit1->getMoral() + unit1->getArmour() > unit2->getArmour() + unit2->getAttack() + unit2->getMoral()){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x2][y2].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x2][y2].getUnit(),x2,y2);
f->move(x1,y1,x2,y2,check);
f->field[x1][y1].getUnit()->decreaseXp(f->field[x1][y1].getUnit()->getXp() / 2);
f->field[x1][y1].getUnit()->increaseMoral(2);
} else if(unit2->getAttack() + unit2->getMoral() + unit2->getArmour() > unit1->getArmour() + unit1->getAttack() + unit1->getMoral()){
this->killUnit(f,f->field[x1][y1].getUnit(),x1,y1);
f->field[x2][y2].getUnit()->decreaseXp(f->field[x2][y2].getUnit()->getXp() / 2);
f->field[x2][y2].getUnit()->increaseMoral(2);
} else{
f->field[x2][y2].getUnit()->decreaseXp(f->field[x2][y2].getUnit()->getXp() / 2 + 1);
f->field[x1][y1].getUnit()->decreaseXp(f->field[x1][y1].getUnit()->getXp() / 2 + 1);
if(f->field[x1][y1].getUnit()->getXp() <= 0){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x1][y1].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x1][y1].getUnit(),x1,y1);
}
if(f->field[x2][y2].getUnit()->getXp() <= 0){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x2][y2].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x2][y2].getUnit(),x2,y2);
}
}
}
void Interaction::attackBase(Field* f, bool &check,int x1,int y1,int x2,int y2) {
if(f->field[x1][y1].getUnit()->getAttack() / 2 + f->field[x1][y1].getUnit()->getMoral() / 5 >= f->field[x2][y2].getBase()->getBaseXp()){
f->destroyBase(f->field[x2][y2].getBase()->getObjectId());
} else{
f->field[x2][y2].getBase()->decreaseXp(f->field[x1][y1].getUnit()->getAttack() / 2 + f->field[x1][y1].getUnit()->getMoral() / 5);
}
check = true;
}
void Interaction::attack(Field* f,Unit* curr_unit,bool &check,int x,int y) {
bool check1,check2;
bool check_on_fit_to_field;
int player_move;
Unit* enemy_unit;
int x_new,y_new;
while (1) {
check_on_fit_to_field = false;
check1 = false;
check = false;
cout << "0 - вернуться на шаг назад\n";
cout << "1 - аттаковать направо\n";
cout << "2 - аттаковать налево\n";
cout << "3 - аттаковать наверх\n";
cout << "4 - аттаковать вниз\n";
int ch;
cin >> ch;
if(!ch)
break;
switch (ch) {
case 3:
x_new = x + 1;
y_new = y;
if(y_new >= f->getYsize()){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 4:
x_new = x - 1;
y_new = y;
if(y_new < 0){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 2:
x_new = x;
y_new = y - 1;
if(x_new < 0){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 1:
x_new = x;
y_new = y + 1;
if(x_new >= f->getXsize()){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
default:
break;
}
if(!check_on_fit_to_field)
continue;
while (1) {
cout << "0 - вернуться на шаг назад\n";
if (f->field[x_new][y_new].getIfOccupiedByUnit() &&
f->field[x_new][y_new].getUnit()->getId() != curr_unit->getId()) {
cout << "1 - Атаковать вражеского юнита\n";
check1 = true;
}
if (f->field[x_new][y_new].getBase() != nullptr && f->field[x_new][y_new].getBase()->getObjectId() != f->field[x][y].getUnit()->getId()) {
cout << "2 - Атаковать базу\n";
check2 = true;
}
if(!check1 && !check2){
f->getLog()->write("На этом поле нет объектов/юнитов для атаки\n");
break;
}
cin >> player_move;
if(!player_move)
break;
switch (player_move){
case 1:
enemy_unit = f->field[x_new][y_new].getUnit();
if(check1)
this->battleWithUnit(f,check,curr_unit,enemy_unit,x,y,x_new,y_new);
break;
case 2:
if(check2)
this->attackBase(f,check,x,y,x_new,y_new);
break;
default:
break;
}
if(check)
break;
}
if(check)
break;
}
}
|
[
"sinelnikovmaxim2000@mail.ru"
] |
sinelnikovmaxim2000@mail.ru
|
4aca813edf1373beaabaa3b9dd6781ff41384a76
|
513f3261ff64159df147cc2c03d13268bcfdda1c
|
/samples/opening_window/main.cpp
|
e3f3f5bb058e185383bc699873042aba4e1df6bc
|
[
"MIT"
] |
permissive
|
sutirthaghosh/gentlemanly_engine
|
b29b858e498b6638b59618d3ce2e16505b033d1e
|
b9481628fdcf0f92d367f9d3afddd501462667fc
|
refs/heads/master
| 2020-12-25T05:35:57.908639
| 2016-05-31T07:50:43
| 2016-05-31T07:50:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,400
|
cpp
|
#include <ge/model_system.hpp>
#include <ge/qt_application.hpp>
#include <ge/asset_manager.hpp>
#include <ge/camera_component.hpp>
#include <ge/material_asset.hpp>
#include <ge/mesh_asset.hpp>
#include <ge/transform_component.hpp>
#include <ge/world.hpp>
#include <iostream>
#include <memory>
using namespace ge;
int main(int argc, char** argv)
{
try
{
qt_application app(argc, argv);
auto window = app.make_window(
"gentlemanly_engine_example_opening_window", {}, {1280, 720}, false, true);
auto viewport = app.make_viewport(*window);
ge::world world;
asset_manager asset_man;
asset_man.add_asset_path("data/");
entityx::Entity camera;
app.signal_init.connect([&] {
viewport->set_background_color({1.f, 0.f, 0.f, 1.f});
auto meshasset = asset_man.get_asset<mesh_asset>("square");
auto wallMesh = asset_man.get_asset<mesh_asset>("ground");
// wall
auto wall = world.entities.create();
wall.assign<model_component>(wallMesh.data);
wall.assign<transform_component>(transform{{4.f, 0.f}, 3.f});
// init camera
camera = world.entities.create();
auto trans = camera.assign<transform_component>(transform{{-0.f, 0.f}, 0.f});
camera.assign<camera_component>(20.f);
});
app.signal_update.connect([&](float dt) { world.update(dt); });
app.execute(*window);
}
catch (std::exception& e)
{
std::cout << e.what();
return 232;
}
}
|
[
"russellgreene8@gmail.com"
] |
russellgreene8@gmail.com
|
214593e855146e0eb5ea38c4a6ecc7eb519bebd1
|
c7ef4e11ac87d3a65cceb5a631f7bd3aa27fc73c
|
/4.14/main.cpp
|
7848f430bae1b5408e3a44cdad0b1b5ec7594774
|
[] |
no_license
|
Gracesr/song_rui
|
544c6be7898af42cf5937cf1491306ee82ebe7c0
|
01e94b7ac87bc966615638e026c37e894c5d88cb
|
refs/heads/master
| 2020-04-02T09:39:15.297807
| 2019-04-21T09:31:45
| 2019-04-21T09:31:45
| 154,302,833
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 769
|
cpp
|
#include <iostream>
using namespace std;
int main{}
{
int account_number;
double a=0,b=0,c=0,d=0,e=0 ;
while{account_number!=-1}
{
cout<<"Enter account number{or -1 to quit}";
cin>>account;
if{account_number==-1}break;
cout<<"Enter beginning balance";
cin>>a;
cout<<"Enter total charges";
cin>>b;
cout<<"Enter total_credits";
cin>>c;
cout<<"Enter credit_limit";
cin>>d;
e=a+b-c;
if{e<=d}
{
cout<<"New balance is "<<e<<endl;
}
eles
{cout<<"New balance is"<<e<<endl;
cout<<"Account"<<account<<endl;
cout<<"Credit Limit"<<d<<endl;
cout<<"Balance"<<e<<endl;
cout << "Credit Limit Exceeded."<<endl;
}
return 0;
}
|
[
"1977502458@qq.com"
] |
1977502458@qq.com
|
58da462fba2dafb8ab1ff3dc35cb3b4ed108d67d
|
0d334a3e32652d9a624ca1eb4a1dfa77d6c8edc3
|
/webDic/webDic/crawler.cpp
|
e6493cbf33ffb34e56634b7fb616feb199378b97
|
[] |
no_license
|
unbiarirang/web_dic
|
b0c52fd998b8c85516b800865addef8f123cd490
|
ac3b11ffb328a49025f1c71c5ed705b63085ef06
|
refs/heads/master
| 2021-03-27T17:22:17.447901
| 2018-03-30T16:04:05
| 2018-03-30T16:04:05
| 114,513,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,813
|
cpp
|
#include "crawler.h"
#include "charString.h"
#include "stack.h"
#include "curl\curl.h"
#include "avlTree.h"
#include "map.h"
#include "hash.h"
#include <pthread.h>
#include <thread>
#include <memory>
#include <vector>
#include <string>
#include <mutex>
AVLTree tree; // AVL tree inverse document
HashDoc hashDoc;// hash table inverse document
Map map; // word-wordID map
std::mutex m;
int g_key_index = 1; // word unique id index
// main algorithm
void analyze_html(int tid, std::vector<CharString>* urlStrs, std::ofstream &opStream, HashTable *dic, HashTable *dic_ex) {
std::vector<CharString>* words = new std::vector<CharString>; // split words result
std::vector<CharString> resultStr(4);
std::wstring wideData = L"";
for (int i = (URL_NUM / MAX_THREAD_NUM) * tid; i < (URL_NUM / MAX_THREAD_NUM) * (tid + 1); i++) {
DocID docID = i + 1;
resultStr.assign(4, "");
CharString urlStr = (*urlStrs)[i];
CharString dataStr = get_html_str(tid, urlStr);
bool exceptional_flag = false; // exceptional situation. in case of ansi string main contents
int index = 0;
resultStr[0] = urlStr;
// extract data trash1, trash2
index = extract_data_from_html(dataStr, "div class=\"z\"", 'a', index, &resultStr, &exceptional_flag, 3);
// no authority to visit this html page
if (index == -1) {
resultStr[0].concat("\n");
std::cout << resultStr[0];
opStream << ansi_to_utf8(&resultStr[0]);
resultStr.clear();
continue;
}
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 1~3 (article big category, article small category, title)
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 1);
// extract data 7 (article type)
index = extract_data_from_html(dataStr, "div class=\"ts z h1\"", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 5 (writer)
index = extract_data_from_html(dataStr, "div class=\"authi\"", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 6 (date)
index = extract_data_from_html(dataStr, "div class=\"authi\"", 'e', index, &resultStr, &exceptional_flag, 3);
//extract data 4 (main contents)
index = extract_data_from_html(dataStr, "div class=\"t_fsz\"", 'p', index, &resultStr, &exceptional_flag, 2);
if (exceptional_flag == true)
index = extract_data_from_html2(dataStr, "div class=\"t_fsz\"", 't', index, &resultStr);
filter_result_str(&resultStr, &wideData);
for (int k = 0; k < 3; k++) {
// handle main contents
if (k == 2) {
bool decimal_flag = false;
int j = 0;
// in case of decimal code main contents
while (true) {
if (j >= resultStr[k].getLen()) break;
if (resultStr[k].getStr()[j] == '&') {
decimal_flag = true; break;
}
if (resultStr[k].getStr()[j] < '0' || resultStr[k].getStr()[j] > '9') {
decimal_flag = false; break;
}
j++;
}
if (decimal_flag == true) {
CharString str = ansi_encode(wideData);
str.concat(",");
opStream << ansi_to_utf8(&str);
std::cout << str;
split_words(dic, dic_ex, words, &str, docID);
continue;
}
else {};
}
// print result string
resultStr[k].concat(",");
opStream << ansi_to_utf8(&resultStr[k]);
std::cout << resultStr[k];
// split words only from title and main contents
if (k == 1 || k == 2)
split_words(dic, dic_ex, words, &resultStr[k], docID);
}
// print split words result
for (auto word : *words) {
word.concat(" ");
std::cout << word;
opStream << ansi_to_utf8(&word);
}
std::cout << "\n";
opStream << std::endl;
words->clear();
resultStr.clear();
}
std::cout << "tid: " << tid << " ended" << std::endl;
}
// get url strings from input file
void get_url_str(std::vector<CharString>* urlStrs, CharString fileName)
{
char buffer[MAX_URL_LENGTH] = { 0 };
std::ifstream readFile(fileName.getStr());
try {
if (readFile.is_open() == true) {
std::cout << "read file: " << fileName << "\n";
// delete the first line of the file
readFile.getline(buffer, sizeof(char) * MAX_URL_LENGTH);
while (readFile.getline(buffer, sizeof(char) * MAX_URL_LENGTH)) {
CharString tempStr = buffer;
char* temp = tempStr.substring(tempStr.indexOf("\"") + 1, tempStr.getLen() - 2);
urlStrs->push_back(temp);
}
std::cout << "close file: " << fileName << "\n";
readFile.close();
}
}
catch (bool) {
std::cout << "fail to read file: " << fileName << "\n";
}
}
void get_search_str(std::vector<CharString>* searchStrs, CharString fileName)
{
std::vector<CharString> search_strs;
char buffer[1024] = { 0 };
std::ifstream readFile(fileName.getStr());
try {
if (readFile.is_open() == true) {
std::cout << "success read file " << fileName << std::endl;
while (readFile.getline(buffer, sizeof(char) * 1024))
searchStrs->push_back(buffer);
readFile.close();
}
}
catch (bool) {
std::cout << "fail to read file" << std::endl;
}
}
// curl write callback
std::string g_dataStr[MAX_THREAD_NUM];
size_t _write_callback(char* buf, size_t size, size_t nmemb, void* tid)
{
for (int c = 0; c<size*nmemb; c++)
g_dataStr[int(tid)].push_back(buf[c]);
return size*nmemb;
}
CharString get_html_str(int tid, CharString urlStr)
{
CURLcode res;
g_dataStr[tid] = std::string();
CURL* curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, urlStr.getStr());
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &_write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)tid);
/* Perform the request, res will get the return code */
m.lock();
res = curl_easy_perform(curl);
m.unlock();
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return CharString(g_dataStr[tid]);
}
// return the end index of match string
int extract_data_from_html(CharString dataStr, CharString matchStr, char tag, int index_prev, std::vector<CharString>* resultStr, bool* exceptional_flag, int res_index)
{
int temp_index_prev = index_prev;
int index = get_index_of_match_str(dataStr, matchStr, index_prev);
if (index == -1) return -1;
bool get_tag_flag = false;
char c_before = 0;
Stack s = Stack();
Stack s2 = Stack();
char data[1024] = { 0 };
int data_index = 0;
while (true) {
char c = dataStr.getStr()[index];
if (c_before == '<' && c == tag) get_tag_flag = true;
if (get_tag_flag)
s.push(c);
// get data between <tag>...</tag>
if (c_before == '/' && c == tag) {
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
bool get_content_flag = false;
char c;
while (!s2.empty()) {
c = s2.top();
if (c == '<' && get_content_flag == true) break;
if (get_content_flag) {
data[data_index] = s2.top();
data_index++;
}
if (c == '>') get_content_flag = true;
s2.pop();
}
// exceptional situation. for ansi string main contents
if (data[0] == '\n') {
*exceptional_flag = true;
return temp_index_prev;
}
(*resultStr)[res_index] = data;
return index;
}
c_before = c;
index++;
}
}
// exceptional situation. for ansi string main contents
int extract_data_from_html2(CharString dataStr, CharString matchStr, char tag, int index_prev, std::vector<CharString>* resultStr)
{
int temp_index_prev = index_prev;
int index = get_index_of_match_str(dataStr, matchStr, index_prev);
if (index == -1) return -1;
bool get_tag_flag = false;
char c_before = 0;
Stack s = Stack();
Stack s2 = Stack();
char data[1024] = { 0 };
int data_index = 0;
int count = 0;
while (true) {
char c = dataStr.getStr()[index];
if (count == 4) get_tag_flag = true;
if (c == '>') count++;
// replace " " with " "
if (c == '&') { index += 6; s.push(' '); continue; }
if (get_tag_flag && c != '\n' && c != ' ')
s.push(c);
// get data between <tag>...</tag>
if (get_tag_flag && c == '<') {
s.pop();
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
while (!s2.empty()) {
if (s2.top() != ',' && s2.top() != '\n') {
data[data_index] = s2.top();
data_index++;
}
s2.pop();
}
(*resultStr)[2] = data;
return index;
}
c_before = c;
index++;
}
}
const int MAX_EXTRACT_STRING_LENGTH = 1024;
char extractStr[MAX_EXTRACT_STRING_LENGTH];
int get_index_of_match_str(CharString dataStr, CharString matchStr, int prev_index)
{
Stack s = Stack();
Stack s2 = Stack();
char c = 0;
int index = prev_index;
bool push_flag = false;
while (index < dataStr.getLen()) {
c = dataStr.getStr()[index];
// get data between the bracket <...>
if (c == '>' && push_flag == true) {
push_flag = false;
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
int i = 0;
while (!s2.empty()) {
extractStr[i] = s2.top();
s2.pop();
i++;
}
extractStr[i] = '\0';
CharString tempStr = extractStr;
if (tempStr.indexOf(&matchStr) >= 0)
return index - tempStr.getLen() - 1;
for (int j = 0; j <= i; j++) {
extractStr[j] = 0;
}
}
if (push_flag)
s.push(c);
if (c == '<') push_flag = true;
index++;
}
return -1;
}
// use dic to split the source string
const int WORD_MAX_LEN = 8;
void split_words(HashTable* dic, HashTable* dic_ex, std::vector<CharString>* resultStr, CharString* srcStr, DocID docID)
{
CharString str = "";
int str_len = WORD_MAX_LEN;
int str_start_index = 0;
int str_end_index = WORD_MAX_LEN;
int index = 0;
while (true) {
str_len = WORD_MAX_LEN;
while (true) {
str_end_index = str_start_index + str_len;
if (str_end_index > srcStr->getLen()) str_end_index = srcStr->getLen();
index = str_start_index;
while (true) {
if (index == str_end_index) break;
str.concat(srcStr->getStr()[index]);
index++;
}
// get a series of number
if (str.getStr()[0] >= 48 && str.getStr()[0] <= 57) {
int num_count = 0;
int num_index = str_start_index;
while (true) {
if (srcStr->getStr()[num_index] < 48 || srcStr->getStr()[num_index] > 57) break;
num_count++;
num_index++;
}
int i = 8;
while (i < num_count) {
str.concat(&(srcStr->getStr()[str_start_index + i]));
i++;
}
str.getStr()[num_count] = '\0';
resultStr->push_back(str.substring(0, num_count-1));
str_start_index = str_start_index + num_count;
str = "";
break;
}
// remove all ascii characters except numbers
if ((str.getStr()[0] >= 32 && str.getStr()[0] < 48) || (str.getStr()[0] > 57 && str.getStr()[0] <= 148)) {
str_start_index = str_start_index + 1;
str = "";
break;
}
// filter exclusion words
if (dic_ex->isExist(str.getStr())) {
str_start_index = str_start_index + str_len;
str = "";
break;
}
// str remains a character
if (str_len == 2) {
resultStr->push_back(str); // save word
str_start_index = str_start_index + str_len;
str = "";
break;
}
// str is a word
if (dic->isExist(str)) {
resultStr->push_back(CharString(str)); // save word
// add a word to inverse document and map
if (docID) {
m.lock();
bool is_success = map.insert(str, g_key_index);
if (is_success) { // new word
WordNode* node = new WordNode(g_key_index, str);
node->add(docID);
tree.insert(g_key_index, node);
hashDoc.insert(g_key_index, node);
g_key_index++;
}
else { // the word already exist in inverse document and map
int wordID = map[str];
//WordNode* node = tree.search(wordID);
WordNode* node = hashDoc.search(wordID);
node->add(docID);
}
m.unlock();
}
str_start_index = str_start_index + str_len;
str = "";
break;
}
str_len--;
str = "";
}
if (str_start_index >= srcStr->getLen()) break;
}
}
void filter_result_str(std::vector<CharString>* resultStr, std::wstring* wideData)
{
bool is_decimal = false;
int j = 0;
// check if the main contents is decimal code
while (true) {
if ((*resultStr)[2].getStr()[j] == '&') {
is_decimal = true; break;
}
if ((*resultStr)[2].getStr()[j] < '0' || (*resultStr)[2].getStr()[j] > '9') {
is_decimal = false; break;
}
j++;
}
// convert decimal code to wide string
if (is_decimal == true) {
CharString contentStr = (*resultStr)[2];
std::wstring str = L"";
Stack s;
Stack s2;
bool end_flag = false;
bool push_flag = false;
bool non_decimal_flag = false;
long long code = 0;
for (int i = 0; i < contentStr.getLen(); i++) {
char c = contentStr.getStr()[i];
if (c == ' ' || c == ',') continue;
if (i == 0 && c != '&') end_flag = true;
if (c == ';') {
end_flag = true;
if (!s.empty()) {
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
while (!s2.empty()) {
code = code * 10 + s2.top() - 48;
s2.pop();
}
}
if (code) {
wchar_t temp = wchar_t(code);
str += temp;
}
else //
str += L" ";
code = 0;
push_flag = false;
non_decimal_flag = false;
continue;
}
// non decimal code
if (end_flag == true && c != '&') {
non_decimal_flag = true;
if (c >= '0' && c <= '9')
str += std::to_wstring(c - 48);
else if (c == '\0') {}
else
str += c;
continue;
}
else
end_flag = false;
if (push_flag == true)
s.push(c);
if (c == '#')
push_flag = true;
}
*wideData = str;
}
}
|
[
"unbiarirang@naver.com"
] |
unbiarirang@naver.com
|
6def73b8fc99a62deda8813e14d956b4556242f1
|
6881ae27fcdae1443da1f24eb73c7da452ecf5d8
|
/reverse_linkelist.cpp
|
bf207b78a5f20143ca6d66b0acc822e95d3468e0
|
[
"MIT"
] |
permissive
|
navitiwari/OpenDS
|
25b4fd85309a71eaa3d4a913ab2fdbc3dbd6a4a4
|
6666fccd580bc7a91cb3f4cd2a0a641fcdaf1f98
|
refs/heads/master
| 2020-04-01T01:14:23.694396
| 2018-10-12T10:08:28
| 2018-10-12T10:08:28
| 152,731,089
| 0
| 0
|
MIT
| 2018-10-12T10:08:29
| 2018-10-12T09:59:37
|
C++
|
UTF-8
|
C++
| false
| false
| 677
|
cpp
|
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void createNode(node **head,int data)
{
node *temp=new node;
temp->data=data;
temp->next=*head;
*head=temp;
}
node *reverse(node *head)
{
node *current,*next,*prev;
prev=NULL;
current=head;
while(current!=NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
head=prev;
}
void display(node *head)
{
while(head!=NULL)
{
cout<<head->data<<" "<<endl;
head=head->next;
}
}
int main(int argc,char *argv[])
{
int i;
node *head=NULL;
node *tail=NULL;
for(i=0;i<argc-1;i++)
{
int k=(atoi)(argv[i+1]);
createNode(&head,k);
}
display(head);
}
|
[
"neeleshvashist@gmail.com"
] |
neeleshvashist@gmail.com
|
e0a1f7925887d9f46be67b213d150e5ebf6347f1
|
46f118ad5fe5a4e47ce90b4350cf0d070271e16a
|
/src/clubman.h
|
f6facd61b635f2683756601d0f35ae2fad86a45f
|
[
"MIT"
] |
permissive
|
lodyman93/taucoin
|
e8ddd76ddfed6ab0dc4482c625dcd1f82377703f
|
dbf0d2ca6a4c1a9c0a1d02538fdebb8b47a2aaa3
|
refs/heads/master
| 2020-03-29T11:02:33.111960
| 2018-09-20T07:50:55
| 2018-09-20T07:50:55
| 149,828,884
| 0
| 0
|
MIT
| 2018-09-21T23:31:20
| 2018-09-21T23:31:20
| null |
UTF-8
|
C++
| false
| false
| 914
|
h
|
// Copyright (c) 2018- The taucoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TAUCOIN_CLUB_MANAGER_H
#define TAUCOIN_CLUB_MANAGER_H
#include "amount.h"
#include "base58.h"
#include "consensus/params.h"
#include "main.h"
#include "script/script.h"
class ClubManager
{
public:
static const int DEFAULT_HARVEST_POWER = 0;
static ClubManager* GetInstance();
uint64_t GetHarvestPowerByAddress(std::string& addr, int nHeight);
bool IsAllowForge(const std::string& pubKey, int nHeight, uint64_t &harvestPower);
bool IsForgeScript(const CScript& script, CBitcoinAddress& addr, uint64_t& memCount, int nHeight = -1);
protected:
ClubManager();
private:
static ClubManager* pSingleton;
};
#endif // TAUCOIN_REWARD_MANAGER_H
|
[
"shengxianshui@iMorpheus.io"
] |
shengxianshui@iMorpheus.io
|
748793d127167a76a294c657294cd66921da7305
|
5896ed2b1fad13132057a76d17c95991c430c476
|
/26 infinite continue fraction.cpp
|
95556b08fb94a3906d25fc8a6b04ae7d122216d7
|
[
"MIT"
] |
permissive
|
adelacvg/PE
|
c1e51c11927299f5f86d55a12beb35eb38bca860
|
0345335a3f959342625be03ae36a21bbad45f273
|
refs/heads/master
| 2021-08-26T00:18:19.423054
| 2021-08-12T10:40:17
| 2021-08-12T10:40:17
| 156,980,203
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 605
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
string f(int num, int den)
{
string res;
map<int,int> m;
m.clear();
int rem = num%den;
while(rem&&m.find(rem) == m.end())
{
m[rem] = res.length();
rem *= 10;
res += to_string(rem / den);
rem %= den;
}
return (rem==0)?"":res.substr(m[rem]);
}
int main()
{
string ss;
int ans,mx=0;
for(int i=1;i<=1000;i++)
{
ss=f(1,i);
if(ss.length()>mx)
{
ans=i;
int len = ss.length();
mx=max(len,mx);
}
}
cout<<ans;
}
|
[
"adelacvgaoiro@163.com"
] |
adelacvgaoiro@163.com
|
1c2f6d448b991a8a0cf92bbae82dc6d2b749c2b9
|
1224e8ce78eb40f8b92a8647f6e18625fb5caee7
|
/http_message.cpp
|
1a5cb284dcf952fdb43067f61facd057d504fa3e
|
[] |
no_license
|
msg555/gnyproxy
|
94e080e308af033fd0565389d03d54cd5b5b01ed
|
50da686bd3aa3d4d84ce5dbc7fced18c7de1ead6
|
refs/heads/master
| 2021-01-15T13:44:57.728853
| 2012-01-26T02:44:21
| 2012-01-26T02:44:21
| 3,270,785
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 895
|
cpp
|
#include "http_message.h"
#include <iostream>
using namespace std;
http_message::~http_message() {
}
void http_message::add_header(const string& key, const string& value) {
assert(state == HTTP_MESSAGE_HEADER);
headers.push_back(make_pair(key, value));
}
void http_message::append_entity(const string& entity_) {
assert(state == HTTP_MESSAGE_ENTITY);
entity.append(entity_);
}
void http_message::add_footer(const string& key, const string& value) {
assert(state == HTTP_MESSAGE_FOOTER);
footers.push_back(make_pair(key, value));
}
void http_message::end_header() {
assert(state <= HTTP_MESSAGE_HEADER);
state = HTTP_MESSAGE_ENTITY;
}
void http_message::end_entity() {
assert(state <= HTTP_MESSAGE_ENTITY);
state = HTTP_MESSAGE_FOOTER;
}
void http_message::end_footer() {
assert(state <= HTTP_MESSAGE_FOOTER);
state = HTTP_MESSAGE_DONE;
}
|
[
"msg555@gmail.com"
] |
msg555@gmail.com
|
1207b6d2df26c88e639c80c64f883a1f0fade0b7
|
3f981d86067464fae3945e2c98e2e23912183afb
|
/Core/Scene/Primitive.h
|
e74ff35959978832df1f0d33c26b00a5d1ddb483
|
[] |
no_license
|
keithbugeja/illuminaPRT
|
8b1a4664f202611412b8e7c720f1e309f05fe6a2
|
faddb7d05a5ea71f8209dfa64d0c82b690347208
|
refs/heads/master
| 2021-03-27T19:50:03.104771
| 2014-05-20T11:12:49
| 2014-05-20T11:12:49
| 87,206,098
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,104
|
h
|
//----------------------------------------------------------------------------------------------
// Filename: Primitive.h
// Author: Keith Bugeja
// Date: 27/02/2010
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
#pragma once
#include "System/IlluminaPRT.h"
//----------------------------------------------------------------------------------------------
namespace Illumina
{
namespace Core
{
class IPrimitive
{
public:
virtual bool IsBounded(void) const = 0;
virtual boost::shared_ptr<IBoundingVolume> GetWorldBounds(void) const = 0;
virtual Vector3 SamplePoint(float p_u, float p_v, Vector3 &p_normal) = 0;
virtual Vector3 SamplePoint(const Vector3 &p_viewPoint, float p_u, float p_v, Vector3 &p_normal) = 0;
virtual bool Intersects(const Ray &p_ray, Intersection &p_intersection) = 0;
virtual bool Intersects(const Ray &p_ray) = 0;
virtual std::string ToString(void) const = 0;
};
}
}
|
[
"keithbugeja@users.noreply.github.com"
] |
keithbugeja@users.noreply.github.com
|
3d7af267baf2c9a5ebb1c637f8187734415a3873
|
4a9e765bd2806cf6fcf94c635cdcccc483619119
|
/disjoint_set/disjoint_set.h
|
67f233b4b1714702c656ce14f7e3633d6c98b7b8
|
[] |
no_license
|
clangpp/codeset
|
1c0aaf4c778ca96025f5ad4e6fcef7c9699d87a2
|
67bb303772b403c9946f262c3a10bf7342ce9072
|
refs/heads/main
| 2021-09-25T22:07:42.000609
| 2021-09-09T07:40:50
| 2021-09-09T07:40:50
| 13,406,758
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,192
|
h
|
#ifndef DISJOINT_SET_H_
#define DISJOINT_SET_H_
#include <algorithm>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <vector>
// disjoint set algorithm
namespace disjoint_set {
typedef std::ptrdiff_t ssize_type;
// ************ notes **************
// concept RandomAccessIterator {
// std::iterator_traits<RandomAccessIterator>::value_type
// is compatible with ssize_type
// };
// ************ notes **************
// pre-condition: root1 and root2 are root node of disdinct subsets
template <typename RandomAccessIterator>
inline void union_sets_plain(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
sets[root2] = root1;
}
template <typename RandomAccessIterator>
inline void union_sets_by_size(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
if (sets[root1] <= sets[root2]) { // size(root1) >= size(root2)
sets[root1] += sets[root2]; // add root2's size to root1's
sets[root2] = root1; // attach tree root2 to tree root1
} else { // size(root1) < size(root2)
sets[root2] += sets[root1]; // add root1's size to root2's
sets[root1] = root2; // attach tree root1 to tree root2
}
}
template <typename RandomAccessIterator>
inline void union_sets_by_height(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
if (sets[root1] <= sets[root2]) { // height(root1) >= height(root2)
if (sets[root1] == sets[root2]) {
--sets[root1]; // update height if same
}
sets[root2] = root1; // attach tree root2 to tree root1
} else { // height(root1) < height(root2)
sets[root1] = root2; // attach tree root1 to tree root2
}
}
// pre-condition: sets[s] is referencable
template <typename RandomAccessIterator>
ssize_type find_plain(RandomAccessIterator sets, ssize_type s) {
return sets[s] < 0 ? s : find_plain(sets, sets[s]);
}
template <typename RandomAccessIterator>
ssize_type find_compress_path(RandomAccessIterator sets, ssize_type s) {
if (sets[s] < 0) {
return s;
}
return sets[s] = find_compress_path(sets, sets[s]);
}
} // namespace disjoint_set
// disjoint set class
class DisjointSet {
public:
typedef std::size_t size_type;
typedef disjoint_set::ssize_type ssize_type;
typedef ssize_type setid_type;
public:
explicit DisjointSet(size_type n = 0) : sets_(n, -1) {}
// find root node of subset that s belongs to
setid_type find(setid_type s) const {
if (s < 0 || s >= ssize_type(sets_.size()))
throw std::invalid_argument("invalid setid");
return disjoint_set::find_plain(sets_.begin(), s);
}
// find root node of subset that s belongs to
setid_type find(setid_type s) {
if (s < 0 || s >= ssize_type(sets_.size()))
throw std::invalid_argument("invalid setid");
return disjoint_set::find_compress_path(sets_.begin(), s);
}
// union two subsets which s1 and s2 belongs to
// return true if union takes place, otherwise false.
bool union_sets(setid_type s1, setid_type s2) {
setid_type root1 = find(s1);
setid_type root2 = find(s2);
if (root1 == root2) return false;
disjoint_set::union_sets_by_size(sets_.begin(), root1, root2);
return true;
}
// get nodes amount in disjoint set
size_type size() const { return sets_.size(); }
// get subsets amount in disjoint set
size_type set_count() const {
return std::count_if(sets_.begin(), sets_.end(),
[](setid_type set) { return set < 0; });
}
// get nodes amount in subset that s belongs to
size_type set_size(setid_type s) const {
setid_type root = find(s);
return static_cast<size_type>(-sets_[root]);
}
// get nodes amount in subset that s belongs to
size_type set_size(setid_type s) {
setid_type root = find(s);
return static_cast<size_type>(-sets_[root]);
}
private:
std::vector<ssize_type> sets_;
};
#endif // DISJOINT_SET_H_
|
[
"clangpp@gmail.com"
] |
clangpp@gmail.com
|
62b723b075914551f7ab46dec4eacd6ff9f8f211
|
4bd0543a3030e040e9ea60952a474b757ebf19e7
|
/206. 反转链表.cpp
|
5b03dc0c7e6c264a22f026c919262ea8db597400
|
[] |
no_license
|
tang2021/leetcode_test
|
f123a3c94aedb8a7876eba0ad92b98f26c4c4297
|
b8a7127736f2f8214d464b1fb245a434cf205153
|
refs/heads/main
| 2023-04-01T13:54:08.297850
| 2021-04-03T11:14:05
| 2021-04-03T11:14:05
| 338,090,786
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 718
|
cpp
|
// 206. 反转链表
// 反转一个单链表。
// 示例:
// 输入: 1->2->3->4->5->NULL
// 输出: 5->4->3->2->1->NULL
// 进阶:
// 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
typedef struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(nullptr){}
}ListNode;
ListNode* reverse(ListNode* head){
ListNode *newhead=nullptr,*h=head;
while(h!=nullptr){
ListNode* n=h->next;
h->next=newhead;
newhead=h;
h=n;
}
return newhead;
}
ListNode* reverse(ListNode* head){
if(head==nullptr)return head;
ListNode* p=reverse(head->next);
head->next->next=head;
head->next=nullptr;
return p;
}
|
[
"123246235@qq.com"
] |
123246235@qq.com
|
1e0c45aafb3803facaf5574b7416e815bd34c440
|
c51febc209233a9160f41913d895415704d2391f
|
/library/ATF/tagPAGERANGE.hpp
|
9e24564de60ae573b492688d2ea6f5d3c9af85f7
|
[
"MIT"
] |
permissive
|
roussukke/Yorozuya
|
81f81e5e759ecae02c793e65d6c3acc504091bc3
|
d9a44592b0714da1aebf492b64fdcb3fa072afe5
|
refs/heads/master
| 2023-07-08T03:23:00.584855
| 2023-06-29T08:20:25
| 2023-06-29T08:20:25
| 463,330,454
| 0
| 0
|
MIT
| 2022-02-24T23:15:01
| 2022-02-24T23:15:00
| null |
UTF-8
|
C++
| false
| false
| 271
|
hpp
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct tagPAGERANGE
{
int nFromPage;
int nToPage;
};
END_ATF_NAMESPACE
|
[
"b1ll.cipher@yandex.ru"
] |
b1ll.cipher@yandex.ru
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.