blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
91054d400d0424de1a98c80546f96af33ef314af | 4de3565dd26efbb2fd1ef82c2e4c1d311934728b | /src/content/browser/storage_partition_impl.cc | b1a8a1df01aa876028c142b3b6e62d9a7fb3d53d | [
"BSD-3-Clause"
]
| permissive | sundermann/chromium84-temp | 8c9bf42e855ed36adccab4bcb2148543e3793375 | df04aa361ad493d47003a80ebfa3034dfc9de6e0 | refs/heads/master | 2023-05-30T17:21:35.921797 | 2020-02-10T12:57:27 | 2020-09-07T06:22:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 97,716 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/storage_partition_impl.h"
#include <stdint.h>
#include <functional>
#include <set>
#include <utility>
#include <vector>
#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/syslog_logging.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequence_local_storage_slot.h"
#include "base/time/default_clock.h"
#include "build/build_config.h"
#include "components/leveldb_proto/public/proto_database_provider.h"
#include "components/services/storage/public/cpp/filesystem/filesystem_impl.h"
#include "components/services/storage/public/mojom/filesystem/directory.mojom.h"
#include "components/services/storage/public/mojom/indexed_db_control.mojom.h"
#include "components/services/storage/public/mojom/storage_service.mojom.h"
#include "components/services/storage/storage_service_impl.h"
#include "content/browser/background_fetch/background_fetch_context.h"
#include "content/browser/blob_storage/blob_registry_wrapper.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/browsing_data/clear_site_data_handler.h"
#include "content/browser/browsing_data/storage_partition_code_cache_data_remover.h"
#include "content/browser/code_cache/generated_code_cache.h"
#include "content/browser/code_cache/generated_code_cache_context.h"
#include "content/browser/conversions/conversion_manager_impl.h"
#include "content/browser/cookie_store/cookie_store_context.h"
#include "content/browser/devtools/devtools_instrumentation.h"
#include "content/browser/devtools/devtools_url_loader_interceptor.h"
#include "content/browser/file_system/browser_file_system_helper.h"
#include "content/browser/gpu/shader_cache_factory.h"
#include "content/browser/idle/idle_manager_impl.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/native_file_system/native_file_system_manager_impl.h"
#include "content/browser/native_io/native_io_context.h"
#include "content/browser/network_context_client_base_impl.h"
#include "content/browser/notifications/platform_notification_context_impl.h"
#include "content/browser/quota/quota_context.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/ssl/ssl_client_auth_handler.h"
#include "content/browser/ssl/ssl_error_handler.h"
#include "content/browser/ssl_private_key_impl.h"
#include "content/browser/web_contents/frame_tree_node_id_registry.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/navigation_params.mojom.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/cors_exempt_headers.h"
#include "content/public/browser/dom_storage_context.h"
#include "content/public/browser/login_delegate.h"
#include "content/public/browser/native_file_system_entry_factory.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/permission_controller.h"
#include "content/public/browser/service_process_host.h"
#include "content/public/browser/session_storage_usage_info.h"
#include "content/public/browser/storage_notification_service.h"
#include "content/public/browser/storage_usage_info.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/net_errors.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_util.h"
#include "net/http/http_auth_preferences.h"
#include "net/ssl/client_cert_store.h"
#include "net/url_request/url_request_context.h"
#include "ppapi/buildflags/buildflags.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/cookie_access_observer.mojom.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/trust_tokens.mojom.h"
#include "storage/browser/blob/blob_registry_impl.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/database/database_tracker.h"
#include "storage/browser/quota/quota_client_type.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/quota/quota_settings.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/devtools/inspector_issue.mojom-shared.h"
#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#if defined(OS_ANDROID)
#include "net/android/http_auth_negotiate_android.h"
#else
#include "content/browser/host_zoom_map_impl.h"
#endif // defined(OS_ANDROID)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/plugin_private_storage_helper.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
using CookieDeletionFilter = network::mojom::CookieDeletionFilter;
using CookieDeletionFilterPtr = network::mojom::CookieDeletionFilterPtr;
namespace content {
namespace {
const storage::QuotaSettings* g_test_quota_settings;
mojo::Remote<storage::mojom::StorageService>& GetStorageServiceRemoteStorage() {
// NOTE: This use of sequence-local storage is only to ensure that the Remote
// only lives as long as the UI-thread sequence, since the UI-thread sequence
// may be torn down and reinitialized e.g. between unit tests.
static base::NoDestructor<base::SequenceLocalStorageSlot<
mojo::Remote<storage::mojom::StorageService>>>
remote_slot;
return remote_slot->GetOrCreateValue();
}
void RunInProcessStorageService(
mojo::PendingReceiver<storage::mojom::StorageService> receiver) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
static base::NoDestructor<base::SequenceLocalStorageSlot<
std::unique_ptr<storage::StorageServiceImpl>>>
service_storage_slot;
service_storage_slot->GetOrCreateValue() =
std::make_unique<storage::StorageServiceImpl>(std::move(receiver),
/*io_task_runner=*/nullptr);
}
#if !defined(OS_ANDROID)
void BindStorageServiceFilesystemImpl(
const base::FilePath& directory_path,
mojo::PendingReceiver<storage::mojom::Directory> receiver) {
mojo::MakeSelfOwnedReceiver(
std::make_unique<storage::FilesystemImpl>(directory_path),
std::move(receiver));
}
#endif
mojo::Remote<storage::mojom::StorageService>& GetStorageServiceRemote() {
mojo::Remote<storage::mojom::StorageService>& remote =
GetStorageServiceRemoteStorage();
if (!remote) {
#if !defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kStorageServiceOutOfProcess)) {
const bool should_sandbox =
base::FeatureList::IsEnabled(features::kStorageServiceSandbox);
const base::FilePath sandboxed_data_dir =
GetContentClient()
->browser()
->GetSandboxedStorageServiceDataDirectory();
const bool is_sandboxed = should_sandbox && !sandboxed_data_dir.empty();
if (should_sandbox && !is_sandboxed) {
DLOG(ERROR) << "Running unsandboxed Storage Service instance,because "
<< "the current ContentBrowserClient does not specify a "
<< "sandboxed data directory.";
}
remote = ServiceProcessHost::Launch<storage::mojom::StorageService>(
ServiceProcessHost::Options()
.WithSandboxType(is_sandboxed ? SandboxType::kUtility
: SandboxType::kNoSandbox)
.WithDisplayName("Storage Service")
.Pass());
remote.reset_on_disconnect();
if (is_sandboxed) {
// In sandboxed mode, provide the service with an API it can use to
// access filesystem contents *only* within the embedder's specified
// data directory.
const base::FilePath data_dir =
GetContentClient()
->browser()
->GetSandboxedStorageServiceDataDirectory();
DCHECK(!data_dir.empty())
<< "Storage Service sandboxing requires a root data directory.";
mojo::PendingRemote<storage::mojom::Directory> directory;
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE})
->PostTask(
FROM_HERE,
base::BindOnce(&BindStorageServiceFilesystemImpl, data_dir,
directory.InitWithNewPipeAndPassReceiver()));
remote->SetDataDirectory(data_dir, std::move(directory));
}
} else
#endif // !defined(OS_ANDROID)
{
base::PostTask(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&RunInProcessStorageService,
remote.BindNewPipeAndPassReceiver()));
}
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableAggressiveDOMStorageFlushing)) {
remote->EnableAggressiveDomStorageFlushing();
}
}
return remote;
}
// A callback to create a URLLoaderFactory that is used in tests.
StoragePartitionImpl::CreateNetworkFactoryCallback&
GetCreateURLLoaderFactoryCallback() {
static base::NoDestructor<StoragePartitionImpl::CreateNetworkFactoryCallback>
create_factory_callback;
return *create_factory_callback;
}
void OnClearedCookies(base::OnceClosure callback, uint32_t num_deleted) {
// The final callback needs to happen from UI thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&OnClearedCookies, std::move(callback), num_deleted));
return;
}
std::move(callback).Run();
}
void CheckQuotaManagedDataDeletionStatus(size_t* deletion_task_count,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (*deletion_task_count == 0) {
delete deletion_task_count;
std::move(callback).Run();
}
}
void OnQuotaManagedOriginDeleted(const url::Origin& origin,
blink::mojom::StorageType type,
size_t* deletion_task_count,
base::OnceClosure callback,
blink::mojom::QuotaStatusCode status) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_GT(*deletion_task_count, 0u);
if (status != blink::mojom::QuotaStatusCode::kOk) {
DLOG(ERROR) << "Couldn't remove data of type " << static_cast<int>(type)
<< " for origin " << origin
<< ". Status: " << static_cast<int>(status);
}
(*deletion_task_count)--;
CheckQuotaManagedDataDeletionStatus(deletion_task_count, std::move(callback));
}
void PerformQuotaManagerStorageCleanup(
const scoped_refptr<storage::QuotaManager>& quota_manager,
blink::mojom::StorageType quota_storage_type,
storage::QuotaClientTypes quota_client_types,
base::OnceClosure callback) {
quota_manager->PerformStorageCleanup(
quota_storage_type, std::move(quota_client_types), std::move(callback));
}
void ClearedShaderCache(base::OnceClosure callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
base::PostTask(FROM_HERE, {BrowserThread::UI},
base::BindOnce(&ClearedShaderCache, std::move(callback)));
return;
}
std::move(callback).Run();
}
void ClearShaderCacheOnIOThread(const base::FilePath& path,
const base::Time begin,
const base::Time end,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
gpu::ShaderCacheFactory* shader_cache_factory =
GetShaderCacheFactorySingleton();
// May be null in tests where it is difficult to plumb through a test storage
// partition.
if (!shader_cache_factory) {
std::move(callback).Run();
return;
}
shader_cache_factory->ClearByPath(
path, begin, end,
base::BindOnce(&ClearedShaderCache, std::move(callback)));
}
void OnLocalStorageUsageInfo(
const scoped_refptr<DOMStorageContextWrapper>& dom_storage_context,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
const base::Time delete_begin,
const base::Time delete_end,
base::OnceClosure callback,
const std::vector<StorageUsageInfo>& infos) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::OnceClosure done_callback =
perform_storage_cleanup
? base::BindOnce(
&DOMStorageContextWrapper::PerformLocalStorageCleanup,
dom_storage_context, std::move(callback))
: std::move(callback);
base::RepeatingClosure barrier =
base::BarrierClosure(infos.size(), std::move(done_callback));
for (const StorageUsageInfo& info : infos) {
if (origin_matcher &&
!origin_matcher.Run(info.origin, special_storage_policy.get())) {
barrier.Run();
continue;
}
if (info.last_modified >= delete_begin &&
info.last_modified <= delete_end) {
dom_storage_context->DeleteLocalStorage(info.origin, barrier);
} else {
barrier.Run();
}
}
}
void OnSessionStorageUsageInfo(
const scoped_refptr<DOMStorageContextWrapper>& dom_storage_context,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback,
const std::vector<SessionStorageUsageInfo>& infos) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::OnceClosure done_callback =
perform_storage_cleanup
? base::BindOnce(
&DOMStorageContextWrapper::PerformSessionStorageCleanup,
dom_storage_context, std::move(callback))
: std::move(callback);
base::RepeatingClosure barrier =
base::BarrierClosure(infos.size(), std::move(done_callback));
for (const SessionStorageUsageInfo& info : infos) {
if (origin_matcher && !origin_matcher.Run(url::Origin::Create(info.origin),
special_storage_policy.get())) {
barrier.Run();
continue;
}
dom_storage_context->DeleteSessionStorage(info, barrier);
}
}
void ClearLocalStorageOnUIThread(
const scoped_refptr<DOMStorageContextWrapper>& dom_storage_context,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
const GURL& storage_origin,
bool perform_storage_cleanup,
const base::Time begin,
const base::Time end,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!storage_origin.is_empty()) {
bool can_delete = !origin_matcher ||
origin_matcher.Run(url::Origin::Create(storage_origin),
special_storage_policy.get());
if (can_delete) {
dom_storage_context->DeleteLocalStorage(
url::Origin::Create(storage_origin), std::move(callback));
} else {
std::move(callback).Run();
}
return;
}
dom_storage_context->GetLocalStorageUsage(
base::BindOnce(&OnLocalStorageUsageInfo, dom_storage_context,
special_storage_policy, std::move(origin_matcher),
perform_storage_cleanup, begin, end, std::move(callback)));
}
void ClearSessionStorageOnUIThread(
const scoped_refptr<DOMStorageContextWrapper>& dom_storage_context,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
dom_storage_context->GetSessionStorageUsage(base::BindOnce(
&OnSessionStorageUsageInfo, dom_storage_context, special_storage_policy,
std::move(origin_matcher), perform_storage_cleanup, std::move(callback)));
}
WebContents* GetWebContentsForStoragePartition(uint32_t process_id,
uint32_t routing_id) {
if (process_id != network::mojom::kBrowserProcessId) {
return WebContentsImpl::FromRenderFrameHostID(process_id, routing_id);
}
return WebContents::FromFrameTreeNodeId(routing_id);
}
BrowserContext* GetBrowserContextFromStoragePartition(
base::WeakPtr<StoragePartitionImpl> weak_partition_ptr) {
return weak_partition_ptr ? weak_partition_ptr->browser_context() : nullptr;
}
WebContents* GetWebContents(int process_id, int routing_id) {
if (process_id != network::mojom::kBrowserProcessId) {
return WebContentsImpl::FromRenderFrameHostID(process_id, routing_id);
}
return WebContents::FromFrameTreeNodeId(routing_id);
}
// LoginHandlerDelegate manages HTTP auth. It is self-owning and deletes itself
// when the credentials are resolved or the AuthChallengeResponder is cancelled.
class LoginHandlerDelegate {
public:
LoginHandlerDelegate(
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder,
WebContents::Getter web_contents_getter,
const net::AuthChallengeInfo& auth_info,
bool is_request_for_main_frame,
uint32_t process_id,
uint32_t routing_id,
uint32_t request_id,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers,
bool first_auth_attempt)
: auth_challenge_responder_(std::move(auth_challenge_responder)),
auth_info_(auth_info),
request_id_(process_id, request_id),
routing_id_(routing_id),
is_request_for_main_frame_(is_request_for_main_frame),
creating_login_delegate_(false),
url_(url),
response_headers_(std::move(response_headers)),
first_auth_attempt_(first_auth_attempt),
web_contents_getter_(web_contents_getter) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auth_challenge_responder_.set_disconnect_handler(base::BindOnce(
&LoginHandlerDelegate::OnRequestCancelled, base::Unretained(this)));
DevToolsURLLoaderInterceptor::HandleAuthRequest(
request_id_.child_id, routing_id_, request_id_.request_id, auth_info_,
base::BindOnce(&LoginHandlerDelegate::ContinueAfterInterceptor,
weak_factory_.GetWeakPtr()));
}
private:
void OnRequestCancelled() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// This will destroy |login_handler_io_| on the IO thread and, if needed,
// inform the delegate.
delete this;
}
void ContinueAfterInterceptor(
bool use_fallback,
const base::Optional<net::AuthCredentials>& auth_credentials) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!(use_fallback && auth_credentials.has_value()));
if (!use_fallback) {
OnAuthCredentials(auth_credentials);
return;
}
WebContents* web_contents = web_contents_getter_.Run();
if (!web_contents) {
OnAuthCredentials(base::nullopt);
return;
}
// WeakPtr is not strictly necessary here due to OnRequestCancelled.
creating_login_delegate_ = true;
login_delegate_ = GetContentClient()->browser()->CreateLoginDelegate(
auth_info_, web_contents, request_id_, is_request_for_main_frame_, url_,
response_headers_, first_auth_attempt_,
base::BindOnce(&LoginHandlerDelegate::OnAuthCredentials,
weak_factory_.GetWeakPtr()));
creating_login_delegate_ = false;
if (!login_delegate_) {
OnAuthCredentials(base::nullopt);
return;
}
}
void OnAuthCredentials(
const base::Optional<net::AuthCredentials>& auth_credentials) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// CreateLoginDelegate must not call the callback reentrantly. For
// robustness, detect this mistake.
CHECK(!creating_login_delegate_);
auth_challenge_responder_->OnAuthCredentials(auth_credentials);
delete this;
}
mojo::Remote<network::mojom::AuthChallengeResponder>
auth_challenge_responder_;
net::AuthChallengeInfo auth_info_;
const content::GlobalRequestID request_id_;
const uint32_t routing_id_;
bool is_request_for_main_frame_;
bool creating_login_delegate_;
GURL url_;
const scoped_refptr<net::HttpResponseHeaders> response_headers_;
bool first_auth_attempt_;
WebContents::Getter web_contents_getter_;
std::unique_ptr<LoginDelegate> login_delegate_;
base::WeakPtrFactory<LoginHandlerDelegate> weak_factory_{this};
};
void OnAuthRequiredContinuation(
uint32_t process_id,
uint32_t routing_id,
uint32_t request_id,
const GURL& url,
bool is_request_for_main_frame,
bool first_auth_attempt,
const net::AuthChallengeInfo& auth_info,
network::mojom::URLResponseHeadPtr head,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder,
base::RepeatingCallback<WebContents*(void)> web_contents_getter) {
if (!web_contents_getter) {
web_contents_getter =
base::BindRepeating(GetWebContents, process_id, routing_id);
}
if (!web_contents_getter.Run()) {
mojo::Remote<network::mojom::AuthChallengeResponder>
auth_challenge_responder_remote(std::move(auth_challenge_responder));
auth_challenge_responder_remote->OnAuthCredentials(base::nullopt);
return;
}
new LoginHandlerDelegate(std::move(auth_challenge_responder),
std::move(web_contents_getter), auth_info,
is_request_for_main_frame, process_id, routing_id,
request_id, url, head ? head->headers : nullptr,
first_auth_attempt); // deletes self
}
FrameTreeNodeIdRegistry::IsMainFrameGetter GetIsMainFrameFromRegistry(
const base::UnguessableToken& window_id) {
return FrameTreeNodeIdRegistry::GetInstance()->GetIsMainFrameGetter(
window_id);
}
base::RepeatingCallback<WebContents*(void)> GetWebContentsFromRegistry(
const base::UnguessableToken& window_id) {
return FrameTreeNodeIdRegistry::GetInstance()->GetWebContentsGetter(
window_id);
}
void OnAuthRequiredContinuationForWindowId(
const base::UnguessableToken& window_id,
uint32_t process_id,
uint32_t routing_id,
uint32_t request_id,
const GURL& url,
bool first_auth_attempt,
const net::AuthChallengeInfo& auth_info,
network::mojom::URLResponseHeadPtr head,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder,
FrameTreeNodeIdRegistry::IsMainFrameGetter is_main_frame_getter) {
if (!is_main_frame_getter) {
// FrameTreeNode id may already be removed from FrameTreeNodeIdRegistry
// due to thread hopping.
mojo::Remote<network::mojom::AuthChallengeResponder>
auth_challenge_responder_remote(std::move(auth_challenge_responder));
auth_challenge_responder_remote->OnAuthCredentials(base::nullopt);
return;
}
base::Optional<bool> is_main_frame_opt = is_main_frame_getter.Run();
// The frame may already be gone due to thread hopping.
if (!is_main_frame_opt) {
mojo::Remote<network::mojom::AuthChallengeResponder>
auth_challenge_responder_remote(std::move(auth_challenge_responder));
auth_challenge_responder_remote->OnAuthCredentials(base::nullopt);
return;
}
if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) {
OnAuthRequiredContinuation(process_id, routing_id, request_id, url,
*is_main_frame_opt, first_auth_attempt,
auth_info, std::move(head),
std::move(auth_challenge_responder),
GetWebContentsFromRegistry(window_id));
} else {
base::PostTaskAndReplyWithResult(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&GetWebContentsFromRegistry, window_id),
base::BindOnce(&OnAuthRequiredContinuation, process_id, routing_id,
request_id, url, *is_main_frame_opt, first_auth_attempt,
auth_info, std::move(head),
std::move(auth_challenge_responder)));
}
}
bool IsMainFrameRequest(int process_id, int routing_id) {
if (process_id != network::mojom::kBrowserProcessId)
return false;
auto* frame_tree_node = FrameTreeNode::GloballyFindByID(routing_id);
return frame_tree_node && frame_tree_node->IsMainFrame();
}
// This class lives on the UI thread. It is self-owned and will delete itself
// after any of the SSLClientAuthHandler::Delegate methods are invoked (or when
// a mojo connection error occurs).
class SSLClientAuthDelegate : public SSLClientAuthHandler::Delegate {
public:
SSLClientAuthDelegate(
mojo::PendingRemote<network::mojom::ClientCertificateResponder>
client_cert_responder_remote,
content::BrowserContext* browser_context,
WebContents::Getter web_contents_getter,
const scoped_refptr<net::SSLCertRequestInfo>& cert_info)
: client_cert_responder_(std::move(client_cert_responder_remote)),
ssl_client_auth_handler_(std::make_unique<SSLClientAuthHandler>(
GetContentClient()->browser()->CreateClientCertStore(
browser_context),
std::move(web_contents_getter),
std::move(cert_info.get()),
this)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(client_cert_responder_);
client_cert_responder_.set_disconnect_handler(base::BindOnce(
&SSLClientAuthDelegate::DeleteSelf, base::Unretained(this)));
ssl_client_auth_handler_->SelectCertificate();
}
~SSLClientAuthDelegate() override { DCHECK_CURRENTLY_ON(BrowserThread::UI); }
void DeleteSelf() { delete this; }
// SSLClientAuthHandler::Delegate:
void CancelCertificateSelection() override {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
client_cert_responder_->CancelRequest();
DeleteSelf();
}
// SSLClientAuthHandler::Delegate:
void ContinueWithCertificate(
scoped_refptr<net::X509Certificate> cert,
scoped_refptr<net::SSLPrivateKey> private_key) override {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK((cert && private_key) || (!cert && !private_key));
if (cert && private_key) {
mojo::PendingRemote<network::mojom::SSLPrivateKey> ssl_private_key;
mojo::MakeSelfOwnedReceiver(
std::make_unique<SSLPrivateKeyImpl>(private_key),
ssl_private_key.InitWithNewPipeAndPassReceiver());
client_cert_responder_->ContinueWithCertificate(
cert, private_key->GetProviderName(),
private_key->GetAlgorithmPreferences(), std::move(ssl_private_key));
} else {
client_cert_responder_->ContinueWithoutCertificate();
}
DeleteSelf();
}
private:
mojo::Remote<network::mojom::ClientCertificateResponder>
client_cert_responder_;
std::unique_ptr<SSLClientAuthHandler> ssl_client_auth_handler_;
};
void OnCertificateRequestedContinuation(
uint32_t process_id,
uint32_t routing_id,
uint32_t request_id,
const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
mojo::PendingRemote<network::mojom::ClientCertificateResponder>
client_cert_responder_remote,
base::RepeatingCallback<WebContents*(void)> web_contents_getter) {
if (!web_contents_getter) {
web_contents_getter =
base::BindRepeating(GetWebContents, process_id, routing_id);
}
WebContents* web_contents = web_contents_getter.Run();
if (!web_contents) {
DCHECK(client_cert_responder_remote);
mojo::Remote<network::mojom::ClientCertificateResponder>
client_cert_responder(std::move(client_cert_responder_remote));
client_cert_responder->CancelRequest();
return;
}
new SSLClientAuthDelegate(std::move(client_cert_responder_remote),
web_contents->GetBrowserContext(),
std::move(web_contents_getter),
cert_info); // deletes self
}
class SSLErrorDelegate : public SSLErrorHandler::Delegate {
public:
explicit SSLErrorDelegate(
network::mojom::NetworkContextClient::OnSSLCertificateErrorCallback
response)
: response_(std::move(response)) {}
~SSLErrorDelegate() override = default;
void CancelSSLRequest(int error, const net::SSLInfo* ssl_info) override {
std::move(response_).Run(error);
delete this;
}
void ContinueSSLRequest() override {
std::move(response_).Run(net::OK);
delete this;
}
base::WeakPtr<SSLErrorDelegate> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
private:
network::mojom::NetworkContextClient::OnSSLCertificateErrorCallback response_;
base::WeakPtrFactory<SSLErrorDelegate> weak_factory_{this};
};
#if defined(OS_ANDROID)
void FinishGenerateNegotiateAuthToken(
std::unique_ptr<net::android::HttpAuthNegotiateAndroid> auth_negotiate,
std::unique_ptr<std::string> auth_token,
std::unique_ptr<net::HttpAuthPreferences> prefs,
network::mojom::NetworkContextClient::
OnGenerateHttpNegotiateAuthTokenCallback callback,
int result) {
std::move(callback).Run(result, *auth_token);
}
#endif
// Conceptually, many downstream interfaces don't need to know about the
// complexity of callers into StoragePartition, so this function reduces the API
// surface to something simple and generic. It is designed to be used by
// callsites in ClearDataImpl.
//
// Precondition: |matcher_func| and |storage_origin| cannot both be set.
// If both |matcher_func| and |storage_origin| are null/empty, should return a
// null callback that indicates all origins should match. This is an
// optimization for backends to efficiently clear all data.
//
// TODO(csharrison, mek): Right now, the only storage backend that uses this is
// is for conversion measurement. We should consider moving some of the
// backends to use this if they can, and additionally we should consider
// rethinking this approach if / when storage backends move out of process
// (see crbug.com/1016065 for initial work here).
base::RepeatingCallback<bool(const url::Origin&)> CreateGenericOriginMatcher(
const GURL& storage_origin,
StoragePartition::OriginMatcherFunction matcher_func,
scoped_refptr<storage::SpecialStoragePolicy> policy) {
DCHECK(storage_origin.is_empty() || matcher_func.is_null());
if (storage_origin.is_empty() && matcher_func.is_null())
return base::NullCallback();
if (matcher_func) {
return base::BindRepeating(
[](StoragePartition::OriginMatcherFunction matcher_func,
scoped_refptr<storage::SpecialStoragePolicy> policy,
const url::Origin& origin) -> bool {
return matcher_func.Run(origin, policy.get());
},
std::move(matcher_func), std::move(policy));
}
DCHECK(!storage_origin.is_empty());
return base::BindRepeating(std::equal_to<const url::Origin&>(),
url::Origin::Create(storage_origin));
}
} // namespace
class StoragePartitionImpl::URLLoaderFactoryForBrowserProcess
: public network::SharedURLLoaderFactory {
public:
explicit URLLoaderFactoryForBrowserProcess(
StoragePartitionImpl* storage_partition,
bool corb_enabled)
: storage_partition_(storage_partition), corb_enabled_(corb_enabled) {}
// mojom::URLLoaderFactory implementation:
void CreateLoaderAndStart(
mojo::PendingReceiver<network::mojom::URLLoader> receiver,
int32_t routing_id,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& url_request,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
override {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!storage_partition_)
return;
storage_partition_
->GetURLLoaderFactoryForBrowserProcessInternal(corb_enabled_)
->CreateLoaderAndStart(std::move(receiver), routing_id, request_id,
options, url_request, std::move(client),
traffic_annotation);
}
void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver)
override {
if (!storage_partition_)
return;
storage_partition_
->GetURLLoaderFactoryForBrowserProcessInternal(corb_enabled_)
->Clone(std::move(receiver));
}
// SharedURLLoaderFactory implementation:
std::unique_ptr<network::PendingSharedURLLoaderFactory> Clone() override {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return std::make_unique<network::CrossThreadPendingSharedURLLoaderFactory>(
this);
}
void Shutdown() { storage_partition_ = nullptr; }
private:
friend class base::RefCounted<URLLoaderFactoryForBrowserProcess>;
~URLLoaderFactoryForBrowserProcess() override = default;
StoragePartitionImpl* storage_partition_;
const bool corb_enabled_;
DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForBrowserProcess);
};
// Static.
storage::QuotaClientTypes StoragePartitionImpl::GenerateQuotaClientTypes(
uint32_t remove_mask) {
storage::QuotaClientTypes quota_client_types;
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS)
quota_client_types.insert(storage::QuotaClientType::kFileSystem);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_WEBSQL)
quota_client_types.insert(storage::QuotaClientType::kDatabase);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_APPCACHE)
quota_client_types.insert(storage::QuotaClientType::kAppcache);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_INDEXEDDB)
quota_client_types.insert(storage::QuotaClientType::kIndexedDatabase);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS)
quota_client_types.insert(storage::QuotaClientType::kServiceWorker);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE)
quota_client_types.insert(storage::QuotaClientType::kServiceWorkerCache);
if (remove_mask & StoragePartition::REMOVE_DATA_MASK_BACKGROUND_FETCH)
quota_client_types.insert(storage::QuotaClientType::kBackgroundFetch);
return quota_client_types;
}
// static
void StoragePartitionImpl::
SetGetURLLoaderFactoryForBrowserProcessCallbackForTesting(
CreateNetworkFactoryCallback url_loader_factory_callback) {
DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!url_loader_factory_callback || !GetCreateURLLoaderFactoryCallback())
<< "It is not expected that this is called with non-null callback when "
<< "another overriding callback is already set.";
GetCreateURLLoaderFactoryCallback() = std::move(url_loader_factory_callback);
}
// Helper for deleting quota managed data from a partition.
//
// Most of the operations in this class are done on IO thread.
class StoragePartitionImpl::QuotaManagedDataDeletionHelper {
public:
QuotaManagedDataDeletionHelper(
uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
const base::Optional<url::Origin>& storage_origin,
base::OnceClosure callback)
: remove_mask_(remove_mask),
quota_storage_remove_mask_(quota_storage_remove_mask),
storage_origin_(storage_origin),
callback_(std::move(callback)),
task_count_(0) {
DCHECK(!storage_origin_.has_value() ||
!storage_origin_->GetURL().is_empty());
}
void IncrementTaskCountOnIO();
void DecrementTaskCountOnIO();
void ClearDataOnIOThread(
const scoped_refptr<storage::QuotaManager>& quota_manager,
const base::Time begin,
const scoped_refptr<storage::SpecialStoragePolicy>&
special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup);
void ClearOriginsOnIOThread(
storage::QuotaManager* quota_manager,
const scoped_refptr<storage::SpecialStoragePolicy>&
special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback,
const std::set<url::Origin>& origins,
blink::mojom::StorageType quota_storage_type);
private:
// All of these data are accessed on IO thread.
uint32_t remove_mask_;
uint32_t quota_storage_remove_mask_;
base::Optional<url::Origin> storage_origin_;
base::OnceClosure callback_;
int task_count_;
DISALLOW_COPY_AND_ASSIGN(QuotaManagedDataDeletionHelper);
};
// Helper for deleting all sorts of data from a partition, keeps track of
// deletion status.
//
// StoragePartitionImpl creates an instance of this class to keep track of
// data deletion progress. Deletion requires deleting multiple bits of data
// (e.g. cookies, local storage, session storage etc.) and hopping between UI
// and IO thread. An instance of this class is created in the beginning of
// deletion process (StoragePartitionImpl::ClearDataImpl) and the instance is
// forwarded and updated on each (sub) deletion's callback. The instance is
// finally destroyed when deletion completes (and |callback| is invoked).
class StoragePartitionImpl::DataDeletionHelper {
public:
DataDeletionHelper(uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
base::OnceClosure callback)
: remove_mask_(remove_mask),
quota_storage_remove_mask_(quota_storage_remove_mask),
callback_(std::move(callback)),
task_count_(0) {}
~DataDeletionHelper() = default;
void ClearDataOnUIThread(
const GURL& storage_origin,
OriginMatcherFunction origin_matcher,
CookieDeletionFilterPtr cookie_deletion_filter,
const base::FilePath& path,
DOMStorageContextWrapper* dom_storage_context,
storage::QuotaManager* quota_manager,
storage::SpecialStoragePolicy* special_storage_policy,
storage::FileSystemContext* filesystem_context,
network::mojom::CookieManager* cookie_manager,
ConversionManagerImpl* conversion_manager,
bool perform_storage_cleanup,
const base::Time begin,
const base::Time end);
void ClearQuotaManagedDataOnIOThread(
const scoped_refptr<storage::QuotaManager>& quota_manager,
const base::Time begin,
const GURL& storage_origin,
const scoped_refptr<storage::SpecialStoragePolicy>&
special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback);
private:
enum class TracingDataType {
kSynchronous = 1,
kCookies = 2,
kQuota = 3,
kLocalStorage = 4,
kSessionStorage = 5,
kShaderCache = 6,
kPluginPrivate = 7,
kConversions = 8,
};
base::OnceClosure CreateTaskCompletionClosure(TracingDataType data_type);
void OnTaskComplete(int tracing_id); // Callable on any thread.
uint32_t remove_mask_;
uint32_t quota_storage_remove_mask_;
// Accessed on UI thread.
base::OnceClosure callback_;
// Accessed on UI thread.
int task_count_;
DISALLOW_COPY_AND_ASSIGN(DataDeletionHelper);
};
void StoragePartitionImpl::DataDeletionHelper::ClearQuotaManagedDataOnIOThread(
const scoped_refptr<storage::QuotaManager>& quota_manager,
const base::Time begin,
const GURL& storage_origin,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
StoragePartitionImpl::QuotaManagedDataDeletionHelper* helper =
new StoragePartitionImpl::QuotaManagedDataDeletionHelper(
remove_mask_, quota_storage_remove_mask_,
storage_origin.is_empty()
? base::nullopt
: base::make_optional(url::Origin::Create(storage_origin)),
std::move(callback));
helper->ClearDataOnIOThread(quota_manager, begin, special_storage_policy,
std::move(origin_matcher),
perform_storage_cleanup);
}
class StoragePartitionImpl::ServiceWorkerCookieAccessObserver
: public network::mojom::CookieAccessObserver {
public:
explicit ServiceWorkerCookieAccessObserver(
StoragePartitionImpl* storage_partition)
: storage_partition_(storage_partition) {}
private:
void Clone(mojo::PendingReceiver<network::mojom::CookieAccessObserver>
observer) override {
storage_partition_->service_worker_cookie_observers_.Add(
std::make_unique<ServiceWorkerCookieAccessObserver>(storage_partition_),
std::move(observer));
}
void OnCookiesAccessed(
network::mojom::CookieAccessDetailsPtr details) override {
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context =
storage_partition_->GetServiceWorkerContext();
RunOrPostTaskOnThread(
FROM_HERE, ServiceWorkerContext::GetCoreThreadId(),
base::BindOnce(&OnServiceWorkerCookiesAccessedOnCoreThread,
service_worker_context, std::move(details)));
}
static void OnServiceWorkerCookiesAccessedOnCoreThread(
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context,
network::mojom::CookieAccessDetailsPtr details) {
std::vector<GlobalFrameRoutingId> destinations =
*service_worker_context->GetWindowClientFrameRoutingIds(
details->url.GetOrigin());
if (destinations.empty())
return;
RunOrPostTaskOnThread(
FROM_HERE, BrowserThread::UI,
base::BindOnce(&ReportCookiesAccessedOnUI, std::move(destinations),
std::move(details)));
}
static void ReportCookiesAccessedOnUI(
std::vector<GlobalFrameRoutingId> destinations,
network::mojom::CookieAccessDetailsPtr details) {
for (GlobalFrameRoutingId frame_id : destinations) {
if (RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(frame_id)) {
rfh->OnCookiesAccessed(mojo::Clone(details));
}
}
}
// |storage_partition_| owns this object via UniqueReceiverSet
// (service_worker_cookie_observers_).
StoragePartitionImpl* storage_partition_;
};
StoragePartitionImpl::StoragePartitionImpl(
BrowserContext* browser_context,
const base::FilePath& partition_path,
bool is_in_memory,
const base::FilePath& relative_partition_path,
const std::string& partition_domain,
storage::SpecialStoragePolicy* special_storage_policy)
: browser_context_(browser_context),
partition_path_(partition_path),
is_in_memory_(is_in_memory),
relative_partition_path_(relative_partition_path),
partition_domain_(partition_domain),
special_storage_policy_(special_storage_policy),
deletion_helpers_running_(0) {}
StoragePartitionImpl::~StoragePartitionImpl() {
browser_context_ = nullptr;
if (url_loader_factory_getter_)
url_loader_factory_getter_->OnStoragePartitionDestroyed();
if (shared_url_loader_factory_for_browser_process_) {
shared_url_loader_factory_for_browser_process_->Shutdown();
}
if (shared_url_loader_factory_for_browser_process_with_corb_) {
shared_url_loader_factory_for_browser_process_with_corb_->Shutdown();
}
if (GetDatabaseTracker()) {
GetDatabaseTracker()->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&storage::DatabaseTracker::Shutdown,
GetDatabaseTracker()));
}
if (GetFileSystemContext())
GetFileSystemContext()->Shutdown();
if (GetDOMStorageContext())
GetDOMStorageContext()->Shutdown();
if (GetServiceWorkerContext())
GetServiceWorkerContext()->Shutdown();
if (GetIndexedDBContextInternal())
GetIndexedDBContextInternal()->Shutdown();
if (GetCacheStorageContext())
GetCacheStorageContext()->Shutdown();
if (GetPlatformNotificationContext())
GetPlatformNotificationContext()->Shutdown();
if (GetBackgroundSyncContext())
GetBackgroundSyncContext()->Shutdown();
if (GetPaymentAppContext())
GetPaymentAppContext()->Shutdown();
if (GetBackgroundFetchContext())
GetBackgroundFetchContext()->Shutdown();
if (GetContentIndexContext())
GetContentIndexContext()->Shutdown();
if (GetAppCacheService())
GetAppCacheService()->Shutdown();
if (GetGeneratedCodeCacheContext())
GetGeneratedCodeCacheContext()->Shutdown();
}
// static
std::unique_ptr<StoragePartitionImpl> StoragePartitionImpl::Create(
BrowserContext* context,
bool in_memory,
const base::FilePath& relative_partition_path,
const std::string& partition_domain) {
// Ensure that these methods are called on the UI thread, except for
// unittests where a UI thread might not have been created.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
!BrowserThread::IsThreadInitialized(BrowserThread::UI));
base::FilePath partition_path =
context->GetPath().Append(relative_partition_path);
return base::WrapUnique(new StoragePartitionImpl(
context, partition_path, in_memory, relative_partition_path,
partition_domain, context->GetSpecialStoragePolicy()));
}
void StoragePartitionImpl::Initialize() {
// Ensure that these methods are called on the UI thread, except for
// unittests where a UI thread might not have been created.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
!BrowserThread::IsThreadInitialized(BrowserThread::UI));
DCHECK(!initialized_);
initialized_ = true;
// All of the clients have to be created and registered with the
// QuotaManager prior to the QuotaManager being used. We do them
// all together here prior to handing out a reference to anything
// that utilizes the QuotaManager.
quota_context_ = base::MakeRefCounted<QuotaContext>(
is_in_memory_, partition_path_,
browser_context_->GetSpecialStoragePolicy(),
base::BindRepeating(&StoragePartitionImpl::GetQuotaSettings,
weak_factory_.GetWeakPtr()));
quota_manager_ = quota_context_->quota_manager();
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy =
quota_manager_->proxy();
StorageNotificationService* storage_notification_service =
browser_context_->GetStorageNotificationService();
if (storage_notification_service) {
// base::Unretained is safe to use because the BrowserContext is guaranteed
// to outlive QuotaManager. This is because BrowserContext outlives this
// StoragePartitionImpl, which destroys the QuotaManager on teardown.
base::RepeatingCallback<void(const url::Origin)>
send_notification_function = base::BindRepeating(
[](StorageNotificationService* service, const url::Origin origin) {
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&StorageNotificationService::
MaybeShowStoragePressureNotification,
base::Unretained(service), std::move(origin)));
},
base::Unretained(storage_notification_service));
quota_manager_->SetStoragePressureCallback(send_notification_function);
}
// Each consumer is responsible for registering its QuotaClient during
// its construction.
filesystem_context_ =
CreateFileSystemContext(browser_context_, partition_path_, is_in_memory_,
quota_manager_proxy.get());
database_tracker_ = base::MakeRefCounted<storage::DatabaseTracker>(
partition_path_, is_in_memory_,
browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy.get());
dom_storage_context_ = DOMStorageContextWrapper::Create(
this, browser_context_->GetSpecialStoragePolicy());
idle_manager_ = std::make_unique<IdleManagerImpl>(browser_context_);
lock_manager_ = std::make_unique<LockManager>();
scoped_refptr<ChromeBlobStorageContext> blob_context =
ChromeBlobStorageContext::GetFor(browser_context_);
native_file_system_manager_ =
base::MakeRefCounted<NativeFileSystemManagerImpl>(
filesystem_context_, blob_context,
browser_context_->GetNativeFileSystemPermissionContext(),
browser_context_->IsOffTheRecord());
mojo::PendingRemote<storage::mojom::NativeFileSystemContext>
native_file_system_context;
native_file_system_manager_->BindInternalsReceiver(
native_file_system_context.InitWithNewPipeAndPassReceiver());
base::FilePath path = is_in_memory_ ? base::FilePath() : partition_path_;
auto indexed_db_context = base::MakeRefCounted<IndexedDBContextImpl>(
path, browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy,
base::DefaultClock::GetInstance(),
ChromeBlobStorageContext::GetRemoteFor(browser_context_),
std::move(native_file_system_context),
base::CreateSingleThreadTaskRunner({BrowserThread::IO}),
/*task_runner=*/nullptr);
indexed_db_control_wrapper_ =
std::make_unique<IndexedDBControlWrapper>(std::move(indexed_db_context));
cache_storage_context_ = new CacheStorageContextImpl(browser_context_);
cache_storage_context_->Init(
path, browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy);
service_worker_context_ = new ServiceWorkerContextWrapper(browser_context_);
service_worker_context_->set_storage_partition(this);
appcache_service_ = base::MakeRefCounted<ChromeAppCacheService>(
quota_manager_proxy.get(), weak_factory_.GetWeakPtr());
dedicated_worker_service_ = std::make_unique<DedicatedWorkerServiceImpl>();
native_io_context_ = std::make_unique<NativeIOContext>(path);
shared_worker_service_ = std::make_unique<SharedWorkerServiceImpl>(
this, service_worker_context_, appcache_service_);
push_messaging_context_ = std::make_unique<PushMessagingContext>(
browser_context_, service_worker_context_);
#if !defined(OS_ANDROID)
host_zoom_level_context_.reset(new HostZoomLevelContext(
browser_context_->CreateZoomLevelDelegate(partition_path_)));
#endif // !defined(OS_ANDROID)
platform_notification_context_ = new PlatformNotificationContextImpl(
path, browser_context_, service_worker_context_);
platform_notification_context_->Initialize();
devtools_background_services_context_ =
base::MakeRefCounted<DevToolsBackgroundServicesContextImpl>(
browser_context_, service_worker_context_);
content_index_context_ = base::MakeRefCounted<ContentIndexContextImpl>(
browser_context_, service_worker_context_);
background_fetch_context_ = base::MakeRefCounted<BackgroundFetchContext>(
browser_context_, service_worker_context_, cache_storage_context_,
quota_manager_proxy, devtools_background_services_context_);
background_sync_context_ = base::MakeRefCounted<BackgroundSyncContextImpl>();
background_sync_context_->Init(service_worker_context_,
devtools_background_services_context_);
payment_app_context_ = new PaymentAppContextImpl();
payment_app_context_->Init(service_worker_context_);
broadcast_channel_provider_ = std::make_unique<BroadcastChannelProvider>();
bluetooth_allowed_devices_map_ =
std::make_unique<BluetoothAllowedDevicesMap>();
url_loader_factory_getter_ = new URLLoaderFactoryGetter();
url_loader_factory_getter_->Initialize(this);
service_worker_context_->Init(path, quota_manager_proxy.get(),
browser_context_->GetSpecialStoragePolicy(),
blob_context.get(),
url_loader_factory_getter_.get());
blob_registry_ =
BlobRegistryWrapper::Create(blob_context, filesystem_context_);
prefetch_url_loader_service_ =
base::MakeRefCounted<PrefetchURLLoaderService>(browser_context_);
cookie_store_context_ = base::MakeRefCounted<CookieStoreContext>();
// Unit tests use the Initialize() callback to crash early if restoring the
// CookieManagerStore's state from ServiceWorkerStorage fails. Production and
// browser tests rely on CookieStoreManager's well-defined behavior when
// restoring the state fails.
cookie_store_context_->Initialize(service_worker_context_, base::DoNothing());
// The Conversion Measurement API is not available in Incognito mode.
if (!is_in_memory_ &&
base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
conversion_manager_ = std::make_unique<ConversionManagerImpl>(
this, path,
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT}));
}
GeneratedCodeCacheSettings settings =
GetContentClient()->browser()->GetGeneratedCodeCacheSettings(
browser_context_);
// For Incognito mode, we should not persist anything on the disk so
// we do not create a code cache. Caching the generated code in memory
// is not useful, since V8 already maintains one copy in memory.
if (!is_in_memory_ && settings.enabled()) {
generated_code_cache_context_ =
base::MakeRefCounted<GeneratedCodeCacheContext>();
base::FilePath code_cache_path;
if (partition_domain_.empty()) {
code_cache_path = settings.path().AppendASCII("Code Cache");
} else {
// For site isolated partitions use the config directory.
code_cache_path = settings.path()
.Append(relative_partition_path_)
.AppendASCII("Code Cache");
}
DCHECK_GE(settings.size_in_bytes(), 0);
GetGeneratedCodeCacheContext()->Initialize(code_cache_path,
settings.size_in_bytes());
}
}
void StoragePartitionImpl::OnStorageServiceDisconnected() {
// This will be lazily re-bound on next use.
remote_partition_.reset();
dom_storage_context_->RecoverFromStorageServiceCrash();
for (const auto& client : dom_storage_clients_)
client.second->ResetStorageAreaAndNamespaceConnections();
}
base::FilePath StoragePartitionImpl::GetPath() {
return partition_path_;
}
network::mojom::NetworkContext* StoragePartitionImpl::GetNetworkContext() {
DCHECK(initialized_);
if (!network_context_.is_bound())
InitNetworkContext();
return network_context_.get();
}
scoped_refptr<network::SharedURLLoaderFactory>
StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcess() {
DCHECK(initialized_);
if (!shared_url_loader_factory_for_browser_process_) {
shared_url_loader_factory_for_browser_process_ =
new URLLoaderFactoryForBrowserProcess(this, false /* corb_enabled */);
}
return shared_url_loader_factory_for_browser_process_;
}
scoped_refptr<network::SharedURLLoaderFactory>
StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessWithCORBEnabled() {
DCHECK(initialized_);
if (!shared_url_loader_factory_for_browser_process_with_corb_) {
shared_url_loader_factory_for_browser_process_with_corb_ =
new URLLoaderFactoryForBrowserProcess(this, true /* corb_enabled */);
}
return shared_url_loader_factory_for_browser_process_with_corb_;
}
std::unique_ptr<network::PendingSharedURLLoaderFactory>
StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessIOThread() {
DCHECK(initialized_);
return url_loader_factory_getter_->GetPendingNetworkFactory();
}
network::mojom::CookieManager*
StoragePartitionImpl::GetCookieManagerForBrowserProcess() {
DCHECK(initialized_);
// Create the CookieManager as needed.
if (!cookie_manager_for_browser_process_ ||
!cookie_manager_for_browser_process_.is_connected()) {
// Reset |cookie_manager_for_browser_process_| before binding it again.
cookie_manager_for_browser_process_.reset();
GetNetworkContext()->GetCookieManager(
cookie_manager_for_browser_process_.BindNewPipeAndPassReceiver());
}
return cookie_manager_for_browser_process_.get();
}
void StoragePartitionImpl::CreateRestrictedCookieManager(
network::mojom::RestrictedCookieManagerRole role,
const url::Origin& origin,
const net::SiteForCookies& site_for_cookies,
const url::Origin& top_frame_origin,
bool is_service_worker,
int process_id,
int routing_id,
mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver,
mojo::PendingRemote<network::mojom::CookieAccessObserver> cookie_observer) {
DCHECK(initialized_);
if (!GetContentClient()->browser()->WillCreateRestrictedCookieManager(
role, browser_context_, origin, site_for_cookies, top_frame_origin,
is_service_worker, process_id, routing_id, &receiver)) {
GetNetworkContext()->GetRestrictedCookieManager(
std::move(receiver), role, origin, site_for_cookies, top_frame_origin,
std::move(cookie_observer));
}
}
void StoragePartitionImpl::CreateHasTrustTokensAnswerer(
mojo::PendingReceiver<network::mojom::HasTrustTokensAnswerer> receiver,
const url::Origin& top_frame_origin) {
DCHECK(initialized_);
GetNetworkContext()->GetHasTrustTokensAnswerer(std::move(receiver),
top_frame_origin);
}
storage::QuotaManager* StoragePartitionImpl::GetQuotaManager() {
DCHECK(initialized_);
return quota_manager_.get();
}
ChromeAppCacheService* StoragePartitionImpl::GetAppCacheService() {
DCHECK(initialized_);
return appcache_service_.get();
}
BackgroundSyncContextImpl* StoragePartitionImpl::GetBackgroundSyncContext() {
DCHECK(initialized_);
return background_sync_context_.get();
}
storage::FileSystemContext* StoragePartitionImpl::GetFileSystemContext() {
DCHECK(initialized_);
return filesystem_context_.get();
}
storage::DatabaseTracker* StoragePartitionImpl::GetDatabaseTracker() {
DCHECK(initialized_);
return database_tracker_.get();
}
DOMStorageContextWrapper* StoragePartitionImpl::GetDOMStorageContext() {
DCHECK(initialized_);
return dom_storage_context_.get();
}
IdleManager* StoragePartitionImpl::GetIdleManager() {
DCHECK(initialized_);
return idle_manager_.get();
}
LockManager* StoragePartitionImpl::GetLockManager() {
DCHECK(initialized_);
return lock_manager_.get();
}
storage::mojom::IndexedDBControl& StoragePartitionImpl::GetIndexedDBControl() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return *indexed_db_control_wrapper_.get();
}
IndexedDBContextImpl* StoragePartitionImpl::GetIndexedDBContextInternal() {
DCHECK(initialized_);
return indexed_db_control_wrapper_->GetIndexedDBContextInternal();
}
NativeFileSystemEntryFactory*
StoragePartitionImpl::GetNativeFileSystemEntryFactory() {
DCHECK(initialized_);
return native_file_system_manager_.get();
}
QuotaContext* StoragePartitionImpl::GetQuotaContext() {
DCHECK(initialized_);
return quota_context_.get();
}
CacheStorageContextImpl* StoragePartitionImpl::GetCacheStorageContext() {
DCHECK(initialized_);
return cache_storage_context_.get();
}
ServiceWorkerContextWrapper* StoragePartitionImpl::GetServiceWorkerContext() {
DCHECK(initialized_);
return service_worker_context_.get();
}
DedicatedWorkerServiceImpl* StoragePartitionImpl::GetDedicatedWorkerService() {
DCHECK(initialized_);
return dedicated_worker_service_.get();
}
SharedWorkerServiceImpl* StoragePartitionImpl::GetSharedWorkerService() {
DCHECK(initialized_);
return shared_worker_service_.get();
}
#if !defined(OS_ANDROID)
HostZoomMap* StoragePartitionImpl::GetHostZoomMap() {
DCHECK(initialized_);
DCHECK(host_zoom_level_context_.get());
return host_zoom_level_context_->GetHostZoomMap();
}
HostZoomLevelContext* StoragePartitionImpl::GetHostZoomLevelContext() {
DCHECK(initialized_);
return host_zoom_level_context_.get();
}
ZoomLevelDelegate* StoragePartitionImpl::GetZoomLevelDelegate() {
DCHECK(initialized_);
DCHECK(host_zoom_level_context_.get());
return host_zoom_level_context_->GetZoomLevelDelegate();
}
#endif // !defined(OS_ANDROID)
PlatformNotificationContextImpl*
StoragePartitionImpl::GetPlatformNotificationContext() {
DCHECK(initialized_);
return platform_notification_context_.get();
}
BackgroundFetchContext* StoragePartitionImpl::GetBackgroundFetchContext() {
DCHECK(initialized_);
return background_fetch_context_.get();
}
PaymentAppContextImpl* StoragePartitionImpl::GetPaymentAppContext() {
DCHECK(initialized_);
return payment_app_context_.get();
}
BroadcastChannelProvider* StoragePartitionImpl::GetBroadcastChannelProvider() {
DCHECK(initialized_);
return broadcast_channel_provider_.get();
}
BluetoothAllowedDevicesMap*
StoragePartitionImpl::GetBluetoothAllowedDevicesMap() {
DCHECK(initialized_);
return bluetooth_allowed_devices_map_.get();
}
BlobRegistryWrapper* StoragePartitionImpl::GetBlobRegistry() {
DCHECK(initialized_);
return blob_registry_.get();
}
PrefetchURLLoaderService* StoragePartitionImpl::GetPrefetchURLLoaderService() {
DCHECK(initialized_);
return prefetch_url_loader_service_.get();
}
CookieStoreContext* StoragePartitionImpl::GetCookieStoreContext() {
DCHECK(initialized_);
return cookie_store_context_.get();
}
GeneratedCodeCacheContext*
StoragePartitionImpl::GetGeneratedCodeCacheContext() {
DCHECK(initialized_);
return generated_code_cache_context_.get();
}
DevToolsBackgroundServicesContextImpl*
StoragePartitionImpl::GetDevToolsBackgroundServicesContext() {
DCHECK(initialized_);
return devtools_background_services_context_.get();
}
NativeFileSystemManagerImpl*
StoragePartitionImpl::GetNativeFileSystemManager() {
DCHECK(initialized_);
return native_file_system_manager_.get();
}
ConversionManagerImpl* StoragePartitionImpl::GetConversionManager() {
DCHECK(initialized_);
return conversion_manager_.get();
}
ContentIndexContextImpl* StoragePartitionImpl::GetContentIndexContext() {
DCHECK(initialized_);
return content_index_context_.get();
}
NativeIOContext* StoragePartitionImpl::GetNativeIOContext() {
DCHECK(initialized_);
return native_io_context_.get();
}
leveldb_proto::ProtoDatabaseProvider*
StoragePartitionImpl::GetProtoDatabaseProvider() {
if (!proto_database_provider_) {
proto_database_provider_ =
std::make_unique<leveldb_proto::ProtoDatabaseProvider>(partition_path_);
}
return proto_database_provider_.get();
}
void StoragePartitionImpl::SetProtoDatabaseProvider(
std::unique_ptr<leveldb_proto::ProtoDatabaseProvider> proto_db_provider) {
DCHECK(!proto_database_provider_);
proto_database_provider_ = std::move(proto_db_provider);
}
void StoragePartitionImpl::OpenLocalStorage(
const url::Origin& origin,
mojo::PendingReceiver<blink::mojom::StorageArea> receiver) {
DCHECK(initialized_);
const auto& security_policy_handle = dom_storage_receivers_.current_context();
if (!security_policy_handle->CanAccessDataForOrigin(origin)) {
SYSLOG(WARNING) << "Killing renderer: illegal localStorage request.";
dom_storage_receivers_.ReportBadMessage(
"Access denied for localStorage request");
return;
}
dom_storage_context_->OpenLocalStorage(origin, std::move(receiver));
}
void StoragePartitionImpl::BindSessionStorageNamespace(
const std::string& namespace_id,
mojo::PendingReceiver<blink::mojom::SessionStorageNamespace> receiver) {
DCHECK(initialized_);
dom_storage_context_->BindNamespace(
namespace_id, dom_storage_receivers_.GetBadMessageCallback(),
std::move(receiver));
}
void StoragePartitionImpl::BindSessionStorageArea(
const url::Origin& origin,
const std::string& namespace_id,
mojo::PendingReceiver<blink::mojom::StorageArea> receiver) {
DCHECK(initialized_);
ChildProcessSecurityPolicyImpl::Handle security_policy_handle =
dom_storage_receivers_.current_context()->Duplicate();
dom_storage_context_->BindStorageArea(
std::move(security_policy_handle), origin, namespace_id,
dom_storage_receivers_.GetBadMessageCallback(), std::move(receiver));
}
void StoragePartitionImpl::OnAuthRequired(
const base::Optional<base::UnguessableToken>& window_id,
int32_t process_id,
int32_t routing_id,
uint32_t request_id,
const GURL& url,
bool first_auth_attempt,
const net::AuthChallengeInfo& auth_info,
network::mojom::URLResponseHeadPtr head,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder) {
if (window_id) {
if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) {
OnAuthRequiredContinuationForWindowId(
*window_id, process_id, routing_id, request_id, url,
first_auth_attempt, auth_info, std::move(head),
std::move(auth_challenge_responder),
GetIsMainFrameFromRegistry(*window_id));
} else {
base::PostTaskAndReplyWithResult(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&GetIsMainFrameFromRegistry, *window_id),
base::BindOnce(&OnAuthRequiredContinuationForWindowId, *window_id,
process_id, routing_id, request_id, url,
first_auth_attempt, auth_info, std::move(head),
std::move(auth_challenge_responder)));
}
return;
}
OnAuthRequiredContinuation(process_id, routing_id, request_id, url,
IsMainFrameRequest(process_id, routing_id),
first_auth_attempt, auth_info, std::move(head),
std::move(auth_challenge_responder), {});
}
void StoragePartitionImpl::OnCertificateRequested(
const base::Optional<base::UnguessableToken>& window_id,
int32_t process_id,
int32_t routing_id,
uint32_t request_id,
const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
mojo::PendingRemote<network::mojom::ClientCertificateResponder>
cert_responder) {
// Use |window_id| if it's provided.
if (window_id) {
if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) {
OnCertificateRequestedContinuation(
process_id, routing_id, request_id, cert_info,
std::move(cert_responder), GetWebContentsFromRegistry(*window_id));
} else {
base::PostTaskAndReplyWithResult(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&GetWebContentsFromRegistry, *window_id),
base::BindOnce(&OnCertificateRequestedContinuation, process_id,
routing_id, request_id, cert_info,
std::move(cert_responder)));
}
return;
}
OnCertificateRequestedContinuation(process_id, routing_id, request_id,
cert_info, std::move(cert_responder), {});
}
void StoragePartitionImpl::OnSSLCertificateError(
int32_t process_id,
int32_t routing_id,
const GURL& url,
int net_error,
const net::SSLInfo& ssl_info,
bool fatal,
OnSSLCertificateErrorCallback response) {
SSLErrorDelegate* delegate =
new SSLErrorDelegate(std::move(response)); // deletes self
bool is_main_frame_request = IsMainFrameRequest(process_id, routing_id);
SSLManager::OnSSLCertificateError(
delegate->GetWeakPtr(), is_main_frame_request, url,
GetWebContents(process_id, routing_id), net_error, ssl_info, fatal);
}
void StoragePartitionImpl::OnFileUploadRequested(
int32_t process_id,
bool async,
const std::vector<base::FilePath>& file_paths,
OnFileUploadRequestedCallback callback) {
NetworkContextOnFileUploadRequested(process_id, async, file_paths,
std::move(callback));
}
void StoragePartitionImpl::OnCanSendReportingReports(
const std::vector<url::Origin>& origins,
OnCanSendReportingReportsCallback callback) {
DCHECK(initialized_);
PermissionController* permission_controller =
BrowserContext::GetPermissionController(browser_context_);
DCHECK(permission_controller);
std::vector<url::Origin> origins_out;
for (auto& origin : origins) {
GURL origin_url = origin.GetURL();
bool allowed = permission_controller->GetPermissionStatus(
PermissionType::BACKGROUND_SYNC, origin_url,
origin_url) == blink::mojom::PermissionStatus::GRANTED;
if (allowed)
origins_out.push_back(origin);
}
std::move(callback).Run(origins_out);
}
void StoragePartitionImpl::OnCanSendDomainReliabilityUpload(
const GURL& origin,
OnCanSendDomainReliabilityUploadCallback callback) {
DCHECK(initialized_);
PermissionController* permission_controller =
BrowserContext::GetPermissionController(browser_context_);
std::move(callback).Run(
permission_controller->GetPermissionStatus(
content::PermissionType::BACKGROUND_SYNC, origin, origin) ==
blink::mojom::PermissionStatus::GRANTED);
}
void StoragePartitionImpl::OnClearSiteData(int32_t process_id,
int32_t routing_id,
const GURL& url,
const std::string& header_value,
int load_flags,
OnClearSiteDataCallback callback) {
DCHECK(initialized_);
auto browser_context_getter = base::BindRepeating(
GetBrowserContextFromStoragePartition, weak_factory_.GetWeakPtr());
auto web_contents_getter = base::BindRepeating(
GetWebContentsForStoragePartition, process_id, routing_id);
ClearSiteDataHandler::HandleHeader(browser_context_getter,
web_contents_getter, url, header_value,
load_flags, std::move(callback));
}
#if defined(OS_ANDROID)
void StoragePartitionImpl::OnGenerateHttpNegotiateAuthToken(
const std::string& server_auth_token,
bool can_delegate,
const std::string& auth_negotiate_android_account_type,
const std::string& spn,
OnGenerateHttpNegotiateAuthTokenCallback callback) {
// The callback takes ownership of these unique_ptrs and destroys them when
// run.
auto prefs = std::make_unique<net::HttpAuthPreferences>();
prefs->set_auth_android_negotiate_account_type(
auth_negotiate_android_account_type);
auto auth_negotiate =
std::make_unique<net::android::HttpAuthNegotiateAndroid>(prefs.get());
net::android::HttpAuthNegotiateAndroid* auth_negotiate_raw =
auth_negotiate.get();
auth_negotiate->set_server_auth_token(server_auth_token);
auth_negotiate->set_can_delegate(can_delegate);
auto auth_token = std::make_unique<std::string>();
auth_negotiate_raw->GenerateAuthTokenAndroid(
nullptr, spn, std::string(), auth_token.get(),
base::BindOnce(&FinishGenerateNegotiateAuthToken,
std::move(auth_negotiate), std::move(auth_token),
std::move(prefs), std::move(callback)));
}
#endif
#if defined(OS_CHROMEOS)
void StoragePartitionImpl::OnTrustAnchorUsed() {
GetContentClient()->browser()->OnTrustAnchorUsed(browser_context_);
}
#endif
void StoragePartitionImpl::ClearDataImpl(
uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
const GURL& storage_origin,
OriginMatcherFunction origin_matcher,
CookieDeletionFilterPtr cookie_deletion_filter,
bool perform_storage_cleanup,
const base::Time begin,
const base::Time end,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DataDeletionHelper* helper = new DataDeletionHelper(
remove_mask, quota_storage_remove_mask,
base::BindOnce(&StoragePartitionImpl::DeletionHelperDone,
weak_factory_.GetWeakPtr(), std::move(callback)));
// |helper| deletes itself when done in
// DataDeletionHelper::DecrementTaskCount().
deletion_helpers_running_++;
helper->ClearDataOnUIThread(
storage_origin, std::move(origin_matcher),
std::move(cookie_deletion_filter), GetPath(), dom_storage_context_.get(),
quota_manager_.get(), special_storage_policy_.get(),
filesystem_context_.get(), GetCookieManagerForBrowserProcess(),
conversion_manager_.get(), perform_storage_cleanup, begin, end);
}
void StoragePartitionImpl::DeletionHelperDone(base::OnceClosure callback) {
std::move(callback).Run();
deletion_helpers_running_--;
if (on_deletion_helpers_done_callback_ && deletion_helpers_running_ == 0) {
// Notify tests that storage partition is done with all deletion tasks.
std::move(on_deletion_helpers_done_callback_).Run();
}
}
void StoragePartitionImpl::QuotaManagedDataDeletionHelper::
IncrementTaskCountOnIO() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
++task_count_;
}
void StoragePartitionImpl::QuotaManagedDataDeletionHelper::
DecrementTaskCountOnIO() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_GT(task_count_, 0);
--task_count_;
if (task_count_)
return;
std::move(callback_).Run();
delete this;
}
void StoragePartitionImpl::QuotaManagedDataDeletionHelper::ClearDataOnIOThread(
const scoped_refptr<storage::QuotaManager>& quota_manager,
const base::Time begin,
const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup) {
IncrementTaskCountOnIO();
base::RepeatingClosure decrement_callback = base::BindRepeating(
&QuotaManagedDataDeletionHelper::DecrementTaskCountOnIO,
base::Unretained(this));
if (quota_storage_remove_mask_ & QUOTA_MANAGED_STORAGE_MASK_PERSISTENT) {
IncrementTaskCountOnIO();
// Ask the QuotaManager for all origins with persistent quota modified
// within the user-specified timeframe, and deal with the resulting set in
// ClearQuotaManagedOriginsOnIOThread().
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kPersistent, begin,
base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
base::Unretained(this), base::RetainedRef(quota_manager),
special_storage_policy, origin_matcher,
perform_storage_cleanup, decrement_callback));
}
// Do the same for temporary quota.
if (quota_storage_remove_mask_ & QUOTA_MANAGED_STORAGE_MASK_TEMPORARY) {
IncrementTaskCountOnIO();
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kTemporary, begin,
base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
base::Unretained(this), base::RetainedRef(quota_manager),
special_storage_policy, origin_matcher,
perform_storage_cleanup, decrement_callback));
}
// Do the same for syncable quota.
if (quota_storage_remove_mask_ & QUOTA_MANAGED_STORAGE_MASK_SYNCABLE) {
IncrementTaskCountOnIO();
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kSyncable, begin,
base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
base::Unretained(this), base::RetainedRef(quota_manager),
special_storage_policy, std::move(origin_matcher),
perform_storage_cleanup, decrement_callback));
}
DecrementTaskCountOnIO();
}
void StoragePartitionImpl::QuotaManagedDataDeletionHelper::
ClearOriginsOnIOThread(
storage::QuotaManager* quota_manager,
const scoped_refptr<storage::SpecialStoragePolicy>&
special_storage_policy,
StoragePartition::OriginMatcherFunction origin_matcher,
bool perform_storage_cleanup,
base::OnceClosure callback,
const std::set<url::Origin>& origins,
blink::mojom::StorageType quota_storage_type) {
// The QuotaManager manages all storage other than cookies, LocalStorage,
// and SessionStorage. This loop wipes out most HTML5 storage for the given
// origins.
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (origins.empty()) {
std::move(callback).Run();
return;
}
storage::QuotaClientTypes quota_client_types =
StoragePartitionImpl::GenerateQuotaClientTypes(remove_mask_);
// The logic below (via CheckQuotaManagedDataDeletionStatus) only
// invokes the callback when all processing is complete.
base::RepeatingClosure done_callback = base::AdaptCallbackForRepeating(
perform_storage_cleanup
? base::BindOnce(&PerformQuotaManagerStorageCleanup,
base::WrapRefCounted(quota_manager),
quota_storage_type, quota_client_types,
std::move(callback))
: std::move(callback));
size_t* deletion_task_count = new size_t(0u);
(*deletion_task_count)++;
for (const auto& origin : origins) {
// TODO(mkwst): Clean this up, it's slow. http://crbug.com/130746
if (storage_origin_.has_value() && origin != *storage_origin_)
continue;
if (origin_matcher &&
!origin_matcher.Run(origin, special_storage_policy.get())) {
continue;
}
(*deletion_task_count)++;
quota_manager->DeleteOriginData(
origin, quota_storage_type, quota_client_types,
base::BindOnce(&OnQuotaManagedOriginDeleted, origin, quota_storage_type,
deletion_task_count, done_callback));
}
(*deletion_task_count)--;
CheckQuotaManagedDataDeletionStatus(deletion_task_count, done_callback);
}
base::OnceClosure
StoragePartitionImpl::DataDeletionHelper::CreateTaskCompletionClosure(
TracingDataType data_type) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
++task_count_;
static int tracing_id = 0;
TRACE_EVENT_ASYNC_BEGIN1("browsing_data", "StoragePartitionImpl",
++tracing_id, "data_type",
static_cast<int>(data_type));
return base::BindOnce(
&StoragePartitionImpl::DataDeletionHelper::OnTaskComplete,
base::Unretained(this), tracing_id);
}
void StoragePartitionImpl::DataDeletionHelper::OnTaskComplete(int tracing_id) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
base::PostTask(FROM_HERE, {BrowserThread::UI},
base::BindOnce(&DataDeletionHelper::OnTaskComplete,
base::Unretained(this), tracing_id));
return;
}
DCHECK_GT(task_count_, 0);
--task_count_;
TRACE_EVENT_ASYNC_END0("browsing_data", "StoragePartitionImpl", tracing_id);
if (!task_count_) {
std::move(callback_).Run();
delete this;
}
}
void StoragePartitionImpl::DataDeletionHelper::ClearDataOnUIThread(
const GURL& storage_origin,
OriginMatcherFunction origin_matcher,
CookieDeletionFilterPtr cookie_deletion_filter,
const base::FilePath& path,
DOMStorageContextWrapper* dom_storage_context,
storage::QuotaManager* quota_manager,
storage::SpecialStoragePolicy* special_storage_policy,
storage::FileSystemContext* filesystem_context,
network::mojom::CookieManager* cookie_manager,
ConversionManagerImpl* conversion_manager,
bool perform_storage_cleanup,
const base::Time begin,
const base::Time end) {
DCHECK_NE(remove_mask_, 0u);
DCHECK(callback_);
// Only one of |storage_origin| and |origin_matcher| can be set.
DCHECK(storage_origin.is_empty() || origin_matcher.is_null());
base::ScopedClosureRunner synchronous_clear_operations(
CreateTaskCompletionClosure(TracingDataType::kSynchronous));
scoped_refptr<storage::SpecialStoragePolicy> storage_policy_ref =
base::WrapRefCounted(special_storage_policy);
if (remove_mask_ & REMOVE_DATA_MASK_COOKIES) {
// The CookieDeletionFilter has a redundant time interval to |begin| and
// |end|. Ensure that the filter has no time interval specified to help
// callers detect when they are using the wrong interval values.
DCHECK(!cookie_deletion_filter->created_after_time.has_value());
DCHECK(!cookie_deletion_filter->created_before_time.has_value());
if (!begin.is_null())
cookie_deletion_filter->created_after_time = begin;
if (!end.is_null())
cookie_deletion_filter->created_before_time = end;
cookie_manager->DeleteCookies(
std::move(cookie_deletion_filter),
base::BindOnce(
&OnClearedCookies,
// Handle the cookie store being destroyed and the callback thus not
// being called.
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
CreateTaskCompletionClosure(TracingDataType::kCookies))));
}
if (remove_mask_ & REMOVE_DATA_MASK_INDEXEDDB ||
remove_mask_ & REMOVE_DATA_MASK_WEBSQL ||
remove_mask_ & REMOVE_DATA_MASK_APPCACHE ||
remove_mask_ & REMOVE_DATA_MASK_FILE_SYSTEMS ||
remove_mask_ & REMOVE_DATA_MASK_SERVICE_WORKERS ||
remove_mask_ & REMOVE_DATA_MASK_CACHE_STORAGE) {
base::PostTask(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&DataDeletionHelper::ClearQuotaManagedDataOnIOThread,
base::Unretained(this),
base::WrapRefCounted(quota_manager), begin,
storage_origin, storage_policy_ref, origin_matcher,
perform_storage_cleanup,
CreateTaskCompletionClosure(TracingDataType::kQuota)));
}
if (remove_mask_ & REMOVE_DATA_MASK_LOCAL_STORAGE) {
ClearLocalStorageOnUIThread(
base::WrapRefCounted(dom_storage_context), storage_policy_ref,
origin_matcher, storage_origin, perform_storage_cleanup, begin, end,
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
CreateTaskCompletionClosure(TracingDataType::kLocalStorage)));
// ClearDataImpl cannot clear session storage data when a particular origin
// is specified. Therefore we ignore clearing session storage in this case.
// TODO(lazyboy): Fix.
if (storage_origin.is_empty()) {
// TODO(crbug.com/960325): Sometimes SessionStorage fails to call its
// callback. Figure out why.
ClearSessionStorageOnUIThread(
base::WrapRefCounted(dom_storage_context), storage_policy_ref,
origin_matcher, perform_storage_cleanup,
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
CreateTaskCompletionClosure(TracingDataType::kSessionStorage)));
}
}
if (remove_mask_ & REMOVE_DATA_MASK_SHADER_CACHE) {
base::PostTask(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&ClearShaderCacheOnIOThread, path, begin, end,
CreateTaskCompletionClosure(
TracingDataType::kShaderCache)));
}
auto filter = CreateGenericOriginMatcher(storage_origin, origin_matcher,
storage_policy_ref);
if (conversion_manager && (remove_mask_ & REMOVE_DATA_MASK_CONVERSIONS)) {
conversion_manager->ClearData(
begin, end, std::move(filter),
CreateTaskCompletionClosure(TracingDataType::kConversions));
}
#if BUILDFLAG(ENABLE_PLUGINS)
if (remove_mask_ & REMOVE_DATA_MASK_PLUGIN_PRIVATE_DATA) {
filesystem_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(
&ClearPluginPrivateDataOnFileTaskRunner,
base::WrapRefCounted(filesystem_context), storage_origin,
origin_matcher, storage_policy_ref, begin, end,
CreateTaskCompletionClosure(TracingDataType::kPluginPrivate)));
}
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void StoragePartitionImpl::ClearDataForOrigin(
uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
const GURL& storage_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(initialized_);
CookieDeletionFilterPtr deletion_filter = CookieDeletionFilter::New();
if (!storage_origin.host().empty())
deletion_filter->host_name = storage_origin.host();
ClearDataImpl(remove_mask, quota_storage_remove_mask, storage_origin,
OriginMatcherFunction(), std::move(deletion_filter), false,
base::Time(), base::Time::Max(), base::DoNothing());
}
void StoragePartitionImpl::ClearData(uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
const GURL& storage_origin,
const base::Time begin,
const base::Time end,
base::OnceClosure callback) {
DCHECK(initialized_);
CookieDeletionFilterPtr deletion_filter = CookieDeletionFilter::New();
if (!storage_origin.host().empty())
deletion_filter->host_name = storage_origin.host();
bool perform_storage_cleanup =
begin.is_null() && end.is_max() && storage_origin.is_empty();
ClearDataImpl(remove_mask, quota_storage_remove_mask, storage_origin,
OriginMatcherFunction(), std::move(deletion_filter),
perform_storage_cleanup, begin, end, std::move(callback));
}
void StoragePartitionImpl::ClearData(
uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
OriginMatcherFunction origin_matcher,
network::mojom::CookieDeletionFilterPtr cookie_deletion_filter,
bool perform_storage_cleanup,
const base::Time begin,
const base::Time end,
base::OnceClosure callback) {
DCHECK(initialized_);
ClearDataImpl(remove_mask, quota_storage_remove_mask, GURL(),
std::move(origin_matcher), std::move(cookie_deletion_filter),
perform_storage_cleanup, begin, end, std::move(callback));
}
void StoragePartitionImpl::ClearCodeCaches(
const base::Time begin,
const base::Time end,
const base::RepeatingCallback<bool(const GURL&)>& url_matcher,
base::OnceClosure callback) {
DCHECK(initialized_);
// StoragePartitionCodeCacheDataRemover deletes itself when it is done.
StoragePartitionCodeCacheDataRemover::Create(this, url_matcher, begin, end)
->Remove(std::move(callback));
}
void StoragePartitionImpl::Flush() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(initialized_);
if (GetDOMStorageContext())
GetDOMStorageContext()->Flush();
}
void StoragePartitionImpl::ResetURLLoaderFactories() {
DCHECK(initialized_);
GetNetworkContext()->ResetURLLoaderFactories();
url_loader_factory_for_browser_process_.reset();
url_loader_factory_for_browser_process_with_corb_.reset();
url_loader_factory_getter_->Initialize(this);
}
void StoragePartitionImpl::ClearBluetoothAllowedDevicesMapForTesting() {
DCHECK(initialized_);
bluetooth_allowed_devices_map_->Clear();
}
void StoragePartitionImpl::FlushNetworkInterfaceForTesting() {
DCHECK(initialized_);
DCHECK(network_context_);
network_context_.FlushForTesting();
if (url_loader_factory_for_browser_process_)
url_loader_factory_for_browser_process_.FlushForTesting();
if (url_loader_factory_for_browser_process_with_corb_)
url_loader_factory_for_browser_process_with_corb_.FlushForTesting();
if (cookie_manager_for_browser_process_)
cookie_manager_for_browser_process_.FlushForTesting();
if (origin_policy_manager_for_browser_process_)
origin_policy_manager_for_browser_process_.FlushForTesting();
}
void StoragePartitionImpl::WaitForDeletionTasksForTesting() {
DCHECK(initialized_);
if (deletion_helpers_running_) {
base::RunLoop loop;
on_deletion_helpers_done_callback_ = loop.QuitClosure();
loop.Run();
}
}
void StoragePartitionImpl::WaitForCodeCacheShutdownForTesting() {
DCHECK(initialized_);
if (generated_code_cache_context_) {
// If this is still running its initialization task it may check
// enabled features on a sequenced worker pool which could race
// between ScopedFeatureList destruction.
base::RunLoop loop;
generated_code_cache_context_->generated_js_code_cache()->GetBackend(
base::BindOnce([](base::OnceClosure quit,
disk_cache::Backend*) { std::move(quit).Run(); },
loop.QuitClosure()));
loop.Run();
generated_code_cache_context_->Shutdown();
}
}
void StoragePartitionImpl::SetNetworkContextForTesting(
mojo::PendingRemote<network::mojom::NetworkContext>
network_context_remote) {
network_context_.reset();
network_context_.Bind(std::move(network_context_remote));
}
BrowserContext* StoragePartitionImpl::browser_context() const {
return browser_context_;
}
storage::mojom::Partition* StoragePartitionImpl::GetStorageServicePartition() {
if (!remote_partition_) {
base::Optional<base::FilePath> storage_path;
if (!is_in_memory_) {
storage_path =
browser_context_->GetPath().Append(relative_partition_path_);
}
GetStorageServiceRemote()->BindPartition(
storage_path, remote_partition_.BindNewPipeAndPassReceiver());
remote_partition_.set_disconnect_handler(
base::BindOnce(&StoragePartitionImpl::OnStorageServiceDisconnected,
base::Unretained(this)));
}
return remote_partition_.get();
}
// static
mojo::Remote<storage::mojom::StorageService>&
StoragePartitionImpl::GetStorageServiceForTesting() {
return GetStorageServiceRemote();
}
mojo::ReceiverId StoragePartitionImpl::BindDomStorage(
int process_id,
mojo::PendingReceiver<blink::mojom::DomStorage> receiver,
mojo::PendingRemote<blink::mojom::DomStorageClient> client) {
DCHECK(initialized_);
auto handle =
ChildProcessSecurityPolicyImpl::GetInstance()->CreateHandle(process_id);
mojo::ReceiverId id = dom_storage_receivers_.Add(
this, std::move(receiver),
std::make_unique<SecurityPolicyHandle>(std::move(handle)));
dom_storage_clients_[id].Bind(std::move(client));
return id;
}
void StoragePartitionImpl::UnbindDomStorage(mojo::ReceiverId receiver_id) {
DCHECK(initialized_);
dom_storage_receivers_.Remove(receiver_id);
dom_storage_clients_.erase(receiver_id);
}
void StoragePartitionImpl::OverrideQuotaManagerForTesting(
storage::QuotaManager* quota_manager) {
DCHECK(initialized_);
quota_manager_ = quota_manager;
}
void StoragePartitionImpl::OverrideSpecialStoragePolicyForTesting(
storage::SpecialStoragePolicy* special_storage_policy) {
DCHECK(initialized_);
special_storage_policy_ = special_storage_policy;
}
void StoragePartitionImpl::ShutdownBackgroundSyncContextForTesting() {
DCHECK(initialized_);
if (GetBackgroundSyncContext())
GetBackgroundSyncContext()->Shutdown();
}
void StoragePartitionImpl::OverrideBackgroundSyncContextForTesting(
BackgroundSyncContextImpl* background_sync_context) {
DCHECK(initialized_);
DCHECK(!GetBackgroundSyncContext() ||
!GetBackgroundSyncContext()->background_sync_manager());
background_sync_context_ = background_sync_context;
}
void StoragePartitionImpl::OverrideSharedWorkerServiceForTesting(
std::unique_ptr<SharedWorkerServiceImpl> shared_worker_service) {
DCHECK(initialized_);
shared_worker_service_ = std::move(shared_worker_service);
}
void StoragePartitionImpl::GetQuotaSettings(
storage::OptionalQuotaSettingsCallback callback) {
if (g_test_quota_settings) {
// For debugging tests harness can inject settings.
std::move(callback).Run(*g_test_quota_settings);
return;
}
#if defined(USE_NEVA_APPRUNTIME)
if (GetContentClient()->browser()->HasQuotaSettings()) {
GetContentClient()->browser()->GetQuotaSettings(browser_context_, this,
std::move(callback));
return;
}
#endif
storage::GetNominalDynamicSettings(
GetPath(), browser_context_->IsOffTheRecord(),
storage::GetDefaultDeviceInfoHelper(), std::move(callback));
}
void StoragePartitionImpl::InitNetworkContext() {
network::mojom::NetworkContextParamsPtr context_params =
network::mojom::NetworkContextParams::New();
network::mojom::CertVerifierCreationParamsPtr cert_verifier_creation_params =
network::mojom::CertVerifierCreationParams::New();
GetContentClient()->browser()->ConfigureNetworkContextParams(
browser_context_, is_in_memory_, relative_partition_path_,
context_params.get(), cert_verifier_creation_params.get());
DCHECK(!context_params->cert_verifier_creation_params)
<< "|cert_verifier_creation_params| should not be set in the "
"NetworkContextParams, as they will eventually be removed when the "
"CertVerifierService ships.";
context_params->cert_verifier_creation_params =
std::move(cert_verifier_creation_params);
network_context_.reset();
GetNetworkService()->CreateNetworkContext(
network_context_.BindNewPipeAndPassReceiver(), std::move(context_params));
DCHECK(network_context_);
network_context_client_receiver_.reset();
network_context_->SetClient(
network_context_client_receiver_.BindNewPipeAndPassRemote());
network_context_.set_disconnect_handler(base::BindOnce(
&StoragePartitionImpl::InitNetworkContext, weak_factory_.GetWeakPtr()));
}
network::mojom::URLLoaderFactory*
StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessInternal(
bool corb_enabled) {
auto& url_loader_factory =
corb_enabled ? url_loader_factory_for_browser_process_with_corb_
: url_loader_factory_for_browser_process_;
auto& is_test_url_loader_factory =
corb_enabled ? is_test_url_loader_factory_for_browser_process_with_corb_
: is_test_url_loader_factory_for_browser_process_;
// Create the URLLoaderFactory as needed, but make sure not to reuse a
// previously created one if the test override has changed.
if (url_loader_factory && url_loader_factory.is_connected() &&
is_test_url_loader_factory != !GetCreateURLLoaderFactoryCallback()) {
return url_loader_factory.get();
}
network::mojom::URLLoaderFactoryParamsPtr params =
network::mojom::URLLoaderFactoryParams::New();
params->process_id = network::mojom::kBrowserProcessId;
params->automatically_assign_isolation_info = true;
params->is_corb_enabled = corb_enabled;
// Corb requests are likely made on behalf of untrusted renderers.
if (!corb_enabled)
params->is_trusted = true;
params->disable_web_security =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableWebSecurity);
url_loader_factory.reset();
if (!GetCreateURLLoaderFactoryCallback()) {
GetNetworkContext()->CreateURLLoaderFactory(
url_loader_factory.BindNewPipeAndPassReceiver(), std::move(params));
is_test_url_loader_factory = false;
return url_loader_factory.get();
}
mojo::PendingRemote<network::mojom::URLLoaderFactory> original_factory;
GetNetworkContext()->CreateURLLoaderFactory(
original_factory.InitWithNewPipeAndPassReceiver(), std::move(params));
url_loader_factory.Bind(
GetCreateURLLoaderFactoryCallback().Run(std::move(original_factory)));
is_test_url_loader_factory = true;
return url_loader_factory.get();
}
network::mojom::OriginPolicyManager*
StoragePartitionImpl::GetOriginPolicyManagerForBrowserProcess() {
DCHECK(initialized_);
if (!origin_policy_manager_for_browser_process_ ||
!origin_policy_manager_for_browser_process_.is_connected()) {
GetNetworkContext()->GetOriginPolicyManager(
origin_policy_manager_for_browser_process_
.BindNewPipeAndPassReceiver());
}
return origin_policy_manager_for_browser_process_.get();
}
void StoragePartitionImpl::SetOriginPolicyManagerForBrowserProcessForTesting(
mojo::PendingRemote<network::mojom::OriginPolicyManager>
test_origin_policy_manager) {
DCHECK(initialized_);
origin_policy_manager_for_browser_process_.Bind(
std::move(test_origin_policy_manager));
}
void StoragePartitionImpl::
ResetOriginPolicyManagerForBrowserProcessForTesting() {
DCHECK(initialized_);
origin_policy_manager_for_browser_process_.reset();
}
void StoragePartition::SetDefaultQuotaSettingsForTesting(
const storage::QuotaSettings* settings) {
g_test_quota_settings = settings;
}
bool StoragePartition::IsAppCacheEnabled() {
return base::FeatureList::IsEnabled(blink::features::kAppCache);
}
mojo::PendingRemote<network::mojom::CookieAccessObserver>
StoragePartitionImpl::CreateCookieAccessObserverForServiceWorker() {
mojo::PendingRemote<network::mojom::CookieAccessObserver> remote;
service_worker_cookie_observers_.Add(
std::make_unique<ServiceWorkerCookieAccessObserver>(this),
remote.InitWithNewPipeAndPassReceiver());
return remote;
}
} // namespace content
| [
"[email protected]"
]
| |
15252d0ac83c208bb51af1f3404c2b4afb24475b | 67e24dd384bdf75beb0f4d21eec362da0af6d89d | /Arrays.cpp | e91213f6d20f0f066d2374bd0fb2af8955c55918 | []
| no_license | OdessaRadio/CPP-From-Beginner-to-Expert | 0b8cc32eaa0179b7b161645d870a789df9e926cb | 18a46624e9c41f626533562b5daa0d4e1c30bc56 | refs/heads/master | 2022-12-28T23:27:34.094170 | 2020-10-13T08:48:57 | 2020-10-13T08:48:57 | 296,020,264 | 0 | 0 | null | 2020-10-07T06:46:50 | 2020-09-16T12:04:40 | C++ | UTF-8 | C++ | false | false | 449 | cpp | # include <iostream>
using namespace std;
//ARRAYS
//Ex.1
main()
{
int x,y;
int wArray[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 9},
{10, 11, 12, 14}};
cout << "Please, set the position of the element to show x,y" << endl;;
cout << "Set x position: ";
cin >> x;
cout << "Set y position: ";
cin >> y;
cout << "Selected array value is: " << wArray[x-1][y-1] << endl;
}
| [
"[email protected]"
]
| |
d620fde35c87f6c3222b8ded54a6aebbefc22d55 | 786de89be635eb21295070a6a3452f3a7fe6712c | /pypdsdata/tags/V00-00-46/pyext/types/bld/BldDataPimV1.cpp | d503d144b0de5ed45b18707fcf096f32da0566c8 | []
| no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | cpp | //--------------------------------------------------------------------------
// File and Version Information:
// $Id$
//
// Description:
// Class BldDataPimV1...
//
// Author List:
// Andrei Salnikov
//
//------------------------------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "BldDataPimV1.h"
//-----------------
// C/C++ Headers --
//-----------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "../../Exception.h"
#include "../TypeLib.h"
#include "../pulnix/TM6740ConfigV2.h"
#include "../lusi/PimImageConfigV1.h"
#include "../camera/FrameV1.h"
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
namespace {
// methods
PyObject* camConfig( PyObject* self, void* );
PyObject* pimConfig( PyObject* self, void* );
PyObject* frame( PyObject* self, void* );
PyObject* _repr( PyObject *self );
PyGetSetDef getset[] = {
{"camConfig", camConfig, 0, "", 0},
{"pimConfig", pimConfig, 0, "", 0},
{"frame", frame, 0, "", 0},
{0, 0, 0, 0, 0}
};
char typedoc[] = "Python class wrapping C++ Pds::BldDataPimV1 class.";
}
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
void
pypdsdata::BldDataPimV1::initType( PyObject* module )
{
PyTypeObject* type = BaseType::typeObject() ;
type->tp_doc = ::typedoc;
type->tp_getset = ::getset;
type->tp_str = _repr;
type->tp_repr = _repr;
BaseType::initType( "BldDataPimV1", module );
}
namespace {
PyObject*
camConfig( PyObject* self, void* )
{
Pds::BldDataPimV1* pdsObj = pypdsdata::BldDataPimV1::pdsObject(self);
if(not pdsObj) return 0;
return pypdsdata::Pulnix::TM6740ConfigV2::PyObject_FromPds(&pdsObj->camConfig,
self, sizeof(pdsObj->camConfig));
}
PyObject*
pimConfig( PyObject* self, void* )
{
Pds::BldDataPimV1* pdsObj = pypdsdata::BldDataPimV1::pdsObject(self);
if(not pdsObj) return 0;
return pypdsdata::Lusi::PimImageConfigV1::PyObject_FromPds(&pdsObj->pimConfig,
self, sizeof(pdsObj->pimConfig));
}
PyObject*
frame( PyObject* self, void* )
{
Pds::BldDataPimV1* pdsObj = pypdsdata::BldDataPimV1::pdsObject(self);
if(not pdsObj) return 0;
return pypdsdata::Camera::FrameV1::PyObject_FromPds(&pdsObj->frame,
self, sizeof(pdsObj->frame));
}
PyObject*
_repr( PyObject *self )
{
Pds::BldDataPimV1* pdsObj = pypdsdata::BldDataPimV1::pdsObject(self);
if(not pdsObj) return 0;
char buf[96];
snprintf( buf, sizeof buf, "BldDataPimV1(@%p)", pdsObj );
return PyString_FromString( buf );
}
}
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
]
| [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
7787b8d6e6b23100753f60c482674c40d63c91e2 | 271c0013bb2399942472720cb6940967f7b47474 | /OPENGL_SCALARFIELD.cpp | ca3055cdc3e531c71f1fd97332a913a182c4911d | []
| no_license | ByungJoonLee/Fluid_Simulator_BackUp | 845943c9a289026a818fa5d4acb18445d997e8a0 | 8677b9b044fa7acb63d33be347f15a7f1e6287b7 | refs/heads/master | 2016-09-05T12:27:08.716525 | 2015-07-11T09:42:04 | 2015-07-11T09:42:04 | 28,326,797 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include "stdafx.h"
#include "OPENGL_SCALARFIELD.h"
int OPENGL_OBJECT_BASE::count_object_for_name = 0;
| [
"[email protected]"
]
| |
b74404527360ed56a606447422ac32437836bafc | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /ash/system/power/peripheral_battery_notifier_unittest.cc | 88028b659f6f50c447f882dd9efe0f9a8917e1cc | [
"BSD-3-Clause"
]
| permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 9,713 | cc | // Copyright 2013 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 "ash/system/power/peripheral_battery_notifier.h"
#include <memory>
#include "ash/public/cpp/config.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "base/macros.h"
#include "base/test/simple_test_tick_clock.h"
#include "ui/events/devices/touchscreen_device.h"
#include "ui/events/test/device_data_manager_test_api.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
namespace {
const char kTestBatteryPath[] =
"/sys/class/power_supply/hid-AA:BB:CC:DD:EE:FF-battery";
const char kTestBatteryAddress[] = "ff:ee:dd:cc:bb:aa";
const char kTestDeviceName[] = "test device";
} // namespace
namespace ash {
class PeripheralBatteryNotifierTest : public ash::AshTestBase {
public:
PeripheralBatteryNotifierTest() {}
~PeripheralBatteryNotifierTest() override {}
void SetUp() override {
ash::AshTestBase::SetUp();
observer_ = std::make_unique<PeripheralBatteryNotifier>();
}
void TearDown() override {
observer_.reset();
ash::AshTestBase::TearDown();
}
protected:
std::unique_ptr<PeripheralBatteryNotifier> observer_;
private:
DISALLOW_COPY_AND_ASSIGN(PeripheralBatteryNotifierTest);
};
TEST_F(PeripheralBatteryNotifierTest, Basic) {
base::SimpleTestTickClock clock;
observer_->set_testing_clock(&clock);
message_center::MessageCenter* message_center =
message_center::MessageCenter::Get();
// Level 50 at time 100, no low-battery notification.
clock.Advance(base::TimeDelta::FromSeconds(100));
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
50);
EXPECT_EQ(1u, observer_->batteries_.count(kTestBatteryPath));
const PeripheralBatteryNotifier::BatteryInfo& info =
observer_->batteries_[kTestBatteryPath];
EXPECT_EQ(kTestDeviceName, info.name);
EXPECT_EQ(50, info.level);
EXPECT_EQ(base::TimeTicks(), info.last_notification_timestamp);
EXPECT_EQ(kTestBatteryAddress, info.bluetooth_address);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) ==
nullptr);
// Level 5 at time 110, low-battery notification.
clock.Advance(base::TimeDelta::FromSeconds(10));
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
5);
EXPECT_EQ(5, info.level);
EXPECT_EQ(clock.NowTicks(), info.last_notification_timestamp);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) !=
nullptr);
// Verify that the low-battery notification for stylus does not show up.
EXPECT_FALSE(message_center->FindVisibleNotificationById(
PeripheralBatteryNotifier::kStylusNotificationId) !=
nullptr);
// Level -1 at time 115, cancel previous notification
clock.Advance(base::TimeDelta::FromSeconds(5));
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
-1);
EXPECT_EQ(5, info.level);
EXPECT_EQ(clock.NowTicks() - base::TimeDelta::FromSeconds(5),
info.last_notification_timestamp);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) ==
nullptr);
// Level 50 at time 120, no low-battery notification.
clock.Advance(base::TimeDelta::FromSeconds(5));
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
50);
EXPECT_EQ(50, info.level);
EXPECT_EQ(clock.NowTicks() - base::TimeDelta::FromSeconds(10),
info.last_notification_timestamp);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) ==
nullptr);
// Level 5 at time 130, no low-battery notification (throttling).
clock.Advance(base::TimeDelta::FromSeconds(10));
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
5);
EXPECT_EQ(5, info.level);
EXPECT_EQ(clock.NowTicks() - base::TimeDelta::FromSeconds(20),
info.last_notification_timestamp);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) ==
nullptr);
}
TEST_F(PeripheralBatteryNotifierTest, InvalidBatteryInfo) {
const std::string invalid_path1 = "invalid-path";
const std::string invalid_path2 = "/sys/class/power_supply/hid-battery";
observer_->PeripheralBatteryStatusReceived(invalid_path1, kTestDeviceName,
10);
EXPECT_TRUE(observer_->batteries_.empty());
observer_->PeripheralBatteryStatusReceived(invalid_path2, kTestDeviceName,
10);
EXPECT_TRUE(observer_->batteries_.empty());
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
-2);
EXPECT_TRUE(observer_->batteries_.empty());
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
101);
EXPECT_TRUE(observer_->batteries_.empty());
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
-1);
EXPECT_TRUE(observer_->batteries_.empty());
}
// Verify that for Bluetooth devices, the correct address gets stored in the
// BatteryInfo's bluetooth_address member, and for non-Bluetooth devices, that
// bluetooth_address member is empty.
TEST_F(PeripheralBatteryNotifierTest, ExtractBluetoothAddress) {
const std::string bluetooth_path =
"/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f5-battery";
const std::string expected_bluetooth_address = "f5:e4:d3:c2:b1:a0";
const std::string non_bluetooth_path =
"/sys/class/power_supply/hid-notbluetooth-battery";
observer_->PeripheralBatteryStatusReceived(bluetooth_path, kTestDeviceName,
10);
observer_->PeripheralBatteryStatusReceived(non_bluetooth_path,
kTestDeviceName, 10);
EXPECT_EQ(2u, observer_->batteries_.size());
const PeripheralBatteryNotifier::BatteryInfo& bluetooth_device_info =
observer_->batteries_[bluetooth_path];
EXPECT_EQ(expected_bluetooth_address,
bluetooth_device_info.bluetooth_address);
const PeripheralBatteryNotifier::BatteryInfo& non_bluetooth_device_info =
observer_->batteries_[non_bluetooth_path];
EXPECT_TRUE(non_bluetooth_device_info.bluetooth_address.empty());
}
// TODO(crbug.com/765794): Flaky on ash_unittests.
TEST_F(PeripheralBatteryNotifierTest, DISABLED_DeviceRemove) {
message_center::MessageCenter* message_center =
message_center::MessageCenter::Get();
observer_->PeripheralBatteryStatusReceived(kTestBatteryPath, kTestDeviceName,
5);
EXPECT_EQ(1u, observer_->batteries_.count(kTestBatteryPath));
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) !=
nullptr);
observer_->RemoveBluetoothBattery(kTestBatteryAddress);
EXPECT_TRUE(message_center->FindVisibleNotificationById(kTestBatteryPath) ==
nullptr);
}
// TODO(crbug.com/765794): Flaky on ash_unittests.
TEST_F(PeripheralBatteryNotifierTest, DISABLED_StylusNotification) {
// DeviceDataManager is nullptr when the config is not classic.
// TODO(sammiequon): Make this work for mash.
if (Shell::GetAshConfig() != Config::CLASSIC)
return;
const std::string kTestStylusBatteryPath =
"/sys/class/power_supply/hid-AAAA:BBBB:CCCC.DDDD-battery";
const std::string kTestStylusName = "test_stylus";
// Add an external stylus to our test device manager.
ui::TouchscreenDevice stylus(0 /* id */, ui::INPUT_DEVICE_EXTERNAL,
kTestStylusName, gfx::Size(),
1 /* touch_points */);
stylus.sys_path = base::FilePath(kTestStylusBatteryPath);
stylus.is_stylus = true;
ui::test::DeviceDataManagerTestAPI test_api;
test_api.SetTouchscreenDevices({stylus});
message_center::MessageCenter* message_center =
message_center::MessageCenter::Get();
// Verify that when the battery level is 50, no stylus low battery
// notification is shown.
observer_->PeripheralBatteryStatusReceived(kTestStylusBatteryPath,
kTestStylusName, 50);
EXPECT_TRUE(message_center->FindVisibleNotificationById(
PeripheralBatteryNotifier::kStylusNotificationId) == nullptr);
// Verify that when the battery level is 5, a stylus low battery notification
// is shown. Also check that a non stylus device low battery notification will
// not show up.
observer_->PeripheralBatteryStatusReceived(kTestStylusBatteryPath,
kTestStylusName, 5);
EXPECT_TRUE(message_center->FindVisibleNotificationById(
PeripheralBatteryNotifier::kStylusNotificationId) != nullptr);
EXPECT_TRUE(message_center->FindVisibleNotificationById(
kTestBatteryAddress) == nullptr);
// Verify that when the battery level is -1, the previous stylus low battery
// notification is cancelled.
observer_->PeripheralBatteryStatusReceived(kTestStylusBatteryPath,
kTestStylusName, -1);
EXPECT_TRUE(message_center->FindVisibleNotificationById(
PeripheralBatteryNotifier::kStylusNotificationId) == nullptr);
}
} // namespace ash
| [
"[email protected]"
]
| |
57eca8b011e34d7a4ca367e98c763e6280f3a861 | 67ed24f7e68014e3dbe8970ca759301f670dc885 | /win10.19042/SysWOW64/DDOIProxy.dll.cpp | edfb1ca65ed92ddc994b6352d0198bb2f7ec5420 | []
| no_license | nil-ref/dll-exports | d010bd77a00048e52875d2a739ea6a0576c82839 | 42ccc11589b2eb91b1aa82261455df8ee88fa40c | refs/heads/main | 2023-04-20T21:28:05.295797 | 2021-05-07T14:06:23 | 2021-05-07T14:06:23 | 401,055,938 | 1 | 0 | null | 2021-08-29T14:00:50 | 2021-08-29T14:00:49 | null | UTF-8 | C++ | false | false | 214 | cpp | #pragma comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\SysWOW64\\DDOIProxy.DllCanUnloadNow\"")
#pragma comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\SysWOW64\\DDOIProxy.DllGetClassObject\"")
| [
"[email protected]"
]
| |
8e7974004fba84172cbcdb0d942e3d101150aba8 | 9caaf31e5c11f17174c54c7b337cb436b949cd03 | /ch10/main.cpp | 562f2c5d9111164c8ee1f8c3f184e180ed3dfd35 | [
"MIT"
]
| permissive | Queequeg92/CLRS | 2510a1d9b1d1e22be93e58af2b8a3203388a6f6d | 0ce4ff74b8d2a6376a15306e2441e9a624597d17 | refs/heads/master | 2020-05-25T11:27:34.142624 | 2014-11-04T07:54:58 | 2014-11-04T07:54:58 | 26,424,181 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include <iostream>
#include "mergeable_heap.hpp"
#include "merge_sort_for_list.hpp"
#include "list.hpp"
int main()
{
ch10::mergeable_heap_UL<int> lhs, rhs, uni;
lhs.insert(1);
lhs.insert(3);
lhs.insert(78);
rhs.insert(78);
rhs.insert(1);
rhs.insert(2);
uni = lhs + rhs;
uni.print();
}
| [
"[email protected]"
]
| |
dde5701cdd263ad1cb579e9f61ab26538c178673 | ede9bdbfb5c408174a22818fef296a30864654cf | /Src/GPUPerfAPICounterGenerator/InternalCountersCLGfx9.cpp | c9ab4a9f33b435892042fb4998d3481270a022ab | [
"MIT"
]
| permissive | plohrmann/GPA | 43c51ca936d66c51bdfd3126aef4f109c90b5b29 | 64f920864aabd42bfe71c1762e4de24e72f3f7cc | refs/heads/master | 2020-03-10T14:58:59.309347 | 2018-03-22T17:12:40 | 2018-03-22T17:12:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,386 | cpp | //==============================================================================
// Copyright (c) 2010-2017 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief CL internal counter definitions for GFX9
//==============================================================================
#include "GPAInternalCountersGfx9.h"
#include "InternalCountersCLGfx9.h"
// This file is autogenerated by the ConvertHWEnums project
GPA_HardwareCounterDesc* CLCounterGroupArrayGfx9[] =
{
CB0countersGfx9,
CB1countersGfx9,
CB2countersGfx9,
CB3countersGfx9,
CPFcountersGfx9,
DB0countersGfx9,
DB1countersGfx9,
DB2countersGfx9,
DB3countersGfx9,
GRBMcountersGfx9,
GRBMSE0countersGfx9,
PA_SU0countersGfx9,
PA_SC0countersGfx9,
SPI0countersGfx9,
SQ0countersGfx9,
SQ_ES0countersGfx9,
SQ_GS0countersGfx9,
SQ_VS0countersGfx9,
SQ_PS0countersGfx9,
SQ_LS0countersGfx9,
SQ_HS0countersGfx9,
SQ_CS0countersGfx9,
SX0countersGfx9,
TA0countersGfx9,
TA1countersGfx9,
TA2countersGfx9,
TA3countersGfx9,
TA4countersGfx9,
TA5countersGfx9,
TA6countersGfx9,
TA7countersGfx9,
TA8countersGfx9,
TA9countersGfx9,
TA10countersGfx9,
TA11countersGfx9,
TA12countersGfx9,
TA13countersGfx9,
TA14countersGfx9,
TA15countersGfx9,
TCA0countersGfx9,
TCA1countersGfx9,
TCC0countersGfx9,
TCC1countersGfx9,
TCC2countersGfx9,
TCC3countersGfx9,
TCC4countersGfx9,
TCC5countersGfx9,
TCC6countersGfx9,
TCC7countersGfx9,
TCC8countersGfx9,
TCC9countersGfx9,
TCC10countersGfx9,
TCC11countersGfx9,
TCC12countersGfx9,
TCC13countersGfx9,
TCC14countersGfx9,
TCC15countersGfx9,
TD0countersGfx9,
TD1countersGfx9,
TD2countersGfx9,
TD3countersGfx9,
TD4countersGfx9,
TD5countersGfx9,
TD6countersGfx9,
TD7countersGfx9,
TD8countersGfx9,
TD9countersGfx9,
TD10countersGfx9,
TD11countersGfx9,
TD12countersGfx9,
TD13countersGfx9,
TD14countersGfx9,
TD15countersGfx9,
TCP0countersGfx9,
TCP1countersGfx9,
TCP2countersGfx9,
TCP3countersGfx9,
TCP4countersGfx9,
TCP5countersGfx9,
TCP6countersGfx9,
TCP7countersGfx9,
TCP8countersGfx9,
TCP9countersGfx9,
TCP10countersGfx9,
TCP11countersGfx9,
TCP12countersGfx9,
TCP13countersGfx9,
TCP14countersGfx9,
TCP15countersGfx9,
GDScountersGfx9,
VGT0countersGfx9,
IA0countersGfx9,
WDcountersGfx9,
CPGcountersGfx9,
CPCcountersGfx9,
ATCcountersGfx9,
ATCL2countersGfx9,
MCVML2countersGfx9,
GCEA0countersGfx9,
GCEA1countersGfx9,
GCEA2countersGfx9,
GCEA3countersGfx9,
GCEA4countersGfx9,
GCEA5countersGfx9,
GCEA6countersGfx9,
GCEA7countersGfx9,
GCEA8countersGfx9,
GCEA9countersGfx9,
GCEA10countersGfx9,
GCEA11countersGfx9,
GCEA12countersGfx9,
GCEA13countersGfx9,
GCEA14countersGfx9,
GCEA15countersGfx9,
RPBcountersGfx9,
RMI0countersGfx9,
RMI1countersGfx9,
RMI2countersGfx9,
RMI3countersGfx9,
RMI4countersGfx9,
RMI5countersGfx9,
RMI6countersGfx9,
RMI7countersGfx9,
};
GPA_CounterGroupDesc HWCLGroupsGfx9[] =
{
{0, "CB0", 0, 438, 4},
{1, "CB1", 1, 438, 4},
{2, "CB2", 2, 438, 4},
{3, "CB3", 3, 438, 4},
{4, "CPF", 0, 32, 2},
{5, "DB0", 0, 328, 4},
{6, "DB1", 1, 328, 4},
{7, "DB2", 2, 328, 4},
{8, "DB3", 3, 328, 4},
{9, "GRBM", 0, 38, 2},
{10, "GRBMSE", 0, 16, 4},
{11, "PA_SU", 0, 292, 4},
{12, "PA_SC", 0, 491, 8},
{13, "SPI", 0, 196, 6},
{14, "SQ", 0, 374, 16},
{15, "SQ_ES", 0, 374, 16},
{16, "SQ_GS", 0, 374, 16},
{17, "SQ_VS", 0, 374, 16},
{18, "SQ_PS", 0, 374, 16},
{19, "SQ_LS", 0, 374, 16},
{20, "SQ_HS", 0, 374, 16},
{21, "SQ_CS", 0, 374, 16},
{22, "SX", 0, 208, 4},
{23, "TA0", 0, 119, 2},
{24, "TA1", 1, 119, 2},
{25, "TA2", 2, 119, 2},
{26, "TA3", 3, 119, 2},
{27, "TA4", 4, 119, 2},
{28, "TA5", 5, 119, 2},
{29, "TA6", 6, 119, 2},
{30, "TA7", 7, 119, 2},
{31, "TA8", 8, 119, 2},
{32, "TA9", 9, 119, 2},
{33, "TA10", 10, 119, 2},
{34, "TA11", 11, 119, 2},
{35, "TA12", 12, 119, 2},
{36, "TA13", 13, 119, 2},
{37, "TA14", 14, 119, 2},
{38, "TA15", 15, 119, 2},
{39, "TCA0", 0, 35, 4},
{40, "TCA1", 1, 35, 4},
{41, "TCC0", 0, 256, 4},
{42, "TCC1", 1, 256, 4},
{43, "TCC2", 2, 256, 4},
{44, "TCC3", 3, 256, 4},
{45, "TCC4", 4, 256, 4},
{46, "TCC5", 5, 256, 4},
{47, "TCC6", 6, 256, 4},
{48, "TCC7", 7, 256, 4},
{49, "TCC8", 8, 256, 4},
{50, "TCC9", 9, 256, 4},
{51, "TCC10", 10, 256, 4},
{52, "TCC11", 11, 256, 4},
{53, "TCC12", 12, 256, 4},
{54, "TCC13", 13, 256, 4},
{55, "TCC14", 14, 256, 4},
{56, "TCC15", 15, 256, 4},
{57, "TD0", 0, 57, 2},
{58, "TD1", 1, 57, 2},
{59, "TD2", 2, 57, 2},
{60, "TD3", 3, 57, 2},
{61, "TD4", 4, 57, 2},
{62, "TD5", 5, 57, 2},
{63, "TD6", 6, 57, 2},
{64, "TD7", 7, 57, 2},
{65, "TD8", 8, 57, 2},
{66, "TD9", 9, 57, 2},
{67, "TD10", 10, 57, 2},
{68, "TD11", 11, 57, 2},
{69, "TD12", 12, 57, 2},
{70, "TD13", 13, 57, 2},
{71, "TD14", 14, 57, 2},
{72, "TD15", 15, 57, 2},
{73, "TCP0", 0, 85, 4},
{74, "TCP1", 1, 85, 4},
{75, "TCP2", 2, 85, 4},
{76, "TCP3", 3, 85, 4},
{77, "TCP4", 4, 85, 4},
{78, "TCP5", 5, 85, 4},
{79, "TCP6", 6, 85, 4},
{80, "TCP7", 7, 85, 4},
{81, "TCP8", 8, 85, 4},
{82, "TCP9", 9, 85, 4},
{83, "TCP10", 10, 85, 4},
{84, "TCP11", 11, 85, 4},
{85, "TCP12", 12, 85, 4},
{86, "TCP13", 13, 85, 4},
{87, "TCP14", 14, 85, 4},
{88, "TCP15", 15, 85, 4},
{89, "GDS", 0, 121, 4},
{90, "VGT", 0, 148, 4},
{91, "IA", 0, 32, 4},
{92, "WD", 0, 58, 4},
{93, "CPG", 0, 59, 2},
{94, "CPC", 0, 35, 2},
{95, "ATC", 0, 24, 4},
{96, "ATCL2", 0, 8, 2},
{97, "MCVML2", 0, 21, 8},
{98, "GCEA0", 0, 77, 2},
{99, "GCEA1", 1, 77, 2},
{100, "GCEA2", 2, 77, 2},
{101, "GCEA3", 3, 77, 2},
{102, "GCEA4", 4, 77, 2},
{103, "GCEA5", 5, 77, 2},
{104, "GCEA6", 6, 77, 2},
{105, "GCEA7", 7, 77, 2},
{106, "GCEA8", 8, 77, 2},
{107, "GCEA9", 9, 77, 2},
{108, "GCEA10", 10, 77, 2},
{109, "GCEA11", 11, 77, 2},
{110, "GCEA12", 12, 77, 2},
{111, "GCEA13", 13, 77, 2},
{112, "GCEA14", 14, 77, 2},
{113, "GCEA15", 15, 77, 2},
{114, "RPB", 0, 63, 4},
{115, "RMI0", 0, 257, 4},
{116, "RMI1", 1, 257, 4},
{117, "RMI2", 2, 257, 4},
{118, "RMI3", 3, 257, 4},
{119, "RMI4", 4, 257, 4},
{120, "RMI5", 5, 257, 4},
{121, "RMI6", 6, 257, 4},
{122, "RMI7", 7, 257, 4},
};
GPA_SQCounterGroupDesc HWCLSQGroupsGfx9[] =
{
{14, 0, SQ_ALL},
{15, 0, SQ_ES},
{16, 0, SQ_GS},
{17, 0, SQ_VS},
{18, 0, SQ_PS},
{19, 0, SQ_LS},
{20, 0, SQ_HS},
{21, 0, SQ_CS},
};
unsigned int HWCLSQIsolatedGroupsGfx9[] =
{
23, // Ta
24, // Ta
25, // Ta
26, // Ta
27, // Ta
28, // Ta
29, // Ta
30, // Ta
31, // Ta
32, // Ta
33, // Ta
34, // Ta
35, // Ta
36, // Ta
37, // Ta
38, // Ta
39, // Tca
40, // Tca
41, // Tcc
42, // Tcc
43, // Tcc
44, // Tcc
45, // Tcc
46, // Tcc
47, // Tcc
48, // Tcc
49, // Tcc
50, // Tcc
51, // Tcc
52, // Tcc
53, // Tcc
54, // Tcc
55, // Tcc
56, // Tcc
57, // Td
58, // Td
59, // Td
60, // Td
61, // Td
62, // Td
63, // Td
64, // Td
65, // Td
66, // Td
67, // Td
68, // Td
69, // Td
70, // Td
71, // Td
72, // Td
73, // Tcp
74, // Tcp
75, // Tcp
76, // Tcp
77, // Tcp
78, // Tcp
79, // Tcp
80, // Tcp
81, // Tcp
82, // Tcp
83, // Tcp
84, // Tcp
85, // Tcp
86, // Tcp
87, // Tcp
88, // Tcp
};
const unsigned int HWCLGroupCountGfx9 = sizeof(HWCLGroupsGfx9) / sizeof(GPA_CounterGroupDesc);
const unsigned int HWCLSQGroupCountGfx9 = sizeof(HWCLSQGroupsGfx9) / sizeof(GPA_SQCounterGroupDesc);
const unsigned int HWCLSQIsolatedGroupCountGfx9 = sizeof(HWCLSQIsolatedGroupsGfx9) / sizeof(unsigned int);
| [
"[email protected]"
]
| |
d2fd1ffd327bf09b8e4df878296264ee2d2efb89 | 78db62d5993d85828b21d5f48dfd91241087a005 | /src/main.h | d865e9a6e2951c51890d332c3db4afc088ce0953 | [
"MIT"
]
| permissive | robo-coin/robocoin-wallet-source | 46919032bf7759f28191dbaa4f9191ffce9076ed | abe482712ea21384282bb62e9e2086d84d6b8476 | refs/heads/master | 2020-12-31T05:10:10.480694 | 2016-04-29T09:13:46 | 2016-04-29T09:13:46 | 57,355,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,422 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class CAddress;
class CInv;
class CNode;
struct CBlockIndexWorkComparator;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit
/** Obsolete: maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit
/** Default for -blockmaxsize, maximum size for mined blocks **/
static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000;
/** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000;
/** The maximum size for transactions we're willing to relay/mine */
static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 25;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
/** Dust Soft Limit, allowed with additional fee per output */
static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 LTC
/** Dust Hard Limit, ignored as wallet inputs (mininput default) */
static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 LTC mininput
/** No amount larger than this (in satoshi) is valid */
static const int64 MAX_MONEY = 2800000000 * COIN;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
static const int COINBASE_MATURITY = 20;
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Maximum number of script-checking threads allowed */
static const int MAX_SCRIPTCHECK_THREADS = 16;
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern uint256 nBestChainWork;
extern uint256 nBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern bool fImporting;
extern bool fReindex;
extern bool fBenchmark;
extern int nScriptCheckThreads;
extern bool fTxIndex;
extern unsigned int nCoinCacheSize;
// Settings
extern int64 nTransactionFee;
extern int64 nMinimumInputValue;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CCoinsDB;
class CBlockTreeDB;
struct CDiskBlockPos;
class CCoins;
class CTxUndo;
class CCoinsView;
class CCoinsViewCache;
class CScriptCheck;
class CValidationState;
struct CBlockTemplate;
/** Register a wallet to receive updates from core */
void RegisterWallet(CWallet* pwalletIn);
/** Unregister a wallet from core */
void UnregisterWallet(CWallet* pwalletIn);
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
/** Process an incoming block */
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
/** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Open an undo file (rev?????.dat) */
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Import blocks from an external file */
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
/** Initialize a new block tree database + block data on disk */
bool InitBlockIndex();
/** Load the block tree and coins database from disk */
bool LoadBlockIndex();
/** Unload database information */
void UnloadBlockIndex();
/** Verify consistency of the block and coin databases */
bool VerifyDB(int nCheckLevel, int nCheckDepth);
/** Print the loaded block tree */
void PrintBlockTree();
/** Find a block by height in the currently-connected chain */
CBlockIndex* FindBlockByHeight(int nHeight);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom);
/** Send queued protocol messages to be sent to a give node */
bool SendMessages(CNode* pto, bool fSendTrickle);
/** Run an instance of the script checking thread */
void ThreadScriptCheck();
/** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
/** Do mining precalculation */
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
/** Check mined block */
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
/** Get the number of active peers */
int GetNumBlocksOfPeers();
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(std::string strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
/** Find the best known block, and make it the tip of the block chain */
bool ConnectBestBlock(CValidationState &state);
/** Create a new block index entry for a given block hash */
CBlockIndex * InsertBlockIndex(uint256 hash);
/** Verify a signature */
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
/** Abort with a message */
bool AbortNode(const std::string &msg);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
struct CDiskBlockPos
{
int nFile;
unsigned int nPos;
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
)
CDiskBlockPos() {
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return !(a == b);
}
void SetNull() { nFile = -1; nPos = 0; }
bool IsNull() const { return (nFile == -1); }
};
struct CDiskTxPos : public CDiskBlockPos
{
unsigned int nTxOffset; // after header
IMPLEMENT_SERIALIZE(
READWRITE(*(CDiskBlockPos*)this);
READWRITE(VARINT(nTxOffset));
)
CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
}
CDiskTxPos() {
SetNull();
}
void SetNull() {
CDiskBlockPos::SetNull();
nTxOffset = 0;
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
bool IsDust() const;
std::string ToString() const
{
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static int64 nMinTxFee;
static int64 nMinRelayTxFee;
static const int CURRENT_VERSION=1;
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
vin.clear();
vout.clear();
nLockTime = 0;
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
uint256 GetNormalizedHash() const
{
return SignatureHash(CScript(), *this, 0, SIGHASH_ALL);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard(std::string& strReason) const;
bool IsStandard() const
{
std::string strReason;
return IsStandard(strReason);
}
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
*/
bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
*/
unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
*/
int64 GetValueIn(CCoinsViewCache& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 576 / 250;
}
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
GetHash().ToString().c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
// Check whether all prevouts of this transaction are present in the UTXO set represented by view
bool HaveInputs(CCoinsViewCache &view) const;
// Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
// This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
// instead of being performed inline.
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
std::vector<CScriptCheck> *pvChecks = NULL) const;
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
// Context-independent validity checks
bool CheckTransaction(CValidationState &state) const;
// Try to accept this transaction into the memory pool
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL, bool fRejectInsaneFee = false);
protected:
static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut &txout;
public:
static uint64 CompressAmount(uint64 nAmount);
static uint64 DecompressAmount(uint64 nAmount);
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
IMPLEMENT_SERIALIZE(({
if (!fRead) {
uint64 nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));
} else {
uint64 nVal = 0;
READWRITE(VARINT(nVal));
txout.nValue = DecompressAmount(nVal);
}
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
});)
};
/** Undo information for a CTxIn
*
* Contains the prevout's CTxOut being spent, and if this was the
* last output of the affected transaction, its metadata as well
* (coinbase or not, height, transaction version)
*/
class CTxInUndo
{
public:
CTxOut txout; // the txout data before being spent
bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
unsigned int nHeight; // if the outpoint was the last unspent: its height
int nVersion; // if the outpoint was the last unspent: its version
CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
unsigned int GetSerializeSize(int nType, int nVersion) const {
return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
(nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
if (nHeight > 0)
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
::Unserialize(s, VARINT(nCode), nType, nVersion);
nHeight = nCode / 2;
fCoinBase = nCode & 1;
if (nHeight > 0)
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
}
};
/** Undo information for a CTransaction */
class CTxUndo
{
public:
// undo information for all txins
std::vector<CTxInUndo> vprevout;
IMPLEMENT_SERIALIZE(
READWRITE(vprevout);
)
};
/** Undo information for a CBlock */
class CBlockUndo
{
public:
std::vector<CTxUndo> vtxundo; // for all but the coinbase
IMPLEMENT_SERIALIZE(
READWRITE(vtxundo);
)
bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to read
CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
return true;
}
};
/** pruned version of CTransaction: only retains metadata and unspent transaction outputs
*
* Serialized format:
* - VARINT(nVersion)
* - VARINT(nCode)
* - unspentness bitvector, for vout[2] and further; least significant byte first
* - the non-spent CTxOuts (via CTxOutCompressor)
* - VARINT(nHeight)
*
* The nCode value consists of:
* - bit 1: IsCoinBase()
* - bit 2: vout[0] is not spent
* - bit 4: vout[1] is not spent
* - The higher bits encode N, the number of non-zero bytes in the following bitvector.
* - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
* least one non-spent output).
*
* Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
* <><><--------------------------------------------><---->
* | \ | /
* version code vout[1] height
*
* - version = 1
* - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
* - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
* - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
* * 8358: compact amount representation for 60000000000 (600 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
* - height = 203998
*
*
* Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
* <><><--><--------------------------------------------------><----------------------------------------------><---->
* / \ \ | | /
* version code unspentness vout[4] vout[16] height
*
* - version = 1
* - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
* 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
* - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
* - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
* * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
* - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
* * bbd123: compact amount representation for 110397 (0.001 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
* - height = 120891
*/
class CCoins
{
public:
// whether transaction is a coinbase
bool fCoinBase;
// unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
// at which height this transaction was included in the active block chain
int nHeight;
// version of the CTransaction; accesses to this value should probably check for nHeight as well,
// as new tx version will probably only be introduced at certain heights
int nVersion;
// construct a CCoins from a CTransaction, at a given height
CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
// empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
// remove spent outputs at the end of vout
void Cleanup() {
while (vout.size() > 0 && vout.back().IsNull())
vout.pop_back();
if (vout.empty())
std::vector<CTxOut>().swap(vout);
}
void swap(CCoins &to) {
std::swap(to.fCoinBase, fCoinBase);
to.vout.swap(vout);
std::swap(to.nHeight, nHeight);
std::swap(to.nVersion, nVersion);
}
// equality test
friend bool operator==(const CCoins &a, const CCoins &b) {
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.nVersion == b.nVersion &&
a.vout == b.vout;
}
friend bool operator!=(const CCoins &a, const CCoins &b) {
return !(a == b);
}
// calculate number of bytes for the bitmask, and its number of non-zero bytes
// each bit in the bitmask represents the availability of one output, but the
// availabilities of the first two outputs are encoded separately
void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool IsCoinBase() const {
return fCoinBase;
}
unsigned int GetSerializeSize(int nType, int nVersion) const {
unsigned int nSize = 0;
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
// size of header code
nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
// spentness bitmask
nSize += nMaskSize;
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++)
if (!vout[i].IsNull())
nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
// height
nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
return nSize;
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Serialize(s, VARINT(nCode), nType, nVersion);
// spentness bitmask
for (unsigned int b = 0; b<nMaskSize; b++) {
unsigned char chAvail = 0;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
if (!vout[2+b*8+i].IsNull())
chAvail |= (1 << i);
::Serialize(s, chAvail, nType, nVersion);
}
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++) {
if (!vout[i].IsNull())
::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
}
// coinbase height
::Serialize(s, VARINT(nHeight), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
// version
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Unserialize(s, VARINT(nCode), nType, nVersion);
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = nCode & 2;
vAvail[1] = nCode & 4;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail, nType, nVersion);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
}
// coinbase height
::Unserialize(s, VARINT(nHeight), nType, nVersion);
Cleanup();
}
// mark an outpoint spent, and construct undo information
bool Spend(const COutPoint &out, CTxInUndo &undo) {
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.nVersion = this->nVersion;
}
return true;
}
// mark a vout spent
bool Spend(int nPos) {
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
// check whether a particular output is still available
bool IsAvailable(unsigned int nPos) const {
return (nPos < vout.size() && !vout[nPos].IsNull());
}
// check whether the entire CCoins is spent
// note that only !IsPruned() CCoins can be serialized
bool IsPruned() const {
BOOST_FOREACH(const CTxOut &out, vout)
if (!out.IsNull())
return false;
return true;
}
};
/** Closure representing one script verification
* Note that this stores references to the spending transaction */
class CScriptCheck
{
private:
CScript scriptPubKey;
const CTransaction *ptxTo;
unsigned int nIn;
unsigned int nFlags;
int nHashType;
public:
CScriptCheck() {}
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
bool operator()() const;
void swap(CScriptCheck &check) {
scriptPubKey.swap(check.scriptPubKey);
std::swap(ptxTo, check.ptxTo);
std::swap(nIn, check.nIn);
std::swap(nFlags, check.nFlags);
std::swap(nHashType, check.nHashType);
}
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
};
/** Data structure that represents a partial merkle tree.
*
* It respresents a subset of the txid's of a known block, in a way that
* allows recovery of the list of txid's and the merkle root, in an
* authenticated way.
*
* The encoding works as follows: we traverse the tree in depth-first order,
* storing a bit for each traversed node, signifying whether the node is the
* parent of at least one matched leaf txid (or a matched txid itself). In
* case we are at the leaf level, or this bit is 0, its merkle node hash is
* stored, and its children are not explorer further. Otherwise, no hash is
* stored, but we recurse into both (or the only) child branch. During
* decoding, the same depth-first traversal is performed, consuming bits and
* hashes as they written during encoding.
*
* The serialization is fixed and provides a hard guarantee about the
* encoded size:
*
* SIZE <= 10 + ceil(32.25*N)
*
* Where N represents the number of leaf nodes of the partial tree. N itself
* is bounded by:
*
* N <= total_transactions
* N <= 1 + matched_transactions*tree_height
*
* The serialization format:
* - uint32 total_transactions (4 bytes)
* - varint number of hashes (1-3 bytes)
* - uint256[] hashes in depth-first order (<= 32*N bytes)
* - varint number of bytes of flag bits (1-3 bytes)
* - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
* The size constraints follow from this.
*/
class CPartialMerkleTree
{
protected:
// the total number of transactions in the block
unsigned int nTransactions;
// node-is-parent-of-matched-txid bits
std::vector<bool> vBits;
// txids and internal hashes
std::vector<uint256> vHash;
// flag set when encountering invalid data
bool fBad;
// helper function to efficiently calculate the number of nodes at given height in the merkle tree
unsigned int CalcTreeWidth(int height) {
return (nTransactions+(1 << height)-1) >> height;
}
// calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
// recursive function that traverses tree nodes, storing the data as bits and hashes
void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
// recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
// it returns the hash of the respective node.
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
public:
// serialization implementation
IMPLEMENT_SERIALIZE(
READWRITE(nTransactions);
READWRITE(vHash);
std::vector<unsigned char> vBytes;
if (fRead) {
READWRITE(vBytes);
CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
us.vBits.resize(vBytes.size() * 8);
for (unsigned int p = 0; p < us.vBits.size(); p++)
us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
us.fBad = false;
} else {
vBytes.resize((vBits.size()+7)/8);
for (unsigned int p = 0; p < vBits.size(); p++)
vBytes[p / 8] |= vBits[p] << (p % 8);
READWRITE(vBytes);
}
)
// Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
CPartialMerkleTree();
// extract the matching txid's represented by this partial merkle tree.
// returns the merkle root, or 0 in case of failure
uint256 ExtractMatches(std::vector<uint256> &vMatch);
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int CURRENT_VERSION=2;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockHeader()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
IMPLEMENT_SERIALIZE
(
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
)
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
}
uint256 GetPoWHash() const
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
const uint256 &GetTxHash(unsigned int nIndex) const {
assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
assert(nIndex < vtx.size());
return vMerkleTree[nIndex];
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(CDiskBlockPos &pos)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (!CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
GetHash().ToString().c_str(),
HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(),
GetPoWHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().c_str());
printf("\n");
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
* will be true if no problems were found. Otherwise, the return value will be false in case
* of problems. Note that in any case, coins may be modified. */
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
// Apply the effects of this block (with given index) on the UTXO set represented by coins
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
// Read a block from disk
bool ReadFromDisk(const CBlockIndex* pindex);
// Add this block to the block index, and if necessary, switch the active block chain to this
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
// Context-independent validity checks
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
// Store block on disk
// if dbp is provided, the file is known to already reside on disk
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
};
class CBlockFileInfo
{
public:
unsigned int nBlocks; // number of blocks stored in file
unsigned int nSize; // number of used bytes of block file
unsigned int nUndoSize; // number of used bytes in the undo file
unsigned int nHeightFirst; // lowest height of block in file
unsigned int nHeightLast; // highest height of block in file
uint64 nTimeFirst; // earliest time of block in file
uint64 nTimeLast; // latest time of block in file
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
)
void SetNull() {
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo() {
SetNull();
}
std::string ToString() const {
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
}
// update statistics (does not update nSize)
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
if (nBlocks==0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks==0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightFirst)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
extern CCriticalSection cs_LastBlockFile;
extern CBlockFileInfo infoLastBlockFile;
extern int nLastBlockFile;
enum BlockStatus {
BLOCK_VALID_UNKNOWN = 0,
BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
BLOCK_VALID_MASK = 7,
BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
BLOCK_HAVE_MASK = 24,
BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, // descends from failed block
BLOCK_FAILED_MASK = 96
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
// pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock;
// pointer to the index of the predecessor of this block
CBlockIndex* pprev;
// (memory only) pointer to the index of the *active* successor of this block
CBlockIndex* pnext;
// height of the entry in the chain. The genesis block has height 0
int nHeight;
// Which # file this block is stored in (blk?????.dat)
int nFile;
// Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
// Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
// (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork;
// Number of transactions in this block.
// Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
// (memory only) Number of transactions in the chain up to and including this block
unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
// Verification status of this block. See enum BlockStatus
unsigned int nStatus;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(CBlockHeader& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CDiskBlockPos GetBlockPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
/** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256.
* This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */
return true; // return CheckProofOfWork(GetBlockHash(), nBits);
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nHeight,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
struct CBlockIndexWorkComparator
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
return false; // identical blocks
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Capture information about block/transaction validation */
class CValidationState {
private:
enum mode_state {
MODE_VALID, // everything ok
MODE_INVALID, // network rule violation (DoS value may be set)
MODE_ERROR, // run-time error
} mode;
int nDoS;
bool corruptionPossible;
public:
CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
bool DoS(int level, bool ret = false, bool corruptionIn = false) {
if (mode == MODE_ERROR)
return ret;
nDoS += level;
mode = MODE_INVALID;
corruptionPossible = corruptionIn;
return ret;
}
bool Invalid(bool ret = false) {
return DoS(0, ret);
}
bool Error() {
mode = MODE_ERROR;
return false;
}
bool Abort(const std::string &msg) {
AbortNode(msg);
return Error();
}
bool IsValid() {
return mode == MODE_VALID;
}
bool IsInvalid() {
return mode == MODE_INVALID;
}
bool IsError() {
return mode == MODE_ERROR;
}
bool IsInvalid(int &nDoSOut) {
if (IsInvalid()) {
nDoSOut = nDoS;
return true;
}
return false;
}
bool CorruptionPossible() {
return corruptionPossible;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false);
bool addUnchecked(const uint256& hash, const CTransaction &tx);
bool remove(const CTransaction &tx, bool fRecursive = false);
bool removeConflicts(const CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
void pruneSpent(const uint256& hash, CCoins &coins);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64 nTransactions;
uint64 nTransactionOutputs;
uint64 nSerializedSize;
uint256 hashSerialized;
int64 nTotalAmount;
CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
};
/** Abstract view on the open txout dataset. */
class CCoinsView
{
public:
// Retrieve the CCoins (unspent transaction outputs) for a given txid
virtual bool GetCoins(const uint256 &txid, CCoins &coins);
// Modify the CCoins for a given txid
virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
// Just check whether we have data for a given txid.
// This may (but cannot always) return true for fully spent transactions
virtual bool HaveCoins(const uint256 &txid);
// Retrieve the block index whose state this CCoinsView currently represents
virtual CBlockIndex *GetBestBlock();
// Modify the currently active block index
virtual bool SetBestBlock(CBlockIndex *pindex);
// Do a bulk modification (multiple SetCoins + one SetBestBlock)
virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Calculate statistics about the unspent transaction output set
virtual bool GetStats(CCoinsStats &stats);
// As we use CCoinsViews polymorphically, have a virtual destructor
virtual ~CCoinsView() {}
};
/** CCoinsView backed by another CCoinsView */
class CCoinsViewBacked : public CCoinsView
{
protected:
CCoinsView *base;
public:
CCoinsViewBacked(CCoinsView &viewIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
void SetBackend(CCoinsView &viewIn);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
bool GetStats(CCoinsStats &stats);
};
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
class CCoinsViewCache : public CCoinsViewBacked
{
protected:
CBlockIndex *pindexTip;
std::map<uint256,CCoins> cacheCoins;
public:
CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
// Standard CCoinsView methods
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Return a modifiable reference to a CCoins. Check HaveCoins first.
// Many methods explicitly require a CCoinsViewCache because of this method, to reduce
// copying.
CCoins &GetCoins(const uint256 &txid);
// Push the modifications applied to this cache to its base.
// Failure to call this method before destruction will cause the changes to be forgotten.
bool Flush();
// Calculate the size of the cache (in number of transactions)
unsigned int GetCacheSize();
private:
std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
};
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
CTxMemPool &mempool;
public:
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool HaveCoins(const uint256 &txid);
};
/** Global variable that points to the active CCoinsView (protected by cs_main) */
extern CCoinsViewCache *pcoinsTip;
/** Global variable that points to the active block tree (protected by cs_main) */
extern CBlockTreeDB *pblocktree;
struct CBlockTemplate
{
CBlock block;
std::vector<int64_t> vTxFees;
std::vector<int64_t> vTxSigOps;
};
#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64)
extern unsigned int cpuid_edx;
#endif
/** Used to relay blocks as header + vector<merkle branch>
* to filtered nodes.
*/
class CMerkleBlock
{
public:
// Public only for unit testing
CBlockHeader header;
CPartialMerkleTree txn;
public:
// Public only for unit testing and relay testing
// (not relayed)
std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
// Create from a CBlock, filtering transactions according to filter
// Note that this will call IsRelevantAndUpdate on the filter for each transaction,
// thus the filter will likely be modified.
CMerkleBlock(const CBlock& block, CBloomFilter& filter);
IMPLEMENT_SERIALIZE
(
READWRITE(header);
READWRITE(txn);
)
};
#endif
| [
"[email protected]"
]
| |
98deeb5c969b1a03209e9d015bb71a9b66f49423 | 6b92f60359ce64084c2484417783e369500d5c7c | /px4_ws/src/slam_test/src/SURF.cpp | a9219826b7524f1aca9f080a599f05b070468a88 | []
| no_license | tuofeichen/MAV-Project | f4f345b68fae249a8b79f5773e52f5653973adad | 37c7a743639f57a800bec061a9d7e8912b30d545 | refs/heads/master | 2020-11-29T15:23:22.364084 | 2017-06-20T15:10:44 | 2017-06-20T15:10:44 | 55,184,997 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,131 | cpp | /**
* @file SURF.cpp
* @author Gian Danuser & Michael Eugster
* @brief This file contains the implementation of the SURF class.
*
*/
#include <iostream>
#include "SURF.h"
using namespace std;
namespace SLAM {
SURF::SURF(float aRatio, int minMatches, int sufficientMatches)
: ratio(aRatio), sufficientNrOfMatches(sufficientMatches), minNrOfMatches(minMatches),
detecterExtracter(cv::xfeatures2d::SURF::create(100, 6, 5, false, true)) // is thread safe
{ }
SURF::~SURF()
{ }
boost::shared_ptr<std::vector<cv::KeyPoint>> SURF::detect(const cv::Mat& img)
{
boost::shared_ptr<std::vector<cv::KeyPoint>> keypoints(new std::vector<cv::KeyPoint>);
detecterExtracter->detect(img, *keypoints);
return keypoints;
}
boost::shared_ptr<cv::Mat> SURF::extract(const cv::Mat& img, const std::vector<cv::KeyPoint>& kpts)
{
boost::shared_ptr<cv::Mat> descriptors(new cv::Mat);
cv::Mat img_key;
detecterExtracter->compute(img,const_cast<std::vector<cv::KeyPoint>&>(kpts), *descriptors);
// cv::namedWindow("SURF KeyPoints",cv::WINDOW_NORMAL);
// cv::drawKeypoints(img,kpts,img_key,cv::Scalar::all(-1),cv::DrawMatchesFlags::DEFAULT);
// cv::imshow("SURF KeyPoints", img_key);
return descriptors;
}
bool SURF::match(const std::vector<cv::KeyPoint>& kpts1, const cv::Mat& descs1,
const std::vector<cv::KeyPoint>& kpts2, const cv::Mat& descs2,
std::vector<int>& matchesIdx1, std::vector<int>& matchesIdx2) const
{
cv::flann::Index tree(descs1, cv::flann::KDTreeIndexParams(4), cvflann::FLANN_DIST_EUCLIDEAN);
cv::Mat indices, dists;
tree.knnSearch(descs2, indices, dists, 2, cv::flann::SearchParams(16));
matchesIdx1.clear();
matchesIdx2.clear();
for (int i = 0; i < indices.rows && static_cast<int>(matchesIdx1.size()) < sufficientNrOfMatches; ++i)
{
float tmpRatio = dists.at<float>(i,0) / dists.at<float>(i,1);
if (tmpRatio <= ratio) // ratio test
{
//cout << "match detected" << endl;
matchesIdx1.push_back(indices.at<int>(i,0));
matchesIdx2.push_back(i);
}
}
if (static_cast<int>(matchesIdx1.size()) < minNrOfMatches)
return false;
else
return true;
}
} /* namespace SLAM */
| [
"[email protected]"
]
| |
80dcfc48474a0137e50a9b6a1894780a3b2834e1 | 48d5dbf4475448f5df6955f418d7c42468d2a165 | /SDK/SoT_BP_PetPreview_Parrot_functions.cpp | fdd075b80863a1bd072079de12f0ce4f6d47ef60 | []
| no_license | Outshynd/SoT-SDK-1 | 80140ba84fe9f2cdfd9a402b868099df4e8b8619 | 8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4 | refs/heads/master | 2022-11-21T04:35:29.362290 | 2020-07-10T14:50:55 | 2020-07-10T14:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | // Sea of Thieves (1.4.16) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_PetPreview_Parrot_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
]
| |
d379036720f649ac17c8cc3884419438bf962d44 | 2af0442c5a128092c2d20aad1ef975cc73d9c90a | /SlAiCourse/Source/SlAiCourse/Private/UI/Widget/SSlAiChooseRecordWidget.cpp | 2d1ddb6bf95825c9c757fbddec24d9d34cb9c657 | []
| no_license | MacroGu/UE4Projects | 24518b1d995f84f4946c17b985c926705e8039ef | 51c92bf13db31bb95823f97c1d7cdd44d3173f1b | refs/heads/master | 2023-06-15T10:33:51.816648 | 2021-07-09T07:35:58 | 2021-07-09T07:35:58 | 111,319,010 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,828 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SSlAiChooseRecordWidget.h"
#include "SlateOptMacros.h"
#include "SlAiStyle.h"
#include "SlAiMenuWidgetStyle.h"
#include "SBox.h"
#include "STextBlock.h"
#include "SOverlay.h"
#include "SImage.h"
#include "STextComboBox.h"
#include "SlAiDataHandle.h"
BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION
void SSlAiChooseRecordWidget::Construct(const FArguments& InArgs)
{
// 获取 MenuStyle
MenuStyle = &SlAiStyle::Get().GetWidgetStyle<FSlAiMenuStyle>("BPSlAiMenuStyle");
// 初始化下拉菜单数据
for (TArray<FString>::TIterator It(SlAiDataHandle::Get()->RecordDataList); It; ++It)
{
OptionsSource.Add(MakeShareable(new FString(*It)));
}
ChildSlot
[
SNew(SBox)
.WidthOverride(500.f)
.HeightOverride(100.f)
[
SNew(SOverlay)
+ SOverlay::Slot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SImage)
.Image(&MenuStyle->MenuItemBrush)
]
+ SOverlay::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.Padding(FMargin(20.f, 0.f, 0.f, 0.f))
[
SNew(STextBlock)
.Font(MenuStyle->Font_40)
.Text(NSLOCTEXT("SlAiMenu", "NewGame", "NewGame"))
]
+ SOverlay::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Center)
.Padding(FMargin(0.f, 0.f, 20.f, 0.f))
[
SNew(SBox)
.WidthOverride(300.f)
.HeightOverride(60.f)
[
SAssignNew(RecordComboBox, STextComboBox)
.Font(MenuStyle->Font_30)
.OptionsSource(&OptionsSource)
]
]
]
];
// 设置默认的选项
RecordComboBox->SetSelectedItem(OptionsSource[0]);
}
END_SLATE_FUNCTION_BUILD_OPTIMIZATION
void SSlAiChooseRecordWidget::UpdateRecordName()
{
// 修改存档名
SlAiDataHandle::Get()->RecordName = *RecordComboBox->GetSelectedItem().Get();
}
| [
"[email protected]"
]
| |
3e6f20436d256fb51b6616f58ff4a317b65a9c61 | 9c433cba8a1d67410cc5354c789a7d17af6b8890 | /COM/p20140825_Plugin/CAD/Shape/MyShapeFactory.cpp | 3b7eeadac9e86ea8c1c3d198ab24fb0f6b8b0a58 | []
| no_license | 958724723/KR_Ph2 | 011d5d4bcd6c3381ea16e051f5e50c828a63cdfc | 07e3ed72265e8254b894f444cca3fd807d1fc6bb | refs/heads/master | 2021-12-03T16:13:31.529881 | 2014-08-28T16:19:09 | 2014-08-28T16:19:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 560 | cpp | // MyShapeFactory.cpp: implementation of the CMyShapeFactory class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "..\CAD.h"
#include "MyShapeFactory.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyShapeFactory::CMyShapeFactory()
{
}
CMyShapeFactory::~CMyShapeFactory()
{
}
| [
"[email protected]"
]
| |
13efb7092d4fa93ba369d264d2d947eca2822160 | 880ba6f0ad1090d5c1d837d0e76d1d767ebe20d8 | /source/bi01.h | 9a7869356c0db0bd6ceeb59639523f2ca68b64b1 | []
| no_license | jetma/adso | 7657e02978c0afdc35c66a67771841ddbed69f17 | 56fd41696a542cc9a80da60a6ffe06ebfb2e67f3 | refs/heads/master | 2020-06-18T12:32:10.407939 | 2019-03-03T08:49:52 | 2019-03-03T08:49:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | h | #ifndef BI01_H
#define BI01_H
#include "verb.h"
class Bi01: public Verb {
public:
Bi01(Text *t);
~Bi01();
};
#endif
| [
"[email protected]"
]
| |
2efac0b8a0b134decc0baf53eb7e7dd72736cf41 | 711b767d05bd9988ea47090b981aaf3b3d4572d2 | /gap_buffer.test.cpp | dd53fe4242a2e2f9d02c32983c7cf626c73b43ce | [
"MIT"
]
| permissive | cmaughan/gapbuffer | d479588864282442795ca97125c04340c9b2e27b | 7fdd0a382b490be394f6fce5fbe280a0c5272e2a | refs/heads/master | 2020-12-02T21:06:28.954367 | 2017-10-25T10:42:30 | 2017-10-25T10:42:30 | 96,256,803 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,700 | cpp | #include "gap_buffer.h"
#include <gtest/gtest.h>
TEST(GapBuffer, PushPop)
{
GapBuffer<unsigned char> buffer(0, 4);
buffer.push_back('a');
buffer.push_back('b');
buffer.push_back('c');
buffer.push_back('d');
buffer.push_back('e');
auto out = buffer.string(true);
ASSERT_EQ(out, "abcde|4|");
buffer.pop_back();
buffer.pop_back();
buffer.pop_back();
out = buffer.string(true);
ASSERT_EQ(out, "ab|7|");
buffer.pop_back();
buffer.pop_back();
out = buffer.string(true);
ASSERT_EQ(out, "|9|");
#ifdef _MSC_VER
EXPECT_DEATH(buffer.pop_back(), ".*!empty.*");
#endif
}
TEST(GapBuffer, FrontBack)
{
GapBuffer<unsigned char> buffer;
std::string foo("Hello");
buffer.insert(buffer.begin(), foo.begin(), foo.end());
ASSERT_EQ(buffer[0], 'H');
ASSERT_EQ(buffer[4], 'o');
buffer.push_back('a');
ASSERT_EQ(buffer[5], 'a');
}
TEST(GapBuffer, Assign)
{
GapBuffer<unsigned char> buffer(0, 4);
std::string foo("Hello");
buffer.assign(foo.begin(), foo.end());
std::string out = buffer.string(true);
ASSERT_TRUE(out == "Hello|4|");
foo = "He";
buffer.assign(foo.begin(), foo.end());
out = buffer.string(true);
ASSERT_TRUE(out == "He|7|");
foo = "";
buffer.assign(foo.begin(), foo.end());
out = buffer.string(true);
ASSERT_TRUE(out == "|9|");
foo = "abcdefghijklmnopqrstuvwxyz";
buffer.assign(foo.begin(), foo.end());
out = buffer.string(true);
ASSERT_TRUE(out == "abcdefghijklmnopqrstuvwxyz|9|");
buffer.assign({ 'r', 'e', 'd' });
out = buffer.string(false);
ASSERT_TRUE(out == "red");
buffer.assign(10, 'x');
out = buffer.string(false);
ASSERT_TRUE(out == "xxxxxxxxxx");
}
TEST(GapBuffer, Resize)
{
GapBuffer<unsigned char> buffer(0, 4);
std::string str("A sentence containing text.");
buffer.assign(str.begin(), str.end());
ASSERT_EQ(str.size(), buffer.size());
buffer.resize(3);
ASSERT_EQ(3, buffer.size());
auto out = buffer.string();
ASSERT_TRUE(out == "A s");
}
TEST(GapBuffer, Find)
{
GapBuffer<unsigned char> buffer(0, 4);
std::string foo("The big brown fox jumped over the lazy dog.");
buffer.assign(foo.begin(), foo.end());
std::string skip("Th");
auto pos = buffer.find_first_not_of(buffer.begin(), buffer.end(), skip.begin(), skip.end());
ASSERT_EQ(pos, (buffer.begin() + 2));
std::string search("o");
pos = buffer.find_first_of(buffer.begin(), buffer.end(), search.begin(), search.end());
ASSERT_EQ(pos, (buffer.begin() + 10));
}
TEST(GapBuffer, Manipulations)
{
GapBuffer<unsigned char> buffer(0, 4);
// Empty buffer
ASSERT_TRUE(buffer.size() == 0);
buffer.resize(2);
ASSERT_TRUE(buffer.size() == 2);
auto itr = buffer.begin();
*itr++ = '0';
*itr++ = '1';
std::string foo("Hello");
buffer.insert(buffer.begin(), foo.begin(), foo.end());
std::string out = buffer.string(true);
ASSERT_TRUE(out == "Hello|4|01");
auto itrErasePoint = buffer.erase(buffer.begin(), buffer.begin() + 3);
out = buffer.string(true);
ASSERT_TRUE(out == "|7|lo01");
*itrErasePoint = 'c';
out = buffer.string(true);
ASSERT_TRUE(out == "|7|co01");
buffer.insert(buffer.begin() + 2, foo.begin(), foo.end());
out = buffer.string(true);
ASSERT_TRUE(out == "coHello|2|01");
// This insertion will make more gap space, and pad that with default gap size (4)
foo = "A really long string";
buffer.insert(buffer.begin() + 7, foo.begin(), foo.end());
out = buffer.string(true);
ASSERT_TRUE(out == "coHelloA really long string|4|01");
}
| [
"[email protected]"
]
| |
8135ebf17566d9a462d38d876c318d451d1375b3 | 622160b3388d7d358daf067bceb892bc2acd5eb8 | /MemoryBuffer.h | fe125d10e85eadee31f4319dcacdaf17c784bcdc | []
| no_license | jeroenoverman/druk_sensor_display | 4506f9a3f5425332df7dc77d7168033980509844 | 85af40fee681b670ee7518bae8bd438f3c3b2071 | refs/heads/master | 2023-03-01T12:34:14.505505 | 2021-02-02T19:57:31 | 2021-02-02T19:57:31 | 331,758,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,720 | h | #ifndef __MEMORYBUFFER_H__
#define __MEMORYBUFFER_H__
#include <stdint.h>
template<unsigned N>
class MemoryBuffer
{
private:
uint16_t _values[N];
static const uint16_t _size = N;
int16_t _index;
uint16_t _maxValue;
int16_t _maxIndex;
uint16_t _minValue;
int16_t _minIndex;
bool _firstEntry;
void _recalculateMinMax();
int16_t _getArrayIndex(int16_t index);
public:
MemoryBuffer();
~MemoryBuffer();
void AddMeasurement(uint16_t value);
uint16_t GetMaxMeasurement();
int16_t GetMaxMeasurementIndex();
uint16_t GetMinMeasurement();
int16_t GetMinMeasurementIndex();
};
template<unsigned N>
MemoryBuffer<N>::MemoryBuffer():_index(0), _maxValue(0), _maxIndex(0), _minValue(0), _minIndex(0), _firstEntry(true)
{
}
template<unsigned N>
MemoryBuffer<N>::~MemoryBuffer()
{
}
template<unsigned N>
void MemoryBuffer<N>::AddMeasurement(uint16_t value)
{
int16_t valueIndex = _index;
_index = (_index + 1) % _size;
_values[valueIndex] = value;
if (_firstEntry)
{
_firstEntry = false;
_maxValue = _minValue = value;
_maxIndex = _minIndex = valueIndex;
return;
}
if (value >= _maxValue)
{
_maxValue = value;
_maxIndex = valueIndex;
} else if (_maxIndex == valueIndex)
{
_recalculateMinMax();
}
if (value <= _minValue)
{
_minValue = value;
_minIndex = valueIndex;
} else if (_minIndex == valueIndex)
{
_recalculateMinMax();
}
}
template<unsigned N>
uint16_t MemoryBuffer<N>::GetMaxMeasurement()
{
return _maxValue;
}
template<unsigned N>
int16_t MemoryBuffer<N>::GetMaxMeasurementIndex()
{
return (_index - _maxIndex + _size) % _size;
}
template<unsigned N>
uint16_t MemoryBuffer<N>::GetMinMeasurement()
{
return _minValue;
}
template<unsigned N>
int16_t MemoryBuffer<N>::GetMinMeasurementIndex()
{
return (_index - _minIndex + _size) % _size;
}
template<unsigned N>
void MemoryBuffer<N>::_recalculateMinMax()
{
_maxValue = _minValue = _values[_getArrayIndex(-1)];
_maxIndex = _minIndex = _getArrayIndex(-1);
for (uint16_t i = 0; i < (_size - 1); i++)
{
int16_t currentIndex = _getArrayIndex(i);
uint16_t currentValue = _values[currentIndex];
if (currentValue >= _maxValue)
{
_maxValue = currentValue;
_maxIndex = currentIndex;
}
if (currentValue <= _minValue)
{
_minValue = currentValue;
_minIndex = currentIndex;
}
}
}
template<unsigned N>
int16_t MemoryBuffer<N>::_getArrayIndex(int16_t index)
{
return (_index + index) % _size;
}
#endif | [
"[email protected]"
]
| |
250c7ae270ccdaf4da1a7493d54d287e178cdb48 | e21ebe9fbcc013a429d213e71e4a216473f679bb | /LeetCodeAnswer/ClimbingStairs/ClimbingStairs.cpp | d8319d374ee6b02fb7ffe9b16a076166aaa76c0a | []
| no_license | amoonfana/LeetCodeAnswer_CPP | a60b62c710e949a8fd608cb59dc6642c1e0f184d | aaf91cfd78262a097fa9633d612de9ef5598a2b0 | refs/heads/master | 2020-07-28T20:41:14.245000 | 2019-05-27T15:39:58 | 2019-05-27T15:39:58 | 73,696,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
//Fibonacci Formula
int climbStairs(int n) {
double sqrt5 = sqrt(5);
double fibn = pow((1 + sqrt5) / 2, n + 1) - pow((1 - sqrt5) / 2, n + 1);
return (int)(fibn / sqrt5);
}
////Fibonacci Number
//int climbStairs(int n) {
// bool flg = true;
// int a = 1, b = 0;
// for (int i = 1; i <= n; ++i) {
// if (flg) {
// b += a;
// flg = false;
// }
// else {
// a += b;
// flg = true;
// }
// }
// return flg ? a : b;
//}
};
void main()
{
Solution sol;
int n = 5;
cout << sol.climbStairs(n) << endl;
system("pause");
} | [
"[email protected]"
]
| |
450d8105a69a58d605ceca6705c6753c1237618a | 4815a0bc4b78159097998e101a413b8f6e640d38 | /ws_server/sources/VShared/FBL/publ/Values/FBL_Value_Time.cpp | 81c1b35e90fd92b651aba8df9a9b6775a7c344be | []
| no_license | Cempl/http-server-ws | 9dca21f6e21b794645927e729626aa5eb43a300a | c63a50bcbc22e2ba8c7c44c67e6b5b3fa05d10bc | refs/heads/master | 2020-12-25T04:55:18.472674 | 2018-06-21T04:29:25 | 2018-06-21T04:29:25 | 63,309,126 | 3 | 0 | null | 2018-05-27T06:45:01 | 2016-07-14T06:36:10 | C++ | UTF-8 | C++ | false | false | 20,812 | cpp | /**********************************************************************************************/
/* FBL_Value_Time.cpp */
/* */
/* Copyright Paradigma, 1998-2017 */
/* All Rights Reserved */
/**********************************************************************************************/
#include <VShared/FBL/publ/Headers/StdAfx.h>
#include <VShared/FBL/publ/Values/FBL_Value_Time.h>
// FBL:
#include <VShared/FBL/publ/Util_classes/FBL_DTFormat.h>
#include <VShared/FBL/publ/Util_classes/FBL_ToUChar.h>
#include <VShared/FBL/publ/Util_Strings/FBL_String_Len_Const.h>
#include <VShared/FBL/publ/Util_Strings/FBL_ustdio.h>
#include <VShared/FBL/publ/Utilities/FBL_DateTimeEncode.h>
/**********************************************************************************************/
FBL_Begin_Namespace
#pragma mark === Convert functions ===
/**********************************************************************************************/
void Convert_str_time_aa_fast(
const char* inString,
const DTFormat* inDTFormat,
TimeEncoded& outTimeEnc )
{
argused1( inDTFormat );
if( !inString || *inString == 0 )
{
outTimeEnc.encoded = 0;
return;
}
char c;
short unsigned int h, mn, s, ms; /// time
h = mn = s = ms = 0;
sscanf( inString, "%hu%c%hu%c%hu%c%hu", &h, &c, &mn, &c, &s, &c, &ms );
outTimeEnc.decoded.h = h;
outTimeEnc.decoded.m = mn;
outTimeEnc.decoded.s = s;
outTimeEnc.decoded.ms = ms;
}
/**********************************************************************************************/
// WRAPPER, from UChar* to char*
//
void Convert_str_time_uu_fast(
const UChar* inStr,
const UChar* inStrEnd,
const DTFormat* inDTFormat,
TimeEncoded& outTimeEnc )
{
char strTime[kTimeStrMaxLength + 1];
tslen len = tslen( inStrEnd - inStr );
vu_u2a(inStr, strTime, len);
Convert_str_time_aa_fast(strTime, inDTFormat, outTimeEnc );
}
#pragma mark -
/**********************************************************************************************/
tslen Convert_time_str_uu_fast(
const TimeEncoded& inTimeEnc,
const UChar inSep,
UChar* outString )
{
char strTime[kTimeStrMaxLength + 1];
tslen len = Convert_time_str_aa_fast(inTimeEnc, static_cast<char>(inSep), strTime);
vu_a2u(strTime, outString, len);
return len;
}
/**********************************************************************************************/
tslen Convert_time_str_aa_fast(
const TimeEncoded& inTimeEnc,
const char inSep,
char* outString )
{
unsigned int ms = (unsigned int)inTimeEnc.decoded.ms % 1000;
vuint32 Written = sprintf( outString, "%.2u%c%.2u%c%.2u%c%.3u",
inTimeEnc.decoded.h, (char)inSep,
inTimeEnc.decoded.m, (char)inSep,
inTimeEnc.decoded.s, (char)inSep,
ms );
tslen ToMap = static_cast<tslen>(Written > kTimeStrMaxLength ? kTimeStrMaxLength : Written);
outString[ToMap] = 0;
return ToMap;
}
#pragma mark -
#pragma mark === Convert from UChar* ===
/**********************************************************************************************/
// Convert functions
//
void Convert_str_time_aa_aux(
const char* inStr,
const DTFormat* inDTFormat,
TimeEncoded& ioTime )
{
if( !inStr || *inStr == 0 )
{
ioTime.encoded = 0;
return;
}
vint32 BadCharIndex = CheckTimeStringFormat( inStr, inDTFormat );
if( BadCharIndex )
{
throw xValueError(
ERR_TIME_VALUE_NOT_MATCH_FORMAT,
String(inStr).c_str(), ToUCharPtr(BadCharIndex).c_str() );
}
// Now we know that string STRICTLY correspond to expected format,
// so we can do fast extracting of numbers using scanf()
Convert_str_time_aa_fast( inStr, inDTFormat, ioTime );
// Final step - we check that extracted numbers fit limits:
if( CheckTimeValueLimits( ioTime ) == false )
throw xValueError( ERR_TIME_VALUE_HAVE_WRONG_NUMBERS, inStr );
}
/**********************************************************************************************/
// WRAPPER: UChar* => char*
//
void Convert_str_time_uu_aux(
const UChar* inStr,
const UChar* inStrEnd,
const DTFormat* inDTFormat,
TimeEncoded& ioTime )
{
if( !inStr )
return;
char strTime[kTimeStrMaxLength + 1];
tslen len = inStrEnd ? tslen(inStrEnd - inStr) : vu_strlen(inStr);
vu_u2a(inStr, strTime, len);
Convert_str_time_aa_aux( strTime, inDTFormat, ioTime );
}
#pragma mark -
#pragma mark === Convert to/from string value ===
/**********************************************************************************************/
// Convert functions
//
void Convert_str_time(
const I_Value* inValue,
I_Value* outValue )
{
I_ValueTime* pValueTime = dcast< I_ValueTime* >( outValue );
const DTFormat* pDTFormat = pValueTime->get_DTFormat();
Convert_str_time_uu_aux(
(UChar*) inValue->begin(),
(UChar*) inValue->end(),
pDTFormat,
*(TimeEncoded*) outValue->begin() );
}
/**********************************************************************************************/
void Convert_time_str(
const I_Value* inValue,
I_Value* outValue )
{
const I_ValueTime* pValueTime = dcast< const I_ValueTime* >( inValue );
const DTFormat* pDTFormat = pValueTime->get_DTFormat();
char strTime[kTimeStrMaxLength + 1];
tslen len = Convert_time_str_aa_fast(*(TimeEncoded*)inValue->begin(), static_cast<char>(pDTFormat->mTimeSep), strTime);
vuint32 outValueLen = outValue->get_MaxChars();
len = ( (tslen)outValueLen < len ) ? outValueLen : len;
vu_a2u(strTime, (UChar*) outValue->begin(), len);
outValue->put_ByteLength( len * sizeof(UChar) );
}
/**********************************************************************************************/
void Convert_bin_time(
const I_Value* inValue,
I_Value* outValue );
void Convert_bin_time(
const I_Value* inValue,
I_Value* outValue )
{
I_ValueTime* pValueTime = dcast< I_ValueTime* >( outValue );
const DTFormat* pDTFormat = pValueTime->get_DTFormat();
// TODO:
// Currently we assume inValue is a single-byted string.
// After we make everything localizable we can improve this using IOConverter as we do
// for string values.
//
const char* pBinStart = inValue->begin();
const char* pBinEnd = inValue->end();
if( pBinStart )
{
char strTime[kTimeStrMaxLength + 1];
tslen len = tslen(pBinEnd - pBinStart);
memcpy( strTime, pBinStart, Min(len, (tslen)kTimeStrMaxLength) );
Convert_str_time_aa_aux(
strTime,
pDTFormat,
*(TimeEncoded*) outValue->begin() );
}
}
#pragma mark -
#pragma mark === Value_time_imp ===
/**********************************************************************************************/
Value_time_imp::~Value_time_imp( void )
{
if( mDTFormatOwner )
ForgetObject(mDTFormat);
}
/**********************************************************************************************/
Value_time_imp::Value_time_imp( I_Database_Ptr inpDatabase )
{
if( inpDatabase )
{
mpDatabase = inpDatabase.get();
mDTFormat = nullptr;
mDTFormatOwner = false;
}
else
{
mpDatabase = nullptr;
mDTFormat = new DTFormat();
mDTFormatOwner = true;
}
}
/**********************************************************************************************/
Value_time_imp::Value_time_imp( const DTFormat* inDTFormat )
{
mpDatabase = nullptr;
if (inDTFormat)
{
mDTFormat = inDTFormat;
mDTFormatOwner = false;
}
else
{
mDTFormat = new DTFormat();
mDTFormatOwner = true;
}
}
/**********************************************************************************************/
Value_time_imp::Value_time_imp( const Value_time_imp& inOther )
:
Value_Numeric< kTypeTime, vcTime, policyInPlace_ulong >( inOther )
{
mpDatabase = inOther.mpDatabase;
mDTFormat = inOther.mDTFormat;
mDTFormatOwner = false;
}
#pragma mark -
/**********************************************************************************************/
const DTFormat* Value_time_imp::get_DTFormat( void ) const
{
FBL_CHECK( mpDatabase || mDTFormat );
return (mpDatabase) ? mpDatabase->get_DTFormat() : mDTFormat;
}
/**********************************************************************************************/
vuint16 Value_time_imp::get_Hours( void ) const
{
vuint16 result = ((TimeEncoded&)mValue).decoded.h;
return result;
}
/**********************************************************************************************/
void Value_time_imp::put_Hours( vuint16 inHours )
{
((TimeEncoded&)mValue).decoded.h = inHours;
put_IsNull( false );
}
/**********************************************************************************************/
vuint16 Value_time_imp::get_Minutes( void ) const
{
vuint16 result = ((TimeEncoded&)mValue).decoded.m;
return result;
}
/**********************************************************************************************/
void Value_time_imp::put_Minutes( vuint16 inMinutes )
{
((TimeEncoded&)mValue).decoded.m = inMinutes;
put_IsNull( false );
}
/**********************************************************************************************/
vuint16 Value_time_imp::get_Seconds( void ) const
{
vuint32 result = (vuint32) ((TimeEncoded&)mValue).decoded.s;
return static_cast<vuint16>(result);
}
/**********************************************************************************************/
void Value_time_imp::put_Seconds( vuint16 inSeconds )
{
TimeEncoded& te = (TimeEncoded&) mValue;
te.decoded.s = inSeconds;
put_IsNull( false );
}
/**********************************************************************************************/
vuint16 Value_time_imp::get_Milliseconds( void ) const
{
vuint16 result = ((TimeEncoded&)mValue).decoded.ms;
return result;
}
/**********************************************************************************************/
void Value_time_imp::put_Milliseconds( vuint16 inMilliseconds )
{
((TimeEncoded&)mValue).decoded.ms = inMilliseconds;
}
/**********************************************************************************************/
void Value_time_imp::get_Time(
vuint16& outHours,
vuint16& outMinutes,
vuint16& outSeconds,
vuint16& outMilliseconds ) const
{
TimeEncoded& te = (TimeEncoded&)mValue;
outHours = (vuint16) te.decoded.h;
outMinutes = (vuint16) te.decoded.m;
vuint32 secs = (vuint32) te.decoded.s;
outSeconds = (vuint16)secs;
outMilliseconds = te.decoded.ms;
}
/**********************************************************************************************/
void Value_time_imp::put_Time(
vuint16 inHours,
vuint16 inMinutes,
vuint16 inSeconds,
vuint16 inMilliseconds )
{
TimeEncoded& te = (TimeEncoded&)mValue;
te.decoded.h = inHours;
te.decoded.m = inMinutes;
te.decoded.s = inSeconds;
te.decoded.ms = inMilliseconds;
put_IsNull( false );
}
/**********************************************************************************************/
String Value_time_imp::get_String( tslen inLimit ) const
{
String str;
if( inLimit != 0 )
{
UChar* p = str.getBuffer(kTimeStrMaxLength + 1);
const DTFormat* pDTFormat = get_DTFormat();
Convert_time_str_uu_fast(
(TimeEncoded&)mValue, pDTFormat->mTimeSep, p );
str.releaseBuffer(kTimeStrMaxLength);
// not -1 and less than maxLen
if( inLimit > 0 && vuint32(inLimit) < kTimeStrMaxLength )
{
str.truncate( inLimit );
}
}
return str;
}
/**********************************************************************************************/
void Value_time_imp::put_String( const String& inStr )
{
if( inStr.isSingleByte() )
put_String( inStr.getBufferA() );
else
put_String( inStr.c_str() );
}
/**********************************************************************************************/
UChar* Value_time_imp::get_String(
UChar* outString,
tslen inBufferChars ) const
{
// The size of input buffer (inBufferChars) cannot be -1 !
// Because this is unsafe then to write to the memory
// location pointed by outString - because we don't know the size !
if( outString == nullptr || inBufferChars <= 0 )
return nullptr;
UChar* pEnd = nullptr;
if( inBufferChars < tslen(kTimeStrMaxLength) )
{
String res( get_String( inBufferChars ) );
tslen len = res.length();
memcpy( outString, res.begin(), len * sizeof(UChar) );
*(outString + len) = 0;
pEnd = outString + len;
}
else
{
const DTFormat* pDTFormat = get_DTFormat();
Convert_time_str_uu_fast(
(TimeEncoded&)mValue, pDTFormat->mTimeSep, outString );
pEnd = outString + kTimeStrMaxLength;
}
return pEnd;
}
/**********************************************************************************************/
void Value_time_imp::put_String(
const UChar* inStart,
const UChar* inEnd )
{
argused1( inEnd );
const DTFormat* pDTFormat = get_DTFormat();
Convert_str_time_uu_aux( inStart, inEnd, pDTFormat, (TimeEncoded&)mValue );
put_IsNull( false );
}
/**********************************************************************************************/
char* Value_time_imp::get_String(
char* outString,
tslen inBufferChars ) const
{
// The size of input buffer (inBufferChars) cannot be -1 !
// Because this is unsafe then to write to the memory
// location pointed by outString - because we don't know the size !
if( outString == nullptr || inBufferChars <= 0 )
return nullptr;
char* pEnd = nullptr;
if( inBufferChars < tslen(kTimeStrMaxLength) )
{
String res( get_String( inBufferChars ) );
tslen len = res.length();
memcpy( outString, res.getBufferA(), len );
*(outString + len) = 0;
pEnd = outString + len;
}
else
{
const DTFormat* pDTFormat = get_DTFormat();
Convert_time_str_aa_fast(
(TimeEncoded&)mValue, static_cast<char>(pDTFormat->mTimeSep), outString );
pEnd = outString + kTimeStrMaxLength;
}
return pEnd;
}
/**********************************************************************************************/
void Value_time_imp::put_String( const char* inStart, const char* inEnd )
{
argused1( inEnd );
const DTFormat* pDTFormat = get_DTFormat();
Convert_str_time_aa_aux( inStart, pDTFormat, (TimeEncoded&)mValue );
put_IsNull( false );
}
/**********************************************************************************************/
vuint32 Value_time_imp::get_MaxChars( void ) const
{
return kTimeStrMaxLength;
}
#pragma mark -
#pragma mark === Value_time ===
/**********************************************************************************************/
Value_time::~Value_time( void )
{
}
/**********************************************************************************************/
Value_time::Value_time( I_Database_Ptr inpDatabase )
:
Value_time_imp( inpDatabase )
{
}
/**********************************************************************************************/
Value_time::Value_time( const DTFormat* inDTFormat )
:
Value_time_imp( inDTFormat )
{
}
/**********************************************************************************************/
Value_time::Value_time( const Value_time& inOther )
:
Value_time_imp( inOther )
{
}
/**********************************************************************************************/
Value_time::Value_time(
vuint16 inHours,
vuint16 inMinutes,
vuint16 inSeconds,
vuint16 inMilliseconds,
const DTFormat* inDTFormat )
:
Value_time_imp( inDTFormat )
{
put_Time( inHours, inMinutes, inSeconds, inMilliseconds );
}
/**********************************************************************************************/
I_Value_Ptr Value_time::Clone( bool inCopyData ) const
{
I_Value_Ptr result = new Value_time( *this );
if( inCopyData == false )
result->put_IsNull( true );
result->put_IsRemote(mIsRemote);
return result;
}
#pragma mark === Value_time_null ===
/**********************************************************************************************/
Value_time_null::~Value_time_null( void )
{
}
/**********************************************************************************************/
Value_time_null::Value_time_null( I_Database_Ptr inpDatabase )
:
Value_time( inpDatabase )
{
}
/**********************************************************************************************/
Value_time_null::Value_time_null( const DTFormat* inDTFormat )
:
Value_time( inDTFormat )
{
}
/**********************************************************************************************/
Value_time_null::Value_time_null( const Value_time_null& inOther )
:
Value_time( inOther )
{
put_IsNull( inOther.get_IsNull() );
}
/**********************************************************************************************/
Value_time_null::Value_time_null(
vuint16 inHours,
vuint16 inMinutes,
vuint16 inSeconds,
vuint16 inMilliseconds,
const DTFormat* inDTFormat )
:
Value_time( inHours, inMinutes, inSeconds, inMilliseconds, inDTFormat )
{
put_IsNull(false);
}
#pragma mark -
/**********************************************************************************************/
I_Value_Ptr Value_time_null::Clone( bool inCopyData ) const
{
I_Value_Ptr result = new Value_time_null( *this );
if( inCopyData == false )
result->put_IsNull( true );
result->put_IsRemote(mIsRemote);
return result;
}
/**********************************************************************************************/
int Value_time_null::Compare(
const I_Value& inOther,
COMPARE_TYPE inCompareType ) const
{
argused1( inCompareType );
FBL_CHECK( get_Type() == inOther.get_Type() );
// If one of values (this or inOther) have null...
if( get_IsNull() )
{
if( inOther.get_IsNull() )
return 0; // Both are NULL
else
return -1; // Any NULL is less then NOT NULL
}
else
{
if( inOther.get_IsNull() )
return 1; // Any NOT NULL is greater then NULL
else
{
// ... have not null values - compare them.
return Value_time::Compare( inOther );
}
}
}
/**********************************************************************************************/
bool Value_time_null::get_IsNull( void ) const
{
return PN::get_IsNull();
}
/**********************************************************************************************/
void Value_time_null::put_IsNull( bool inValue )
{
PN::put_IsNull( PS::get_ValuePtr(), inValue );
}
/**********************************************************************************************/
String Value_time_null::get_String( tslen inLimit ) const
{
if( get_IsNull() )
return String::sEmpty();
return Value_time::get_String(inLimit);
}
/**********************************************************************************************/
UChar* Value_time_null::get_String(
UChar* outString,
tslen inBufferChars ) const
{
if( get_IsNull() )
if( inBufferChars > 0 )
{
outString[0] = 0;
return outString;
}
return Value_time::get_String(outString, inBufferChars);
}
/**********************************************************************************************/
char* Value_time_null::get_String(
char* outString,
tslen inBufferChars ) const
{
if( get_IsNull() )
if( inBufferChars > 0 )
{
outString[0] = 0;
return outString;
}
return Value_time::get_String(outString, inBufferChars);
}
/**********************************************************************************************/
//#if FBL_TEST_CODE
/**********************************************************************************************/
void Value_time_imp::Init( void )
{
// Used in tests only so make it just for our datetime parser be happy.
put_Hours(0);
put_Minutes(0);
put_Seconds(0);
put_Milliseconds(1);
}
/**********************************************************************************************/
void Value_time_imp::Increment( void )
{
// Used in tests only so make it just for our datetime parser be happy.
if( mValue == 0 )
{
Init();
return;
}
vuint16 hours = get_Hours();
vuint16 minutes = get_Minutes();
vuint16 seconds = get_Seconds();
vuint16 ms = get_Milliseconds();
if( ms < 999 )
{
put_Milliseconds( ++ms );
}
else if( seconds < 59 )
{
put_Milliseconds(0);
put_Seconds( ++seconds );
}
else if( minutes < 59 )
{
put_Milliseconds(0);
put_Seconds(0);
put_Minutes( ++minutes );
}
else if( hours < 24 )
{
put_Milliseconds(0);
put_Seconds(0);
put_Minutes(0);
put_Hours( ++hours );
}
else
{
// no nore time which makes parser happy. Actually we rarelly get here.
Init();
}
}
//#endif // FBL_TEST_CODE
/**********************************************************************************************/
FBL_End_Namespace
| [
"[email protected]"
]
| |
bb1c7853d3c157629023ea08e110945bed314500 | 928f4876b1ee963bef2139edab3e28daf4a9de9c | /bn/Dlg1.h | beca142c254884569394a5122e30efbb6ee8edb4 | []
| no_license | ms930602/BNumber | a5a7e198254af2791258c149a7bacff2aa461c78 | 2dffafa244d7ae1a4674582e874666ff79ac693b | refs/heads/master | 2020-03-21T03:28:54.193192 | 2018-07-01T14:33:44 | 2018-07-01T14:33:44 | 138,047,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 102 | h | #pragma once
#include "afxdialogex.h"
class Dlg1 :
public CDialogEx
{
public:
Dlg1();
~Dlg1();
};
| [
"[email protected]"
]
| |
0bcd9b00fadae3af440fd9b8b12815e7ec61c856 | 2a7b4d774b46b9b45ff6992528fbb0cfc73e113c | /include/amqpcpp/deferredconfirmedpublish.h | 9d36c3ff648444b06c4b80c792ccda3155a8df98 | [
"Apache-2.0"
]
| permissive | tarhan/AMQP-CPP | 02dbf2436ca59bebc67dff5ef13a4e30690cfc9f | 98a43d8e5b939b06fa86daac8599c6f0233763d6 | refs/heads/master | 2022-12-28T17:38:39.056577 | 2020-10-14T20:25:32 | 2020-10-14T20:25:32 | 283,503,224 | 0 | 0 | Apache-2.0 | 2020-07-29T13:13:52 | 2020-07-29T13:13:51 | null | UTF-8 | C++ | false | false | 3,535 | h | /**
* DeferredConfirmedPublish.h
*
* Deferred callback for RabbitMQ-specific publisher confirms mechanism per-message.
*
* @author Michael van der Werve <[email protected]>
* @copyright 2020 Copernica BV
*/
/**
* Include guard
*/
#pragma once
/**
* Set up namespace
*/
namespace AMQP {
/**
* We extend from the default deferred and add extra functionality
*/
class DeferredConfirmedPublish : public Deferred
{
private:
/**
* Callback to execute when server confirms that message is processed
* @var AckCallback
*/
PublishAckCallback _ackCallback;
/**
* Callback to execute when server sends negative acknowledgement
* @var NackCallback
*/
PublishNackCallback _nackCallback;
/**
* Callback to execute when message is lost (nack / error)
* @var LostCallback
*/
PublishLostCallback _lostCallback;
/**
* Report an ack, calls the callback.
*/
void reportAck()
{
// check if the callback is set
if (_ackCallback) _ackCallback();
}
/**
* Report an nack, calls the callback if set.
*/
void reportNack()
{
// check if the callback is set
if (_nackCallback) _nackCallback();
// message is 'lost'
if (_lostCallback) _lostCallback();
}
/**
* Indicate failure
* @param error Description of the error that occured
*/
void reportError(const char *error)
{
// from this moment on the object should be listed as failed
_failed = true;
// message is lost
if (_lostCallback) _lostCallback();
// execute callbacks if registered
if (_errorCallback) _errorCallback(error);
}
/**
* The wrapped confirmed channel implementation may call our
* private members and construct us
*/
friend class Confirmed;
public:
/**
* Protected constructor that can only be called
* from within the channel implementation
*
* Note: this constructor _should_ be protected, but because make_shared
* will then not work, we have decided to make it public after all,
* because the work-around would result in not-so-easy-to-read code.
*
* @param boolean are we already failed?
*/
DeferredConfirmedPublish(bool failed = false) : Deferred(failed) {}
public:
/**
* Callback that is called when the broker confirmed message publication
* @param callback the callback to execute
*/
DeferredConfirmedPublish &onAck(const PublishAckCallback &callback)
{
// store callback
_ackCallback = callback;
// allow chaining
return *this;
}
/**
* Callback that is called when the broker denied message publication
* @param callback the callback to execute
*/
DeferredConfirmedPublish &onNack(const PublishNackCallback &callback)
{
// store callback
_nackCallback = callback;
// allow chaining
return *this;
}
/**
* Callback that is called when a message is lost, either through RabbitMQ
* rejecting it or because of a channel error
* @param callback the callback to execute
*/
DeferredConfirmedPublish &onLost(const PublishLostCallback &callback)
{
// store callback
_lostCallback = callback;
// allow chaining
return *this;
}
};
/**
* End namespace
*/
}
| [
"[email protected]"
]
| |
9707b7757f5828d29fc9c23022a523e5d9d71701 | 33392bbfbc4abd42b0c67843c7c6ba9e0692f845 | /ultrasound/L1/include/mulVV/mulVV.cpp | f4991892a73cf2efb39b617ca06f8ba65ff9990c | [
"Apache-2.0"
]
| permissive | Xilinx/Vitis_Libraries | bad9474bf099ed288418430f695572418c87bc29 | 2e6c66f83ee6ad21a7c4f20d6456754c8e522995 | refs/heads/main | 2023-07-20T09:01:16.129113 | 2023-06-08T08:18:19 | 2023-06-08T08:18:19 | 210,433,135 | 785 | 371 | Apache-2.0 | 2023-07-06T21:35:46 | 2019-09-23T19:13:46 | C++ | UTF-8 | C++ | false | false | 2,549 | cpp | /*
* Copyright 2022 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "kernels.hpp"
namespace us {
namespace L1 {
template <typename T, const unsigned int LEN, const unsigned int INCREMENT, const unsigned VECDIM>
void mulVV(adf::input_buffer<T>& __restrict in1,
adf::input_buffer<T>& __restrict in2,
adf::output_buffer<T>& __restrict out) {
T* __restrict p_in1 = in1.data();
T* __restrict p_in2 = in2.data();
T* __restrict p_out = out.data();
aie::vector<T, VECDIM> op1 = aie::zeros<T, VECDIM>();
aie::vector<T, VECDIM> op2 = aie::zeros<T, VECDIM>();
aie::vector<T, VECDIM> res = aie::zeros<T, VECDIM>();
for (unsigned i = 0; i < LEN; i += INCREMENT) {
op1 = aie::load_v<VECDIM>(p_in1);
op2 = aie::load_v<VECDIM>(p_in2);
p_in1 = byte_incr(p_in1, VECDIM * sizeof(T));
p_in2 = byte_incr(p_in2, VECDIM * sizeof(T));
res = aie::mul(op1, op2);
aie::store_v(p_out, res);
p_out = byte_incr(p_out, VECDIM * sizeof(T));
}
};
template <typename T, const unsigned int LEN, const unsigned int INCREMENT, const unsigned VECDIM>
void mulVVStreamOut(adf::input_buffer<T>& __restrict in1,
adf::input_buffer<T>& __restrict in2,
adf::output_buffer<T>& __restrict out) {
T* __restrict p_in1 = in1.data();
T* __restrict p_in2 = in2.data();
T* __restrict p_out = out.data();
aie::vector<T, VECDIM> op1 = aie::zeros<T, VECDIM>();
aie::vector<T, VECDIM> op2 = aie::zeros<T, VECDIM>();
aie::vector<T, VECDIM> res = aie::zeros<T, VECDIM>();
for (unsigned i = 0; i < LEN; i += INCREMENT) {
op1 = aie::load_v<VECDIM>(p_in1);
op2 = aie::load_v<VECDIM>(p_in2);
p_in1 = byte_incr(p_in1, VECDIM * sizeof(T));
p_in2 = byte_incr(p_in2, VECDIM * sizeof(T));
res = aie::mul(op1, op2);
aie::store_v(p_out, res);
p_out = byte_incr(p_out, VECDIM * sizeof(T));
}
};
} // namespace L1
} // namespace us
| [
"[email protected]"
]
| |
7d5302539af8d65d47d3060cc07dc7558598c058 | d976eb3bf136ec04c2287cc196c22a8a3a1081eb | /alg/splay_linkcut.cc | 2d630208fc7d377b9dea35ebae397620df01db9e | []
| no_license | idemura/codecon | 4060995ae5ece108c1ee18a10a71b21cf03306ef | 4dcd966c5c52618903e643303c791ab7e700553f | refs/heads/master | 2020-04-22T01:08:32.407524 | 2019-12-22T07:58:33 | 2019-12-22T07:58:33 | 170,004,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,520 | cc | #include "tree.h"
void test1() {
auto n10 = make_node(10);
auto n30 = make_node(30);
auto n40 = make_node(40);
auto n50 = make_node(50);
auto n60 = make_node(60);
auto n80 = make_node(80);
auto n90 = make_node(90);
link(n50, link(n30, n10, n40), link(n80, n60, n90));
auto sub = splay_split(n50);
CHECK(sub.first == n50 && sub.second == n80);
CHECK(n50->root());
CHECK(n80->root());
CHECK(walk(n50) == vector<int>({50, 30, 10, 0, 0, 40, 0, 0, 0}));
CHECK(walk(n80) == vector<int>({80, 60, 0, 0, 90, 0, 0}));
auto linked = splay_join(sub.first, sub.second);
CHECK(walk(linked) ==
vector<int>({50, 30, 10, 0, 0, 40, 0, 0, 80, 60, 0, 0, 90, 0, 0}));
delete_tree(linked);
}
void test2() {
auto n10 = make_node(10);
auto n30 = make_node(30);
auto n40 = make_node(40);
auto n50 = make_node(50);
auto n60 = make_node(60);
auto n80 = make_node(80);
auto n90 = make_node(90);
link(n50, link(n30, n10, n40), link(n80, n60, n90));
auto sub = splay_split(n40);
CHECK(sub.first == n40 && sub.second == n50);
CHECK(n40->root());
CHECK(n50->root());
CHECK(walk(n40) == vector<int>({40, 30, 10, 0, 0, 0, 0}));
CHECK(walk(n50) == vector<int>({50, 0, 80, 60, 0, 0, 90, 0, 0}));
auto linked = splay_join(sub.first, sub.second);
CHECK(walk(linked) ==
vector<int>({40, 30, 10, 0, 0, 0, 50, 0, 80, 60, 0, 0, 90, 0, 0}));
delete_tree(linked);
}
void test3() {
auto n10 = make_node(10);
auto n30 = make_node(30);
auto n40 = make_node(40);
auto n50 = make_node(50);
auto n60 = make_node(60);
auto n80 = make_node(80);
auto n90 = make_node(90);
link(n50, link(n30, n10, n40), link(n80, n60, n90));
auto sub = splay_split(n80);
CHECK(sub.first == n80 && sub.second == n90);
CHECK(n80->root());
CHECK(n90->root());
CHECK(walk(n80) ==
vector<int>({80, 50, 30, 10, 0, 0, 40, 0, 0, 60, 0, 0, 0}));
CHECK(walk(n90) == vector<int>({90, 0, 0}));
// Move 60 to root.
splay(n60);
CHECK(walk(n60) ==
vector<int>({60, 50, 30, 10, 0, 0, 40, 0, 0, 0, 80, 0, 0}));
auto linked = splay_join(sub.first, sub.second);
CHECK(walk(linked) ==
vector<int>({80, 60, 50, 30, 10, 0, 0, 40, 0, 0, 0, 0, 90, 0, 0}));
delete_tree(linked);
}
int main(int argc, char **argv) {
ios_base::sync_with_stdio(false);
test1();
test2();
test3();
cout << "TESTS PASSED." << endl;
return 0;
}
| [
"[email protected]"
]
| |
b32379e774e305b8d0cc30348374410ccc5cc35a | b69ae70cc9ce2aa77b667af87d0540f03daa53b7 | /dynamixel_workbench_controllers/src/dynamixel_workbench_multi_port.cpp | 221a7e55bbe9a8db270f5387e31d22927bbea833 | [
"BSD-3-Clause"
]
| permissive | Jmeyer1292/dynamixel-workbench | 50a4dafee80a590a82725af543ab50131590ec25 | 850fd560bd1e1739c303a412770108dc94ab9eac | refs/heads/master | 2021-09-05T19:36:07.516807 | 2017-05-23T04:14:04 | 2017-05-23T04:14:04 | 116,590,378 | 0 | 0 | null | 2018-01-07T18:48:33 | 2018-01-07T18:48:33 | null | UTF-8 | C++ | false | false | 26,590 | cpp | /*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* 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 ROBOTIS 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 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.
*******************************************************************************/
/* Author: Taehoon Lim (Darby) */
#include "dynamixel_workbench_controllers/dynamixel_workbench_multi_port.h"
using namespace dynamixel_workbench_multi_port;
DynamixelWorkbenchMultiPort::DynamixelWorkbenchMultiPort()
:nh_priv_("~"),
is_debug_(false),
pan_motor_device_name_(""),
pan_motor_baud_rate_(0),
pan_motor_model_(""),
pan_motor_id_(0),
pan_motor_protocol_version_(0.0),
tilt_motor_device_name_(""),
tilt_motor_baud_rate_(0),
tilt_motor_model_(""),
tilt_motor_id_(0),
tilt_motor_protocol_version_(0.0),
profile_velocity_(0),
profile_acceleration_(0)
{
// Init parameter
nh_.param("is_debug", is_debug_, is_debug_);
nh_priv_.getParam("pan_motor/device_name", pan_motor_device_name_);
nh_priv_.getParam("pan_motor/baud_rate", pan_motor_baud_rate_);
nh_priv_.getParam("pan_motor/motor_model", pan_motor_model_);
nh_priv_.getParam("pan_motor/protocol_version", pan_motor_protocol_version_);
nh_priv_.getParam("pan_motor/motor_id", pan_motor_id_);
nh_priv_.getParam("tilt_motor/device_name", tilt_motor_device_name_);
nh_priv_.getParam("tilt_motor/baud_rate", tilt_motor_baud_rate_);
nh_priv_.getParam("tilt_motor/motor_model", tilt_motor_model_);
nh_priv_.getParam("tilt_motor/protocol_version", tilt_motor_protocol_version_);
nh_priv_.getParam("tilt_motor/motor_id", tilt_motor_id_);
nh_priv_.getParam("profile_velocity", profile_velocity_);
nh_priv_.getParam("profile_acceleration", profile_acceleration_);
// Init target name
ROS_ASSERT(initDynamixelWorkbenchMultiPort());
// Initialize PortHandler instance
// Set the port path
// Get methods and members of PortHandlerLinux
pan_motor_portHandler_ = dynamixel::PortHandler::getPortHandler(pan_motor_device_name_.c_str());
tilt_motor_portHandler_ = dynamixel::PortHandler::getPortHandler(tilt_motor_device_name_.c_str());
// Initialize PacketHandler instance
// Set the protocol version
// Get methods and members of Protocol 2.0 PacketHandler
pan_motor_packetHandler_ = dynamixel::PacketHandler::getPacketHandler(pan_motor_protocol_version_);
tilt_motor_packetHandler_ = dynamixel::PacketHandler::getPacketHandler(tilt_motor_protocol_version_);
// init ROS Publish
dynamixel_state_pub_ = nh_.advertise<dynamixel_workbench_msgs::MotorStateList>("/dynamixel_workbench_multi_port/motor_state",10);
// init ROS Server
multi_port_control_server = nh_.advertiseService("/dynamixel_workbench_tutorials/pan_tilt", &DynamixelWorkbenchMultiPort::controlPanTiltMotorCallback, this);
// Open port
if (pan_motor_portHandler_->openPort())
{
ROS_INFO("Succeeded to open the pan_motor_port(%s)!", pan_motor_device_name_.c_str());
}
else
{
ROS_ERROR("Failed to open the pan_motor_port!");
ROS_ASSERT(shutdownDynamixelWorkbenchMultiPort());
}
// Set port baudrate
if (pan_motor_portHandler_->setBaudRate(pan_motor_baud_rate_))
{
ROS_INFO("Succeeded to change the pan_motor_baudrate(%d)\n!", pan_motor_portHandler_->getBaudRate());
}
else
{
ROS_ERROR("Failed to change the pan_motor_baudrate!");
ROS_ASSERT(shutdownDynamixelWorkbenchMultiPort());
}
ROS_INFO("pan_motor_device_name: %s", pan_motor_device_name_.c_str());
ROS_INFO("pan_motor_baud_rate: %d", pan_motor_baud_rate_);
ROS_INFO("pan_motor_protocol_version_: %.1f", pan_motor_protocol_version_);
ROS_INFO("pan_motor_id: %d", pan_motor_id_);
ROS_INFO("pan_motor_model: %s\n", pan_motor_model_.c_str());
initMotor(pan_motor_model_, pan_motor_id_, pan_motor_protocol_version_);
// Open port
if (tilt_motor_portHandler_->openPort())
{
ROS_INFO("Succeeded to open the tilt_motor_port(%s)!", tilt_motor_device_name_.c_str());
}
else
{
ROS_ERROR("Failed to open the tilt_motor_port!");
ROS_ASSERT(shutdownDynamixelWorkbenchMultiPort());
}
// Set port baudrate
if (tilt_motor_portHandler_->setBaudRate(tilt_motor_baud_rate_))
{
ROS_INFO("Succeeded to change the tilt_motor_baudrate(%d)\n!", tilt_motor_portHandler_->getBaudRate());
}
else
{
ROS_ERROR("Failed to change the tilt_motor_baudrate!");
ROS_ASSERT(shutdownDynamixelWorkbenchMultiPort());
}
ROS_INFO("tilt_motor_device_name: %s", tilt_motor_device_name_.c_str());
ROS_INFO("tilt_motor_baud_rate: %d", tilt_motor_baud_rate_);
ROS_INFO("tilt_motor_protocol_version_: %.1f", tilt_motor_protocol_version_);
ROS_INFO("tilt_motor_id: %d", tilt_motor_id_);
ROS_INFO("tilt_motor_model: %s\n", tilt_motor_model_.c_str());
initMotor(tilt_motor_model_, tilt_motor_id_, tilt_motor_protocol_version_);
writeTorque(true);
writeProfile(profile_velocity_, profile_acceleration_);
}
DynamixelWorkbenchMultiPort::~DynamixelWorkbenchMultiPort()
{
ROS_ASSERT(shutdownDynamixelWorkbenchMultiPort());
}
bool DynamixelWorkbenchMultiPort::initDynamixelWorkbenchMultiPort(void)
{
ROS_INFO("dynamixel_workbench_multi_port : Init OK!");
return true;
}
bool DynamixelWorkbenchMultiPort::shutdownDynamixelWorkbenchMultiPort(void)
{
writeTorque(false);
pan_motor_portHandler_->closePort();
tilt_motor_portHandler_->closePort();
ros::shutdown();
return true;
}
bool DynamixelWorkbenchMultiPort::initMotor(std::string motor_model, uint8_t motor_id, float protocol_version)
{
dynamixel_tool::DynamixelTool *dynamixel_motor = new dynamixel_tool::DynamixelTool(motor_id, motor_model, protocol_version);
dynamixel_.push_back(dynamixel_motor);
}
bool DynamixelWorkbenchMultiPort::writeDynamixelRegister(dynamixel::PortHandler *portHandler, dynamixel::PacketHandler *packetHandler, uint8_t id, uint16_t addr, uint8_t length, int64_t value)
{
uint8_t dynamixel_error = 0;
int dynamixel_comm_result = COMM_TX_FAIL;
if (length == 1)
{
dynamixel_comm_result = packetHandler->write1ByteTxRx(portHandler, id, addr, (int8_t)value, &dynamixel_error);
}
else if (length == 2)
{
dynamixel_comm_result = packetHandler->write2ByteTxRx(portHandler, id, addr, (int16_t)value, &dynamixel_error);
}
else if (length == 4)
{
dynamixel_comm_result = packetHandler->write4ByteTxRx(portHandler, id, addr, (int32_t)value, &dynamixel_error);
}
if (dynamixel_comm_result == COMM_SUCCESS)
{
if (dynamixel_error != 0)
{
packetHandler->printRxPacketError(dynamixel_error);
}
return true;
}
else
{
packetHandler->printTxRxResult(dynamixel_comm_result);
ROS_ERROR("[ID] %u, Fail to write!", id);
return false;
}
}
bool DynamixelWorkbenchMultiPort::readDynamixelRegister(dynamixel::PortHandler *portHandler, dynamixel::PacketHandler *packetHandler, uint8_t id, uint16_t addr, uint8_t length, int64_t *value)
{
uint8_t dynamixel_error = 0;
int8_t dynamixel_comm_result_;
int8_t value_8_bit = 0;
int16_t value_16_bit = 0;
int32_t value_32_bit = 0;
if (length == 1)
{
dynamixel_comm_result_ = packetHandler->read1ByteTxRx(portHandler, id, addr, (uint8_t*)&value_8_bit, &dynamixel_error);
}
else if (length == 2)
{
dynamixel_comm_result_ = packetHandler->read2ByteTxRx(portHandler, id, addr, (uint16_t*)&value_16_bit, &dynamixel_error);
}
else if (length == 4)
{
dynamixel_comm_result_ = packetHandler->read4ByteTxRx(portHandler, id, addr, (uint32_t*)&value_32_bit, &dynamixel_error);
}
if (dynamixel_comm_result_ == COMM_SUCCESS)
{
if (dynamixel_error != 0)
{
packetHandler->printRxPacketError(dynamixel_error);
}
if (length == 1)
{
*value = value_8_bit;
return true;
}
else if (length == 2)
{
*value = value_16_bit;
return true;
}
else if (length == 4)
{
*value = value_32_bit;
return true;
}
}
else
{
packetHandler->printTxRxResult(dynamixel_comm_result_);
ROS_ERROR("[ID] %u, Fail to read!", id);
return false;
}
}
bool DynamixelWorkbenchMultiPort::writeTorque(bool onoff)
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["torque_enable"];
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["torque_enable"];
if (onoff == true)
{
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, true);
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, true);
}
else
{
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, false);
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, false);
}
}
bool DynamixelWorkbenchMultiPort::writeProfile(int velocity, int acceleration)
{
if (!strncmp(pan_motor_model_.c_str(), "AX", 2) || !strncmp(pan_motor_model_.c_str(), "RX", 2) || !strncmp(pan_motor_model_.c_str(), "EX", 2))
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["moving_speed"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, velocity);
}
else if (!strncmp(pan_motor_model_.c_str(), "MX", 2))
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["moving_speed"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, velocity);
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["goal_acceleration"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, acceleration);
}
else if (!strncmp(pan_motor_model_.c_str(), "PRO", 3))
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["goal_velocity"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, velocity);
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["goal_acceleration"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, acceleration);
}
else
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["profile_velocity"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, velocity);
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["profile_acceleration"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, acceleration);
}
if (!strncmp(tilt_motor_model_.c_str(), "AX", 2) || !strncmp(tilt_motor_model_.c_str(), "RX", 2) || !strncmp(tilt_motor_model_.c_str(), "EX", 2))
{
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["moving_speed"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, velocity);
}
else if (!strncmp(tilt_motor_model_.c_str(), "MX", 2))
{
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["moving_speed"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, velocity);
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["goal_acceleration"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, acceleration);
}
else if (!strncmp(tilt_motor_model_.c_str(), "PRO", 3))
{
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["goal_velocity"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, velocity);
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["goal_acceleration"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, acceleration);
}
else
{
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["profile_velocity"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, velocity);
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["profile_acceleration"];
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, acceleration);
}
}
bool DynamixelWorkbenchMultiPort::writePosition(int64_t pan_pos, int64_t tilt_pos)
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_["goal_position"];
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_["goal_position"];
writeDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, pan_pos);
writeDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, tilt_pos);
}
bool DynamixelWorkbenchMultiPort::readMotorState(int8_t motor, std::string addr_name)
{
int64_t read_value;
if (motor == PAN_MOTOR)
{
dynamixel_[PAN_MOTOR]->item_ = dynamixel_[PAN_MOTOR]->ctrl_table_[addr_name];
readDynamixelRegister(pan_motor_portHandler_, pan_motor_packetHandler_, pan_motor_id_, dynamixel_[PAN_MOTOR]->item_->address, dynamixel_[PAN_MOTOR]->item_->data_length, &read_value);
read_pan_motor_data_[addr_name] = read_value;
return true;
}
else
{
dynamixel_[TILT_MOTOR]->item_ = dynamixel_[TILT_MOTOR]->ctrl_table_[addr_name];
readDynamixelRegister(tilt_motor_portHandler_, tilt_motor_packetHandler_, tilt_motor_id_, dynamixel_[TILT_MOTOR]->item_->address, dynamixel_[TILT_MOTOR]->item_->data_length, &read_value);
read_tilt_motor_data_[addr_name] = read_value;
return true;
}
}
bool DynamixelWorkbenchMultiPort::getPublishedMsg(void)
{
readMotorState(PAN_MOTOR, "torque_enable");
readMotorState(PAN_MOTOR, "moving");
readMotorState(PAN_MOTOR, "goal_position");
readMotorState(PAN_MOTOR, "present_position");
readMotorState(PAN_MOTOR, "present_velocity");
if (!strncmp(pan_motor_model_.c_str(), "AX", 2) || !strncmp(pan_motor_model_.c_str(), "RX", 2) || !strncmp(pan_motor_model_.c_str(), "MX", 2) || !strncmp(pan_motor_model_.c_str(), "EX", 2))
{
readMotorState(PAN_MOTOR, "moving_speed");
}
else
{
readMotorState(PAN_MOTOR, "goal_velocity");
}
if (!strncmp(pan_motor_model_.c_str(), "MX", 2) || !strncmp(pan_motor_model_.c_str(), "PRO", 3))
{
readMotorState(PAN_MOTOR, "goal_acceleration");
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(pan_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2))
{
readMotorState(PAN_MOTOR, "profile_velocity");
readMotorState(PAN_MOTOR, "profile_acceleration");
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(pan_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2) || !strncmp(pan_motor_model_.c_str(), "PRO", 3))
{
readMotorState(PAN_MOTOR, "min_position_limit");
readMotorState(PAN_MOTOR, "max_position_limit");
}
else
{
readMotorState(PAN_MOTOR, "cw_angle_limit");
readMotorState(PAN_MOTOR, "ccw_angle_limit");
}
readMotorState(TILT_MOTOR, "torque_enable");
readMotorState(TILT_MOTOR, "moving");
readMotorState(TILT_MOTOR, "goal_position");
readMotorState(TILT_MOTOR, "present_position");
readMotorState(TILT_MOTOR, "present_velocity");
if (!strncmp(tilt_motor_model_.c_str(), "AX", 2) || !strncmp(tilt_motor_model_.c_str(), "RX", 2) || !strncmp(tilt_motor_model_.c_str(), "MX", 2) || !strncmp(tilt_motor_model_.c_str(), "EX", 2))
{
readMotorState(TILT_MOTOR, "moving_speed");
}
else
{
readMotorState(TILT_MOTOR, "goal_velocity");
}
if (!strncmp(tilt_motor_model_.c_str(), "MX", 2) || !strncmp(tilt_motor_model_.c_str(), "PRO", 3))
{
readMotorState(TILT_MOTOR, "goal_acceleration");
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(tilt_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2))
{
readMotorState(TILT_MOTOR, "profile_velocity");
readMotorState(TILT_MOTOR, "profile_acceleration");
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(tilt_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2) || !strncmp(tilt_motor_model_.c_str(), "PRO", 3))
{
readMotorState(TILT_MOTOR, "min_position_limit");
readMotorState(TILT_MOTOR, "max_position_limit");
}
else
{
readMotorState(TILT_MOTOR, "cw_angle_limit");
readMotorState(TILT_MOTOR, "ccw_angle_limit");
}
}
int64_t DynamixelWorkbenchMultiPort::convertRadian2Value(int8_t motor, double radian)
{
int64_t value = 0;
if (radian > 0)
{
if (dynamixel_[motor]->value_of_max_radian_position_ <= dynamixel_[motor]->value_of_0_radian_position_)
return dynamixel_[motor]->value_of_max_radian_position_;
value = (radian * (dynamixel_[motor]->value_of_max_radian_position_ - dynamixel_[motor]->value_of_0_radian_position_) / dynamixel_[motor]->max_radian_)
+ dynamixel_[motor]->value_of_0_radian_position_;
}
else if (radian < 0)
{
if (dynamixel_[motor]->value_of_min_radian_position_ >= dynamixel_[motor]->value_of_0_radian_position_)
return dynamixel_[motor]->value_of_min_radian_position_;
value = (radian * (dynamixel_[motor]->value_of_min_radian_position_ - dynamixel_[motor]->value_of_0_radian_position_) / dynamixel_[motor]->min_radian_)
+ dynamixel_[motor]->value_of_0_radian_position_;
}
else
value = dynamixel_[motor]->value_of_0_radian_position_;
if (value > dynamixel_[motor]->value_of_max_radian_position_)
return dynamixel_[motor]->value_of_max_radian_position_;
else if (value < dynamixel_[motor]->value_of_min_radian_position_)
return dynamixel_[motor]->value_of_min_radian_position_;
return value;
}
bool DynamixelWorkbenchMultiPort::dynamixelControlLoop(void)
{
getPublishedMsg();
dynamixel_workbench_msgs::MotorState dynamixel_response[dynamixel_.size()];
dynamixel_workbench_msgs::MotorStateList dynamixel_response_list;
dynamixel_response[PAN_MOTOR].motor_model = dynamixel_[PAN_MOTOR]->model_name_;
dynamixel_response[PAN_MOTOR].id = dynamixel_[PAN_MOTOR]->id_;
dynamixel_response[PAN_MOTOR].torque_enable = read_pan_motor_data_["torque_enable"];
dynamixel_response[PAN_MOTOR].present_position = read_pan_motor_data_["present_position"];
dynamixel_response[PAN_MOTOR].present_velocity = read_pan_motor_data_["present_velocity"];
dynamixel_response[PAN_MOTOR].goal_position = read_pan_motor_data_["goal_position"];
dynamixel_response[PAN_MOTOR].moving = read_pan_motor_data_["moving"];
if (!strncmp(pan_motor_model_.c_str(), "AX", 2) || !strncmp(pan_motor_model_.c_str(), "RX", 2) || !strncmp(pan_motor_model_.c_str(), "MX", 2) || !strncmp(pan_motor_model_.c_str(), "EX", 2))
{
dynamixel_response[PAN_MOTOR].moving_speed = read_pan_motor_data_["moving_speed"];
}
else
{
dynamixel_response[PAN_MOTOR].goal_velocity = read_pan_motor_data_["goal_velocity"];
}
if (!strncmp(pan_motor_model_.c_str(), "MX", 2) || !strncmp(pan_motor_model_.c_str(), "PRO", 3))
{
dynamixel_response[PAN_MOTOR].goal_acceleration = read_pan_motor_data_["goal_acceleration"];
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(pan_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2))
{
dynamixel_response[PAN_MOTOR].profile_velocity = read_pan_motor_data_["profile_velocity"];
dynamixel_response[PAN_MOTOR].profile_acceleration = read_pan_motor_data_["profile_acceleration"];
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(pan_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2) || !strncmp(pan_motor_model_.c_str(), "PRO", 3))
{
dynamixel_response[PAN_MOTOR].max_position_limit = read_pan_motor_data_["max_position_limit"];
dynamixel_response[PAN_MOTOR].min_position_limit = read_pan_motor_data_["min_position_limit"];
}
else
{
dynamixel_response[PAN_MOTOR].cw_angle_limit = read_pan_motor_data_["cw_angle_limit"];
dynamixel_response[PAN_MOTOR].ccw_angle_limit = read_pan_motor_data_["ccw_angle_limit"];
}
dynamixel_response_list.motor_states.push_back(dynamixel_response[PAN_MOTOR]);
dynamixel_response[TILT_MOTOR].motor_model = dynamixel_[TILT_MOTOR]->model_name_;
dynamixel_response[TILT_MOTOR].id = dynamixel_[TILT_MOTOR]->id_;
dynamixel_response[TILT_MOTOR].torque_enable = read_tilt_motor_data_["torque_enable"];
dynamixel_response[TILT_MOTOR].present_position = read_tilt_motor_data_["present_position"];
dynamixel_response[TILT_MOTOR].present_velocity = read_tilt_motor_data_["present_velocity"];
dynamixel_response[TILT_MOTOR].goal_position = read_tilt_motor_data_["goal_position"];
dynamixel_response[TILT_MOTOR].moving = read_tilt_motor_data_["moving"];
if (!strncmp(tilt_motor_model_.c_str(), "AX", 2) || !strncmp(tilt_motor_model_.c_str(), "RX", 2) || !strncmp(tilt_motor_model_.c_str(), "MX", 2) || !strncmp(tilt_motor_model_.c_str(), "EX", 2))
{
dynamixel_response[TILT_MOTOR].moving_speed = read_tilt_motor_data_["moving_speed"];
}
else
{
dynamixel_response[TILT_MOTOR].goal_velocity = read_tilt_motor_data_["goal_velocity"];
}
if (!strncmp(tilt_motor_model_.c_str(), "MX", 2) || !strncmp(tilt_motor_model_.c_str(), "PRO", 3))
{
dynamixel_response[TILT_MOTOR].goal_acceleration = read_tilt_motor_data_["goal_acceleration"];
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(tilt_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2))
{
dynamixel_response[TILT_MOTOR].profile_velocity = read_tilt_motor_data_["profile_velocity"];
dynamixel_response[TILT_MOTOR].profile_acceleration = read_tilt_motor_data_["profile_acceleration"];
}
if (!strncmp(pan_motor_model_.c_str(), "XL", 2) || !strncmp(tilt_motor_model_.c_str(), "XM", 2) || !strncmp(pan_motor_model_.c_str(), "XH", 2) || !strncmp(tilt_motor_model_.c_str(), "PRO", 3))
{
dynamixel_response[TILT_MOTOR].max_position_limit = read_tilt_motor_data_["max_position_limit"];
dynamixel_response[TILT_MOTOR].min_position_limit = read_tilt_motor_data_["min_position_limit"];
}
else
{
dynamixel_response[TILT_MOTOR].cw_angle_limit = read_tilt_motor_data_["cw_angle_limit"];
dynamixel_response[TILT_MOTOR].ccw_angle_limit = read_tilt_motor_data_["ccw_angle_limit"];
}
dynamixel_response_list.motor_states.push_back(dynamixel_response[TILT_MOTOR]);
dynamixel_state_pub_.publish(dynamixel_response_list);
}
bool DynamixelWorkbenchMultiPort::controlPanTiltMotorCallback(dynamixel_workbench_msgs::SetPosition::Request &req,
dynamixel_workbench_msgs::SetPosition::Response &res)
{
int64_t pan_pos = 0;
int64_t tilt_pos = 0;
if (req.unit == "rad")
{
pan_pos = convertRadian2Value(PAN_MOTOR, req.pan_pos);
tilt_pos = convertRadian2Value(TILT_MOTOR, req.tilt_pos);
}
else if (req.unit == "raw")
{
pan_pos = req.pan_pos;
tilt_pos = req.tilt_pos;
}
else
{
pan_pos = req.pan_pos;
tilt_pos = req.tilt_pos;
}
writePosition(pan_pos, tilt_pos);
res.pan_pos = pan_pos;
res.tilt_pos = tilt_pos;
}
int main(int argc, char **argv)
{
// Init ROS node
ros::init(argc, argv, "dynamixel_workbench_multi_port");
DynamixelWorkbenchMultiPort dynamixel_multi_port;
ros::Rate loop_rate(125);
while (ros::ok())
{
dynamixel_multi_port.dynamixelControlLoop();
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| [
"[email protected]"
]
| |
925319e9c03e0f05a2f716f09944b35818070c02 | 2e3bc275f1ad76df966e9d19561b5cad79839b84 | /third_party/mlir/lib/Conversion/LinalgToLLVM/LinalgToLLVM.cpp | ebb0fd757531d6029d95918b6856954d459452f7 | [
"Apache-2.0"
]
| permissive | themikem/tensorflow | 624ee656d2dbc95ee9774538f20b57808e08dd4c | 5deca4e0eb2d15022b6645c2d5289f1a68717dbd | refs/heads/master | 2020-09-16T14:26:39.745634 | 2019-11-24T16:52:28 | 2019-11-24T16:58:32 | 223,794,503 | 2 | 2 | Apache-2.0 | 2019-12-26T06:32:55 | 2019-11-24T18:59:30 | null | UTF-8 | C++ | false | false | 21,386 | cpp | //===- LinalgToLLVM.cpp - conversion from Linalg to LLVM dialect ----------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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 "mlir/Conversion/LinalgToLLVM/LinalgToLLVM.h"
#include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
#include "mlir/Conversion/LoopToStandard/ConvertLoopToStandard.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Conversion/VectorConversions/VectorConversions.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/Linalg/Utils/Intrinsics.h"
#include "mlir/EDSC/Builders.h"
#include "mlir/EDSC/Intrinsics.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/IR/Types.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/Passes.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
using namespace mlir;
using namespace mlir::edsc;
using namespace mlir::edsc::intrinsics;
using namespace mlir::LLVM;
using namespace mlir::linalg;
using namespace mlir::linalg::intrinsics;
using add = ValueBuilder<mlir::LLVM::AddOp>;
using addi = ValueBuilder<mlir::AddIOp>;
using bitcast = ValueBuilder<mlir::LLVM::BitcastOp>;
using cmpi = ValueBuilder<mlir::CmpIOp>;
using constant = ValueBuilder<mlir::LLVM::ConstantOp>;
using extractvalue = ValueBuilder<mlir::LLVM::ExtractValueOp>;
using gep = ValueBuilder<mlir::LLVM::GEPOp>;
using insertvalue = ValueBuilder<mlir::LLVM::InsertValueOp>;
using llvm_call = OperationBuilder<mlir::LLVM::CallOp>;
using llvm_icmp = ValueBuilder<LLVM::ICmpOp>;
using llvm_load = ValueBuilder<LLVM::LoadOp>;
using llvm_store = OperationBuilder<LLVM::StoreOp>;
using llvm_select = ValueBuilder<LLVM::SelectOp>;
using mul = ValueBuilder<mlir::LLVM::MulOp>;
using ptrtoint = ValueBuilder<mlir::LLVM::PtrToIntOp>;
using sub = ValueBuilder<mlir::LLVM::SubOp>;
using llvm_undef = ValueBuilder<mlir::LLVM::UndefOp>;
using urem = ValueBuilder<mlir::LLVM::URemOp>;
using llvm_alloca = ValueBuilder<LLVM::AllocaOp>;
using llvm_return = OperationBuilder<LLVM::ReturnOp>;
template <typename T>
static LLVMType getPtrToElementType(T containerType,
LLVMTypeConverter &lowering) {
return lowering.convertType(containerType.getElementType())
.template cast<LLVMType>()
.getPointerTo();
}
// Convert the given type to the LLVM IR Dialect type. The following
// conversions are supported:
// - an Index type is converted into an LLVM integer type with pointer
// bitwidth (analogous to intptr_t in C);
// - an Integer type is converted into an LLVM integer type of the same width;
// - an F32 type is converted into an LLVM float type
// - a Buffer, Range or View is converted into an LLVM structure type
// containing the respective dynamic values.
static Type convertLinalgType(Type t, LLVMTypeConverter &lowering) {
auto *context = t.getContext();
auto int64Ty = lowering.convertType(IntegerType::get(64, context))
.cast<LLVM::LLVMType>();
// A buffer descriptor contains the pointer to a flat region of storage and
// the size of the region.
//
// template <typename Elem, size_t Rank>
// struct {
// void *baseAlloc;
// Elem *ptr;
// int64_t size;
// };
if (auto bufferType = t.dyn_cast<BufferType>()) {
auto voidPtrTy = LLVMType::getInt8Ty(lowering.getDialect()).getPointerTo();
auto ptrTy = getPtrToElementType(bufferType, lowering);
return LLVMType::getStructTy(voidPtrTy, ptrTy, int64Ty);
}
// Range descriptor contains the range bounds and the step as 64-bit integers.
//
// struct {
// int64_t min;
// int64_t max;
// int64_t step;
// };
if (t.isa<RangeType>())
return LLVMType::getStructTy(int64Ty, int64Ty, int64Ty);
return Type();
}
namespace {
/// EDSC-compatible wrapper for MemRefDescriptor.
class BaseViewConversionHelper {
public:
BaseViewConversionHelper(Type type)
: d(MemRefDescriptor::undef(rewriter(), loc(), type)) {}
BaseViewConversionHelper(Value *v) : d(v) {}
/// Wrappers around MemRefDescriptor that use EDSC builder and location.
Value *allocatedPtr() { return d.allocatedPtr(rewriter(), loc()); }
void setAllocatedPtr(Value *v) { d.setAllocatedPtr(rewriter(), loc(), v); }
Value *alignedPtr() { return d.alignedPtr(rewriter(), loc()); }
void setAlignedPtr(Value *v) { d.setAlignedPtr(rewriter(), loc(), v); }
Value *offset() { return d.offset(rewriter(), loc()); }
void setOffset(Value *v) { d.setOffset(rewriter(), loc(), v); }
Value *size(unsigned i) { return d.size(rewriter(), loc(), i); }
void setSize(unsigned i, Value *v) { d.setSize(rewriter(), loc(), i, v); }
Value *stride(unsigned i) { return d.stride(rewriter(), loc(), i); }
void setStride(unsigned i, Value *v) { d.setStride(rewriter(), loc(), i, v); }
operator Value *() { return d; }
private:
OpBuilder &rewriter() { return ScopedContext::getBuilder(); }
Location loc() { return ScopedContext::getLocation(); }
MemRefDescriptor d;
};
} // namespace
// RangeOp creates a new range descriptor.
class RangeOpConversion : public LLVMOpLowering {
public:
explicit RangeOpConversion(MLIRContext *context, LLVMTypeConverter &lowering_)
: LLVMOpLowering(RangeOp::getOperationName(), context, lowering_) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
auto rangeOp = cast<RangeOp>(op);
auto rangeDescriptorTy =
convertLinalgType(rangeOp.getResult()->getType(), lowering);
edsc::ScopedContext context(rewriter, op->getLoc());
// Fill in an aggregate value of the descriptor.
RangeOpOperandAdaptor adaptor(operands);
Value *desc = llvm_undef(rangeDescriptorTy);
desc = insertvalue(desc, adaptor.min(), rewriter.getI64ArrayAttr(0));
desc = insertvalue(desc, adaptor.max(), rewriter.getI64ArrayAttr(1));
desc = insertvalue(desc, adaptor.step(), rewriter.getI64ArrayAttr(2));
rewriter.replaceOp(op, desc);
return matchSuccess();
}
};
/// Conversion pattern that transforms a linalg.slice op into:
/// 1. A function entry `alloca` operation to allocate a ViewDescriptor.
/// 2. A load of the ViewDescriptor from the pointer allocated in 1.
/// 3. Updates to the ViewDescriptor to introduce the data ptr, offset, size
/// and stride corresponding to the region of memory within the bounds of
/// the parent view.
/// 4. A store of the resulting ViewDescriptor to the alloca'ed pointer.
/// The linalg.slice op is replaced by the alloca'ed pointer.
class SliceOpConversion : public LLVMOpLowering {
public:
explicit SliceOpConversion(MLIRContext *context, LLVMTypeConverter &lowering_)
: LLVMOpLowering(SliceOp::getOperationName(), context, lowering_) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
edsc::ScopedContext context(rewriter, op->getLoc());
SliceOpOperandAdaptor adaptor(operands);
BaseViewConversionHelper baseDesc(adaptor.view());
auto sliceOp = cast<SliceOp>(op);
auto memRefType = sliceOp.getBaseViewType();
auto int64Ty = lowering.convertType(rewriter.getIntegerType(64))
.cast<LLVM::LLVMType>();
BaseViewConversionHelper desc(lowering.convertType(sliceOp.getViewType()));
// TODO(ntv): extract sizes and emit asserts.
SmallVector<Value *, 4> strides(memRefType.getRank());
for (int i = 0, e = memRefType.getRank(); i < e; ++i)
strides[i] = baseDesc.stride(i);
auto pos = [&rewriter](ArrayRef<int64_t> values) {
return rewriter.getI64ArrayAttr(values);
};
// Compute base offset.
Value *baseOffset = baseDesc.offset();
for (int i = 0, e = memRefType.getRank(); i < e; ++i) {
Value *indexing = adaptor.indexings()[i];
Value *min = indexing;
if (sliceOp.indexing(i)->getType().isa<RangeType>())
min = extractvalue(int64Ty, indexing, pos(0));
baseOffset = add(baseOffset, mul(min, strides[i]));
}
// Insert the base and aligned pointers.
desc.setAllocatedPtr(baseDesc.allocatedPtr());
desc.setAlignedPtr(baseDesc.alignedPtr());
// Insert base offset.
desc.setOffset(baseOffset);
// Corner case, no sizes or strides: early return the descriptor.
if (sliceOp.getViewType().getRank() == 0)
return rewriter.replaceOp(op, {desc}), matchSuccess();
Value *zero =
constant(int64Ty, rewriter.getIntegerAttr(rewriter.getIndexType(), 0));
// Compute and insert view sizes (max - min along the range) and strides.
// Skip the non-range operands as they will be projected away from the view.
int numNewDims = 0;
for (auto en : llvm::enumerate(sliceOp.indexings())) {
Value *indexing = en.value();
if (indexing->getType().isa<RangeType>()) {
int rank = en.index();
Value *rangeDescriptor = adaptor.indexings()[rank];
Value *min = extractvalue(int64Ty, rangeDescriptor, pos(0));
Value *max = extractvalue(int64Ty, rangeDescriptor, pos(1));
Value *step = extractvalue(int64Ty, rangeDescriptor, pos(2));
Value *baseSize = baseDesc.size(rank);
// Bound upper by base view upper bound.
max = llvm_select(llvm_icmp(ICmpPredicate::slt, max, baseSize), max,
baseSize);
Value *size = sub(max, min);
// Bound lower by zero.
size =
llvm_select(llvm_icmp(ICmpPredicate::slt, size, zero), zero, size);
Value *stride = mul(strides[rank], step);
desc.setSize(numNewDims, size);
desc.setStride(numNewDims, stride);
++numNewDims;
}
}
rewriter.replaceOp(op, {desc});
return matchSuccess();
}
};
/// Conversion pattern that transforms a linalg.transpose op into:
/// 1. A function entry `alloca` operation to allocate a ViewDescriptor.
/// 2. A load of the ViewDescriptor from the pointer allocated in 1.
/// 3. Updates to the ViewDescriptor to introduce the data ptr, offset, size
/// and stride. Size and stride are permutations of the original values.
/// 4. A store of the resulting ViewDescriptor to the alloca'ed pointer.
/// The linalg.transpose op is replaced by the alloca'ed pointer.
class TransposeOpConversion : public LLVMOpLowering {
public:
explicit TransposeOpConversion(MLIRContext *context,
LLVMTypeConverter &lowering_)
: LLVMOpLowering(TransposeOp::getOperationName(), context, lowering_) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
// Initialize the common boilerplate and alloca at the top of the FuncOp.
edsc::ScopedContext context(rewriter, op->getLoc());
TransposeOpOperandAdaptor adaptor(operands);
BaseViewConversionHelper baseDesc(adaptor.view());
auto transposeOp = cast<TransposeOp>(op);
// No permutation, early exit.
if (transposeOp.permutation().isIdentity())
return rewriter.replaceOp(op, {baseDesc}), matchSuccess();
BaseViewConversionHelper desc(
lowering.convertType(transposeOp.getViewType()));
// Copy the base and aligned pointers from the old descriptor to the new
// one.
desc.setAllocatedPtr(baseDesc.allocatedPtr());
desc.setAlignedPtr(baseDesc.alignedPtr());
// Copy the offset pointer from the old descriptor to the new one.
desc.setOffset(baseDesc.offset());
// Iterate over the dimensions and apply size/stride permutation.
for (auto en : llvm::enumerate(transposeOp.permutation().getResults())) {
int sourcePos = en.index();
int targetPos = en.value().cast<AffineDimExpr>().getPosition();
desc.setSize(targetPos, baseDesc.size(sourcePos));
desc.setStride(targetPos, baseDesc.stride(sourcePos));
}
rewriter.replaceOp(op, {desc});
return matchSuccess();
}
};
// YieldOp produces and LLVM::ReturnOp.
class YieldOpConversion : public LLVMOpLowering {
public:
explicit YieldOpConversion(MLIRContext *context, LLVMTypeConverter &lowering_)
: LLVMOpLowering(YieldOp::getOperationName(), context, lowering_) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(op, operands);
return matchSuccess();
}
};
// Get a SymbolRefAttr containing the library function name for the LinalgOp.
// If the library function does not exist, insert a declaration.
template <typename LinalgOp>
static FlatSymbolRefAttr getLibraryCallSymbolRef(Operation *op,
PatternRewriter &rewriter) {
auto linalgOp = cast<LinalgOp>(op);
auto fnName = linalgOp.getLibraryCallName();
if (fnName.empty()) {
op->emitWarning("No library call defined for: ") << *op;
return {};
}
// fnName is a dynamic std::String, unique it via a SymbolRefAttr.
FlatSymbolRefAttr fnNameAttr = rewriter.getSymbolRefAttr(fnName);
auto module = op->getParentOfType<ModuleOp>();
if (module.lookupSymbol(fnName)) {
return fnNameAttr;
}
SmallVector<Type, 4> inputTypes(op->getOperandTypes());
assert(op->getNumResults() == 0 &&
"Library call for linalg operation can be generated only for ops that "
"have void return types");
auto libFnType = FunctionType::get(inputTypes, {}, rewriter.getContext());
OpBuilder::InsertionGuard guard(rewriter);
// Insert before module terminator.
rewriter.setInsertionPoint(module.getBody(),
std::prev(module.getBody()->end()));
rewriter.create<FuncOp>(op->getLoc(), fnNameAttr.getValue(), libFnType,
ArrayRef<NamedAttribute>{});
return fnNameAttr;
}
Type LinalgTypeConverter::convertType(Type t) {
if (auto result = LLVMTypeConverter::convertType(t))
return result;
return convertLinalgType(t, *this);
}
// LinalgOpConversion<LinalgOp> creates a new call to the
// `LinalgOp::getLibraryCallName()` function.
// The implementation of the function can be either in the same module or in an
// externally linked library.
template <typename LinalgOp>
class LinalgOpConversion : public OpRewritePattern<LinalgOp> {
public:
using OpRewritePattern<LinalgOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(LinalgOp op,
PatternRewriter &rewriter) const override {
auto libraryCallName = getLibraryCallSymbolRef<LinalgOp>(op, rewriter);
if (!libraryCallName)
return this->matchFailure();
SmallVector<Value *, 4> operands(op.getOperands().begin(),
op.getOperands().end());
rewriter.replaceOpWithNewOp<mlir::CallOp>(op, libraryCallName.getValue(),
ArrayRef<Type>{}, operands);
return this->matchSuccess();
}
};
/// Conversion pattern specialization for CopyOp. This kicks in when both input
/// and output permutations are left unspecified or are the identity.
template <> class LinalgOpConversion<CopyOp> : public OpRewritePattern<CopyOp> {
public:
using OpRewritePattern<CopyOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(CopyOp op,
PatternRewriter &rewriter) const override {
auto inputPerm = op.inputPermutation();
if (inputPerm.hasValue() && !inputPerm->isIdentity())
return matchFailure();
auto outputPerm = op.outputPermutation();
if (outputPerm.hasValue() && !outputPerm->isIdentity())
return matchFailure();
auto libraryCallName = getLibraryCallSymbolRef<CopyOp>(op, rewriter);
if (!libraryCallName)
return matchFailure();
SmallVector<Value *, 4> operands(op.getOperands().begin(),
op.getOperands().end());
rewriter.replaceOpWithNewOp<mlir::CallOp>(op, libraryCallName.getValue(),
ArrayRef<Type>{}, operands);
return matchSuccess();
}
};
/// A non-conversion rewrite pattern kicks in to convert CopyOp with
/// permutations into a sequence of TransposeOp and permutation-free CopyOp.
/// This interplays together with TransposeOpConversion and
/// LinalgConversion<CopyOp> to create a path to the LLVM dialect.
class CopyTransposeConversion : public OpRewritePattern<CopyOp> {
public:
using OpRewritePattern<CopyOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(CopyOp op,
PatternRewriter &rewriter) const override {
Value *in = op.input(), *out = op.output();
// If either inputPerm or outputPerm are non-identities, insert transposes.
auto inputPerm = op.inputPermutation();
if (inputPerm.hasValue() && !inputPerm->isIdentity())
in = rewriter.create<linalg::TransposeOp>(op.getLoc(), in,
AffineMapAttr::get(*inputPerm));
auto outputPerm = op.outputPermutation();
if (outputPerm.hasValue() && !outputPerm->isIdentity())
out = rewriter.create<linalg::TransposeOp>(
op.getLoc(), out, AffineMapAttr::get(*outputPerm));
// If nothing was transposed, fail and let the conversion kick in.
if (in == op.input() && out == op.output())
return matchFailure();
rewriter.replaceOpWithNewOp<CopyOp>(op, in, out);
return matchSuccess();
}
};
/// Populate the given list with patterns that convert from Linalg to Standard.
static void
populateLinalgToStandardConversionPatterns(OwningRewritePatternList &patterns,
MLIRContext *ctx) {
// TODO(ntv) ConvOp conversion needs to export a descriptor with relevant
// attribute values such as kernel striding and dilation.
patterns.insert<CopyTransposeConversion, LinalgOpConversion<ConvOp>,
LinalgOpConversion<CopyOp>, LinalgOpConversion<DotOp>,
LinalgOpConversion<FillOp>, LinalgOpConversion<GenericOp>,
LinalgOpConversion<IndexedGenericOp>,
LinalgOpConversion<MatmulOp>, LinalgOpConversion<MatvecOp>>(
ctx);
}
/// Populate the given list with patterns that convert from Linalg to LLVM.
void mlir::populateLinalgToLLVMConversionPatterns(
LinalgTypeConverter &converter, OwningRewritePatternList &patterns,
MLIRContext *ctx) {
patterns.insert<RangeOpConversion, SliceOpConversion, TransposeOpConversion,
YieldOpConversion>(ctx, converter);
}
namespace {
struct ConvertLinalgToLLVMPass : public ModulePass<ConvertLinalgToLLVMPass> {
void runOnModule() override;
};
} // namespace
void ConvertLinalgToLLVMPass::runOnModule() {
auto module = getModule();
// Convert to the LLVM IR dialect using the converter defined above.
OwningRewritePatternList patterns;
LinalgTypeConverter converter(&getContext());
populateAffineToStdConversionPatterns(patterns, &getContext());
populateLoopToStdConversionPatterns(patterns, &getContext());
populateStdToLLVMConversionPatterns(converter, patterns);
populateVectorToLLVMConversionPatterns(converter, patterns);
populateLinalgToStandardConversionPatterns(patterns, &getContext());
populateLinalgToLLVMConversionPatterns(converter, patterns, &getContext());
ConversionTarget target(getContext());
target.addLegalDialect<LLVM::LLVMDialect>();
target.addDynamicallyLegalOp<FuncOp>(
[&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
target.addLegalOp<ModuleOp, ModuleTerminatorOp>();
if (failed(applyFullConversion(module, target, patterns, &converter)))
signalPassFailure();
}
std::unique_ptr<OpPassBase<ModuleOp>>
mlir::linalg::createConvertLinalgToLLVMPass() {
return std::make_unique<ConvertLinalgToLLVMPass>();
}
static PassRegistration<ConvertLinalgToLLVMPass>
pass("convert-linalg-to-llvm",
"Convert the operations from the linalg dialect into the LLVM dialect");
| [
"[email protected]"
]
| |
280dfb03e575c7e924cbec5c0fe5d54ec94055fd | 8eca4bbf07e2cad4dbc4fa685d2b34b0cdc4508e | /src/sbridge/src/sbridge.h | 87b186ddd469fc559176bd569fa5034bce82d12a | []
| no_license | marcfroberts/NASASwarmathon2018 | a4555d432a0ab23cc96bc36c1f8e2ba417f49478 | e2b1f62eb0d255fe10ab6b5e699bfa71a5e02ffd | refs/heads/master | 2021-05-15T09:04:55.268856 | 2018-03-27T18:41:42 | 2018-03-27T18:41:42 | 108,076,212 | 0 | 0 | null | 2018-03-27T18:41:43 | 2017-10-24T04:21:17 | Makefile | UTF-8 | C++ | false | false | 1,085 | h | #ifndef SBRIDGE
#define SBRIDGE
//ROS messages
#include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <std_msgs/UInt8.h>
using namespace std;
/**
* This class translates drive controls into Gazebo
* friendly velocities.
*/
class sbridge {
public:
sbridge(std::string publishedName);
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void modeHandler(const std_msgs::UInt8::ConstPtr& message);
~sbridge();
private:
//Publishers
ros::Publisher skidsteerPublish;
ros::Publisher heartbeatPublisher;
ros::Publisher infoLogPublisher;
//Subscribers
ros::Subscriber driveControlSubscriber;
ros::Subscriber modeSubscriber;
//Timer callback handler
void publishHeartBeatTimerEventHandler(const ros::TimerEvent& event);
ros::Timer publish_heartbeat_timer;
geometry_msgs::Twist velocity;
int currentMode;
};
#endif /* SBRIDGE */
| [
"[email protected]"
]
| |
981118b639fb2a2cf8d93a0b4d80b17606999218 | 2d97fa37c44f69164a70a95465b4307639e64040 | /week1-cpp/Getting_started_with_images/Image_with_alpha_channel.cpp | 8a7df52b80f9ce591495ea28551039eee8b51a52 | []
| no_license | Phinease/OpenCV-Learning | f62d4745bf1017a63ba761fe3abcd822884ea0c8 | b07b95e426bb2ce6b5e493f73279feb2d330236b | refs/heads/main | 2023-02-01T07:53:28.601968 | 2020-12-22T09:21:52 | 2020-12-22T09:21:52 | 323,577,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 877 | cpp | #include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include "dataPath.hpp"
using namespace std;
using namespace cv;
int main(){
string // Path of the PNG image to be loaded
imagePath = DATA_PATH + "/images/panther.png";
// Read the image
// Note that we are passing flag = -1 while reading the image ( it will read the image as is)
Mat imgPNG = imread(imagePath,-1);
cout << "image size = " << imgPNG.size() << endl;
cout << "number of channels = " << imgPNG.channels() << endl;
Mat imgBGR;
Mat imgPNGChannels[4];
split(imgPNG,imgPNGChannels);
merge(imgPNGChannels,3,imgBGR);
Mat imgMask = imgPNGChannels[3];
imshow("Color Channels",imgBGR);
imshow("Alpha Channel",imgMask);
waitKey(0);
imwrite("./results/colorChannels.png",imgBGR);
imwrite("./results/alphaChannel.png",imgMask);
return 0;
}
| [
"[email protected]"
]
| |
5adcec490671ef8c12d15dda19a79e2bb7afec90 | 1020b97b6b64a5a0b1ed9f04e7b6e9841a449b7f | /UVA/uva483/uva483.cpp | 57573f0b387f38983d2ecf6e43b4a244143ee986 | []
| no_license | theshameem/OJ-Solve | 2aef2e62aa91f567848662076536d90c106636f0 | d4b04a30adba87b0d4cfe59983b2a5b05c94e520 | refs/heads/master | 2021-06-09T07:44:04.414183 | 2021-03-24T13:48:37 | 2021-03-24T13:48:37 | 133,333,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | cpp | /*
Solved!
Date: 10-04-18
Time: 10:50:36 AM
*/
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(){
/*freopen("in_uva483.txt", "r", stdin);
freopen("out_uva483.txt", "w", stdout);
*/
char word[5000];
while(scanf(" %[^\n]", word) != EOF){
int len = strlen(word);
int m = 0;
for(int i = 0; i < len; i++){
if(word[i] == ' ' || i == len - 1){
for(int j = i; j >= m; j--){
if(word[j] != ' '){
printf("%c", word[j]);
}
}
if(i < len - 1){
printf(" ");
}
m = i + 1;
}
}
printf("\n");
}
return 0;
}
| [
"[email protected]"
]
| |
252a733ebdbde70f0f150a9effc0cb9ace3fa1aa | 36736d530481d75f66cd1f99132205c1e4a2a345 | /app/src/main/cpp/native-lib.cpp | bb61e8d0d87beae9049b303febc156b2349d7f79 | []
| no_license | SuperStoneMan/educationExpert | 960962719565614349c2ff0f3a3a24fedcd2a52d | 7dc3caf019ffaf1f4b5983d11093520095b793bc | refs/heads/master | 2021-04-06T12:34:25.210567 | 2018-03-12T06:05:38 | 2018-03-12T06:05:38 | 124,840,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring
JNICALL
Java_com_education_expert_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
| [
"[email protected]"
]
| |
e0d9ae4df46244fefbffa3f9e8ec13bf6b54904c | 02d47913737ad197a7eea70db2a8e85eb87b5fe1 | /src/obfuscation-relay.h | 284edc88dc597058dcfceca680c7bc4f92124789 | [
"MIT"
]
| permissive | SiqsTeam/Siqs | 5f686ee5f2b84adb69f481caca7cc82c9e6152a3 | 01c9ec738274a2ca15af8c01fd1d8fd92a5661c3 | refs/heads/master | 2020-04-28T18:48:59.953842 | 2019-03-15T13:14:02 | 2019-03-15T13:14:02 | 175,490,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,313 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The SIQS developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OBFUSCATION_RELAY_H
#define OBFUSCATION_RELAY_H
#include "activemasternode.h"
#include "main.h"
#include "masternodeman.h"
class CObfuScationRelay
{
public:
CTxIn vinMasternode;
vector<unsigned char> vchSig;
vector<unsigned char> vchSig2;
int nBlockHeight;
int nRelayType;
CTxIn in;
CTxOut out;
CObfuScationRelay();
CObfuScationRelay(CTxIn& vinMasternodeIn, vector<unsigned char>& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vinMasternode);
READWRITE(vchSig);
READWRITE(vchSig2);
READWRITE(nBlockHeight);
READWRITE(nRelayType);
READWRITE(in);
READWRITE(out);
}
std::string ToString();
bool Sign(std::string strSharedKey);
bool VerifyMessage(std::string strSharedKey);
void Relay();
void RelayThroughNode(int nRank);
};
#endif
| [
"[email protected]"
]
| |
de3bfe07ef5c8afa1a542f7303fe5019dc4e271a | f1aaed1e27416025659317d1f679f7b3b14d654e | /Shared-Source/Managers/Database/PaymentTypes/PaymentTypesDriverInterface.cpp | 415f598f8b4db8cd38bdcd8f0b8166beee1dd0ed | []
| no_license | radtek/Pos | cee37166f89a7fcac61de9febb3760d12b823ce5 | f117845e83b41d65f18a4635a98659144d66f435 | refs/heads/master | 2020-11-25T19:49:37.755286 | 2016-09-16T14:55:17 | 2016-09-16T14:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | cpp | //---------------------------------------------------------------------------
#pragma hdrstop
#include "PaymentTypesDriverInterface.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
| [
"[email protected]"
]
| |
d289012a7942c6aad61b2aa5ae7f094085439ada | a60145ce81b297b82d02ca29a684214d64973e65 | /src/rules/FreeKickUsRule.cpp | 62ec64feb0a4b50f02caec356092e95896ef7a30 | []
| no_license | RoboTeamTwente/roboteam_tactics | 0b28ef41b144b583f2bf04a88aea5cb271a08313 | ba5e02464db04db48abdbcb33735dd5abccfbaae | refs/heads/master | 2020-03-23T05:12:20.660153 | 2019-12-30T11:44:35 | 2019-12-30T11:44:35 | 69,663,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include "roboteam_tactics/rules/FreeKickUsRule.h"
namespace rtt {
double FreeKickUsRule::minDistanceToBall(const TeamRobot& bot) const {
return bot.our_team ? 0 : .7;
}
bool FreeKickUsRule::canKick(const TeamRobot& bot) const {
return bot.our_team && /* TODO: is free kick taker */ bot.id == 1;
}
const RefRule* FreeKickUsRule::Direct::SINGLETON = new FreeKickUsRule::Direct();
const RefRule* FreeKickUsRule::Direct::get() { return SINGLETON; }
bool FreeKickUsRule::Direct::canScore(const TeamRobot&) const { return true; }
const RefRule* FreeKickUsRule::Indirect::SINGLETON = new FreeKickUsRule::Indirect();
const RefRule* FreeKickUsRule::Indirect::get() { return SINGLETON; }
bool FreeKickUsRule::Indirect::canScore(const TeamRobot&) const { return false; }
} | [
"[email protected]"
]
| |
c6830470da89918cc32061f01aaf6de7466ea93d | ab3d82ed6bd5b2ab599fd7eaaecdca2893d96729 | /19_2/Inha/week3_greedy_algorithm/1543.cpp | eb38a588ca83b5150d8a1e65f7f61090dc71ef69 | []
| no_license | threedalpeng/algorithm_study | 4ff065c3a8c2cf0ff7a7944cfbf2a248e43f3dcb | c64ceb33b00918fd026624f81244980f89362172 | refs/heads/master | 2023-05-12T07:34:15.515186 | 2023-05-10T01:45:40 | 2023-05-10T01:45:40 | 208,575,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | // 문서 검색
#include <iostream>
using namespace std;
string s, w;
int main() {
getline(cin, s);
getline(cin, w);
int cnt = 0, len = w.size();
if (s.size() < len) cout << 0;
else {
for (int i = 0; i <= s.size() - len;) {
if (s.substr(i, len) == w) {
i += len;
++cnt;
}
else
++i;
}
cout << cnt;
}
} | [
"[email protected]"
]
| |
4ca3fbb3f84fcce5517581c59f1f65d7987e4e55 | f8af85985d643cf6e83b65062570235c94e4107f | /evpp/libevent_compact.cc | 63aa84c433cf792401c2f490ee5cafe429e3c03a | [
"BSD-3-Clause"
]
| permissive | wzc003/evpp | d71d397e522c45d12c7406ab853ed61f64d9a0e4 | 02301722ceaf82bdb37f9c9305c6c6e242b5d612 | refs/heads/master | 2021-01-17T11:12:47.393307 | 2017-03-06T03:55:56 | 2017-03-06T03:55:56 | 84,028,470 | 1 | 0 | null | 2017-03-06T04:04:02 | 2017-03-06T04:04:02 | null | UTF-8 | C++ | false | false | 912 | cc | #include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#ifdef H_LIBEVENT_VERSION_14
struct event* event_new(struct event_base* base, int fd, short events,
void(*cb)(int, short, void*), void* arg) {
struct event* ev;
ev = (struct event*)malloc(sizeof(struct event));
if (ev == NULL) {
return NULL;
}
::event_set(ev, fd, events, cb, arg);
::event_base_set(base, ev);
return ev;
}
void event_free(struct event* ev) {
evpp::EventDel(ev);
free(ev);
}
struct evhttp_connection* evhttp_connection_base_new(struct event_base* base, struct evdns_base* dnsbase, const char* address, unsigned short port) {
struct evhttp_connection* evhttp_conn = evhttp_connection_new(address, port);
evhttp_connection_set_base(evhttp_conn, base);
return evhttp_conn;
}
#endif
#ifdef H_OS_MACOSX
void avoid_macosx_ranlib_complain() {
}
#endif
| [
"[email protected]"
]
| |
3e8298bb1dc5b109a0c559b2414374de536f3036 | 4f30998de9b706a35ba20bedbba0db50b6620db1 | /serialport.h | 3d4575fa4a17dadb3c94eedccce306a53f70181f | []
| no_license | Bluce-Song/2031 | 4f11ad32f6eb71f8a78403cc4898186ef78b05a7 | 1a7e126b386c14e27fa49305e9fba9e9885a3c7c | refs/heads/master | 2020-05-01T03:13:32.575470 | 2019-09-04T06:15:28 | 2019-09-04T06:15:28 | 177,239,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,530 | h | #ifndef SERIALPORT_H
#define SERIALPORT_H
#include <QTime>
#include <QTimer>
#include <QDebug>
#include <QObject>
#include <QTextCodec>
#include <QStringList>
#include <QApplication>
#include <QEventLoop>
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <sys/time.h>
#include "loginsetinfo.h"
extern testConfig tc;
class serialPort : public QObject
{
Q_OBJECT
public:
explicit serialPort(QObject *parent = 0);
private:
int addr;
int port;
int baudRate;
int stop;
int step;
int status,subStatus;
int error;
char Binary[128];
QTimer *timer;
QSerialPort *com;
char getChecksum(char *info,int start,int bytes);
void delay(int d);
int readTestData(int index, int index1, testDataStr *tds);
int startTest(int index);
int stopTest();
void printBinary(int n);
int chooseGroup(int index);
int fillCommon(groupConfig group);
int fillCommonPhase(groupConfig group);
void sendSysConfig(QByteArray msg);
void waitStateFun();
int readMachineStatus();
void readGroupSetData(int g,int s);
signals:
void sendCommand(int index,int cmd,testDataStr tds);
private slots:
void readStatus(void);
void readGroupData(groupConfig group);
void serialReadMessage(quint16 addr,quint16 cmd,QByteArray msg);
public slots:
void openSerial();
void closeSerial(void);
};
#endif // SERIALPORT_H
| [
"[email protected]"
]
| |
a7b4b5aac91492241cc3d6c72cde990b7e191af5 | d4148074bffac1ff08d4f7fd47b9314718ca92ca | /tools/mipsdec/instruction.h | eea63e70f24ed02c21198653b02cc2aba780cb87 | []
| no_license | BackupTheBerlios/tuxap | 9d48132ef91916d43d39f0b468900ffcbe474c27 | 8da69f5eabd05113cfe36b223ae3262c7d969f24 | refs/heads/master | 2020-03-26T03:07:10.117100 | 2006-11-01T21:15:44 | 2006-11-01T21:15:44 | 40,079,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | h | #ifndef INSTRUCTION_H
#define INSTRUCTION_H
#include <list>
#include "register.h"
#include "symbols.h"
typedef enum {
IF_UNKNOWN,
IF_NOARG,
IF_RSRTRD,
IF_RSRT,
IF_RSRTSI,
IF_RSSI,
IF_RSRTUI,
IF_RTUI,
IF_RTRDSA,
IF_RSRD,
IF_RD,
IF_RS,
IF_RTRDSEL,
} tInstructionFormat;
typedef enum {
IDS_NONE,
IDS_CONDITIONAL,
IDS_UNCONDITIONAL,
} tInstructionDelaySlot;
typedef enum {
IC_BRANCH,
IC_JUMP,
IC_OTHER,
} tInstructionClass;
typedef enum {
IT_ADDIU, // No delay slot
IT_ADDU, // No delay slot
IT_AND, // No delay slot
IT_ANDI, // No delay slot
IT_BEQ, // Delay slot
IT_BEQL, // Conditional delay slot
IT_BGEZ, // Delay slot
IT_BGTZ, // Delay slot
IT_BLEZ, // Delay slot
IT_BLTZ, // Delay slot
IT_BNE, // Delay slot
IT_BNEL, // Conditional delay slot
IT_MFHI, // No delay slot
IT_J, // Delay slot
IT_JALR, // Delay slot
IT_JALR_HB, // Delay slot
IT_JR, // Delay slot
IT_JR_HB, // Delay slot
IT_LB, // No delay slot
IT_LBU, // No delay slot
IT_LH, // No delay slot
IT_LHU, // No delay slot
IT_LUI, // No delay slot
IT_LW, // No delay slot
IT_LWL, // No delay slot
IT_LWR, // No delay slot
IT_MFC0, // No delay slot
IT_MTC0, // No delay slot
IT_MULT, // No delay slot
IT_MULTU, // No delay slot
IT_NOP, // No delay slot
IT_NOR, // No delay slot
IT_OR, // No delay slot
IT_ORI, // No delay slot
IT_SB, // No delay slot
IT_SH, // No delay slot
IT_SLL, // No delay slot
IT_SLTI, // No delay slot
IT_SLTIU, // No delay slot
IT_SLTU, // No delay slot
IT_SRA, // No delay slot
IT_SRAV, // No delay slot
IT_SRL, // No delay slot
IT_SSNOP, // No delay slot
IT_SUBU, // No delay slot
IT_SW, // No delay slot
IT_SWL, // No delay slot
IT_SWR, // No delay slot
IT_XORI, // No delay slot
} tInstructionType;
class Instruction;
typedef std::list<Instruction> tInstList;
class Instruction
{
public:
Instruction(void) :
bDelayedDelete(false),
bDelaySlotReordered(false),
bIgnoreJump(false)
{
}
void encodeAbsoluteJump(unsigned uAddress);
void swap(Instruction &aOtherInstruction, bool bSwapAddress);
bool parse(unsigned uInstructionData, unsigned uInstructionAddress);
bool modifiesRegister(tRegister eRegister) const;
void encodeRegisterMove(tRegister eSrcRegister, tRegister eDstRegister);
void makeNOP(void);
tInstructionDelaySlot getDelaySlotType(void);
tInstructionClass getClassType(void);
bool isNOP(void);
void deleteDelayed(void);
bool isSame(const Instruction &aOtherInstruction) const;
unsigned uAddress;
tInstructionType eType;
tInstructionFormat eFormat;
tRegister eRS;
tRegister eRT;
tRegister eRD;
unsigned short uUI;
signed short iSI;
unsigned char uSEL;
unsigned char uSA;
unsigned int uJumpAddress;
tInstList collIfBranch;
tInstList collElseBranch;
tInstList collInsertAfter;
bool bDelayedDelete;
bool bDelaySlotReordered;
bool bIgnoreJump;
bool bIsJumpTarget;
private:
void setDefaults(void);
void decodeNOARG(void);
void decodeRTRDSEL(unsigned uInstructionData);
void decodeRTUI(unsigned uInstructionData);
void decodeRTRDSA(unsigned uInstructionData);
void decodeRSRTRD(unsigned uInstructionData);
void decodeRSRD(unsigned uInstructionData);
void decodeRSRT(unsigned uInstructionData);
void decodeRSRTSI(unsigned uInstructionData);
void decodeRSSI(unsigned uInstructionData);
void decodeRSRTUI(unsigned uInstructionData);
void decodeRD(unsigned uInstructionData);
void decodeRS(unsigned uInstructionData);
};
void updateJumpTargets(tInstList &collInstList);
bool resolveRegisterValue(const tInstList &collInstList, const tInstList::const_iterator &itCurrInstruction, tRegister eRegister, unsigned &uRegisterVal);
void dumpInstructions(const tInstList &collInstList);
const char *getInstrName(const Instruction &aInstruction);
#endif
| [
"jolt"
]
| jolt |
cff711aac8863907b92ddc540f80b5e83b99b39e | 04232709ce2db7160ceff9539706d14b270c236a | /folly/executors/NotificationQueueExecutor.h | 3738be24e71a166d41d8836a8a51903c9f7c74f5 | [
"Apache-2.0"
]
| permissive | JMWY/folly | 7bf2b35221ff9279a900abc2fc0d060b0d8b56f6 | 86617507c88ebb628b8d292903edacd40e77ab13 | refs/heads/master | 2021-07-12T08:24:30.889961 | 2017-10-18T06:36:06 | 2017-10-18T06:55:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | h | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <folly/ExceptionString.h>
#include <folly/Function.h>
#include <folly/futures/DrivableExecutor.h>
#include <folly/io/async/NotificationQueue.h>
namespace folly {
class NotificationQueueExecutor : public folly::DrivableExecutor {
public:
using Func = folly::Func;
void add(Func func) override {
queue_.putMessage(std::move(func));
}
int fileno() const {
return consumer_.getFd();
}
void drive() noexcept override {
Func func;
while (queue_.tryConsume(func)) {
try {
func();
} catch (const std::exception& ex) {
LOG(ERROR) << "Exception thrown by NotificationQueueExecutor task."
<< "Exception message: " << folly::exceptionStr(ex);
} catch (...) {
LOG(ERROR) << "Unknown Exception thrown "
<< "by NotificationQueueExecutor task.";
}
}
}
private:
folly::NotificationQueue<Func> queue_;
folly::NotificationQueue<Func>::SimpleConsumer consumer_{queue_};
}; // NotificationQueueExecutor
} // namespace folly
| [
"[email protected]"
]
| |
99b2caaf33edb2e1a3fb50b76fcdd055e1d04f00 | 1e31f0ab55fdd2baa54f33b50213055c2a52b979 | /cpp05/ex02/RobotomyRequestForm.hpp | 036bdb9688973aa113198f3690fd2e754b91f0c6 | []
| no_license | AverageSlug/CPP | bf4ed437592569cf284dfa8372d9056804a29d2a | 395e4fbc3b8d1245cb496d0ce63a12618337d2a6 | refs/heads/master | 2023-09-02T10:51:51.497544 | 2021-11-22T13:01:25 | 2021-11-22T13:01:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | hpp | #ifndef ROBOTOMYREQUESTFORM_HPP
# define ROBOTOMYREQUESTFORM_HPP
# include "Form.hpp"
# include <time.h>
class RobotomyRequestForm : public Form {
public:
RobotomyRequestForm(std::string const & target);
~RobotomyRequestForm(void);
RobotomyRequestForm(const RobotomyRequestForm &cpy);
RobotomyRequestForm& operator=(const RobotomyRequestForm &a);
void doAction() const;
private:
std::string _target;
};
#endif | [
"[email protected]"
]
| |
30d21a466b2c1d1cf7a81d0d5d3590cdbeb4d9cc | 3736ec87c9ebbe265a3383c60d215d522ff34635 | /sketch_oct29b/sketch_oct29b.ino | 55af9e699dacd9298c0b73ee713415592c50188d | []
| no_license | GuilleCRS/Arduino | 514d290aad580443b9bc2c8a1bbc43f9d833b07f | 874e2e2e7712bcd45045af9bb285fad1c5c34d1e | refs/heads/master | 2020-08-18T15:01:24.850468 | 2019-11-04T04:28:10 | 2019-11-04T04:28:10 | 215,804,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | ino | #include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
String mensajes[3]={"Hola materia de sistemas programables",
"100 y nos vamos !",
"Hecho en Arduino Uno y lcd 16x2 + potenciometro"};
int rapidezTxt=250; //velocidad de avanzado caracter por caracter
//Se asignan las variables al constructor de la libreria Liquid Crystal
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
String msg[16]={};
boolean bandera=false;
void setup() {
// Se inicializan las columnas y filas del lcd
lcd.begin(16, 2);
Serial.begin(9600);
}
void loop() {
//Se genera un mensaje random de la lista de mensajes
String mensaje="";
if(Serial.available()){
mensaje=Serial.readString();
delay(5000);
lcd.print("1");
}
mensaje=" "+mensaje;
for(int tM=0;tM<=mensaje.length();tM++){
for(int i=0;i<16;i++){
msg[i]=mensaje.charAt(tM+i);
lcd.print(msg[i]);
}
delay(rapidezTxt);
lcd.clear();
}
lcd.clear();
}
| [
"[email protected]"
]
| |
cce89a298975958f70f63c1c93b0593038b5ad88 | a00fda364c2cee736ec9fdf09ae14279fd95ecdc | /C++/Module_03/ex02/FragTrap.cpp | acc3cfd47d0af3a6428501a8e8bd247f037448e3 | []
| no_license | mamoussa405/42projects | 0103a88579be5ab773191f7058291bd4296a1994 | 26315465e152605ff5cb05498a7b754e7c14bff9 | refs/heads/main | 2023-04-16T05:34:13.445176 | 2021-04-27T14:36:00 | 2021-04-27T14:36:00 | 311,743,371 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,657 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* FragTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mamoussa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/07 11:20:06 by mamoussa #+# #+# */
/* Updated: 2021/02/08 09:52:14 by mamoussa ### ########.fr */
/* */
/* ************************************************************************** */
#include "FragTrap.hpp"
FragTrap::FragTrap(std::string const & name):ClapTrap(100,100,100,100,1,name,30,20,5){
std::cout<<"FragTrap Constructor called"<<std::endl;
};
FragTrap::FragTrap(void){};
FragTrap::FragTrap(FragTrap const & inst){
*this = inst;
};
FragTrap& FragTrap::operator=(FragTrap const & inst)
{
this->_MaxHitPoints = inst._MaxHitPoints;
this->_HitPoints = inst._HitPoints;
this->_EnergyPoints = inst._EnergyPoints;
this->_MaxEnergyPoints = inst._MaxEnergyPoints;
this->_Level = inst._Level;
this->_Name = inst._Name;
this->_MeleeAttackDamage = inst._MeleeAttackDamage;
this->_RangedAttackDamage = inst._RangedAttackDamage;
this->_ArmorDamageReduction = inst._ArmorDamageReduction;
return *this;
}
FragTrap::~FragTrap(void){
std::cout<<"FragTrap Destructor called"<<std::endl;
}
void FragTrap::rangedAttack(std::string const & target) const{
std::cout<<"FR4G-TP "<<this->_Name<<" attacks "<<target<<" at range, causing "
<<this->_RangedAttackDamage<<" points of damage!"<<std::endl;
}
void FragTrap::meleeAttack(std::string const & target) const{
std::cout<<"FR4G-TP "<<this->_Name<<" attacks "<<target<<" at melee, causing "
<<this->_MeleeAttackDamage<<" points of damage!"<<std::endl;
}
void FragTrap::vaulthunter_dot_exe(std::string const & target) {
std::string attacks[5] = {"superAttack", "mamoussaAttack", "rasinganAttack",
"42Attack", "amaturasAttack"};
int damagePoints[5] = {20, 5, 40, 15, 100};
if (this->_EnergyPoints >= 25)
{
std::cout<<"FR4G-TP "<<attacks[rand()%5]<<" attacks "<<target<<" causing "
<<damagePoints[rand()%5]<<" points of damage!"<<std::endl;
this->_EnergyPoints -= 25;
}
else
std::cout<<"No enough energy"<<std::endl;
} | [
"[email protected]"
]
| |
42901c7cc66f4b759926f621f69a9031f0844e80 | 15dea4de84765fd04efb0367247e94657e76515b | /source/3rdparty/won/msg/Firewall/SMsgTypesFirewall.h | 890e7b9673323b72cac35a1c112d5785e30f56bd | []
| no_license | dppereyra/darkreign2 | 4893a628a89642121d230e6e02aa353636566be8 | 85c83fdbb4b4e32aa5f816ebfcaf286b5457a11d | refs/heads/master | 2020-12-30T13:22:17.657084 | 2017-01-30T21:20:28 | 2017-01-30T21:20:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | #ifndef __SMSGTYPESFIREWALL_H__
#define __SMSGTYPESFIREWALL_H__
namespace WONMsg
{
enum MsgTypeFirewall
{
FirewallMsgMin = 0,
FirewallDetectMsg = 1,
FirewallStatusReply = 2,
// Last Message type. Don't use
FirewallMsgMax
};
};
#endif | [
"[email protected]"
]
| |
0a65028f24ed10da66ac523716a6c02c28cd8b75 | 4750fe54a18eac014c58cd581a9994b040e35d66 | /src/support/allocators/secure.h | 9ba93ea7cbda2b2e0b30cafc52793646f2d73929 | [
"MIT"
]
| permissive | bitcoin-rush/bitcoinrush | b326b5c6a9efd68fac35d008df5363cf49931090 | 4329a6a7b9ce7a2188225f4abfc307e68de7dae0 | refs/heads/master | 2020-06-07T06:02:13.111203 | 2019-06-21T12:04:04 | 2019-06-21T12:04:04 | 192,943,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,966 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 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 BITCOINRUSH_SUPPORT_ALLOCATORS_SECURE_H
#define BITCOINRUSH_SUPPORT_ALLOCATORS_SECURE_H
#include <support/lockedpool.h>
#include <support/cleanse.h>
#include <string>
//
// Allocator that locks its contents from being paged
// out of memory and clears its contents before deletion.
//
template <typename T>
struct secure_allocator : public std::allocator<T> {
// MSVC8 default copy constructor is broken
typedef std::allocator<T> base;
typedef typename base::size_type size_type;
typedef typename base::difference_type difference_type;
typedef typename base::pointer pointer;
typedef typename base::const_pointer const_pointer;
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
secure_allocator() noexcept {}
secure_allocator(const secure_allocator& a) noexcept : base(a) {}
template <typename U>
secure_allocator(const secure_allocator<U>& a) noexcept : base(a)
{
}
~secure_allocator() noexcept {}
template <typename _Other>
struct rebind {
typedef secure_allocator<_Other> other;
};
T* allocate(std::size_t n, const void* hint = 0)
{
return static_cast<T*>(LockedPoolManager::Instance().alloc(sizeof(T) * n));
}
void deallocate(T* p, std::size_t n)
{
if (p != nullptr) {
memory_cleanse(p, sizeof(T) * n);
}
LockedPoolManager::Instance().free(p);
}
};
// This is exactly like std::string, but with a custom allocator.
typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
#endif // BITCOINRUSH_SUPPORT_ALLOCATORS_SECURE_H
| [
"[email protected]"
]
| |
163fb8f217d7ad6aca65a249deb3bba5edae6370 | fa7474550cac23f55205666e13a99e59c749db97 | /diagnostics/cros_healthd/routines/signal_strength/signal_strength.h | 0f1836854e41764885bd6aec6282c390c6e237ce | [
"BSD-3-Clause"
]
| permissive | kalyankondapally/chromiumos-platform2 | 4fe8bac63a95a07ac8afa45088152c2b623b963d | 5e5337009a65b1c9aa9e0ea565f567438217e91f | refs/heads/master | 2023-01-05T15:25:41.667733 | 2020-11-08T06:12:01 | 2020-11-08T07:16:44 | 295,388,294 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | h | // Copyright 2020 The Chromium OS 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 DIAGNOSTICS_CROS_HEALTHD_ROUTINES_SIGNAL_STRENGTH_SIGNAL_STRENGTH_H_
#define DIAGNOSTICS_CROS_HEALTHD_ROUTINES_SIGNAL_STRENGTH_SIGNAL_STRENGTH_H_
#include <memory>
#include "diagnostics/cros_healthd/network_diagnostics/network_diagnostics_adapter.h"
#include "diagnostics/cros_healthd/routines/diag_routine.h"
namespace diagnostics {
// Status messages reported by the signal strength routine.
extern const char kSignalStrengthRoutineNoProblemMessage[];
extern const char kSignalStrengthRoutineSignalNotFoundProblemMessage[];
extern const char kSignalStrengthRoutineWeakSignalProblemMessage[];
extern const char kSignalStrengthRoutineNotRunMessage[];
// Creates the signal strength connetivity routine.
std::unique_ptr<DiagnosticRoutine> CreateSignalStrengthRoutine(
NetworkDiagnosticsAdapter* network_diagnostics_adapter);
} // namespace diagnostics
#endif // DIAGNOSTICS_CROS_HEALTHD_ROUTINES_SIGNAL_STRENGTH_SIGNAL_STRENGTH_H_
| [
"[email protected]"
]
| |
966d5ae8e6f772e554b23bc84f64558c39f6d6ea | 83df5380e3cc3a49e581f32233ff8a0716badb8a | /part1/serial_main.cpp | 0fd0e1cca6d491536cd3650b87a9d66a7871a960 | []
| no_license | sgupta38/Parallel-Programming-using-OpenMP-and-SIMD | f056ea0d1e9819e3a5a22d8274f3b1adf0146bcb | d0edaee645612e343cdb6247156fd39d9d063f0d | refs/heads/master | 2022-10-14T10:57:02.965402 | 2020-06-10T06:10:27 | 2020-06-10T06:10:27 | 271,192,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | //
// Created by sonu on 4/2/19.
//
#include <iostream>
#include "Csequential.h"
//const int N = 5000; // number of points
int
main(int argc, char *argv[])
{
if(argc != 2)
{
std::cout<<"Usage: ./sequential_sphere <number_of_points>\n"<<endl;
return 0;
}
std::string arg = argv[1];
std::size_t pos;
int N = std::stoi(arg, &pos);
if(N <=0)
{
std::cout<<" Invalid Number of Points. "<<endl;
return 0;
}
std::cout<<" Number of points: "<<N<<endl;
CSequential seq;
seq.generatePointsEx(N);
seq.plotGlobalGraph(); // Gracefull handling
return 0;
}
| [
"[email protected]"
]
| |
6dcf49244b6da807b9319a40e45f1eb83f37c9b1 | fa85329dbe03772df56547375154c5437ff2b076 | /Zero_L/Bueno_final_chido2.0. Betha, ss13.143.23/Wall.h | baf67e810087ea4af1106b57bf751ae1888127ed | [
"Apache-2.0"
]
| permissive | Ninefrm/Unsingned | 9597f3c3cf1c422adbbcbf36a41d0b97aa71aa9a | cf051f6aa6c9d93f8582539b2d36c64a41447a58 | refs/heads/master | 2021-08-24T05:07:38.657326 | 2017-12-08T05:12:47 | 2017-12-08T05:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | h | //Realizado por:
//Maximiliano Fonseca Romero
//Hrista Arantxa Martinez Martinez
//Jorge Salazar Ramirez
//Wendy Vanessa Bravo Guevara
//Vicente Ramirez Gonzales
//Luis David Lopez Zavala
#ifndef _WALL_H_
#define _WALL_H_
//librerias
#include "Obj.h"
#include "Character.h"
#include <curses.h>
class Wall : public Obj{ //Wall hereda de Obj sus miembros
public:
//constructores
Wall();
Wall(int, int, char, int, int);
//destructor
~Wall() { };
void draw() const; //metodo que dibuja en pantalla un character
bool collision(int, int) const; //verifica las colisiones con otros objetos o derivados
bool collision( const Character& p) const;//verifica las colisiones con otros objetos o derivados
//accesors
int get_rows() const;
int get_cols() const;
private:
int rows;
int cols;
};
#endif
| [
"[email protected]"
]
| |
5458663b740ca9f2f9ca393ccc3bd9042971d324 | c28f358c68ebe4f53a5074e9ba35d0f7a7488c0e | /RVTP4/mainwindow.h | 8d94c481d69e8386302af32a2a3fd16d1fbe46cd | []
| no_license | Romain-GARNIER/VirtualReality | 3d2d4fe94746f533e662fb12a579e9f748b591e8 | 8a32a132bb4a723da365f5befedaceba682238a1 | refs/heads/master | 2020-12-19T21:26:47.176806 | 2020-02-29T09:06:18 | 2020-02-29T09:06:18 | 235,856,350 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QColorDialog>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void changeAmbientLight();
void changeSpecularLight();
void changeDiffuseLight();
void changeXLight();
void changeYLight();
void changeZLight();
void changeSpecCoeff(int);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"[email protected]"
]
| |
0a684de2a60a8e3455843e6dd22dbc9ece0f7c7a | 03b21a78523264aa1210605cd407682abceadace | /code/Rendering/IRendererType.h | 73aec6bc14e119504978ed28acf92e31512f18f1 | [
"MIT"
]
| permissive | inzombiak/Orbitals | 96367f91135ae4a3490800fa2de0742387d6aea0 | b87f59eecc11863d9a355a305c45b018200c8058 | refs/heads/master | 2020-06-16T18:21:37.659473 | 2018-04-25T21:55:16 | 2018-04-25T21:55:16 | 75,171,768 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | h | #ifndef I_RENDERER_TYPE_H
#define I_RENDERER_TYPE_H
#define GLEW_STATIC
#include <GL\glew.h>
#include <string>
#include <iostream>
#include "..\Utilities\HelperFunctions.h"
#include "../Utilities/OrbitalsDefs.h"
#include "RenderComponent.h"
class IRendererType
{
public:
virtual ~IRendererType()
{ }
virtual void Init(GLuint preDrawProgram, GLuint drawProgram) = 0;
//Returns ID of program
virtual GLuint Draw(const glm::mat4& proj = glm::mat4(1.f), const glm::mat4& view = glm::mat4(1.f), const glm::vec3& lightPos = glm::vec3(0), const glm::vec3& lightDir = glm::vec3(0)) = 0;
virtual GLuint PreDraw(const glm::mat4& proj = glm::mat4(1.f), const glm::mat4& view = glm::mat4(1.f), const glm::vec3& lightPos = glm::vec3(0), const glm::vec3& lightDir = glm::vec3(0))
{
//Optional
return -1;
}
Orbitals::DrawingType GetType() const
{
return m_type;
}
//Need to rethink this whole rendering thing, its more interconnected than I thought
virtual GLuint GetTexutreID() = 0;
virtual glm::mat4 GetMVP() = 0;
protected:
GLuint m_preProgID;
GLuint m_progID;
Orbitals::DrawingType m_type;
};
#endif | [
"[email protected]"
]
| |
d814412cb88c2002f6fd20f0dcc755f1498be584 | 2bc4cd3572e0904fedbc6610dc1208eb33967431 | /prac_interp/BuildConstants.h | 596e5d3214252e2c4684f9e247755cc381a94ee1 | []
| no_license | anishmgoyal/prac_interp | d2d90c3765ee3f673adc0c833cb4dbb4b1caa3ca | 04d0b9aecd53adc06b5e8d1a517aeabe70331009 | refs/heads/master | 2021-06-22T19:04:31.198942 | 2017-08-17T16:37:44 | 2017-08-17T16:37:44 | 100,624,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | h | #ifndef BuildConstants_H
#define BuildConstants_H
#include "Main.h"
#include <string>
#include "Token.h"
namespace Prac
{
enum BuildException
{
INVALID_START_OF_STATEMENT,
INVALID_ESCAPE_CHAR_USAGE,
EXPECTED_KEYWORD_NOT_FOUND,
EXPECTED_IDENTIFIER_NOT_FOUND,
EXPECTED_SEMICOLON_NOT_FOUND,
EXPECTED_CLOSEPARENTH_NOT_FOUND,
EXPECTED_CLOSEBRACKET_NOT_FOUND,
EXPECTED_OPENBRACKET_NOT_FOUND,
EXPECTED_OTHERWISE_BRANCH_NOT_FOUND,
INVALID_IDENTIFIER,
KEYWORD_AS_IDENTIFIER,
INVALID_TYPENAME,
INVALID_OPERANDS,
UNSUPPORTED_OPERATION,
TYPES_DONT_MATCH,
NON_BOOLEAN_CONDITIONAL,
UNEXPECTED_END,
};
enum ReservedKeyword
{
NONE,
KEY_A,
KEY_AN,
KEY_AND,
KEY_AS,
KEY_ASSIGN,
KEY_DECLARE,
KEY_DOESNT,
KEY_EQUAL,
KEY_EQUALS,
KEY_FALSE,
KEY_FROM,
KEY_GET,
KEY_IF,
KEY_IN,
KEY_IT,
KEY_NEWLINE,
KEY_NOT,
KEY_OF,
KEY_OR,
KEY_OTHERWISE,
KEY_PRINT,
KEY_STORE,
KEY_THE,
KEY_TO,
KEY_TRUE,
KEY_USER,
KEY_WHILE,
TYPE_INTEGER,
TYPE_NUMBER,
TYPE_CHARACTER,
TYPE_BOOLEAN,
TYPE_TYPE,
};
ReservedKeyword getKeyword(const Token& token);
ReservedKeyword getKeyword(const std::string& str);
}
#endif | [
"[email protected]"
]
| |
ffb0b3860a39c73113ddbc71ae900c41cf3ba089 | ed470a87602ee93203f44c1c94bf721f58a2b20b | /雜題/各種瑣碎/K_bestbefore.cpp | ed14b53986138e7d18eddb3d175c8ed529ade43a | []
| no_license | WilliamHsieh/OmegaExercise | e91837502e43ec536eb1872213b0f765d0eed403 | a6f88eb16d69203901a18bfeb3d64a2a588000bd | refs/heads/master | 2021-10-20T13:59:58.861137 | 2019-02-28T07:39:21 | 2019-02-28T07:39:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | cpp | #include <bits/stdc++.h>
using namespace std;
bool isleap(int y) {
if (y % 400 == 0)
return true;
else if (y % 100 == 0)
return false;
else if (y % 4 == 0)
return true;
else
return false;
}
int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool islegal(int y, int m, int d) {
if (m >= 13 || m == 0) return false;
if (m == 2) {
if (d > day[m - 1] + isleap(y) || d == 0)
return false;
} else {
if (d > day[m - 1] || d == 0)
return false;
}
return true;
}
int main() {
string input; cin >> input;
string tar = input;
for (auto &c : tar)
if (c == '/')
c = ' ';
stringstream ss; ss << tar;
vector<int> vec; int tmp;
while (ss >> tmp) vec.push_back(tmp);
sort(vec.begin(), vec.end());
bool legal = false;
do {
if (islegal(vec[0] < 2000 ? vec[0] + 2000 : vec[0], vec[1], vec[2])) {
legal = true;
break;
}
} while (next_permutation(vec.begin(), vec.end()));
if (legal) {
cout << (vec[0] < 2000 ? vec[0] + 2000 : vec[0]) << '-';
cout << setw(2) << setfill('0') << vec[1] << '-';
cout << setw(2) << setfill('0') << vec[2] << '\n';
} else {
cout << input << " is illegal\n";
}
}
| [
"[email protected]"
]
| |
9a3853762653f6d26f00e7923bc0994be2eab53b | 0b070626740788d5af23fcd1cd095e56033308de | /984.cpp | 8bd302bbbcc9efe1b99076a982f84ed0963845a1 | []
| no_license | xis19/leetcode | 71cb76c5764f8082155d31abcb024b25fd90bc75 | fb35fd050d69d5d8abf6794ae4bed174aaafb001 | refs/heads/master | 2021-03-24T12:53:34.379480 | 2020-02-24T04:25:36 | 2020-02-24T04:25:36 | 76,006,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cpp | #include <string>
std::string strWithout3a3b(int A, int B) {
// take the longest as 'a'
bool swapAB = false;
if (B > A) {
std::swap(A, B);
swapAB = true;
}
std::string result;
// First fill ABABAB pattern
// three possibilities:
// A > B * 2 + 2, then there could not be a solution
// A > B * 2, then the result is AABAABAAB...BAA
// A = B * 2, then the result is AABAABAAB...AAB
// A < B * 2, then we could always write ABABAB until A = B * 2
// as (A - 1) - (B - 1) * 2 = (A - B * 2) + 1
auto residue = A > B * 2 ? A - B * 2 : 0;
A -= residue;
// Fill ABAB pattern
while(A < B * 2) {
result.push_back('1');
result.push_back('2');
--A, --B;
}
// Then fill AABAAB pattern
while(B > 0) {
result.push_back('1');
result.push_back('1');
result.push_back('2');
A -= 2;
B -= 1;
}
for (auto i = 0; i < residue; ++i) {
result.push_back('1');
}
char x = 'a', y = 'b';
if (swapAB) std::swap(x, y);
for (auto& ch: result) {
if (ch == '1') ch = x; else ch = y;
}
return result;
}
| [
"[email protected]"
]
| |
b856074c27b8aeb8281cd0c830f1f816f9e9f7b3 | 08000a356fbf57cb0aef9d98daef0e79fde44c62 | /cppgst.cpp | e4578ea709b81344c37d2381cc4b67519cc53ca5 | []
| no_license | Plumes/hitsm | bde80279ac656b86ba7b9794862c78313895553e | 2f3347a14c8687f377ca508169a9921cdb7f67b5 | refs/heads/master | 2016-09-06T07:14:49.734352 | 2014-08-01T16:34:51 | 2014-08-01T16:34:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,851 | cpp | #include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<ctime>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
//#define MML 20
#define MAX_LENGTH 500
typedef struct Max_Match_Type{
int p,t,s;
}Max_Match_Type;
vector<Max_Match_Type> match,tile;
char *text,*patten;
int *mark_t,*mark_p;
int len_t,len_p;
double sim_pt;
int MML;
int main(int argc,char*argv[]){
FILE *fa,*fb,*fgst,*fmatch;
int fa_size,fb_size;
int max_match;
int i,j,k;
int fx,fy;
if(argc!=5 && argc!=6){
cout<<"Usage:"<<argv[0]<<" <source file 1> <source file 2>"<<endl;
return -1;
}
if(!(fa=fopen(argv[1],"rb"))){
cout<<"Open "<<argv[1]<<" error!"<<endl;
return -1;
}
if(!(fb=fopen(argv[2],"rb"))){
cout<<"Open "<<argv[2]<<" error!"<<endl;
return -1;
}
fx=atoi(argv[3]);
fy=atoi(argv[4]);
if(argc==6)
MML=atoi(argv[5]);
else
MML=30;
fseek(fa,0,SEEK_END);
fa_size = ftell(fa);
fseek(fa,0,SEEK_SET);
fseek(fb,0,SEEK_END);
fb_size = ftell(fb);
fseek(fb,0,SEEK_SET);
if(fb_size<=fa_size){
text=(char *)malloc((fa_size+1) * sizeof(char));
mark_t=(int *)malloc((fa_size+1) * sizeof(int));
fread(text,fa_size,sizeof(char),fa);
text[fa_size]='\0';
patten=(char *)malloc((fb_size+1) * sizeof(char));
mark_p=(int *)malloc((fb_size+1) * sizeof(int));
fread(patten,fb_size,sizeof(char),fb);
patten[fb_size]='\0';
}else{
text=(char *)malloc((fb_size+1) * sizeof(char));
mark_t=(int *)malloc((fb_size+1) * sizeof(int));
fread(text,fb_size,sizeof(char),fb);
text[fb_size]='\0';
patten=(char *)malloc((fa_size+1) * sizeof(char));
mark_p=(int *)malloc((fa_size+1) * sizeof(int));
fread(patten,fa_size,sizeof(char),fa);
patten[fa_size]='\0';
}
memset(mark_t,0,sizeof(mark_t));
memset(mark_p,0,sizeof(mark_p));
len_t=strlen(text);
len_p=strlen(patten);
tile.clear();
do{
max_match=MML;
match.clear();
for(i=0;i<len_p;i++)
if(!mark_p[i])
for(j=0;j<len_t;j++)
if(!mark_t[j]){
k=0;
while(patten[i+k]==text[j+k] && !mark_p[i+k] && !mark_t[j+k] && patten[i+k]!='\0' && text[j+k]!='\0')
k++;
Max_Match_Type a;
a.p=i;a.t=j;a.s=k;
if(k==max_match){
match.push_back(a);
break;
}
else if(k>max_match){
match.clear();
match.push_back(a);
max_match=k;
break;
}
}
for(i=0;i<match.size();i++){
int unmark=1;
for(j=0;j<match[i].s;j++)
if(mark_p[match[i].p+j]==1 || mark_t[match[i].t+j]==1){
unmark=0;
break;
}
if(unmark){
for(j=0;j<match[i].s;j++){
mark_p[match[i].p+j]=1;
mark_t[match[i].t+j]=1;
}
tile.push_back(match[i]);
}
}
}while(max_match>MML);
sim_pt=0;
int totol=0;
for(i=0;i<tile.size();i++)
totol+=tile[i].s;
totol*=2;
sim_pt=totol*1.0/(len_p+len_t);
/*
//ofstream ofs("cmp.txt");
//streambuf *osb = cout.rdbuf(ofs.rdbuf());
cout<<text<<endl;
cout<<"***************************************************"<<endl;
cout<<patten<<endl;
cout<<"***************************************************"<<endl;
for(i=0;i<tile.size();i++){
cout<<tile[i].p<<","<<tile[i].t<<","<<tile[i].s<<endl;
cout<<"---------------------------------------------------"<<endl;
for(j=0;j<tile[i].s;j++)
cout<<patten[tile[i].p+j];
cout<<endl;
cout<<"---------------------------------------------------"<<endl;
for(j=0;j<tile[i].s;j++)
cout<<text[tile[i].t+j];
cout<<endl;
cout<<"###################################################"<<endl;
}
cout<<"simPT:"<<sim_pt<<endl;
cout<<"len_p="<<len_p<<",len_t="<<len_t<<",totol="<<totol<<endl;
//cout.rdbuf(osb);
*/
/*
cout<<argv[1]<<"\t"<<argv[2]<<"\t"<<fixed<<setprecision(6)<<sim_pt<<"\t";
cout<<"|";
if(int(sim_pt)==1)
for(i=0;i<int(sim_pt*20);i++)
cout<<"=";
else
for(i=0;i<=int(sim_pt*20);i++)
cout<<"=";
for(i=1;i<20-int(sim_pt*20);i++)
cout<<" ";
cout<<"|";
if(sim_pt>0.9-0.000000000000001)
cout<<"\tAlarm!";
else if(sim_pt>0.8-0.00000000000001)
cout<<"\tWarning!";
cout<<endl;
*/
/* fgst = fopen("./doc/sim.gst","a");
fprintf(fgst,"%d\t%d\t%0.6f\n",fx,fy,sim_pt);
//cout<<fx<<"\t"<<fy<<"\t"<<fixed<<setprecision(6)<<sim_pt<<endl;
*/
char dir[1000]="./doc/";//+argv[3]+"_"+argv[4]+".match";
strcat(dir,argv[3]);
strcat(dir,"_");
strcat(dir,argv[4]);
strcat(dir,".match");
fmatch = fopen(dir,"w");
if(fb_size<=fa_size)
{
for(i=0;i<tile.size();i++)
fprintf(fmatch,"%d\t%d\t%d\n",tile[i].t,tile[i].p,tile[i].s);
}
else
{
for(i=0;i<tile.size();i++)
fprintf(fmatch,"%d\t%d\t%d\n",tile[i].p,tile[i].t,tile[i].s);
}
//fprintf(fmatch,"world");
free(mark_t);
free(mark_p);
free(text);
free(patten);
fclose(fa);
fclose(fb);
//fclose(fgst);
fclose(fmatch);
return sim_pt;
}
| [
"[email protected]"
]
| |
02adc4eedbc73c4381bd28b58089340a4397258d | d7c77018b0c5e7d1e6e24d82fa905a1ac5b0a85e | /PbInfo/multimi.cpp | 89fc124833add6f2b94f9db3586a8a88bfb818ea | []
| no_license | muresangabriel-alexander/cplusplus-competitive | 9396cff60c6be0f5ae3d307f58e350423e336764 | 4a17656ccbea58d779bf5bd74aed5edb9c579ca6 | refs/heads/master | 2021-04-28T07:57:22.419138 | 2018-02-20T18:42:59 | 2018-02-20T18:42:59 | 122,238,407 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | #include <iostream>
using namespace std;
int main()
{
int n,m,k,l,a[1001], b[1001], c[2001], d[1001];
cin>>n;
for(int i=1; i<=n; i++) cin>>a[i];
cin>>m;
for(int i=1; i<=m; i++) cin>>b[i];
int i=1, j=1;
k=l=0;
while(i<=n && j<=m)
if(a[i]<b[j]) c[++k]=a[i++];
else if(b[j]<a[i]) c[++k]=b[j++];
else
{
c[++k]=a[i];
d[++l]=a[i++];
j++;
}
while(i<=n) c[++k]=a[i++];
while(j<=m) c[++k]=b[j++];
for(i=1; i<=k; i++) cout<<c[i]<<" ";
cout<<'\n';
for(i=1; i<=l; i++) cout<<d[i]<<" ";
return 0;
}
| [
"[email protected]"
]
| |
f07718e1c15e3696becebc0496c27a23bfdb7f23 | f97ce0a588e023675eaa980f2f105f0a9c25ce18 | /UVa/v6/624.CPP | 5fc78ce51a5dcac69697b235722c789f6025fa4d | []
| no_license | anindya028/Programming-Contest-Problems | a5c49653d990391a6e2003f2ec9d951222cabbe2 | 7038b6267432189de72539ef5ad046d38e730ee8 | refs/heads/master | 2023-03-17T06:27:38.339049 | 2021-02-23T22:58:06 | 2021-02-23T22:58:06 | 277,399,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | #include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main()
{
int c,n,cd[50],i,j,sum,max,t;
while(scanf("%d%d",&c,&n)==2)
{
for(i=0;i<n;i++)
scanf("%d",&cd[i]);
max=0;
for(i=1;i<=(1<<n);i++)
{
for(j=sum=0;j<n;j++)
if(i & 1<<j)
{
sum+=cd[j];
}
if(sum>max && sum<=c)
{
max=sum;
t=i;
}
}
for(j=0;j<n;j++)
if(t & 1<<j)
printf("%d ",cd[j]);
printf("sum:%d\n",max);
}
return 0;
}
| [
"[email protected]"
]
| |
1ef7b971945a56eed75cae571a7ef88620c5808c | 4260be4aee77d71c15cfe52b6c7e0622fdfd6c30 | /run_external_udf.cc | f8c05b4049e2bc1ec4a28ed27392a9f1dfa1ad97 | []
| no_license | dveeden/run_external | 15793914d4182fc6dab88dc3218fc2e17245877e | 3f7573cee7157373d7b9fd4fdcd1b11ea37b3535 | refs/heads/master | 2021-01-18T08:09:18.255918 | 2015-02-14T11:38:02 | 2015-02-14T11:38:02 | 30,794,939 | 0 | 0 | null | 2015-02-14T11:37:19 | 2015-02-14T11:37:18 | null | UTF-8 | C++ | false | false | 1,025 | cc | #include "run_external_udf.h"
long long run_external(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
char *command = new char[args->lengths[0]+1];
command = args->args[0];
command[args->lengths[0]] = '\0';
int result = system(command);
if (0 != result)
return false;
else
return true;
}
my_bool run_external_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count < 1) {
strcpy(message, "You must specify at least one argument");
return 1;
}
for (unsigned int i = 0; i < args->arg_count; i ++) {
if (args->arg_type[0] != STRING_RESULT) {
strcpy(message, "RUN_EXTERNAL accepts only string arguments");
return 1;
}
}
if (!(initid->ptr = (char*)malloc(MAXRES))) {
strcpy(message,"Couldn't allocate memory for result buffer");
return 1;
}
memset(initid->ptr, '\0', MAXRES);
initid->maybe_null = 1;
initid->max_length = 1;
initid->const_item = 0;
return 0;
}
void run_external_deinit(UDF_INIT *initid)
{
if (initid->ptr)
free(initid->ptr);
}
| [
"[email protected]"
]
| |
02eba7a9bcd14b4f731afcc94c1dfa7862c2008b | cd052cb6b2796ed7335241f4bb18077dc3d8c023 | /library/framework/server/web/include/sirius_web_server_framework.h | 4510efccbf90546fb6f3ff184d5605572455c577 | []
| no_license | nemeyes/sirius | 8280b9d64cfab3c3ac9623849f0f3bcc9d7d72a3 | 75df58a23de41a17833e17ba2326719c6e7954e5 | refs/heads/master | 2021-03-27T13:27:52.387337 | 2019-05-17T09:29:29 | 2019-05-17T09:29:29 | 107,658,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,808 | h | #ifndef _SIRIUS_WEB_SERVER_FRAMEWORK_H_
#define _SIRIUS_WEB_SERVER_FRAMEWORK_H_
#include <sirius_server_framework.h>
#include <SDKDDKVer.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace sirius
{
namespace library
{
namespace framework
{
namespace server
{
class __declspec(dllexport) web
: public sirius::library::framework::server::base
{
public:
class core;
class d3d11_video_source;
class host_video_source;
public:
web(void);
virtual ~web(void);
void set_notification_callee(sirius::library::misc::notification::internal::notifier::callee* callee);
int32_t initialize(sirius::library::framework::server::web::context_t * context);
int32_t release(void);
int32_t play(void);
int32_t pause(void);
int32_t stop(void);
int32_t state(void) const;
void on_keyup(int32_t key);
void on_keydown(int32_t key);
void on_L_mouse_down(int32_t pos_x, int32_t pos_y);
void on_L_mouse_up(int32_t pos_x, int32_t pos_y);
void on_R_mouse_down(int32_t pos_x, int32_t pos_y);
void on_R_mouse_up(int32_t pos_x, int32_t pos_y);
void on_L_mouse_dclick(int32_t pos_x, int32_t pos_y);
void on_R_mouse_dclick(int32_t pos_x, int32_t pos_y);
void on_mouse_move(int32_t pos_x, int32_t pos_y);
void on_mouse_wheel(int32_t pos_x, int32_t pos_y, int32_t wheel_delta);
void on_end2end_data(const uint8_t * packet, int32_t packet_size);
private:
sirius::library::framework::server::web::core * _core;
};
};
};
};
};
extern "C"
{
__declspec(dllexport) sirius::library::framework::server::base * create_server_framework(void);
__declspec(dllexport) void destroy_server_framework(sirius::library::framework::server::base ** player_framework);
}
#endif
| [
"[email protected]"
]
| |
487da6d8e57aec0823c7b735ff52475ca108891e | eb80296e7c74cf2ea3f2f06a144e1818cd367a56 | /textshredder_core/server/usermanager.cpp | e0b9412c136dc536a9d05358937bc2adb0b73b35 | []
| no_license | mitchelkuijpers/TextShredder | 6d2ef5cef0ea6862eb70f7bd518d433c62ce38fc | 742128cc810234bef791f82795ecc1cd7f013127 | refs/heads/master | 2020-08-10T14:51:40.529529 | 2011-06-14T12:56:02 | 2011-06-14T12:56:02 | 1,576,419 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | #include "usermanager.h"
#include <QDebug>
UserManager * UserManager::sharedInstance = NULL;
UserManager * UserManager::Instance()
{
if (sharedInstance == NULL) {
sharedInstance = new UserManager(NULL);
}
return sharedInstance;
}
UserManager::UserManager(QObject *parent) :
QObject(parent)
{
}
void UserManager::addAlias(QString alias)
{
qDebug() << "UserManager::addAlias(QString alias)" << alias;
userNames.append(alias);
emit usersChanged();
}
void UserManager::removeAlias(QString alias)
{
qDebug() << "UserManager::removeAlias(QString alias)" << alias;
int index = userNames.indexOf(alias);
userNames.removeAt(index);
emit usersChanged();
}
void UserManager::clearAndAddList(QList<QString> newList) {
userNames.clear();
qDebug() << "Usernames count "<< userNames.count();
userNames.append(newList);
qDebug() << "Usernames count "<< userNames.count();
emit usersChanged();
}
QList<QString> UserManager::getUsers()
{
return userNames;
}
| [
"[email protected]"
]
| |
f476a65ef7f661c604bdd89748052b2ec49d7754 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /cc/test/fake_tile_task_manager.h | 9c97ca06204ee180546f8793e441828c985dd7ba | [
"BSD-3-Clause"
]
| permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 871 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_TEST_FAKE_TILE_TASK_MANAGER_H_
#define CC_TEST_FAKE_TILE_TASK_MANAGER_H_
#include "cc/test/fake_raster_buffer_provider.h"
#include "cc/tiles/tile_task_manager.h"
namespace cc {
// This class immediately cancels the scheduled work, i.e. in ScheduleTasks()
// it cancels all the tasks.
class FakeTileTaskManagerImpl : public TileTaskManager {
public:
FakeTileTaskManagerImpl();
~FakeTileTaskManagerImpl() override;
// Overridden from TileTaskManager:
void ScheduleTasks(TaskGraph* graph) override;
void CheckForCompletedTasks() override;
void Shutdown() override;
protected:
Task::Vector completed_tasks_;
};
} // namespace cc
#endif // CC_TEST_FAKE_TILE_TASK_MANAGER_H_
| [
"[email protected]"
]
| |
bec97cfaa31d3430560f0bbfd3dc6f295ea4b97b | 2a3327090b5827982a82c86a653d17382dd4e006 | /CHARMS/ref/famuls/gcell_solid_h8.cc | d95ce42a72e3ddd15bf44174e97bb70c5350112d | []
| no_license | kengwit/misc | 85e7e0aa1366258f246d5a98cae4ee6b19f3bff5 | ca3a8cb6453f3a3fc37bcaf084627fb7cd2fbbc6 | refs/heads/master | 2020-04-01T03:21:53.407225 | 2019-10-31T01:36:45 | 2019-10-31T01:36:45 | 152,818,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,272 | cc | /*--------------------------------------------------------------------------
-- --
-- (F)ramework for (A)daptive (MUL)tiphysics (S)imulations --
-- Copyright (C) 2001, Petr Krysl ([email protected]). --
-- --
-- [Pronounce `famulus': scholar's helper] --
-- --
-- --
-- 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. --
-- --
--------------------------------------------------------------------------*/
#include "famuls.h"
#include "gcell_solid_h8.h"
#include "field.h"
#include "evalpt.h"
#include "ref_ctx.h"
const char GCELL_SOLID_H8::TYPE_NAME[] = "solid_h8";
const double GCELL_SOLID_H8::_child_map[NCHILDREN][2][3] = {
{ {-1,-1,-1}, {0,0,0} },
{ { 0,-1,-1}, {1,0,0} },
{ { 0, 0,-1}, {1,1,0} },
{ {-1, 0,-1}, {0,1,0} },
{ {-1,-1, 0}, {0,0,1} },
{ { 0,-1, 0}, {1,0,1} },
{ { 0, 0, 0}, {1,1,1} },
{ {-1, 0, 0}, {0,1,1} }
};
extern "C" {
#include "g3dhex.h"
}
GCELL_SOLID_H8::GCELL_SOLID_H8 (vector <FEN *> fens) : GCELL ()
{
sizet nfens = _conn.nfens ();
CHECK (fens.size () == nfens, EXCEPTION_BAD_VALUE ,;);
for (unsigned int i = 0; i < nfens; i++) _conn.fen(i) = fens[i];
_parent = 0;
for (sizet i = 0; i < NCHILDREN; i++) _child[i] = 0;
}
static GCELL *
make (vector <FEN *> fens)
{
return (new GCELL_SOLID_H8 (fens));
}
bool
GCELL_SOLID_H8::register_make_func ()
{
return GCELL::register_make_func (make, string(TYPE_NAME), string ("default"));
}
void
GCELL_SOLID_H8::eval_ns (GCELL_SOLID_H8 *child, EVALPT *evalpt,
double xi, double eta, double theta, double dxiparent_dxichild)
{
const sizet nbfuns = evalpt->nbfuns();
if (child != 0) {
for (sizet j = 0; j < GCELL_SOLID_H8::NCHILDREN; j++) {
if (child == this->child(j)) {
const int LO = 0, HI = 1;
xi = (1 - xi) / 2 * _child_map[j][LO][0] + (1 + xi) / 2 * _child_map[j][HI][0];
eta = (1 - eta) / 2 * _child_map[j][LO][1] + (1 + eta) / 2 * _child_map[j][HI][1];
theta = (1 - theta) / 2 * _child_map[j][LO][2] + (1 + theta) / 2 * _child_map[j][HI][2];
break; // done
}
}
dxiparent_dxichild /= 2;
}
// Evaluate your own basis functions
const sizet nfens = 8;
double N[nfens];
G3D_hex_N (N, xi, eta, theta);
double N_xi[nfens], N_eta[nfens], N_theta[nfens];
G3D_hex_N_xi ( N_xi, xi, eta, theta);
G3D_hex_N_eta ( N_eta, xi, eta, theta);
G3D_hex_N_theta (N_theta, xi, eta, theta);
// Now shove the results into the buffer
sizet had = 0;
for (sizet j = 0; j < nbfuns; j++) {
for (sizet k = 0; k < nfens; k++) {
if (evalpt->fen(j) == _conn.fen(k)) {
evalpt->set_N (j, N[k]);
evalpt->set_N_der (j, 0, N_xi[k] * dxiparent_dxichild);
evalpt->set_N_der (j, 1, N_eta[k] * dxiparent_dxichild);
evalpt->set_N_der (j, 2, N_theta[k] * dxiparent_dxichild);
had++;
}
}
if (had == nfens) break;
}
// If you're the child of another cell, ask it to do its job
if (this->_parent != 0) this->_parent->eval_ns (this, evalpt, xi, eta, theta, dxiparent_dxichild);
}
bool
GCELL_SOLID_H8::eval_bfun_set (EVALPT *evalpt)
{
POINT param_loc = evalpt->param_loc();
eval_ns (0, evalpt, param_loc(0), param_loc(1), param_loc(2), 1.0);
return true;
}
void
GCELL_SOLID_H8::divide (REF_CTX *ref_ctx)
{
if (this->nchildren () == 0) { // Not refined yet
const sizet nfens = 8;
# define EVN(e,v) g3dhex_vertex_on_edge[e][v]
# define FVN(f,v) g3dhex_vertex_on_face[f][v]
// Get the refinement nodes for the vertices
vector <FEN *> v_fens(nfens);
CONN_POINT_1 vertex_conn[nfens];
vector <POINT> ref_locs(1);
for (sizet i = 0; i < nfens; i++) {
vertex_conn[i].fen(0) = _conn.fen(i);
ref_locs[0] = _conn.fen(i)->ref_loc();
v_fens[i] = ref_ctx->get_ref_fen (&vertex_conn[i], 0, ref_locs);
CHECK (v_fens[i] != 0, EXCEPTION_NULL_PTR,;);
}
// Get the refinement nodes for the edges
vector <FEN *> e_fens(NEDGES);
CONN_LINE_2 edge_conn[NEDGES];
for (sizet i = 0; i < NEDGES; i++) {
edge_conn[i].fen(0) = _conn.fen(EVN(i,0));
edge_conn[i].fen(1) = _conn.fen(EVN(i,1));
FIXED_VECTOR<3> l; l.assign (0.5, _conn.fen(EVN(i,0))->ref_loc(),
0.5, _conn.fen(EVN(i,1))->ref_loc());
ref_locs[0] = l;
e_fens[i] = ref_ctx->get_ref_fen (&edge_conn[i], 0, ref_locs);
CHECK (e_fens[i] != 0, EXCEPTION_NULL_PTR,;);
}
// Get the refinement nodes for the faces
vector <FEN *> f_fens(NFACES);
CONN_SURF_4 face_conn[NFACES];
for (sizet i = 0; i < NFACES; i++) {
FIXED_VECTOR<3> l(0.0);
for (int j = 0; j < 4; j++) {
face_conn[i].fen(j) = _conn.fen(FVN(i,j));
l.add (0.25, _conn.fen(FVN(i,j))->ref_loc());
}
ref_locs[0] = l;
f_fens[i] = ref_ctx->get_ref_fen (&face_conn[i], 0, ref_locs);
CHECK (f_fens[i] != 0, EXCEPTION_NULL_PTR,;);
}
// Get the refinement node for the interior
POINT midpoint(0.0);
for (sizet i = 0; i < nfens; i++) {
midpoint.add (1.0/8, _conn.fen(i)->ref_loc());
}
ref_locs[0] = midpoint;
FEN *m_fen = ref_ctx->get_ref_fen (&_conn, 0, ref_locs);
CHECK (m_fen != 0, EXCEPTION_NULL_PTR,;);
// Now generate the new gcells
vector <FEN *> fens(nfens);
int nc;
#define V(i) v_fens[i]
#define E(i) e_fens[i]
#define F(i) f_fens[i]
#define M m_fen
#define DEFFEN(n0,n1,n2,n3,n4,n5,n6,n7) {fens[0] = n0; fens[1] = n1; fens[2] = n2; fens[3] = n3; fens[4] = n4; fens[5] = n5; fens[6] = n6; fens[7] = n7;}
nc = 0; ///////////////////////////////////
DEFFEN (V(0), E(0), F(0), E(3), E(8), F(1), M, F(4));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 1; ///////////////////////////////////
DEFFEN (E(0), V(1), E(1), F(0), F(1), E(9), F(2), M);
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 2; ///////////////////////////////////
DEFFEN (F(0), E(1), V(2), E(2), M, F(2), E(10), F(3));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 3; ///////////////////////////////////
DEFFEN (E(3), F(0), E(2), V(3), F(4), M, F(3), E(11));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 4; ///////////////////////////////////
DEFFEN (E(8), F(1), M, F(4), V(4), E(4), F(5), E(7));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 5; ///////////////////////////////////
DEFFEN (F(1), E(9), F(2), M, E(4), V(5), E(5), F(5));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 6; ///////////////////////////////////
DEFFEN (M, F(2), E(10), F(3), F(5), E(5), V(6), E(6));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
nc = 7; ///////////////////////////////////
DEFFEN (F(4), M, F(3), E(11), E(7), F(5), E(6), V(7));
_child[nc] = new GCELL_SOLID_H8 (fens);
_child[nc]->_parent = this;
this->gcell_group ()->add (_child[nc]);
}
}
void
GCELL_SOLID_H8::detail_set (FEN *fen_of_bfun_to_refine,set <FEN *> *rf)
{
int local_index = _conn.local_index (fen_of_bfun_to_refine);
if (local_index >= 0) { // Insert nodes
const sizet nfens = 8;
for (sizet i = 0; i < nfens; i++) {
if (i != (sizet) local_index) {
(*rf).insert (_child[local_index]->conn()->fen(i));
}
}
}
}
void
GCELL_SOLID_H8::complete_refinement_set (FEN *fen_of_bfun_to_refine,set <FEN *> *rf)
{
int local_index = _conn.local_index (fen_of_bfun_to_refine);
if (local_index >= 0) { // Insert nodes
detail_set (fen_of_bfun_to_refine, rf);
(*rf).insert(_child[local_index]->conn()->fen(local_index));
}
}
extern "C" {
#include "g3dhex.h"
}
void
GCELL_SOLID_H8::map_fen (FEN *fen, POINT *param_loc)
{
for (sizet j = 0; j < _conn.nfens (); j++) {
if (fen->id() == _conn.fen(j)->id()) {
(*param_loc)(0) = g3dhex_vertex_param_coord[j][0];
(*param_loc)(1) = g3dhex_vertex_param_coord[j][1];
(*param_loc)(2) = g3dhex_vertex_param_coord[j][2];
return;
}
}
throw EXCEPTION_BAD_VALUE(); // the node is unknown to this cell; raise hell
}
bool
GCELL_SOLID_H8::map_to_child (POINT ¶m_loc, GCELL **child, POINT *child_param_loc)
{
if (nchildren() == 0) return false;
double xi = param_loc(0), eta = param_loc(1), theta = param_loc(2);
if (xi < 0) {
if (eta < 0) {
if (theta < 0) {
*child = _child[0];
(*child_param_loc)(0) = 2 * xi + 1;
(*child_param_loc)(1) = 2 * eta + 1;
(*child_param_loc)(2) = 2 * theta + 1;
} else {
*child = _child[4];
(*child_param_loc)(0) = 2 * xi + 1;
(*child_param_loc)(1) = 2 * eta + 1;
(*child_param_loc)(2) = 2 * theta - 1;
}
} else {
if (theta < 0) {
*child = _child[3];
(*child_param_loc)(0) = 2 * xi + 1;
(*child_param_loc)(1) = 2 * eta - 1;
(*child_param_loc)(2) = 2 * theta + 1;
} else {
*child = _child[7];
(*child_param_loc)(0) = 2 * xi + 1;
(*child_param_loc)(1) = 2 * eta - 1;
(*child_param_loc)(2) = 2 * theta - 1;
}
}
} else {
if (eta < 0) {
if (theta < 0) {
*child = _child[1];
(*child_param_loc)(0) = 2 * xi - 1;
(*child_param_loc)(1) = 2 * eta + 1;
(*child_param_loc)(2) = 2 * theta + 1;
} else {
*child = _child[5];
(*child_param_loc)(0) = 2 * xi - 1;
(*child_param_loc)(1) = 2 * eta + 1;
(*child_param_loc)(2) = 2 * theta - 1;
}
} else {
if (theta < 0) {
*child = _child[2];
(*child_param_loc)(0) = 2 * xi - 1;
(*child_param_loc)(1) = 2 * eta - 1;
(*child_param_loc)(2) = 2 * theta + 1;
} else {
*child = _child[6];
(*child_param_loc)(0) = 2 * xi - 1;
(*child_param_loc)(1) = 2 * eta - 1;
(*child_param_loc)(2) = 2 * theta - 1;
}
}
}
return true; // done
}
bool
GCELL_SOLID_H8::map_to_parent (POINT ¶m_loc, GCELL **parent, POINT *parent_param_loc)
{
if (_parent) {
double xi = param_loc(0), eta = param_loc(1), theta = param_loc(2);
for (sizet j = 0; j < GCELL_SOLID_H8::NCHILDREN; j++) {
if (this == _parent->child(j)) {
const int LO = 0, HI = 1;
(*parent_param_loc)(0)
= (1 - xi) / 2 * _child_map[j][LO][0] + (1 + xi) / 2 * _child_map[j][HI][0];
(*parent_param_loc)(1)
= (1 - eta) / 2 * _child_map[j][LO][1] + (1 + eta) / 2 * _child_map[j][HI][1];
(*parent_param_loc)(2)
= (1 - theta) / 2 * _child_map[j][LO][2] + (1 + theta) / 2 * _child_map[j][HI][2];
*parent = _parent;
return true;
}
}
}
return false; // no parent
}
void
GCELL_SOLID_H8::debug_display ()
{
cerr << "GCELL_SOLID_H8 "
<< this->conn()->fen(0)->id() << " "
<< this->conn()->fen(1)->id() << " "
<< this->conn()->fen(2)->id() << " "
<< this->conn()->fen(3)->id() << " "
<< this->conn()->fen(4)->id() << " "
<< this->conn()->fen(5)->id() << " "
<< this->conn()->fen(6)->id() << " "
<< this->conn()->fen(7)->id();
}
| [
"[email protected]"
]
| |
9e0dc07f259bdb554220534f3612f0f54b35e777 | fb1d349e2fa43c1b9b73e6c05c865071b35eea7e | /codec1/src/lbg.h | b5949421c5aa2a515a88fbc8f1ed4f7453612224 | []
| no_license | Silveryu/AVC | 12db438f2907ce14a04cd9e47152ad9e8e5423c8 | 144914107e187083249c11bbfe8e3ace550fda3c | refs/heads/master | 2020-06-02T17:31:26.640301 | 2019-06-12T17:01:31 | 2019-06-12T17:01:31 | 191,249,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,681 | h | #ifndef LBG_H
#define LBG_H
#include <iostream>
#include <vector>
#include <random>
#include <numeric>
#include <stdlib.h>
#include "binarystream.h"
struct
{
unsigned int elSize;
unsigned int blockSize;
unsigned int codebookSize;
} CB_METADATA;
// not a great name
class LBG{
private:
std::vector<std::vector<short>> training_vectors;
std::vector<std::vector<short>> codebook;
std::vector<unsigned int> clusterAssignments;
std::vector<int> assignmentSum;
unsigned int codebookSize;
unsigned int blockSize;
double calculateDistortion(){
double distortion = 0;
for(size_t i=0; i < training_vectors.size(); ++i){
distortion += ldistance(training_vectors[i], codebook[clusterAssignments[i]]);
}
return distortion;
}
public:
LBG( unsigned int codebookSize, unsigned int blockSize):
codebookSize(codebookSize), blockSize(blockSize)
{
//reserve vars
codebook = std::vector<std::vector<short>>(codebookSize, std::vector<short>(blockSize));
//assignments for each centroid
assignmentSum.reserve(blockSize);
}
LBG(std::vector<std::vector<short>>& codebook, unsigned int codebookSize, unsigned int blockSize):
codebook(codebook), codebookSize(codebookSize), blockSize(blockSize)
{
//assignments for each centroid
assignmentSum.reserve(blockSize);
}
// rest of samples that don't complete a full block are discarded
void updateTrainingVectors(const std::vector<short>& samples, int overlapFactor) {
std::vector<short> block(blockSize);
size_t n { };
for(auto s : samples){
block[n++ % blockSize] = s;
if(n % (blockSize-overlapFactor) == 0 && n > blockSize)
training_vectors.push_back(block);
}
}
void chooseInitialRandomCentroids(){
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(0, training_vectors.size()-1); // define the range
for(unsigned int i=0; i<codebookSize; ++i){
codebook[i] = training_vectors[distr(eng)];
}
}
// runs LBG on specified training vectors
std::vector<double> runLBG(double threshold, unsigned int max_iter, bool print_distortion = false){
// D0 = 0
unsigned int n = 0;
double distortion;
clusterAssign(clusterAssignments);
std::vector<double> d(1,0);
while(1){
n++;
moveCentroids();
clusterAssign(clusterAssignments);
distortion = calculateDistortion();
d.push_back(distortion);
if(print_distortion){
std::cout << "n: " << n << "\tdistortion: " << distortion << std::endl;
}
if(abs(d[n-1] - d[n]) < threshold || n >= max_iter){
break;
}
}
return d;
}
std::vector<std::vector<short>>& getCodebook(){
return codebook;
}
void clusterAssign(std::vector<unsigned int>& clusterAssignments){
clusterAssignments.resize(training_vectors.size());
//find closest vector
for(size_t i=0; i < training_vectors.size(); ++i){
unsigned int minCentroid = 0;
auto assign_vector = training_vectors[i];
double minDistance = ldistance(assign_vector, codebook[0]);
for(size_t centroid=1; centroid < codebookSize; ++centroid){
double distance = ldistance(assign_vector, codebook[centroid]);
if(distance < minDistance){
minDistance = distance;
minCentroid = centroid;
}
}
clusterAssignments[i] = minCentroid;
}
}
void moveCentroids(){
double assignments;
std::fill(assignmentSum.begin(), assignmentSum.end(),0);
for(size_t centroid=0; centroid < codebookSize; ++centroid){
assignments = 0;
//sum points assigned to centroid
for(size_t i=0; i < training_vectors.size(); ++i){
if(clusterAssignments[i] == centroid){
assignments++;
for(size_t idx=0; idx < blockSize; ++idx)
assignmentSum[idx] += training_vectors[i][idx];
}
}
if(assignments){
for(size_t j=0; j < blockSize; j++){
codebook[centroid][j] = assignmentSum[j] / assignments;
}
}
}
}
// default is euclidean dist
double ldistance(std::vector<short> block1, std::vector<short> block2, int p = 2){
double sum = 0;
for(size_t i = 0; i < block1.size(); ++i){
sum+=std::pow(block1[i] - block2[i], p);
}
return std::pow(sum, 1.0/p);
}
void writeCodebook(std::string codebookName){
CB_METADATA.elSize = sizeof(short);
CB_METADATA.blockSize = blockSize;
CB_METADATA.codebookSize = codebookSize;
BinaryStream ostream { codebookName, std::fstream::out };
ostream.write((char *)&CB_METADATA, sizeof(CB_METADATA));
for(unsigned int i=0; i < codebookSize; ++i){
for(unsigned int j=0; j < blockSize; ++j){
ostream.writebits(codebook[i][j], sizeof(short)*8);
}
}
}
};
#endif
| [
"[email protected]"
]
| |
3f4e29d662d79324d2e1bbb7d8d996a8fea5163c | 5aa27e95265015a51bf97d7436011d9f50c2704f | /stl/os/path/to_absolute.hpp | c8e55014872db2f9a72fd2ba693ef5088c460f43 | []
| no_license | RyanLiuF/Public | 6cc9a1c18459a2b1186c1a69435189ff160fe4c1 | c9313535188f16d94d8ac36c4dce10d1f08eb356 | refs/heads/master | 2020-04-28T19:55:36.547609 | 2019-07-02T06:29:57 | 2019-07-02T06:29:57 | 175,526,917 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | hpp | #ifndef __STL_OS_PATH_TO_ABSOLUTE_HPP__
#define __STL_OS_PATH_TO_ABSOLUTE_HPP__
#include <stl/os/path/revise.hpp>
#include <stl/os/path/current.hpp>
#include <stl/os/path/integrity.hpp>
#include <stl/os/path/truncate.hpp>
#include <stl/os/path/is_absolute.hpp>
#include <string.h>
namespace stl {
namespace os {
namespace path {
/** @ingroup path Function declaration
* @brief transform a relative path to an absolute path.
* @param[in] path a relative path
* @return the absolute path
**/
static
std::string
to_absolute(
const std::string& path)
{
if(is_absolute(path))
{
return revise(path);
}
#ifdef __os_windows__
const char* currentFolder = ".\\";
const char* preFolder = "..\\";
#else
const char* currentFolder = "./";
const char* preFolder = "../";
#endif
std::string regular = revise(path);
std::string curpath = current();
while(!regular.empty() && !curpath.empty())
{
if(::stl::stringhelper::begin_with(regular, currentFolder))
{
regular.erase(0, strlen(currentFolder));
}
else if(::stl::stringhelper::begin_with(regular, preFolder))
{
regular.erase(0, strlen(preFolder));
curpath = truncate(curpath);
}
else
{
break;
}
}
return integrity(curpath) + regular;
}
}}}
#endif //__STL_OS_PATH_TO_ABSOLUTE_HPP__ | [
"[email protected]"
]
| |
8a7c58a4c79b3573c49458ea9fd178ffc0b9972b | bf1d7c19fd2b1b2b992472cbd6500d5f35deecef | /1 Month Preparation Kit/Week 4/Day 23/Array Manipulation.cpp | e429f9cf26c1104f24812712d548233fd90d7e7f | []
| no_license | Kareem100/HackerRankProblems | 32c2ac13972a50bb3485aa7d5fcfe642323d0e0b | 2065f772a20b05439fbd5a4a4ffb03d97520865c | refs/heads/main | 2023-08-23T09:35:33.076750 | 2021-10-12T21:31:07 | 2021-10-12T21:31:07 | 404,119,546 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | cpp | /*
Problem Title: Array Manipulation
Problem URL: https://www.hackerrank.com/challenges/one-month-preparation-kit-crush/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=preparation-kits&playlist_slugs%5B%5D%5B%5D=one-month-preparation-kit&playlist_slugs%5B%5D%5B%5D=one-month-week-four
Max Score: 100
Score: 100
Language: C++
Category: One Month Preparation
*/
long arrayManipulation(int n, vector<vector<int>> queries) {
vector<long int> A(n,0);
long len = queries.size();
for(long i=0; i<len; i++)
{
A[(queries[i][0])-1] = A[(queries[i][0])-1]+queries[i][2];
if(queries[i][1]<n)
A[(queries[i][1])] = A[(queries[i][1])]-queries[i][2];
}
long sum =0,x=0;
for(long i=0; i<n; i++)
{
x = x + A[i];
if(x>sum)
sum = x;
}
return sum;
}
| [
"[email protected]"
]
| |
20dc274628c1c6ff83b8d53e5a91a01198e5e550 | 646182cc74ac8b8bdc9750c5b0afbc86ff7f7601 | /source/hash/hmac_sha384.cpp | 3fe08768c68fa3d61dc418482943dd5cd80d880c | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"MulanPSL-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | qqsskk/tinyToolkit | 04d42cfbedd1f8b8f4343de1c016ce6a5ecdb547 | 6387b8865d85cfbccac6b2acd758e497bd111a85 | refs/heads/master | 2022-12-20T12:05:40.856443 | 2020-10-21T03:18:13 | 2020-10-21T03:18:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,205 | cpp | /**
*
* 作者: hm
*
* 说明: hmac_sha384
*
*/
#include "hmac_sha384.h"
#include <cstring>
namespace tinyToolkit
{
namespace hash
{
const uint32_t HMAC_SHA384::PAD_SIZE;
const uint32_t HMAC_SHA384::DIGEST_SIZE;
/**
*
* 构造函数
*
*/
HMAC_SHA384::HMAC_SHA384()
{
Reset();
}
/**
*
* 重置
*
*/
void HMAC_SHA384::Reset()
{
_isComputed = false;
::memset(reinterpret_cast<void *>(_digest), 0, sizeof(_digest));
::memset(reinterpret_cast<void *>(&_context), 0, sizeof(_context));
_result.clear();
_result.shrink_to_fit();
Initialization(_context);
_sha384.Reset();
}
/**
*
* 设置密钥
*
* @param key 密钥
*
*/
void HMAC_SHA384::SetKey(const char * key)
{
if (key == nullptr)
{
return;
}
SetKey(key, ::strlen(key));
}
/**
*
* 设置密钥
*
* @param key 密钥
*
*/
void HMAC_SHA384::SetKey(const uint8_t * key)
{
if (key == nullptr)
{
return;
}
SetKey(key, ::strlen(reinterpret_cast<const char *>(key)));
}
/**
*
* 设置密钥
*
* @param key 密钥
*
*/
void HMAC_SHA384::SetKey(const std::string & key)
{
if (key.empty())
{
return;
}
SetKey(key, key.size());
}
/**
*
* 设置密钥
*
* @param key 密钥
* @param length 长度
*
*/
void HMAC_SHA384::SetKey(const char * key, std::size_t length)
{
if (key == nullptr || length == 0)
{
return;
}
SetKey(reinterpret_cast<const uint8_t *>(key), length);
}
/**
*
* 设置密钥
*
* @param key 密钥
* @param length 长度
*
*/
void HMAC_SHA384::SetKey(const uint8_t * key, std::size_t length)
{
if (key == nullptr || length == 0)
{
return;
}
if (length > PAD_SIZE)
{
SHA384 sha384{ };
sha384.Append(key, length);
for (uint32_t i = 0; i < PAD_SIZE; ++i)
{
_context.iPad[i] = sha384.Digest()[i] ^ 0x36;
_context.oPad[i] = sha384.Digest()[i] ^ 0x5c;
}
}
else
{
::memset(_context.iPad, 0x36, PAD_SIZE);
::memset(_context.oPad, 0x5c, PAD_SIZE);
for (std::size_t i = 0; i < length; ++i)
{
_context.iPad[i] = key[i] ^ 0x36;
_context.oPad[i] = key[i] ^ 0x5c;
}
}
Append(_context.iPad, PAD_SIZE);
}
/**
*
* 设置密钥
*
* @param key 密钥
* @param length 长度
*
*/
void HMAC_SHA384::SetKey(const std::string & key, std::size_t length)
{
if (length == 0)
{
return;
}
SetKey(key.c_str(), length);
}
/**
*
* 追加内容
*
* @param content 内容
*
*/
void HMAC_SHA384::Append(const char * content)
{
if (content == nullptr)
{
return;
}
Append(content, ::strlen(content));
}
/**
*
* 追加内容
*
* @param content 内容
*
*/
void HMAC_SHA384::Append(const uint8_t * content)
{
if (content == nullptr)
{
return;
}
Append(content, ::strlen(reinterpret_cast<const char *>(content)));
}
/**
*
* 追加内容
*
* @param content 内容
*
*/
void HMAC_SHA384::Append(const std::string & content)
{
if (content.empty())
{
return;
}
Append(content, content.size());
}
/**
*
* 追加内容
*
* @param content 内容
* @param length 长度
*
*/
void HMAC_SHA384::Append(const char * content, std::size_t length)
{
if (content == nullptr || length == 0)
{
return;
}
Append(reinterpret_cast<const uint8_t *>(content), length);
}
/**
*
* 追加内容
*
* @param content 内容
* @param length 长度
*
*/
void HMAC_SHA384::Append(const uint8_t * content, std::size_t length)
{
if (content == nullptr || length == 0)
{
return;
}
_sha384.Append(content, length);
_isComputed = false;
}
/**
*
* 追加内容
*
* @param content 内容
* @param length 长度
*
*/
void HMAC_SHA384::Append(const std::string & content, std::size_t length)
{
if (length == 0)
{
return;
}
Append(content.c_str(), length);
}
/**
*
* 摘要
*
* @return 摘要
*
*/
const uint8_t * HMAC_SHA384::Digest()
{
Generate();
return _digest;
}
/**
*
* 摘要
*
* @return 摘要
*
*/
const std::string & HMAC_SHA384::Result()
{
Generate();
return _result;
}
/**
*
* 生成
*
*/
void HMAC_SHA384::Generate()
{
if (_isComputed)
{
return;
}
_isComputed = true;
SHA384 sha384{ };
sha384.Append(_context.oPad, PAD_SIZE);
sha384.Append(_sha384.Digest(), DIGEST_SIZE);
::memcpy(_digest, sha384.Digest(), DIGEST_SIZE);
_result.clear();
_result.shrink_to_fit();
for (uint32_t i = 0; i != DIGEST_SIZE; ++i)
{
char buffer[3]{ 0 };
::snprintf(buffer, sizeof(buffer), "%02x", _digest[i]);
_result.append(buffer, 2);
}
}
/**
*
* 初始化
*
* @param context 上下文
*
*/
void HMAC_SHA384::Initialization(Context & context)
{
::memset(context.iPad, 0x36, PAD_SIZE);
::memset(context.oPad, 0x5c, PAD_SIZE);
}
}
}
| [
"[email protected]"
]
| |
1750ae77f85d3bc3790a34e01b6425decb86db1a | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/MPLSBuffers/UNIX_MPLSBuffersMain.cpp | add477fbd06418e36dfd54468810e3da423f087e | [
"MIT"
]
| permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,254 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/String.h>
#include <Pegasus/Common/PegasusVersion.h>
#include <UNIX_Common.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
using PROVIDER_LIB_NS::CIMHelper;
#include <MPLSBuffers/UNIX_MPLSBuffersProvider.h>
extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
else if (String::equalNoCase(providerName, "UNIX_MPLSBuffersProvider")) return new UNIX_MPLSBuffersProvider();
return NULL;
}
| [
"[email protected]"
]
| |
6973922fb6cbfbcf8ea4524f66ac9d3c058f255f | 86798d4b8ccaa9ac4b66b3e86f87fec62df70180 | /DS & Algo Implementation/Graph Theory/Tree depth/tree_depth.cpp | bf2b66fcdaf26f7437516d44e55e429601964b87 | []
| no_license | sakiib/competitive-programming-code-library | 03675e4c9646bd0d65f08b146310abfd4b36f1c4 | e25d7f50932fb2659bbe3673daf846eb5e7c5428 | refs/heads/master | 2022-12-04T16:11:18.307005 | 2022-12-03T14:25:49 | 2022-12-03T14:25:49 | 208,120,580 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 979 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair < int , int > ii;
typedef pair < int , ii > iii;
typedef long long int LL;
typedef unsigned long long uLL;
const int inf = (int)1e9;
const LL INF = (LL)2e18;
const int N = 100005;
const int mod = 1000000007;
const double eps = 1e-8;
const double pi = acos( -1.0 );
vector <int> graph[ N ];
int dfs( int s , int p ) {
int ret = 0;
for( auto x : graph[s] ) {
if( x == p ) continue;
ret = max( ret , dfs( x , s ) + 1 );
}
return ret;
}
int main( int argc, char const *argv[] ) {
ios_base::sync_with_stdio(0); cin.tie(0);
for( int i = 1; i <= 6; i++ ) {
int u , v;
cin >> u >> v;
graph[u].push_back( v );
graph[v].push_back( u );
}
cout << "Depth of the tree : " << dfs( 1 , 0 ) << endl;
return 0;
}
/**
depth : 4
1 2
1 3
2 4
2 5
5 6
6 7
*/
| [
"[email protected]"
]
| |
e9d80bc9c22b282afe4c9a62094fc21d02fcc2fe | 66bd3309a21fe92651fc01ba2e4c2b44b0f734b9 | /MCP3428.h | 070a6afed27188658225415d20a42360867a0d83 | []
| no_license | ControlEverythingCom/MCP3428_Particle | 40e9fbdddf47f88bac31374f86f4ef9e0a55ffd8 | 9f2969788ab2dd8ece88df2d5fcbc06c43d41e22 | refs/heads/master | 2021-01-01T04:48:27.397309 | 2017-07-14T16:07:34 | 2017-07-14T16:07:34 | 97,251,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | h | /****************************************************************************
/*
Distributed with a free-will license.
Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
MCP3428
This code is designed to work with the MCP3428_I2CADC I2C Mini Module available from ControlEverything.com.
https://www.controleverything.com/content/Analog-Digital-Converters?sku=MCP3428_I2CADC#tabs-0-product_tabset-2
*/
/****************************************************************************/
#include <spark_wiring_i2c.h>
#include <math.h>
class MCP3428
{
protected:
long raw_adc;
uint8_t SPS;
bool MODE;
uint8_t i;
uint8_t testvar;
uint8_t config;
uint8_t GAIN;
uint8_t no_of_bytes;
uint8_t data[3];
public:
uint8_t devAddr;
MCP3428(uint8_t i2cAddress);
~MCP3428();
bool testConnection(void);
void SetConfiguration(uint8_t channel, uint8_t resolution, bool mode, uint8_t PGA);
bool CheckConversion();
long readADC();
private:
};
| [
"[email protected]"
]
| |
3e6a91495372969cb6578d187b8b80871501f8c8 | 0f2b08b31fab269c77d4b14240b8746a3ba17d5e | /onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlGridSample.h | c63863853fb4e059fc608593483ccb20a2a68b95 | [
"MIT"
]
| permissive | microsoft/onnxruntime | f75aa499496f4d0a07ab68ffa589d06f83b7db1d | 5e747071be882efd6b54d7a7421042e68dcd6aff | refs/heads/main | 2023-09-04T03:14:50.888927 | 2023-09-02T07:16:28 | 2023-09-02T07:16:28 | 156,939,672 | 9,912 | 2,451 | MIT | 2023-09-14T21:22:46 | 2018-11-10T02:22:53 | C++ | UTF-8 | C++ | false | false | 36,534 | h | #pragma once
#include "../../../OperatorAuthorHelper/OperatorHelper.h"
#include "../MLOperatorAuthorImpl.h"
#include "../External/D3DX12/d3dx12.h"
#include <d3d12.h>
// NOTE: When this operator's implementation is moved into DML, the associated FP16 fallback
// should be removed from IsCustomOpShader(...) in
// onnxruntime\core\providers\dml\DmlExecutionProvider\src\ExecutionProvider.cpp
// The shader headers are produced using "GeneratedShaders/GenerateShaders.bat"
namespace GridSample_uint16_float
{
#include "GeneratedShaders/grid_sample_uint16_float.h"
}
namespace GridSample_uint_float
{
#include "GeneratedShaders/grid_sample_uint_float.h"
}
namespace GridSample_uint64_float
{
#include "GeneratedShaders/grid_sample_uint64_float.h"
}
namespace GridSample_int16_float
{
#include "GeneratedShaders/grid_sample_int16_float.h"
}
namespace GridSample_int_float
{
#include "GeneratedShaders/grid_sample_int_float.h"
}
namespace GridSample_int64_float
{
#include "GeneratedShaders/grid_sample_int64_float.h"
}
namespace GridSample_fp16_float
{
#include "GeneratedShaders/grid_sample_fp16_float.h"
}
namespace GridSample_float_float
{
#include "GeneratedShaders/grid_sample_float_float.h"
}
namespace GridSample_double_float
{
#include "GeneratedShaders/grid_sample_double_float.h"
}
namespace GridSample_bool_float
{
#include "GeneratedShaders/grid_sample_bool_float.h"
}
namespace GridSample_uint16_fp16
{
#include "GeneratedShaders/grid_sample_uint16_fp16.h"
}
namespace GridSample_uint_fp16
{
#include "GeneratedShaders/grid_sample_uint_fp16.h"
}
namespace GridSample_uint64_fp16
{
#include "GeneratedShaders/grid_sample_uint64_fp16.h"
}
namespace GridSample_int16_fp16
{
#include "GeneratedShaders/grid_sample_int16_fp16.h"
}
namespace GridSample_int_fp16
{
#include "GeneratedShaders/grid_sample_int_fp16.h"
}
namespace GridSample_int64_fp16
{
#include "GeneratedShaders/grid_sample_int64_fp16.h"
}
namespace GridSample_fp16_fp16
{
#include "GeneratedShaders/grid_sample_fp16_fp16.h"
}
namespace GridSample_float_fp16
{
#include "GeneratedShaders/grid_sample_float_fp16.h"
}
namespace GridSample_double_fp16
{
#include "GeneratedShaders/grid_sample_double_fp16.h"
}
namespace GridSample_bool_fp16
{
#include "GeneratedShaders/grid_sample_bool_fp16.h"
}
namespace GridSample_uint16_double
{
#include "GeneratedShaders/grid_sample_uint16_double.h"
}
namespace GridSample_uint_double
{
#include "GeneratedShaders/grid_sample_uint_double.h"
}
namespace GridSample_uint64_double
{
#include "GeneratedShaders/grid_sample_uint64_double.h"
}
namespace GridSample_int16_double
{
#include "GeneratedShaders/grid_sample_int16_double.h"
}
namespace GridSample_int_double
{
#include "GeneratedShaders/grid_sample_int_double.h"
}
namespace GridSample_int64_double
{
#include "GeneratedShaders/grid_sample_int64_double.h"
}
namespace GridSample_fp16_double
{
#include "GeneratedShaders/grid_sample_fp16_double.h"
}
namespace GridSample_float_double
{
#include "GeneratedShaders/grid_sample_float_double.h"
}
namespace GridSample_double_double
{
#include "GeneratedShaders/grid_sample_double_double.h"
}
namespace GridSample_bool_double
{
#include "GeneratedShaders/grid_sample_bool_double.h"
}
#include <wrl/client.h>
#include <wrl/implements.h>
#include <sstream>
using namespace Microsoft::WRL;
enum DmlGridSampleKernelInputIndex : uint32_t
{
Input,
Grid,
};
enum DmlGridSampleMode : uint32_t
{
Bilinear,
Nearest,
Bicubic,
};
enum DmlGridSamplePaddingMode : uint32_t
{
Zeros,
Border,
Reflection
};
// Helper to derive dimensions and attributes from either the GridSample shape inferrer or the GridSample kernel constructor.
struct DmlGridSampleParameters
{
uint32_t batchSize = 0;
uint32_t channelSize = 0;
uint32_t height = 0;
uint32_t width = 0;
int64_t alignCorners = 0;
DmlGridSampleMode mode = DmlGridSampleMode::Bilinear;
DmlGridSamplePaddingMode paddingMode = DmlGridSamplePaddingMode::Zeros;
DML_TENSOR_DATA_TYPE dataType = DML_TENSOR_DATA_TYPE_UNKNOWN;
DmlGridSampleParameters(){}
DmlGridSampleParameters(
const OperatorHelper::IKernelInformationAdapter& kernelInfo,
const OperatorHelper::IShapeInformationAdapter& shapeInfo)
{
auto& attributes = kernelInfo.GetAttributes();
alignCorners = attributes.GetOptionalAttribute<int64_t>(AttrName::AlignCorners, 0);
std::string str_attrib = attributes.GetOptionalAttribute<std::string>(AttrName::Mode, "bilinear");
ML_CHECK_VALID_ARGUMENT(str_attrib == "bilinear" || str_attrib == "nearest" || str_attrib == "bicubic");
if (str_attrib == "bilinear")
{
mode = DmlGridSampleMode::Bilinear;
}
else if (str_attrib == "nearest")
{
mode = DmlGridSampleMode::Nearest;
}
else if (str_attrib == "bicubic")
{
mode = DmlGridSampleMode::Bicubic;
}
str_attrib = attributes.GetOptionalAttribute<std::string>(AttrName::PaddingMode, "zeros");
ML_CHECK_VALID_ARGUMENT(str_attrib == "zeros" || str_attrib == "border" || str_attrib == "reflection");
if (str_attrib == "zeros")
{
paddingMode = DmlGridSamplePaddingMode::Zeros;
}
else if (str_attrib == "border")
{
paddingMode = DmlGridSamplePaddingMode::Border;
}
else if (str_attrib == "reflection")
{
paddingMode = DmlGridSamplePaddingMode::Reflection;
}
// input 0: signal (required; tensor)
{
// Input shape is expected to be [batch_size, channels, height, width]
// 4-D tensor of shape (N, C, H_out, W_out) of sampled values.
// For integer input types, intermediate values are computed as floating point and cast to integer at the end. uint32_t rank = shapeInfo.GetInputTensorDimensionCount(DmlGridSampleKernelInputIndex::Input);
uint32_t rank = shapeInfo.GetInputTensorDimensionCount(DmlGridSampleKernelInputIndex::Input);
ML_CHECK_VALID_ARGUMENT(rank == 4, "Input shape must be 4D.");
auto dims = shapeInfo.GetInputTensorShape(DmlGridSampleKernelInputIndex::Input);
assert(dims.size() == rank);
this->batchSize = dims[0];
this->channelSize = dims[1];
MLOperatorEdgeDescription edgeDesc = kernelInfo.GetInputEdgeDescription(DmlGridSampleKernelInputIndex::Input);
assert(edgeDesc.edgeType == MLOperatorEdgeType::Tensor);
this->dataType = Dml::GetDmlDataTypeFromMlDataType(edgeDesc.tensorDataType);
}
// input 1: grid (required; tensor)
{
// Grid shape is expected to be [batch_size, height_out, width_out, 2]
uint32_t rank = shapeInfo.GetInputTensorDimensionCount(DmlGridSampleKernelInputIndex::Grid);
ML_CHECK_VALID_ARGUMENT(rank == 4, "Input shape must be 4D.");
auto dims = shapeInfo.GetInputTensorShape(DmlGridSampleKernelInputIndex::Grid);
assert(dims.size() == rank);
this->height = dims[1];
this->width = dims[2];
}
}
};
namespace GridSampleHelpers
{
// Divides and rounds
inline uint32_t CeilDivide(uint32_t dividend, uint32_t divisor)
{
uint64_t temp = static_cast<uint64_t>(dividend) + divisor - 1;
return static_cast<uint32_t>(temp / divisor);
}
// Gets the next number of elements to dispatch to the GPU within a loop handling a large
// total number of tensor elements and threads.
void GetNextDispatchSize(
uint32_t elementCount,
uint32_t elementsPerThread,
uint32_t numThreads,
_Out_ uint32_t& dispatch,
_Out_ uint32_t& pendingElementCount
)
{
// Max threads per workgroup is 2^10 (1024). Max dispatch per dimension is 2^16. Taken together, we can dispatch a maximum of
// 2^26 (268,435,456) threads along a single dimension. This should suffice for a majority of the workload. Therefore, even
// though it is possible to dispatch up to (2^16)^3 workgroups simultaneously, we stick to the simpler 1D dispatch alternative.
assert(numThreads <= D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP);
const uint32_t maxThreadsPerDispatch = numThreads * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
const uint32_t requiredThreadCount = CeilDivide(elementCount, elementsPerThread);
// Compute max dispatchable elements
const uint32_t availableThreadCount = std::min(requiredThreadCount, maxThreadsPerDispatch);
// Compute required thread group count
uint32_t workGroupCount1D = CeilDivide(availableThreadCount, numThreads);
// Compute min dispatch size
dispatch = workGroupCount1D;
// With the dispatch size computed, compute the dispatched element count
const uint32_t dispatchedElementCount = workGroupCount1D * numThreads * elementsPerThread;
// Update the pending element count
pendingElementCount = (dispatchedElementCount < elementCount) ? elementCount - dispatchedElementCount : 0;
}
}
class DmlGridSampleOperator : public WRL::Base<IMLOperatorKernel>
{
private:
ComPtr<ID3D12Device> m_device;
ComPtr<ID3D12RootSignature> m_gridSampleRootSignature;
ComPtr<ID3D12PipelineState> m_gridSamplePipelineState;
DmlGridSampleParameters m_params = {};
// Allocate temporary buffers if needed
struct ResourceDesc
{
ComPtr<ID3D12Resource> Resource;
std::array<uint32_t, 4> Sizes;
std::array<uint32_t, 4> Strides;
};
struct GridSampleShaderConstants
{
uint32_t StartIndex;
uint32_t ElementCount;
uint32_t Mode;
uint32_t PaddingMode;
uint32_t InputSizes[4];
uint32_t InputStrides[4];
uint32_t GridSizes[4];
uint32_t GridStrides[4];
uint32_t OutputSizes[4];
uint32_t OutputStrides[4];
uint32_t AlignCorners;
};
public:
DmlGridSampleOperator(IMLOperatorKernelCreationContext* context)
{
ComPtr<IUnknown> executionObject;
context->GetExecutionInterface(executionObject.GetAddressOf());
ComPtr<ID3D12GraphicsCommandList> commandList;
executionObject.As(&commandList);
ORT_THROW_IF_FAILED(commandList->GetDevice(IID_ID3D12Device, &m_device));
MLOperatorKernelCreationContext creationContext(context);
OperatorHelper::KernelInformationAdapter kernelInfo{creationContext};
OperatorHelper::ShapeInformationAdapter shapeInfo{creationContext};
m_params = DmlGridSampleParameters(kernelInfo, shapeInfo);
MLOperatorEdgeDescription inputEdgeDesc;
ORT_THROW_IF_FAILED(context->GetInputEdgeDescription(0, &inputEdgeDesc));
assert(inputEdgeDesc.edgeType == MLOperatorEdgeType::Tensor);
MLOperatorEdgeDescription gridEdgeDesc;
ORT_THROW_IF_FAILED(context->GetInputEdgeDescription(0, &gridEdgeDesc));
assert(gridEdgeDesc.edgeType == MLOperatorEdgeType::Tensor);
PrepareGridSample(inputEdgeDesc.tensorDataType, gridEdgeDesc.tensorDataType);
}
void PrepareGridSample(MLOperatorTensorDataType inputDataType, MLOperatorTensorDataType gridDataType)
{
// Compute root signature.
const int uavCount = 3; // 3 bound UAVs: input, grid & output
std::vector<CD3DX12_ROOT_PARAMETER1> rootParameters;
rootParameters.resize(uavCount + 1);
for (uint32_t i = 0; i < uavCount; i++)
{
rootParameters[i].InitAsUnorderedAccessView(i);
}
// cbuffer Constants
// {
// uint StartIndex;
// uint ElementCount;
// uint Mode;
// uint PaddingMode;
// uint4 InputSizes;
// uint4 InputStrides;
// uint4 GridSizes;
// uint4 GridStrides;
// uint4 OutputSizes;
// uint4 OutputStrides;
// uint AlignCorners;
// };
int constantCount = 29;
rootParameters[uavCount].InitAsConstants(constantCount, 0);
CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC desc;
desc.Init_1_1(static_cast<uint32_t>(rootParameters.size()), rootParameters.data());
ComPtr<ID3DBlob> rootSignatureBlob;
ComPtr<ID3DBlob> rootSignatureErrorBlob;
ORT_THROW_IF_FAILED(D3D12SerializeVersionedRootSignature(
&desc,
rootSignatureBlob.GetAddressOf(),
rootSignatureErrorBlob.GetAddressOf()
));
ORT_THROW_IF_FAILED(m_device->CreateRootSignature(
0,
rootSignatureBlob->GetBufferPointer(),
rootSignatureBlob->GetBufferSize(),
IID_ID3D12RootSignature,
&m_gridSampleRootSignature
));
// Describe and create the compute pipeline state object (PSO).
D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
computePsoDesc.pRootSignature = m_gridSampleRootSignature.Get();
switch (gridDataType)
{
case MLOperatorTensorDataType::Float:
{
switch (inputDataType)
{
case MLOperatorTensorDataType::UInt16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint16_float::g_GridSample, sizeof(GridSample_uint16_float::g_GridSample));
break;
case MLOperatorTensorDataType::UInt32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint_float::g_GridSample, sizeof(GridSample_uint_float::g_GridSample));
break;
case MLOperatorTensorDataType::UInt64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint64_float::g_GridSample, sizeof(GridSample_uint64_float::g_GridSample));
break;
case MLOperatorTensorDataType::Int16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int16_float::g_GridSample, sizeof(GridSample_int16_float::g_GridSample));
break;
case MLOperatorTensorDataType::Int32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int_float::g_GridSample, sizeof(GridSample_int_float::g_GridSample));
break;
case MLOperatorTensorDataType::Int64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int64_float::g_GridSample, sizeof(GridSample_int64_float::g_GridSample));
break;
case MLOperatorTensorDataType::Float16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_fp16_float::g_GridSample, sizeof(GridSample_fp16_float::g_GridSample));
break;
case MLOperatorTensorDataType::Float:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_float_float::g_GridSample, sizeof(GridSample_float_float::g_GridSample));
break;
case MLOperatorTensorDataType::Double:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_double_float::g_GridSample, sizeof(GridSample_double_float::g_GridSample));
break;
case MLOperatorTensorDataType::Bool:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_bool_float::g_GridSample, sizeof(GridSample_bool_float::g_GridSample));
break;
default:
ORT_THROW_HR(E_INVALIDARG);
}
break;
}
case MLOperatorTensorDataType::Float16:
{
switch (inputDataType)
{
case MLOperatorTensorDataType::UInt16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint16_fp16::g_GridSample, sizeof(GridSample_uint16_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::UInt32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint_fp16::g_GridSample, sizeof(GridSample_uint_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::UInt64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint64_fp16::g_GridSample, sizeof(GridSample_uint64_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Int16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int16_fp16::g_GridSample, sizeof(GridSample_int16_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Int32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int_fp16::g_GridSample, sizeof(GridSample_int_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Int64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int64_fp16::g_GridSample, sizeof(GridSample_int64_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Float16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_fp16_fp16::g_GridSample, sizeof(GridSample_fp16_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Float:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_float_fp16::g_GridSample, sizeof(GridSample_float_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Double:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_double_fp16::g_GridSample, sizeof(GridSample_double_fp16::g_GridSample));
break;
case MLOperatorTensorDataType::Bool:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_bool_fp16::g_GridSample, sizeof(GridSample_bool_fp16::g_GridSample));
break;
default:
ORT_THROW_HR(E_INVALIDARG);
}
break;
}
case MLOperatorTensorDataType::Double:
{
switch (inputDataType)
{
case MLOperatorTensorDataType::UInt16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint16_double::g_GridSample, sizeof(GridSample_uint16_double::g_GridSample));
break;
case MLOperatorTensorDataType::UInt32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint_double::g_GridSample, sizeof(GridSample_uint_double::g_GridSample));
break;
case MLOperatorTensorDataType::UInt64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_uint64_double::g_GridSample, sizeof(GridSample_uint64_double::g_GridSample));
break;
case MLOperatorTensorDataType::Int16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int16_double::g_GridSample, sizeof(GridSample_int16_double::g_GridSample));
break;
case MLOperatorTensorDataType::Int32:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int_double::g_GridSample, sizeof(GridSample_int_double::g_GridSample));
break;
case MLOperatorTensorDataType::Int64:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_int64_double::g_GridSample, sizeof(GridSample_int64_double::g_GridSample));
break;
case MLOperatorTensorDataType::Float16:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_fp16_double::g_GridSample, sizeof(GridSample_fp16_double::g_GridSample));
break;
case MLOperatorTensorDataType::Float:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_float_double::g_GridSample, sizeof(GridSample_float_double::g_GridSample));
break;
case MLOperatorTensorDataType::Double:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_double_double::g_GridSample, sizeof(GridSample_double_double::g_GridSample));
break;
case MLOperatorTensorDataType::Bool:
computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(GridSample_bool_double::g_GridSample, sizeof(GridSample_bool_double::g_GridSample));
break;
default:
ORT_THROW_HR(E_INVALIDARG);
}
break;
}
default:
ORT_THROW_HR(E_INVALIDARG);
}
ORT_THROW_IF_FAILED(m_device->CreateComputePipelineState(&computePsoDesc, IID_ID3D12PipelineState, &m_gridSamplePipelineState));
}
// Computes the outputs of the kernel. This may be called multiple times
// simultaneously within the same instance of the class. Implementations
// of this method must be thread-safe.
STDMETHOD(Compute)(IMLOperatorKernelContext* context)
{
try
{
// Get the input tensor
ComPtr<IMLOperatorTensor> inputTensor;
ORT_THROW_IF_FAILED(context->GetInputTensor(0, inputTensor.GetAddressOf()));
// Get the grid tensor
ComPtr<IMLOperatorTensor> gridTensor;
ORT_THROW_IF_FAILED(context->GetInputTensor(1, gridTensor.GetAddressOf()));
// Get the output tensor
ComPtr<IMLOperatorTensor> outputTensor;
context->GetOutputTensor(0, outputTensor.GetAddressOf());
if (outputTensor->IsCpuData() || inputTensor->IsCpuData() || gridTensor->IsCpuData())
{
return E_UNEXPECTED;
}
ComPtr<IUnknown> executionObject;
ComPtr<ID3D12GraphicsCommandList> commandList;
context->GetExecutionInterface(executionObject.GetAddressOf());
executionObject.As(&commandList);
// Get the input and output shape sizes
auto inputDims = GetTensorDimensions(inputTensor.Get());
auto gridDims = GetTensorDimensions(gridTensor.Get());
auto outputDims = GetTensorDimensions(outputTensor.Get());
ComPtr<IUnknown> inputUnknown;
ComPtr<ID3D12Resource> inputResource;
inputTensor->GetDataInterface(inputUnknown.GetAddressOf());
ORT_THROW_IF_FAILED(inputUnknown.As(&inputResource));
ComPtr<IUnknown> gridUnknown;
ComPtr<ID3D12Resource> gridResource;
gridTensor->GetDataInterface(gridUnknown.GetAddressOf());
ORT_THROW_IF_FAILED(gridUnknown.As(&gridResource));
ComPtr<IUnknown> outputUnknown;
ComPtr<ID3D12Resource> outputResource;
outputTensor->GetDataInterface(outputUnknown.GetAddressOf());
ORT_THROW_IF_FAILED(outputUnknown.As(&outputResource));
return Compute(
commandList.Get(),
context,
inputResource.Get(),
inputDims,
gridResource.Get(),
gridDims,
outputResource.Get(),
outputDims
);
}
catch (...)
{
return E_FAIL;
}
return S_OK;
}
HRESULT Compute(
ID3D12GraphicsCommandList* commandList,
IMLOperatorKernelContext* context,
ID3D12Resource* inputResource,
gsl::span<const uint32_t> inputDims,
ID3D12Resource* gridResource,
gsl::span<const uint32_t> gridDims,
ID3D12Resource* outputResource,
gsl::span<const uint32_t> outputDims)
{
try
{
GridSample(
inputResource,
inputDims,
gridResource,
gridDims,
outputResource,
outputDims,
commandList);
}
catch (...)
{
return E_FAIL;
}
return S_OK;
}
void GridSample(
ID3D12Resource* inputResource,
gsl::span<const uint32_t> inputDims,
ID3D12Resource* gridResource,
gsl::span<const uint32_t> gridDims,
ID3D12Resource* outputResource,
gsl::span<const uint32_t> outputDims,
ID3D12GraphicsCommandList* commandList)
{
std::array<uint32_t, 4> inputStrides;
std::array<uint32_t, 4> gridStrides;
std::array<uint32_t, 4> outputStrides;
Dml::GetDescendingPackedStrides(inputDims, inputStrides);
Dml::GetDescendingPackedStrides(gridDims, gridStrides);
Dml::GetDescendingPackedStrides(outputDims, outputStrides);
// Transition resources from common to UAV state
D3D12_RESOURCE_BARRIER barriers[3];
barriers[0] = CD3DX12_RESOURCE_BARRIER::Transition(
inputResource,
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS
);
barriers[1] = CD3DX12_RESOURCE_BARRIER::Transition(
gridResource,
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS
);
barriers[2] = CD3DX12_RESOURCE_BARRIER::Transition(
outputResource,
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS
);
inputResource->SetName(L"InputResource");
outputResource->SetName(L"OutputResource");
gridResource->SetName(L"GridResource");
commandList->ResourceBarrier(3, barriers);
// Set the root signature and pipeline state
commandList->SetComputeRootSignature(m_gridSampleRootSignature.Get());
commandList->SetPipelineState(m_gridSamplePipelineState.Get());
// Each iteration of the below loop represents 1 level in the Stockham DFT
// Dispatch in a loop
GridSampleShaderConstants constants = {};
constants.AlignCorners = static_cast<uint32_t>(m_params.alignCorners);
constants.Mode = static_cast<uint32_t>(m_params.mode);
constants.PaddingMode = static_cast<uint32_t>(m_params.paddingMode);
std::copy(inputDims.begin(), inputDims.end(), constants.InputSizes);
std::copy(inputStrides.begin(), inputStrides.end(), constants.InputStrides);
std::copy(gridDims.begin(), gridDims.end(), constants.GridSizes);
std::copy(gridStrides.begin(), gridStrides.end(), constants.GridStrides);
std::copy(outputDims.begin(), outputDims.end(), constants.OutputSizes);
std::copy(outputStrides.begin(), outputStrides.end(), constants.OutputStrides);
constants.ElementCount = ComputeElementCountFromDimensions(constants.OutputSizes);
std::array<ID3D12Resource*, 3> uav_resources = { inputResource, gridResource, outputResource };
Dispatch(uav_resources, constants, commandList);
// Transition resources to common state
barriers[0] = CD3DX12_RESOURCE_BARRIER::Transition(
inputResource,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON
);
barriers[1] = CD3DX12_RESOURCE_BARRIER::Transition(
gridResource,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON
);
barriers[2] = CD3DX12_RESOURCE_BARRIER::Transition(
outputResource,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON
);
commandList->ResourceBarrier(3, barriers);
}
std::vector<uint32_t> GetTensorDimensions(IMLOperatorTensor* tensor)
{
auto inputDimsSize = tensor->GetDimensionCount();
auto dims = std::vector<uint32_t>(inputDimsSize);
ORT_THROW_IF_FAILED(tensor->GetShape(static_cast<uint32_t>(dims.size()), dims.data()));
return dims;
}
template <typename TConstants, uint32_t TSize>
void Dispatch(
std::array<ID3D12Resource*, TSize>& resources,
TConstants& constants,
ID3D12GraphicsCommandList* commandList)
{
D3D12_RESOURCE_BARRIER uav_barriers[TSize];
std::transform(
resources.begin(), resources.end(),
uav_barriers,
[](auto& resource) { return CD3DX12_RESOURCE_BARRIER::UAV(resource); } );
commandList->ResourceBarrier(TSize, uav_barriers);
for (uint32_t i = 0; i < TSize; i++)
{
// Set resource views
if (resources[i]) {
commandList->SetComputeRootUnorderedAccessView(
i, // root parameter index
resources[i]->GetGPUVirtualAddress()
);
}
else
{
commandList->SetComputeRootUnorderedAccessView(
i, // root parameter index
{}
);
}
}
auto pendingElementCount = constants.ElementCount;
// Dispatch up to the maximum number of threads per iteration until
// all elements are completed
while (pendingElementCount > 0)
{
constants.StartIndex = constants.ElementCount - pendingElementCount;
uint32_t dispatchSizeX;
GridSampleHelpers::GetNextDispatchSize(
pendingElementCount,
1,
64,
dispatchSizeX,
pendingElementCount
);
// Set root constants
commandList->SetComputeRoot32BitConstants(
TSize, // root parameter index
29, // Constant count
&constants,
0 // offset
);
commandList->Dispatch(dispatchSizeX, 1, 1);
}
commandList->ResourceBarrier(2, uav_barriers);
}
};
struct GridSampleShapeInferrer : public WRL::Base<IMLOperatorShapeInferrer>
{
STDMETHOD(InferOutputShapes)(IMLOperatorShapeInferenceContext* context) noexcept
{
try
{
ComPtr<IMLOperatorShapeInferenceContextPrivate> contextPrivate;
ORT_THROW_IF_FAILED(context->QueryInterface(IID_PPV_ARGS(&contextPrivate)));
MLShapeInferenceContext inferenceContext(context);
OperatorHelper::KernelInformationAdapter kernelInfo{inferenceContext};
OperatorHelper::ShapeInformationAdapter shapeInfo{inferenceContext};
DmlGridSampleParameters params(kernelInfo, shapeInfo);
std::array<uint32_t, 4> outputDims = { params.batchSize, params.channelSize, params.height, params.width };
ORT_THROW_IF_FAILED(context->SetOutputTensorShape(0, onnxruntime::narrow<uint32_t>(outputDims.size()), outputDims.data()));
}
catch (...)
{
return E_FAIL;
}
return S_OK;
}
};
class DmlGridSampleOperatorFactory : public WRL::Base<IMLOperatorKernelFactory>
{
public:
STDMETHOD(CreateKernel)(
IMLOperatorKernelCreationContext* context,
IMLOperatorKernel** kernel)
{
try
{
auto dftOperator = wil::MakeOrThrow<DmlGridSampleOperator>(context);
dftOperator.CopyTo(kernel);
return S_OK;
}
catch (...)
{
return E_FAIL;
}
}
static void RegisterGridSampleKernel(IMLOperatorRegistry* registry)
{
MLOperatorKernelDescription kernelDescription = {};
kernelDescription.domain = "";
kernelDescription.name = "GridSample";
kernelDescription.minimumOperatorSetVersion = 16;
kernelDescription.executionType = MLOperatorExecutionType::D3D12;
// T1: tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
MLOperatorEdgeTypeConstrant t1Constraint;
t1Constraint.typeLabel = "T1";
std::vector<MLOperatorEdgeDescription> t1AllowedEdges
{
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Float },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Float16 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Int8 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Int16 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Int32 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Int64 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::UInt8 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::UInt16 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::UInt32 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::UInt64 },
};
t1Constraint.allowedTypes = t1AllowedEdges.data();
t1Constraint.allowedTypeCount = static_cast<uint32_t>(t1AllowedEdges.size());
// T2 : tensor(int32), tensor(int64)
MLOperatorEdgeTypeConstrant t2Constraint;
t2Constraint.typeLabel = "T2";
std::vector<MLOperatorEdgeDescription> t2AllowedEdges
{
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Float16 },
MLOperatorEdgeDescription { MLOperatorEdgeType::Tensor, (uint64_t)MLOperatorTensorDataType::Float },
};
t2Constraint.allowedTypes = t2AllowedEdges.data();
t2Constraint.allowedTypeCount = static_cast<uint32_t>(t2AllowedEdges.size());
std::vector<MLOperatorEdgeTypeConstrant> typeConstraints{ t1Constraint, t2Constraint };
kernelDescription.typeConstraints = typeConstraints.data();
kernelDescription.typeConstraintCount = static_cast<uint32_t>(typeConstraints.size());
MLOperatorAttributeNameValue alignedCornersAttributeValue;
alignedCornersAttributeValue.name = AttrName::AlignCorners;
alignedCornersAttributeValue.type = MLOperatorAttributeType::Int;
alignedCornersAttributeValue.valueCount = 1;
static const int64_t alignedCorners[] = { 0 };
alignedCornersAttributeValue.ints = alignedCorners;
MLOperatorAttributeNameValue modeAttributeValue;
modeAttributeValue.name = AttrName::Mode;
modeAttributeValue.type = MLOperatorAttributeType::String;
modeAttributeValue.valueCount = 1;
static const char* modes[] = { "bilinear" };
modeAttributeValue.strings = modes;
MLOperatorAttributeNameValue paddingModeAttributeValue;
paddingModeAttributeValue.name = AttrName::Mode;
paddingModeAttributeValue.type = MLOperatorAttributeType::String;
paddingModeAttributeValue.valueCount = 1;
static const char* paddingModes[] = { "zeros" };
paddingModeAttributeValue.strings = paddingModes;
std::vector<MLOperatorAttributeNameValue> attributeDefaultValues{
alignedCornersAttributeValue,
modeAttributeValue,
paddingModeAttributeValue
};
kernelDescription.defaultAttributes = attributeDefaultValues.data();
kernelDescription.defaultAttributeCount = static_cast<uint32_t>(attributeDefaultValues.size());
kernelDescription.options = MLOperatorKernelOptions::None;
kernelDescription.executionOptions = 0;
auto shareInferrer = wil::MakeOrThrow<GridSampleShapeInferrer>();
auto factory = wil::MakeOrThrow<DmlGridSampleOperatorFactory>();
ComPtr<IMLOperatorRegistryPrivate> registryPrivate;
ORT_THROW_IF_FAILED(registry->QueryInterface(IID_PPV_ARGS(®istryPrivate)));
ORT_THROW_IF_FAILED(registryPrivate->RegisterOperatorKernel(
&kernelDescription,
factory.Get(),
shareInferrer.Get(),
nullptr,
false, // isInternalOperator
false, // alias
false, // supportsGraph
nullptr,
nullptr,
0));
}
};
| [
"[email protected]"
]
| |
6e53b894a8312b53e9eadbd2522e12ee3f561a91 | 6cf43021bf234f48a245724ecede839a3c3b28eb | /Hypercube2Logical.h | 525c5abe654c52fde73c7eb6af9f76091bda6178 | []
| no_license | kmrodgers/GraphTheoryProgram | 4cb3067831906cec05c897745cd9049cb5466e4c | 55086d36d906725bc13e5b8c65c573f72b7b0cc6 | refs/heads/master | 2021-01-18T14:22:38.151502 | 2014-08-11T20:37:46 | 2014-08-11T20:37:46 | 21,622,671 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 801 | h | //Hypercube2Logical.h
#ifndef GUARD_Hypercube2Logical_h
#define GUARD_Hypercube2Logical_h
#include <list>
#include <vector>
#include <string>
//#include <boolean>
class Node;
class Hypercube2Logical {
public:
Hypercube2Logical(int, int, bool, int);
virtual ~Hypercube2Logical();
void createInitialEdges();
void createInitialNodes(int);
void removeEdge();
void printVersion();
void print();
void game();
//std::vector<std::string> player1;
//std::vector<std::string> player2;
//void analysis(int);
int getRandomNumber(int);
int getRandomEdge(int);
int gameNumber;
private:
int nodeNameCount; //Keeps track of what the name of the next Node will be
int edgeWeight;
int totalGames;
bool watch;
void rotateBar();
int barCount;
std::list<Node*> nodeList;
};
#endif | [
"[email protected]"
]
| |
f69848a4cced746222625e6a322e23b7c3997536 | d042359575198fd90ff13ac68ed09d23e4a69806 | /editor/NoteEvents.h | 3c2e45aebe18c2097993af0539e1c340fdfe7d83 | [
"BSD-3-Clause"
]
| permissive | ElonSatoshi/editor | 8056ad705e12ee2b5ce9a0847de8e7cb1eeccc5b | 06d6efce856ba369db340a2d834e003fe5a99fa0 | refs/heads/master | 2021-05-07T13:56:15.958716 | 2013-09-20T07:25:11 | 2013-09-20T07:25:11 | 109,775,164 | 0 | 0 | null | 2017-11-07T02:15:38 | 2017-11-07T02:15:38 | null | UTF-8 | C++ | false | false | 4,382 | h | /* NoteEvents.h from QTau http://github.com/qtau-devgroup/editor by digited, BSD license */
#ifndef NOTEEVENTS_H
#define NOTEEVENTS_H
#include <QVector>
#include <QPoint>
#include <QSize>
#include "Events.h"
namespace ENoteEvents
{
enum {
add = 100,
resize,
move,
text,
effect
};
}
// add/remove note(s)
class qtauEvent_NoteAddition : public qtauEvent
{
public:
typedef struct {
quint64 id;
QString lyrics;
int pulseOffset;
int pulseLength;
int keyNumber;
QString toString() const { return QString("id: %1 offset: %2 length: %3 key number: %4 lyrics: %5")
.arg(id).arg(pulseOffset).arg(pulseLength).arg(keyNumber).arg(lyrics); }
} noteAddData;
typedef QVector<noteAddData> noteAddVector;
qtauEvent_NoteAddition(const noteAddVector &changeset, bool forward = true, bool deleteEvent = false) :
qtauEvent(ENoteEvents::add, forward), added(changeset), deleteInstead(deleteEvent) {}
const noteAddVector& getAdded() const { return added; }
bool isDeleteEvent() const { return deleteInstead; }
protected:
noteAddVector added;
bool deleteInstead; // if it really is a delete event, so its transformation should be reversed
qtauEvent_NoteAddition* allocCopy() const override { return new qtauEvent_NoteAddition(*this); }
};
class qtauEvent_NoteResize : public qtauEvent
{
public:
typedef struct {
quint64 id;
int offset; // offset is delta of start of note
int length;
int prevOffset;
int prevLength;
QString toString() const { return QString("id: %1 offset: %2 offset was: %3 length: %4 length was: %5")
.arg(id).arg(offset).arg(prevOffset).arg(length).arg(prevLength); }
} noteResizeData;
typedef QVector<noteResizeData> noteResizeVector;
qtauEvent_NoteResize(const noteResizeVector &changeset, bool forward = true) :
qtauEvent(ENoteEvents::resize, forward), resized(changeset) {}
const noteResizeVector& getResized() const { return resized; }
protected:
noteResizeVector resized;
qtauEvent_NoteResize* allocCopy() const override { return new qtauEvent_NoteResize(*this); }
};
class qtauEvent_NoteMove : public qtauEvent
{
public:
typedef struct {
quint64 id;
int pulseOffDelta;
int keyNumber;
int prevKeyNumber;
QString toString() const { return QString("id: %1 pulseOffDelta: %2 key number: %3 key number was: %4")
.arg(id).arg(pulseOffDelta).arg(keyNumber).arg(prevKeyNumber); }
} noteMoveData;
typedef QVector<noteMoveData> noteMoveVector;
qtauEvent_NoteMove(const noteMoveVector &changeset, bool forward = true) :
qtauEvent(ENoteEvents::move, forward), moved(changeset) {}
const noteMoveVector& getMoved() const { return moved; }
protected:
noteMoveVector moved;
qtauEvent_NoteMove* allocCopy() const override { return new qtauEvent_NoteMove(*this); }
};
class qtauEvent_NoteText : public qtauEvent
{
public:
typedef struct {
quint64 id;
QString txt;
QString prevTxt;
QString toString() const { return QString("id: %1 text: %2 text was: %3").arg(id).arg(txt).arg(prevTxt); }
} noteTextData;
typedef QVector<noteTextData> noteTextVector;
qtauEvent_NoteText(const noteTextVector &changeset, bool forward = true) :
qtauEvent(ENoteEvents::text, forward), text(changeset) {}
const noteTextVector& getText() const { return text; }
protected:
noteTextVector text;
qtauEvent_NoteText* allocCopy() const override { return new qtauEvent_NoteText(*this); }
};
class qtauEvent_NoteEffect : public qtauEvent
{
public:
typedef struct {
quint64 id;
// old data, new data
QString toString() const { return QString("id: %1").arg(id); }
} noteEffectData;
typedef QVector<noteEffectData> noteEffectVector;
qtauEvent_NoteEffect(const noteEffectVector &changeset, bool forward = true) :
qtauEvent(ENoteEvents::effect, forward), effect(changeset) {}
const noteEffectVector& getEffect() const { return effect; }
protected:
noteEffectVector effect;
qtauEvent_NoteEffect* allocCopy() const override { return new qtauEvent_NoteEffect(*this); }
};
#endif // NOTEEVENTS_H
| [
"[email protected]"
]
| |
ea81a75353e8d5b8a89dcc4849fc4b8eeb8e989b | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.cc | 245a847f3225858c7eb9413732682b95cfbbe7f3 | [
"BSD-3-Clause"
]
| permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 6,033 | cc | // 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.
#include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar/toolbar_account_icon_container_view.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/grit/generated_resources.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_view_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "url/origin.h"
LocationBarBubbleDelegateView::WebContentMouseHandler::WebContentMouseHandler(
LocationBarBubbleDelegateView* bubble,
content::WebContents* web_contents)
: bubble_(bubble), web_contents_(web_contents) {
DCHECK(bubble_);
DCHECK(web_contents_);
event_monitor_ = views::EventMonitor::CreateWindowMonitor(
this, web_contents_->GetTopLevelNativeWindow(),
{ui::ET_MOUSE_PRESSED, ui::ET_KEY_PRESSED, ui::ET_TOUCH_PRESSED});
}
LocationBarBubbleDelegateView::WebContentMouseHandler::
~WebContentMouseHandler() = default;
void LocationBarBubbleDelegateView::WebContentMouseHandler::OnEvent(
const ui::Event& event) {
if (event.IsKeyEvent() && event.AsKeyEvent()->key_code() != ui::VKEY_ESCAPE &&
!web_contents_->IsFocusedElementEditable()) {
return;
}
bubble_->CloseBubble();
}
LocationBarBubbleDelegateView::LocationBarBubbleDelegateView(
views::View* anchor_view,
content::WebContents* web_contents)
: BubbleDialogDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
WebContentsObserver(web_contents) {
// Add observer to close the bubble if the fullscreen state changes.
if (web_contents) {
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
// |browser| can be null in tests.
if (browser)
fullscreen_observer_.Add(
browser->exclusive_access_manager()->fullscreen_controller());
}
}
LocationBarBubbleDelegateView::~LocationBarBubbleDelegateView() = default;
void LocationBarBubbleDelegateView::ShowForReason(DisplayReason reason,
bool allow_refocus_alert) {
// These bubbles all anchor to the location bar or toolbar. We selectively
// anchor location bar bubbles to one end or the other of the toolbar based on
// whether their normal anchor point is visible. However, if part or all of
// the toolbar is off-screen, we should ajust the bubbles so that they are
// visible on the screen and not cut off.
//
// Note: These must be set after the bubble is created.
// Note also: |set_adjust_if_offscreen| is disabled by default on some
// platforms for arbitrary dialog bubbles to be consistent with platform
// standards, however in this case there is no good reason not to ensure the
// bubbles are displayed on-screen.
set_adjust_if_offscreen(true);
GetBubbleFrameView()->set_preferred_arrow_adjustment(
views::BubbleFrameView::PreferredArrowAdjustment::kOffset);
if (reason == USER_GESTURE) {
GetWidget()->Show();
} else {
GetWidget()->ShowInactive();
if (allow_refocus_alert) {
// Since this widget is inactive (but shown), accessibility tools won't
// alert the user to its presence. Accessibility tools such as screen
// readers work by tracking system focus. Give users of these tools a hint
// description and alert them to the presence of this widget.
GetWidget()->GetRootView()->GetViewAccessibility().OverrideDescription(
l10n_util::GetStringUTF8(IDS_SHOW_BUBBLE_INACTIVE_DESCRIPTION));
}
}
if (GetAccessibleWindowRole() == ax::mojom::Role::kAlert ||
GetAccessibleWindowRole() == ax::mojom::Role::kAlertDialog) {
GetWidget()->GetRootView()->NotifyAccessibilityEvent(
ax::mojom::Event::kAlert, true);
}
}
void LocationBarBubbleDelegateView::OnFullscreenStateChanged() {
GetWidget()->SetVisibilityAnimationTransition(views::Widget::ANIMATE_NONE);
CloseBubble();
}
void LocationBarBubbleDelegateView::OnVisibilityChanged(
content::Visibility visibility) {
if (visibility == content::Visibility::HIDDEN)
CloseBubble();
}
void LocationBarBubbleDelegateView::WebContentsDestroyed() {
CloseBubble();
}
void LocationBarBubbleDelegateView::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!close_on_main_frame_origin_navigation_ ||
!navigation_handle->IsInMainFrame() ||
!navigation_handle->HasCommitted()) {
return;
}
// Close dialog when navigating to a different domain.
if (!url::IsSameOriginWith(navigation_handle->GetPreviousURL(),
navigation_handle->GetURL())) {
CloseBubble();
}
}
gfx::Rect LocationBarBubbleDelegateView::GetAnchorBoundsInScreen() const {
gfx::Rect bounds = GetBoundsInScreen();
bounds.Inset(gfx::Insets(
GetLayoutConstant(LOCATION_BAR_BUBBLE_ANCHOR_VERTICAL_INSET), 0));
return bounds;
}
void LocationBarBubbleDelegateView::AdjustForFullscreen(
const gfx::Rect& screen_bounds) {
if (GetAnchorView())
return;
const int kBubblePaddingFromScreenEdge = 20;
int horizontal_offset = width() / 2 + kBubblePaddingFromScreenEdge;
const int x_pos = base::i18n::IsRTL()
? (screen_bounds.x() + horizontal_offset)
: (screen_bounds.right() - horizontal_offset);
SetAnchorRect(gfx::Rect(x_pos, screen_bounds.y(), 0, 0));
}
void LocationBarBubbleDelegateView::CloseBubble() {
GetWidget()->Close();
}
| [
"[email protected]"
]
| |
368fb2173b9adc485bf63102f3a3b76799e68380 | 0e844fb903a85e4193da8d4cd9d157c250996529 | /source_SpaceWireRMAPLibrary/SpaceWireAsynchronousStatus.cc | 08b183a7f9dd0ec39e29c7504a0918ee703f5c62 | []
| no_license | lzgjxh/SpaceWireRMAPLibrary | 0e3c87a72e911a7f957a22389a08d0b341fb2559 | 5b4340afb608b1be9c14f684587536f5a260d6f9 | refs/heads/master | 2021-01-18T11:41:09.729691 | 2011-08-04T03:25:28 | 2011-08-04T03:25:28 | 2,561,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | cc | #include "SpaceWireAsynchronousStatus.hh"
using namespace std;
int SpaceWireAsynchronousStatus::CurrentAsynchronousProcessID;
map<int,bool> SpaceWireAsynchronousStatus::processIDMap;
SpaceWireAsynchronousStatus::SpaceWireAsynchronousStatus(){
asynchronousOperationID=SpaceWireAsynchronousStatus::DefaultAsynchronousProcessID;
}
SpaceWireAsynchronousStatus::~SpaceWireAsynchronousStatus(){}
int SpaceWireAsynchronousStatus::getID(){
return asynchronousOperationID;
}
void SpaceWireAsynchronousStatus::setLinkStatus(SpaceWireLinkStatus newlinkstatus){
linkstatus=newlinkstatus;
}
SpaceWireLinkStatus SpaceWireAsynchronousStatus::getLinkStatus(){
return linkstatus;
}
void SpaceWireAsynchronousStatus::waitCompletion() throw(SpaceWireException){
SpaceWireException e(SpaceWireException::NotImplemented);
throw e;
}
int SpaceWireAsynchronousStatus::newAsynchronousProcessID(){
/**
*
*/
if(CurrentAsynchronousProcessID==MaximumAsynchronousProcessID){
CurrentAsynchronousProcessID=MinimumAsynchronousProcessID;
}else{
CurrentAsynchronousProcessID++;
}
return CurrentAsynchronousProcessID;
/**
*
*/
}
void SpaceWireAsynchronousStatus::clearAsynchronousProcessID(int id){
/**
*
*/
}
| [
"[email protected]"
]
| |
2b7e9e248e961338f6536685337c466fbad29feb | 9021b7b0848aaee250df43f597dd25b6853b0262 | /src/feature_provider_test.cc | 4935a75ac2f25c11554a2b66767f56189428c61b | []
| no_license | weimingtom/TensorFlow_MIMXRT1064-EVK_Microspeech | 92b772f4c4e6402072b0a81061958d421e4d11e2 | fba0626c8e37587471bd41e3755f46a81d9f5215 | refs/heads/master | 2022-12-28T02:31:54.591455 | 2020-10-08T08:39:02 | 2020-10-08T08:39:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,619 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "feature_provider.h"
#include "tensorflow/lite/c/common.h"
#include "micro_features/micro_model_settings.h"
#include "micro_features/no_micro_features_data.h"
#include "micro_features/yes_micro_features_data.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/testing/micro_test.h"
TF_LITE_MICRO_TESTS_BEGIN
TF_LITE_MICRO_TEST(TestFeatureProviderMockYes) {
tflite::MicroErrorReporter micro_error_reporter;
tflite::ErrorReporter* error_reporter = µ_error_reporter;
uint8_t feature_data[kFeatureElementCount];
FeatureProvider feature_provider(kFeatureElementCount, feature_data);
int how_many_new_slices = 0;
TfLiteStatus populate_status = feature_provider.PopulateFeatureData(
error_reporter, /* last_time_in_ms= */ 0, /* time_in_ms= */ 970,
&how_many_new_slices);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, populate_status);
TF_LITE_MICRO_EXPECT_EQ(kFeatureSliceCount, how_many_new_slices);
for (int i = 0; i < kFeatureElementCount; ++i) {
TF_LITE_MICRO_EXPECT_EQ(g_yes_micro_f2e59fea_nohash_1_data[i],
feature_data[i]);
}
}
TF_LITE_MICRO_TEST(TestFeatureProviderMockNo) {
tflite::MicroErrorReporter micro_error_reporter;
tflite::ErrorReporter* error_reporter = µ_error_reporter;
uint8_t feature_data[kFeatureElementCount];
FeatureProvider feature_provider(kFeatureElementCount, feature_data);
int how_many_new_slices = 0;
TfLiteStatus populate_status = feature_provider.PopulateFeatureData(
error_reporter, /* last_time_in_ms= */ 4000, /* time_in_ms= */ 4970,
&how_many_new_slices);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, populate_status);
TF_LITE_MICRO_EXPECT_EQ(kFeatureSliceCount, how_many_new_slices);
for (int i = 0; i < kFeatureElementCount; ++i) {
TF_LITE_MICRO_EXPECT_EQ(g_no_micro_f9643d42_nohash_4_data[i],
feature_data[i]);
}
}
TF_LITE_MICRO_TESTS_END
| [
"[email protected]"
]
| |
d980abdfd78ed437f75aa2752f7d5469a016df61 | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Tools/Character_NET/TReActionAnimationInfo.cpp | de1935e32390f480466e285fc78642f476f6fb18 | []
| no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 483 | cpp | #include "stdafx.h"
#include "TReActionAnimationInfo.h"
#include "MXml.h"
TReActionAnimationInfo::TReActionAnimationInfo()
: XReActionAnimationInfo()
{
}
TReActionAnimationInfo::~TReActionAnimationInfo()
{
}
void TReActionAnimationInfo::DelReActionAnimationInfo( string strBaseAni )
{
map<tstring, ReAction_DATA>::iterator itFind = m_mapReActionAnimationList.find(strBaseAni);
if(itFind != m_mapReActionAnimationList.end())
{
m_mapReActionAnimationList.erase(itFind);
}
}
| [
"[email protected]"
]
| |
cd489852e45825700811bca5e2325e9f83c21e55 | 0987d5b2682302fddc151711091e8540014c9558 | /SymbolPatterns/patterns_04.cpp | c0bc0cf55d00131fa8c0fcd24c8e2f9f4b08196e | []
| no_license | vivek-gurjar/Basic-Cpp-Programs | 0cad65c6f5888af1549fd18117e76d65f973d907 | c545d1732f5ba80c2aae2dd34d52aa86a4edf93d | refs/heads/main | 2023-04-08T04:58:45.099541 | 2021-04-17T10:55:13 | 2021-04-17T10:55:13 | 358,602,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | #include<iostream>
using namespace std;
int main()
{
int i,j,num;
cout<<" Enter te number --> ";
cin>>num;
for(i=1; i<=num; i++)
{
for(j=num; j>=i; j--)
{
cout<<" "<<"*";
}
cout<<endl;\
}
} | [
"[email protected]"
]
| |
1b3ed1fb7ccded31cf7019fcd776a845a749d8c5 | 4fd19a2d5ef199e932454ee21c84e6e0d4981284 | /libcot/automate/actions/CActionDCEngine.h | e09158b37fa8220d34fca10e80f2a7fd6690bb04 | []
| no_license | benoitk/COT | bce8dcb066bacd5e2356566918ba65d190054a04 | af9ddcc672322a13b69ebb30eb5b372562927f7b | refs/heads/master | 2021-01-17T10:21:14.613281 | 2017-01-16T16:10:50 | 2017-01-16T16:10:50 | 30,191,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | h | #ifndef CACTIONDCENGINE_H
#define CACTIONDCENGINE_H
#include "IAction.h"
class IVariable;
class QTimer;
class CActionDCEngine : public IAction
{
Q_OBJECT
public:
CActionDCEngine(const QVariantMap&, CAutomate *parent);
~CActionDCEngine();
bool runAction(ICycle* arg_stepParent) Q_DECL_OVERRIDE;
QList<IVariable*> getListParameters()const Q_DECL_OVERRIDE;
actionType getType()const Q_DECL_OVERRIDE;
bool variableUsed(IVariable *)const Q_DECL_OVERRIDE;
QMap<QString, IVariable*> getMapIVariableParameters() Q_DECL_OVERRIDE;
QMap<QString, IVariable*> getMapCstParameters() Q_DECL_OVERRIDE;
void setParameter(const QString& arg_key, IVariable* arg_parameter)Q_DECL_OVERRIDE;
void abortAction() Q_DECL_OVERRIDE;
enumVariableType getWaitedType(const QString& arg_key) Q_DECL_OVERRIDE;
QVariantMap serialize() Q_DECL_OVERRIDE;
public slots:
void slotTimeout();
private:
QMap<QThread* ,QTimer*> m_mapTimer;
IVariable* m_varPump;
IVariable* m_varClockwise;
IVariable* m_varTimeout;
};
#endif // CACTIONDCENGINE_H
| [
"[email protected]"
]
| |
7b93c5c234693f50ba6847135f2f4417b9e56b5f | 4d657ab78b904f3103ff9f8dc2bd5c137fb0973a | /cses/apartments.cpp | a9f3a01b3c43a94f093b42094d057c19b9a00133 | []
| no_license | durgeshak19/Cpp_DS_Algos | 8b5eddcdea0d552f50f72fc4295bd632c4de6d61 | 42e5071b110e82a6cbda0ab08813daaf51119af2 | refs/heads/main | 2023-09-05T04:52:08.131393 | 2021-11-22T08:49:32 | 2021-11-22T08:49:32 | 367,378,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ll n ,m ,k;
cin>>n>>m>>k;
ll a[n];
ll b[m];
for(ll i=0;i<n;i++){
cin>>a[i];
}
for(ll i=0;i<m;i++){
cin>>b[i];
}
sort(a ,a+n);
sort(b , b+m);
//if the apartmenet has been alloted dont allot it again
//binary search from 1 next to the last value
//find lower bound for max efficieny
//if bs cant find move on to next element;
//keep count
ll i=0, j=0 , count = 0;
while( i<n && j<m){
if(abs(a[i] - b[j]) <=k){
++i,++j;
++count;
}
else{
if(a[i] - b[j] > k){
++j;
}
else{
++i;
}
}
}
cout<<count;
} | [
"[email protected]"
]
| |
ef6cdce03f7b5ee68b1e41d5dd81750dfd7b5a16 | 98b2966e73074b24da191411cb1d19b21dcb2296 | /source/editor/elements/mesh_renderer.h | 2b2911081f370721e69215be24ccba78c2bd5fce | []
| no_license | mad-s/ruffles-editor | 7ac152b50ccea2790ea6bd57b70840a75e8b1417 | 89ac9d345f426da8c9b0edaf53d80d2e651ccb93 | refs/heads/main | 2023-04-18T16:12:54.410490 | 2021-05-11T20:06:40 | 2021-05-11T20:06:40 | 328,366,688 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 686 | h | #pragma once
#include "editor/elements/abstract_element.h"
#include "model/mesh_model.h"
using namespace ruffles::model;
namespace ruffles::editor {
class MeshRenderer : public AbstractElement
{
public:
MeshRenderer(igl::opengl::glfw::Viewer& viewer, Menu& menu) : AbstractElement(viewer, menu) {};
virtual void update_view(igl::opengl::glfw::Viewer& viewer) override;
virtual void update_menu(Menu& menu) override;
void add_mesh(Mesh& mesh);
private:
Mesh* mesh = NULL;
int view_index = -1;
bool pending_add_mesh = false;
bool show_fill;
float color_menu[3];
Eigen::Vector3d fill;
void add_mesh_to_view(igl::opengl::glfw::Viewer& viewer);
bool is_valid();
};
} | [
"[email protected]"
]
| |
1e0895f1ddfc6a29b361cbde8b2c7794cfe9ad3c | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/api/rtp_receiver_interface.cc | bc9aef5aef79b279dbb96f563a1ac78841210a88 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 1,253 | cc | /*
* Copyright 2018 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/rtp_receiver_interface.h"
namespace webrtc {
std::vector<std::string> RtpReceiverInterface::stream_ids() const {
return {};
}
std::vector<rtc::scoped_refptr<MediaStreamInterface>>
RtpReceiverInterface::streams() const {
return {};
}
std::vector<RtpSource> RtpReceiverInterface::GetSources() const {
return {};
}
void RtpReceiverInterface::SetFrameDecryptor(
rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor) {}
rtc::scoped_refptr<FrameDecryptorInterface>
RtpReceiverInterface::GetFrameDecryptor() const {
return nullptr;
}
rtc::scoped_refptr<DtlsTransportInterface>
RtpReceiverInterface::dtls_transport() const {
return nullptr;
}
void RtpReceiverInterface::SetDepacketizerToDecoderFrameTransformer(
rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) {}
} // namespace webrtc
| [
"[email protected]"
]
| |
2f5c0090c22afcbf4244d910e398c637a15216c3 | b7e97047616d9343be5b9bbe03fc0d79ba5a6143 | /src/protocols/simple_moves/ConstraintSetMover.fwd.hh | 467d9d61b78172a122e228dd626206959176463a | []
| no_license | achitturi/ROSETTA-main-source | 2772623a78e33e7883a453f051d53ea6cc53ffa5 | fe11c7e7cb68644f404f4c0629b64da4bb73b8f9 | refs/heads/master | 2021-05-09T15:04:34.006421 | 2018-01-26T17:10:33 | 2018-01-26T17:10:33 | 119,081,547 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,030 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
/// @file
/// @brief
/// @author ashworth
#ifndef INCLUDED_protocols_simple_moves_ConstraintSetMover_fwd_hh
#define INCLUDED_protocols_simple_moves_ConstraintSetMover_fwd_hh
#include <utility/pointer/owning_ptr.hh>
namespace protocols {
namespace simple_moves {
class ConstraintSetMover;
typedef utility::pointer::shared_ptr< ConstraintSetMover > ConstraintSetMoverOP;
typedef utility::pointer::shared_ptr< ConstraintSetMover const > ConstraintSetMoverCOP;
} // moves
} // protocols
#endif
| [
"[email protected]"
]
| |
4fe6c3c12c7342f74f8c65d36395f3e1e5a3c026 | 7b3d4dff3945584460dc474a8bb8fe8fd9bdb625 | /exercises/4/seminar/14/SoftwareCompany/Person.cpp | 3335ee0c4732c17ec9042381ad270a0fa61cba47 | [
"MIT"
]
| permissive | triffon/oop-2019-20 | 305535b006cb19e96c9c58d47737a28135fc666e | ec3e5488859d8140de5aa5090811cd0e1318d952 | refs/heads/master | 2022-05-13T07:04:22.306200 | 2022-03-19T09:49:17 | 2022-03-19T09:49:45 | 241,474,762 | 21 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | #include "Person.h"
Person::Person(string firstName, string lastName, int age): firstName(firstName), lastName(lastName), age(age) {}
void Person::write(ostream& out) const {
out << firstName << " " << lastName << " " << age << endl;
}
int Person::getAge() const {
return age;
}
ostream& operator<<(ostream& out, Person& p) {
p.write(out);
return out;
}
| [
"[email protected]"
]
| |
886b5fbe2fad914bd30cf2bd001827b0c3198187 | d3c8ab61646f67dfa0a3d6974637bc7bc6d530b7 | /ExCircunferencia-Sequencial.cpp | aa41dc2ced0de8af355cb50d7551318db9d7538a | []
| no_license | joaopioner1/Exercise_Cpp | cf14d4409c10ff78f917b64b06edff957e8a43e1 | a7ddb6baba33a73a5071ceec2fb3f919765f6f3c | refs/heads/master | 2022-12-23T00:10:51.385870 | 2020-09-28T20:30:03 | 2020-09-28T20:30:03 | 285,738,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | #include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main()
{
double r, area, diam, comp;
cout << "Insira o raio da circunferencia: ";
cin >> r;
area = 3.14 * pow(r,2);
diam = r * 2;
comp = 2 * 3.14 * r;
cout << fixed << setprecision(2);
cout << "Area = " << area << endl;
cout << "Diametro = " << diam << endl;
cout << "Comprimento = " << comp << endl;
return 0;
}
| [
"[email protected]"
]
| |
651b206bd8256aee102e57f3a35bcc19b3a3d5be | a07d1ae886800fe3758203683d6067089322b78c | /src/armnn/layers/FloorLayer.cpp | 34ad7f628e9803cf0ba1fa67d9e7b5165cf8e656 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | oubotong/arm-secure-nn-1 | 7a896f15e20636493a485b5a8ea71081bb8af12a | a92eba03be9a4df62f21d2494869e74b44de3364 | refs/heads/master | 2023-03-17T17:22:54.972293 | 2020-04-14T14:36:58 | 2020-04-14T14:36:58 | 557,095,350 | 1 | 0 | MIT | 2022-10-25T04:11:50 | 2022-10-25T04:11:49 | null | UTF-8 | C++ | false | false | 1,338 | cpp | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "FloorLayer.hpp"
#include "LayerCloneBase.hpp"
#include <armnn/TypesUtils.hpp>
#include <backendsCommon/WorkloadData.hpp>
#include <backendsCommon/WorkloadFactory.hpp>
namespace armnn
{
FloorLayer::FloorLayer(const char* name)
: Layer(1, 1, LayerType::Floor, name)
{
}
std::unique_ptr<IWorkload> FloorLayer::CreateWorkload(const Graph& graph,
const IWorkloadFactory& factory) const
{
FloorQueueDescriptor descriptor;
return factory.CreateFloor(descriptor, PrepInfoAndDesc(descriptor, graph));
}
FloorLayer* FloorLayer::Clone(Graph& graph) const
{
return CloneBase<FloorLayer>(graph, GetName());
}
void FloorLayer::ValidateTensorShapesFromInputs()
{
VerifyLayerConnections(1, CHECK_LOCATION());
auto inferredShapes = InferOutputShapes({ GetInputSlot(0).GetConnection()->GetTensorInfo().GetShape() });
BOOST_ASSERT(inferredShapes.size() == 1);
ConditionalThrowIfNotEqual<LayerValidationException>(
"FloorLayer: TensorShape set on OutputSlot[0] does not match the inferred shape.",
GetOutputSlot(0).GetTensorInfo().GetShape(),
inferredShapes[0]);
}
void FloorLayer::Accept(ILayerVisitor& visitor) const
{
visitor.VisitFloorLayer(this, GetName());
}
} // namespace armnn
| [
"[email protected]"
]
| |
e02b8aba88c7592b196e80b46f74821290d31060 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/dawn/src/dawn/wire/server/ServerInstance.cpp | 435760437553a46e279bdc7b7d15c5f42132c74a | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 3,492 | cpp | // Copyright 2021 The Dawn Authors
//
// 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 <algorithm>
#include <vector>
#include "dawn/wire/SupportedFeatures.h"
#include "dawn/wire/server/Server.h"
namespace dawn::wire::server {
bool Server::DoInstanceRequestAdapter(ObjectId instanceId,
uint64_t requestSerial,
ObjectHandle adapterHandle,
const WGPURequestAdapterOptions* options) {
auto* instance = InstanceObjects().Get(instanceId);
if (instance == nullptr) {
return false;
}
auto* resultData = AdapterObjects().Allocate(adapterHandle, AllocationState::Reserved);
if (resultData == nullptr) {
return false;
}
resultData->generation = adapterHandle.generation;
auto userdata = MakeUserdata<RequestAdapterUserdata>();
userdata->instance = ObjectHandle{instanceId, instance->generation};
userdata->requestSerial = requestSerial;
userdata->adapterObjectId = adapterHandle.id;
mProcs.instanceRequestAdapter(instance->handle, options,
ForwardToServer<&Server::OnRequestAdapterCallback>,
userdata.release());
return true;
}
void Server::OnRequestAdapterCallback(RequestAdapterUserdata* data,
WGPURequestAdapterStatus status,
WGPUAdapter adapter,
const char* message) {
ReturnInstanceRequestAdapterCallbackCmd cmd = {};
cmd.instance = data->instance;
cmd.requestSerial = data->requestSerial;
cmd.status = status;
cmd.message = message;
if (status != WGPURequestAdapterStatus_Success) {
// Free the ObjectId which will make it unusable.
AdapterObjects().Free(data->adapterObjectId);
ASSERT(adapter == nullptr);
SerializeCommand(cmd);
return;
}
WGPUAdapterProperties properties = {};
WGPUSupportedLimits limits = {};
std::vector<WGPUFeatureName> features;
// Assign the handle and allocated status if the adapter is created successfully.
auto* adapterObject = AdapterObjects().FillReservation(data->adapterObjectId, adapter);
ASSERT(adapterObject != nullptr);
size_t featuresCount = mProcs.adapterEnumerateFeatures(adapter, nullptr);
features.resize(featuresCount);
mProcs.adapterEnumerateFeatures(adapter, features.data());
// Hide features the wire cannot support.
auto it = std::partition(features.begin(), features.end(), IsFeatureSupported);
cmd.featuresCount = static_cast<uint32_t>(std::distance(features.begin(), it));
cmd.features = features.data();
mProcs.adapterGetProperties(adapter, &properties);
mProcs.adapterGetLimits(adapter, &limits);
cmd.properties = &properties;
cmd.limits = &limits;
SerializeCommand(cmd);
}
} // namespace dawn::wire::server
| [
"[email protected]"
]
| |
3fd6182de7c0c3fb610b9037f1e37dcd1a6d85e0 | f4edee6fec9d9c6c1f8b17917c6442a3a9dfe050 | /selectiontopk.cpp | 1b416ca26fc27376297087367c947d6cefc89f14 | []
| no_license | parmeshmalhotra/Mytest | e4279a6e3f11ed1a2145e105f22469998fa78f24 | 3a0103766d66dcc9dc3b192611ed5415d814361d | refs/heads/master | 2016-09-10T00:09:45.999612 | 2015-07-05T13:32:14 | 2015-07-05T13:32:14 | 38,210,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | #include<iostream>
#include<vector>
using namespace std;
void swap( int &a,int &b)
{
int c=a;
a=b;
b=c;
}
void selection(vector<int> &a,int k)
{
int min;
for (int i=0;i<k;i++)
{
min=i;
for (int j=i+1;j<a.size();j++)
{
if (a[min]>a[j])
{
min=j;
}
}
swap(a[i],a[min]);
}
for (int i=0;i<k;i++)
{
cout<<a[i]<<"\n";
}
}
void display(vector<int> a,int k)
{
for (int i=0;i<a.size();i++)
{
cout<<a[i]<<"\n";
}
}
int main()
{
vector<int> a={4,5,6,3,1,2,8};
int k=3;
selection(a,k);
//display(a,k);
}
| [
"[email protected]"
]
| |
a2cf1a8b4854c63b42e99f2c56fec6f6f37c0086 | 2dbcd410940b00f38813c9cb8bdf95a781612485 | /Skelton/main.cpp | c3546d0c4234d893d3a2d21aba28ec28963d489d | [
"CC0-1.0"
]
| permissive | Tomohiro-nagi/FirstSkelton | 3145d418f3066c8eaae19cde74176247569f5fe5 | de6cba9b9e65ee2ed8355d6cac8bde05d328d1aa | refs/heads/main | 2023-04-19T16:47:07.747630 | 2021-05-25T03:57:37 | 2021-05-25T03:57:37 | 370,555,100 | 0 | 0 | CC0-1.0 | 2021-05-25T03:57:38 | 2021-05-25T03:41:33 | null | WINDOWS-1252 | C++ | false | false | 365 | cpp | #include <DxLib.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
SetWindowText(L"2016003_ˆî–Ø’q‘å");
DxLib::ChangeWindowMode(true);
DxLib_Init();
DxLib::SetDrawScreen(DX_SCREEN_BACK);
while (DxLib::ProcessMessage() == 0) {
ClearDrawScreen();
DrawString(100, 100, L"hello wold", 0xffffff);
ScreenFlip();
}
DxLib_End();
return 0;
}
| [
"[email protected]"
]
| |
0e8d5bbae842e9a7ab35f3f939f3cff4ced462a6 | db6d5226ad3d8d213e06d59d3998a4ce2e9030bd | /src/qt/platformstyle.h | 7154565764dec40e29f88809c3f0d682ba7d6416 | [
"MIT"
]
| permissive | Schilling99/SchillingCoin | 9536c00d1bd8eef55482a398f3b5f12429938cb2 | c9d7c4f70341e7ab552131e7e4a018197bc8558a | refs/heads/master | 2022-12-26T14:58:40.917535 | 2020-10-08T12:33:38 | 2020-10-08T12:33:38 | 302,329,522 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | h | // Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2016-2019 The PIVX developers
// Copyright (c) 2018-2020 The SchillingCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_PLATFORMSTYLE_H
#define BITCOIN_QT_PLATFORMSTYLE_H
#include <QIcon>
#include <QPixmap>
#include <QString>
/* Coin network-specific GUI style information */
class PlatformStyle
{
public:
/** Get style associated with provided platform name, or 0 if not known */
static const PlatformStyle* instantiate(const QString& platformId);
const QString& getName() const { return name; }
bool getImagesOnButtons() const { return imagesOnButtons; }
bool getUseExtraSpacing() const { return useExtraSpacing; }
QColor TextColor() const { return textColor; }
QColor SingleColor() const { return singleColor; }
/** Colorize an image (given filename) with the icon color */
QImage SingleColorImage(const QString& filename) const;
/** Colorize an icon (given filename) with the icon color */
QIcon SingleColorIcon(const QString& filename) const;
/** Colorize an icon (given object) with the icon color */
QIcon SingleColorIcon(const QIcon& icon) const;
/** Colorize an icon (given filename) with the text color */
QIcon TextColorIcon(const QString& filename) const;
/** Colorize an icon (given object) with the text color */
QIcon TextColorIcon(const QIcon& icon) const;
private:
PlatformStyle(const QString& name, bool imagesOnButtons, bool colorizeIcons, bool useExtraSpacing);
QString name;
bool imagesOnButtons;
bool colorizeIcons;
bool useExtraSpacing;
QColor singleColor;
QColor textColor;
/* ... more to come later */
};
#endif // BITCOIN_QT_PLATFORMSTYLE_H
| [
"[email protected]"
]
| |
df5211e931bc45ebe3503178b551aa890c7fbcf3 | a8c518b75d5785780a9f54ef743c941fdd15c098 | /src/leveldb/helpers/memenv/memenv.h | 579eb1dffe6be6e6e9d12220ef20a6bacf05d132 | [
"BSD-3-Clause",
"MIT"
]
| permissive | booog35/GiveCoin | 9450b8c953fa1ee62b1a17ce61a29ad5d8c5edf2 | 644c086e62c3835847c821d5b1f100cffe6105b0 | refs/heads/master | 2021-04-26T23:11:45.169815 | 2018-03-17T22:37:33 | 2018-03-17T22:37:33 | 123,876,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef STORAGE_LEVELDB_HELPERS_MEMENV_MEMENV_H_
#define STORAGE_LEVELDB_HELPERS_MEMENV_MEMENV_H_
namespace leveldb {
class Env;
// Returns a new environment that stores its data in memory and delegates
// all non-file-storage tasks to base_env. The caller must delete the result
// when it is no longer needed.
// *base_env must remain live while the result is in use.
Env *NewMemEnv(Env *base_env);
} // namespace leveldb
#endif // STORAGE_LEVELDB_HELPERS_MEMENV_MEMENV_H_
| [
"[email protected]"
]
| |
b234c48e567456bf4e2136a9b0b43f04a1b44b87 | ab80f5be71af88204119348b47c6caf80553818c | /Algorithms/DynamicProgramming/Candies.cpp | 7525a63abf07449062e733596523464c586868f1 | []
| no_license | MananVyas24/HackerRankSolutions | acdaa896b0307d3b79fd37d6e3e0223033fc4473 | 36e7f36ba56eb12bc25e7bee2b5288f7e528da2b | refs/heads/master | 2021-01-21T14:32:53.354283 | 2016-06-21T21:21:17 | 2016-06-21T21:21:17 | 58,163,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,465 | cpp | /**
Alice is a kindergarden teacher. She wants to give some candies to the children in her class.
All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class.
Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies.
Alice wants to save money, so she needs to minimize the total number of candies given to the children.
Input Format
The first line of the input is an integer N, the number of children in Alice's class.
Each of the following N lines contains an integer that indicates the rating of each child.
1 <= N <= 105
1 <= ratingi <= 105
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input
3
1
2
2
Sample Output
4
Explanation
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies.
Hence optimal distribution will be 1, 2, 1.
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/** ---------
Ref :http://stackoverflow.com/questions/3437404/min-and-max-in-c
--------- **/
# define MAX(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
int numberOfCandies(vector<int>&scores, int N)
{
int numberOfCandies = 0;
//int N = scores.size();
//Give One candy to all
vector<int>leftNeighbours = vector<int>(N,1);
vector<int>rightNeighbours = vector<int>(N,1);
// If scores agjacent to current student has more score then give 1+ candy more
for(int i=1; i<N; i++)
{
if(scores[i-1]<scores[i])
leftNeighbours[i] = leftNeighbours[i-1] + 1;
}
for(int i=N-2; i>=1; i--)
{
if(scores[i+1]<scores[i])
rightNeighbours[i] = rightNeighbours[i+1] + 1;
}
// Total candies distributed
for(int i=0; i<N; i++)
numberOfCandies += MAX(leftNeighbours[i],rightNeighbours[i]);
return numberOfCandies;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> scores;
int marks;
int N;
cin>>N;
for(int i=0; i<N; i++)
{
cin>>marks;
scores.push_back(marks);
}
cout<<(numberOfCandies(scores,N))<<endl;
return 0;
} | [
"[email protected]"
]
| |
fc94fb186683ec948e865ac6dc431f17d745643d | d7eb6d7d0fa6d9afc54fa2edb8e42ff174ebca80 | /main.cpp | 0c685124ef0a0fa56c0b87dda588a2fce1ed7a98 | [
"MIT"
]
| permissive | ailihong/keras2tensorflow | d9b53601bbf7e501b92a44bcc89979fd9abbbd91 | 26b1074b938ce4621f31c3b4c1dfb38765d6f17f | refs/heads/master | 2020-05-21T08:36:00.386914 | 2019-10-14T06:05:27 | 2019-10-14T06:05:27 | 185,985,226 | 0 | 0 | MIT | 2019-05-10T12:33:01 | 2019-05-10T12:33:01 | null | UTF-8 | C++ | false | false | 15,744 | cpp | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A minimal but useful C++ example showing how to load an Imagenet-style object
// recognition TensorFlow model, prepare input images for it, run them through
// the graph, and interpret the results.
//
// It's designed to have as few dependencies and be as clear as possible, so
// it's more verbose than it could be in production code. In particular, using
// auto for the types of a lot of the returned values from TensorFlow calls can
// remove a lot of boilerplate, but I find the explicit types useful in sample
// code to make it simple to look up the classes involved.
//
// To use it, compile and then run in a working directory with the
// learning/brain/tutorials/label_image/data/ folder below it, and you should
// see the top five labels for the example Lena image output. You can then
// customize it to use your own models or images by changing the file names at
// the top of the main() function.
//
// The googlenet_graph.pb file included by default is created from Inception.
//
// Note that, for GIF inputs, to reuse existing code, only single-frame ones
// are supported.
#include <fstream>
#include <utility>
#include <vector>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
// These are all common classes it's handy to reference with no namespace.
using tensorflow::Flag;
using tensorflow::Tensor;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::int32;
// Takes a file name, and loads a list of labels from it, one per line, and
// returns a vector of the strings. It pads with empty strings so the length
// of the result is a multiple of 16, because our model expects that.
Status ReadLabelsFile(const string& file_name, std::vector<string>* result,
size_t* found_label_count) {
std::ifstream file(file_name);
if (!file) {
return tensorflow::errors::NotFound("Labels file ", file_name,
" not found.");
}
result->clear();
string line;
while (std::getline(file, line)) {
result->push_back(line);
}
*found_label_count = result->size();
const int padding = 16;
while (result->size() % padding) {
result->emplace_back();
}
return Status::OK();
}
static Status ReadEntireFile(tensorflow::Env* env, const string& filename,
Tensor* output) {
tensorflow::uint64 file_size = 0;
TF_RETURN_IF_ERROR(env->GetFileSize(filename, &file_size));
string contents;
contents.resize(file_size);
std::unique_ptr<tensorflow::RandomAccessFile> file;
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename, &file));
tensorflow::StringPiece data;
TF_RETURN_IF_ERROR(file->Read(0, file_size, &data, &(contents)[0]));
if (data.size() != file_size) {
return tensorflow::errors::DataLoss("Truncated read of '", filename,
"' expected ", file_size, " got ",
data.size());
}
output->scalar<string>()() = data.ToString();
return Status::OK();
}
// Given an image file name, read in the data, try to decode it as an image,
// resize it to the requested size, and then scale the values as desired.
Status ReadTensorFromImageFile(const string& file_name, const int input_height,
const int input_width, const float input_mean,
const float input_std,
std::vector<Tensor>* out_tensors) {
auto root = tensorflow::Scope::NewRootScope();
using namespace ::tensorflow::ops; // NOLINT(build/namespaces)
string input_name = "file_reader";
string output_name = "normalized";
// read file_name into a tensor named input
Tensor input(tensorflow::DT_STRING, tensorflow::TensorShape());
TF_RETURN_IF_ERROR(
ReadEntireFile(tensorflow::Env::Default(), file_name, &input));
// use a placeholder to read input data
auto file_reader =
Placeholder(root.WithOpName("input"), tensorflow::DataType::DT_STRING);
std::vector<std::pair<string, tensorflow::Tensor>> inputs = {
{"input", input},
};
// Now try to figure out what kind of file it is and decode it.
const int wanted_channels = 3;
tensorflow::Output image_reader;
if (tensorflow::str_util::EndsWith(file_name, ".png")) {
image_reader = DecodePng(root.WithOpName("png_reader"), file_reader,
DecodePng::Channels(wanted_channels));
} else if (tensorflow::str_util::EndsWith(file_name,".gif")) {
// gif decoder returns 4-D tensor, remove the first dim
image_reader =
Squeeze(root.WithOpName("squeeze_first_dim"),
DecodeGif(root.WithOpName("gif_reader"), file_reader));
} /*else if (tensorflow::StringPiece(file_name).ends_with(".bmp")) {
image_reader = DecodeBmp(root.WithOpName("bmp_reader"), file_reader);
}*/ else {
// Assume if it's neither a PNG nor a GIF then it must be a JPEG.
image_reader = DecodeJpeg(root.WithOpName("jpeg_reader"), file_reader,
DecodeJpeg::Channels(wanted_channels));
}
// Now cast the image data to float so we can do normal math on it.
auto float_caster =
Cast(root.WithOpName("float_caster"), image_reader, tensorflow::DT_FLOAT);
// The convention for image ops in TensorFlow is that all images are expected
// to be in batches, so that they're four-dimensional arrays with indices of
// [batch, height, width, channel]. Because we only have a single image, we
// have to add a batch dimension of 1 to the start with ExpandDims().
auto dims_expander = ExpandDims(root, float_caster, 0);
// Bilinearly resize the image to fit the required dimensions.
auto resized = ResizeBilinear(
root, dims_expander,
Const(root.WithOpName("size"), {input_height, input_width}));
// Subtract the mean and divide by the scale.
Div(root.WithOpName(output_name), Sub(root, resized, {input_mean}),
{input_std});
// This runs the GraphDef network definition that we've just constructed, and
// returns the results in the output tensor.
tensorflow::GraphDef graph;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graph));
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graph));
TF_RETURN_IF_ERROR(session->Run({inputs}, {output_name}, {}, out_tensors));
return Status::OK();
}
// Reads a model graph definition from disk, and creates a session object you
// can use to run it.
Status LoadGraph(const string& graph_file_name,
std::unique_ptr<tensorflow::Session>* session) {
tensorflow::GraphDef graph_def;
Status load_graph_status =
ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def);
if (!load_graph_status.ok()) {
return tensorflow::errors::NotFound("Failed to load compute graph at '",
graph_file_name, "'");
}
session->reset(tensorflow::NewSession(tensorflow::SessionOptions()));
Status session_create_status = (*session)->Create(graph_def);
if (!session_create_status.ok()) {
return session_create_status;
}
return Status::OK();
}
// Analyzes the output of the Inception graph to retrieve the highest scores and
// their positions in the tensor, which correspond to categories.
Status GetTopLabels(const std::vector<Tensor>& outputs, int how_many_labels,
Tensor* indices, Tensor* scores) {
auto root = tensorflow::Scope::NewRootScope();
using namespace ::tensorflow::ops; // NOLINT(build/namespaces)
string output_name = "top_k";
TopK(root.WithOpName(output_name), outputs[0], how_many_labels);
// This runs the GraphDef network definition that we've just constructed, and
// returns the results in the output tensors.
tensorflow::GraphDef graph;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graph));
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graph));
// The TopK node returns two outputs, the scores and their original indices,
// so we have to append :0 and :1 to specify them both.
std::vector<Tensor> out_tensors;
TF_RETURN_IF_ERROR(session->Run({}, {output_name + ":0", output_name + ":1"},
{}, &out_tensors));
*scores = out_tensors[0];
*indices = out_tensors[1];
return Status::OK();
}
// Given the output of a model run, and the name of a file containing the labels
// this prints out the top five highest-scoring values.
Status PrintTopLabels(const std::vector<Tensor>& outputs,
const string& labels_file_name) {
std::vector<string> labels;
size_t label_count;
Status read_labels_status =
ReadLabelsFile(labels_file_name, &labels, &label_count);
if (!read_labels_status.ok()) {
LOG(ERROR) << read_labels_status;
return read_labels_status;
}
const int how_many_labels = std::min(5, static_cast<int>(label_count));
Tensor indices;
Tensor scores;
TF_RETURN_IF_ERROR(GetTopLabels(outputs, how_many_labels, &indices, &scores));
tensorflow::TTypes<float>::Flat scores_flat = scores.flat<float>();
tensorflow::TTypes<int32>::Flat indices_flat = indices.flat<int32>();
for (int pos = 0; pos < how_many_labels; ++pos) {
const int label_index = indices_flat(pos);
const float score = scores_flat(pos);
LOG(INFO) << labels[label_index] << " (" << label_index << "): " << score;
}
return Status::OK();
}
// This is a testing function that returns whether the top label index is the
// one that's expected.
Status CheckTopLabel(const std::vector<Tensor>& outputs, int expected,
bool* is_expected) {
*is_expected = false;
Tensor indices;
Tensor scores;
const int how_many_labels = 1;
TF_RETURN_IF_ERROR(GetTopLabels(outputs, how_many_labels, &indices, &scores));
tensorflow::TTypes<int32>::Flat indices_flat = indices.flat<int32>();
if (indices_flat(0) != expected) {
LOG(ERROR) << "Expected label #" << expected << " but got #"
<< indices_flat(0);
*is_expected = false;
} else {
*is_expected = true;
}
return Status::OK();
}
int main(int argc, char* argv[]) {
// These are the command-line flags the program can understand.
// They define where the graph and input data is located, and what kind of
// input the model expects. If you train your own model, or use something
// other than inception_v3, then you'll need to update these.
string image = "tensorflow/examples/label_image/data/grace_hopper.jpg";
string graph =
"tensorflow/examples/label_image/data/inception_v3_2016_08_28_frozen.pb";
string labels =
"tensorflow/examples/label_image/data/imagenet_slim_labels.txt";
int32 input_width = 299;
int32 input_height = 299;
float input_mean = 0;
float input_std = 255;
string input_layer = "input";
string output_layer = "InceptionV3/Predictions/Reshape_1";
bool self_test = false;
string root_dir = "";
std::vector<Flag> flag_list = {
Flag("image", &image, "image to be processed"),
Flag("graph", &graph, "graph to be executed"),
Flag("labels", &labels, "name of file containing labels"),
Flag("input_width", &input_width, "resize image to this width in pixels"),
Flag("input_height", &input_height,
"resize image to this height in pixels"),
//Flag("input_mean", &input_mean, "scale pixel values to this mean"),
//Flag("input_std", &input_std, "scale pixel values to this std deviation"),
Flag("input_layer", &input_layer, "name of input layer"),
Flag("output_layer", &output_layer, "name of output layer"),
Flag("self_test", &self_test, "run a self test"),
Flag("root_dir", &root_dir,
"interpret image and graph file names relative to this directory"),
};
string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
// We need to call this to set up global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
// First we load and initialize the model.
std::unique_ptr<tensorflow::Session> session;
string graph_path = tensorflow::io::JoinPath(root_dir, graph);
Status load_graph_status = LoadGraph(graph_path, &session);
if (!load_graph_status.ok()) {
LOG(ERROR) << load_graph_status;
return -1;
}
// Get the image from disk as a float array of numbers, resized and normalized
// to the specifications the main graph expects.
std::vector<Tensor> resized_tensors;
string image_path = tensorflow::io::JoinPath(root_dir, image);
Status read_tensor_status =
ReadTensorFromImageFile(image_path, input_height, input_width, input_mean,
input_std, &resized_tensors);
if (!read_tensor_status.ok()) {
LOG(ERROR) << read_tensor_status;
return -1;
}
const Tensor& resized_tensor = resized_tensors[0];
// Actually run the image through the model.
std::vector<Tensor> outputs;
Status run_status = session->Run({{input_layer, resized_tensor}},
{output_layer}, {}, &outputs);
if (!run_status.ok()) {
LOG(ERROR) << "Running model failed: " << run_status;
return -1;
}
// This is for automated testing to make sure we get the expected result with
// the default settings. We know that label 653 (military uniform) should be
// the top label for the Admiral Hopper image.
if (self_test) {
bool expected_matches;
Status check_status = CheckTopLabel(outputs, 653, &expected_matches);
if (!check_status.ok()) {
LOG(ERROR) << "Running check failed: " << check_status;
return -1;
}
if (!expected_matches) {
LOG(ERROR) << "Self-test failed!";
return -1;
}
}
// Do something interesting with the results we've generated.
Status print_status = PrintTopLabels(outputs, labels);
if (!print_status.ok()) {
LOG(ERROR) << "Running print failed: " << print_status;
return -1;
}
return 0;
}
| [
"[email protected]"
]
| |
2bdbd4ec53b224f31143499886014bbd1e519795 | a997f6b37a217cf40542fd8a8aebb4e7936593b8 | /Old Versions/LEDtest.ino | f296e05fa665f2e7c18bd3e818948ee0da54b2e4 | []
| no_license | 388298347/rotierendelitfassaeule | a2044e082c1c2084eeecdd757e114bbd5c23ce64 | 67e352e3c7ec2a8bce29481a5bb798d6c0cdf4d3 | refs/heads/master | 2021-01-18T20:38:01.109557 | 2017-04-02T11:14:12 | 2017-04-02T11:14:12 | 86,979,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | ino | int delay = 10;
int[] list = [13,2,3,4,5,6,7,8,9,10,11,12];
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
for (int i = 0; i < list.length; i ++)
{
pinMode(list[i], OUTPUT); //pin can output to control LEDs
}
}
// the loop function runs over and over again forever
void loop() {
for (int i = 0; i < list.length; i ++)
{
digitalWrite(list[i], HIGH); //LED on
delay(delay);
digitalWrite(list[i], LOW); //LED off
delay(delay);
}
}
| [
"[email protected]"
]
| |
55a0efd241ff9569f77e526c8ee561a50aaee57e | 6753dba9d4b225770f5e641cf38c2998f19d2f73 | /Source/Core/Platform/LSPlatformFwd.h | 8491f48eced93e8271174995a7561040c919f728 | []
| no_license | iTShun/Vision | b9ea51033a97518b5befd4b98f1f3d376a55d10c | 2ed766060c52736e9386ff249f3a18c0b698d81a | refs/heads/master | 2020-03-24T06:22:06.426801 | 2019-01-18T13:30:39 | 2019-01-18T13:30:39 | 142,525,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,758 | h | #pragma once
namespace ls
{
/** @addtogroup Math
* @{
*/
/** Values that represent in which order are euler angles applied when used in transformations. */
enum class EulerAngleOrder
{
XYZ,
XZY,
YXZ,
YZX,
ZXY,
ZYX
};
/** Enum used for object construction specifying the object should be zero initialized. */
enum LS_ZERO { LSZero };
/** Enum used for matrix/quaternion constructor specifying it should be initialized with an identity value. */
enum LS_IDENTITY { LSIdentity };
/** @} */
}
namespace ls
{
// Rtti
class IReflectable;
class RTTITypeBase;
struct RTTIField;
// Serialization
struct SerializationContext;
struct SerializedInstance;
struct SerializedObject;
// FileSystem
class DataStream;
class Path;
// Math
class AABox;
class Bounds;
class Capsule;
class Color;
class Degree;
class Math;
class Matrix3;
class Matrix4;
class Plane;
class Quaternion;
class Radian;
class Ray;
class Rect2;
class Rect2I;
class Rect3;
class Sphere;
class Vector2;
struct Vector2I;
class Vector3;
class Vector4;
enum TypeID_Utility
{
TID_Abstract = 50, // Special type ID used for Abstract classes. Only type ID that may be used by more than one class.
TID_WString = 51,
TID_Path = 52,
TID_Vector = 53,
TID_Map = 54,
TID_UnorderedMap = 55,
TID_Pair = 56,
TID_Set = 57,
TID_StringID = 58,
TID_SerializedInstance = 59,
TID_SerializedField = 60,
TID_SerializedObject = 61,
TID_SerializedArray = 62,
TID_SerializedEntry = 63,
TID_SerializedArrayEntry = 64,
TID_SerializedSubObject = 65,
TID_UnorderedSet = 66,
TID_SerializedDataBlock = 67,
TID_Flags = 68,
TID_IReflectable = 69,
TID_DataBlob = 70,
TID_ColorGradient = 71,
TID_SerializationContext = 72
};
}
| [
"[email protected]"
]
| |
7b1325fe673c2875b9c8b23b41adc0b25d44a4c4 | 95404f610ee5d35c996f9df0f4658c3246d26086 | /DynamicState.cpp | 0572b557e5fe044285a3d84391bfb8953f795e0c | []
| no_license | raysloks/Project3 | e43121bab671055555a57dfe5251ddf785d633a8 | be039ebaa49839f9b70e23cd77337344389c41f7 | refs/heads/master | 2023-05-25T18:45:44.042874 | 2023-04-28T22:47:31 | 2023-04-28T22:47:31 | 230,270,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #include "DynamicState.h"
bool DynamicState::operator==(const DynamicState& rhs) const
{
return !(*this != rhs);
}
bool DynamicState::operator!=(const DynamicState& rhs) const
{
if (scissor.offset.x != rhs.scissor.offset.x)
return true;
if (scissor.offset.y != rhs.scissor.offset.y)
return true;
if (scissor.extent.width != rhs.scissor.extent.width)
return true;
if (scissor.extent.height != rhs.scissor.extent.height)
return true;
return false;
}
| [
"[email protected]"
]
| |
c08cccededb1445544ecab5c9f701a330724cd54 | 410e45283cf691f932b07c5fdf18d8d8ac9b57c3 | /third_party/blink/renderer/core/layout/geometry/physical_offset_test.cc | df53d1742f820c9eedba1b0a11f8e8c52c82aa63 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
]
| permissive | yanhuashengdian/chrome_browser | f52a7f533a6b8417e19b85f765f43ea63307a1fb | 972d284a9ffa4b794f659f5acc4116087704394c | refs/heads/master | 2022-12-21T03:43:07.108853 | 2019-04-29T14:20:05 | 2019-04-29T14:20:05 | 184,068,841 | 0 | 2 | BSD-3-Clause | 2022-12-17T17:35:55 | 2019-04-29T12:40:27 | null | UTF-8 | C++ | false | false | 3,053 | cc | // Copyright 2017 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 "third_party/blink/renderer/core/layout/geometry/physical_offset.h"
#include "third_party/blink/renderer/core/layout/geometry/logical_offset.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_size.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
namespace {
TEST(GeometryUnitsTest, ConvertPhysicalOffsetToLogicalOffset) {
PhysicalOffset physical_offset(LayoutUnit(20), LayoutUnit(30));
PhysicalSize outer_size(LayoutUnit(300), LayoutUnit(400));
PhysicalSize inner_size(LayoutUnit(5), LayoutUnit(65));
LogicalOffset offset;
offset = physical_offset.ConvertToLogical(
WritingMode::kHorizontalTb, TextDirection::kLtr, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(20), offset.inline_offset);
EXPECT_EQ(LayoutUnit(30), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kHorizontalTb, TextDirection::kRtl, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(275), offset.inline_offset);
EXPECT_EQ(LayoutUnit(30), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kVerticalRl, TextDirection::kLtr, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(30), offset.inline_offset);
EXPECT_EQ(LayoutUnit(275), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kVerticalRl, TextDirection::kRtl, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(305), offset.inline_offset);
EXPECT_EQ(LayoutUnit(275), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kSidewaysRl, TextDirection::kLtr, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(30), offset.inline_offset);
EXPECT_EQ(LayoutUnit(275), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kSidewaysRl, TextDirection::kRtl, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(305), offset.inline_offset);
EXPECT_EQ(LayoutUnit(275), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kVerticalLr, TextDirection::kLtr, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(30), offset.inline_offset);
EXPECT_EQ(LayoutUnit(20), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kVerticalLr, TextDirection::kRtl, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(305), offset.inline_offset);
EXPECT_EQ(LayoutUnit(20), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kSidewaysLr, TextDirection::kLtr, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(305), offset.inline_offset);
EXPECT_EQ(LayoutUnit(20), offset.block_offset);
offset = physical_offset.ConvertToLogical(
WritingMode::kSidewaysLr, TextDirection::kRtl, outer_size, inner_size);
EXPECT_EQ(LayoutUnit(30), offset.inline_offset);
EXPECT_EQ(LayoutUnit(20), offset.block_offset);
}
} // namespace
} // namespace blink
| [
"[email protected]"
]
| |
eb44a4dcb980074234e1c43df9e837c66b828fbc | b1b734ab75a6fe114733d3c0b8ca5046d54b407d | /third_party/ComputeLibrary/examples/graph_alexnet.cpp | 8705c8ed1e3688ef76d24413c5f9ff426bbe15ee | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"Apache-2.0"
]
| permissive | waybarrios/video_nonlocal_net_caffe2 | 754fea2b96318d677144f16faadf59cb6b00189b | b19c2ac3ddc1836d90d7d0fccb60d710c017253e | refs/heads/master | 2020-04-20T03:15:12.286080 | 2019-01-31T20:44:01 | 2019-01-31T20:44:01 | 168,593,110 | 0 | 0 | Apache-2.0 | 2019-01-31T20:40:40 | 2019-01-31T20:40:39 | null | UTF-8 | C++ | false | false | 8,257 | cpp | /*
* Copyright (c) 2017, 2018 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/graph/Graph.h"
#include "arm_compute/graph/Nodes.h"
#include "support/ToolchainSupport.h"
#include "utils/GraphUtils.h"
#include "utils/Utils.h"
#include <cstdlib>
#include <iostream>
#include <memory>
using namespace arm_compute::utils;
using namespace arm_compute::graph;
using namespace arm_compute::graph_utils;
/** Example demonstrating how to implement AlexNet's network using the Compute Library's graph API
*
* @param[in] argc Number of arguments
* @param[in] argv Arguments ( [optional] Target (0 = NEON, 1 = OpenCL), [optional] Path to the weights folder, [optional] image, [optional] labels )
*/
class GraphAlexnetExample : public Example
{
public:
void do_setup(int argc, char **argv) override
{
std::string data_path; /* Path to the trainable data */
std::string image; /* Image data */
std::string label; /* Label data */
constexpr float mean_r = 122.68f; /* Mean value to subtract from red channel */
constexpr float mean_g = 116.67f; /* Mean value to subtract from green channel */
constexpr float mean_b = 104.01f; /* Mean value to subtract from blue channel */
// Set target. 0 (NEON), 1 (OpenCL). By default it is NEON
TargetHint target_hint = set_target_hint(argc > 1 ? std::strtol(argv[1], nullptr, 10) : 0);
ConvolutionMethodHint convolution_hint = target_hint == TargetHint::NEON ? ConvolutionMethodHint::GEMM : ConvolutionMethodHint::DIRECT;
// Parse arguments
if(argc < 2)
{
// Print help
std::cout << "Usage: " << argv[0] << " [target] [path_to_data] [image] [labels]\n\n";
std::cout << "No data folder provided: using random values\n\n";
}
else if(argc == 2)
{
std::cout << "Usage: " << argv[0] << " " << argv[1] << " [path_to_data] [image] [labels]\n\n";
std::cout << "No data folder provided: using random values\n\n";
}
else if(argc == 3)
{
data_path = argv[2];
std::cout << "Usage: " << argv[0] << " " << argv[1] << " " << argv[2] << " [image] [labels]\n\n";
std::cout << "No image provided: using random values\n\n";
}
else if(argc == 4)
{
data_path = argv[2];
image = argv[3];
std::cout << "Usage: " << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << " [labels]\n\n";
std::cout << "No text file with labels provided: skipping output accessor\n\n";
}
else
{
data_path = argv[2];
image = argv[3];
label = argv[4];
}
graph << target_hint
<< Tensor(TensorInfo(TensorShape(227U, 227U, 3U, 1U), 1, DataType::F32),
get_input_accessor(image, mean_r, mean_g, mean_b))
// Layer 1
<< ConvolutionLayer(
11U, 11U, 96U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv1_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv1_b.npy"),
PadStrideInfo(4, 4, 0, 0))
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
<< NormalizationLayer(NormalizationLayerInfo(NormType::CROSS_MAP, 5, 0.0001f, 0.75f))
<< PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, PadStrideInfo(2, 2, 0, 0)))
// Layer 2
<< convolution_hint
<< ConvolutionLayer(
5U, 5U, 256U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv2_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv2_b.npy"),
PadStrideInfo(1, 1, 2, 2), 2)
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
<< NormalizationLayer(NormalizationLayerInfo(NormType::CROSS_MAP, 5, 0.0001f, 0.75f))
<< PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, PadStrideInfo(2, 2, 0, 0)))
// Layer 3
<< ConvolutionLayer(
3U, 3U, 384U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv3_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv3_b.npy"),
PadStrideInfo(1, 1, 1, 1))
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
// Layer 4
<< ConvolutionLayer(
3U, 3U, 384U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv4_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv4_b.npy"),
PadStrideInfo(1, 1, 1, 1), 2)
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
// Layer 5
<< ConvolutionLayer(
3U, 3U, 256U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv5_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/conv5_b.npy"),
PadStrideInfo(1, 1, 1, 1), 2)
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
<< PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, PadStrideInfo(2, 2, 0, 0)))
// Layer 6
<< FullyConnectedLayer(
4096U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc6_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc6_b.npy"))
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
// Layer 7
<< FullyConnectedLayer(
4096U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc7_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc7_b.npy"))
<< ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU))
// Layer 8
<< FullyConnectedLayer(
1000U,
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc8_w.npy"),
get_weights_accessor(data_path, "/cnn_data/alexnet_model/fc8_b.npy"))
// Softmax
<< SoftmaxLayer()
<< Tensor(get_output_accessor(label, 5));
}
void do_run() override
{
// Run graph
graph.run();
}
private:
Graph graph{};
};
/** Main program for AlexNet
*
* @param[in] argc Number of arguments
* @param[in] argv Arguments ( [optional] Target (0 = NEON, 1 = OpenCL), [optional] Path to the weights folder, [optional] image, [optional] labels )
*/
int main(int argc, char **argv)
{
return arm_compute::utils::run_example<GraphAlexnetExample>(argc, argv);
}
| [
"[email protected]"
]
| |
e0f394cdcb1fc29f8478bd8851db4c7399c72ec4 | bc84ffab49351bed0cd4edaf4f55be2ef8fe8da5 | /MultiplyStrings/MultiplyStrings/main.cpp | 0a27034898967d4fcd74ecf93447533407e8e8c1 | []
| no_license | jjhartmann/strident-octo-weasel | 8b81682d621e48a0e9725fc1586e507a3a80baf1 | d7489b5362547a8b913e459db0254a9de7c5eca8 | refs/heads/master | 2020-04-12T02:31:17.091513 | 2018-02-21T20:21:47 | 2018-02-21T20:21:47 | 45,711,022 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,572 | cpp | //////////////////////////////////////////////////////////////////////
// Multiply Strings
// Given two numbers represented as strings, return multiplication of the numbers as a string.
// Note: The numbers can be arbitrarily large and are non - negative.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
// Struct to represent disembodied numer
struct NumberD
{
int val;
int exp;
};
int countInteger(int x)
{
int sz = sizeof(int) * 8;
int c = 0;
for (int i = 0; i < sz; ++i)
{
if ((x & (1 << i)) > 0)
{
c = i;
}
}
return c;
}
string addStrings(string a, string b)
{
int alen = a.length();
int blen = b.length();
int ad = 0;
int bd = 0;
int maxlen = max(alen, blen);
if (maxlen != alen){
ad = blen - alen;
}
else {
bd = alen - blen;
}
string res = "";
int carry = 0;
for (int i = maxlen - 1; i >= 0; --i)
{
char ac = ((i - ad) >= 0) ? a[i - ad] : '0';
char bc = ((i - bd) >= 0) ? b[i - bd] : '0';
int ai = atoi(&ac);
int bi = atoi(&bc);
int sum = ai + bi + carry;
int lsb = (sum % 10);
carry = static_cast<int>(floor(sum/10)) % 10;
res = to_string(lsb) + res;
}
if (carry > 0)
{
res = to_string(carry) + res;
}
return res;
}
// Build vector
void buildNumVec(string str, vector<NumberD> &vec)
{
int slen = str.length();
int i = max(slen - 4, 0);
int exp = 0;
int len = 4;
while (len > 0)
{
NumberD num;
string valstr = str.substr(i, len);
int val = atoi(valstr.c_str());
num.val = val;
num.exp = exp;
vec.push_back(num);
if (i - 4 < 0) {
len = i;
i = 0;
}
else {
i -= 4;
}
exp += 4;
}
}
// Multiple Vectors
vector<NumberD> multipleVector(vector<NumberD> &avec, vector<NumberD> &bvec)
{
vector<NumberD> res;
int asize = avec.size();
int bsize = bvec.size();
for (int i = 0; i < asize; ++i)
{
for (int j = 0; j < bsize; ++j)
{
NumberD temp;
temp.val = avec[i].val * bvec[j].val;
temp.exp = avec[i].exp + bvec[j].exp;
res.push_back(temp);
}
}
return res;
}
// Convert to string
vector<string> convertVecToString(vector<NumberD> vec)
{
vector<string> res;
for (int i = 0; i < vec.size(); ++i)
{
string temp = to_string(vec[i].val);
for (int j = 0; j < vec[i].exp; ++j)
{
temp += "0";
}
res.push_back(temp);
}
return res;
}
// Multiply Two Strings
string multiplyString(string a, string b)
{
int alen = a.length();
int blen = b.length();
vector<NumberD> avec;
vector<NumberD> bvec;
buildNumVec(a, avec);
buildNumVec(b, bvec);
// Multiply components and merge.
vector<NumberD> resvec = multipleVector(avec, bvec);
// Convert resvect to strings
vector<string> resStr = convertVecToString(resvec);
// Add Strings together
string product = "0";
for (int i = 0; i < resStr.size(); ++i)
{
product = addStrings(resStr[i], product);
}
return product;
}
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0")
return "0";
int alen = num1.length();
int blen = num2.length();
vector<NumberD> avec;
vector<NumberD> bvec;
buildNumVec(num1, avec);
buildNumVec(num2, bvec);
// Multiply components and merge.
vector<NumberD> resvec = multipleVector(avec, bvec);
// Convert resvect to strings
vector<string> resStr = convertVecToString(resvec);
// Add Strings together
string product = "0";
for (int i = 0; i < resStr.size(); ++i)
{
product = addStrings(resStr[i], product);
}
return product;
}
};
int main()
{
cout << "Multiply Strings" << endl;
int res = countInteger(123456789);
Solution sol;
string sum = addStrings("92258441254412541111221122211443", "99855566658477412554412155444188");
string test = sol.multiply("9212518930487213973668059034619153835677898283391567122521443284", "9212518930487213973668059034619153835677898283391567122521443284");
return 0;
} | [
"[email protected]"
]
| |
9c9ccb3f34af223d9b9dc588a52582fd331cec71 | 44870348e567857d98327441dd85a16836e7a42d | /waveprint.cpp | 9e8f561dd55110a9dec7f60c00de82691ce3fc67 | []
| no_license | talhaarshad7/Learning-CPP | de50c1790d67e3f85fcc7129c9324fdc291a251a | 839f67f534ca4930bd20932f89ed63489279ce88 | refs/heads/main | 2023-07-27T01:22:13.618758 | 2021-09-09T16:17:26 | 2021-09-09T16:17:26 | 404,790,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | #include<iostream>
using namespace std;
int main()
{
int t,m,n;
int a[1000][1000];
cin>>t;
while(t>0)
{
t--;
cin>>m>>n;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
for(int i=0;i<n;i++)
{
if(i%2==0)
{
for(int j=0;j<m;j++)
cout<<a[j][i];
}
else
{
for(int j=m-1;j>=0;j--)
cout<<a[j][i];
}
}
}
} | [
"[email protected]"
]
| |
7ba5f85b264e87fa6672e5b116420a90055f31c0 | 4b27033174f3f27e2efc107b80af4cab349f2b9b | /opi_emac_osc_dmx/firmware/main.cpp | 88eca5d316dc0c7e20ce770e582d79f5578b4650 | []
| no_license | Adco28k/rpidmx512 | aeed26049217f29172615ed5ceeccae8ab21b531 | fe9278265603807b453237ed294a4cc8709ed039 | refs/heads/master | 2022-07-19T22:18:32.157884 | 2020-05-28T19:07:40 | 2020-05-28T19:07:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,228 | cpp | /**
* @file main.cpp
*
*/
/* Copyright (C) 2019-2020 by Arjan van Vught mailto:[email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include "hardware.h"
#include "networkh3emac.h"
#include "ledblink.h"
#include "display.h"
#include "networkconst.h"
#include "mdns.h"
#include "mdnsservices.h"
#include "oscserver.h"
#include "oscserverparms.h"
#include "oscservermsgconst.h"
// DMX Out
#include "dmxparams.h"
#include "dmxsend.h"
#include "storedmxsend.h"
#include "spiflashinstall.h"
#include "spiflashstore.h"
#include "storeoscserver.h"
#include "remoteconfig.h"
#include "remoteconfigparams.h"
#include "storeremoteconfig.h"
#include "firmwareversion.h"
#include "software_version.h"
#include "displayhandler.h"
extern "C" {
void notmain(void) {
Hardware hw;
NetworkH3emac nw;
LedBlink lb;
Display display(DisplayType::SSD1306);
FirmwareVersion fw(SOFTWARE_VERSION, __DATE__, __TIME__);
SpiFlashInstall spiFlashInstall;
SpiFlashStore spiFlashStore;
StoreOscServer storeOscServer;
StoreDmxSend storeDmxSend;
OSCServerParams params(&storeOscServer);
OscServer server;
if (params.Load()) {
params.Dump();
params.Set(&server);
}
fw.Print();
hw.SetLed(HARDWARE_LED_ON);
lb.SetLedBlinkDisplay(new DisplayHandler);
display.TextStatus(NetworkConst::MSG_NETWORK_INIT, DISPLAY_7SEGMENT_MSG_INFO_NETWORK_INIT, CONSOLE_YELLOW);
nw.Init(spiFlashStore.GetStoreNetwork());
nw.SetNetworkStore(spiFlashStore.GetStoreNetwork());
nw.Print();
MDNS mDns;
mDns.Start();
mDns.AddServiceRecord(0, MDNS_SERVICE_CONFIG, 0x2905);
mDns.AddServiceRecord(0, MDNS_SERVICE_OSC, server.GetPortIncoming(), "type=server");
mDns.Print();
display.TextStatus(OscServerMsgConst::PARAMS, DISPLAY_7SEGMENT_MSG_INFO_BRIDGE_PARMAMS, CONSOLE_YELLOW);
DMXSend dmx;
DMXParams dmxparams(&storeDmxSend);
if (dmxparams.Load()) {
dmxparams.Dump();
dmxparams.Set(&dmx);
}
server.SetOutput(&dmx);
server.Print();
dmx.Print();
RemoteConfig remoteConfig(REMOTE_CONFIG_OSC, REMOTE_CONFIG_MODE_DMX, 1);
StoreRemoteConfig storeRemoteConfig;
RemoteConfigParams remoteConfigParams(&storeRemoteConfig);
if(remoteConfigParams.Load()) {
remoteConfigParams.Set(&remoteConfig);
remoteConfigParams.Dump();
}
for (unsigned i = 1; i < 7 ; i++) {
display.ClearLine(i);
}
uint8_t nHwTextLength;
display.Printf(1, "OSC DMX 1");
display.Write(2, hw.GetBoardName(nHwTextLength));
display.Printf(3, "IP: " IPSTR " %c", IP2STR(Network::Get()->GetIp()), nw.IsDhcpKnown() ? (nw.IsDhcpUsed() ? 'D' : 'S') : ' ');
display.Printf(4, "In: %d", server.GetPortIncoming());
display.Printf(5, "Out: %d", server.GetPortOutgoing());
display.TextStatus(OscServerMsgConst::START, DISPLAY_7SEGMENT_MSG_INFO_BRIDGE_START, CONSOLE_YELLOW);
server.Start();
hw.SetLed(HARDWARE_LED_FLASH);
display.TextStatus(OscServerMsgConst::STARTED, DISPLAY_7SEGMENT_MSG_INFO_BRIDGE_STARTED, CONSOLE_GREEN);
while (spiFlashStore.Flash())
;
hw.WatchdogInit();
for (;;) {
hw.WatchdogFeed();
nw.Run();
server.Run();
remoteConfig.Run();
spiFlashStore.Flash();
mDns.Run();
lb.Run();
display.Run();
}
}
}
| [
"[email protected]"
]
| |
dd848894fc16c8875d1fdd4e5320b8145faae5e4 | 75a29841cd696c058d2c653381b0fa2c4551163b | /solutions/12/system.cpp | 17c1d518a20424537d7bf68ef1a7015d1056c98f | []
| no_license | Shinmera/ETHZ-NumericalMethods | e62a5f3cb2c459936c5ec4c05008e488d51fa872 | 282124b21cc92063c77e30d2ba5ed19cb545dfde | refs/heads/master | 2021-01-18T21:15:35.985625 | 2016-04-06T11:40:21 | 2016-04-06T11:40:21 | 42,939,237 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | cpp | #include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/SparseLU>
#include <vector>
#include <iomanip>
#include "errors.hpp"
using namespace Eigen;
int main() {
// Construct data for RK order 4
MatrixXd A = MatrixXd::Zero(4,4);
A(1,0) = .5;
A(2,1) = .5;
A(3,2) = 1;
VectorXd b(4);
b << 1./6, 1./3, 1./3, 1./6;
// Construct data for the IVP
double T = 1;
int n = 5;
VectorXd y0(2*n);
for(int i = 0; i < n; ++i) {
y0(i)=(i+1.)/n;
y0(i+n)=-1;
}
auto f = [n] (VectorXd y) {
VectorXd fy(2*n);
VectorXd g(n);
g(0) = y(0)*(y(1)+y(0));
g(n-1) = y(n-1)*(y(n-1)+y(n-2));
for(int i = 1; i < n-1; ++i) {
g(i) = y(i)*(y(i-1)+y(i+1));
}
Eigen::SparseMatrix<double> C(n,n);
C.reserve(3);
for(int i = 0; i < n; ++i) {
C.insert(i,i) = 2;
if(i < n-1) C.insert(i,i+1) = -1;
if(i >= 1) C.insert(i,i-1) = -1;
}
C.makeCompressed();
fy.head(n) = y.head(n);
Eigen::SparseLU< Eigen::SparseMatrix<double> > solver;
solver.analyzePattern(C);
solver.compute(C);
fy.tail(n) = solver.solve(g);
return fy;
};
errors(f, T, y0, A, b);
} | [
"[email protected]"
]
| |
1fac6bfb7fcad1b4cb1aef2b53e82f27bbb6a2c5 | d5046cfc7f23e2ae2c284dba58e83edc43a254ac | /Homework/Assignment 1/Gaddis_8th_Ch6_7_Celsius Temp Table/main.cpp | 5bc6b899aa1d7293da3c910eac43b78a77c7e550 | []
| no_license | kn2496922/KhanhNguyen_CIS17A_48591 | 3a81c9251d7ea0b4ef2d15d7b10fca9e352e11d8 | c75dd61d416916242aeb0bd5bf9b8ead7c84c518 | refs/heads/master | 2023-09-01T00:59:54.184857 | 2021-10-23T05:43:48 | 2021-10-23T05:43:48 | 403,729,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: Khanh Nguyen
* Purpose: Displaying the fahrenheit to celsius table using function
* Created on September 6, 2021, 6:03 PM
*/
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
float celsius (int&);
/*
*
*/
int main(int argc, char** argv) {
//Using for loop to display the conversion of 0-20F to C
for (int i = 0; i < 21; i++)
{
float cel = celsius(i);
cout << i << "F is equal to " << fixed << setprecision(2) << cel << "C" << endl;
}
return 0;
}
/*
* Function to convert F to C
* Parameter(s): fah
*/
float celsius (int& fah)
{
return (5/9.0) * (fah - 32);
}
| [
"[email protected]"
]
| |
e82363da88a46b964f33bb2e33934729e692bc5c | 82b081493f7f2401ce0a309c22962444744170ed | /CodeChef/DIGITOP.cpp | 581bc0ecf4d727ebe4fd4030c4fcd6bf6422129a | []
| no_license | HeNeos/CompetitiveProgramming | c69eaf91e597f7b66d5ad325daa8862ae813d7c1 | 56de3e5e403f9f6f7801f56683f5245c93f56a87 | refs/heads/master | 2023-06-23T06:14:15.373718 | 2023-06-18T21:42:35 | 2023-06-18T21:42:35 | 164,735,512 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while(t--){
long long n, k; cin >> n >> k;
string a[n];
string b[n];
map <char, int> m;
for(int i=0; i<n; i++){
cin >> a[i];
for(int j=0; j<a[i].size(); j++) m[a[i][j]]++;
}
for(int i=0; i<n; i++){
cin >> b[i];
for(int j=0; j<b[i].size(); j++) m[b[i][j]]--;
}
bool ispossible = true;
for(int i=0; i<n; i++){
if(a[i].size() != b[i].size()) ispossible = false;
}
if(!ispossible){
cout << "NO\n";
continue;
}
long long ans = 0;
for(auto v: m){
ans += abs(v.second);
}
// cout << ans << "XD\n";
if(ans <= 2LL*k) cout << "YES";
else cout << "NO";
cout << '\n';
}
return 0;
} | [
"[email protected]"
]
| |
da370cb383206d5df8b8c00ed3423e5a8dac5d83 | a39078d2683af20ac9be4b6d8a5426fcd587cb2f | /ui/events/win/events_win.cc | f533367eab30dd7663964ebfd9e2640ec5ff74e1 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
]
| permissive | EnjoyHacking/ChromiumGStreamerBackend | 802f454dd01151b4b03d894869426dde4c7d52fa | 1339c551e24bdd4f3dafaac4d9d0f02b8b60454b | refs/heads/master | 2020-12-24T13:28:12.004578 | 2016-01-11T18:56:57 | 2016-01-11T19:03:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,190 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windowsx.h>
#include "ui/events/event_constants.h"
#include "base/logging.h"
#include "base/time/time.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_code_conversion_win.h"
#include "ui/events/win/system_event_state_lookup.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/win/dpi.h"
namespace ui {
namespace {
// From MSDN: "Mouse" events are flagged with 0xFF515700 if they come
// from a touch or stylus device. In Vista or later, they are also flagged
// with 0x80 if they come from touch.
#define MOUSEEVENTF_FROMTOUCH (0xFF515700 | 0x80)
// Get the native mouse key state from the native event message type.
int GetNativeMouseKey(const base::NativeEvent& native_event) {
switch (native_event.message) {
case WM_LBUTTONDBLCLK:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_NCLBUTTONDBLCLK:
case WM_NCLBUTTONDOWN:
case WM_NCLBUTTONUP:
return MK_LBUTTON;
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_NCMBUTTONDBLCLK:
case WM_NCMBUTTONDOWN:
case WM_NCMBUTTONUP:
return MK_MBUTTON;
case WM_RBUTTONDBLCLK:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_NCRBUTTONDBLCLK:
case WM_NCRBUTTONDOWN:
case WM_NCRBUTTONUP:
return MK_RBUTTON;
case WM_NCXBUTTONDBLCLK:
case WM_NCXBUTTONDOWN:
case WM_NCXBUTTONUP:
case WM_XBUTTONDBLCLK:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
return MK_XBUTTON1;
}
return 0;
}
bool IsButtonDown(const base::NativeEvent& native_event) {
return ((MK_LBUTTON | MK_MBUTTON | MK_RBUTTON | MK_XBUTTON1 | MK_XBUTTON2) &
native_event.wParam) != 0;
}
bool IsClientMouseEvent(const base::NativeEvent& native_event) {
return native_event.message == WM_MOUSELEAVE ||
native_event.message == WM_MOUSEHOVER ||
(native_event.message >= WM_MOUSEFIRST &&
native_event.message <= WM_MOUSELAST);
}
bool IsNonClientMouseEvent(const base::NativeEvent& native_event) {
return native_event.message == WM_NCMOUSELEAVE ||
native_event.message == WM_NCMOUSEHOVER ||
(native_event.message >= WM_NCMOUSEMOVE &&
native_event.message <= WM_NCXBUTTONDBLCLK);
}
bool IsMouseEvent(const base::NativeEvent& native_event) {
return IsClientMouseEvent(native_event) ||
IsNonClientMouseEvent(native_event);
}
bool IsMouseWheelEvent(const base::NativeEvent& native_event) {
return native_event.message == WM_MOUSEWHEEL ||
native_event.message == WM_MOUSEHWHEEL;
}
bool IsKeyEvent(const base::NativeEvent& native_event) {
return native_event.message == WM_KEYDOWN ||
native_event.message == WM_SYSKEYDOWN ||
native_event.message == WM_CHAR ||
native_event.message == WM_SYSCHAR ||
native_event.message == WM_KEYUP ||
native_event.message == WM_SYSKEYUP;
}
bool IsScrollEvent(const base::NativeEvent& native_event) {
return native_event.message == WM_VSCROLL ||
native_event.message == WM_HSCROLL;
}
// Returns a mask corresponding to the set of pressed modifier keys.
// Checks the current global state and the state sent by client mouse messages.
int KeyStateFlagsFromNative(const base::NativeEvent& native_event) {
int flags = GetModifiersFromKeyState();
// Check key messages for the extended key flag.
if (IsKeyEvent(native_event))
flags |= (HIWORD(native_event.lParam) & KF_EXTENDED) ? EF_EXTENDED : 0;
// Most client mouse messages include key state information.
if (IsClientMouseEvent(native_event)) {
int win_flags = GET_KEYSTATE_WPARAM(native_event.wParam);
flags |= (win_flags & MK_SHIFT) ? EF_SHIFT_DOWN : 0;
flags |= (win_flags & MK_CONTROL) ? EF_CONTROL_DOWN : 0;
}
return flags;
}
// Returns a mask corresponding to the set of pressed mouse buttons.
// This includes the button of the given message, even if it is being released.
int MouseStateFlagsFromNative(const base::NativeEvent& native_event) {
int win_flags = GetNativeMouseKey(native_event);
// Client mouse messages provide key states in their WPARAMs.
if (IsClientMouseEvent(native_event))
win_flags |= GET_KEYSTATE_WPARAM(native_event.wParam);
int flags = 0;
flags |= (win_flags & MK_LBUTTON) ? EF_LEFT_MOUSE_BUTTON : 0;
flags |= (win_flags & MK_MBUTTON) ? EF_MIDDLE_MOUSE_BUTTON : 0;
flags |= (win_flags & MK_RBUTTON) ? EF_RIGHT_MOUSE_BUTTON : 0;
flags |= IsNonClientMouseEvent(native_event) ? EF_IS_NON_CLIENT : 0;
return flags;
}
} // namespace
void UpdateDeviceList() {
NOTIMPLEMENTED();
}
EventType EventTypeFromNative(const base::NativeEvent& native_event) {
switch (native_event.message) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_CHAR:
case WM_SYSCHAR:
return ET_KEY_PRESSED;
// The WM_DEADCHAR message is posted to the window with the keyboard focus
// when a WM_KEYUP message is translated. This happens for special keyboard
// sequences.
case WM_DEADCHAR:
case WM_KEYUP:
// The WM_SYSDEADCHAR message is posted to a window with keyboard focus
// when the WM_SYSKEYDOWN message is translated by the TranslateMessage
// function. It specifies the character code of the system dead key.
case WM_SYSDEADCHAR:
case WM_SYSKEYUP:
return ET_KEY_RELEASED;
case WM_LBUTTONDBLCLK:
case WM_LBUTTONDOWN:
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
case WM_NCLBUTTONDOWN:
case WM_NCMBUTTONDBLCLK:
case WM_NCMBUTTONDOWN:
case WM_NCRBUTTONDBLCLK:
case WM_NCRBUTTONDOWN:
case WM_NCXBUTTONDBLCLK:
case WM_NCXBUTTONDOWN:
case WM_RBUTTONDBLCLK:
case WM_RBUTTONDOWN:
case WM_XBUTTONDBLCLK:
case WM_XBUTTONDOWN:
return ET_MOUSE_PRESSED;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_NCLBUTTONUP:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONUP:
case WM_NCXBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP:
return ET_MOUSE_RELEASED;
case WM_MOUSEMOVE:
return IsButtonDown(native_event) ? ET_MOUSE_DRAGGED : ET_MOUSE_MOVED;
case WM_NCMOUSEMOVE:
return ET_MOUSE_MOVED;
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
return ET_MOUSEWHEEL;
case WM_MOUSELEAVE:
case WM_NCMOUSELEAVE:
return ET_MOUSE_EXITED;
case WM_VSCROLL:
case WM_HSCROLL:
return ET_SCROLL;
default:
// We can't NOTREACHED() here, since this function can be called for any
// message.
break;
}
return ET_UNKNOWN;
}
int EventFlagsFromNative(const base::NativeEvent& native_event) {
int flags = KeyStateFlagsFromNative(native_event);
if (IsMouseEvent(native_event))
flags |= MouseStateFlagsFromNative(native_event);
return flags;
}
base::TimeDelta EventTimeFromNative(const base::NativeEvent& native_event) {
return base::TimeDelta::FromMilliseconds(native_event.time);
}
gfx::Point EventLocationFromNative(const base::NativeEvent& native_event) {
POINT native_point;
if ((native_event.message == WM_MOUSELEAVE ||
native_event.message == WM_NCMOUSELEAVE) ||
IsScrollEvent(native_event)) {
// These events have no coordinates. For sanity with rest of events grab
// coordinates from the OS.
::GetCursorPos(&native_point);
} else if (IsClientMouseEvent(native_event) &&
!IsMouseWheelEvent(native_event)) {
// Note: Wheel events are considered client, but their position is in screen
// coordinates.
// Client message. The position is contained in the LPARAM.
return gfx::Point(native_event.lParam);
} else {
DCHECK(IsNonClientMouseEvent(native_event) ||
IsMouseWheelEvent(native_event) || IsScrollEvent(native_event));
// Non-client message. The position is contained in a POINTS structure in
// LPARAM, and is in screen coordinates so we have to convert to client.
native_point.x = GET_X_LPARAM(native_event.lParam);
native_point.y = GET_Y_LPARAM(native_event.lParam);
}
ScreenToClient(native_event.hwnd, &native_point);
return gfx::Point(native_point);
}
gfx::Point EventSystemLocationFromNative(
const base::NativeEvent& native_event) {
POINT global_point = { static_cast<short>(LOWORD(native_event.lParam)),
static_cast<short>(HIWORD(native_event.lParam)) };
ClientToScreen(native_event.hwnd, &global_point);
return gfx::Point(global_point);
}
KeyboardCode KeyboardCodeFromNative(const base::NativeEvent& native_event) {
return KeyboardCodeForWindowsKeyCode(static_cast<WORD>(native_event.wParam));
}
DomCode CodeFromNative(const base::NativeEvent& native_event) {
const uint16 scan_code = GetScanCodeFromLParam(native_event.lParam);
return CodeForWindowsScanCode(scan_code);
}
bool IsCharFromNative(const base::NativeEvent& native_event) {
return native_event.message == WM_CHAR || native_event.message == WM_SYSCHAR;
}
int GetChangedMouseButtonFlagsFromNative(
const base::NativeEvent& native_event) {
switch (GetNativeMouseKey(native_event)) {
case MK_LBUTTON:
return EF_LEFT_MOUSE_BUTTON;
case MK_MBUTTON:
return EF_MIDDLE_MOUSE_BUTTON;
case MK_RBUTTON:
return EF_RIGHT_MOUSE_BUTTON;
// TODO: add support for MK_XBUTTON1.
default:
break;
}
return 0;
}
PointerDetails GetMousePointerDetailsFromNative(
const base::NativeEvent& native_event) {
return PointerDetails(EventPointerType::POINTER_TYPE_MOUSE);
}
gfx::Vector2d GetMouseWheelOffset(const base::NativeEvent& native_event) {
DCHECK(native_event.message == WM_MOUSEWHEEL ||
native_event.message == WM_MOUSEHWHEEL);
if (native_event.message == WM_MOUSEWHEEL)
return gfx::Vector2d(0, GET_WHEEL_DELTA_WPARAM(native_event.wParam));
return gfx::Vector2d(GET_WHEEL_DELTA_WPARAM(native_event.wParam), 0);
}
base::NativeEvent CopyNativeEvent(const base::NativeEvent& event) {
return event;
}
void ReleaseCopiedNativeEvent(const base::NativeEvent& event) {
}
void ClearTouchIdIfReleased(const base::NativeEvent& xev) {
NOTIMPLEMENTED();
}
int GetTouchId(const base::NativeEvent& xev) {
NOTIMPLEMENTED();
return 0;
}
float GetTouchRadiusX(const base::NativeEvent& native_event) {
NOTIMPLEMENTED();
return 1.0;
}
float GetTouchRadiusY(const base::NativeEvent& native_event) {
NOTIMPLEMENTED();
return 1.0;
}
float GetTouchAngle(const base::NativeEvent& native_event) {
NOTIMPLEMENTED();
return 0.0;
}
float GetTouchForce(const base::NativeEvent& native_event) {
NOTIMPLEMENTED();
return 0.0;
}
bool GetScrollOffsets(const base::NativeEvent& native_event,
float* x_offset,
float* y_offset,
float* x_offset_ordinal,
float* y_offset_ordinal,
int* finger_count) {
// TODO(ananta)
// Support retrieving the scroll offsets from the scroll event.
if (native_event.message == WM_VSCROLL || native_event.message == WM_HSCROLL)
return true;
return false;
}
bool GetFlingData(const base::NativeEvent& native_event,
float* vx,
float* vy,
float* vx_ordinal,
float* vy_ordinal,
bool* is_cancel) {
// Not supported in Windows.
NOTIMPLEMENTED();
return false;
}
int GetModifiersFromKeyState() {
int modifiers = EF_NONE;
if (ui::win::IsShiftPressed())
modifiers |= EF_SHIFT_DOWN;
if (ui::win::IsCtrlPressed())
modifiers |= EF_CONTROL_DOWN;
if (ui::win::IsAltPressed())
modifiers |= EF_ALT_DOWN;
if (ui::win::IsAltGrPressed())
modifiers |= EF_ALTGR_DOWN;
if (ui::win::IsWindowsKeyPressed())
modifiers |= EF_COMMAND_DOWN;
if (ui::win::IsCapsLockOn())
modifiers |= EF_CAPS_LOCK_DOWN;
if (ui::win::IsNumLockOn())
modifiers |= EF_NUM_LOCK_DOWN;
if (ui::win::IsScrollLockOn())
modifiers |= EF_SCROLL_LOCK_DOWN;
return modifiers;
}
// Windows emulates mouse messages for touch events.
bool IsMouseEventFromTouch(UINT message) {
return (message >= WM_MOUSEFIRST) && (message <= WM_MOUSELAST) &&
(GetMessageExtraInfo() & MOUSEEVENTF_FROMTOUCH) ==
MOUSEEVENTF_FROMTOUCH;
}
// Conversion scan_code and LParam each other.
// uint16 scan_code:
// ui/events/keycodes/dom/keycode_converter_data.inc
// 0 - 15bits: represetns the scan code.
// 28 - 30 bits (0xE000): represents whether this is an extended key or not.
//
// LPARAM lParam:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms644984.aspx
// 16 - 23bits: represetns the scan code.
// 24bit (0x0100): represents whether this is an extended key or not.
uint16 GetScanCodeFromLParam(LPARAM l_param) {
uint16 scan_code = ((l_param >> 16) & 0x00FF);
if (l_param & (1 << 24))
scan_code |= 0xE000;
return scan_code;
}
LPARAM GetLParamFromScanCode(uint16 scan_code) {
LPARAM l_param = static_cast<LPARAM>(scan_code & 0x00FF) << 16;
if ((scan_code & 0xE000) == 0xE000)
l_param |= (1 << 24);
return l_param;
}
} // namespace ui
| [
"[email protected]"
]
| |
1deacc747dbac5ca0436977ea67351f4c385a2e1 | 46992e63e8cae3ec44414f04c312280e5393bcbc | /RelayTemp/RelayTemp.ino | 7d650a987696732bc2c7b59a915fca8f880e2852 | []
| no_license | nmetcalf/MySensors-Relay_Temp | 8e4ccb57dc2dfb5224b4692b5649aebca2331073 | 722223558b6f75cdca40630fd430951d99e0a07e | refs/heads/master | 2021-10-11T13:44:53.397229 | 2019-01-27T00:33:17 | 2019-01-27T00:33:17 | 139,863,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,996 | ino | /**2.20/**
REVISION HISTORY
Version 1.0 - Nathan Metcalf
Battery Relay with Temp.
*/
#define MY_NODE_ID 203
// Enable debug prints to serial monitor
#define MY_DEBUG
// Set blinking period (in milliseconds)
#define MY_DEFAULT_LED_BLINK_PERIOD 300
//#define MY_DEFAULT_TX_LED_PIN 3
//#define MY_DEFAULT_RX_LED_PIN 2
// Enable and select radio type attached
#define MY_RADIO_NRF24
#define MY_RF24_CE_PIN 9
#define MY_RF24_CS_PIN 10
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
// Enable repeater functionality for this node
#define MY_REPEATER_FEATURE
#include <SPI.h>
#include <MySensors.h>
#include <DHT.h>
#define RELAY_PIN 2 // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 4 // Total number of attached relays
#define RELAY_ON 0 // GPIO value to write to turn on attached relay
#define RELAY_OFF 1 // GPIO value to write to turn off attached relay
// DHT11 STUFF
// Set this to the pin you connected the DHT's data pin to
#define DHT_DATA_PIN 7
// Set this offset if the sensor has a permanent small offset to the real temperatures
#define SENSOR_TEMP_OFFSET 0
// Sleep time between sensor updates (in milliseconds)
// Must be >1000ms for DHT22 and >2000ms for DHT11
static const uint64_t UPDATE_INTERVAL = 60000;
// Force sending an update of the temperature after n sensor reads, so a controller showing the
// timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
// the value didn't change since;
// i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
static const uint8_t FORCE_UPDATE_N_READS = 10;
#define CHILD_ID_HUM 5
#define CHILD_ID_TEMP 6
#define CHILD_ID_VOLT 7
float lastTemp;
float lastHum;
uint8_t nNoUpdatesTemp;
uint8_t nNoUpdatesHum;
bool metric = true;
MyMessage msgHum(CHILD_ID_HUM, V_HUM);
MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
MyMessage msgBatteryVolt(CHILD_ID_VOLT, V_VOLTAGE);
DHT dht;
// END DHT11
// Voltage Devider
int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point
int oldBatteryPcnt = 0;
float oldBatteryVolt = 0;
// End Voltage
void before()
{
for (int sensor = 1, pin = RELAY_PIN; sensor <= NUMBER_OF_RELAYS; sensor++, pin++) {
// Then set relay pins in output mode
pinMode(pin, OUTPUT);
// Set relay to last known state (using eeprom storage)
digitalWrite(pin, loadState(sensor) ? RELAY_ON : RELAY_OFF);
}
}
void setup()
{
dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
}
// Sleep for the time of the minimum sampling period to give the sensor time to power up
// (otherwise, timeout errors might occure for the first reading)
sleep(dht.getMinimumSamplingPeriod());
}
void presentation()
{
// Send the sketch version information to the gateway and Controller
sendSketchInfo("NDM.Guru Garden Back", "1.5");
for (int sensor = 1, pin = RELAY_PIN; sensor <= NUMBER_OF_RELAYS; sensor++, pin++) {
// Register all sensors to gw (they will be created as child devices)
present(sensor, S_BINARY);
}
// Register all sensors to gw (they will be created as child devices)
present(CHILD_ID_HUM, S_HUM);
present(CHILD_ID_TEMP, S_TEMP);
present( CHILD_ID_VOLT, S_MULTIMETER );
metric = getControllerConfig().isMetric;
}
void loop()
{
// 1M, 100K divider across battery and using internal ADC ref of 1.1V
// Sense point is bypassed with 0.1 uF cap to reduce noise at that point
// ((1e6+470e3)/470e3)*1.1 = Vmax = 3.44 Volts
// 3.44/1023 = Volts per bit = 0.003363075
float batteryVolt = getBatteryVoltage();
int batteryPcnt = getBatteryPercentage();
#ifdef MY_DEBUG
Serial.print("Battery Voltage: ");
Serial.print(batteryVolt);
Serial.println(" V");
Serial.print("Battery percent: ");
Serial.print(batteryPcnt);
Serial.println(" %");
#endif
if (oldBatteryVolt != batteryVolt) {
// Power up radio after sleep
send(msgBatteryVolt.set(batteryVolt, 3));
oldBatteryVolt = batteryVolt;
}
delay(10);
if (oldBatteryPcnt != batteryPcnt) {
// Power up radio after sleep
sendBatteryLevel(batteryPcnt);
oldBatteryPcnt = batteryPcnt;
}
// Force reading sensor, so it works also after sleep()
dht.readSensor(true);
// Get temperature from DHT library
float temperature = dht.getTemperature();
if (isnan(temperature)) {
Serial.println("Failed reading temperature from DHT!");
} else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
// Only send temperature if it changed since the last measurement or if we didn't send an update for n times
lastTemp = temperature;
if (!metric) {
temperature = dht.toFahrenheit(temperature);
}
// Reset no updates counter
nNoUpdatesTemp = 0;
temperature += SENSOR_TEMP_OFFSET;
send(msgTemp.set(temperature, 1));
#ifdef MY_DEBUG
Serial.print("Temperature: ");
Serial.println(temperature);
#endif
} else {
// Increase no update counter if the temperature stayed the same
nNoUpdatesTemp++;
}
delay(10);
// Get humidity from DHT library
float humidity = dht.getHumidity();
if (isnan(humidity)) {
Serial.println("Failed reading humidity from DHT");
} else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
// Only send humidity if it changed since the last measurement or if we didn't send an update for n times
lastHum = humidity;
// Reset no updates counter
nNoUpdatesHum = 0;
send(msgHum.set(humidity, 1));
#ifdef MY_DEBUG
Serial.print("Humidity: ");
Serial.println(humidity);
#endif
} else {
// Increase no update counter if the humidity stayed the same
nNoUpdatesHum++;
}
// Sleep for a while to save energy
sleep(UPDATE_INTERVAL);
}
void receive(const MyMessage &message)
{
// We only expect one type of message from controller. But we better check anyway.
if (message.type == V_STATUS) {
// Change relay state
digitalWrite(message.sensor - 1 + RELAY_PIN, message.getBool() ? RELAY_ON : RELAY_OFF);
// Store state in eeprom
saveState(message.sensor, message.getBool());
// Write some debug info
Serial.print("Incoming change for sensor:");
Serial.print(message.sensor);
Serial.print(", New status: ");
Serial.println(message.getBool());
}
}
float getBatteryVoltage() {
// get the battery Voltage
float sensorValue = analogRead(BATTERY_SENSE_PIN);
float batteryVoltage = (((sensorValue * 5.00) / 1024) * 11.252);
return batteryVoltage;
}
int getBatteryPercentage() {
float batteryVoltage = getBatteryVoltage();
int VccMin = 2.80;
int VccMax = 4.25;
int batteryPcnt = constrain(map(batteryVoltage, VccMin, VccMax, 0, 100),0,100); // and map to the 0-100% range
return batteryPcnt;
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.