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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c87f76c063a10298c920314ce247c995c1c783b9 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/examples/androidvoip/jni/android_voip_client.h | 8e1edd5ef918f5a39a474f33a19e36692b041f69 | [
"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 | 8,391 | h | /*
* Copyright 2020 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.
*/
#ifndef EXAMPLES_ANDROIDVOIP_JNI_ANDROID_VOIP_CLIENT_H_
#define EXAMPLES_ANDROIDVOIP_JNI_ANDROID_VOIP_CLIENT_H_
#include <jni.h>
#include <memory>
#include <string>
#include <vector>
#include "api/audio_codecs/audio_format.h"
#include "api/call/transport.h"
#include "api/voip/voip_base.h"
#include "api/voip/voip_engine.h"
#include "rtc_base/async_packet_socket.h"
#include "rtc_base/async_udp_socket.h"
#include "rtc_base/socket_address.h"
#include "rtc_base/third_party/sigslot/sigslot.h"
#include "rtc_base/thread.h"
#include "sdk/android/native_api/jni/scoped_java_ref.h"
namespace webrtc_examples {
// AndroidVoipClient facilitates the use of the VoIP API defined in
// api/voip/voip_engine.h. One instance of AndroidVoipClient should
// suffice for most VoIP applications. AndroidVoipClient implements
// webrtc::Transport to send RTP/RTCP packets to the remote endpoint.
// It also creates methods (slots) for sockets to connect to in
// order to receive RTP/RTCP packets. AndroidVoipClient does all
// operations with rtc::Thread (voip_thread_), this is to comply
// with consistent thread usage requirement with ProcessThread used
// within VoipEngine, as well as providing asynchronicity to the
// caller. AndroidVoipClient is meant to be used by Java through JNI.
class AndroidVoipClient : public webrtc::Transport,
public sigslot::has_slots<> {
public:
// Returns a pointer to an AndroidVoipClient object. Clients should
// use this factory method to create AndroidVoipClient objects. The
// method will return a nullptr in case of initialization errors.
// It is the client's responsibility to delete the pointer when
// they are done with it (this class provides a Delete() method).
static AndroidVoipClient* Create(
JNIEnv* env,
const webrtc::JavaParamRef<jobject>& application_context,
const webrtc::JavaParamRef<jobject>& j_voip_client);
~AndroidVoipClient() override;
// Provides client with a Java List of Strings containing names of
// the built-in supported codecs through callback.
void GetSupportedCodecs(JNIEnv* env);
// Provides client with a Java String of the default local IPv4 address
// through callback. If IPv4 address is not found, provide the default
// local IPv6 address. If IPv6 address is not found, provide an empty
// string.
void GetLocalIPAddress(JNIEnv* env);
// Sets the encoder used by the VoIP API.
void SetEncoder(JNIEnv* env,
const webrtc::JavaParamRef<jstring>& j_encoder_string);
// Sets the decoders used by the VoIP API.
void SetDecoders(JNIEnv* env,
const webrtc::JavaParamRef<jobject>& j_decoder_strings);
// Sets two local/remote addresses, one for RTP packets, and another for
// RTCP packets. The RTP address will have IP address j_ip_address_string
// and port number j_port_number_int, the RTCP address will have IP address
// j_ip_address_string and port number j_port_number_int+1.
void SetLocalAddress(JNIEnv* env,
const webrtc::JavaParamRef<jstring>& j_ip_address_string,
jint j_port_number_int);
void SetRemoteAddress(
JNIEnv* env,
const webrtc::JavaParamRef<jstring>& j_ip_address_string,
jint j_port_number_int);
// Starts a VoIP session, then calls a callback method with a boolean
// value indicating if the session has started successfully. The VoIP
// operations below can only be used after a session has already started.
void StartSession(JNIEnv* env);
// Stops the current session, then calls a callback method with a
// boolean value indicating if the session has stopped successfully.
void StopSession(JNIEnv* env);
// Starts sending RTP/RTCP packets to the remote endpoint, then calls
// a callback method with a boolean value indicating if sending
// has started successfully.
void StartSend(JNIEnv* env);
// Stops sending RTP/RTCP packets to the remote endpoint, then calls
// a callback method with a boolean value indicating if sending
// has stopped successfully.
void StopSend(JNIEnv* env);
// Starts playing out the voice data received from the remote endpoint,
// then calls a callback method with a boolean value indicating if
// playout has started successfully.
void StartPlayout(JNIEnv* env);
// Stops playing out the voice data received from the remote endpoint,
// then calls a callback method with a boolean value indicating if
// playout has stopped successfully.
void StopPlayout(JNIEnv* env);
// Deletes this object. Used by client when they are done.
void Delete(JNIEnv* env);
// Implementation for Transport.
bool SendRtp(const uint8_t* packet,
size_t length,
const webrtc::PacketOptions& options) override;
bool SendRtcp(const uint8_t* packet, size_t length) override;
// Slots for sockets to connect to.
void OnSignalReadRTPPacket(rtc::AsyncPacketSocket* socket,
const char* rtp_packet,
size_t size,
const rtc::SocketAddress& addr,
const int64_t& timestamp);
void OnSignalReadRTCPPacket(rtc::AsyncPacketSocket* socket,
const char* rtcp_packet,
size_t size,
const rtc::SocketAddress& addr,
const int64_t& timestamp);
private:
AndroidVoipClient(JNIEnv* env,
const webrtc::JavaParamRef<jobject>& j_voip_client)
: voip_thread_(rtc::Thread::CreateWithSocketServer()),
j_voip_client_(env, j_voip_client) {}
void Init(JNIEnv* env,
const webrtc::JavaParamRef<jobject>& application_context);
// Overloaded methods having native C++ variables as arguments.
void SetEncoder(const std::string& encoder);
void SetDecoders(const std::vector<std::string>& decoders);
void SetLocalAddress(const std::string& ip_address, int port_number);
void SetRemoteAddress(const std::string& ip_address, int port_number);
// Methods to send and receive RTP/RTCP packets. Takes in a
// copy of a packet as a vector to prolong the lifetime of
// the packet as these methods will be called asynchronously.
void SendRtpPacket(const std::vector<uint8_t>& packet_copy);
void SendRtcpPacket(const std::vector<uint8_t>& packet_copy);
void ReadRTPPacket(const std::vector<uint8_t>& packet_copy);
void ReadRTCPPacket(const std::vector<uint8_t>& packet_copy);
// Used to invoke operations and send/receive RTP/RTCP packets.
std::unique_ptr<rtc::Thread> voip_thread_;
// Reference to the VoipClient java instance used to
// invoke callbacks when operations are finished.
webrtc::ScopedJavaGlobalRef<jobject> j_voip_client_
RTC_GUARDED_BY(voip_thread_);
// A list of AudioCodecSpec supported by the built-in
// encoder/decoder factories.
std::vector<webrtc::AudioCodecSpec> supported_codecs_
RTC_GUARDED_BY(voip_thread_);
// A JNI context used by the voip_thread_.
JNIEnv* env_ RTC_GUARDED_BY(voip_thread_);
// The entry point to all VoIP APIs.
std::unique_ptr<webrtc::VoipEngine> voip_engine_ RTC_GUARDED_BY(voip_thread_);
// Used by the VoIP API to facilitate a VoIP session.
absl::optional<webrtc::ChannelId> channel_ RTC_GUARDED_BY(voip_thread_);
// Members below are used for network related operations.
std::unique_ptr<rtc::AsyncUDPSocket> rtp_socket_ RTC_GUARDED_BY(voip_thread_);
std::unique_ptr<rtc::AsyncUDPSocket> rtcp_socket_
RTC_GUARDED_BY(voip_thread_);
rtc::SocketAddress rtp_local_address_ RTC_GUARDED_BY(voip_thread_);
rtc::SocketAddress rtcp_local_address_ RTC_GUARDED_BY(voip_thread_);
rtc::SocketAddress rtp_remote_address_ RTC_GUARDED_BY(voip_thread_);
rtc::SocketAddress rtcp_remote_address_ RTC_GUARDED_BY(voip_thread_);
};
} // namespace webrtc_examples
#endif // EXAMPLES_ANDROIDVOIP_JNI_ANDROID_VOIP_CLIENT_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
dfc16bf7dc2a83e42d5c9ea8ac9a09b400d1a5cb | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-mgn/include/aws/mgn/model/UpdateReplicationConfigurationTemplateResult.h | c81a991d9462d7e34f165d98962190d0e6fd450f | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 23,296 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/mgn/Mgn_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/mgn/model/ReplicationConfigurationDataPlaneRouting.h>
#include <aws/mgn/model/ReplicationConfigurationDefaultLargeStagingDiskType.h>
#include <aws/mgn/model/ReplicationConfigurationEbsEncryption.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace mgn
{
namespace Model
{
class UpdateReplicationConfigurationTemplateResult
{
public:
AWS_MGN_API UpdateReplicationConfigurationTemplateResult();
AWS_MGN_API UpdateReplicationConfigurationTemplateResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_MGN_API UpdateReplicationConfigurationTemplateResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Replication Configuration template ARN.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>Replication Configuration template ARN.</p>
*/
inline void SetArn(const Aws::String& value) { m_arn = value; }
/**
* <p>Replication Configuration template ARN.</p>
*/
inline void SetArn(Aws::String&& value) { m_arn = std::move(value); }
/**
* <p>Replication Configuration template ARN.</p>
*/
inline void SetArn(const char* value) { m_arn.assign(value); }
/**
* <p>Replication Configuration template ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>Replication Configuration template ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>Replication Configuration template ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>Replication Configuration template associate default Application Migration
* Service Security group.</p>
*/
inline bool GetAssociateDefaultSecurityGroup() const{ return m_associateDefaultSecurityGroup; }
/**
* <p>Replication Configuration template associate default Application Migration
* Service Security group.</p>
*/
inline void SetAssociateDefaultSecurityGroup(bool value) { m_associateDefaultSecurityGroup = value; }
/**
* <p>Replication Configuration template associate default Application Migration
* Service Security group.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithAssociateDefaultSecurityGroup(bool value) { SetAssociateDefaultSecurityGroup(value); return *this;}
/**
* <p>Replication Configuration template bandwidth throttling.</p>
*/
inline long long GetBandwidthThrottling() const{ return m_bandwidthThrottling; }
/**
* <p>Replication Configuration template bandwidth throttling.</p>
*/
inline void SetBandwidthThrottling(long long value) { m_bandwidthThrottling = value; }
/**
* <p>Replication Configuration template bandwidth throttling.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithBandwidthThrottling(long long value) { SetBandwidthThrottling(value); return *this;}
/**
* <p>Replication Configuration template create Public IP.</p>
*/
inline bool GetCreatePublicIP() const{ return m_createPublicIP; }
/**
* <p>Replication Configuration template create Public IP.</p>
*/
inline void SetCreatePublicIP(bool value) { m_createPublicIP = value; }
/**
* <p>Replication Configuration template create Public IP.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithCreatePublicIP(bool value) { SetCreatePublicIP(value); return *this;}
/**
* <p>Replication Configuration template data plane routing.</p>
*/
inline const ReplicationConfigurationDataPlaneRouting& GetDataPlaneRouting() const{ return m_dataPlaneRouting; }
/**
* <p>Replication Configuration template data plane routing.</p>
*/
inline void SetDataPlaneRouting(const ReplicationConfigurationDataPlaneRouting& value) { m_dataPlaneRouting = value; }
/**
* <p>Replication Configuration template data plane routing.</p>
*/
inline void SetDataPlaneRouting(ReplicationConfigurationDataPlaneRouting&& value) { m_dataPlaneRouting = std::move(value); }
/**
* <p>Replication Configuration template data plane routing.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithDataPlaneRouting(const ReplicationConfigurationDataPlaneRouting& value) { SetDataPlaneRouting(value); return *this;}
/**
* <p>Replication Configuration template data plane routing.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithDataPlaneRouting(ReplicationConfigurationDataPlaneRouting&& value) { SetDataPlaneRouting(std::move(value)); return *this;}
/**
* <p>Replication Configuration template use default large Staging Disk type.</p>
*/
inline const ReplicationConfigurationDefaultLargeStagingDiskType& GetDefaultLargeStagingDiskType() const{ return m_defaultLargeStagingDiskType; }
/**
* <p>Replication Configuration template use default large Staging Disk type.</p>
*/
inline void SetDefaultLargeStagingDiskType(const ReplicationConfigurationDefaultLargeStagingDiskType& value) { m_defaultLargeStagingDiskType = value; }
/**
* <p>Replication Configuration template use default large Staging Disk type.</p>
*/
inline void SetDefaultLargeStagingDiskType(ReplicationConfigurationDefaultLargeStagingDiskType&& value) { m_defaultLargeStagingDiskType = std::move(value); }
/**
* <p>Replication Configuration template use default large Staging Disk type.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithDefaultLargeStagingDiskType(const ReplicationConfigurationDefaultLargeStagingDiskType& value) { SetDefaultLargeStagingDiskType(value); return *this;}
/**
* <p>Replication Configuration template use default large Staging Disk type.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithDefaultLargeStagingDiskType(ReplicationConfigurationDefaultLargeStagingDiskType&& value) { SetDefaultLargeStagingDiskType(std::move(value)); return *this;}
/**
* <p>Replication Configuration template EBS encryption.</p>
*/
inline const ReplicationConfigurationEbsEncryption& GetEbsEncryption() const{ return m_ebsEncryption; }
/**
* <p>Replication Configuration template EBS encryption.</p>
*/
inline void SetEbsEncryption(const ReplicationConfigurationEbsEncryption& value) { m_ebsEncryption = value; }
/**
* <p>Replication Configuration template EBS encryption.</p>
*/
inline void SetEbsEncryption(ReplicationConfigurationEbsEncryption&& value) { m_ebsEncryption = std::move(value); }
/**
* <p>Replication Configuration template EBS encryption.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithEbsEncryption(const ReplicationConfigurationEbsEncryption& value) { SetEbsEncryption(value); return *this;}
/**
* <p>Replication Configuration template EBS encryption.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithEbsEncryption(ReplicationConfigurationEbsEncryption&& value) { SetEbsEncryption(std::move(value)); return *this;}
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline const Aws::String& GetEbsEncryptionKeyArn() const{ return m_ebsEncryptionKeyArn; }
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline void SetEbsEncryptionKeyArn(const Aws::String& value) { m_ebsEncryptionKeyArn = value; }
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline void SetEbsEncryptionKeyArn(Aws::String&& value) { m_ebsEncryptionKeyArn = std::move(value); }
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline void SetEbsEncryptionKeyArn(const char* value) { m_ebsEncryptionKeyArn.assign(value); }
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithEbsEncryptionKeyArn(const Aws::String& value) { SetEbsEncryptionKeyArn(value); return *this;}
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithEbsEncryptionKeyArn(Aws::String&& value) { SetEbsEncryptionKeyArn(std::move(value)); return *this;}
/**
* <p>Replication Configuration template EBS encryption key ARN.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithEbsEncryptionKeyArn(const char* value) { SetEbsEncryptionKeyArn(value); return *this;}
/**
* <p>Replication Configuration template ID.</p>
*/
inline const Aws::String& GetReplicationConfigurationTemplateID() const{ return m_replicationConfigurationTemplateID; }
/**
* <p>Replication Configuration template ID.</p>
*/
inline void SetReplicationConfigurationTemplateID(const Aws::String& value) { m_replicationConfigurationTemplateID = value; }
/**
* <p>Replication Configuration template ID.</p>
*/
inline void SetReplicationConfigurationTemplateID(Aws::String&& value) { m_replicationConfigurationTemplateID = std::move(value); }
/**
* <p>Replication Configuration template ID.</p>
*/
inline void SetReplicationConfigurationTemplateID(const char* value) { m_replicationConfigurationTemplateID.assign(value); }
/**
* <p>Replication Configuration template ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationConfigurationTemplateID(const Aws::String& value) { SetReplicationConfigurationTemplateID(value); return *this;}
/**
* <p>Replication Configuration template ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationConfigurationTemplateID(Aws::String&& value) { SetReplicationConfigurationTemplateID(std::move(value)); return *this;}
/**
* <p>Replication Configuration template ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationConfigurationTemplateID(const char* value) { SetReplicationConfigurationTemplateID(value); return *this;}
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline const Aws::String& GetReplicationServerInstanceType() const{ return m_replicationServerInstanceType; }
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline void SetReplicationServerInstanceType(const Aws::String& value) { m_replicationServerInstanceType = value; }
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline void SetReplicationServerInstanceType(Aws::String&& value) { m_replicationServerInstanceType = std::move(value); }
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline void SetReplicationServerInstanceType(const char* value) { m_replicationServerInstanceType.assign(value); }
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationServerInstanceType(const Aws::String& value) { SetReplicationServerInstanceType(value); return *this;}
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationServerInstanceType(Aws::String&& value) { SetReplicationServerInstanceType(std::move(value)); return *this;}
/**
* <p>Replication Configuration template server instance type.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationServerInstanceType(const char* value) { SetReplicationServerInstanceType(value); return *this;}
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline const Aws::Vector<Aws::String>& GetReplicationServersSecurityGroupsIDs() const{ return m_replicationServersSecurityGroupsIDs; }
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline void SetReplicationServersSecurityGroupsIDs(const Aws::Vector<Aws::String>& value) { m_replicationServersSecurityGroupsIDs = value; }
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline void SetReplicationServersSecurityGroupsIDs(Aws::Vector<Aws::String>&& value) { m_replicationServersSecurityGroupsIDs = std::move(value); }
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationServersSecurityGroupsIDs(const Aws::Vector<Aws::String>& value) { SetReplicationServersSecurityGroupsIDs(value); return *this;}
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithReplicationServersSecurityGroupsIDs(Aws::Vector<Aws::String>&& value) { SetReplicationServersSecurityGroupsIDs(std::move(value)); return *this;}
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddReplicationServersSecurityGroupsIDs(const Aws::String& value) { m_replicationServersSecurityGroupsIDs.push_back(value); return *this; }
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddReplicationServersSecurityGroupsIDs(Aws::String&& value) { m_replicationServersSecurityGroupsIDs.push_back(std::move(value)); return *this; }
/**
* <p>Replication Configuration template server Security Groups IDs.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddReplicationServersSecurityGroupsIDs(const char* value) { m_replicationServersSecurityGroupsIDs.push_back(value); return *this; }
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline const Aws::String& GetStagingAreaSubnetId() const{ return m_stagingAreaSubnetId; }
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline void SetStagingAreaSubnetId(const Aws::String& value) { m_stagingAreaSubnetId = value; }
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline void SetStagingAreaSubnetId(Aws::String&& value) { m_stagingAreaSubnetId = std::move(value); }
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline void SetStagingAreaSubnetId(const char* value) { m_stagingAreaSubnetId.assign(value); }
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithStagingAreaSubnetId(const Aws::String& value) { SetStagingAreaSubnetId(value); return *this;}
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithStagingAreaSubnetId(Aws::String&& value) { SetStagingAreaSubnetId(std::move(value)); return *this;}
/**
* <p>Replication Configuration template Staging Area subnet ID.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithStagingAreaSubnetId(const char* value) { SetStagingAreaSubnetId(value); return *this;}
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetStagingAreaTags() const{ return m_stagingAreaTags; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline void SetStagingAreaTags(const Aws::Map<Aws::String, Aws::String>& value) { m_stagingAreaTags = value; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline void SetStagingAreaTags(Aws::Map<Aws::String, Aws::String>&& value) { m_stagingAreaTags = std::move(value); }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithStagingAreaTags(const Aws::Map<Aws::String, Aws::String>& value) { SetStagingAreaTags(value); return *this;}
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithStagingAreaTags(Aws::Map<Aws::String, Aws::String>&& value) { SetStagingAreaTags(std::move(value)); return *this;}
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(const Aws::String& key, const Aws::String& value) { m_stagingAreaTags.emplace(key, value); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(Aws::String&& key, const Aws::String& value) { m_stagingAreaTags.emplace(std::move(key), value); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(const Aws::String& key, Aws::String&& value) { m_stagingAreaTags.emplace(key, std::move(value)); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(Aws::String&& key, Aws::String&& value) { m_stagingAreaTags.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(const char* key, Aws::String&& value) { m_stagingAreaTags.emplace(key, std::move(value)); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(Aws::String&& key, const char* value) { m_stagingAreaTags.emplace(std::move(key), value); return *this; }
/**
* <p>Replication Configuration template Staging Area Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddStagingAreaTags(const char* key, const char* value) { m_stagingAreaTags.emplace(key, value); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tags = value; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tags = std::move(value); }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(const Aws::String& key, const Aws::String& value) { m_tags.emplace(key, value); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(Aws::String&& key, const Aws::String& value) { m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(const Aws::String& key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(Aws::String&& key, Aws::String&& value) { m_tags.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(const char* key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(Aws::String&& key, const char* value) { m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>Replication Configuration template Tags.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& AddTags(const char* key, const char* value) { m_tags.emplace(key, value); return *this; }
/**
* <p>Replication Configuration template use Dedicated Replication Server.</p>
*/
inline bool GetUseDedicatedReplicationServer() const{ return m_useDedicatedReplicationServer; }
/**
* <p>Replication Configuration template use Dedicated Replication Server.</p>
*/
inline void SetUseDedicatedReplicationServer(bool value) { m_useDedicatedReplicationServer = value; }
/**
* <p>Replication Configuration template use Dedicated Replication Server.</p>
*/
inline UpdateReplicationConfigurationTemplateResult& WithUseDedicatedReplicationServer(bool value) { SetUseDedicatedReplicationServer(value); return *this;}
private:
Aws::String m_arn;
bool m_associateDefaultSecurityGroup;
long long m_bandwidthThrottling;
bool m_createPublicIP;
ReplicationConfigurationDataPlaneRouting m_dataPlaneRouting;
ReplicationConfigurationDefaultLargeStagingDiskType m_defaultLargeStagingDiskType;
ReplicationConfigurationEbsEncryption m_ebsEncryption;
Aws::String m_ebsEncryptionKeyArn;
Aws::String m_replicationConfigurationTemplateID;
Aws::String m_replicationServerInstanceType;
Aws::Vector<Aws::String> m_replicationServersSecurityGroupsIDs;
Aws::String m_stagingAreaSubnetId;
Aws::Map<Aws::String, Aws::String> m_stagingAreaTags;
Aws::Map<Aws::String, Aws::String> m_tags;
bool m_useDedicatedReplicationServer;
};
} // namespace Model
} // namespace mgn
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
58c522ea71ca9ac3fd8361a343d17fa2bb097ca4 | 6b660cb96baa003de9e18e332b048c0f1fa67ab9 | /External/SDK/BP_LavaZone_classes.h | 4737385c50beb6cd5101ac43a445423d79a0f9be | [] | no_license | zanzo420/zSoT-SDK | 1edbff62b3e12695ecf3969537a6d2631a0ff36f | 5e581eb0400061f6e5f93b3affd95001f62d4f7c | refs/heads/main | 2022-07-30T03:35:51.225374 | 2021-07-07T01:07:20 | 2021-07-07T01:07:20 | 383,634,601 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | h | #pragma once
// Name: SoT, Version: 2.2.0.2
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_LavaZone.BP_LavaZone_C
// 0x0008 (FullSize[0x0478] - InheritedSize[0x0470])
class ABP_LavaZone_C : public ALavaZone
{
public:
class USceneComponent* DefaultSceneRoot; // 0x0470(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_LavaZone.BP_LavaZone_C");
return ptr;
}
void UserConstructionScript();
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
ccafef4d6141c29d97b639365903eb7b5a219882 | eeea540c22526b1f1d14e2ea451c74e96d3bb093 | /src/serializisation.hpp | 9ddd0cc1f5d4b31e4143dc8accc93eca2f6914f9 | [
"MIT"
] | permissive | LeniLeGoff/online-multiclass-lpboost | 2d7d37f3122f98db89baa37798017aa3de2f839e | c821c4dfe5b81a2b7d89ece84f25599180a6167a | refs/heads/master | 2020-12-26T15:59:11.872775 | 2016-07-04T08:39:53 | 2016-07-04T08:39:53 | 55,956,091 | 0 | 0 | null | 2016-04-11T08:45:19 | 2016-04-11T08:45:19 | null | UTF-8 | C++ | false | false | 1,225 | hpp | #include <iostream>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
namespace boost {
namespace serialization {
template< class archive,
class S,
int Rows_,
int Cols_,
int Ops_,
int MaxRows_,
int MaxCols_>
inline void serialize(archive & ar,
Eigen::Matrix<S, Rows_, Cols_, Ops_, MaxRows_, MaxCols_> & matrix,
const unsigned int version)
{
int rows = matrix.rows();
int cols = matrix.cols();
ar & make_nvp("rows", rows);
ar & make_nvp("cols", cols);
matrix.resize(rows, cols); // no-op if size does not change!
// always save/load row-major
for(int r = 0; r < rows; ++r)
for(int c = 0; c < cols; ++c)
ar & make_nvp("val", matrix(r,c));
}
template< class archive,
class S,
int Dim_,
int Mode_,
int Options_>
inline void serialize(archive & ar,
Eigen::Transform<S, Dim_, Mode_, Options_> & transform,
const unsigned int version)
{
serialize(ar, transform.matrix(), version);
}
} //namespace serialization
} //namespace boost
| [
"le_goff@isir.upmc.fr"
] | le_goff@isir.upmc.fr |
3f3a265c3f9216a717635afeb801ef2fa98c250b | 5cb4993509dab0764bdf2f1db203f663c8a2a3f4 | /bh1750/bh1750.ino | 61eeca9c07ef462b7b34ccfabbbe94345b60e15f | [] | no_license | youngda/BH1750 | 92826a7e0379adfe2794055ddae47904180ccfc3 | 8d9f6501d72f470dd3f21cc8a00ba5f7044953c4 | refs/heads/master | 2021-01-11T03:19:35.218830 | 2016-10-15T17:26:26 | 2016-10-15T17:26:26 | 71,023,741 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | ino | /* author:youngda
* version:v1.0
* data:21-5-2015
*/
#include <Wire.h> //IIC
#include <math.h>
int BH1750address = 0x23;
byte buff[2];
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
int i;
uint16_t val=0;
BH1750_Init(BH1750address);
delay(200);
if(2==BH1750_Read(BH1750address))
{
val=((buff[0]<<8)|buff[1])/1.2;
Serial.print(val,DEC);
Serial.println("[lx]");
}
delay(150);
}
int BH1750_Read(int address) //
{
int i=0;
Wire.beginTransmission(address);
Wire.requestFrom(address, 2);
while(Wire.available()) //
{
buff[i] = Wire.read(); // receive one byte
i++;
}
Wire.endTransmission();
return i;
}
void BH1750_Init(int address)
{
Wire.beginTransmission(address);
Wire.write(0x10);//1lx reolution 120ms
Wire.endTransmission();
}
| [
"fz0030403@hotmail.com"
] | fz0030403@hotmail.com |
36706e19bfdfab642b2a09c357002505936dda9e | 29a4c1e436bc90deaaf7711e468154597fc379b7 | /modules/boost_math/include/nt2/toolbox/boost_math/function/simd/sse/ssse3/ibetac_invb.hpp | 29ecbf12da27fcf83364e66a8528e3289f5bbefa | [
"BSL-1.0"
] | permissive | brycelelbach/nt2 | 31bdde2338ebcaa24bb76f542bd0778a620f8e7c | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | refs/heads/master | 2021-01-17T12:41:35.021457 | 2011-04-03T17:37:15 | 2011-04-03T17:37:15 | 1,263,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | hpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_SSE_SSSE3_IBETAC_INVB_HPP_INCLUDED
#define NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_SSE_SSSE3_IBETAC_INVB_HPP_INCLUDED
#include <nt2/toolbox/boost_math/function/simd/sse/sse3/ibetac_invb.hpp>
#endif
| [
"jtlapreste@gmail.com"
] | jtlapreste@gmail.com |
fc337592a7131f52dfda1e17a934ef454fa4dde5 | af0ffd69d5e28b217990ffdd751b31bdd2608c45 | /12. Operator Overloading/C12_21_Strings1.cpp | 3ba90690c7aebd1e6af334f604c30f2905355172 | [] | no_license | Vuean/ThinkingInCPlusPlus | 2c2feb3bbfc4489094435193ad56fab3edfbd6ee | 19d13bd9318381b526a70478bc3cc0b6eb0712c9 | refs/heads/master | 2023-03-20T19:26:54.209080 | 2021-03-09T14:18:10 | 2021-03-09T14:18:10 | 284,883,766 | 13 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | // C12_21_Strings1.cpp
// No auto tupe conversion
#include "../require.h"
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;
class Stringc
{
string s;
public:
Stringc(const string& str = "") : s(str) {}
int strcmp(const Stringc& S) const
{
return ::strcmp(s.c_str(), S.s.c_str());
}
};
int main()
{
Stringc s1("hello"), s2("there");
s1.strcmp(s2);
} | [
"hzhlxy@outlook.com"
] | hzhlxy@outlook.com |
b8cd7bb203e5b345730d4e64db1a065ea97811aa | 7575668a328508652e169653d37eddaa08396a62 | /Native/Graphics/Mesh/GfxMeshPrimitives.cpp | 6c28db8f5d16ccce281a826cc404891ae02dd009 | [] | no_license | huangdonghai/titan3d | dad61082d27ba1c65b0de7b3ca9d4a299ff1123c | 571bce8ad677efb6ce3d92441b5af0b2340ff74f | refs/heads/master | 2022-12-31T15:35:53.529550 | 2020-10-20T10:41:35 | 2020-10-20T10:41:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,371 | cpp | #include "GfxMeshPrimitives.h"
#include "GfxMesh.h"
#include "GfxMdfQueue.h"
#include "GfxModifier.h"
#include "../../../Core/thread/vfxthread.h"
#define new VNEW
NS_BEGIN
RTTI_IMPL(EngineNS::GfxMeshPrimitives, EngineNS::VIUnknown);
RTTI_IMPL(EngineNS::GfxMeshDataProvider, EngineNS::VIUnknown);
void GfxMeshPrimitives::CalcNormals32(OUT std::vector<v3dxVector3>& normals, const v3dxVector3* pos, UINT nVert, const UINT* triangles, UINT nTri)
{
struct VertexFaces
{
std::vector<UINT> Faces;
};
std::vector<VertexFaces> VtxFaces;
VtxFaces.resize(nVert);
for (UINT i = 0; i < nVert; i++)
{
for (UINT j = 0; j < nTri; j++)
{
if (triangles[3 * j + 0] == i ||
triangles[3 * j + 1] == i ||
triangles[3 * j + 2] == i)
{
VtxFaces[i].Faces.push_back((UINT)j);
}
}
}
normals.resize(nVert);
for (UINT i = 0; i < nVert; i++)
{
normals[i].setValue(0, 0, 0);
for (auto j : VtxFaces[i].Faces)
{
auto a = triangles[3 * j + 0];
auto b = triangles[3 * j + 1];
auto c = triangles[3 * j + 2];
const v3dxVector3& vA = pos[a];
const v3dxVector3& vB = pos[b];
const v3dxVector3& vC = pos[c];
v3dxVector3 nor;
v3dxCalcNormal(&nor, &vA, &vB, &vC, TRUE);
normals[i] += nor;
}
normals[i] /= (float)VtxFaces[i].Faces.size();
normals[i].normalize();
}
}
void GfxMeshPrimitives::CalcNormals16(OUT std::vector<v3dxVector3>& normals, const v3dxVector3* pos, UINT nVert, const USHORT* triangles, UINT nTri)
{
struct VertexFaces
{
std::vector<UINT> Faces;
};
std::vector<VertexFaces> VtxFaces;
VtxFaces.resize(nVert);
for (UINT i = 0; i < nVert; i++)
{
for (UINT j = 0; j < nTri; j++)
{
if ((UINT)triangles[3 * j + 0] == i ||
(UINT)triangles[3 * j + 1] == i ||
(UINT)triangles[3 * j + 2] == i)
{
VtxFaces[i].Faces.push_back((UINT)j);
}
}
}
normals.resize(nVert);
for (UINT i = 0; i < nVert; i++)
{
normals[i].setValue(0, 0, 0);
for (auto j : VtxFaces[i].Faces)
{
auto a = triangles[3 * j + 0];
auto b = triangles[3 * j + 1];
auto c = triangles[3 * j + 2];
const v3dxVector3& vA = pos[a];
const v3dxVector3& vB = pos[b];
const v3dxVector3& vC = pos[c];
v3dxVector3 nor;
v3dxCalcNormal(&nor, &vA, &vB, &vC, TRUE);
normals[i] += nor;
}
normals[i] /= (float)VtxFaces[i].Faces.size();
normals[i].normalize();
}
}
GfxMeshPrimitives::GfxMeshPrimitives()
{
}
GfxMeshPrimitives::~GfxMeshPrimitives()
{
Cleanup();
}
void GfxMeshPrimitives::Cleanup()
{
}
vBOOL GfxMeshPrimitives::Init(IRenderContext* rc, const char* name, UINT atom)
{
mContext.FromObject(rc);
mName = name;
mAtoms.resize(atom);
mDesc.AtomNumber = atom;
mGeometryMesh = rc->CreateGeometryMesh();
mMdfQueue = new GfxMdfQueue();
return TRUE;
}
vBOOL GfxMeshPrimitives::InitFromGeomtryMesh(IRenderContext* rc, IGeometryMesh* mesh, UINT atom, const v3dxBox3* aabb)
{
ASSERT(GLogicThreadId == vfxThread::GetCurrentThreadId());
mContext.FromObject(rc);
mAtoms.resize(atom);
mDesc.AtomNumber = atom;
mGeometryMesh.StrongRef(mesh);
mMdfQueue = new GfxMdfQueue();
mAABB = *aabb;
this->GetResourceState()->SetStreamState(SS_Valid);
return TRUE;
}
void GfxMeshPrimitives::Save2Xnd(IRenderContext* rc, XNDNode* pNode)
{
XNDAttrib* pAttr = pNode->AddAttrib("HeadAttrib3");
pAttr->BeginWrite();
{
auto pos_vb = mGeometryMesh->GetVertexBuffer(VST_Position);
mDesc.AtomNumber = (UINT)mAtoms.size();
mDesc.PolyNumber = mAtoms[0][0].NumPrimitives / 3;
mDesc.VertexNumber = pos_vb->mDesc.ByteWidth / sizeof(v3dxVector3);
mDesc.Flags = 0;
mDesc.UnUsed = 0;
mDesc.GeoTabeNumber = 0;
pAttr->Write(mDesc);
}
pAttr->Write(mAABB);
pAttr->Write(mOBB);
pAttr->Write(mOBBMatrix);
DWORD StreamIgnoreSaveFlag = 0;
pAttr->Write(StreamIgnoreSaveFlag);
pAttr->EndWrite();
pAttr = pNode->AddAttrib("RenderAtom");
pAttr->BeginWrite();
for (size_t i = 0; i < mAtoms.size(); i++)
{
const auto& dpDesc = mAtoms[i][0];
pAttr->Write(dpDesc.PrimitiveType);
UINT uLodLevel = (UINT)mAtoms[i].size();
pAttr->Write(uLodLevel);
for (UINT j = 0; j < uLodLevel; j++)
{
const auto& dpDesc1 = mAtoms[i][j];
pAttr->Write(dpDesc1.StartIndex);
pAttr->Write(dpDesc1.NumPrimitives);
}
}
pAttr->EndWrite();
auto vb = mGeometryMesh->GetVertexBuffer(VST_Position);
if (vb)
{
pAttr = pNode->AddAttrib("Position");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_Position], sizeof(v3dxVector3));
}
vb = mGeometryMesh->GetVertexBuffer(VST_Normal);
if (vb)
{
pAttr = pNode->AddAttrib("Normal");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_Normal], sizeof(v3dxVector3));
}
vb = mGeometryMesh->GetVertexBuffer(VST_Tangent);
if (vb)
{
pAttr = pNode->AddAttrib("Tangent");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_Tangent], sizeof(v3dVector4_t));
}
/*vb = mGeometryMesh->GetVertexBuffer(VST_Tangent);
if (vb)
{
pAttr = pNode->AddAttrib("Binormal");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_Tangent], sizeof(v3dxVector3));
}*/
vb = mGeometryMesh->GetVertexBuffer(VST_UV);
if (vb)
{
pAttr = pNode->AddAttrib("DiffuseUV");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_UV], sizeof(v3dxVector2));
}
vb = mGeometryMesh->GetVertexBuffer(VST_LightMap);
if (vb)
{
pAttr = pNode->AddAttrib("LightMapUV");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_LightMap], sizeof(v3dxVector2));
}
vb = mGeometryMesh->GetVertexBuffer(VST_Color);
if (vb)
{
pAttr = pNode->AddAttrib("VertexColor");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_Color], sizeof(DWORD));
}
vb = mGeometryMesh->GetVertexBuffer(VST_SkinIndex);
if (vb)
{
pAttr = pNode->AddAttrib("BlendIndex");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_SkinIndex], sizeof(DWORD));
}
vb = mGeometryMesh->GetVertexBuffer(VST_SkinWeight);
if (vb)
{
pAttr = pNode->AddAttrib("BlendWeight");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_SkinWeight], sizeof(v3dVector4_t));
}
vb = mGeometryMesh->GetVertexBuffer(VST_TerrainIndex);
if (vb)
{
pAttr = pNode->AddAttrib("Fix_VIDTerrain");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_TerrainIndex], sizeof(DWORD));
}
vb = mGeometryMesh->GetVertexBuffer(VST_TerrainGradient);
if (vb)
{
pAttr = pNode->AddAttrib("TerrainGradient");
SaveVB(rc, pAttr, vb, mGeometryMesh->MopherKeys[VST_TerrainGradient], sizeof(DWORD));
}
auto ib = mGeometryMesh->GetIndexBuffer();
if (ib)
{
pAttr = pNode->AddAttrib("Indices");
pAttr->BeginWrite();
const IIndexBufferDesc& desc = ib->mDesc;
UINT count = 0;
if (desc.Type == IBT_Int32)
{
count = desc.ByteWidth / sizeof(DWORD);
pAttr->Write(count);
vBOOL bFormatIndex32 = 1;
pAttr->Write(bFormatIndex32);
}
else
{
count = desc.ByteWidth / sizeof(WORD);
pAttr->Write(count);
vBOOL bFormatIndex32 = 0;
pAttr->Write(bFormatIndex32);
}
IBlobObject buffData;
while(buffData.GetSize() == 0)
{
ib->GetBufferData(rc, &buffData);
Sleep(10);
}
pAttr->Write(buffData.GetData(), desc.ByteWidth);
pAttr->EndWrite();
}
}
vBOOL GfxMeshPrimitives::LoadXnd(IRenderContext* rc, const char* name, XNDNode* pNode, bool isLoad)
{
mContext.FromObject(rc);
mSrcNode.StrongRef(pNode);
mName = name;
if (mGeometryMesh == nullptr)
{
mGeometryMesh = rc->CreateGeometryMesh();
}
else
{
mGeometryMesh->Cleanup();
}
if (mMdfQueue == nullptr)
{
mMdfQueue = new GfxMdfQueue();
}
else
{
mMdfQueue->Cleanup();
}
XNDAttrib* pAttr = pNode->GetAttrib("HeadAttrib3");
if (pAttr)
{
pAttr->BeginRead(__FILE__, __LINE__);
pAttr->Read(mDesc);
pAttr->Read(mAABB);
pAttr->Read(mOBB);
pAttr->Read(mOBBMatrix);
DWORD StreamIgnoreSaveFlag;
pAttr->Read(StreamIgnoreSaveFlag);
pAttr->EndRead();
}
else
{
pAttr = pNode->GetAttrib("HeadAttrib2");
if (pAttr)
{
pAttr->BeginRead(__FILE__, __LINE__);
pAttr->Read(mDesc);
pAttr->Read(mAABB);
pAttr->Read(mOBB);
pAttr->Read(mOBBMatrix);
pAttr->EndRead();
}
else
{
pAttr = pNode->GetAttrib("HeadAttrib");
if (pAttr)
{
pAttr->BeginRead(__FILE__, __LINE__);
pAttr->Read(mDesc);
pAttr->Read(mAABB);
pAttr->EndRead();
}
else
return FALSE;
}
}
pAttr = pNode->GetAttrib("RenderAtom");
if (pAttr)
{
mAtoms.clear();
mAtoms.resize(mDesc.AtomNumber);
pAttr->BeginRead(__FILE__, __LINE__);
for (size_t i = 0; i < mDesc.AtomNumber; i++)
{
DrawPrimitiveDesc dpDesc;
pAttr->Read(dpDesc.PrimitiveType);
UINT uLodLevel;
pAttr->Read(uLodLevel);
for (UINT j = 0; j < uLodLevel; j++)
{
pAttr->Read(dpDesc.StartIndex);
pAttr->Read(dpDesc.NumPrimitives);
mAtoms[i].push_back(dpDesc);
}
}
pAttr->EndRead();
}
else
{
return FALSE;
}
/*auto mdfQueue = pNode->GetChild("MdfQueue");
if (mdfQueue != nullptr)
{
auto& nodes = mdfQueue->GetChildVector();
for (auto i : nodes)
{
auto id = i->GetClassID();
auto mdfRtti = CoreRttiManager::GetInstance()->FindRtti(id);
if (mdfRtti == nullptr)
continue;
AutoRef<GfxModifier> pModifier = (GfxModifier*)mdfRtti->Constructor(__FILE__, __LINE__);
if (false == pModifier->LoadXnd(i))
{
continue;
}
mMdfQueue->AddModifier(pModifier);
}
}*/
if (mAABB.IsEmpty())
{
isLoad = true;
VFX_LTRACE(ELTT_Resource, "Mesh %s AABB is empty, Core will Restore object and recalculate it\r\n", this->GetName());
}
if (isLoad == false)
{
pNode->TryReleaseHolder();
return TRUE;
}
else
{
return RestoreResource();
}
}
void GfxMeshPrimitives::InvalidateResource()
{
mGeometryMesh->InvalidateResource();
}
const char* VBType2String(EVertexSteamType type)
{
switch (type)
{
case EngineNS::VST_Position:
return "Pos";
case EngineNS::VST_Normal:
return "Nor";
case EngineNS::VST_Tangent:
return "Tan";
case EngineNS::VST_Color:
return "Color";
case EngineNS::VST_UV:
return "UV";
case EngineNS::VST_LightMap:
return "LightMap";
case EngineNS::VST_SkinIndex:
return "SkinIndex";
case EngineNS::VST_SkinWeight:
return "SkinWeight";
case EngineNS::VST_TerrainIndex:
return "TerrainIndex";
case EngineNS::VST_TerrainGradient:
return "TerrainGradient";
case EngineNS::VST_InstPos:
return "InstPos";
case EngineNS::VST_InstQuat:
return "InstQuat";
case EngineNS::VST_InstScale:
return "InstScale";
case EngineNS::VST_F4_1:
return "F41";
case EngineNS::VST_F4_2:
return "F42";
case EngineNS::VST_F4_3:
return "F43";
default:
return "Unknown";
}
}
AutoRef<IVertexBuffer> GfxMeshPrimitives::LoadVB(IRenderContext* rc, XNDAttrib* pAttr, UINT stride, TimeKeys& tkeys, UINT& resSize, EVertexSteamType stream)
{
pAttr->BeginRead(__FILE__, __LINE__);
UINT uVert, uKey, uStride;
pAttr->Read(uStride);
pAttr->Read(uVert);
pAttr->Read(uKey);
tkeys.Load(*pAttr);
IVertexBufferDesc desc;
desc.CPUAccess = 0;
desc.Stride = uStride;
ASSERT(desc.Stride == stride);
desc.ByteWidth = uStride * uKey * uVert;
BYTE* data = new BYTE[desc.ByteWidth];
//data = new BYTE[desc.ByteWidth];
pAttr->Read(data, desc.ByteWidth);
desc.InitData = data;
pAttr->EndRead();
if (stream == VST_Position && mAABB.IsEmpty())
{
mAABB.InitializeBox();
v3dxVector3* pPosition = (v3dxVector3*)data;
for (UINT i = 0; i < uVert; i++)
{
mAABB.OptimalVertex(pPosition[i]);
}
}
AutoRef<IVertexBuffer> vb = rc->CreateVertexBuffer(&desc);
Safe_DeleteArray(data);
resSize += desc.ByteWidth;
return vb;
}
void GfxMeshPrimitives::SaveVB(IRenderContext* rc, XNDAttrib* pAttr, IVertexBuffer* vb, TimeKeys& tkeys, UINT stride)
{
IBlobObject buffData;
vb->GetBufferData(rc, &buffData);
if (buffData.GetSize() == 0)
return;
pAttr->BeginWrite();
UINT uVert, uKey;
uKey = tkeys.GetKeyCount();
if (uKey == 0)
uKey = 1;
uVert = (UINT)buffData.GetSize() / (uKey*stride);
pAttr->Write(stride);
pAttr->Write(uVert);
pAttr->Write(uKey);
tkeys.Save(*pAttr);
pAttr->Write(buffData.GetData(), (UINT)buffData.GetSize());
pAttr->EndWrite();
}
vBOOL GfxMeshPrimitives::RefreshResource(IRenderContext* rc, const char* name, XNDNode* node)
{
if (GetResourceState()->GetStreamState() == SS_Streaming)
return FALSE;
if (mSrcNode != nullptr)
{
mSrcNode->TryReleaseHolder();
if (LoadXnd(mContext.GetPtr(), mName.c_str(), node, true))
{
GetResourceState()->SetStreamState(SS_Valid);
return TRUE;
}
}
return FALSE;
}
vBOOL GfxMeshPrimitives::RestoreResource()
{
if (mSrcNode == nullptr)
return false;
auto rc = mContext.GetPtr();
if (rc == nullptr)
return false;
UINT resSize = 0;
XNDAttrib* pAttr = mSrcNode->GetAttrib("Position");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dxVector3), mGeometryMesh->MopherKeys[VST_Position], resSize, VST_Position);
mGeometryMesh->BindVertexBuffer(VST_Position, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":Pos").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("Normal");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dxVector3), mGeometryMesh->MopherKeys[VST_Normal], resSize, VST_Normal);
mGeometryMesh->BindVertexBuffer(VST_Normal, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":Nor").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("Tangent");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dVector4_t), mGeometryMesh->MopherKeys[VST_Tangent], resSize, VST_Tangent);
mGeometryMesh->BindVertexBuffer(VST_Tangent, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":Tan").c_str());
#endif
}
/*pAttr = mSrcNode->GetAttrib("Binormal");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dxVector3), mGeometryMesh->MopherKeys[VST_Tangent], resSize);
mGeometryMesh->BindVertexBuffer(VST_Tangent, vb);
}*/
pAttr = mSrcNode->GetAttrib("DiffuseUV");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dxVector2), mGeometryMesh->MopherKeys[VST_UV], resSize, VST_UV);
mGeometryMesh->BindVertexBuffer(VST_UV, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":UV").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("LightMapUV");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dxVector2), mGeometryMesh->MopherKeys[VST_LightMap], resSize, VST_LightMap);
mGeometryMesh->BindVertexBuffer(VST_LightMap, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":LightMap").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("VertexColor");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(DWORD), mGeometryMesh->MopherKeys[VST_Color], resSize, VST_Color);
mGeometryMesh->BindVertexBuffer(VST_Color, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":Color").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("BlendIndex");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(DWORD), mGeometryMesh->MopherKeys[VST_SkinIndex], resSize, VST_SkinIndex);
mGeometryMesh->BindVertexBuffer(VST_SkinIndex, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":BlendIndex").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("BlendWeight");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(v3dVector4_t), mGeometryMesh->MopherKeys[VST_SkinWeight], resSize, VST_SkinWeight);
mGeometryMesh->BindVertexBuffer(VST_SkinWeight, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":BlendWeight").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("Fix_VIDTerrain");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(DWORD), mGeometryMesh->MopherKeys[VST_TerrainIndex], resSize, VST_TerrainIndex);
mGeometryMesh->BindVertexBuffer(VST_TerrainIndex, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":TerrainIndex").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("TerrainGradient");
if (pAttr)
{
TimeKeys tkeys;
auto vb = LoadVB(rc, pAttr, sizeof(DWORD), mGeometryMesh->MopherKeys[VST_TerrainGradient], resSize, VST_TerrainGradient);
mGeometryMesh->BindVertexBuffer(VST_TerrainGradient, vb);
#if _DEBUG
vb->SetDebugInfo((mName + ":TerrainGradient").c_str());
#endif
}
pAttr = mSrcNode->GetAttrib("Indices");
if (pAttr)
{
pAttr->BeginRead(__FILE__, __LINE__);
IIndexBufferDesc desc;
desc.CPUAccess = 0;
UINT count;
pAttr->Read(count);
vBOOL bFormatIndex32;
pAttr->Read(bFormatIndex32);
desc.ByteWidth = count * ((bFormatIndex32) ? sizeof(DWORD) : sizeof(WORD));
desc.Type = bFormatIndex32 ? IBT_Int32 : IBT_Int16;
BYTE* data = new BYTE[desc.ByteWidth];
pAttr->Read(data, desc.ByteWidth);
pAttr->EndRead();
desc.InitData = data;
AutoRef<IIndexBuffer> ib = rc->CreateIndexBuffer(&desc);
mGeometryMesh->BindIndexBuffer(ib);
Safe_DeleteArray(data);
//ib->SetDebugInfo((mName + ":IB").c_str());
resSize += desc.ByteWidth;
}
mSrcNode->TryReleaseHolder();
this->GetResourceState()->SetResourceSize(resSize);
mGeometryMesh->SetIsDirty(TRUE);
return true;
}
GfxMdfQueue* GfxMeshPrimitives::GetMdfQueue()
{
return mMdfQueue;
}
const char* GfxMeshPrimitives::GetName() const
{
return mName.c_str();
}
UINT GfxMeshPrimitives::GetAtomNumber() const
{
return (UINT)mAtoms.size();
}
vBOOL GfxMeshPrimitives::GetAtom(UINT index, UINT lod, DrawPrimitiveDesc* desc) const
{
if (index >= (UINT)mAtoms.size())
return FALSE;
if (lod >= (UINT)mAtoms[index].size())
return FALSE;
*desc = mAtoms[index][lod];
return TRUE;
}
vBOOL GfxMeshPrimitives::SetAtom(UINT index, UINT lod, const DrawPrimitiveDesc* desc)
{
if (index >= (UINT)mAtoms.size())
return FALSE;
if (lod >= (UINT)mAtoms[index].size())
return FALSE;
mAtoms[index][lod] = *desc;
return TRUE;
}
void GfxMeshPrimitives::PushAtomLOD(UINT index, const DrawPrimitiveDesc* desc)
{
mAtoms[index].push_back(*desc);
}
UINT GfxMeshPrimitives::GetAtomLOD(UINT index)
{
return (UINT)mAtoms[index].size();
}
UINT GfxMeshPrimitives::GetLodLevel(UINT index, float lod)
{
auto num = (float)(GetAtomLOD(index));
return (UINT)(num * lod);
}
vBOOL GfxMeshPrimitives::SetGeomtryMeshStream(IRenderContext* rc, EVertexSteamType stream, void* data, UINT size, UINT stride, UINT cpuAccess)
{
IVertexBufferDesc desc;
desc.ByteWidth = size;
desc.Stride = stride;
desc.CPUAccess = cpuAccess;
desc.InitData = data;
AutoRef<IVertexBuffer> vb = rc->CreateVertexBuffer(&desc);
if (vb == nullptr)
return FALSE;
mGeometryMesh->BindVertexBuffer(stream, vb);
return TRUE;
}
vBOOL GfxMeshPrimitives::SetGeomtryMeshIndex(IRenderContext* rc, void* data, UINT size, EIndexBufferType type, UINT cpuAccess)
{
IIndexBufferDesc desc;
desc.ByteWidth = size;
desc.CPUAccess = cpuAccess;
desc.Type = type;
desc.InitData = data;
AutoRef<IIndexBuffer> ib = rc->CreateIndexBuffer(&desc);
if (ib == nullptr)
return FALSE;
mGeometryMesh->BindIndexBuffer(ib);
return TRUE;
}
//-----------------------------------------
GfxMeshDataProvider::GfxMeshDataProvider()
{
memset(mVertexBuffers, 0, sizeof(mVertexBuffers));
IndexBuffer = nullptr;
IBType = IBT_Int16;
}
GfxMeshDataProvider::~GfxMeshDataProvider()
{
Cleanup();
}
void GfxMeshDataProvider::Cleanup()
{
for (int i = 0; i < VST_Number; i++)
{
Safe_Release(mVertexBuffers[i]);
}
Safe_Release(IndexBuffer);
mAtoms.clear();
}
vBOOL GfxMeshDataProvider::ToMesh(IRenderContext* rc, GfxMeshPrimitives* mesh)
{
auto geom = mesh->GetGeomtryMesh();
UINT resSize = 0;
for (int i = 0; i < VST_Number; i++)
{
auto vb = geom->GetVertexBuffer((EVertexSteamType)i);
if (vb == nullptr)
continue;
resSize += mVertexBuffers[i]->GetSize();
mesh->SetGeomtryMeshStream(rc, (EVertexSteamType)i,
mVertexBuffers[i]->GetData(),
mVertexBuffers[i]->GetSize(),
GetStreamStride((EVertexSteamType)i), 0);
}
mesh->SetGeomtryMeshIndex(rc, IndexBuffer->GetData(), IndexBuffer->GetSize(), IBType, 0);
mesh->mAtoms = mAtoms;
auto pPos = (v3dxVector3*)mVertexBuffers[VST_Position]->GetData();
mesh->mAABB.InitializeBox();
for (UINT i = 0; i < VertexNumber; i++)
{
mesh->mAABB.OptimalVertex(pPos[i]);
}
mesh->mDesc.AtomNumber = (UINT)mAtoms.size();
mesh->mDesc.VertexNumber = VertexNumber;
mesh->mDesc.PolyNumber = TriangleNumber;
mesh->GetGeomtryMesh()->SetIsDirty(TRUE);
mesh->GetResourceState()->SetStreamState(SS_Valid);
mesh->GetResourceState()->SetResourceSize(resSize);
return TRUE;
}
vBOOL GfxMeshDataProvider::InitFromMesh(IRenderContext* rc, GfxMeshPrimitives* mesh)
{
Cleanup();
auto geom = mesh->GetGeomtryMesh();
auto ib = geom->GetIndexBuffer();
if (ib == nullptr)
{
return FALSE;
}
for (int i = 0; i < VST_Number; i++)
{
auto vb = geom->GetVertexBuffer((EVertexSteamType)i);
if(vb==nullptr)
continue;
mVertexBuffers[i] = new IBlobObject();
vb->GetBufferData(rc, mVertexBuffers[i]);
}
IndexBuffer = new IBlobObject();
ib->GetBufferData(rc, IndexBuffer);
IBType = ib->mDesc.Type;
switch (IBType)
{
case EngineNS::IBT_Int16:
TriangleNumber = IndexBuffer->GetSize() / (sizeof(USHORT) * 3);
break;
case EngineNS::IBT_Int32:
TriangleNumber = IndexBuffer->GetSize() / (sizeof(int) * 3);
break;
default:
break;
}
VertexNumber = mVertexBuffers[VST_Position]->GetSize() / sizeof(v3dxVector3);
mAtoms = mesh->mAtoms;
return TRUE;
}
vBOOL GfxMeshDataProvider::Init(DWORD streams, EIndexBufferType ibType, int atom)
{
Cleanup();
for (int i = 0; i < VST_Number; i++)
{
if (streams&(1 << i))
{
mVertexBuffers[i] = new IBlobObject();
}
}
IndexBuffer = new IBlobObject();
IBType = ibType;
switch (IBType)
{
case EngineNS::IBT_Int16:
TriangleNumber = IndexBuffer->GetSize() / (3 * sizeof(USHORT));
break;
case EngineNS::IBT_Int32:
TriangleNumber = IndexBuffer->GetSize() / (3 * sizeof(int));
break;
default:
break;
}
VertexNumber = mVertexBuffers[VST_Position]->GetSize() / sizeof(v3dxVector3);
mAtoms.resize(atom);
return TRUE;
}
UINT GfxMeshDataProvider::GetVertexNumber() const
{
return VertexNumber;
}
UINT GfxMeshDataProvider::GetTriangleNumber() const
{
return TriangleNumber;
}
UINT GfxMeshDataProvider::GetAtomNumber() const
{
return (UINT)mAtoms.size();
}
IBlobObject* GfxMeshDataProvider::GetStream(EVertexSteamType index)
{
return mVertexBuffers[index];
}
IBlobObject* GfxMeshDataProvider::GetIndices()
{
return IndexBuffer;
}
vBOOL GfxMeshDataProvider::GetAtom(UINT index, UINT lod, DrawPrimitiveDesc* desc) const
{
if (index >= (UINT)mAtoms.size())
return FALSE;
if (lod >= (UINT)mAtoms[index].size())
return FALSE;
*desc = mAtoms[index][lod];
return TRUE;
}
vBOOL GfxMeshDataProvider::SetAtom(UINT index, UINT lod, const DrawPrimitiveDesc* desc)
{
if (index >= (UINT)mAtoms.size())
return FALSE;
if (lod >= (UINT)mAtoms[index].size())
return FALSE;
mAtoms[index][lod] = *desc;
return TRUE;
}
void GfxMeshDataProvider::PushAtomLOD(UINT index, const DrawPrimitiveDesc* desc)
{
mAtoms[index].push_back(*desc);
}
UINT GfxMeshDataProvider::GetAtomLOD(UINT index)
{
return (UINT)mAtoms[index].size();
}
vBOOL GfxMeshDataProvider::GetAtomTriangle(UINT atom, UINT index, UINT* vA, UINT* vB, UINT* vC)
{
auto desc = GetAtom(atom, 0);
UINT startIndex = desc->StartIndex;
switch (IBType)
{
case EngineNS::IBT_Int16:
{
auto pIndices = (USHORT*)IndexBuffer->GetData();
UINT count = IndexBuffer->GetSize() / sizeof(USHORT);
if (startIndex + (index + 1) * 3 > count)
{
return FALSE;
}
*vA = (UINT)pIndices[startIndex + index * 3 + 0];
*vB = (UINT)pIndices[startIndex + index * 3 + 1];
*vC = (UINT)pIndices[startIndex + index * 3 + 2];
return TRUE;
}
case EngineNS::IBT_Int32:
{
auto pIndices = (UINT*)IndexBuffer->GetData();
UINT count = IndexBuffer->GetSize() / sizeof(UINT);
if (startIndex + (index + 1) * 3 > count)
{
return FALSE;
}
*vA = (UINT)pIndices[startIndex + index * 3 + 0];
*vB = (UINT)pIndices[startIndex + index * 3 + 1];
*vC = (UINT)pIndices[startIndex + index * 3 + 2];
return TRUE;
}
default:
return FALSE;
}
}
vBOOL GfxMeshDataProvider::GetTriangle(int index, UINT* vA, UINT* vB, UINT* vC)
{
switch (IBType)
{
case EngineNS::IBT_Int16:
{
auto pIndices = (USHORT*)IndexBuffer->GetData();
int count = IndexBuffer->GetSize() / sizeof(USHORT);
if (index * 3 + 2 > count)
{
return FALSE;
}
*vA = (UINT)pIndices[index * 3 + 0];
*vB = (UINT)pIndices[index * 3 + 1];
*vC = (UINT)pIndices[index * 3 + 2];
return TRUE;
}
case EngineNS::IBT_Int32:
{
auto pIndices = (UINT*)IndexBuffer->GetData();
int count = IndexBuffer->GetSize() / sizeof(UINT);
if (index * 3 + 2 > count)
{
return FALSE;
}
*vA = (UINT)pIndices[index * 3 + 0];
*vB = (UINT)pIndices[index * 3 + 1];
*vC = (UINT)pIndices[index * 3 + 2];
return TRUE;
}
default:
return FALSE;
}
}
int GfxMeshDataProvider::IntersectTriangle(const v3dxVector3* vStart, const v3dxVector3* vEnd, float* closedDist)
{
auto pPos = (v3dxVector3*)mVertexBuffers[VST_Position]->GetData();
v3dxVector3 dir = *vEnd - *vStart;
switch (IBType)
{
case EngineNS::IBT_Int16:
{
int triangle = -1;
*closedDist = FLT_MAX;
auto pIndices = (USHORT*)IndexBuffer->GetData();
int count = IndexBuffer->GetSize() / (sizeof(USHORT)*3);
for (int i = 0; i < count; i++)
{
auto ia = pIndices[i * 3 + 0];
auto ib = pIndices[i * 3 + 1];
auto ic = pIndices[i * 3 + 2];
float u, v, dist;
if (v3dxIntersectTri(&pPos[ia], &pPos[ib], &pPos[ic], vStart, &dir, &u, &v, &dist))
{
if (dist < *closedDist)
{
*closedDist = dist;
triangle = i;
}
}
}
return triangle;
}
case EngineNS::IBT_Int32:
{
int triangle = -1;
*closedDist = FLT_MAX;
auto pIndices = (int*)IndexBuffer->GetData();
int count = IndexBuffer->GetSize() / (sizeof(int) * 3);
for (int i = 0; i < count; i++)
{
auto ia = pIndices[i * 3 + 0];
auto ib = pIndices[i * 3 + 1];
auto ic = pIndices[i * 3 + 2];
float u, v, dist;
if (v3dxIntersectTri(&pPos[ia], &pPos[ib], &pPos[ic], vStart, &dir, &u, &v, &dist))
{
if (dist < *closedDist)
{
*closedDist = dist;
triangle = i;
}
}
}
return triangle;
}
default:
break;
}
return -1;
}
void* GfxMeshDataProvider::GetVertexPtr(EVertexSteamType stream, UINT index)
{
auto vb = mVertexBuffers[stream];
if (vb == nullptr)
return nullptr;
auto stride = GetStreamStride(stream);
if ((index + 1) * stride >= vb->GetSize())
return nullptr;
auto pData = (BYTE*)vb->GetData();
return pData + index * stride;
}
UINT GfxMeshDataProvider::GetStreamStride(EVertexSteamType stream)
{
switch (stream)
{
case EngineNS::VST_Position:
return sizeof(v3dxVector3);
case EngineNS::VST_Normal:
return sizeof(v3dxVector3);
case EngineNS::VST_Tangent:
return sizeof(v3dxQuaternion);
case EngineNS::VST_Color:
return sizeof(DWORD);
case EngineNS::VST_UV:
return sizeof(v3dxVector2);
case EngineNS::VST_LightMap:
return sizeof(v3dxVector2);
case EngineNS::VST_SkinIndex:
return sizeof(DWORD);
case EngineNS::VST_SkinWeight:
return sizeof(v3dxQuaternion);
case EngineNS::VST_TerrainIndex:
return sizeof(DWORD);
case EngineNS::VST_TerrainGradient:
return sizeof(DWORD);
case EngineNS::VST_InstPos:
return sizeof(v3dxVector3);
case EngineNS::VST_InstQuat:
return sizeof(v3dxQuaternion);
case EngineNS::VST_InstScale:
return sizeof(v3dxVector3);
case EngineNS::VST_F4_1:
return sizeof(v3dxQuaternion);
case EngineNS::VST_F4_2:
return sizeof(v3dxQuaternion);
case EngineNS::VST_F4_3:
return sizeof(v3dxQuaternion);
case EngineNS::VST_Number:
default:
return 0;
}
}
UINT GfxMeshDataProvider::AddVertex(const v3dxVector3* pos, const v3dxVector3* nor, const v3dxVector2* uv, DWORD color)
{
auto cur = mVertexBuffers[VST_Position];
if (cur != nullptr)
{
cur->PushData(pos, sizeof(v3dxVector3));
}
cur = mVertexBuffers[VST_Normal];
if (cur != nullptr)
{
cur->PushData(nor, sizeof(v3dxVector3));
}
cur = mVertexBuffers[VST_Tangent];
if (cur != nullptr)
{
cur->PushData(&v3dxQuaternion::ZERO, sizeof(v3dxQuaternion));
}
cur = mVertexBuffers[VST_Color];
if (cur != nullptr)
{
cur->PushData(&color, sizeof(DWORD));
}
cur = mVertexBuffers[VST_UV];
if (cur != nullptr)
{
cur->PushData(uv, sizeof(v3dxVector2));
}
cur = mVertexBuffers[VST_LightMap];
if (cur != nullptr)
{
cur->PushData(&v3dxVector3::ZERO, sizeof(v3dxVector2));
}
cur = mVertexBuffers[VST_SkinIndex];
if (cur != nullptr)
{
DWORD value = 0;
cur->PushData(&value, sizeof(DWORD));
}
cur = mVertexBuffers[VST_SkinWeight];
if (cur != nullptr)
{
cur->PushData(&v3dxQuaternion::ZERO, sizeof(v3dxQuaternion));
}
cur = mVertexBuffers[VST_TerrainIndex];
if (cur != nullptr)
{
DWORD value = 0;
cur->PushData(&value, sizeof(DWORD));
}
cur = mVertexBuffers[VST_TerrainGradient];
if (cur != nullptr)
{
DWORD value = 0;
cur->PushData(&value, sizeof(DWORD));
}
return VertexNumber++;
}
vBOOL GfxMeshDataProvider::AddTriangle(UINT a, UINT b, UINT c)
{
if (a >= VertexNumber ||
b >= VertexNumber ||
c >= VertexNumber)
return FALSE;
IndexBuffer->PushData(&a, sizeof(UINT));
IndexBuffer->PushData(&b, sizeof(UINT));
IndexBuffer->PushData(&c, sizeof(UINT));
TriangleNumber++;
return TRUE;
}
NS_END
using namespace EngineNS;
extern "C"
{
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshPrimitives, Init, IRenderContext*, const char*, UINT);
CSharpReturnAPI4(vBOOL, EngineNS, GfxMeshPrimitives, InitFromGeomtryMesh, IRenderContext*, IGeometryMesh*, UINT, const v3dxBox3*);
CSharpAPI2(EngineNS, GfxMeshPrimitives, Save2Xnd, IRenderContext*, XNDNode*);
CSharpReturnAPI4(vBOOL, EngineNS, GfxMeshPrimitives, LoadXnd, IRenderContext*, const char*, XNDNode*, bool);
CSharpReturnAPI0(IGeometryMesh*, EngineNS, GfxMeshPrimitives, GetGeomtryMesh);
CSharpReturnAPI0(GfxMdfQueue*, EngineNS, GfxMeshPrimitives, GetMdfQueue);
CSharpReturnAPI0(const char*, EngineNS, GfxMeshPrimitives, GetName);
CSharpReturnAPI0(UINT, EngineNS, GfxMeshPrimitives, GetAtomNumber);
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshPrimitives, GetAtom, UINT, UINT, DrawPrimitiveDesc*);
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshPrimitives, SetAtom, UINT, UINT, DrawPrimitiveDesc*);
CSharpAPI2(EngineNS, GfxMeshPrimitives, PushAtomLOD, UINT, DrawPrimitiveDesc*);
CSharpReturnAPI1(UINT, EngineNS, GfxMeshPrimitives, GetAtomLOD, UINT);
CSharpReturnAPI2(UINT, EngineNS, GfxMeshPrimitives, GetLodLevel, UINT, float);
CSharpReturnAPI6(vBOOL, EngineNS, GfxMeshPrimitives, SetGeomtryMeshStream, IRenderContext*, EVertexSteamType, void*, UINT, UINT , UINT);
CSharpReturnAPI5(vBOOL, EngineNS, GfxMeshPrimitives, SetGeomtryMeshIndex, IRenderContext*, void*, UINT, EIndexBufferType, UINT);
struct Box3_t
{
v3dVector3_t MinBox;
v3dVector3_t MaxBox;
};
VFX_API Box3_t SDK_GfxMeshPrimitives_GetAABB(GfxMeshPrimitives* self)
{
auto box = self->GetAABB();
return *((Box3_t*)&box);
}
VFX_API void SDK_GfxMeshPrimitives_SetAABB(GfxMeshPrimitives* self, Box3_t* box)
{
self->SetAABB(*(v3dxBox3*)box);
}
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshPrimitives, RefreshResource, IRenderContext*, const char*, XNDNode*);
CSharpReturnAPI2(vBOOL, EngineNS, GfxMeshDataProvider, InitFromMesh, IRenderContext*, GfxMeshPrimitives*);
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshDataProvider, Init, DWORD, EIndexBufferType, int);
CSharpReturnAPI0(UINT, EngineNS, GfxMeshDataProvider, GetVertexNumber);
CSharpReturnAPI0(UINT, EngineNS, GfxMeshDataProvider, GetTriangleNumber);
CSharpReturnAPI0(UINT, EngineNS, GfxMeshDataProvider, GetAtomNumber);
CSharpReturnAPI1(IBlobObject*, EngineNS, GfxMeshDataProvider, GetStream, EVertexSteamType);
CSharpReturnAPI0(IBlobObject*, EngineNS, GfxMeshDataProvider, GetIndices);
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshDataProvider, GetAtom, UINT, UINT, DrawPrimitiveDesc*);
CSharpReturnAPI3(vBOOL, EngineNS, GfxMeshDataProvider, SetAtom, UINT, UINT, const DrawPrimitiveDesc*);
CSharpAPI2(EngineNS, GfxMeshDataProvider, PushAtomLOD, UINT, const DrawPrimitiveDesc*);
CSharpReturnAPI1(UINT, EngineNS, GfxMeshDataProvider, GetAtomLOD, UINT);
CSharpReturnAPI4(vBOOL, EngineNS, GfxMeshDataProvider, GetTriangle, int, UINT*, UINT*, UINT*);
CSharpReturnAPI5(vBOOL, EngineNS, GfxMeshDataProvider, GetAtomTriangle, UINT, UINT, UINT*, UINT*, UINT*);
CSharpReturnAPI3(int, EngineNS, GfxMeshDataProvider, IntersectTriangle, const v3dxVector3*, const v3dxVector3*, float*);
CSharpReturnAPI2(void*, EngineNS, GfxMeshDataProvider, GetVertexPtr, EVertexSteamType, UINT);
CSharpReturnAPI2(vBOOL, EngineNS, GfxMeshDataProvider, ToMesh, IRenderContext*, GfxMeshPrimitives*);
}
| [
"1832617@qq.com"
] | 1832617@qq.com |
5075924884eb97042b837bad65eb1289921cb359 | 66e9d4ade105ca25ccaeece17b63831aaf133e7d | /chrome/browser/ui/views/bookmarks/bookmark_bar_view_browsertest.cc | 3c7c75bb3d275bf3418bb857fc341affa2dd01b3 | [
"BSD-3-Clause"
] | permissive | rookiechao/chromium | 17eed8364b9f369d35ca62ff380a7c5d55c5f810 | 2cd605c5bfcb7672fd6f4cae7400ec62308f3c2f | refs/heads/master | 2023-03-07T20:13:33.287402 | 2019-04-04T09:48:01 | 2019-04-04T09:48:01 | 178,987,904 | 1 | 0 | NOASSERTION | 2019-04-02T03:00:16 | 2019-04-02T03:00:16 | null | UTF-8 | C++ | false | false | 6,724 | cc | // Copyright 2019 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/bookmarks/bookmark_bar_view.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tab_ui_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view_observer.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view_test_helper.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/common/bookmark_pref_names.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/network/public/cpp/features.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/test/button_test_api.h"
class DummyEvent : public ui::Event {
public:
DummyEvent() : Event(ui::ET_UNKNOWN, base::TimeTicks(), 0) {}
~DummyEvent() override = default;
};
// Test suite covering the interaction between browser bookmarks and
// `Sec-Fetch-*` headers that can't be covered by Web Platform Tests (yet).
// See https://mikewest.github.io/sec-metadata/#directly-user-initiated and
// https://github.com/web-platform-tests/wpt/issues/16019.
class BookmarkBarNavigationTest : public InProcessBrowserTest {
public:
BookmarkBarNavigationTest()
: https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
void SetUp() override {
scoped_feature_list_.InitAndEnableFeature(network::features::kSecMetadata);
InProcessBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
InProcessBrowserTest::SetUpOnMainThread();
// Setup HTTPS server serving files from standard test directory.
static constexpr base::FilePath::CharType kDocRoot[] =
FILE_PATH_LITERAL("chrome/test/data");
https_test_server_.AddDefaultHandlers(base::FilePath(kDocRoot));
https_test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
ASSERT_TRUE(https_test_server_.Start());
// Setup the mock host resolver
host_resolver()->AddRule("*", "127.0.0.1");
browser()->profile()->GetPrefs()->SetBoolean(
bookmarks::prefs::kShowBookmarkBar, true);
test_helper_ = std::make_unique<BookmarkBarViewTestHelper>(bookmark_bar());
}
views::LabelButton* GetBookmarkButton(int index) {
return test_helper_->GetBookmarkButton(index);
}
BrowserView* browser_view() {
return BrowserView::GetBrowserViewForBrowser(browser());
}
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
BookmarkBarView* bookmark_bar() { return browser_view()->bookmark_bar(); }
std::string GetContent() {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
return content::EvalJs(web_contents, "document.body.textContent")
.ExtractString();
}
void CreateBookmarkForHeader(const std::string& header) {
// Populate bookmark bar with a single bookmark to
// `/echoheader?` + |header|.
bookmarks::BookmarkModel* model =
BookmarkModelFactory::GetForBrowserContext(browser()->profile());
bookmarks::test::WaitForBookmarkModelToLoad(model);
model->ClearStore();
std::string url = "/echoheader?";
model->AddURL(model->bookmark_bar_node(), 0, base::ASCIIToUTF16("Example"),
https_test_server_.GetURL(url + header));
}
void NavigateToBookmark() {
// Click on the 0th bookmark after setting up a navigation observer that
// waits for a single navigation to complete successfully.
content::TestNavigationObserver observer(web_contents(), 1);
views::LabelButton* button = GetBookmarkButton(0);
views::test::ButtonTestApi clicker(button);
DummyEvent click_event;
clicker.NotifyClick(click_event);
observer.Wait();
// All bookmark navigations should have a null initiator, as there's no
// web origin from which the navigation is triggered.
ASSERT_EQ(base::nullopt, observer.last_initiator_origin());
}
private:
net::EmbeddedTestServer https_test_server_;
std::unique_ptr<BookmarkBarViewTestHelper> test_helper_;
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(BookmarkBarNavigationTest, SecFetchFromEmptyTab) {
// Navigate to an empty tab
ui_test_utils::NavigateToURL(browser(), GURL("about:blank"));
{
// Sec-Fetch-Dest: document
CreateBookmarkForHeader("Sec-Fetch-Dest");
NavigateToBookmark();
EXPECT_EQ("document", GetContent());
}
{
// Sec-Fetch-Mode: navigate
CreateBookmarkForHeader("Sec-Fetch-Mode");
NavigateToBookmark();
EXPECT_EQ("navigate", GetContent());
}
{
// Sec-Fetch-Site: none
CreateBookmarkForHeader("Sec-Fetch-Site");
NavigateToBookmark();
EXPECT_EQ("none", GetContent());
}
{
// Sec-Fetch-User: ?T
CreateBookmarkForHeader("Sec-Fetch-User");
NavigateToBookmark();
EXPECT_EQ("?T", GetContent());
}
}
IN_PROC_BROWSER_TEST_F(BookmarkBarNavigationTest,
SecFetchSiteNoneFromNonEmptyTab) {
// Navigate to an non-empty tab
ui_test_utils::NavigateToURL(browser(), GURL("http://example.com/"));
{
// Sec-Fetch-Dest: document
CreateBookmarkForHeader("Sec-Fetch-Dest");
NavigateToBookmark();
EXPECT_EQ("document", GetContent());
}
{
// Sec-Fetch-Mode: navigate
CreateBookmarkForHeader("Sec-Fetch-Mode");
NavigateToBookmark();
EXPECT_EQ("navigate", GetContent());
}
{
// Sec-Fetch-Site: none
CreateBookmarkForHeader("Sec-Fetch-Site");
NavigateToBookmark();
EXPECT_EQ("none", GetContent());
}
{
// Sec-Fetch-User: ?T
CreateBookmarkForHeader("Sec-Fetch-User");
NavigateToBookmark();
EXPECT_EQ("?T", GetContent());
}
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1076520697becf42d45bbc46b0f2c99547dcd811 | aaabfbb7faadb59f0dad573be47781f267a10812 | /elliptic_group.cpp | 8319970b20cde3c53eac19682792e2d49a710f7d | [] | no_license | MansDolorem/ecdsa_example | 774da0f304a7e967fb17d49a3fdaa0a3e2b0be8c | be219078ce292c58599bf0066e566297e359bf88 | refs/heads/master | 2021-07-22T13:56:57.998071 | 2017-10-31T19:45:58 | 2017-10-31T19:45:58 | 109,041,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,081 | cpp | #include "elliptic_group.h";
#include <iostream>
using namespace std;
int reverse_mod(int value, int mod) {
if (value < 0) {
value += mod;
}
int q;
int r_0, r_1, r_2;
int x_0, x_1, x_2;
int y_0, y_1, y_2;
r_0 = mod; r_1 = value;
x_0 = 1; x_1 = 0;
y_0 = 0; y_1 = 1;
while (r_1) {
q = r_0 / r_1;
r_2 = r_0 - q*r_1;
x_2 = x_0 - q*x_1;
y_2 = y_0 - q*y_1;
r_0 = r_1; r_1 = r_2;
x_0 = x_1; x_1 = x_2;
y_0 = y_1; y_1 = y_2;
}
if (y_0 < 0) {
y_0 += mod;
}
return y_0;
}
point add_points(point P, point Q, int a, int mod) {
point R;
if (P.x == -1) {
return Q;
}
if (Q.x == -1) {
return P;
}
int lambda;
if (P.x == Q.x) {
if (((P.y + Q.y) % mod) == 0) {
R.x = R.y = -1;
return R;
}
lambda = (3 * P.x * P.x + a) * reverse_mod((2 * P.y), mod);
}
else {
lambda = (Q.y - P.y) * reverse_mod((Q.x - P.x), mod);
}
lambda %= mod;
if (lambda < 0) {
lambda += mod;
}
R.x = (lambda*lambda - P.x - Q.x) % mod;
if (R.x < 0) {
R.x += mod;
}
R.y = ((lambda*(P.x - R.x) - P.y)) % mod;
if (R.y < 0) {
R.y += mod;
}
return R;
}
point multiply_point(point P, int number, int a, int mod) {
point R = P;
if (number == 0) {
return point{ -1,-1 };
}
for (int i = 2; i <= number; i++) {
R = add_points(R, P, a, mod);
}
return R;
}
void elliptic_group::generate_secret_key() {
secret_key = rand() % (order_of_G - 1) + 1;
}
void elliptic_group::generate_public_key() {
public_key = multiply_point(G, secret_key, a, module);
}
bool elliptic_group::read(uint8_t* message) {
ifstream input(filename);
input >> public_key.x;
if (public_key.x == EOF) {
return false;
}
input >> public_key.y;
input >> signature.r;
input >> signature.s;
input.getline((char*)message, 255);
return true;
}
void elliptic_group::write(uint8_t* message) {
ofstream output(filename);
output << public_key.x << " " << public_key.y<<" ";
output << signature.r << " " << signature.s<<" ";
output <<(char*) message << endl;
output.close();
}
uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed = 0xB0F57EE3) {
uint32_t h = seed;
if (len > 3) {
const uint32_t* key_x4 = (const uint32_t*)key;
size_t i = len >> 2;
do {
uint32_t k = *key_x4++;
k *= 0xcc9e2d51;
k = (k << 15) | (k >> 17);
k *= 0x1b873593;
h ^= k;
h = (h << 13) | (h >> 19);
h = (h * 5) + 0xe6546b64;
} while (--i);
key = (const uint8_t*)key_x4;
}
if (len & 3) {
size_t i = len & 3;
uint32_t k = 0;
key = &key[i - 1];
do {
k <<= 8;
k |= *key--;
} while (--i);
k *= 0xcc9e2d51;
k = (k << 15) | (k >> 17);
k *= 0x1b873593;
h ^= k;
}
h ^= len;
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
void elliptic_group::sign(uint8_t* message) {
int k;
point kG;
while (true) {
k = rand() % (order_of_G - 3) + 2;
kG = multiply_point(G, k, a, module);
signature.r = kG.x%order_of_G;
if (signature.r != 0) {
signature.s = murmur3_32((const uint8_t*)message, strlen((char*)message)) % order_of_G;
signature.s += (secret_key*signature.r);
signature.s %= order_of_G;
signature.s *= reverse_mod(k, order_of_G);
signature.s %= order_of_G;
if (signature.s < 0) {
signature.s += order_of_G;
}
if (signature.s != 0) {
break;
}
}
}
}
bool elliptic_group::verify(uint8_t* message) {
int w, u1, u2, _r;
point u1G, u2Pa, sum;
if (signature.r < 1 || signature.r > (order_of_G - 1) ||
signature.s < 1 || signature.s > (order_of_G - 1)) {
return false;
}
w = reverse_mod(signature.s, order_of_G);
for (int i = 0; i <= strlen((char*)message); i++) {
message[i] = message[i + 1];
}
u1 = murmur3_32((const uint8_t*)message, strlen((char*)message)) % order_of_G;
u1 *= w;
u1 %= order_of_G;
if (u1 < 0) {
u1 += order_of_G;
}
u2 = (signature.r*w) % order_of_G;
u1G = multiply_point(G, u1, a, module);
u2Pa = multiply_point(public_key, u2, a, module);
sum = add_points(u1G, u2Pa, a, module);
_r = sum.x%order_of_G;
if (_r == signature.r) {
return true;
}
return false;
} | [
"mohnach.polina@gmail.com"
] | mohnach.polina@gmail.com |
0bf61c49f16ee346ba1499ec9e08d06c2e9ba573 | 44eb4b7c9cb8891cb3544936c7bbf8536eb2714c | /src/341.cpp | b96c1363877f08824d2fee271bd1bed2cbc91aa2 | [] | no_license | xf97/myLeetCodeSolutions | 7a330089e14c6d44a0de0de8b034f2a759c17348 | 5de6aa3977117e59ef69307894e163351b1d88fa | refs/heads/master | 2023-08-18T09:27:09.900780 | 2021-10-18T04:44:36 | 2021-10-18T04:44:36 | 291,883,909 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,075 | cpp | /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
private:
vector<int> values; //存储列表值的数组
vector<int>::iterator nowIte; //迭代器
void dfs(const vector<NestedInteger> &nestedList){
//深度优先搜索,把是整数的元素压入values
//vector的遍历保留原顺序
for(const auto & i : nestedList){
//已经提供的方法
if(i.isInteger()){
//是整数,压入
values.emplace_back(i.getInteger());
}
else{
//已经提供的方法
dfs(i.getList());
}
}
}
public:
//第一次遇见这种类型的题目,有点懵
//看了下题解,了解了,现在自己实现
//要善用已经定义好的方法
//时间击败:90.84%,空间击败:70.16%
NestedIterator(vector<NestedInteger> &nestedList) {
//获取整数序列并且初始化迭代器
dfs(nestedList);
nowIte = values.begin();
}
int next() {
return *nowIte++; //返回数值并前进一位
}
bool hasNext() {
return nowIte != values.end();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/
| [
"noreply@github.com"
] | noreply@github.com |
cc2b5fadb0b8c3e7a4659a4befb54c05c5af8df8 | 88664987cfbde8867df11f00b72c4050115292db | /lite/pre.cpp | fcdd3d0875862506a82f87c392d49e29a1e973e4 | [] | no_license | ddehilster/nlp-engine | 5a190832781ae150569bc41f83ba8e0e1e74bc84 | ebda6020a2af5fd831bda567956f3568fcc85b8d | refs/heads/master | 2020-06-22T05:49:04.764005 | 2020-01-28T22:26:00 | 2020-01-28T22:26:00 | 197,648,953 | 0 | 0 | null | 2020-01-28T22:26:01 | 2019-07-18T19:58:26 | C++ | UTF-8 | C++ | false | false | 18,049 | cpp | /*******************************************************************************
Copyright (c) 2001-2010 by Text Analysis International, Inc.
All rights reserved.
********************************************************************************
*
* NAME: PRE.CPP
* FILE: lite\pre.cpp
* CR: 11/30/98 AM.
* SUBJ: Pre actions for Pat pass.
* NOTE: User can employ pre actions to accept or reject the rule match
* prior to modifying the parse tree.
*
*******************************************************************************/
#include "StdAfx.h"
#include "machine.h" // 10/25/06 AM.
#include "u_out.h" // 01/19/06 AM.
#include "lite/global.h"
#include "inline.h" // 09/26/01 AM.
#include "dlist.h" // 07/07/03 AM.
#include "node.h" // 07/07/03 AM.
#include "tree.h" // 07/24/06 AM.
#include "lite/Auser.h" // 07/07/03 AM.
#include "lite/iarg.h" // 05/14/03 AM.
#include "str.h"
#include "io.h"
#include "chars.h"
#include "string.h"
#include "lite/nlppp.h" // 07/24/06 AM.
#include "gen.h" // Linux. // 04/26/07 AM.
#include "irule.h"
#include "parse.h"
//#include "lite/nlppp.h" // 07/24/06 AM.
#include "pat.h"
#include "pn.h"
#include "ivar.h" // 06/14/05 AM.
#include "regexp.h" // 03/24/09 AM.
#include "arg.h"
#include "lite/pre.h"
int Pre::count_ = 0;
// For users to be able to register a Pre action class containing
// their pre actions.
static Pre *userpre_ = 0;
/********************************************
* FN: Special functions for the class
********************************************/
Pre::Pre()
{
#ifndef STABLE_
++count_;
#endif
}
/*******************************************/
/*******************************************/
Pre::~Pre()
{
#ifndef STABLE_
--count_;
#endif
}
/*******************************************/
/*******************************************/
/********************************************
* FN: Access Functions
********************************************/
/********************************************
* FN: Modify Functions
********************************************/
/********************************************
* FN: GETCOUNT
* CR: 11/30/98 AM.
* NOTE: Class function.
********************************************/
#ifndef STABLE_
int Pre::getCount() { return count_; }
#endif
/********************************************
* FN: PRETTYCOUNT
* CR: 11/30/98 AM.
* NOTE: Class function.
********************************************/
#ifndef STABLE_
void Pre::prettyCount()
{
if (count_)
{
*gout << _T("Active Pre count=") << count_ << endl;
_t_strstream gerrStr;
gerrStr << _T("Active Pre count=") << count_ << ends;
errOut(&gerrStr,false);
}
}
#endif
/********************************************
* FN: PREMATCH
* CR: 11/30/98 AM.
* SUBJ: See if node conforms to pre-actions.
* RET: True if successful match, else false.
* NOTE: 06/16/05 AM. Moving leafMatch functionality down here.
* See obsolete leafMatch for its documentation.
********************************************/
//bool Pat::preMatch(
// Dlist<Ipre> *pres,
// Pn *pn
// )
bool Pat::preMatch(
Ielt *ielt, // 06/16/05 AM.
Node<Pn> *node // 06/16/05 AM.
)
{
if (!node || !ielt) // 06/16/05 AM.
return false; // 06/16/05 AM.
Dlist<Ipre> *pres = ielt->getPres(); // 06/16/05 AM.
if (!pres)
return true;
Delt<Ipre> *dpre;
_TCHAR *func;
Iaction *pre;
Dlist<Iarg> *dargs;
Delt<Iarg> *args;
bool accept = true; // If accepting current rule match.
for (dpre = pres->getFirst(); dpre; dpre = dpre->Right())
{
// Perform the current pre action.
pre = dpre->getData();
func = pre->getName();
dargs = pre->getArgs();
if (dargs)
args = dargs->getFirst();
else
args = 0;
if (!preAction(func, args,
node )) // 06/16/05 AM.
return false;
}
return true; // Completed obstacle course.
}
/********************************************
* FN: PREACTION
* CR: 11/30/98 AM.
* SUBJ: Execute one pre action on current node.
* RET: True if successful match, else false.
********************************************/
bool Pat::preAction(
_TCHAR *func, // Name of pre action.
Delt<Iarg> *args, // Action's arguments.
// Pn *pn // Current node being matched. // 06/16/05 AM.
Node<Pn> *node // TOPLEVEL node being matched. // 06/16/05 AM.
)
{
if (!node) // 06/16/05 AM.
return false; // 06/16/05 AM.
//if (Debug())
// *gout << " [Execute pre action...]" << endl;
////////////////////////////////////////
// PRE ACTIONS THAT MATCH TOPLEVEL NODE. // 06/16/05 AM.
Pn *pn = node->getData(); // 06/16/05 AM.
if (!strcmp_i(func, _T("var")))
return Pre::preVar(args, pn); // 06/14/05 AM.
if (!strcmp_i(func, _T("varz")))
return Pre::preVarz(args, pn); // 06/16/05 AM.
if (!strcmp_i(func, _T("vareq")))
return Pre::preVareq(args, pn); // 06/16/05 AM.
if (!strcmp_i(func, _T("varne")))
return Pre::preVarne(args, pn); // 06/16/05 AM.
if (!strcmp_i(func, _T("regexp")))
return Pre::preRegexp(args, pn); // 03/23/09 AM.
if (!strcmp_i(func, _T("regexpi")))
return Pre::preRegexpi(args, pn); // 03/26/09 AM.
////////////////////////////////////////
// PRE ACTIONS THAT MATCH LEAF NODE. // 06/16/05 AM.
Node<Pn> *leaf; // 06/16/05 AM.
if (!(leaf = leafNode(node))) // 06/16/05 AM.
return false; // 06/16/05 AM.
pn = leaf->getData(); // 06/16/05 AM.
// Just a simple test of pre actions.
if (!strcmp_i(func, _T("uppercase")))
return Pre::preUppercase(args, pn);
else if (!strcmp_i(func, _T("lowercase"))) // 01/03/00 AM.
return Pre::preLowercase(args, pn); // 01/03/00 AM.
else if (!strcmp_i(func, _T("cap")))
return Pre::preCap(args, pn);
else if (!strcmp_i(func, _T("length")))
return Pre::preLength(args, pn);
else if (!strcmp_i(func, _T("lengthr")))
return Pre::preLengthr(args, pn);
else if (!strcmp_i(func, _T("numrange"))) // 08/10/99 AM.
return Pre::preNumrange(args, pn);
else if (!strcmp_i(func, _T("unknown")))
return Pre::preUnknown(args, pn);
else if (!strcmp_i(func, _T("debug")))
return Pre::preDebug(args, pn); // 09/17/99 AM.
if (!Pre::userPre(func, args, pn))
return false; // Unknown or botched user-defined pre action.
return true;
}
/********************************************
* FN: USERPRE
* CR: 12/04/98 AM.
* SUBJ: Execute user-defined preactions on current node, if any.
* RET: True if successful match, else false.
********************************************/
bool Pre::userPre(_TCHAR *func, Delt<Iarg> *args, Pn *pn)
{
if (userpre_)
return userpre_->execute(func, args, pn); // Let pre subclass do it.
_t_strstream gerrStr;
gerrStr << _T("[Execute pre action: Unknown action=") << func << _T("].") << ends;
errOut(&gerrStr,false);
return false;
}
/********************************************
* FN: REGPRE
* CR: 12/04/98 AM.
* SUBJ: Register the user-defined pre-action class.
* NOTE: Class function.
* ALLOC: User creates the algorithm instance to add.
* Expected to be a derived class of Pre.
********************************************/
bool Pre::regPre(
Pre *pre // Algorithm class to register.
)
{
if (userpre_)
{
_t_strstream gerrStr;
gerrStr << _T("[regPre: Can only register one pre action class.]") << ends;
errOut(&gerrStr,false);
return false;
}
userpre_ = pre;
return true;
}
/********************************************
* FN: CLEAN
* CR: 12/04/98 AM.
* SUBJ: Cleanups for pre class.
* NOTE: Class function.
* ALLOC: Deletes the user-registered pre action class.
********************************************/
void Pre::clean()
{
if (userpre_)
{
delete userpre_;
userpre_ = 0;
}
}
/********************************************
* FN: PRE ACTIONS.
********************************************/
/********************************************
* FN: PREUPPERCASE
* CR: 11/30/98 AM.
* SUBJ: Succeed if all of the range of rule elements is all-uppercase.
* RET: True if pre succeeded.
* NOTE: Testing the pre action machinery with this first pre.
********************************************/
bool Pre::preUppercase(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
static bool warned = false;
bool ok = true;
if (args && !warned)
{
_t_strstream gerrStr;
gerrStr << _T("[Uppercase pre action: Ignoring arguments.]") << ends;
errOut(&gerrStr,false);
warned = true; // Don't repeat this message.
}
// Get the node's text. If alphabetic chars are all uppercase, then
// success.
_TCHAR *buf;
buf = pn->pnStr(); // Create buffer for node's text.
ok = all_uppercase(buf);
Chars::destroy(buf); // Free up buffer.
return ok;
}
/********************************************
* FN: PRELOWERCASE
* CR: 01/03/00 AM.
* SUBJ: Succeed if all of the range of rule elements is all-lowercase.
* RET: True if pre succeeded.
********************************************/
bool Pre::preLowercase(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
static bool warned = false;
bool ok = true;
if (args && !warned)
{
_t_strstream gerrStr;
gerrStr << _T("[Lowercase pre action: Ignoring arguments.]") << ends;
errOut(&gerrStr,false);
warned = true; // Don't repeat this message.
}
// Get the node's text. If alphabetic chars are all uppercase, then
// success.
_TCHAR *buf;
buf = pn->pnStr(); // Create buffer for node's text.
ok = all_lowercase(buf);
Chars::destroy(buf); // Free up buffer.
return ok;
}
/********************************************
* FN: PRECAP
* CR: 01/26/99 AM.
* SUBJ: See if covered nodes are capitalized.
* RET: True if pre succeeded.
* NOTE: Succeed if capitalized alphabetic.
* 01/31/99 AM. Fail if not alphabetic at all. We might be
* traversing down a singlet, so that if the top node is nonliteral,
* we'll always succeed, no matter what's underlying it.
********************************************/
bool Pre::preCap(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
static bool warned = false;
bool ok = true;
if (args && !warned)
{
_t_strstream gerrStr;
gerrStr << _T("[Cap pre action: Ignoring arguments.]") << ends;
errOut(&gerrStr,false);
warned = true; // Don't repeat this message.
}
// Get the node's text. If alphabetic chars are all uppercase, then
// success.
_TCHAR *buf;
_TCHAR ch;
buf = pn->getName();
if (!(ch = *buf))
{
_t_strstream gerrStr;
gerrStr << _T("[Cap pre action: Node with no text.]") << ends;
errOut(&gerrStr,false);
return false;
}
if (!alphabetic(ch)) // 09/22/99 AM.
return false; // NON ALPHABETIC FAILS. // 01/31/99 AM.
if (is_upper((_TUCHAR)ch)) // 12/16/01 AM.
return ok;
return false;
}
/********************************************
* FN: PREUNKNOWN
* CR: 01/25/99 AM.
* SUBJ: Check for unknown word.
* RET: True if pre succeeded.
* NOTE: Assumes this is applied to alphabetics only.
* If word hasn't been looked up, not looking it up here.
********************************************/
bool Pre::preUnknown(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
static bool warned = false;
bool ok = true;
if (args && !warned)
{
_t_strstream gerrStr;
gerrStr << _T("['Unknown' pre action: Ignoring arguments.]") << ends;
errOut(&gerrStr,false);
warned = true; // Don't repeat this message.
}
// Get the node's text. If alphabetic chars are all uppercase, then
// success.
Sym *sym;
sym = pn->getlcSym(); // Get lowercased sym.
if (sym && // 06/05/00 AM.
sym->isLooked() && !(sym->isKnown()))
return ok;
return false;
}
/********************************************
* FN: PRELENGTH
* CR: 01/31/99 AM.
* SUBJ: Check if length of token is a match.
* RET: True if pre succeeded.
********************************************/
bool Pre::preLength(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
long len = 0;
if (!Arg::num1(_T("preLength"), (DELTS*&)args, len))
return false;
if (!Arg::done(args, _T("preLength")))
return false;
return ((unsigned int) len == _tcsclen(pn->getName()));
}
/********************************************
* FN: PRELENGTHR
* CR: 03/22/99 AM.
* SUBJ: Check if length of token is in given number range.
* RET: True if pre succeeded.
********************************************/
bool Pre::preLengthr(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
long len1 = 0, len2=0;
long len = 0;
if (!Arg::num1(_T("preLength"), (DELTS*&)args, len1))
return false;
if (!Arg::num1(_T("preLength"), (DELTS*&)args, len2))
return false;
if (!Arg::done(args, _T("preLength")))
return false;
if (len1 < 0 || len2 < 0 || (len1 > len2))
{
_t_strstream gerrStr;
gerrStr << _T("[LENGTHR pre action: Bad range (") << len1 << _T(",") << len2
<< _T(")]") << ends;
errOut(&gerrStr,false);
return false;
}
len = _tcsclen(pn->getName());
if ((len >= len1) && (len <= len2))
return true;
return false;
}
/********************************************
* FN: PRENUMRANGE
* CR: 08/10/99 AM.
* SUBJ: See if numeric token is in given range.
* RET: True if pre succeeded.
* FORM: numrange(LOWNUM, HIGHNUM)
* These are INCLUSIVE numbers.
********************************************/
bool Pre::preNumrange(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
long len1 = 0, len2=0;
if (!Arg::num1(_T("preNumrange"), (DELTS*&)args, len1))
return false;
if (!Arg::num1(_T("preNumrange"), (DELTS*&)args, len2))
return false;
if (!Arg::done(args, _T("preNumrange")))
return false;
if (len1 < 0 || len2 < 0 || (len1 > len2))
{
_t_strstream gerrStr;
gerrStr << _T("[NUMRANGE pre action: Bad range (") << len1 << _T(",") << len2
<< _T(")]") << ends;
errOut(&gerrStr,false);
return false;
}
long num = 0;
_TCHAR *str;
str = pn->getName();
if (!str_to_long(str, /*UP*/ num))
{
_t_strstream gerrStr;
gerrStr << _T("[NUMRANGE pre action: Bad num=") << str << _T("]") << ends;
errOut(&gerrStr,false);
return false;
}
if (num >= len1 && num <= len2)
return true; // Number is within range.
return false;
}
/********************************************
* FN: PREDEBUG
* CR: 09/17/99 AM.
* SUBJ: Always succeed! A way for programmer to place a breakpoint.
* RET: True.
* NOTE: Programmer must set a breakpoint manually. (Would be nice to
* do what VC++ does when user sets a breakpoint.)
********************************************/
bool Pre::preDebug(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
if (!Arg::done(args, _T("preDebug")))
return false;
// SET A BREAKPOINT HERE!
return true;
}
/********************************************
* FN: PREVAR
* CR: 06/14/05 AM.
* SUBJ: Check if node's var has non-empty value.
* RET: True if pre succeeded.
********************************************/
bool Pre::preVar(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
if (!Arg::str1(_T("preVar"), (DELTS*&)args, str))
return false;
if (!Arg::done(args, _T("preVar")))
return false;
return Ivar::nodeVarNZ(pn,str);
}
/********************************************
* FN: PREVARZ
* CR: 06/16/05 AM.
* SUBJ: Check if node's var has empty value.
* RET: True if pre succeeded.
********************************************/
bool Pre::preVarz(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
if (!Arg::str1(_T("preVarz"), (DELTS*&)args, str))
return false;
if (!Arg::done(args, _T("preVarz")))
return false;
return !Ivar::nodeVarNZ(pn,str);
}
/********************************************
* FN: PREVAREQ
* CR: 06/16/05 AM.
* SUBJ: Check if node's var equals value.
* RET: True if pre succeeded.
********************************************/
bool Pre::preVareq(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
_TCHAR *sval;
long nval;
if (!Arg::str1(_T("preVareq"), (DELTS*&)args, str))
return false;
if (!Arg::str_or_num1(_T("preVareq"), (DELTS*&)args, sval,nval))
return false;
if (!Arg::done(args, _T("preVareq")))
return false;
if (sval && *sval)
return Ivar::nodeVarEQ(pn,str,sval);
else
return Ivar::nodeVarEQ(pn,str,nval);
}
/********************************************
* FN: PREVARNE
* CR: 06/16/05 AM.
* SUBJ: Check if node's var does not equal value.
* RET: True if pre succeeded.
********************************************/
bool Pre::preVarne(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
_TCHAR *sval;
long nval;
if (!Arg::str1(_T("preVareq"), (DELTS*&)args, str))
return false;
if (!Arg::str_or_num1(_T("preVareq"), (DELTS*&)args, sval,nval))
return false;
if (!Arg::done(args, _T("preVareq")))
return false;
if (sval && *sval)
return !Ivar::nodeVarEQ(pn,str,sval);
else
return !Ivar::nodeVarEQ(pn,str,nval);
}
/********************************************
* FN: PREREGEXP
* CR: 03/23/09 AM.
* SUBJ: Match node to regular expression.
* RET: True if pre succeeded.
********************************************/
bool Pre::preRegexp(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
if (!Arg::str1(_T("preRegexp"), (DELTS*&)args, str))
return false;
if (!Arg::done(args, _T("preRegexp")))
return false;
// Get node's text.
if (!pn)
return false;
_TCHAR *nstr = pn->pnStr();
bool ok = Regexp::regexp_match(nstr,str);
Chars::destroy(nstr); // Free up buffer.
return ok;
}
/********************************************
* FN: PREREGEXPI
* CR: 03/26/09 AM.
* SUBJ: Match node to regular expression. (Case insensitive)
* RET: True if pre succeeded.
********************************************/
bool Pre::preRegexpi(
Delt<Iarg> *args, // Action's arguments.
Pn *pn // Node to match.
)
{
_TCHAR *str;
if (!Arg::str1(_T("preRegexpi"), (DELTS*&)args, str))
return false;
if (!Arg::done(args, _T("preRegexpi")))
return false;
// Get node's text.
if (!pn)
return false;
_TCHAR *nstr = pn->pnStr();
bool ok = Regexp::regexpi_match(nstr,str);
Chars::destroy(nstr); // Free up buffer.
return ok;
}
| [
"dehilster@gmail.com"
] | dehilster@gmail.com |
12e84af7fd66eae284f45ea1bc7cd972b0170e97 | 7e3845226a5186494321bc8147acf19c5af5b577 | /src/demo_server/util/inc/burden_common_logic_interface.h | c1c652c1a36ea66046719b35d6325a9f6c43327c | [] | no_license | Confucius-Mencius/demo_proj | 2ef27359933b4af71b138152bd8a6a3131e3b20d | e5ef85b81b68f96d7db52ba4a63055eca9ff05c6 | refs/heads/master | 2020-04-17T02:32:45.266096 | 2019-06-08T08:53:03 | 2019-06-08T08:53:03 | 159,490,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | h | #ifndef DEMO_SERVER_UTIL_INC_BURDEN_COMMON_LOGIC_INTERFACE_H_
#define DEMO_SERVER_UTIL_INC_BURDEN_COMMON_LOGIC_INTERFACE_H_
#include "burden_logic_interface.h"
// 线程内多个模块共享的逻辑,一般不需加锁
namespace burden
{
class TheCommonLogicInterface : public CommonLogicInterface
{
public:
virtual ~TheCommonLogicInterface()
{
}
};
}
#endif // DEMO_SERVER_UTIL_INC_BURDEN_COMMON_LOGIC_INTERFACE_H_
| [
"guang11cheng@qq.com"
] | guang11cheng@qq.com |
532c4842ddc9bd5523a0fd1b4e4e4c80eedb373f | 055f5302967d6bdb59e65d97ec69f937188d27e7 | /Graphic_CW/nclgl/Window.cpp | 6f629b6e6c53d0e1556efcc1a833428792b7d93e | [] | no_license | YiZChen/Game-Graphic | f8a80e3a2fac043791345d36e860489f3f14d6e6 | f759b2ff94fa16ef8db77f2e73cc3600cba035e7 | refs/heads/master | 2021-01-01T04:52:53.879823 | 2017-07-14T18:42:42 | 2017-07-14T18:42:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,219 | cpp | #include "Window.h"
#include "Mouse.h"
#include "Keyboard.h"
Window* Window::window;
Keyboard*Window::keyboard = NULL;
Mouse*Window::mouse = NULL;
//GameTimer*Window::timer = NULL;
Window::Window(std::string title, int sizeX, int sizeY, bool fullScreen) {
renderer = NULL;
window = this;
forceQuit = false;
init = false;
mouseLeftWindow = false;
lockMouse = false;
showMouse = true;
this->fullScreen = fullScreen;
size.x = (float)sizeX; size.y = (float)sizeY;
fullScreen ? position.x = 0.0f : position.x = 100.0f;
fullScreen ? position.y = 0.0f : position.y = 100.0f;
HINSTANCE hInstance = GetModuleHandle( NULL );
////This creates the console window
// AllocConsole();
//
// int consoleHandle;
// long stdHandle;
// FILE *file;
//
// // redirect stdout
// stdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
// consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
// file = _fdopen( consoleHandle, "w" );
// *stdout = *file;
// setvbuf( stdout, NULL, _IONBF, 0 );
//
// // redirect stdin
// stdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
// file = _fdopen( consoleHandle, "r" );
// *stdin = *file;
// setvbuf( stdin, NULL, _IONBF, 0 );
////
WNDCLASSEX windowClass;
ZeroMemory(&windowClass, sizeof(WNDCLASSEX));
if(!GetClassInfoEx(hInstance,WINDOWCLASS,&windowClass)) {
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = (WNDPROC)WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
windowClass.lpszClassName = WINDOWCLASS;
if(!RegisterClassEx(&windowClass)) {
std::cout << "Window::Window(): Failed to register class!" << std::endl;
return;
}
}
if(fullScreen) {
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = sizeX; // Selected Screen Width
dmScreenSettings.dmPelsHeight = sizeY; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = 32; // Selected Bits Per Pixel
dmScreenSettings.dmDisplayFrequency = 60;
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQUENCY;
if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) {
std::cout << "Window::Window(): Failed to switch to fullscreen!" << std::endl;
return;
}
}
windowHandle = CreateWindowEx(fullScreen ? WS_EX_TOPMOST : NULL,
WINDOWCLASS, // name of the window class
title.c_str(), // title of the window
fullScreen ? WS_POPUP|WS_VISIBLE : WS_OVERLAPPEDWINDOW|WS_POPUP|WS_VISIBLE|WS_SYSMENU|WS_MAXIMIZEBOX|WS_MINIMIZEBOX, // window style
(int)position.x, // x-position of the window
(int)position.y, // y-position of the window
(int)size.x, // width of the window
(int)size.y, // height of the window
NULL, // No parent window!
NULL, // No Menus!
hInstance, // application handle
NULL); // No multiple windows!
if(!windowHandle) {
std::cout << "Window::Window(): Failed to create window!" << std::endl;
return;
}
if(!keyboard) {
keyboard = new Keyboard(windowHandle);
}
if(!mouse) {
mouse = new Mouse(windowHandle);
}
//if(!timer) {
timer = new GameTimer();
//}
elapsedMS = timer->GetMS();
Window::GetMouse()->SetAbsolutePositionBounds((unsigned int)size.x,(unsigned int)size.y);
POINT pt;
GetCursorPos(&pt);
ScreenToClient(window->windowHandle, &pt);
Window::GetMouse()->SetAbsolutePosition(pt.x,pt.y);
LockMouseToWindow(lockMouse);
ShowOSPointer(showMouse);
init = true;
}
Window::~Window(void)
{
delete keyboard;keyboard = NULL;
delete mouse; mouse = NULL;
// FreeConsole(); //Destroy the console window
}
HWND Window::GetHandle() {
return windowHandle;
}
bool Window::HasInitialised() {
return init;
}
void Window::SetRenderer(OGLRenderer* r) {
renderer = r;
if(r) {
renderer->Resize((int)size.x,(int)size.y);
}
}
bool Window::UpdateWindow() {
MSG msg;
float diff = timer->GetMS()-elapsedMS;
Window::GetMouse()->UpdateDoubleClick(diff);
Window::GetKeyboard()->UpdateHolds();
Window::GetMouse()->UpdateHolds();
while(PeekMessage(&msg,windowHandle,0,0,PM_REMOVE)) {
CheckMessages(msg);
}
elapsedMS = timer->GetMS();
return !forceQuit;
}
void Window::CheckMessages(MSG &msg) {
switch (msg.message) { // Is There A Message Waiting?
case (WM_QUIT):
case (WM_CLOSE): { // Have We Received A Quit Message?
window->ShowOSPointer(true);
window->LockMouseToWindow(false);
forceQuit = true;
}break;
case (WM_INPUT): {
UINT dwSize;
GetRawInputData((HRAWINPUT)msg.lParam, RID_INPUT, NULL, &dwSize,sizeof(RAWINPUTHEADER));
BYTE* lpb = new BYTE[dwSize];
GetRawInputData((HRAWINPUT)msg.lParam, RID_INPUT, lpb, &dwSize,sizeof(RAWINPUTHEADER));
RAWINPUT* raw = (RAWINPUT*)lpb;
if (keyboard && raw->header.dwType == RIM_TYPEKEYBOARD) {
Window::GetKeyboard()->Update(raw);
}
if (mouse && raw->header.dwType == RIM_TYPEMOUSE) {
Window::GetMouse()->Update(raw);
}
delete lpb;
}break;
default: { // If Not, Deal With Window Messages
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
}
LRESULT CALLBACK Window::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch(message) {
case(WM_DESTROY): {
window->ShowOSPointer(true);
window->LockMouseToWindow(false);
PostQuitMessage(0);
window->forceQuit = true;
} break;
case (WM_ACTIVATE): {
//int fMinimized = (BOOL) HIWORD(wParam);
if(LOWORD(wParam) == WA_INACTIVE) {
ReleaseCapture();
ClipCursor(NULL);
mouse->Sleep();
keyboard->Sleep();
}
else{
if(window->init) {
mouse->Wake();
keyboard->Wake();
POINT pt;
GetCursorPos(&pt);
ScreenToClient(window->windowHandle, &pt);
mouse->SetAbsolutePosition(pt.x,pt.y);
if(window->lockMouse) {
window->LockMouseToWindow(true);
}
}
}
return 0;
}break;
case (WM_LBUTTONDOWN): {
if(window->lockMouse) {
window->LockMouseToWindow(true);
}
}break;
case (WM_MOUSEMOVE): {
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = window->windowHandle;
TrackMouseEvent(&tme);
if(window->mouseLeftWindow) {
window->mouseLeftWindow = false;
mouse->Wake();
keyboard->Wake();
POINT pt;
GetCursorPos(&pt);
ScreenToClient(window->windowHandle, &pt);
mouse->SetAbsolutePosition(pt.x,pt.y);
}
}break;
case(WM_MOUSELEAVE):{
window->mouseLeftWindow = true;
mouse->Sleep();
keyboard->Sleep();
}break;
case(WM_SIZE): {
window->size.x = (float)LOWORD(lParam);
window->size.y = (float)HIWORD(lParam);
if(window->renderer) {
window->renderer->Resize(LOWORD(lParam),HIWORD(lParam));
}
if(window->init) {
mouse->SetAbsolutePositionBounds(LOWORD(lParam),HIWORD(lParam));
POINT pt;
GetCursorPos(&pt);
ScreenToClient(window->windowHandle, &pt);
mouse->SetAbsolutePosition(pt.x,pt.y);
window->LockMouseToWindow(window->lockMouse);
}
}break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
void Window::LockMouseToWindow(bool lock) {
lockMouse = lock;
if(lock) {
RECT windowRect;
GetWindowRect (window->windowHandle, &windowRect);
SetCapture(window->windowHandle);
ClipCursor(&windowRect);
POINT pt;
GetCursorPos(&pt);
ScreenToClient(window->windowHandle, &pt);
Window::GetMouse()->SetAbsolutePosition(pt.x,pt.y);
}
else{
ReleaseCapture();
ClipCursor(NULL);
}
}
void Window::ShowOSPointer(bool show) {
if(show == showMouse) {
return; //ShowCursor does weird things, due to being a counter internally...
}
showMouse = show;
if(show) {
ShowCursor(1);
}
else{
ShowCursor(0);
}
} | [
"cyz8889@sina.cn"
] | cyz8889@sina.cn |
18ee311013ee5fe64414d5073f3212b97a6e42c5 | f43cb67096faba4810925f1c98bc57e6f0b38fb1 | /Pong/block.cpp | 189bd64156f8f9fd15448f37df284df972e61bfe | [] | no_license | MichaelKhalil/Ping-Pong-Game | 486837d427a9f5c1257d71954bfca43bbe6d1fcd | d2b8c00c6fc6cfb59489955b0864c18a4890d36a | refs/heads/master | 2021-01-17T17:49:39.196465 | 2016-07-01T00:11:39 | 2016-07-01T00:11:39 | 61,458,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 323 | cpp |
#include "block.h"
block::block(sf::RenderWindow* window){
this->Load("block.png");
}
void block::Update(){
Entity::Update();
}
void block::blockReset(int number){
switch(number){
case 0:
setPosition(280, 401);
break;
case 1:
setPosition(400, 180);
break;
case 2:
setPosition(550, 400);
break;
}
}
| [
"michael.khalil123@gmail.com"
] | michael.khalil123@gmail.com |
e6a60c24cf4ae6dbe0e441f84668e0ea23f67d5a | f18cd24af16476f7bf0e80e14c2b69dc7cc2de70 | /cpp1/ItemToPurchase.h | e9a4f006a6cef57c0288f0d687aad83f4e5f24a8 | [] | no_license | kzbigboss/2019-bc-spring-cs212 | 838ee3cf6e60f22b25c0ee2efb34eaa80a593bbc | 6c10555588061458c32625170e4af64fc526a008 | refs/heads/master | 2020-05-18T13:29:25.334343 | 2019-05-15T16:34:30 | 2019-05-15T16:34:30 | 184,440,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 393 | h | #include <string>
class ItemToPurchase {
std::string itemName;
double itemPrice;
double itemQuantity;
public:
ItemToPurchase(std::string, double, double);
ItemToPurchase();
double itemTotal();
std::string toString();
void MakeBlankItem(ItemToPurchase& inputItempToPurchase);
void PrintItemCost(ItemToPurchase inputItemToPurchase);
};
| [
"noreply@github.com"
] | noreply@github.com |
2d9f2ae77a53124b4c7561296c1bbd54ea0d0e5c | 33303d4a07598139320c796f07c614d5e901e6ef | /cpp/oneapi/dal/algo/decision_forest/backend/gpu/infer_train_cls_kernel_dpc_test.cpp | a555c0d3b4b80774b5de4422cd03cb8fb33fb77e | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Intel",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"MIT",
"Zlib"
] | permissive | bysheva/oneDAL | 7eb33dbb5aa3393c032f4e68cc1cb93fc50c0c3f | 84cb27c9afde49320670006b4ff0791ee90d73d1 | refs/heads/master | 2023-05-05T21:18:45.345237 | 2021-03-01T08:00:08 | 2021-03-01T08:00:08 | 284,727,302 | 0 | 2 | Apache-2.0 | 2021-05-29T00:02:24 | 2020-08-03T14:49:26 | C++ | UTF-8 | C++ | false | false | 14,822 | cpp | /*******************************************************************************
* Copyright 2020-2021 Intel Corporation
*
* 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 <CL/sycl.hpp>
#include "gtest/gtest.h"
#include "oneapi/dal/algo/decision_forest/train.hpp"
#include "oneapi/dal/algo/decision_forest/infer.hpp"
#include "oneapi/dal/algo/decision_forest/test/utils.hpp"
using namespace oneapi;
namespace df = oneapi::dal::decision_forest;
using df_hist_classifier = df::descriptor<float, df::method::hist, df::task::classification>;
using df_dense_classifier = df::descriptor<float, df::method::dense, df::task::classification>;
TEST(df_bad_arg_tests, test_checks_for_inputs_exceed_int32) {
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t column_count = 2;
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_class_count(0xFFFFFFFF),
x_train_table,
y_train_table)),
dal::domain_error);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_min_observations_in_leaf_node(0xFFFFFFFF),
x_train_table,
y_train_table)),
dal::domain_error);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_features_per_node(0xFFFFFFFF),
x_train_table,
y_train_table)),
dal::domain_error);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_max_bins(0xFFFFFFFF),
x_train_table,
y_train_table)),
dal::domain_error);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_min_bin_size(0xFFFFFFFF),
x_train_table,
y_train_table)),
dal::domain_error);
}
TEST(df_bad_arg_tests, test_overflow_checks_in_train) {
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t column_count = 2;
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
ASSERT_THROW((dal::train(queue,
df_hist_classifier{}.set_tree_count(0x7FFFFFFFFFFFFFFF),
x_train_table,
y_train_table)),
dal::internal_error);
}
TEST(df_bad_arg_tests, set_infer_params_over_int32) {
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t row_count_test = 3;
constexpr std::int64_t column_count = 2;
const float x_train_host[] = { -2.f, -1.f, -1.f, -1.f, -1.f, -2.f,
+1.f, +1.f, +1.f, +2.f, +2.f, +1.f };
const float y_train_host[] = { 0.f, 0.f, 0.f, 1.f, 1.f, 1.f };
const float x_test_host[] = { -1.f, -1.f, 2.f, 2.f, 3.f, 2.f };
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
std::memcpy(x_train, x_train_host, sizeof(float) * row_count_train * column_count);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
std::memcpy(y_train, y_train_host, sizeof(float) * row_count_train);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
auto x_test = sycl::malloc_shared<float>(row_count_test * column_count, queue);
ASSERT_NE(x_test, nullptr);
std::memcpy(x_test, x_test_host, sizeof(float) * row_count_test * column_count);
const auto x_test_table = dal::homogen_table::wrap(queue, x_test, row_count_test, column_count);
const auto df_train_desc = df_hist_classifier{};
const auto result_train = dal::train(queue, df_train_desc, x_train_table, y_train_table);
ASSERT_THROW((dal::infer(queue,
df_dense_classifier{}.set_class_count(0xFFFFFFFF),
result_train.get_model(),
x_test_table)),
dal::domain_error);
}
TEST(infer_and_train_cls_kernels_test, can_process_simple_case_default_params) {
constexpr double accuracy_threshold = 0.05;
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t row_count_test = 3;
constexpr std::int64_t column_count = 2;
const float x_train_host[] = { -2.f, -1.f, -1.f, -1.f, -1.f, -2.f,
+1.f, +1.f, +1.f, +2.f, +2.f, +1.f };
const float y_train_host[] = { 0.f, 0.f, 0.f, 1.f, 1.f, 1.f };
const float x_test_host[] = { -1.f, -1.f, 2.f, 2.f, 3.f, 2.f };
const float y_test_host[] = { 0.f, 1.f, 1.f };
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
std::memcpy(x_train, x_train_host, sizeof(float) * row_count_train * column_count);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
std::memcpy(y_train, y_train_host, sizeof(float) * row_count_train);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
auto x_test = sycl::malloc_shared<float>(row_count_test * column_count, queue);
ASSERT_NE(x_test, nullptr);
std::memcpy(x_test, x_test_host, sizeof(float) * row_count_test * column_count);
const auto x_test_table = dal::homogen_table::wrap(queue, x_test, row_count_test, column_count);
const auto df_train_desc = df_hist_classifier{};
const auto df_infer_desc = df_dense_classifier{};
const auto result_train = dal::train(queue, df_train_desc, x_train_table, y_train_table);
ASSERT_EQ(!(result_train.get_var_importance().has_data()), true);
ASSERT_EQ(!(result_train.get_oob_err().has_data()), true);
ASSERT_EQ(!(result_train.get_oob_err_per_observation().has_data()), true);
// infer on CPU for now
const auto result_infer =
dal::infer(queue, df_infer_desc, result_train.get_model(), x_test_table);
auto labels_table = result_infer.get_labels();
ASSERT_EQ(labels_table.has_data(), true);
ASSERT_EQ(labels_table.get_row_count(), row_count_test);
ASSERT_EQ(labels_table.get_column_count(), 1);
ASSERT_EQ(!result_infer.get_probabilities().has_data(), true);
ASSERT_LE(calculate_classification_error(labels_table, y_test_host), accuracy_threshold);
}
TEST(infer_and_train_cls_kernels_test, can_process_simple_case_non_default_params) {
constexpr double accuracy_threshold = 0.05;
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t row_count_test = 3;
constexpr std::int64_t column_count = 2;
constexpr std::int64_t tree_count = 10;
constexpr std::int64_t class_count = 2;
const float x_train_host[] = { -2.f, -1.f, -1.f, -1.f, -1.f, -2.f,
+1.f, +1.f, +1.f, +2.f, +2.f, +1.f };
const float y_train_host[] = { 0.f, 0.f, 0.f, 1.f, 1.f, 1.f };
const float x_test_host[] = { -1.f, -1.f, 2.f, 2.f, 3.f, 2.f };
const float y_test_host[] = { 0.f, 1.f, 1.f };
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
std::memcpy(x_train, x_train_host, sizeof(float) * row_count_train * column_count);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
std::memcpy(y_train, y_train_host, sizeof(float) * row_count_train);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
auto x_test = sycl::malloc_shared<float>(row_count_test * column_count, queue);
ASSERT_NE(x_test, nullptr);
std::memcpy(x_test, x_test_host, sizeof(float) * row_count_test * column_count);
const auto x_test_table = dal::homogen_table::wrap(queue, x_test, row_count_test, column_count);
const auto df_train_desc =
df_hist_classifier{}
.set_class_count(class_count)
.set_tree_count(tree_count)
.set_features_per_node(1)
.set_min_observations_in_leaf_node(2)
.set_variable_importance_mode(df::variable_importance_mode::mdi)
.set_error_metric_mode(df::error_metric_mode::out_of_bag_error |
df::error_metric_mode::out_of_bag_error_per_observation);
const auto df_infer_desc =
df_dense_classifier{}
.set_infer_mode(df::infer_mode::class_labels | df::infer_mode::class_probabilities)
.set_voting_mode(df::voting_mode::unweighted);
const auto result_train = dal::train(queue, df_train_desc, x_train_table, y_train_table);
ASSERT_EQ(result_train.get_model().get_tree_count(), tree_count);
ASSERT_EQ(result_train.get_model().get_class_count(), class_count);
ASSERT_EQ(result_train.get_var_importance().has_data(), true);
ASSERT_EQ(result_train.get_var_importance().get_column_count(), column_count);
ASSERT_EQ(result_train.get_var_importance().get_row_count(), 1);
ASSERT_EQ(result_train.get_oob_err().has_data(), true);
ASSERT_EQ(result_train.get_oob_err().get_row_count(), 1);
ASSERT_EQ(result_train.get_oob_err().get_column_count(), 1);
ASSERT_EQ(result_train.get_oob_err_per_observation().has_data(), true);
ASSERT_EQ(result_train.get_oob_err_per_observation().get_row_count(), row_count_train);
ASSERT_EQ(result_train.get_oob_err_per_observation().get_column_count(), 1);
verify_oob_err_vs_oob_err_per_observation(result_train.get_oob_err(),
result_train.get_oob_err_per_observation(),
accuracy_threshold);
const auto result_infer =
dal::infer(queue, df_infer_desc, result_train.get_model(), x_test_table);
auto labels_table = result_infer.get_labels();
ASSERT_EQ(labels_table.has_data(), true);
ASSERT_EQ(labels_table.get_row_count(), row_count_test);
ASSERT_EQ(labels_table.get_column_count(), 1);
ASSERT_EQ(result_infer.get_probabilities().has_data(), true);
ASSERT_EQ(result_infer.get_probabilities().get_column_count(), class_count);
ASSERT_EQ(result_infer.get_probabilities().get_row_count(), row_count_test);
ASSERT_LE(calculate_classification_error(labels_table, y_test_host), accuracy_threshold);
}
TEST(infer_and_train_cls_kernels_test, can_process_corner_case) {
constexpr double accuracy_threshold = 0.05;
constexpr std::int64_t row_count_train = 3;
constexpr std::int64_t row_count_test = 1;
constexpr std::int64_t column_count = 1;
const float x_train_host[] = { -1.f, 2.f, 2.3f };
const float y_train_host[] = { 0.f, 1.f, 1.f };
const float x_test_host[] = { 1.f };
const float y_test_host[] = { 1.f };
auto selector = sycl::gpu_selector();
auto queue = sycl::queue(selector);
auto x_train = sycl::malloc_shared<float>(row_count_train * column_count, queue);
ASSERT_NE(x_train, nullptr);
std::memcpy(x_train, x_train_host, sizeof(float) * row_count_train * column_count);
const auto x_train_table =
dal::homogen_table::wrap(queue, x_train, row_count_train, column_count);
auto y_train = sycl::malloc_shared<float>(row_count_train, queue);
ASSERT_NE(y_train, nullptr);
std::memcpy(y_train, y_train_host, sizeof(float) * row_count_train);
const auto y_train_table = dal::homogen_table::wrap(queue, y_train, row_count_train, 1);
auto x_test = sycl::malloc_shared<float>(row_count_test * column_count, queue);
ASSERT_NE(x_test, nullptr);
std::memcpy(x_test, x_test_host, sizeof(float) * row_count_test * column_count);
const auto x_test_table = dal::homogen_table::wrap(queue, x_test, row_count_test, column_count);
const auto df_train_desc = df_hist_classifier{}
.set_class_count(2)
.set_tree_count(10)
.set_min_observations_in_leaf_node(8);
const auto df_infer_desc = df_dense_classifier{}.set_class_count(2);
const auto result_train = dal::train(queue, df_train_desc, x_train_table, y_train_table);
// infer on CPU for now
const auto result_infer =
dal::infer(queue, df_infer_desc, result_train.get_model(), x_test_table);
auto labels_table = result_infer.get_labels();
ASSERT_EQ(labels_table.has_data(), true);
ASSERT_EQ(labels_table.get_row_count(), row_count_test);
ASSERT_EQ(labels_table.get_column_count(), 1);
ASSERT_LE(calculate_classification_error(labels_table, y_test_host), accuracy_threshold);
}
| [
"noreply@github.com"
] | noreply@github.com |
0a98edbd9e9d10a460b03e733b7ba42a405b19e4 | 4b529e36321aa3e7f14f79305bc18c43bd8e4ba1 | /Tests/Solar-System/Source/Utilities/utilities.h | 43e3ce70c327fdd9c17f538c7ae8c6a3069c80cc | [] | no_license | zhangxuelei86/OpenGL-Engine | 26b07a5559629a626227d97cc9a0fc03b98158bd | b5e60d88e5aba313e38b6c4f5fe03c1e6093132c | refs/heads/master | 2022-03-13T00:38:23.263618 | 2017-07-07T02:21:37 | 2017-07-07T02:21:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,049 | h | #pragma once
// External Headers
#include "stb_image.h"
#include "freeglut.h"
#include "glew.h"
#include "SOIL2.h"
#include "spdlog\spdlog.h"
// System Headers
#include <string>
#include <vector>
#include <fstream>
namespace Rendering {
namespace Utilities {
/* Load DDS Texture - using SOIL2 again */
GLuint LoadDDSTexture(const std::string& file)
{
GLuint textureID = SOIL_load_OGL_texture(file.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
return textureID;
}
/* Load faces of a cube map texture */
unsigned int LoadCubeMapTexture(std::vector<std::string> faces) {
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data
);
stbi_image_free(data);
spdlog::get("console")->info("Cube Map Texture Face {0} successfully loaded!", faces[i]);
}
else {
spdlog::get("console")->error("Failed to load cube map face at path : {0}", faces[i]);
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
}
} | [
"pranav.srinivas.kumar@gmail.com"
] | pranav.srinivas.kumar@gmail.com |
0966a38a9e4073161aaa7c63dcbc5fdcbe418a35 | 7cf0595bcffa98c88df20bc13bc2672a127a448b | /src/cfgdecode/CfgDecoder.hpp | 726daaa417dc5dbd524ba13cf69f5fdbcf01be17 | [
"BSD-2-Clause-Views"
] | permissive | CSLDepend/bil | bbff795b65a8bc0f2cf2fd487f52fcead7083aa4 | d5f201afcfa54606db3f368cb34fa146c045b36c | refs/heads/master | 2021-05-03T17:10:36.745918 | 2016-10-27T18:56:24 | 2016-10-27T18:56:24 | 72,053,785 | 0 | 0 | null | 2016-10-26T23:42:29 | 2016-10-26T23:42:29 | null | UTF-8 | C++ | false | false | 2,073 | hpp | /**
* \file CfgDecoder.hpp
* \brief Contains declaration of CfgDecoder class.
*/
#pragma once
#ifndef BIL_CFGDECODER_HPP
#define BIL_CFGDECODER_HPP
#include <correlation/cfgextraction/CfgExtractor.hpp>
#include <mappingdb/DeviceCfgDb.hpp>
#include <xdl/model/PIPRef.hpp>
#include <xdlrc/model/Device.hpp>
namespace bil {
/**
* \brief Decodes configuration data by using a configuration data base.
*
* This class will decode binary configuration data to lists of active PIPs
* and configurated primitive sites. For this task it needs a configuration
* data base for the device the data is for, and a description of the device.
*/
class CfgDecoder {
public:
/**********************************************************************/
/* DECODING */
/**********************************************************************/
/**
* \brief Decodes configuration data.
* \param extractor The extractor object to get configuration data.
* \param db The configuration data base.
* \param device The device the configuration is for.
* \throw .
*/
void decode(CfgExtractor& extractor, const DeviceCfgDb& db, const Device& device);
/**********************************************************************/
/* DECODING RESULT LISTS */
/**********************************************************************/
/**
* \brief Gets PIP result list.
* \return The PIP list.
*/
const PIPRefs& pipRefs() const;
/**
* \todo Result lits with configurated primitive sites.
*/
private:
void decodeTileType(CfgExtractor& extractor, const TileTypeCfgDb& tileTypeDb, const Tiles& tiles);
void decodeTilePIPs(const PIPControlSets& pipControlSets, size_t tileIndex);
PIPRefs m_pipRefs;
std::vector<boost::uint32_t> m_buffer;
};
}
#endif
| [
"florianbenz@florianbenz.de"
] | florianbenz@florianbenz.de |
4524dc26dc22dbed3bc36cb73849383eef9ba5c0 | 3b149ff4c5bdd953a901d709ca38b03f464e348a | /problem_solving_class/DT06/2/DT06.V2.cpp | 3b2fb858702dfe328e63aa78e650bfdd49ebef83 | [] | no_license | T208FOR2/T208FOR2_2015 | 150dcffa6139d29258b2b570e08e01fb36dec31e | 030dfa76926ddbbc5bbf158b969bbbd7ed295358 | refs/heads/master | 2016-09-06T05:51:08.040266 | 2015-11-11T20:02:07 | 2015-11-11T20:02:07 | 40,606,700 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | cpp | //
// main.cpp
// DT07.verkefni2
//
// Created by Silja Guðbjörg Tryggvadóttir on 29/09/15.
// Copyright (c) 2015 siljagudbjorg. All rights reserved.
//
/* Þið eigið að skrifa tvo föll sem tekur við kvik fylki og skilar max eða min af stökunum af fylkinu. Þið byrjið á að bua til kvik fylki af stærð n sem notandi slær inn og svo eigi þið að setja inn tölurnar sem koma inn frá notandanum. Eftir það eigi þið að nýta ykkur max og min föllinn og prenta út hvað var stærsta stakið og það minnsta. */
#include <iostream>
using namespace std;
int findMax(int *array, int size);
int findMin(int *array, int size);
int main()
{
int n = 0, max = 0, min = 0;
cin >> n;
int *array;
array = new int[n];
for (int i = 0; i < n; i++)
{
cin >> array[i];
}
max = findMax(array, n);
min = findMin(array, n);
cout << "Maximum value: " << max << endl;
cout << "Minimum value: " << min << endl;
delete [] array;
return 0;
}
int findMax(int *array, int size)
{
int max = array[0];
for (int i = 0; i < size; i++)
{
if (max < array[i])
{
max = array[i];
}
}
return max;
}
int findMin(int *array, int size)
{
int min = array[0];
for (int i = 1; i < size; i++)
{
if (min > array[i])
{
min = array[i];
}
}
return min;
} | [
"kristofert13@ru.is"
] | kristofert13@ru.is |
698df84d24b094dda13fea4764da66325fc8f92c | 9ad65c9b2cbacc5b88c22cade2170e2a009ba897 | /Project02/sample.cpp | c802e2cf0321d6c8cc0cba15ab8d8cec1ff9d594 | [] | no_license | bouyal/CS450 | 121408ccb3fe0a80d8a92875f45afc758aa94d97 | 26143aa5dab4cc633ab4b6828c310499fa6a296b | refs/heads/master | 2023-03-16T01:10:19.389125 | 2018-11-05T11:37:17 | 2018-11-05T11:37:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,035 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define _USE_MATH_DEFINES
#include <math.h>
#ifdef WIN32
#include <windows.h>
#pragma warning(disable:4996)
#include "glew.h"
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include "heli.550"
// This is a sample OpenGL / GLUT program
//
// The objective is to draw a 3d object and change the color of the axes
// with a glut menu
//
// The left mouse button does rotation
// The middle mouse button does scaling
// The user interface allows:
// 1. The axes to be turned on and off
// 2. The color of the axes to be changed
// 3. Debugging to be turned on and off
// 4. Depth cueing to be turned on and off
// 5. The projection to be changed
// 6. The transformations to be reset
// 7. The program to quit
//
// Author: Alan Neads
// NOTE: There are a lot of good reasons to use const variables instead
// of #define's. However, Visual C++ does not allow a const variable
// to be used as an array size or as the case in a switch( ) statement. So in
// the following, all constants are const variables except those which need to
// be array sizes or cases in switch( ) statements. Those are #defines.
// title of these windows:
const char *WINDOWTITLE = { "OpenGL Project 02 -- Alan Neads" };
const char *GLUITITLE = { "User Interface Window" };
// what the glui package defines as true and false:
const int GLUITRUE = { true };
const int GLUIFALSE = { false };
// the escape key:
#define ESCAPE 0x1b
// initial window size:
const int INIT_WINDOW_SIZE[2] = { 1024, 768 };
// size of the box:
const float BOXSIZE = { 2.f };
// multiplication factors for input interaction:
// (these are known from previous experience)
const float ANGFACT = { 1. };
const float SCLFACT = { 0.005f };
// minimum allowable scale factor:
const float MINSCALE = { 0.05f };
// active mouse buttons (or them together):
const int LEFT = { 4 };
const int MIDDLE = { 2 };
const int RIGHT = { 1 };
// which projection:
enum Projections
{
ORTHO,
PERSP
};
// which button:
enum ButtonVals
{
RESET,
QUIT
};
// window background color (rgba):
const GLfloat BACKCOLOR[ ] = { 0., 0., 0., 1. };
// line width for the axes:
const GLfloat AXES_WIDTH = { 3. };
float Time;
#define MS_IN_THE_ANIMATION_CYCLE 10000
// blade parameters
#define BLADE_SPINNING_MULTIPLIER 20
#define BLADE_ROTATION_RATIO 3
// the color numbers:
// this order must match the radio button order
enum Colors
{
RED,
YELLOW,
GREEN,
CYAN,
BLUE,
MAGENTA,
WHITE,
BLACK
};
char * ColorNames[ ] =
{
"Red",
"Yellow",
"Green",
"Cyan",
"Blue",
"Magenta",
"White",
"Black"
};
// the color definitions:
// this order must match the menu order
const GLfloat Colors[ ][3] =
{
{ 1., 0., 0. }, // red
{ 1., 1., 0. }, // yellow
{ 0., 1., 0. }, // green
{ 0., 1., 1. }, // cyan
{ 0., 0., 1. }, // blue
{ 1., 0., 1. }, // magenta
{ 1., 1., 1. }, // white
{ 0., 0., 0. }, // black
};
// fog parameters:
const GLfloat FOGCOLOR[4] = { .0, .0, .0, 1. };
const GLenum FOGMODE = { GL_LINEAR };
const GLfloat FOGDENSITY = { 0.30f };
const GLfloat FOGSTART = { 1.5 };
const GLfloat FOGEND = { 4. };
// non-constant global variables:
int ActiveButton; // current button that is down
GLuint AxesList; // list to hold the axes
int AxesOn; // != 0 means to draw the axes
int DebugOn; // != 0 means to print debugging info
int DepthCueOn; // != 0 means to use intensity depth cueing
int DepthBufferOn; // != 0 means to use the z-buffer
int DepthFightingOn; // != 0 means to use the z-buffer
int MainWindow; // window id for main graphics window
float Scale; // scaling factor
int WhichColor; // index into Colors[ ]
int WhichProjection; // ORTHO or PERSP
int Xmouse, Ymouse; // mouse values
float Xrot, Yrot; // rotation angles in degrees
int InteriorOn; // we're looking inside the helicopter
GLuint CustomList; // My custom shape
GLuint HelicopterList; // My custom shape
GLuint HelicopterBladeList; // My custom shape
// function prototypes:
void Animate( );
void Display( );
void DoAxesMenu( int );
void DoColorMenu( int );
void DoDepthBufferMenu( int );
void DoDepthFightingMenu( int );
void DoInteriorView(int);
void DoDepthMenu( int );
void DoDebugMenu( int );
void DoMainMenu( int );
void DoProjectMenu( int );
void DoRasterString( float, float, float, char * );
void DoStrokeString( float, float, float, float, char * );
float ElapsedSeconds( );
void InitGraphics( );
void InitLists( );
void DrawTriangle(GLfloat*, GLfloat*, GLfloat*, GLfloat*, GLfloat*, int, int, float);
void InitMenus( );
void Keyboard( unsigned char, int, int );
void MouseButton( int, int, int, int );
void MouseMotion( int, int );
void Reset( );
void Resize( int, int );
void Visibility( int );
void Axes( float );
void HsvRgb( float[3], float [3] );
float Dot(float v1[3], float v2[3]);
void Cross(float v1[3], float v2[3], float vout[3]);
float Unit(float vin[3], float vout[3]);
// main program:
int
main( int argc, char *argv[ ] )
{
// turn on the glut package:
// (do this before checking argc and argv since it might
// pull some command line arguments out)
glutInit( &argc, argv );
// setup all the graphics stuff:
InitGraphics( );
// create the display structures that will not change:
InitLists( );
// init all the global variables used by Display( ):
// this will also post a redisplay
Reset( );
// setup all the user interface stuff:
InitMenus( );
// draw the scene once and wait for some interaction:
// (this will never return)
glutSetWindow( MainWindow );
glutMainLoop( );
// this is here to make the compiler happy:
return 0;
}
// this is where one would put code that is to be called
// everytime the glut main loop has nothing to do
//
// this is typically where animation parameters are set
//
// do not call Display( ) from here -- let glutMainLoop( ) do it
void
Animate( )
{
// put animation stuff in here -- change some global variables
// for Display( ) to find:
int ms = glutGet(GLUT_ELAPSED_TIME); // milliseconds
ms %= MS_IN_THE_ANIMATION_CYCLE;
Time = (float)ms / (float)MS_IN_THE_ANIMATION_CYCLE; // [ 0., 1. )
// force a call to Display( ) next time it is convenient:
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// draw the complete scene:
void
Display( )
{
if( DebugOn != 0 )
{
fprintf( stderr, "Display\n" );
}
// set which window we want to do the graphics into:
glutSetWindow( MainWindow );
// erase the background:
glDrawBuffer( GL_BACK );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if( DepthBufferOn != 0 )
glEnable( GL_DEPTH_TEST );
else
glDisable( GL_DEPTH_TEST );
// specify shading to be flat:
glShadeModel( GL_FLAT );
// set the viewport to a square centered in the window:
GLsizei vx = glutGet( GLUT_WINDOW_WIDTH );
GLsizei vy = glutGet( GLUT_WINDOW_HEIGHT );
GLsizei v = vx < vy ? vx : vy; // minimum dimension
GLint xl = ( vx - v ) / 2;
GLint yb = ( vy - v ) / 2;
glViewport( xl, yb, v, v );
// set the viewing volume:
// remember that the Z clipping values are actually
// given as DISTANCES IN FRONT OF THE EYE
// USE gluOrtho2D( ) IF YOU ARE DOING 2D !
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );
if( WhichProjection == ORTHO )
glOrtho( -3., 3., -3., 3., 0.1, 1000. );
else
gluPerspective( 90., 1., 0.1, 1000. );
// place the objects into the scene:
glMatrixMode( GL_MODELVIEW );
glLoadIdentity( );
if (InteriorOn == 1) {
// we're inside
// set the eye position, look-at position, and up-vector:
gluLookAt(-0.4, 1.8, -4.9, 0.0, 0.0, -10.0, 0., 1., 0.);
} else {
// we're outside
// set the eye position, look-at position, and up-vector:
gluLookAt(0.0, 0.0, 3.0, 0., 0., 0., 0., 1., 0.);
// rotate the scene:
glRotatef((GLfloat)Yrot, 0., 1., 0.);
glRotatef((GLfloat)Xrot, 1., 0., 0.);
// uniformly scale the scene:
if (Scale < MINSCALE)
Scale = MINSCALE;
glScalef((GLfloat)Scale, (GLfloat)Scale, (GLfloat)Scale);
}
// set the fog parameters:
if( DepthCueOn != 0 )
{
glFogi( GL_FOG_MODE, FOGMODE );
glFogfv( GL_FOG_COLOR, FOGCOLOR );
glFogf( GL_FOG_DENSITY, FOGDENSITY );
glFogf( GL_FOG_START, FOGSTART );
glFogf( GL_FOG_END, FOGEND );
glEnable( GL_FOG );
}
else
{
glDisable( GL_FOG );
}
// possibly draw the axes:
if( AxesOn != 0 )
{
glColor3fv( &Colors[WhichColor][0] );
glCallList( AxesList );
}
// since we are using glScalef( ), be sure normals get unitized:
glEnable( GL_NORMALIZE );
// draw the helicopter and stuff
glPushMatrix();
glCallList(HelicopterList);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 2.9f, -2.0f);
glRotatef( 90.0f, 1.0f, 0.0f, 0.0f );
glRotatef(360.0f * Time * BLADE_SPINNING_MULTIPLIER, 0.0f, 0.0f, 1.0f );
glScalef(5.0f, 5.0f, 5.0f);
glCallList(HelicopterBladeList);
glPopMatrix();
glPushMatrix();
glTranslatef(0.5f, 2.5f, 9.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
glRotatef(360.0f * Time * BLADE_SPINNING_MULTIPLIER * BLADE_ROTATION_RATIO, 0.0f, 0.0f, 1.0f);
glScalef(1.5f, 1.5f, 1.5f);
glCallList(HelicopterBladeList);
glPopMatrix();
// draw the custom object:
glPushMatrix();
glTranslatef(0.0f, 0.0f, -15.0f);
glScalef(4.0f, 4.0f, 4.0f);
glCallList(CustomList);
glPopMatrix();
// swap the double-buffered framebuffers:
glutSwapBuffers( );
// be sure the graphics buffer has been sent:
// note: be sure to use glFlush( ) here, not glFinish( ) !
glFlush( );
}
void
DoAxesMenu( int id )
{
AxesOn = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoColorMenu( int id )
{
WhichColor = id - RED;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoDebugMenu( int id )
{
DebugOn = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoDepthBufferMenu( int id )
{
DepthBufferOn = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoDepthFightingMenu( int id )
{
DepthFightingOn = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoInteriorViewMenu(int id)
{
InteriorOn = id;
if (id == 0) {
Scale = 0.2;
Xrot = 15.0;
Yrot = -45.0;
} else {
Scale = 5.0;
Xrot = 0.0;
Yrot = 0.0;
}
glutSetWindow(MainWindow);
glutPostRedisplay();
}
void
DoDepthMenu( int id )
{
DepthCueOn = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// main menu callback:
void
DoMainMenu( int id )
{
switch( id )
{
case RESET:
Reset( );
break;
case QUIT:
// gracefully close out the graphics:
// gracefully close the graphics window:
// gracefully exit the program:
glutSetWindow( MainWindow );
glFinish( );
glutDestroyWindow( MainWindow );
exit( 0 );
break;
default:
fprintf( stderr, "Don't know what to do with Main Menu ID %d\n", id );
}
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
void
DoProjectMenu( int id )
{
WhichProjection = id;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// use glut to display a string of characters using a raster font:
void
DoRasterString( float x, float y, float z, char *s )
{
glRasterPos3f( (GLfloat)x, (GLfloat)y, (GLfloat)z );
char c; // one character to print
for( ; ( c = *s ) != '\0'; s++ )
{
glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, c );
}
}
// use glut to display a string of characters using a stroke font:
void
DoStrokeString( float x, float y, float z, float ht, char *s )
{
glPushMatrix( );
glTranslatef( (GLfloat)x, (GLfloat)y, (GLfloat)z );
float sf = ht / ( 119.05f + 33.33f );
glScalef( (GLfloat)sf, (GLfloat)sf, (GLfloat)sf );
char c; // one character to print
for( ; ( c = *s ) != '\0'; s++ )
{
glutStrokeCharacter( GLUT_STROKE_ROMAN, c );
}
glPopMatrix( );
}
// return the number of seconds since the start of the program:
float
ElapsedSeconds( )
{
// get # of milliseconds since the start of the program:
int ms = glutGet( GLUT_ELAPSED_TIME );
// convert it to seconds:
return (float)ms / 1000.f;
}
// initialize the glui window:
void
InitMenus( )
{
glutSetWindow( MainWindow );
int numColors = sizeof( Colors ) / ( 3*sizeof(int) );
int colormenu = glutCreateMenu( DoColorMenu );
for( int i = 0; i < numColors; i++ )
{
glutAddMenuEntry( ColorNames[i], i );
}
int axesmenu = glutCreateMenu( DoAxesMenu );
glutAddMenuEntry( "Off", 0 );
glutAddMenuEntry( "On", 1 );
int depthcuemenu = glutCreateMenu( DoDepthMenu );
glutAddMenuEntry( "Off", 0 );
glutAddMenuEntry( "On", 1 );
int depthbuffermenu = glutCreateMenu( DoDepthBufferMenu );
glutAddMenuEntry( "Off", 0 );
glutAddMenuEntry( "On", 1 );
int depthfightingmenu = glutCreateMenu( DoDepthFightingMenu );
glutAddMenuEntry( "Off", 0 );
glutAddMenuEntry( "On", 1 );
int interiormenu = glutCreateMenu( DoInteriorViewMenu );
glutAddMenuEntry("Off", 0);
glutAddMenuEntry("On", 1);
int debugmenu = glutCreateMenu( DoDebugMenu );
glutAddMenuEntry( "Off", 0 );
glutAddMenuEntry( "On", 1 );
int projmenu = glutCreateMenu( DoProjectMenu );
glutAddMenuEntry( "Orthographic", ORTHO );
glutAddMenuEntry( "Perspective", PERSP );
int mainmenu = glutCreateMenu( DoMainMenu );
glutAddSubMenu("Interior View", interiormenu);
glutAddSubMenu( "Axes", axesmenu);
glutAddSubMenu( "Colors", colormenu);
glutAddSubMenu( "Depth Buffer", depthbuffermenu);
glutAddSubMenu( "Depth Fighting",depthfightingmenu);
glutAddSubMenu( "Depth Cue", depthcuemenu);
glutAddSubMenu( "Projection", projmenu );
glutAddMenuEntry( "Reset", RESET );
glutAddSubMenu( "Debug", debugmenu);
glutAddMenuEntry( "Quit", QUIT );
// attach the pop-up menu to the right mouse button:
glutAttachMenu( GLUT_RIGHT_BUTTON );
}
// initialize the glut and OpenGL libraries:
// also setup display lists and callback functions
void
InitGraphics( )
{
// request the display modes:
// ask for red-green-blue-alpha color, double-buffering, and z-buffering:
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
// set the initial window configuration:
glutInitWindowPosition( 0, 0 );
glutInitWindowSize( INIT_WINDOW_SIZE[0], INIT_WINDOW_SIZE[1] );
// open the window and set its title:
MainWindow = glutCreateWindow( WINDOWTITLE );
glutSetWindowTitle( WINDOWTITLE );
// set the framebuffer clear values:
glClearColor( BACKCOLOR[0], BACKCOLOR[1], BACKCOLOR[2], BACKCOLOR[3] );
// setup the callback functions:
// DisplayFunc -- redraw the window
// ReshapeFunc -- handle the user resizing the window
// KeyboardFunc -- handle a keyboard input
// MouseFunc -- handle the mouse button going down or up
// MotionFunc -- handle the mouse moving with a button down
// PassiveMotionFunc -- handle the mouse moving with a button up
// VisibilityFunc -- handle a change in window visibility
// EntryFunc -- handle the cursor entering or leaving the window
// SpecialFunc -- handle special keys on the keyboard
// SpaceballMotionFunc -- handle spaceball translation
// SpaceballRotateFunc -- handle spaceball rotation
// SpaceballButtonFunc -- handle spaceball button hits
// ButtonBoxFunc -- handle button box hits
// DialsFunc -- handle dial rotations
// TabletMotionFunc -- handle digitizing tablet motion
// TabletButtonFunc -- handle digitizing tablet button hits
// MenuStateFunc -- declare when a pop-up menu is in use
// TimerFunc -- trigger something to happen a certain time from now
// IdleFunc -- what to do when nothing else is going on
glutSetWindow( MainWindow );
glutDisplayFunc( Display );
glutReshapeFunc( Resize );
glutKeyboardFunc( Keyboard );
glutMouseFunc( MouseButton );
glutMotionFunc( MouseMotion );
glutPassiveMotionFunc( NULL );
glutVisibilityFunc( Visibility );
glutEntryFunc( NULL );
glutSpecialFunc( NULL );
glutSpaceballMotionFunc( NULL );
glutSpaceballRotateFunc( NULL );
glutSpaceballButtonFunc( NULL );
glutButtonBoxFunc( NULL );
glutDialsFunc( NULL );
glutTabletMotionFunc( NULL );
glutTabletButtonFunc( NULL );
glutMenuStateFunc( NULL );
glutTimerFunc( -1, NULL, 0 );
glutIdleFunc( Animate );
// init glew (a window must be open to do this):
#ifdef WIN32
GLenum err = glewInit( );
if( err != GLEW_OK )
{
fprintf( stderr, "glewInit Error\n" );
}
else
fprintf( stderr, "GLEW initialized OK\n" );
fprintf( stderr, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
#endif
}
// initialize the display lists that will not change:
// (a display list is a way to store opengl commands in
// memory so that they can be played back efficiently at a later time
// with a call to glCallList( )
void
InitLists( )
{
float dx = BOXSIZE / 2.f;
float dy = BOXSIZE / 2.f;
float dz = BOXSIZE / 2.f;
glutSetWindow( MainWindow );
// create the helicopter:
HelicopterList = glGenLists(1);
glNewList(HelicopterList, GL_COMPILE);
int i;
struct point *p0, *p1, *p2;
struct tri *tp;
float p01[3], p02[3], n[3];
glPushMatrix();
glTranslatef(0., -1., 0.);
glRotatef(97., 0., 1., 0.);
glRotatef(-15., 0., 0., 1.);
glBegin(GL_TRIANGLES);
for (i = 0, tp = Helitris; i < Helintris; i++, tp++)
{
p0 = &Helipoints[tp->p0];
p1 = &Helipoints[tp->p1];
p2 = &Helipoints[tp->p2];
// fake "lighting" from above:
p01[0] = p1->x - p0->x;
p01[1] = p1->y - p0->y;
p01[2] = p1->z - p0->z;
p02[0] = p2->x - p0->x;
p02[1] = p2->y - p0->y;
p02[2] = p2->z - p0->z;
Cross(p01, p02, n);
Unit(n, n);
n[1] = fabs(n[1]);
n[1] += .25;
if (n[1] > 1.)
n[1] = 1.;
glColor3f(0., n[1], 0.);
glVertex3f(p0->x, p0->y, p0->z);
glVertex3f(p1->x, p1->y, p1->z);
glVertex3f(p2->x, p2->y, p2->z);
}
glEnd();
glPopMatrix();
glEndList();
HelicopterBladeList = glGenLists(1);
glNewList(HelicopterBladeList, GL_COMPILE);
glPushMatrix();
glBegin(GL_TRIANGLES);
float BLADE_RADIUS = 1.0;
float BLADE_WIDTH = 0.4;
glColor3f( 0.8f, 0.8f, 0.8f );
glVertex2f(BLADE_RADIUS, BLADE_WIDTH / 2.);
glVertex2f(0., 0.);
glVertex2f(BLADE_RADIUS, -BLADE_WIDTH / 2.);
glVertex2f(-BLADE_RADIUS, -BLADE_WIDTH / 2.);
glVertex2f(0., 0.);
glVertex2f(-BLADE_RADIUS, BLADE_WIDTH / 2.);
glEnd();
glPopMatrix();
glEndList();
// create the axes:
AxesList = glGenLists( 1 );
glNewList( AxesList, GL_COMPILE );
glLineWidth( AXES_WIDTH );
Axes( 1.5 );
glLineWidth( 1. );
glEndList( );
float triangleScale = 2.0f;
GLfloat top[3] = { 0.0f, triangleScale, 0.0f };
GLfloat left[3] = { -triangleScale, -triangleScale, 0.0f };
GLfloat right[3] = { triangleScale, -triangleScale, 0.0f };
GLfloat normal[3] = { 0.0f, 0.0f, 1.0f };
GLfloat firstColor[3] = { rand() / ((float)RAND_MAX + 1), rand() / ((float)RAND_MAX + 1), rand() / ((float)RAND_MAX + 1) };
CustomList = glGenLists( 1 );
glNewList( CustomList, GL_COMPILE );
glBegin( GL_TRIANGLES );
DrawTriangle( top, left, right, normal, firstColor, 0, 8, 0.05f );
glEnd( );
glEndList( );
}
// Recursively create the triangles, pushing each layer slightly forward based on the current depth
void DrawTriangle( GLfloat* top, GLfloat* left, GLfloat* right, GLfloat* normal, GLfloat* color, int depth, int depthLimit, float depthOffset )
{
if (depth > depthLimit)
return;
glColor3fv(color);
glNormal3fv(normal);
glVertex3fv(top);
glVertex3fv(right);
glVertex3fv(left);
if (depth + 1 > depthLimit)
return;
// Compute subdivision positions
GLfloat newTop[3] = { top[0], top[1], (depth + 1) * depthOffset };
GLfloat newLeft[3] = { left[0], left[1], (depth + 1) * depthOffset };
GLfloat newRight[3] = { right[0], right[1], (depth + 1) * depthOffset };
GLfloat topMiddle[3] = { newTop[0], newTop[1], (depth+1) * depthOffset };
GLfloat botLeft[3] = { newLeft[0], newLeft[1], (depth + 1) * depthOffset };
GLfloat botRight[3] = { newRight[0], newRight[1], (depth + 1) * depthOffset };
GLfloat middleLeft[3] = { newLeft[0] + ((newTop[0] - newLeft[0]) / 2.0f), newLeft[1] + ((newTop[1] - newLeft[1]) / 2.0f), (depth + 1) * depthOffset };
GLfloat botMiddle[3] = { newTop[0], newLeft[1], (depth + 1) * depthOffset };
GLfloat middleRight[3] = { newTop[0] + ((newTop[0] - newLeft[0]) / 2.0f), newLeft[1] + ((newTop[1] - newLeft[1]) / 2.0f), (depth + 1) * depthOffset };
srand(depth*100 + 3);
GLfloat nextColor[3] = { rand() / ((float)RAND_MAX + 1), rand() / ((float)RAND_MAX + 1), rand() / ((float)RAND_MAX + 1) };
// Recurse
DrawTriangle(middleLeft, newLeft, botMiddle, normal, nextColor, depth + 1, depthLimit, depthOffset); // bottom left triangle
DrawTriangle(newTop, middleLeft, middleRight, normal, nextColor, depth + 1, depthLimit, depthOffset); // top triangle
DrawTriangle(middleRight, botMiddle, newRight, normal, nextColor, depth + 1, depthLimit, depthOffset); // bottom right triangle
}
// the keyboard callback:
void
Keyboard( unsigned char c, int x, int y )
{
if( DebugOn != 0 )
fprintf( stderr, "Keyboard: '%c' (0x%0x)\n", c, c );
switch( c )
{
case 'o':
case 'O':
WhichProjection = ORTHO;
break;
case 'p':
case 'P':
WhichProjection = PERSP;
break;
case 'q':
case 'Q':
case ESCAPE:
DoMainMenu( QUIT ); // will not return here
break; // happy compiler
default:
fprintf( stderr, "Don't know what to do with keyboard hit: '%c' (0x%0x)\n", c, c );
}
// force a call to Display( ):
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// called when the mouse button transitions down or up:
void
MouseButton( int button, int state, int x, int y )
{
int b = 0; // LEFT, MIDDLE, or RIGHT
if( DebugOn != 0 )
fprintf( stderr, "MouseButton: %d, %d, %d, %d\n", button, state, x, y );
// get the proper button bit mask:
switch( button )
{
case GLUT_LEFT_BUTTON:
b = LEFT; break;
case GLUT_MIDDLE_BUTTON:
b = MIDDLE; break;
case GLUT_RIGHT_BUTTON:
b = RIGHT; break;
default:
b = 0;
fprintf( stderr, "Unknown mouse button: %d\n", button );
}
// button down sets the bit, up clears the bit:
if( state == GLUT_DOWN )
{
Xmouse = x;
Ymouse = y;
ActiveButton |= b; // set the proper bit
}
else
{
ActiveButton &= ~b; // clear the proper bit
}
}
// called when the mouse moves while a button is down:
void
MouseMotion( int x, int y )
{
if( DebugOn != 0 )
fprintf( stderr, "MouseMotion: %d, %d\n", x, y );
int dx = x - Xmouse; // change in mouse coords
int dy = y - Ymouse;
if( ( ActiveButton & LEFT ) != 0 )
{
Xrot += ( ANGFACT*dy );
Yrot += ( ANGFACT*dx );
}
if( ( ActiveButton & MIDDLE ) != 0 )
{
Scale += SCLFACT * (float) ( dx - dy );
// keep object from turning inside-out or disappearing:
if( Scale < MINSCALE )
Scale = MINSCALE;
}
Xmouse = x; // new current position
Ymouse = y;
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// reset the transformations and the colors:
// this only sets the global variables --
// the glut main loop is responsible for redrawing the scene
void
Reset( )
{
ActiveButton = 0;
AxesOn = 0;
DebugOn = 0;
DepthBufferOn = 1;
DepthFightingOn = 0;
InteriorOn = 0;
DepthCueOn = 0;
Scale = 0.2;
WhichColor = WHITE;
WhichProjection = PERSP;
Xrot = 15.0;
Yrot = -45.0;
}
// called when user resizes the window:
void
Resize( int width, int height )
{
if( DebugOn != 0 )
fprintf( stderr, "ReSize: %d, %d\n", width, height );
// don't really need to do anything since window size is
// checked each time in Display( ):
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
// handle a change to the window's visibility:
void
Visibility ( int state )
{
if( DebugOn != 0 )
fprintf( stderr, "Visibility: %d\n", state );
if( state == GLUT_VISIBLE )
{
glutSetWindow( MainWindow );
glutPostRedisplay( );
}
else
{
// could optimize by keeping track of the fact
// that the window is not visible and avoid
// animating or redrawing it ...
}
}
/////////////////////////////////////// HANDY UTILITIES: //////////////////////////
// the stroke characters 'X' 'Y' 'Z' :
static float xx[ ] = {
0.f, 1.f, 0.f, 1.f
};
static float xy[ ] = {
-.5f, .5f, .5f, -.5f
};
static int xorder[ ] = {
1, 2, -3, 4
};
static float yx[ ] = {
0.f, 0.f, -.5f, .5f
};
static float yy[ ] = {
0.f, .6f, 1.f, 1.f
};
static int yorder[ ] = {
1, 2, 3, -2, 4
};
static float zx[ ] = {
1.f, 0.f, 1.f, 0.f, .25f, .75f
};
static float zy[ ] = {
.5f, .5f, -.5f, -.5f, 0.f, 0.f
};
static int zorder[ ] = {
1, 2, 3, 4, -5, 6
};
// fraction of the length to use as height of the characters:
const float LENFRAC = 0.10f;
// fraction of length to use as start location of the characters:
const float BASEFRAC = 1.10f;
// Draw a set of 3D axes:
// (length is the axis length in world coordinates)
void
Axes( float length )
{
glBegin( GL_LINE_STRIP );
glVertex3f( length, 0., 0. );
glVertex3f( 0., 0., 0. );
glVertex3f( 0., length, 0. );
glEnd( );
glBegin( GL_LINE_STRIP );
glVertex3f( 0., 0., 0. );
glVertex3f( 0., 0., length );
glEnd( );
float fact = LENFRAC * length;
float base = BASEFRAC * length;
glBegin( GL_LINE_STRIP );
for( int i = 0; i < 4; i++ )
{
int j = xorder[i];
if( j < 0 )
{
glEnd( );
glBegin( GL_LINE_STRIP );
j = -j;
}
j--;
glVertex3f( base + fact*xx[j], fact*xy[j], 0.0 );
}
glEnd( );
glBegin( GL_LINE_STRIP );
for( int i = 0; i < 5; i++ )
{
int j = yorder[i];
if( j < 0 )
{
glEnd( );
glBegin( GL_LINE_STRIP );
j = -j;
}
j--;
glVertex3f( fact*yx[j], base + fact*yy[j], 0.0 );
}
glEnd( );
glBegin( GL_LINE_STRIP );
for( int i = 0; i < 6; i++ )
{
int j = zorder[i];
if( j < 0 )
{
glEnd( );
glBegin( GL_LINE_STRIP );
j = -j;
}
j--;
glVertex3f( 0.0, fact*zy[j], base + fact*zx[j] );
}
glEnd( );
}
// function to convert HSV to RGB
// 0. <= s, v, r, g, b <= 1.
// 0. <= h <= 360.
// when this returns, call:
// glColor3fv( rgb );
void
HsvRgb( float hsv[3], float rgb[3] )
{
// guarantee valid input:
float h = hsv[0] / 60.f;
while( h >= 6. ) h -= 6.;
while( h < 0. ) h += 6.;
float s = hsv[1];
if( s < 0. )
s = 0.;
if( s > 1. )
s = 1.;
float v = hsv[2];
if( v < 0. )
v = 0.;
if( v > 1. )
v = 1.;
// if sat==0, then is a gray:
if( s == 0.0 )
{
rgb[0] = rgb[1] = rgb[2] = v;
return;
}
// get an rgb from the hue itself:
float i = floor( h );
float f = h - i;
float p = v * ( 1.f - s );
float q = v * ( 1.f - s*f );
float t = v * ( 1.f - ( s * (1.f-f) ) );
float r, g, b; // red, green, blue
switch( (int) i )
{
case 0:
r = v; g = t; b = p;
break;
case 1:
r = q; g = v; b = p;
break;
case 2:
r = p; g = v; b = t;
break;
case 3:
r = p; g = q; b = v;
break;
case 4:
r = t; g = p; b = v;
break;
case 5:
r = v; g = p; b = q;
break;
}
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
}
float
Dot(float v1[3], float v2[3])
{
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
void
Cross(float v1[3], float v2[3], float vout[3])
{
float tmp[3];
tmp[0] = v1[1] * v2[2] - v2[1] * v1[2];
tmp[1] = v2[0] * v1[2] - v1[0] * v2[2];
tmp[2] = v1[0] * v2[1] - v2[0] * v1[1];
vout[0] = tmp[0];
vout[1] = tmp[1];
vout[2] = tmp[2];
}
float
Unit(float vin[3], float vout[3])
{
float dist = vin[0] * vin[0] + vin[1] * vin[1] + vin[2] * vin[2];
if (dist > 0.0)
{
dist = sqrt(dist);
vout[0] = vin[0] / dist;
vout[1] = vin[1] / dist;
vout[2] = vin[2] / dist;
}
else
{
vout[0] = vin[0];
vout[1] = vin[1];
vout[2] = vin[2];
}
return dist;
} | [
"alan@neadsdev.com"
] | alan@neadsdev.com |
71c147c9d25aae68a4efe92590b9903ce7f984a0 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/11_12306_100.cpp | 5ba56840c809a2c5d46a51c7134b0a1a55f4bece | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class A {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("A.in"));
PrintWriter pw = new PrintWriter("A.out");
int t = s.nextInt();
for (int test=1; test<=t; test++) {
pw.print("Case #"+test+": ");
int total = 0;
int[] tp = {0,0};
int[] pp = {1,1};
int n = s.nextInt();
for (int i=0; i<n; i++) {
String str = s.next();
int p=0;
if (str.equals("B")) p = 1;
int pos = s.nextInt();
int time = Math.abs(pos - pp[p]);
time = Math.max(1, time - tp[p] + 1);
total += time;
tp[p] = 0;
tp[1-p] += time;
pp[p] = pos;
}
pw.println(total);
}
pw.close();
}
}
| [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
72e248985f05903d998cf65f39cf8340a6aa1760 | d724be1dd2daf6835d6c18428d10f1379c3fda7b | /Assignment 3/src/test_cofold.cpp | d1c247bbf1fc20a3d31865316bb3124aa5cc9d48 | [] | no_license | maltic/cits4008 | 3695c03793a2bbe1a5b009861e701c433b79e913 | 47cc33ffcce3a875d335d1a78da8657815eea726 | refs/heads/master | 2016-09-06T05:01:57.921542 | 2014-09-02T03:34:43 | 2014-09-02T03:34:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp |
#include <iostream>
#include <string>
//include external libs
extern "C"
{
#include "cofold.h"
}
using namespace std;
int main()
{
// read in the testing set
while (cin.good())
{
string id, rna, sstruct;
cin >> id >> rna >> sstruct;
// a structure string is used to get the predicted structure from cofold
char *structure = new char[rna.size()+1];
// cofold that rna!
float fe = cofold(rna.c_str(), structure);
//output
cout << id << '\t' << fe << '\t' << structure << endl;
}
return 0;
}
| [
"max@maltic.com"
] | max@maltic.com |
04aacf13dff5a6f7d1e10784891a856680056d46 | 25509aa66ad1a65663d42bf4ddbe9d1fa295fdab | /YuEngine/EventTimer.cpp | c8af15e8a324f801344ca229a90504c2bae8876e | [] | no_license | NathanVss/Noxel-OpenGL | 24b5d820d9df48bd5b68048a58ec056a3b93d28e | c48203cefc0e4eeaccb78868bd2609b2762666e0 | refs/heads/master | 2016-09-06T14:09:01.472705 | 2015-02-27T17:41:24 | 2015-02-27T17:41:24 | 29,501,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include "EventTimer.h"
namespace YuEngine {
EventTimer::EventTimer(void)
{
}
EventTimer::EventTimer(int _ticksEvent)
{
curTicks = 0;
ticksEvent = _ticksEvent;
}
void EventTimer::update() {
curTicks++;
}
bool EventTimer::isUnder(int a, int b) {
return curTicks >= a && curTicks <= b;
}
bool EventTimer::isOver() {
if(curTicks >= ticksEvent) {
return true;
}
return false;
}
bool EventTimer::isOver(int ticks) {
if(curTicks >= ticks) {
return true;
}
return false;
}
void EventTimer::setOver() {
curTicks = ticksEvent + 1;
}
void EventTimer::reset() {
curTicks = 0;
}
EventTimer::~EventTimer(void)
{
}
} | [
"nathan.vasse@gmail.com"
] | nathan.vasse@gmail.com |
95e525570d879d039cd80875a5fa7ac1489a7d82 | 075735e3b987cb8ad5c629440ee6419ff2762f81 | /leetcode/162_FindPeakElement/FindPeakElement.cpp | ca1bb34b72194775757e76335570aeb8959aecd7 | [] | no_license | Masterqsx/ProgrammingPractice | 6f0d4c08f1857f5a409b78c9ae7cd0ec234899be | acf42fb807dc8584b4ae0081ddf65c495314eabe | refs/heads/master | 2021-01-24T20:26:17.552529 | 2019-07-22T19:16:58 | 2019-07-22T19:16:58 | 68,643,503 | 0 | 0 | null | 2020-10-13T01:11:46 | 2016-09-19T20:26:10 | HTML | UTF-8 | C++ | false | false | 596 | cpp | class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size()<2) return 0;
if(nums[0]>nums[1]) return 0;
if(nums[nums.size()-1]>nums[nums.size()-2]) return nums.size()-1;
int lo=0,hi=nums.size()-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if((nums[mid]>nums[mid+1])&&(nums[mid]>nums[mid-1])){
return mid;
}
else if(nums[mid]>nums[mid-1]){
lo=mid+1;
}
else{
hi=mid-1;
}
}
return 0;
}
}; | [
"qsxyh123@gmail.com"
] | qsxyh123@gmail.com |
eae251bea707e56eeacdb8c226166509df148753 | 7f780a567fa3364ae76f8a2d949618b9ad5634e8 | /lib/window.cpp | 331fb4680c9c8254c80c9f4bf430d8b3f6781390 | [] | no_license | albireoNox/gfxfun | 125914165f7ee671c484ddca10968ecb07d0db68 | 764b04c064e61b647e6a332bbf41ef40eb1863ac | refs/heads/master | 2021-07-10T09:18:09.551318 | 2021-05-11T15:08:24 | 2021-05-11T15:08:24 | 93,285,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,716 | cpp | #include "window.h"
#include "msg_debug.h"
#include <Windows.h>
#include <Windowsx.h>
#include <iostream>
#include <cassert>
using namespace std;
uint Window::numOpenWindows = 0;
LRESULT CALLBACK
handleMsgCb(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
Window* window = reinterpret_cast<Window*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (window != nullptr)
return window->handleMsg(msg, wParam, lParam);
else
return DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT
Window::handleMsg(UINT msg, WPARAM wParam, LPARAM lParam)
{
// wcout << "msg:" << getMsgDebugString(msg) << " w:" << wParam << " l:" << lParam << endl;
switch(msg)
{
case WM_SHOWWINDOW:
this->onCreate();
UpdateWindow(this->windowHandle);
return 0;
case WM_CHAR:
this->onCharInput(static_cast<wchar_t>(wParam));
return 0;
case WM_LBUTTONDOWN:
// TODO This is not really a click.
this->onMouseLClick(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_SIZE:
this->onResize(LOWORD(lParam), HIWORD(lParam));
return 0;
case WM_DESTROY:
this->onClose();
return 0;
default:
return DefWindowProc(this->windowHandle, msg, wParam, lParam);
}
}
void
Window::onCreate()
{
wcout << this->name << ": CREATE" << endl;
}
void
Window::onCharInput(wchar_t ch)
{
wcout << this->name << ": KEY PRESS " << ch << endl;
}
void
Window::onMouseLClick(int x, int y)
{
wcout << this->name << ": LEFT MOUSE BUTTON CLICK @ (" << x << ", " << y << ")" << endl;
}
void
Window::onResize(uint newClientWidth, uint newClientHeight)
{
// Save the new client area dimensions.
this->clientWidth = newClientWidth;
this->clientHeight = newClientHeight;
wcout << this->name << ": RESIZE - Window is now "
<< this->clientWidth << "X" << this->clientHeight << endl;
}
void
Window::onClose()
{
wcout << this->name << ": DESTROYING WINDOW" << endl;
assert(Window::numOpenWindows > 0);
if (--Window::numOpenWindows == 0)
PostQuitMessage(0);
}
void
Window::registerWindowClass()
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = handleMsgCb;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = this->hInstance;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = this->name.c_str();
if (!RegisterClass(&wc))
throw L"RegisterClass Failed.";
cout << "Registered window class." << endl;
}
void
Window::createWindow()
{
RECT R = { 0, 0, this->clientWidth, this->clientHeight };
AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false);
int width = R.right - R.left;
int height = R.bottom - R.top;
cout << "Creating window with final size: " << width << "X" << height << endl;
this->windowHandle = CreateWindow(
this->name.c_str(), // Use name for class name.
this->name.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
width,
height,
nullptr,
nullptr,
this->hInstance,
nullptr);
if (this->windowHandle == nullptr)
throw "Failed to create window";
SetLastError(0);
SetWindowLongPtr(this->windowHandle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
if (GetLastError() != 0)
throw "Failed to bind window object.";
Window::numOpenWindows++;
}
Window::Window(const wstring& name, uint clientWidth, uint clientHeight, HINSTANCE hInstance) :
name(name), hInstance(hInstance), clientWidth(clientWidth), clientHeight(clientHeight)
{
this->registerWindowClass();
this->createWindow();
cout << "CTOR DONE" << endl;
}
void
Window::show()
{
ShowWindow(this->windowHandle, SW_SHOW);
UpdateWindow(this->windowHandle);
}
Window::~Window()
{
// NOOP (for now)
}
| [
"albireoNox@users.noreply.github.com"
] | albireoNox@users.noreply.github.com |
872293ccd8a5a7d86f3632f07aeca0fc818dd0fb | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/hana/test/_include/support/tracked.hpp | 8809a103e5b80ca887a524202a829335962ff1ab | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,572 | hpp | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#ifndef TEST_SUPPORT_TRACKED_HPP
#define TEST_SUPPORT_TRACKED_HPP
// Define this if you want Tracked objects to print information to stderr.
// #define TRACKED_PRINT_STUFF
#include <sstd/boost/hana/assert.hpp>
#ifdef TRACKED_PRINT_STUFF
# include <iostream>
#endif
#include <iosfwd>
struct Tracked {
enum class State { CONSTRUCTED, MOVED_FROM, DESTROYED };
int value;
State state;
explicit Tracked(int k) : value{k}, state{State::CONSTRUCTED} {
#ifdef TRACKED_PRINT_STUFF
std::cerr << "constructing " << *this << '\n';
#endif
}
Tracked(Tracked const& t) : value{t.value}, state{State::CONSTRUCTED} {
BOOST_HANA_RUNTIME_CHECK(t.state != State::MOVED_FROM &&
"copying a moved-from object");
BOOST_HANA_RUNTIME_CHECK(t.state != State::DESTROYED &&
"copying a destroyed object");
#ifdef TRACKED_PRINT_STUFF
std::cerr << "copying " << *this << '\n';
#endif
}
Tracked(Tracked&& t) : value{t.value}, state{State::CONSTRUCTED} {
BOOST_HANA_RUNTIME_CHECK(t.state != State::MOVED_FROM &&
"double moving from an object");
BOOST_HANA_RUNTIME_CHECK(t.state != State::DESTROYED &&
"moving from a destroyed object");
#ifdef TRACKED_PRINT_STUFF
std::cerr << "moving " << t << '\n';
#endif
t.state = State::MOVED_FROM;
}
Tracked& operator=(Tracked const& other) {
BOOST_HANA_RUNTIME_CHECK(this->state != State::DESTROYED &&
"assigning to a destroyed object");
BOOST_HANA_RUNTIME_CHECK(other.state != State::MOVED_FROM &&
"assigning a moved-from object");
BOOST_HANA_RUNTIME_CHECK(other.state != State::DESTROYED &&
"assigning a destroyed object");
#ifdef TRACKED_PRINT_STUFF
std::cerr << "assigning " << other << " to " << *this << '\n';
#endif
this->value = other.value;
return *this;
}
Tracked& operator=(Tracked&& other) {
BOOST_HANA_RUNTIME_CHECK(this->state != State::DESTROYED &&
"assigning to a destroyed object");
BOOST_HANA_RUNTIME_CHECK(other.state != State::MOVED_FROM &&
"double-moving from an object");
BOOST_HANA_RUNTIME_CHECK(other.state != State::DESTROYED &&
"assigning a destroyed object");
#ifdef TRACKED_PRINT_STUFF
std::cerr << "assigning " << other << " to " << *this << '\n';
#endif
this->value = other.value;
other.state = State::MOVED_FROM;
return *this;
}
~Tracked() {
BOOST_HANA_RUNTIME_CHECK(state != State::DESTROYED &&
"double-destroying an object");
#ifdef TRACKED_PRINT_STUFF
std::cerr << "destructing " << *this << '\n';
#endif
state = State::DESTROYED;
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, Tracked const& t) {
os << "Tracked{" << t.value << "}";
switch (t.state) {
case State::CONSTRUCTED:
os << "[ok]"; break;
case State::MOVED_FROM:
os << "[moved from]"; break;
case State::DESTROYED:
os << "[destroyed]"; break;
default:
BOOST_HANA_RUNTIME_CHECK(false && "never reached");
}
return os;
}
};
#endif // !TEST_SUPPORT_TRACKED_HPP
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
c47b4be70fb735d2975b162bbdec3e9f5c7ae69e | f64bcdabae3c5bc99c09afd2e35d6d34ebf3602a | /server/peer_serv.cpp | b61f042ad84e592d1c3f3a0dc2e8d1d7cc5e19ef | [] | no_license | daviddych/CppCloud | 7707a9ba2d181673f8adb2618bb607143cc5d1de | ef9999cc3ef07e7bc00ec599e58477d7769659ad | refs/heads/master | 2020-05-04T10:36:19.696966 | 2019-02-26T04:28:04 | 2019-02-26T04:28:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,889 | cpp |
#include <sys/epoll.h>
#include "peer_serv.h"
#include "comm/strparse.h"
#include "comm/sock.h"
#include "cloud/const.h"
#include "cloud/exception.h"
#include "climanage.h"
#include "cloud/switchhand.h"
HEPMUTICLASS_IMPL(PeerServ, PeerServ, IOHand)
int PeerServ::s_my_svrid = 0;
PeerServ::PeerServ(void): m_stage(0), m_seqid(0), m_svrid(0), m_epfd(INVALID_FD), m_port(0)
{
m_cliType = SERV_CLITYPE_ID;
m_isLocal = true;
//m_outObj = true;
m_inqueue = false;
m_existLink = false;
}
PeerServ::~PeerServ(void)
{
}
void PeerServ::Init( int mysvrid )
{
s_my_svrid = mysvrid;
}
int PeerServ::init( const string& rhost, int port, int epfd )
{
m_rhost = rhost;
m_epfd = epfd;
m_port = port;
m_idProfile = "connTO" + rhost;
m_epCtrl.setEPfd(epfd);
return 0;
}
void PeerServ::setSvrid( int svrid )
{
m_svrid = svrid;
}
int PeerServ::onEvent( int evtype, va_list ap )
{
return 0;
}
int PeerServ::qrun( int flag, long p2 )
{
int ret = 0;
m_inqueue = false;
if (0 == flag)
{
try {
ret = taskRun(flag, p2);
}
catch(OffConnException& exp)
{
LOGERROR("PEERS_TASKRUN| msg=exception| reson=%s| mi=%s", exp.reson.c_str(), m_idProfile.c_str());
IOHand::onClose(flag, p2);
m_stage = 0;
}
return appendTimerq();
}
else if (1 == flag)
{
onClose(HEFG_PEXIT, 2);
}
return ret;
}
// 连接不上或断开连接时到达
int PeerServ::onClose( int p1, long p2 )
{
return IOHand::onClose(p1, p2);
}
void PeerServ::reset( void )
{
m_stage = 0;
m_closeReason.clear();
m_closeFlag = 0;
m_existLink = false;
IFCLOSEFD(m_cliFd);
}
int PeerServ::appendTimerq( void )
{
int ret = 0;
if (!m_inqueue)
{
// 连接正常时 下次检查就延长些; 连接不正常时,下次检查就频繁此
int wait_time_msec = m_existLink? PEERSERV_EXIST_CHKTIME: PEERSERV_NOEXIST_CHKTIME;
ret = SwitchHand::Instance()->appendQTask(this, wait_time_msec + s_my_svrid*200);
m_inqueue = (0 == ret);
ERRLOG_IF1(ret, "APPENDQTASK| msg=append fail| ret=%d", ret);
}
return ret;
}
int PeerServ::taskRun( int flag, long p2 )
{
// 向远端serv发起连接
// 先检查是否已有同一ID的远端serv,有则无需发起
string rsvrid = StrParse::Itoa(m_svrid);
string alias_beg = string(SERV_IN_ALIAS_PREFIX) + rsvrid + "A"; // "A"是排除serv11进入serv1的范围
string alias_end = string(SERV_IN_ALIAS_PREFIX) + rsvrid + "z"; // serv1C serv1S
int ret = 0;
CliMgr::AliasCursor finder(alias_beg, alias_end);
CliBase* serv = NULL;
LOGDEBUG("PEERSRUN| %s", CliMgr::Instance()->selfStat(true).c_str());
if ( (serv = finder.pop()) )
{
if (s_my_svrid < m_svrid)
{
CliBase* more_serv = finder.pop();
IOHand* more_ioh = dynamic_cast<IOHand*>(more_serv);
if (more_ioh)
{
more_ioh->driveClose("close surplus tcplink"); // 关闭多余的一个连接
LOGINFO("REMOTSERVRUN| msg=remove surplus tcplink| svrid=%d", m_svrid);
}
m_existLink = true;
}
//LOGDEBUG("PEERS_RUN| msg=remote serv aliving| svr=%s", serv->m_idProfile.c_str());
}
else
{
if (0 == m_stage && INVALID_FD != m_cliFd)
{
LOGERROR("PEERS_RUN| msg=unexcepct flow| sock=%d| mi=%s", Sock::geterrno(m_cliFd), m_idProfile.c_str());
throw OffConnException("cliFd not null at stage0");
}
reset();
ret = Sock::connect_noblock(m_cliFd, m_rhost.c_str(), m_port);
if (ERRSOCK_AGAIN == ret || 0 == ret)
{
m_epCtrl.setActFd(m_cliFd);
m_stage = 1; // connecting
setIntProperty("fd", m_cliFd);
m_idProfile = StrParse::Format("conneting to %s:%d", m_rhost.c_str(), m_port);
if (0 == ret)
{
m_cliName = Sock::peer_name(m_cliFd, true);
m_idProfile = m_cliName;
}
prepareWhoIam();
m_epCtrl.setEvt(EPOLLOUT|EPOLLIN, this);
}
else
{
throw OffConnException("connect fail");
}
}
return ret;
}
// 准备好发送的包,等连接OK后发出
int PeerServ::prepareWhoIam( void )
{
string whoIamJson;
whoIamJson += "{";
StrParse::PutOneJson(whoIamJson, CONNTERID_KEY, s_my_svrid, true);
StrParse::PutOneJson(whoIamJson, SVRNAME_KEY, MYSERVNAME, true);
StrParse::PutOneJson(whoIamJson, CLISOCKET_KEY, Sock::sock_name(m_cliFd, true, false), true);
StrParse::PutOneJson(whoIamJson, "begin_time", (int)time(NULL), true);
StrParse::PutOneJson(whoIamJson, "pid", getpid(), true);
StrParse::PutOneJson(whoIamJson, CLIENT_TYPE_KEY, m_cliType, false);
whoIamJson += "}";
IOBuffItem* obf = new IOBuffItem;
obf->setData(CMD_IAMSERV_REQ, ++m_seqid, whoIamJson.c_str(), whoIamJson.length());
if (!m_oBuffq.append(obf))
{
LOGERROR("PEERS_WAI| msg=append to oBuffq fail| len=%d| mi=%s", m_oBuffq.size(), m_cliName.c_str());
delete obf;
throw OffConnException("oBuffq.append fail");
}
LOGDEBUG("PEERS_WAI| msg=send iamserv req| mi=%s", m_cliName.c_str());
return 0;
}
| [
"hejl@bmsh.com"
] | hejl@bmsh.com |
47465d644d252a5d4521b712ade0be0a1b98c2cf | cf840414ac8be8ac7522df540d95933e16931b27 | /Design/Firmware/Arduino_Libraries/Scoreboard/examples/ScoreboardBasic/ScoreboardBasic.ino | a1c3d8f91cd31cde47ccfab6f186b0c508d98b4a | [
"MIT"
] | permissive | plainolddave/Scoreboard | 2deed3bf2279ac88b711035c4102633cb228571c | 4e7753640fef9a8e1bb4ffbc34ecac80b06470f4 | refs/heads/master | 2022-12-12T21:10:25.137290 | 2020-08-22T01:50:52 | 2020-08-22T01:50:52 | 89,904,667 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,246 | ino | /*
Author: Dave Skinner
Description: Hotspot controller for scoreboard
*/
// ---------------------------------------------------------------------------------
// Set the scoreboard mode - refer to ScoreboardConfigs.h for options
#define SCOREBOARD_MASTER
// ---------------------------------------------------------------------------------
#include <Arduino.h>
#include <Scoreboard.h>
// ---------------------------------------------------------------------------------
void setup ( void )
{
UBEGIN(115200);
delay(100);
UPRINTLN(F("\n\rStart scoreboard"));
// initialize the scoreboard objects with their field ID
for ( uint8_t id = 0; id < FIELDS; id++ )
scoreboard[id].ID ( id );
// deselect SPI devices by setting their chipselect lines HIGH
// (otherwise the SPI devices will interfere with each other)
utility.DeselectSPI(spi, sizeof(spi));
UPRINTLN(F("Startup complete"));
}
// ---------------------------------------------------------------------------------
void loop ( void )
{
// Process every n seconds
static time_t updateTime = 0;
if ( now() > updateTime + 10 )
{
updateTime = now();
}
}
// ---------------------------------------------------------------------------------
| [
"dave@shoal.net.au"
] | dave@shoal.net.au |
77d4663fc5869a268dbce8ba05c26909907bd8ab | cae1b99c378b36b5a15c84e53d134c39aaf0b355 | /OnlineMapTrack2RWD-StromboliRescan/OnlineMapTrack2RWD.cpp | 9ee020f30021bcaa44447c89ae7d17c48027e5ec | [] | no_license | kryssb/SySal.NET | fca1922a45fdd45d0b135601700c0e46d3637ff3 | 8453d57ab866a75dd4ba81715d56ffbeafb3bb51 | refs/heads/master | 2023-01-11T19:48:29.760409 | 2020-11-13T13:34:01 | 2020-11-13T13:34:01 | 312,584,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,964 | cpp | // This is the main DLL file.
#include "stdafx.h"
#include <vector>
#include "xml-lite.h"
#include "OnlineMapTrack2RWD.h"
#include "gpu_util.h"
#include <stdlib.h>
#include <math.h>
namespace SySal
{
namespace GPU
{
int Utilities::GetAvailableGPUs()
{
return ::SySal::GPU::GetAvailableGPUs();
}
const int StringWorkspaceSize = 4096;
MapTracker::MapTracker()
{
gpu = -1;
pTk = 0;
pIC = new SySal::ImageCorrection;
pCC = new SySal::ClusterChainer::Configuration;
pTC = new SySal::Tracker::Configuration;
pStringWorkspace = new char[StringWorkspaceSize];
pix_x_override = 0.0f;
pix_y_override = 0.0f;
rwdvsConsumer = nullptr;
Activity = gcnew System::String("Idle");
PerfDumpFile = nullptr;
PreloadQueue = gcnew System::Collections::Generic::Queue<IntPtr>();
}
void MapTracker::Free()
{
if (pTk)
{
delete pTk;
pTk = 0;
}
if (pIC)
{
delete pIC;
pIC = 0;
}
if (pCC)
{
delete pCC;
pCC = 0;
}
if (pTC)
{
delete pTC;
pTC = 0;
}
if (pStringWorkspace)
{
delete [] pStringWorkspace;
pStringWorkspace = 0;
}
rwdvsConsumer = nullptr;
gpu = -1;
}
MapTracker::~MapTracker()
{
Free();
}
MapTracker::!MapTracker()
{
Free();
}
char *MapTracker::c_str(System::String ^s)
{
int i;
for (i = 0; i < StringWorkspaceSize - 1 && i < s->Length; i++)
pStringWorkspace[i] = s[i];
pStringWorkspace[i] = 0;
return pStringWorkspace;
}
void MapTracker::SetPerformanceCounterDumpFile(System::String ^perfdumpfile)
{
PerfDumpFile = perfdumpfile;
}
void MapTracker::SetPixelXOverride(float v)
{
pix_x_override = v;
}
void MapTracker::SetPixelYOverride(float v)
{
pix_y_override = v;
}
void MapTracker::SetGPU(int g)
{
if (g < 0 || g >= Utilities::GetAvailableGPUs()) throw gcnew System::String("Invalid GPU number supplied.");
if (gpu >= 0)
{
if (pTk)
{
delete pTk;
pTk = 0;
}
gpu = -1;
}
try
{
gpu = g;
pTk = new GPU::PrismMapTracker(gpu);
}
catch (...)
{
pTk = 0;
gpu = -1;
throw gcnew System::String("Can't create the tracker on the specified GPU: unmanaged C++ exception occurred.");
}
}
void MapTracker::SetImageCorrection(System::String ^ics)
{
if (pIC)
{
std::vector<XMLLite::Element> imcorr_elems;
imcorr_elems = XMLLite::Element::FromString(c_str(ics));
if (imcorr_elems.size() != 1) throw gcnew System::String("The XML document must contain only one element.");
XMLLite::Element &el = imcorr_elems[0];
if (el.Name != "ImageCorrection") throw gcnew System::String("Wrong ImageCorrection config file.");
SySal::ImageCorrection ic;
#define CH_CONF_XML(x,f) ic.x = f(el[# x].Value.c_str());
CH_CONF_XML(DMagDX, atof);
CH_CONF_XML(DMagDY, atof);
CH_CONF_XML(DMagDZ, atof);
CH_CONF_XML(XYCurvature, atof);
CH_CONF_XML(ZCurvature, atof);
CH_CONF_XML(XSlant, atof);
CH_CONF_XML(YSlant, atof);
CH_CONF_XML(CameraRotation, atof);
#undef CH_CONF_XML
*pIC = ic;
}
}
void MapTracker::SetClusterChainerConfig(System::String ^ccs)
{
if (pCC)
{
std::vector<XMLLite::Element> map_elems;
map_elems = XMLLite::Element::FromString(c_str(ccs));
if (map_elems.size() != 1) throw "The XML document must contain only one element.";
XMLLite::Element &el = map_elems[0];
if (el.Name != "ClusterChainer.Configuration") throw "Wrong ClusterChainer config file.";
SySal::ClusterChainer::Configuration cc;
#define CH_CONF_XML(x,f) cc.x = f(el[# x].Value.c_str());/* printf("\nDEBUG-CH_CONF_XML %s val = %s cc.x %d %f", # x, el[# x].Value.c_str(), cc.x, *(float *)(void *)&cc.x);*/
#define CH_CONF_F_XML(x,fn) cc.f ## x = fn(el[# x].Value.c_str());/* printf("\nDEBUG-CH_CONF_XML %s val = %s cc.x %d %f", # x, el[# x].Value.c_str(), cc.x, *(float *)(void *)&cc.x);*/
CH_CONF_XML(MaxCellContent, atoi);
CH_CONF_F_XML(CellSize, atof);
CH_CONF_F_XML(ChainMapMaxXOffset, atof);
CH_CONF_F_XML(ChainMapMaxYOffset, atof);
CH_CONF_F_XML(ChainMapMaxZOffset, atof);
CH_CONF_F_XML(ChainMapXYCoarseTolerance, atof);
CH_CONF_F_XML(ChainMapXYFineTolerance, atof);
CH_CONF_F_XML(ChainMapXYFineAcceptance, atof);
CH_CONF_F_XML(ChainMapZCoarseTolerance, atof);
CH_CONF_F_XML(ChainMapZFineTolerance, atof);
CH_CONF_F_XML(ChainMapZFineAcceptance, atof);
CH_CONF_XML(ChainMapSampleDivider, atoi);
CH_CONF_XML(ChainMapMinVolume, atoi);
CH_CONF_XML(MinChainMapsValid, atoi);
CH_CONF_F_XML(ClusterMapCoarseTolerance, atof);
CH_CONF_F_XML(ClusterMapFineTolerance, atof);
CH_CONF_F_XML(ClusterMapFineAcceptance, atof);
CH_CONF_F_XML(ClusterMapMaxXOffset, atof);
CH_CONF_F_XML(ClusterMapMaxYOffset, atof);
CH_CONF_XML(ClusterMapSampleDivider, atoi);
CH_CONF_XML(MaxChains, atoi);
CH_CONF_XML(MinClustersPerChain, atoi);
CH_CONF_XML(ClusterMapMinSize, atoi);
CH_CONF_XML(MinClusterMapsValid, atoi);
CH_CONF_XML(MinVolumePerChain, atoi);
CH_CONF_XML(ClusterThreshold, atoi);
#undef CH_CONF_XML
*pCC = cc;
}
}
void MapTracker::SetTrackerConfig(System::String ^tcs)
{
if (pTC)
{
std::vector<XMLLite::Element> track_elems;
track_elems = XMLLite::Element::FromString(c_str(tcs));
if (track_elems.size() != 1) throw "The XML document must contain only one element.";
XMLLite::Element &el = track_elems[0];
if (el.Name != "Tracker.Configuration") throw "Wrong Tracker config file.";
SySal::Tracker::Configuration tc;
#define CH_CONF_XML(x,f) tc.x = f(el[# x].Value.c_str());
#define CH_CONF_F_XML(x,fn) tc.f ## x = fn(el[# x].Value.c_str());/* printf("\nDEBUG-CH_CONF_XML %s val = %s tc.x %d %f", # x, el[# x].Value.c_str(), tc.x, *(float *)(void *)&tc.x);*/
CH_CONF_F_XML(XYTolerance, atof)
CH_CONF_F_XML(ZTolerance, atof)
CH_CONF_F_XML(ZThickness, atof)
CH_CONF_F_XML(XYHashTableBinSize, atof)
CH_CONF_F_XML(ZHashTableBinSize, atof)
CH_CONF_XML(ZHashTableBins, atoi)
CH_CONF_XML(HashBinCapacity, atoi)
CH_CONF_F_XML(MinLength, atof)
CH_CONF_F_XML(MaxLength, atof)
CH_CONF_XML(MaxTracks, atoi)
CH_CONF_XML(MinVolume, atoi)
CH_CONF_XML(MinChainVolume, atoi)
CH_CONF_F_XML(SlopeAcceptanceX, atof)
CH_CONF_F_XML(SlopeAcceptanceY, atof)
CH_CONF_F_XML(SlopeCenterX, atof)
CH_CONF_F_XML(SlopeCenterY, atof)
CH_CONF_XML(FilterVolumeLength0, atoi)
CH_CONF_XML(FilterVolumeLength100, atoi)
CH_CONF_XML(FilterChain0, atoi)
CH_CONF_XML(FilterChainMult, atof)
CH_CONF_XML(ClusterVol0, atoi)
CH_CONF_XML(ClusterVolM, atoi)
CH_CONF_F_XML(MergeTrackCell, atof)
CH_CONF_F_XML(MergeTrackXYTolerance, atof)
CH_CONF_F_XML(MergeTrackZTolerance, atof)
#undef CH_CONF_XML
*pTC = tc;
}
}
void MapTracker::SetRawDataViewSideConsumer(IRawDataViewSideConsumer ^v)
{
rwdvsConsumer = v;
}
float MapTracker::GetCurrentThickness()
{
try
{
return pTk->GetThickness();
}
catch(...)
{
throw gcnew System::String("No valid thickness information found.");
}
}
void MapTracker::PreloadFiles(System::Object ^obj)
{
cli::array<System::String ^> ^inputfiles = (cli::array<System::String ^> ^)obj;
int i;
for (i = 0; i < inputfiles->Length && TerminatePreloadThread == false; i++)
{
System::String ^fname = inputfiles[i];
while (PreloadQueue->Count >= PreloadQueueLength)
{
if (TerminatePreloadThread) return;
System::Threading::Thread::Sleep(100);
}
int trial;
SySal::IntClusterFile *pcf = 0;
for (trial = 3; trial >= 0; trial--)
try
{
pcf = new SySal::IntClusterFile(c_str(fname), true);
break;
}
catch (...)
{
if (pcf) { delete pcf; pcf = 0; }
}
PreloadQueue->Enqueue((IntPtr)(void *)pcf);
}
}
void MapTracker::FindTracks(cli::array<System::String ^> ^inputfiles, bool istop, float zsideoffset, SySal::DAQSystem::Scanning::IntercalibrationInfo ^intinfo)
{
IntClusterFile EmptyClusterFile;
SySal::IntClusterFile *pcf = 0;
System::Threading::Thread ^preloaderThread = nullptr;
TerminatePreloadThread = false;
try
{
int i;
float cscale = 0.0f;
int XYScale = pTk->Tracker().GetXYScale();
int ZScale = pTk->Tracker().GetZScale();
SySal::ClusterChainer &oC = pTk->ClusterChainer();
bool templatefound = false;
for (i = 0; i < inputfiles->Length; i++)
{
try
{
Activity = gcnew System::String("PreloadFile");
SySal::IntClusterFile cf(c_str(inputfiles[i]), false);
if (templatefound == false)
{
EmptyClusterFile.CopyEmpty(cf);
Activity = gcnew System::String("ConfigClusterChainer");
cscale = cf.Scale();
if (pix_x_override != 0.0f && pix_y_override != 0.0f)
{
*cf.pPixMicronX = pix_x_override;
*cf.pPixMicronY = pix_y_override;
}
SySal::ClusterChainer::Configuration CC = *pCC;
CC.CellSize = CC.fCellSize * cscale;
CC.ChainMapMaxXOffset = CC.fChainMapMaxXOffset * oC.GetXYScale();
CC.ChainMapMaxYOffset = CC.fChainMapMaxYOffset * oC.GetXYScale();
CC.ChainMapMaxZOffset = CC.fChainMapMaxZOffset * oC.GetZScale();
CC.ChainMapXYCoarseTolerance = CC.fChainMapXYCoarseTolerance * oC.GetXYScale();
CC.ChainMapXYFineTolerance = CC.fChainMapXYFineTolerance * oC.GetXYScale();
CC.ChainMapXYFineAcceptance = CC.fChainMapXYFineAcceptance * oC.GetXYScale();
CC.ChainMapZCoarseTolerance = CC.fChainMapZCoarseTolerance * oC.GetZScale();
CC.ChainMapZFineTolerance = CC.fChainMapZFineTolerance * oC.GetZScale();
CC.ChainMapZFineAcceptance = CC.fChainMapZFineAcceptance * oC.GetZScale();
CC.ClusterMapCoarseTolerance = CC.fClusterMapCoarseTolerance * cscale;
CC.ClusterMapFineTolerance = CC.fClusterMapFineTolerance * cscale;
CC.ClusterMapFineAcceptance = CC.fClusterMapFineAcceptance * cscale;
CC.ClusterMapMaxXOffset = CC.fClusterMapMaxXOffset * cscale;
CC.ClusterMapMaxYOffset = CC.fClusterMapMaxYOffset * cscale;
try
{
Activity = gcnew System::String("Reset");
oC.Reset(CC, *pIC, istop);
}
catch (char *x)
{
printf("\nERROR-AT-GPU-LEVEL-EXCEPTION.\nError in \"%s\"\nPerforming hard reset.", c_str(Activity));
Activity = gcnew System::String("Idle");
pTk->HardReset();
printf("\nHard reset done");
throw gcnew System::Exception(gcnew System::String("GPU-level exception - Hard reset performed."));
}
templatefound = true;
}
Activity = gcnew System::String("SetReferenceZs");
bool valid = oC.SetReferenceZs(cf, istop);
}
catch (char *x)
{
printf("\nWarning: Cannot preload file %s", c_str(inputfiles[i]));
//throw gcnew System::String("Cannot preload file ") + inputfiles[i];
}
}
if (templatefound == false)
{
printf("\nERROR: Could not find any valid file to use as template.");
throw gcnew System::String("Could not find any valid file to use as template.");
}
float thickness = -1.0;
try
{
thickness = GetCurrentThickness();
printf("\nThickness %f", thickness);
}
catch (char *x)
{
printf("\nThickness error %s", x);
throw gcnew System::String("Thickness error.");
}
catch (System::String ^sx)
{
printf("\nThickness error %s", c_str(sx));
throw gcnew System::String("Thickness error.");
}
Activity = gcnew System::String("ConfigTracker");
SySal::Tracker &oT = pTk->Tracker();
{
SySal::Tracker::Configuration TC = *pTC;
TC.XYTolerance = TC.fXYTolerance * oT.GetXYScale();
TC.ZTolerance = TC.fZTolerance * oT.GetZScale();
TC.ZThickness = TC.fZThickness * oT.GetZScale();
TC.XYHashTableBinSize = TC.fXYHashTableBinSize * oT.GetXYScale();
TC.ZHashTableBinSize = TC.fZHashTableBinSize * oT.GetZScale();
TC.MinLength = TC.fMinLength * oT.GetXYScale();
TC.MaxLength = TC.fMaxLength * oT.GetXYScale();
TC.SlopeAcceptanceX = TC.fSlopeAcceptanceX * oT.GetSlopeScale();
TC.SlopeAcceptanceY = TC.fSlopeAcceptanceY * oT.GetSlopeScale();
TC.SlopeCenterX = TC.fSlopeCenterX * oT.GetSlopeScale();
TC.SlopeCenterY = TC.fSlopeCenterY * oT.GetSlopeScale();
TC.MergeTrackCell = TC.fMergeTrackCell * oT.GetXYScale();
TC.MergeTrackXYTolerance = TC.fMergeTrackXYTolerance * oT.GetXYScale();
TC.MergeTrackZTolerance = TC.fMergeTrackZTolerance * oT.GetZScale();
try
{
oT.Reset(TC);
}
catch (char *xstr)
{
throw gcnew System::Exception(gcnew System::String(xstr));
}
}
preloaderThread = gcnew System::Threading::Thread(gcnew System::Threading::ParameterizedThreadStart(this, &MapTracker::PreloadFiles));
preloaderThread->Start(inputfiles);
for (i = 0; i < inputfiles->Length; i++)
{
try
{
Activity = gcnew System::String("LoadFile");
while (PreloadQueue->Count == 0)
{
if (preloaderThread->Join(10) && PreloadQueue->Count == 0) throw gcnew System::Exception("Can't load file " + inputfiles[i]);
}
pcf = (SySal::IntClusterFile *)(void *)PreloadQueue->Dequeue();
if (pcf == 0) pcf = &EmptyClusterFile;
if (pix_x_override != 0.0f && pix_y_override != 0.0f)
{
*pcf->pPixMicronX = pix_x_override;
*pcf->pPixMicronY = pix_y_override;
}
SySal::ClusterChainer::EmulsionFocusInfo ef;
SySal::TrackMapHeader *pTkHdr = 0;
try
{
Activity = gcnew System::String("AddClusters");
ef = oC.AddClusters(*pcf);
Activity = gcnew System::String("Tracking");
pTkHdr = oT.Dump();
}
catch (...)
{
if (pcf != &EmptyClusterFile)
{
delete pcf;
pcf = 0;
}
printf("\nERROR-AT-GPU-LEVEL-EXCEPTION.\nError in \"%s\"\nPerforming hard reset.", c_str(Activity));
Activity = gcnew System::String("Idle");
pTk->HardReset();
printf("\nHard reset done");
throw gcnew System::Exception(gcnew System::String("GPU-level exception - Hard reset performed."));
}
if (rwdvsConsumer != nullptr && pTkHdr != 0)
{
Activity = gcnew System::String("FormattingOutput");
RawDataViewSide ^rwdds = gcnew RawDataViewSide(pTkHdr, *pcf, ef, zsideoffset, intinfo, istop);
if (pcf != &EmptyClusterFile)
{
delete pcf;
pcf = 0;
}
Activity = gcnew System::String("WritingOutput");
rwdvsConsumer->ConsumeData(i, istop, rwdds);
}
else
{
if (pcf != &EmptyClusterFile)
{
delete pcf;
pcf = 0;
}
}
if (PerfDumpFile != nullptr)
{
Activity = gcnew System::String("PerformanceCounterDump");
try
{
PrismMapTracker::PerformanceCounters pfc = pTk->GetPerformanceCounters();
if (System::IO::File::Exists(PerfDumpFile) == false)
System::IO::File::WriteAllText(PerfDumpFile, "GPU\tGPUClockMHz\tGPUCores\tClusters\tChains\tTracks\tMapTimeMS\tTrackTimeMS");
System::IO::File::AppendAllText(PerfDumpFile, gcnew System::String("\n") +
pfc.GPU.ToString() + gcnew System::String("\t") +
pfc.GPUClockMHz.ToString() + gcnew System::String("\t") +
pfc.GPUCores.ToString() + gcnew System::String("\t") +
pfc.Clusters.ToString() + gcnew System::String("\t") +
pfc.Chains.ToString() + gcnew System::String("\t") +
pfc.Tracks.ToString() + gcnew System::String("\t") +
pfc.MapTimeMS.ToString() + gcnew System::String("\t") +
pfc.TrackTimeMS.ToString());
}
catch (Exception ^xx) {}
}
}
catch (char *x)
{
throw gcnew System::Exception(gcnew System::String(x));
}
}
}
catch (System::Exception ^x)
{
Console::WriteLine("\r\n" + Activity);
throw x;
}
catch (...)
{
Console::WriteLine("\r\nGENERIC ERROR in " + Activity);
throw gcnew System::Exception("GENERIC");
}
finally
{
TerminatePreloadThread = true;
if (preloaderThread != nullptr)
preloaderThread->Join();
if (pcf && pcf != &EmptyClusterFile)
{
delete pcf;
pcf = 0;
}
while (PreloadQueue->Count > 0)
{
pcf = (SySal::IntClusterFile *)(void *)PreloadQueue->Dequeue();
delete pcf;
}
Activity = gcnew System::String("Idle");
}
}
System::String ^SySal::GPU::MapTracker::GetCurrentActivity() { return Activity; }
RawDataViewSide::RawDataViewSide(SySal::TrackMapHeader *ptkhdr, SySal::IntClusterFile &cf, SySal::ClusterChainer::EmulsionFocusInfo ef, float sideoffset, SySal::DAQSystem::Scanning::IntercalibrationInfo ^intinfo, bool istop)
{
m_Pos.X = (ptkhdr->MinX + ptkhdr->MaxX) * 0.5 / ptkhdr->XYScale;
m_Pos.Y = (ptkhdr->MinY + ptkhdr->MaxY) * 0.5 / ptkhdr->XYScale;
m_MapPos = intinfo->Transform(m_Pos);
SetM(this, intinfo->MXX, intinfo->MXY, intinfo->MYX, intinfo->MYY);
m_Flags = SySal::Scanning::Plate::IO::OPERA::RawData::Fragment::View::Side::SideFlags::OK;
cli::array<SySal::Scanning::Plate::IO::OPERA::RawData::Fragment::View::Side::LayerInfo> ^linfos =
gcnew cli::array<SySal::Scanning::Plate::IO::OPERA::RawData::Fragment::View::Side::LayerInfo>(cf.Images());
int i;
for (i = 0; i < linfos->Length; i++)
{
linfos[i].Grains = cf.ImageClusterCounts(i);
linfos[i].Z = cf.StageZ(i);
}
m_Layers = gcnew SySal::Scanning::Plate::IO::OPERA::RawData::Fragment::View::Side::LayerInfoList(linfos);
if (istop)
{
m_TopZ = ef.Top.Z - ef.Bottom.Z + sideoffset;
m_BottomZ = sideoffset;
}
else
{
m_TopZ = sideoffset;
m_BottomZ = sideoffset - (ef.Top.Z - ef.Bottom.Z);
}
m_Tracks = gcnew cli::array<SySal::Scanning::MIPIndexedEmulsionTrack ^>(ptkhdr->Count);
double ixyscale = 1.0 / ptkhdr->XYScale;
double izscale = 1.0 / ptkhdr->ZScale;
for (i = 0; i < m_Tracks->Length; i++)
{
SySal::Tracking::MIPEmulsionTrackInfo ^minfo = gcnew SySal::Tracking::MIPEmulsionTrackInfo();
IntTrack &itk = ptkhdr->Tracks[i];
minfo->Field = i;
minfo->Count = itk.Quality;
minfo->AreaSum = itk.Volume;
minfo->Slope.X = ((itk.X1 - itk.X2) * ixyscale) / ((itk.Z1 - itk.Z2) * izscale);
minfo->Slope.Y = ((itk.Y1 - itk.Y2) * ixyscale) / ((itk.Z1 - itk.Z2) * izscale);
minfo->Slope.Z = 1.0;
minfo->Intercept.Z = sideoffset;
minfo->Intercept.X = itk.X1 * ixyscale - itk.Z1 * izscale * minfo->Slope.X - m_Pos.X;
minfo->Intercept.Y = itk.Y1 * ixyscale - itk.Z1 * izscale * minfo->Slope.Y - m_Pos.Y;
minfo->TopZ = sideoffset + Math::Max(itk.Z1 * izscale, itk.Z2 * izscale);
minfo->BottomZ = sideoffset + Math::Min(itk.Z1 * izscale, itk.Z2 * izscale);
minfo->Sigma = Math::Sqrt(((itk.X1 - itk.X2) * ixyscale) * ((itk.X1 - itk.X2) * ixyscale) + ((itk.Y1 - itk.Y2) * ixyscale) * ((itk.Y1 - itk.Y2) * ixyscale) + ((itk.Z1 - itk.Z2) * izscale) * ((itk.Z1 - itk.Z2) * izscale));
SySal::Scanning::MIPIndexedEmulsionTrack ^mtk = gcnew SySal::Scanning::MIPIndexedEmulsionTrack(minfo, nullptr, i);
m_Tracks[i] = mtk;
}
}
}
} | [
"cbozza@km3net.de"
] | cbozza@km3net.de |
84d66637cbfc572773610167dd277650a401dc91 | 6501d76a9eb22f81b9e4c12f710b27029dfef70d | /divide and conquer/skyline.cpp | 19a3af170f68bbb68ab68feda1a6a29a2dcbf936 | [] | no_license | hanrick2000/data-structures | fe7f4d1eb563005e945439f735c62b8c21fe79d1 | ba23723ba2d99caa7fbf42ed203b7ccf01b40088 | refs/heads/master | 2020-12-03T17:10:14.421985 | 2017-01-09T07:22:01 | 2017-01-09T07:22:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | cpp | #include <iostream>
#include <priority_queue>
#include <algorithm>
using namespace std;
struct building
{
int x;
int height;
bool isStart;
};
int main()
{
return 0;
} | [
"tanvisurana20@gmail.com"
] | tanvisurana20@gmail.com |
549fde02ccbdb19aee3cd2cb09f22b72befae449 | 44243644a043acf539498840d5e5ae8df20a1fe9 | /Section 13/STL/ContainerChanges/ContainerChanges/main.cpp | edf35383882c675d8c71997b7a0e305b3f50f53d | [
"MIT"
] | permissive | tiagogomesti/beg_mod_cpp | 37365b88c54eccd86b1befb1f705c56dc7cff367 | f5fbeda349cf3f1894b7e2bef495ec0a4a2fa1b5 | refs/heads/main | 2023-06-07T03:18:49.106866 | 2021-06-12T08:39:06 | 2021-06-12T08:39:06 | 381,865,204 | 0 | 0 | MIT | 2021-07-01T00:24:17 | 2021-07-01T00:24:16 | null | UTF-8 | C++ | false | false | 2,277 | cpp | #include <deque>
#include "Integer.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <filesystem>
#include <set>
void Emplace() {
std::vector<Integer> vInt ;
Integer val{5} ;
//vInt.push_back(val) ;
vInt.emplace_back(val) ;
std::vector<std::pair<int, std::string>> data ;
data.push_back(std::pair<int, std::string>{100, "C++"}) ;
data.emplace_back(100, "C++") ;
}
void Shrink() {
std::vector<int> vInt ;
for(size_t i = 0 ; i < 100 ; ++i) {
vInt.emplace_back(i) ;
}
std::cout << "Size:" << vInt.size() << '\n' ;
std::cout << "Capacity:" << vInt.capacity() << '\n' ;
vInt.erase(vInt.begin(), vInt.end()-10) ;
std::cout <<"After erase & shrink_to_fit\n" ;
vInt.shrink_to_fit() ;
std::cout << "Size:" << vInt.size() << '\n' ;
std::cout << "Capacity:" << vInt.capacity() << '\n' ;
}
void VectorFunctions() {
std::ifstream input{"main.cpp"} ;
if(!input) {
std::cout << "Could not open file\n" ;
return ;
}
auto size = std::filesystem::file_size("main.cpp") ;
//std::vector<char> buffer ;
std::string buffer ;
buffer.resize(size) ;
//char * buff = new char[size]{};
input.read(buffer.data(), size) ;
std::cout << buffer.data() << '\n' ;
//delete []buff ;
}
template<typename Container>
void Print(const Container &cont, const char *msg="") {
std::cout << msg << '\n' ;
for(auto a : cont) {
std::cout << a << '\n' ;
}
}
void Erase() {
std::vector<int> vInt{1,2,3,4,2} ;
std::list<int> lstInt{1,2,3,4,2} ;
std::deque<int> deqInt{1,2,3,4,2} ;
std::erase(vInt,2) ;
std::erase(lstInt,2) ;
std::erase(deqInt,2) ;
Print(vInt, "vector") ;
Print(lstInt, "list") ;
Print(deqInt, "deque") ;
}
int main() {
//std::set<int> data{1,2,6,3} ;
//data.emplace_hint(data.begin(),0) ;
//auto it = data.find(6) ;
//if(it != data.end()) {
// std::cout << "Found\n" ;
//}
//auto found = data.contains(6) ;
//if(found){
// std::cout << "Found\n" ;
//}
std::set<std::string> names{"Omar", "Ayaan", "Raihaan"} ;
auto it = names.find("Omar") ;
auto name = *it ;
name[0] = 'U' ;
names.erase(it) ;
names.insert(name) ;
auto node = names.extract(it) ;
node.value()[0] = 'U' ;
names.insert(std::move(node)) ;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
5eeb84d69987f7069680241ac00233e89661ac88 | 485539af8461d2ce2119bafca181b002703b6653 | /Usaco/Chapter_3/Section_2/fact4.cpp | f6a66de1b15058b089476f258b4c05a1fdb39642 | [] | no_license | joaogui1/Competitive-Programming | f6cea58c7460011b366b04497e69cef97f86cdd1 | 8e7a0eb0f4a48ec3fd5b01b0510bc1ec7a4c46bf | refs/heads/master | 2021-06-16T21:43:57.442360 | 2021-02-06T11:26:01 | 2021-02-06T11:26:01 | 137,510,703 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | cpp | /*
ID: joaogui1
LANG: C++
TASK: fact4
*/
#include <cstdio>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
long long int ans = 1LL, n;
ifstream fin ("fact4.in");
ofstream fout ("fact4.out");
fin >> n;
for(long long int i = 1LL; i <= n; ++i){
ans*=i;
while(ans%10LL == 0LL){
//printf("%lld ans\n", ans);
ans/=10LL;
}
ans %= 1000000000LL;
}
fout << ans%10LL << endl;
return 0;
}
| [
"joaoguilhermearujo@gmail.com"
] | joaoguilhermearujo@gmail.com |
1b892124e6155f52ce27e5b20cffc37cb98ef49d | 9f2a8b3e68533442708087dd365f80889f739bea | /include/pqxx/internal/gates/transaction-tablereader.hxx | ecfb9dff63079fa1325531be0c5aba0af50af9ed | [
"BSD-3-Clause"
] | permissive | svn2github/libpqxx | 195c5e356cea6cad9ac419b765a407c1a192a049 | 575ea1f3be63eea1f5c834eb446800ca5995aff0 | refs/heads/master | 2020-12-25T17:25:54.544025 | 2016-08-19T16:16:30 | 2016-08-19T16:16:30 | 40,840,037 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 542 | hxx | #include <pqxx/internal/callgate.hxx>
namespace pqxx
{
namespace internal
{
namespace gate
{
class PQXX_PRIVATE transaction_tablereader : callgate<transaction_base>
{
friend class pqxx::tablereader;
transaction_tablereader(reference x) : super(x) {}
void BeginCopyRead(const std::string &table, const std::string &columns)
{ home().BeginCopyRead(table, columns); }
bool ReadCopyLine(std::string &line) { return home().ReadCopyLine(line); }
};
} // namespace pqxx::internal::gate
} // namespace pqxx::internal
} // namespace pqxx
| [
"jtv@c3353b84-d008-0410-9ed9-b55c4f7fa7e8"
] | jtv@c3353b84-d008-0410-9ed9-b55c4f7fa7e8 |
aea48827a970be9b01e80fa811c61cf20607d803 | 83f42bc30aaf2ea058082b971a0de6975e7f9eca | /macro-benchmark/kthread_scatter.cc | d75069ad6c737b020183402675fb79cc6caa0c71 | [
"MIT"
] | permissive | RapidsAtHKUST/manymap | 68b8eb003a4c53d533d715de7fed4a5e4ead1e7c | 16ed667f93541ba901b2e3c7d118eb4b3bc3aa1b | refs/heads/master | 2022-11-07T08:28:27.901877 | 2020-06-18T08:31:33 | 2020-06-18T08:31:33 | 273,159,841 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,608 | cc | #include <pthread.h>
#include <stdlib.h>
#include <limits.h>
#include <stdint.h>
#include "kthread.h"
#include <sched.h>
#include <unistd.h>
#if (defined(WIN32) || defined(_WIN32)) && defined(_MSC_VER)
#define __sync_fetch_and_add(ptr, addend) _InterlockedExchangeAdd((void*)ptr, addend)
#endif
/************
* kt_for() *
************/
struct kt_for_t;
typedef struct {
struct kt_for_t *t;
long i;
} ktf_worker_t;
typedef struct kt_for_t {
int n_threads;
long n;
ktf_worker_t *w;
void (*func)(void*,long,int);
void *data;
} kt_for_t;
static inline long steal_work(kt_for_t *t)
{
int i, min_i = -1;
long k, min = LONG_MAX;
for (i = 0; i < t->n_threads; ++i)
if (min > t->w[i].i) min = t->w[i].i, min_i = i;
k = __sync_fetch_and_add(&t->w[min_i].i, t->n_threads);
return k >= t->n? -1 : k;
}
static void *ktf_worker(void *data)
{
ktf_worker_t *w = (ktf_worker_t*)data;
long i;
for (;;) {
i = __sync_fetch_and_add(&w->i, w->t->n_threads);
if (i >= w->t->n) break;
w->t->func(w->t->data, i, w - w->t->w);
}
while ((i = steal_work(w->t)) >= 0)
w->t->func(w->t->data, i, w - w->t->w);
pthread_exit(0);
}
void kt_for(int n_threads, void (*func)(void*,long,int), void *data, long n)
{
if (n_threads > 1) {
int i;
kt_for_t t;
pthread_t *tid;
t.func = func, t.data = data, t.n_threads = n_threads, t.n = n;
t.w = (ktf_worker_t*)calloc(n_threads, sizeof(ktf_worker_t));
tid = (pthread_t*)calloc(n_threads, sizeof(pthread_t));
pthread_attr_t attr;
cpu_set_t cpus;
pthread_attr_init(&attr);
int thr = 0; // 0, 1, 2, 3
for (i = 0; i < n_threads; ++i)
t.w[i].t = &t, t.w[i].i = i;
for (i = 0; i < n_threads; ++i) {
CPU_ZERO(&cpus);
CPU_SET(thr++, &cpus);
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&tid[i], &attr, ktf_worker, &t.w[i]);
}
for (i = 0; i < n_threads; ++i) pthread_join(tid[i], 0);
free(tid); free(t.w);
} else {
long j;
for (j = 0; j < n; ++j) func(data, j, 0);
}
}
/*****************
* kt_pipeline() *
*****************/
struct ktp_t;
typedef struct {
struct ktp_t *pl;
int64_t index;
int step;
void *data;
} ktp_worker_t;
typedef struct ktp_t {
void *shared;
void *(*func)(void*, int, void*);
int64_t index;
int n_workers, n_steps;
ktp_worker_t *workers;
pthread_mutex_t mutex;
pthread_cond_t cv;
} ktp_t;
static void *ktp_worker(void *data)
{
ktp_worker_t *w = (ktp_worker_t*)data;
ktp_t *p = w->pl;
while (w->step < p->n_steps) {
// test whether we can kick off the job with this worker
pthread_mutex_lock(&p->mutex);
for (;;) {
int i;
// test whether another worker is doing the same step
for (i = 0; i < p->n_workers; ++i) {
if (w == &p->workers[i]) continue; // ignore itself
if (p->workers[i].step <= w->step && p->workers[i].index < w->index)
break;
}
if (i == p->n_workers) break; // no workers with smaller indices are doing w->step or the previous steps
pthread_cond_wait(&p->cv, &p->mutex);
}
pthread_mutex_unlock(&p->mutex);
// working on w->step
w->data = p->func(p->shared, w->step, w->step? w->data : 0); // for the first step, input is NULL
// update step and let other workers know
pthread_mutex_lock(&p->mutex);
w->step = w->step == p->n_steps - 1 || w->data? (w->step + 1) % p->n_steps : p->n_steps;
if (w->step == 0) w->index = p->index++;
pthread_cond_broadcast(&p->cv);
pthread_mutex_unlock(&p->mutex);
}
pthread_exit(0);
}
void kt_pipeline(int n_threads, void *(*func)(void*, int, void*), void *shared_data, int n_steps)
{
ktp_t aux;
pthread_t *tid;
int i;
if (n_threads < 1) n_threads = 1;
aux.n_workers = n_threads;
aux.n_steps = n_steps;
aux.func = func;
aux.shared = shared_data;
aux.index = 0;
pthread_mutex_init(&aux.mutex, 0);
pthread_cond_init(&aux.cv, 0);
aux.workers = (ktp_worker_t*)calloc(n_threads, sizeof(ktp_worker_t));
for (i = 0; i < n_threads; ++i) {
ktp_worker_t *w = &aux.workers[i];
w->step = 0; w->pl = &aux; w->data = 0;
w->index = aux.index++;
}
tid = (pthread_t*)calloc(n_threads, sizeof(pthread_t));
// pthread_attr_t attr;
// cpu_set_t cpus;
// pthread_attr_init(&attr);
for (i = 0; i < n_threads; ++i) {
// CPU_ZERO(&cpus);
// CPU_SET(i, &cpus);
// pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&tid[i], 0, ktp_worker, &aux.workers[i]);
}
for (i = 0; i < n_threads; ++i) pthread_join(tid[i], 0);
free(tid); free(aux.workers);
pthread_mutex_destroy(&aux.mutex);
pthread_cond_destroy(&aux.cv);
}
| [
"unisolate@gmail.com"
] | unisolate@gmail.com |
5f18905843a26ad24bae146d628bf658ede8e936 | b444b77e43237b26c184762dd1cc9329c7928238 | /Shot.cpp | b33f8ba258f35d89dd8e221f8c651015076a07b7 | [] | no_license | sarjade9029/gameuploadtest_sora_hanada | 95b108e534e616e651a7ec113132bf340ccb70bd | ceb984c0cdda8f81c6b91eff54e02c1da2e40b01 | refs/heads/master | 2020-05-21T13:25:17.849281 | 2019-05-12T02:12:48 | 2019-05-12T02:12:48 | 186,071,186 | 0 | 0 | null | 2019-05-18T05:15:34 | 2019-05-11T00:45:21 | C++ | UTF-8 | C++ | false | false | 2,765 | cpp | #include "Shot.h"
#include "HitCheck.h"
//弾の初期化
void Shot::Init()
{
Graph = LoadGraph("data/texture/blueshot.png");
VisibleFlag = false;
directionflag = false;
wite = 15;
Dmg = 1;
GetGraphSizeF(Graph, &W, &H);
Ys = 10;
Xs = 10;
Shotflag = false;
}
void Shot::Setshot(Player* player)
{
//プレイヤーの画像の中央を取る
//プレイヤーの横幅の中心
X = (player->positionX) + (player->width*0.75);
//プレイヤーの縦の中心
Y = (player->positionY) + (player->height*0.75);
if (Shotflag == false && player->direction != 0)
{
VisibleFlag = true;
directionflag = true;
Shotflag = true;
}
//生きているならもしくは生き返らせたなら方向を決める
if (Shotflag == true)
{
if (player->direction == 2 || player->direction2 == 2)
{
//画像回転
South = true;
}
if (player->direction == 4 || player->direction2 == 4)
{
//画像回転
West = true;
}
if (player->direction == 6 || player->direction2 == 6)
{
//画像回転
East = true;
}
if (player->direction == 8 || player->direction2 == 8)
{
//画像回転
North = true;
}
player->shotIntervalCount = wite;
}
}
//弾の更新(弾の移動と当たり判定
void Shot::Update(Scr&scr)
{
if(directionflag == true)//動いている
{
if (South == true)
{
Y += Ys;
}
if (North == true)
{
Y -= Ys;
}
if (West == true)
{
X -= Xs;
}
if (East == true)
{
X += Xs;
}
}
if (X > SCREEN_W - W + scr.scrX|| X < 64 || Y < 64 || Y > SCREEN_H - H + scr.scrY || X > SCREEN_W * 2 - (W + 64) || Y > SCREEN_H * 2 - (H + 48) || X < scr.scrX || Y < scr.scrY)//動いていなかったら弾の挙動がおかしくなる、消えないし
{
VisibleFlag = false;
}
if (VisibleFlag == false)
{
directionflag = false;
Shotflag = false;
South = false;
North = false;
East = false;
West = false;
}
}
//弾の描画
void Shot::Draw(Scr&scr)
{
//最初の一発は画像がおかしくなることがある(斜めを二つ描画している)
if (VisibleFlag == true)
{
// 画面に弾iを描画する
if (South || North)
{
if (!East && !West)
{
DrawRotaGraph2F(X - scr.scrX,Y - scr.scrY,0.0,0.0,1.0, 0.0,Graph, TRUE);//上下
}
}
if (East || West)
{
if (!South && !North)
{
DrawRotaGraph2F(X - scr.scrX,Y - scr.scrY,0.0,0.0,1.0, DX_PI_F/2,Graph, TRUE);//左右
}
}
if ((North && East) || (South && West))
{
DrawRotaGraph2F(X - scr.scrX,Y - scr.scrY,0.0,0.0,1.0, DX_PI_F/4,Graph, TRUE);//斜め右上or左下
}
if ((North && West) || (South && East))
{
DrawRotaGraph2F(X - scr.scrX,Y - scr.scrY,0.0,0.0,1.0, DX_PI_F*1.75,Graph, TRUE);//斜め左上or右下
}
}
} | [
"ds215323@gmail.com"
] | ds215323@gmail.com |
ea17d0c54ffd203c94fde85545735853580af8ef | c95332a7c69f6f80afe36a703fe432f2a8bf777e | /KSPIO-HUD/Input.ino | b62212059b7c16c205cc40416f378727d3e6ece9 | [] | no_license | Scoppio/KSPIO-AVIONICS | eee83918279daf3ed5478d5516b62a503c9e762e | d0fc3e469ccc3707c9fb019f2741a0dce5819388 | refs/heads/master | 2020-05-20T09:33:17.035416 | 2015-09-20T03:26:59 | 2015-09-20T03:26:59 | 42,062,519 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | ino | int input() {
int returnValue = -1;
now = millis();
if (KSPBoardReceiveData()){
deadtimeOld = now;
returnValue = id;
switch(id) {
case 0: //Handshake packet
Handshake();
break;
case 1:
//Indicators();
break;
}
//We got some data, turn the green led on
//digitalWrite(GLED,HIGH);
Connected = true;
}
else
{ //if no message received for a while, go idle
deadtime = now - deadtimeOld;
if (deadtime > IDLETIMER)
{
deadtimeOld = now;
Connected = false;
//LEDSAllOff();
}
}
return returnValue;
}
byte ControlStatus(byte n)
{
return ((VData.ActionGroups >> n) & 1) == 1;
}
| [
"lucascoppio@gmail.com"
] | lucascoppio@gmail.com |
d61bb0379447f5a2350ca4c06c8f914c1117220c | 7a7ee8cca53e90f3876c5467162cb0eb9b3bcf9d | /Engine/Logic/gkObjectNode.cpp | 31ea1a87fd4677dd4f0bbbcd4b67b8414b84ca58 | [] | no_license | cnsuhao/gamekit | 1a7818426c5235330417c84d927f26e2cc14616d | 7f898af29bb19ccb0995e39276a01a3adf0169a0 | refs/heads/master | 2021-05-26T20:06:36.266706 | 2012-05-20T17:00:26 | 2012-05-20T17:00:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,800 | cpp | /*
-------------------------------------------------------------------------------
This file is part of OgreKit.
http://gamekit.googlecode.com/
Copyright (c) 2006-2010 Charlie C.
Contributor(s): Nestor Silveira.
-------------------------------------------------------------------------------
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-------------------------------------------------------------------------------
*/
#include "gkObjectNode.h"
#include "gkEngine.h"
#include "gkGameObject.h"
#include "gkScene.h"
using namespace Ogre;
gkObjectNode::gkObjectNode(gkLogicTree* parent, size_t id) :
gkLogicNode(parent, id), m_otherName(""), m_func(OB_FUNC_NONE)
{
ADD_ISOCK(INPUT, true);
ADD_ISOCK(IN_POSITION, gkVector3::ZERO);
ADD_ISOCK(IN_ROTATION, gkVector3::ZERO);
ADD_OSOCK(OUTPUT, false);
ADD_OSOCK(OUT_POSITION, gkVector3::ZERO);
ADD_OSOCK(OUT_ROTATION, gkVector3::ZERO);
}
bool gkObjectNode::evaluate(gkScalar tick)
{
bool update = GET_SOCKET_VALUE(INPUT);
SET_SOCKET_VALUE(OUTPUT, update);
return update;
}
void gkObjectNode::initialize()
{
if (!m_otherName.empty())
{
// look at global scope
if (!m_other)
{
if (m_object)
{
gkScene* scene = m_object->getOwner();
GK_ASSERT(scene);
m_other = scene->getObject(m_otherName);
}
}
}
}
void gkObjectNode::update(gkScalar tick)
{
gkGameObject* ob = m_other ? m_other : m_object;
if (!ob)
return;
if (GET_SOCKET(IN_POSITION)->isLinked())
ob->setPosition(GET_SOCKET_VALUE(IN_POSITION));
else
SET_SOCKET_VALUE(OUT_POSITION, ob->getPosition());
if (GET_SOCKET(IN_ROTATION)->isLinked())
{
gkQuaternion q = gkMathUtils::getQuatFromEuler(GET_SOCKET_VALUE(IN_ROTATION), true);
ob->setOrientation(q);
SET_SOCKET_VALUE(OUT_ROTATION, GET_SOCKET_VALUE(IN_ROTATION));
}
else
SET_SOCKET_VALUE(OUT_ROTATION, gkMathUtils::getEulerFromQuat(ob->getOrientation(), true));
}
| [
"exeqtor@gmail.com"
] | exeqtor@gmail.com |
c8a913425cc62bfcc174d4ec65db9c1526dbc8dd | a176813cf63402278dc21cef757f6092387f560a | /src/chain.h | 3717875bb18f6f221e3446d67304087d6ecdeb67 | [
"MIT"
] | permissive | Voicoin/master | 1a6ff0d2bf1f5c124717ae3f21fd9c2d4495388d | 3a2e01cca1c76fd99db508a07a4ddd896d7a6e64 | refs/heads/master | 2020-04-04T14:38:30.001202 | 2018-11-25T00:01:05 | 2018-11-25T00:01:05 | 156,006,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,400 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018-2019 The voi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CHAIN_H
#define BITCOIN_CHAIN_H
#include "pow.h"
#include "primitives/block.h"
#include "tinyformat.h"
#include "uint256.h"
#include "util.h"
#include <vector>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
struct CDiskBlockPos {
int nFile;
unsigned int nPos;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
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); }
};
enum BlockStatus {
//! Unused.
BLOCK_VALID_UNKNOWN = 0,
//! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_HEADER = 1,
//! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
//! are also at least TREE.
BLOCK_VALID_TREE = 2,
/**
* Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
* sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
* parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
*/
BLOCK_VALID_TRANSACTIONS = 3,
//! Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30.
//! Implies all parents are also at least CHAIN.
BLOCK_VALID_CHAIN = 4,
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
BLOCK_VALID_SCRIPTS = 5,
//! All validity bits.
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN |
BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //! descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
};
/** 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. A blockindex may have multiple pprev pointing
* to it, but at most one of them can be part of the currently active branch.
*/
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;
//! pointer to the index of the next block
CBlockIndex* pnext;
//! pointer to the index of some further predecessor of this block
CBlockIndex* pskip;
//ppcoin: trust score of block chain
uint256 bnChainTrust;
//! 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.
//! This value will be non-zero only if and only if transactions for this block and all its parents are available.
//! Change to 64-bit type when necessary; won't happen before 2030
unsigned int nChainTx;
//! Verification status of this block. See enum BlockStatus
unsigned int nStatus;
unsigned int nFlags; // ppcoin: block index flags
enum {
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
// proof-of-stake specific fields
uint256 GetBlockTrust() const;
uint64_t nStakeModifier; // hash modifier for proof-of-stake
unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProofOfStake;
int64_t nMint;
int64_t nMoneySupply;
//! block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
uint32_t nSequenceId;
void SetNull()
{
phashBlock = NULL;
pprev = NULL;
pskip = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nSequenceId = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = uint256();
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex()
{
SetNull();
}
CBlockIndex(const CBlock& block)
{
SetNull();
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
//Proof of Stake
bnChainTrust = uint256();
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = uint256();
if (block.IsProofOfStake()) {
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.nTime;
} else {
prevoutStake.SetNull();
nStakeTime = 0;
}
}
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_t GetBlockTime() const
{
return (int64_t)nTime;
}
enum { nMedianTimeSpan = 11 };
int64_t GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* 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];
}
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
unsigned int nEntropyBit = ((GetBlockHash().Get64()) & 1);
if (fDebug || GetBoolArg("-printstakemodifier", false))
LogPrintf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetBlockHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit ? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
* and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
//! Check whether this block index entry is valid up to the passed validity level.
bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
//! Build the skiplist pointer for this entry.
void BuildSkip();
//! Efficiently find an ancestor of this block.
CBlockIndex* GetAncestor(int height);
const CBlockIndex* GetAncestor(int height) const;
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = uint256();
hashNext = uint256();
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
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));
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
if (IsProofOfStake()) {
READWRITE(prevoutStake);
READWRITE(nStakeTime);
} else {
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = uint256();
}
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashNext);
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(),
hashPrev.ToString());
return str;
}
};
/** An in-memory indexed chain of blocks. */
class CChain
{
private:
std::vector<CBlockIndex*> vChain;
public:
/** Returns the index entry for the genesis block of this chain, or NULL if none. */
CBlockIndex* Genesis() const
{
return vChain.size() > 0 ? vChain[0] : NULL;
}
/** Returns the index entry for the tip of this chain, or NULL if none. */
CBlockIndex* Tip(bool fProofOfStake = false) const
{
if (vChain.size() < 1)
return NULL;
CBlockIndex* pindex = vChain[vChain.size() - 1];
if (fProofOfStake) {
while (pindex && pindex->pprev && !pindex->IsProofOfStake())
pindex = pindex->pprev;
}
return pindex;
}
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
int64_t GetNetworkHashPS(int lookup, int height);
/** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
CBlockIndex* operator[](int nHeight) const
{
if (nHeight < 0 || nHeight >= (int)vChain.size())
return NULL;
return vChain[nHeight];
}
/** Compare two chains efficiently. */
friend bool operator==(const CChain& a, const CChain& b)
{
return a.vChain.size() == b.vChain.size() &&
a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
}
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex* pindex) const
{
return (*this)[pindex->nHeight] == pindex;
}
/** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
CBlockIndex* Next(const CBlockIndex* pindex) const
{
if (Contains(pindex))
return (*this)[pindex->nHeight + 1];
else
return NULL;
}
/** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
int Height() const
{
return vChain.size() - 1;
}
/** Set/initialize a chain with a given tip. */
void SetTip(CBlockIndex* pindex);
/** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
CBlockLocator GetLocator(const CBlockIndex* pindex = NULL) const;
/** Find the last common block between this chain and a block index entry. */
const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
};
#endif // BITCOIN_CHAIN_H
| [
"exafanizol@gmail.com"
] | exafanizol@gmail.com |
6a752bd72748e2f859738561223fe948b3bebd11 | 69c184211f0f89691116d3b4af17ceaf4c50225d | /src/bullet_physics_component.h | e894521b43a1fb722014922f1e5c75c2eaf75c4e | [] | no_license | calebpalmer/spacegame | 0e29fb331d067180b630c33ade057a4c5f616057 | 2685bda4dbf4d1d8c5cb4e666542521b99ff67e0 | refs/heads/master | 2021-01-01T17:09:31.293192 | 2015-03-22T10:30:40 | 2015-03-22T10:30:40 | 15,512,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | h | #ifndef BULLET_PHYSICS_COMPONENT
#define BULLET_PHYSICS_COMPONENT
#include "gameobject.h"
class BulletPhysicsComponent : public PhysicsComponent {
public:
BulletPhysicsComponent(int width = 10, int height = 10);
virtual void update(GameObject* object, double timestep);
virtual CapEngine::Rectangle boundingPolygon(const GameObject* object) const;
virtual bool handleCollision(GameObject* object, CapEngine::CollisionType, CapEngine::CollisionClass, GameObject* otherObject);
private:
int width;
int height;
};
#endif
| [
"palmer.caleb@gmail.com"
] | palmer.caleb@gmail.com |
0b4d1f67331dc9bb02df350cdba6aea556628676 | cbe732f5d619086c4feabb57d7c456c1fa116631 | /Ch 6 - Objects, Classes and Inheritance/Ex01 - Inheritance/Human.h | 2c0befbc914b18cdaeae955e85b242c9b5483424 | [] | no_license | aadarshasubedi/Learning-CPlusPlus-by-Creating-Games-w-UE4 | 3e7387b10c142fb453cebb8d27a9d1144514eac7 | 9051530f1a0177313fb3a0d83f350227653f3d9d | refs/heads/master | 2020-12-11T04:09:02.573093 | 2016-03-11T23:16:17 | 2016-03-11T23:16:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 208 | h | #pragma once
#include "Mammal.h"
class Human : public Mammal
{
bool civilized;
public:
Human();
~Human();
virtual void talk() override;
virtual void walk() override;
void attack(Human &other);
};
| [
"markums@gmail.com"
] | markums@gmail.com |
96dfc38ff131dd63fc1c6a66d00d160a322ef7a3 | d472433029b4642bdd8d272b173bc2cc8c52ae5d | /2/496.cpp | 680c35b9f771765c931b4fecdbe442b80817b004 | [] | no_license | hostgame/algorithms | 085ecb9ccd2d90da7a0555c6ccc340e18fb54f02 | b5933945c697fc327dd3202d94e86e290c6f85ee | refs/heads/master | 2020-03-17T05:17:09.967142 | 2018-05-15T06:07:59 | 2018-05-15T06:07:59 | 133,310,015 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | cpp | #include <bits/stdc++.h>
using namespace std;
int digits (int n)
{
int number_of_digits;
do {
++number_of_digits;
n /= 10;
} while (n);
return number_of_digits;
}
int main ()
{
string linea;
string lineb;
while(getline(cin, linea))
{
getline(cin, lineb);
vector <int> a;
vector <int> b;
istringstream sinpa (linea);
istringstream sinpb (lineb);
int temp;
while (sinpa >> temp)
a.push_back(temp);
while (sinpb >> temp)
b.push_back(temp);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int sizea = a.size();
int sizeb = b.size();
vector <int> c;
vector <int> d;
c = a;
d = b;
for (int i = 0; i < sizea; i++)
{
if (binary_search(d.begin(), d.end(), a[i]))
d.erase(remove(d.begin(), d.end(), a[i]), d.end());
}
for (int i = 0; i < sizeb; i++)
{
if (binary_search(c.begin(), c.end(), b[i]))
c.erase(remove(c.begin(), c.end(), b[i]), c.end());
}
if (c.size() == 0 and d.size() == 0)
cout << "A equals B" << endl;
else if (c.size() == 0)
cout << "A is a proper subset of B" << endl;
else if (d.size() == 0)
cout << "B is a proper subset of A" << endl;
else if (c.size() == sizea and d.size() == sizeb)
cout << "A and B are disjoint" << endl;
else cout << "I'm confused!" << endl;
}
return 0;
}
| [
"ershov_g@auca.kg"
] | ershov_g@auca.kg |
c4c485cd107b1aec0abc4ceadbfc48822dd3a3ca | 639287c8055492a861d48b8805aa7f5503c03f99 | /examples/OC10_ToggleOutput/OC10_ToggleOutput.ino | 8df7ca9ae4e4f5e85f0dddbddf72c658025f3dd8 | [
"MIT"
] | permissive | xinabox/arduino-OC10 | 85d5090ac1af68fac05b51588e49e44a205abdb6 | 086f3af5e3d0797b9e0b6b9151eb6420b19aec02 | refs/heads/master | 2020-04-05T07:30:10.477281 | 2019-05-15T09:03:54 | 2019-05-15T09:03:54 | 156,677,662 | 0 | 1 | MIT | 2019-05-15T09:03:55 | 2018-11-08T08:54:13 | C++ | UTF-8 | C++ | false | false | 1,143 | ino | /*************************************************************
This is an examples for the OC10
Mechanical Relay
You can buy one on our store!
-----> https://xinabox.cc/products/OC10/
This example in structs the OC10 to turn its output
on and off
The sensor communicates over the I2C Bus.
*************************************************************/
/********************* Library Includes *********************/
#include <arduino-OC10.h> // https://github.com/xinabox/arduino-OC10
#include <xCore.h>
/****************** Global sensor objects *******************/
xOC10 OC10;
/********************* SYSTEM VARIABLES *********************/
const int DELAY_TIME = 2000;
/*********************** Sketch Code ************************/
void setup() {
// Start the Serial Monitor
Serial.begin(115200);
#ifdef ESP8266
Wire.pins(2,14);
#endif
// Start the I2C Communication
Wire.begin();
// Start the OC10 port expander
OC10.begin();
Serial.println("OC10 Test");
}
void loop() {
// Switch OUT on
OC10.digitalWrite(HIGH);
delay(DELAY_TIME);
// Switch OUT off
OC10.digitalWrite(LOW);
delay(DELAY_TIME);
} | [
"brendanvanbreda1993@gmail.com"
] | brendanvanbreda1993@gmail.com |
9d236b1a6d32fdcfe006d00122ec3469125b8eed | 4e940e92366d286de5c1d15fdbd2444dcc0f80f3 | /bag/bag/utility.h | d636f08cc02c8107839f5faac82108adf293fe07 | [] | no_license | dsball/CSC-161 | 54305ed977da3ec5f7c33bcae21d8ceec8b28c01 | ac0b01e523099a90b9321448dc7f6aa1b70ffe63 | refs/heads/master | 2016-08-07T06:37:09.121213 | 2013-02-16T19:52:28 | 2013-02-16T19:52:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | h | /*------------------------------------utility.h
Purpose: provides general utility functions, headers, and generic using declarations.
--- Member Data ---
Name Type Description
-------------------------------------------------------------------------------------------
none
--- Functions ---
Name Return Description; Parameter description
--------------------------------------------------------------------------------------------
pause() void replace system("PAUSE") with non-system function call
no params
printFile(string) void opens a file and prints it with fileToString()
string: relative path of file being printed
fileToString(ifstream &inFile) void stores an ifstream in a string and returns it
ifstream&: ifstream to be read
*/
#ifndef _UIMANIP_INTERFACE_
#define _UIMANIP_INTERFACE_
#include<string>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<vector>
#include<windows.h>
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::string;
using std::vector;
using std::setw;
using std::to_string;
using std::string;
using std::left;
void pause();
bool printFile(string);
string fileToString(ifstream&);
#endif | [
"wolfwoodster@gmail.com"
] | wolfwoodster@gmail.com |
275c5a98f2da1217309c8d5dbe2e47a45ea9c897 | b81ab5ab0c18277ec2a99a1774001d1958d42460 | /src/bitacora.h | 73009f23a1388017da6705b012b0975cd7e578bd | [] | no_license | threevanny/Simulation-Elevator-algorithm | 1eb06fd1a7101390d46d0cbef602d0defd724a86 | e1abeefab5aa865e3f95322421e009a7033f9ce6 | refs/heads/master | 2022-09-22T06:04:13.658538 | 2020-06-03T22:45:05 | 2020-06-03T22:45:05 | 226,188,191 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 725 | h | //bitacora.h
#ifndef BITACORA_H
#define BITACORA_H
class Piso; //declaración forward
class Bitacora{
private:
void programaTiempo(const Piso & ); //tiempo de la bitacora de llegada a piso
void tiempoRetardo(const Piso & ); //tiempo de retardo de llegada piso
void creaNuevaPersona(Piso & ); //crea nueva persona, la coloca en el piso
void manipulaLlegadas(Piso &, int ); //manipulador de llegada de la persona a un piso
int tiempoActualDeReloj;
Piso &refPiso1;
Piso &refPiso2;
int tiempoLlegadaPiso1;
int tiempoLlegadaPiso2;
public:
Bitacora(Piso &, Piso &); //constructor
~Bitacora(); //destructor
void tiempoProceso(int); //establece el tiempo de la bitacora
};
#endif
| [
"ggeovannyreyes@gmail.com"
] | ggeovannyreyes@gmail.com |
8007a3c74c45710b73a5607779432f2507a24dce | 8f9ea3f14bdf2187de759939b2bbc87fe68ccfc0 | /tensorflow/stream_executor/stream.h | 3da1b856d6a41fa0c8d5a77feac33932da392422 | [
"Apache-2.0"
] | permissive | davidstanke/bazel-mvn-demo | 4ea43f0ba293a28b916a27eab5f0812e9b753c2c | cff14dddce15ea7152988da576673bd15bab6c6e | refs/heads/master | 2022-10-20T07:52:29.651851 | 2018-11-22T13:17:51 | 2018-11-22T13:17:51 | 157,782,756 | 2 | 0 | Apache-2.0 | 2022-10-04T23:47:05 | 2018-11-15T22:54:09 | C++ | UTF-8 | C++ | false | false | 112,403 | h | /* 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.
==============================================================================*/
// The Stream is used in conjunction with the StreamExecutor "parent" to
// perform actions with a linear stream of dependencies. Dependencies can also
// be created between Streams to do task management (i.e. limit which tasks
// can be performed concurrently and specify what task dependencies exist).
#ifndef TENSORFLOW_STREAM_EXECUTOR_STREAM_H_
#define TENSORFLOW_STREAM_EXECUTOR_STREAM_H_
#include <complex>
#include <functional>
#include <memory>
#include "tensorflow/stream_executor/blas.h"
#include "tensorflow/stream_executor/device_memory.h"
#include "tensorflow/stream_executor/dnn.h"
#include "tensorflow/stream_executor/event.h"
#include "tensorflow/stream_executor/fft.h"
#include "tensorflow/stream_executor/host_or_device_scalar.h"
#include "tensorflow/stream_executor/kernel.h"
#include "tensorflow/stream_executor/launch_dim.h"
#include "tensorflow/stream_executor/lib/array_slice.h"
#include "tensorflow/stream_executor/platform/mutex.h"
#include "tensorflow/stream_executor/platform/port.h"
#include "tensorflow/stream_executor/platform/thread_annotations.h"
#include "tensorflow/stream_executor/temporary_memory_manager.h"
namespace stream_executor {
namespace host {
class HostBlas;
class HostFft;
class HostRng;
class HostTimer;
} // namespace host
namespace ocl {
class CLBlas;
} // namespace ocl
namespace internal {
class StreamInterface;
} // namespace internal
class DeviceMemoryBase;
template <typename ElemT>
class DeviceMemory;
class Timer;
namespace dnn {
class BatchDescriptor;
class FilterDescriptor;
class ConvolutionDescriptor;
class ProfileResult;
class AlgorithmDesc;
} // namespace dnn
class StreamExecutor;
class ScratchAllocator;
// Convert a type to the corresponding QuantizedActivationMode.
template <typename ElementType>
struct Quantization;
// Represents a stream of dependent computations on a GPU device.
//
// The operations within a stream execute linearly and asynchronously until
// BlockHostUntilDone() is invoked, which synchronously joins host code with
// the execution of the stream.
//
// If any given operation fails when entraining work for the stream, ok() will
// indicate that an error has occurred. After initialization, once a stream is
// !ok(), it will never be ok().
//
// Thread-safe post-initialization.
class Stream {
public:
// Instantiate a stream tied to parent as a platform executor. Work
// entrained onto this stream will be launched/managed on that
// StreamExecutor's platform.
explicit Stream(StreamExecutor *parent);
// Test only. Use an externally-populated value (like a mock) for the
// platform-specific stream implementation.
Stream(StreamExecutor *parent, internal::StreamInterface *implementation);
// Deallocates any stream resources that the parent StreamExecutor has
// bestowed
// upon this object.
~Stream();
// Returns whether any errors have occurred while entraining work for this
// stream.
bool ok() const { return !InErrorState(); }
// Initialize the stream. This must be performed before entraining any other
// operations.
Stream &Init() LOCKS_EXCLUDED(mu_);
// Initializes timer t via the StreamExecutor.
Stream &InitTimer(Timer *t);
// Convenience wrapper around Init() and InitTimer().
Stream &InitWithTimer(Timer *t);
// Get or create a sub-stream from this stream. If there is any sub-stream in
// the pool that can be reused then just return this sub-stream. Otherwise
// create a new sub-stream.
Stream *GetOrCreateSubStream() LOCKS_EXCLUDED(mu_);
// Return the sub-stream back to the host stream so that it can be reused
// later.
void ReturnSubStream(Stream *sub_stream) LOCKS_EXCLUDED(mu_);
// Allocate temporary memories. The stream will deallocate them when blocked
// or destroyed.
template <typename T>
port::StatusOr<std::unique_ptr<TemporaryDeviceMemory<T>>>
AllocateTemporaryArray(uint64 element_count);
// Entrains onto the stream of operations: a kernel launch with the given
// (variadic) parameters for the invocation. These arguments can be things
// like DeviceMemory or primitive types such as int. What arguments you may
// pass to a given kernel are noted as the template parameters to the
// TypedKernel type that the machocc compiler generates.
//
// Template parameters:
// Params... The type list of formal parameters that the typed kernel
// expects, which is matched against Args...
// Args... The deduced type list for passed actual arguments
//
// Implementation: A compile-time compatibility check is performed that has
// some leniency versus an exact parameter pack match -- for example,
// `const DeviceMemory<T>` is considered "pack compatible" with a
// `const DeviceMemory<T>&` formal parameter; in part, because we don't have
// perfect forwarding support without rvalue references. It also attempts to
// spit out helpful static_assert error traces with information as to the
// argument number and types that were mismatched.
template <typename... Params, typename... Args>
Stream &ThenLaunch(ThreadDim thread_dims, BlockDim block_dims,
const TypedKernel<Params...> &kernel, Args... args);
// Record a "start" event for the interval timer at this point in the
// stream's
// execution (relative to the previously and subsequently enqueued items in
// the stream's execution). Streams may be started/stopped multiple times.
Stream &ThenStartTimer(Timer *t);
// Record a "stop" event for the interval timer at this point in the
// stream's
// execution. See also Stream::ThenStartTimer.
Stream &ThenStopTimer(Timer *t);
// TODO(leary) If work is added to the stream that is being depended upon,
// then what? Have to describe what happens.
template <typename... Params>
Stream &ThenWaitFor(Stream *other, Params... more_streams) {
return ThenWaitFor(more_streams...).ThenWaitFor(other);
}
// Create a dependency for this stream's next work on the other stream
// completing. Does not take ownership of other, and other must not be
// null.
//
// Checks that a stream does not wait for itself, and it is up to the
// user to guarantee that a stream does not come to wait on itself in a
// cyclic
// manner; in that case, behavior is undefined.
//
// N.B. Base recursion case for the variadic ThenWaitFor.
Stream &ThenWaitFor(Stream *other);
// Waits for all streams values in others.
// Checks that there is no shallow circular wait (i.e. that "this" is not in
// others)
template <typename P>
Stream &ThenWaitFor(P others) {
for (auto &stream : *others) {
CHECK_NE(stream.get(), this);
ThenWaitFor(stream.get());
}
return *this;
}
// Waits for an event object to be set.
// Note that ThenRecordEvent must have been called on the event before
// you call this function; otherwise the event will be considered complete
// and this wait will do nothing.
Stream &ThenWaitFor(Event *event);
// Inserts the specified event into the end of this stream. Once the stream
// has processed all events prior to the insertion point, the event will be
// marked as completed.
// The stream does not take ownership of event - meaning that event's lifetime
// must extend past the point at which it is marked complete!
Stream &ThenRecordEvent(Event *event);
////////////////
// DNN support
//
// See DnnSupport::* for comments on the following methods.
Stream &ThenBatchNormalizationForward(
const DeviceMemory<float> &x, const DeviceMemory<float> &scale,
const DeviceMemory<float> &offset,
const DeviceMemory<float> &estimated_mean,
const DeviceMemory<float> &estimated_variance,
const dnn::BatchDescriptor &x_desc,
const dnn::BatchDescriptor &scale_offset_desc, const double epsilon,
DeviceMemory<float> *y, DeviceMemory<float> *batch_mean,
DeviceMemory<float> *batch_var, DeviceMemory<float> *saved_mean,
DeviceMemory<float> *saved_inv_var, bool is_training,
std::function<const DeviceMemory<float> &()> var_to_inv_var,
std::function<void()> inv_var_to_var);
Stream &ThenBatchNormalizationBackward(
const DeviceMemory<float> &y_backprop, const DeviceMemory<float> &x,
const DeviceMemory<float> &scale, const DeviceMemory<float> &mean,
const DeviceMemory<float> &inv_var, const dnn::BatchDescriptor &x_desc,
const dnn::BatchDescriptor &scale_offset_desc, const double epsilon,
DeviceMemory<float> *x_backprop, DeviceMemory<float> *scale_backprop,
DeviceMemory<float> *offset_backprop);
Stream &ThenBatchNormalizationForward(
const DeviceMemory<Eigen::half> &x, const DeviceMemory<float> &scale,
const DeviceMemory<float> &offset,
const DeviceMemory<float> &estimated_mean,
const DeviceMemory<float> &estimated_variance,
const dnn::BatchDescriptor &x_desc,
const dnn::BatchDescriptor &scale_offset_desc, const double epsilon,
DeviceMemory<Eigen::half> *y, DeviceMemory<float> *batch_mean,
DeviceMemory<float> *batch_var, DeviceMemory<float> *saved_mean,
DeviceMemory<float> *saved_inv_var, bool is_training,
std::function<const DeviceMemory<float> &()> var_to_inv_var,
std::function<void()> inv_var_to_var);
Stream &ThenBatchNormalizationBackward(
const DeviceMemory<Eigen::half> &y_backprop,
const DeviceMemory<Eigen::half> &x, const DeviceMemory<float> &scale,
const DeviceMemory<float> &mean, const DeviceMemory<float> &inv_var,
const dnn::BatchDescriptor &x_desc,
const dnn::BatchDescriptor &scale_offset_desc, const double epsilon,
DeviceMemory<Eigen::half> *x_backprop,
DeviceMemory<float> *scale_backprop,
DeviceMemory<float> *offset_backprop);
// TODO(leary) add double-precision version of this interface.
Stream &ThenFusedConvolve(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<int8> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<int8> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<int8> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<float> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<int8> *output);
Stream &ThenConvolve(const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output);
Stream &ThenConvolveQuantized(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<int8> &filter_coefficients,
const DeviceMemory<float> &coefficient_scales,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output_data);
Stream &ThenConvolveQuantized(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<int16> &filter_coefficients,
const DeviceMemory<float> &coefficient_scales,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output_data);
Stream &ThenFusedConvolveWithScratch(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<int8> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<int8> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<int8> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<float> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor, DeviceMemory<int8> *output,
ScratchAllocator *scratch_allocator);
Stream &ThenFusedConvolveWithScratch(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<Eigen::half> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<Eigen::half> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<Eigen::half> &biases,
dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> *output, ScratchAllocator *scratch_allocator);
Stream &ThenFusedConvolveWithScratch(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<float> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<float> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<float> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output, ScratchAllocator *scratch_allocator);
Stream &ThenConvolveWithScratch(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<Eigen::half> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> *output, ScratchAllocator *scratch_allocator);
Stream &ThenConvolveWithScratch(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output, ScratchAllocator *scratch_allocator);
Stream &ThenConvolveWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<double> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<double> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<double> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<Eigen::half> &input_data,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenFusedConvolveWithAlgorithm(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<double> &conv_input_data, double conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<double> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<double> &side_input_data, double side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<double> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<double> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenFusedConvolveWithAlgorithm(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<float> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<float> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<float> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenFusedConvolveWithAlgorithm(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<Eigen::half> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<Eigen::half> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<Eigen::half> &biases,
dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> *output, ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenFusedConvolveWithAlgorithm(
const dnn::BatchDescriptor &conv_input_descriptor,
const DeviceMemory<int8> &conv_input_data, float conv_input_scale,
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<int8> &filter_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const DeviceMemory<int8> &side_input_data, float side_input_scale,
const dnn::BatchDescriptor &bias_descriptor,
const DeviceMemory<float> &biases, dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &output_descriptor, DeviceMemory<int8> *output,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenSeparableConvolve(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::FilterDescriptor &filter_descriptor, int depth_multiplier,
const DeviceMemory<float> &first_weights,
const DeviceMemory<float> &second_weights,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> *output);
Stream &ThenConvolveBackwardData(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<float> *backward_input_data);
Stream &ThenConvolveBackwardDataWithScratch(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<float> *backward_input_data,
ScratchAllocator *scratch_allocator);
Stream &ThenConvolveBackwardDataWithScratch(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<Eigen::half> *backward_input_data,
ScratchAllocator *scratch_allocator);
Stream &ThenConvolveBackwardDataWithAlgorithm(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<double> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<double> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<double> *backward_input_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardDataWithAlgorithm(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<float> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<float> *backward_input_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardDataWithAlgorithm(
const dnn::FilterDescriptor &filter_descriptor,
const DeviceMemory<Eigen::half> &filter_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::BatchDescriptor &input_descriptor,
DeviceMemory<Eigen::half> *backward_input_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardFilter(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<float> *backward_filter_data);
Stream &ThenConvolveBackwardFilterWithScratch(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<float> *backward_filter_data,
ScratchAllocator *scratch_allocator);
Stream &ThenConvolveBackwardFilterWithScratch(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<Eigen::half> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<Eigen::half> *backward_filter_data,
ScratchAllocator *scratch_allocator);
Stream &ThenConvolveBackwardFilterWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<double> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<double> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<double> *backward_filter_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardFilterWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<float> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<float> *backward_filter_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardFilterWithAlgorithm(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<Eigen::half> &input_data,
const dnn::BatchDescriptor &output_descriptor,
DeviceMemory<Eigen::half> backward_output_data,
const dnn::ConvolutionDescriptor &convolution_descriptor,
const dnn::FilterDescriptor &filter_descriptor,
DeviceMemory<Eigen::half> *backward_filter_data,
ScratchAllocator *scratch_allocator,
const dnn::AlgorithmConfig &algorithm_config,
dnn::ProfileResult *output_profile_result);
Stream &ThenConvolveBackwardBias(const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<double> &input_data,
const dnn::BatchDescriptor &bias_descriptor,
DeviceMemory<double> *backward_bias_data);
Stream &ThenConvolveBackwardBias(const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &bias_descriptor,
DeviceMemory<float> *backward_bias_data);
Stream &ThenConvolveBackwardBias(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<Eigen::half> &input_data,
const dnn::BatchDescriptor &bias_descriptor,
DeviceMemory<Eigen::half> *backward_bias_data);
Stream &ThenMatMul(const DeviceMemory<float> &input_data,
const DeviceMemory<float> &weights,
const dnn::BatchDescriptor &input_dimensions,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenMatMulQuantized(const DeviceMemory<float> &input_data,
const DeviceMemory<int8> &weights,
const DeviceMemory<float> &weight_scales,
const dnn::BatchDescriptor &input_dimensions,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenMatMulQuantized(const DeviceMemory<float> &input_data,
const DeviceMemory<int16> &weights,
const DeviceMemory<float> &weight_scales,
const dnn::BatchDescriptor &input_dimensions,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenBiasAdd(const DeviceMemory<float> &input_data,
const DeviceMemory<float> &biases,
const dnn::BatchDescriptor &dimensions,
DeviceMemory<float> *output_data);
Stream &ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<double> &input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<double> *output_data);
Stream &ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<Eigen::half> &input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<Eigen::half> *output_data);
Stream &ThenPoolBackward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<double> &input_data,
const dnn::BatchDescriptor &output_dimensions,
const DeviceMemory<double> &output_data,
const DeviceMemory<double> &input_diff_data,
DeviceMemory<double> *output_diff_data);
Stream &ThenPoolBackward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_dimensions,
const DeviceMemory<float> &output_data,
const DeviceMemory<float> &input_diff_data,
DeviceMemory<float> *output_diff_data);
Stream &ThenPoolBackward(const dnn::PoolingDescriptor &pooling_dimensions,
const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<Eigen::half> &input_data,
const dnn::BatchDescriptor &output_dimensions,
const DeviceMemory<Eigen::half> &output_data,
const DeviceMemory<Eigen::half> &input_diff_data,
DeviceMemory<Eigen::half> *output_diff_data);
Stream &ThenNormalize(const dnn::NormalizeDescriptor &normalize_descriptor,
const DeviceMemory<float> &input_data,
DeviceMemory<float> *output_data);
// Similar to ThenNormalize, but normalizes across feature maps and allows for
// specifying the dimensions of the tensor.
Stream &ThenNormalizeWithDimensions(
const dnn::NormalizeDescriptor &normalize_descriptor,
const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data, DeviceMemory<float> *output_data);
Stream &ThenNormalizeBackwardWithDimensions(
const dnn::NormalizeDescriptor &normalize_descriptor,
const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &raw_data,
const DeviceMemory<float> &normalized_data,
const DeviceMemory<float> &normalized_variable_gradient,
DeviceMemory<float> *raw_variable_gradient);
Stream &ThenActivate(dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data,
DeviceMemory<float> *output_data);
// Same as ThenActivate, but also takes an options argument that can be used
// for platform-specific option flags.
Stream &ThenActivateWithOptions(dnn::ActivationMode activation_mode,
const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data,
DeviceMemory<float> *output_data,
uint64 options);
Stream &ThenDepthConcatenate(
port::ArraySlice<dnn::BatchDescriptor> input_dimensions,
port::ArraySlice<const DeviceMemory<float> *> input_data,
DeviceMemory<float> *output_data);
Stream &ThenSpaceConcatenate(
port::ArraySlice<dnn::BatchDescriptor> input_dimensions,
port::ArraySlice<const DeviceMemory<float> *> input_data,
DeviceMemory<float> *output_data,
dnn::SpaceConcatenateMode concat_direction);
// Change the layout of the data by shrinking one dimension (or set of
// dimensions) and growing another dimension (or set of dimensions), while
// keeping the total number of data elements constant, and maintaining the
// current data ordering.
Stream &ThenReshape(const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<float> &input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
// Depth to space takes an X by Y image with depth D*M² and changes it to an
// MX x MY image with depth D. Each input location (x,y) with depth D*M² in
// the input image is changed to an MxM contiguous area in the output image,
// with the values being laid out in raster order specified by
// DepthToSpaceLayout, and will have a new depth of D.
// See the DoDepthToSpace comment for more information.
Stream &ThenDepthToSpace(const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<float> &input_data,
const dnn::DepthToSpaceLayout &depth_to_space_layout,
const int sqrt_depth_reduction,
DeviceMemory<float> *output_data);
// Space to depth is the inverse of depth to space. Space to depth takes each
// non-overlapping M by M patch (in the X and Y dimensions) with depth D of
// the input, and transforms it to a 1 by 1 patch with depth D*M². If the
// input has size (MX, MY, D), the output has size (X, Y, D*M²). The number of
// data elements is not changed.
Stream &ThenSpaceToDepth(const dnn::BatchDescriptor &input_dimensions,
const DeviceMemory<float> &input_data,
const dnn::DepthToSpaceLayout &space_to_depth_layout,
const int sqrt_depth_increase,
DeviceMemory<float> *output_data);
Stream &ThenElementwiseOperate(
dnn::ElementwiseOperation operation,
port::ArraySlice<dnn::BatchDescriptor> input_dimensions,
port::ArraySlice<const DeviceMemory<float> *> input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenElementwiseOperateScaledQuantized(
dnn::ElementwiseOperation operation,
port::ArraySlice<int> input_multiplicands, int output_divisor,
port::ArraySlice<dnn::BatchDescriptor> input_dimensions,
port::ArraySlice<const DeviceMemory<float> *> input_data,
const dnn::BatchDescriptor &output_dimensions,
DeviceMemory<float> *output_data);
Stream &ThenXYPad(const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data, int64 left_pad,
int64 right_pad, int64 top_pad, int64 bottom_pad,
DeviceMemory<float> *output_data);
Stream &ThenXYSlice(const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data, int64 left_trim,
int64 right_trim, int64 top_trim, int64 bottom_trim,
DeviceMemory<float> *output_data);
// Grows the input tensor by replicating the X and Y dimensions. The batch and
// depth/feature_map dimensions are unchanged. Currently, the input tensor is
// limited to X=1 and Y=1.
Stream &ThenXYBroadcast(const dnn::BatchDescriptor &dimensions,
const DeviceMemory<float> &input_data,
int64 replicate_x, int64 replicate_y,
DeviceMemory<float> *output_data);
// See DnnSupport::DoMemcpyD2HQuantized.
Stream &ThenMemcpyD2HQuantized(const DeviceMemory<float> &gpu_unquantized_src,
dnn::QuantizedActivationMode mode,
void *host_dst, uint64 size);
// Template version of ThenMemcpyD2HQuantized that takes a MutableArraySlice
// and uses the Quantization trait to call the generic version of
// ThenMemcpyD2HQuantized with the correct QuantizedActivationMode.
template <typename ElementType>
Stream &ThenMemcpyD2HQuantized(
const DeviceMemory<float> &gpu_unquantized_src,
port::MutableArraySlice<ElementType> host_dst) {
return ThenMemcpyD2HQuantized(
gpu_unquantized_src, Quantization<ElementType>::kModeId,
host_dst.data(), host_dst.size() * sizeof(ElementType));
}
// See DnnSupport::DoMemcpyH2DQuantized.
Stream &ThenMemcpyH2DQuantized(const void *host_src, uint64 size,
dnn::QuantizedActivationMode mode,
DeviceMemory<float> *gpu_unquantized_dst);
// Template version of ThenMemcpyH2DQuantized that takes an ArraySlice
// and uses the Quantization trait to call the generic version of
// ThenMemcpyH2DQuantized with the correct QuantizedActivationMode.
template <typename ElementType>
Stream &ThenMemcpyH2DQuantized(port::ArraySlice<ElementType> host_src,
DeviceMemory<float> *gpu_unquantized_dst) {
return ThenMemcpyH2DQuantized(
host_src.data(), host_src.size() * sizeof(ElementType),
Quantization<ElementType>::kModeId, gpu_unquantized_dst);
}
// See DnnSupport::DoCopyHostBuffer2Device.
Stream &ThenCopyHostBuffer2Device(HostBuffer *buffer_src,
DeviceMemory<float> *gpu_unquantized_dst);
// See DnnSupport::DoCopyDevice2HostBuffer.
Stream &ThenCopyDevice2HostBuffer(
const DeviceMemory<float> &gpu_unquantized_src, HostBuffer *buffer_dst);
/////////////////
// BLAS support
// See BlasSupport::DoBlasAsum.
Stream &ThenBlasAsum(uint64 elem_count, const DeviceMemory<float> &x,
int incx, DeviceMemory<float> *result);
Stream &ThenBlasAsum(uint64 elem_count, const DeviceMemory<double> &x,
int incx, DeviceMemory<double> *result);
Stream &ThenBlasAsum(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<float> *result);
Stream &ThenBlasAsum(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<double> *result);
// See BlasSupport::DoBlasAxpy. Note that, even for the case where alpha is
// present in DeviceMemory, it must be an execution-time constant (i.e. a
// value
// that the stream does not change or populate during the course of
// execution). The value is effectively captured at stream-enqueue time.
Stream &ThenBlasAxpy(uint64 elem_count, float alpha,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasAxpy(uint64 elem_count, double alpha,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *y, int incy);
Stream &ThenBlasAxpy(uint64 elem_count, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasAxpy(uint64 elem_count, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasCopy.
Stream &ThenBlasCopy(uint64 elem_count, const DeviceMemory<float> &x,
int incx, DeviceMemory<float> *y, int incy);
Stream &ThenBlasCopy(uint64 elem_count, const DeviceMemory<double> &x,
int incx, DeviceMemory<double> *y, int incy);
Stream &ThenBlasCopy(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasCopy(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasDot.
Stream &ThenBlasDot(uint64 elem_count, const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *result);
Stream &ThenBlasDot(uint64 elem_count, const DeviceMemory<double> &x,
int incx, const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *result);
// See BlasSupport::DoBlasDotc.
Stream &ThenBlasDotc(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *result);
Stream &ThenBlasDotc(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *result);
// See BlasSupport::DoBlasDotu.
Stream &ThenBlasDotu(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *result);
Stream &ThenBlasDotu(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *result);
// See BlasSupport::DoBlasNrm2.
Stream &ThenBlasNrm2(uint64 elem_count, const DeviceMemory<float> &x,
int incx, DeviceMemory<float> *result);
Stream &ThenBlasNrm2(uint64 elem_count, const DeviceMemory<double> &x,
int incx, DeviceMemory<double> *result);
Stream &ThenBlasNrm2(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<float> *result);
Stream &ThenBlasNrm2(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<double> *result);
// See BlasSupport::DoBlasRot.
Stream &ThenBlasRot(uint64 elem_count, DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy, float c, float s);
Stream &ThenBlasRot(uint64 elem_count, DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy, double c, double s);
Stream &ThenBlasRot(uint64 elem_count, DeviceMemory<std::complex<float>> *x,
int incx, DeviceMemory<std::complex<float>> *y, int incy,
float c, float s);
Stream &ThenBlasRot(uint64 elem_count, DeviceMemory<std::complex<double>> *x,
int incx, DeviceMemory<std::complex<double>> *y, int incy,
double c, double s);
// See BlasSupport::DoBlasRotg.
Stream &ThenBlasRotg(DeviceMemory<float> *a, DeviceMemory<float> *b,
DeviceMemory<float> *c, DeviceMemory<float> *s);
Stream &ThenBlasRotg(DeviceMemory<double> *a, DeviceMemory<double> *b,
DeviceMemory<double> *c, DeviceMemory<double> *s);
Stream &ThenBlasRotg(DeviceMemory<std::complex<float>> *a,
DeviceMemory<std::complex<float>> *b,
DeviceMemory<float> *c,
DeviceMemory<std::complex<float>> *s);
Stream &ThenBlasRotg(DeviceMemory<std::complex<double>> *a,
DeviceMemory<std::complex<double>> *b,
DeviceMemory<double> *c,
DeviceMemory<std::complex<double>> *s);
// See BlasSupport::DoBlasRotm.
Stream &ThenBlasRotm(uint64 elem_count, DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy,
const DeviceMemory<float> ¶m);
Stream &ThenBlasRotm(uint64 elem_count, DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy,
const DeviceMemory<double> ¶m);
// See BlasSupport::DoBlasRotmg.
Stream &ThenBlasRotmg(DeviceMemory<float> *d1, DeviceMemory<float> *d2,
DeviceMemory<float> *x1, const DeviceMemory<float> &y1,
DeviceMemory<float> *param);
Stream &ThenBlasRotmg(DeviceMemory<double> *d1, DeviceMemory<double> *d2,
DeviceMemory<double> *x1,
const DeviceMemory<double> &y1,
DeviceMemory<double> *param);
// See BlasSupport::DoBlasScal.
Stream &ThenBlasScal(uint64 elem_count, float alpha, DeviceMemory<float> *x,
int incx);
Stream &ThenBlasScal(uint64 elem_count, double alpha, DeviceMemory<double> *x,
int incx);
Stream &ThenBlasScal(uint64 elem_count, float alpha,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasScal(uint64 elem_count, double alpha,
DeviceMemory<std::complex<double>> *x, int incx);
Stream &ThenBlasScal(uint64 elem_count, std::complex<float> alpha,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasScal(uint64 elem_count, std::complex<double> alpha,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasSwap.
Stream &ThenBlasSwap(uint64 elem_count, DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasSwap(uint64 elem_count, DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy);
Stream &ThenBlasSwap(uint64 elem_count, DeviceMemory<std::complex<float>> *x,
int incx, DeviceMemory<std::complex<float>> *y,
int incy);
Stream &ThenBlasSwap(uint64 elem_count, DeviceMemory<std::complex<double>> *x,
int incx, DeviceMemory<std::complex<double>> *y,
int incy);
// See BlasSupport::DoBlasIamax.
Stream &ThenBlasIamax(uint64 elem_count, const DeviceMemory<float> &x,
int incx, DeviceMemory<int> *result);
Stream &ThenBlasIamax(uint64 elem_count, const DeviceMemory<double> &x,
int incx, DeviceMemory<int> *result);
Stream &ThenBlasIamax(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<int> *result);
Stream &ThenBlasIamax(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<int> *result);
// See BlasSupport::DoBlasIamin.
Stream &ThenBlasIamin(uint64 elem_count, const DeviceMemory<float> &x,
int incx, DeviceMemory<int> *result);
Stream &ThenBlasIamin(uint64 elem_count, const DeviceMemory<double> &x,
int incx, DeviceMemory<int> *result);
Stream &ThenBlasIamin(uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<int> *result);
Stream &ThenBlasIamin(uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<int> *result);
// See BlasSupport::DoBlasGbmv.
Stream &ThenBlasGbmv(blas::Transpose trans, uint64 m, uint64 n, uint64 kl,
uint64 ku, float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &x, int incx,
float beta, DeviceMemory<float> *y, int incy);
Stream &ThenBlasGbmv(blas::Transpose trans, uint64 m, uint64 n, uint64 kl,
uint64 ku, double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &x, int incx,
double beta, DeviceMemory<double> *y, int incy);
Stream &ThenBlasGbmv(blas::Transpose trans, uint64 m, uint64 n, uint64 kl,
uint64 ku, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasGbmv(blas::Transpose trans, uint64 m, uint64 n, uint64 kl,
uint64 ku, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasGemv.
Stream &ThenBlasGemv(blas::Transpose trans, uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasGemv(blas::Transpose trans, uint64 m, uint64 n, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy);
Stream &ThenBlasGemv(blas::Transpose trans, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasGemv(blas::Transpose trans, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy);
Stream &ThenBlasGemvWithProfiling(blas::Transpose trans, uint64 m, uint64 n,
float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &x,
int incx, float beta,
DeviceMemory<float> *y, int incy,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemvWithProfiling(blas::Transpose trans, uint64 m, uint64 n,
double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &x,
int incx, double beta,
DeviceMemory<double> *y, int incy,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemvWithProfiling(
blas::Transpose trans, uint64 m, uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta, DeviceMemory<std::complex<float>> *y, int incy,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemvWithProfiling(
blas::Transpose trans, uint64 m, uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta, DeviceMemory<std::complex<double>> *y,
int incy, blas::ProfileResult *output_profile_result);
// See BlasSupport::DoBlasGer.
Stream &ThenBlasGer(uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *a, int lda);
Stream &ThenBlasGer(uint64 m, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *a, int lda);
// See BlasSupport::DoBlasGerc.
Stream &ThenBlasGerc(uint64 m, uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda);
Stream &ThenBlasGerc(uint64 m, uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda);
// See BlasSupport::DoBlasGeru.
Stream &ThenBlasGeru(uint64 m, uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda);
Stream &ThenBlasGeru(uint64 m, uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda);
// See BlasSupport::DoBlasHbmv.
Stream &ThenBlasHbmv(blas::UpperLower uplo, uint64 n, uint64 k,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasHbmv(blas::UpperLower uplo, uint64 n, uint64 k,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasHemv.
Stream &ThenBlasHemv(blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasHemv(blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasHer.
Stream &ThenBlasHer(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *a, int lda);
Stream &ThenBlasHer(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *a, int lda);
// See BlasSupport::DoBlasHer2.
Stream &ThenBlasHer2(blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda);
Stream &ThenBlasHer2(blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda);
// See BlasSupport::DoBlasHpmv.
Stream &ThenBlasHpmv(blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &ap,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy);
Stream &ThenBlasHpmv(blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &ap,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy);
// See BlasSupport::DoBlasHpr.
Stream &ThenBlasHpr(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *ap);
Stream &ThenBlasHpr(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *ap);
// See BlasSupport::DoBlasHpr2.
Stream &ThenBlasHpr2(blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *ap);
Stream &ThenBlasHpr2(blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *ap);
// See BlasSupport::DoBlasSbmv.
Stream &ThenBlasSbmv(blas::UpperLower uplo, uint64 n, uint64 k, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasSbmv(blas::UpperLower uplo, uint64 n, uint64 k, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy);
// See BlasSupport::DoBlasSpmv.
Stream &ThenBlasSpmv(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &ap,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasSpmv(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &ap,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy);
// See BlasSupport::DoBlasSpr.
Stream &ThenBlasSpr(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *ap);
Stream &ThenBlasSpr(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *ap);
// See BlasSupport::DoBlasSpr2.
Stream &ThenBlasSpr2(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *ap);
Stream &ThenBlasSpr2(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *ap);
// See BlasSupport::DoBlasSymv.
Stream &ThenBlasSymv(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy);
Stream &ThenBlasSymv(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy);
// See BlasSupport::DoBlasSyr.
Stream &ThenBlasSyr(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *a, int lda);
Stream &ThenBlasSyr(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *a, int lda);
// See BlasSupport::DoBlasSyr2.
Stream &ThenBlasSyr2(blas::UpperLower uplo, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *a, int lda);
Stream &ThenBlasSyr2(blas::UpperLower uplo, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *a, int lda);
// See BlasSupport::DoBlasTbmv.
Stream &ThenBlasTbmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx);
Stream &ThenBlasTbmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx);
Stream &ThenBlasTbmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTbmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasTbsv.
Stream &ThenBlasTbsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx);
Stream &ThenBlasTbsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx);
Stream &ThenBlasTbsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTbsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n, uint64 k,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasTpmv.
Stream &ThenBlasTpmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &ap, DeviceMemory<float> *x,
int incx);
Stream &ThenBlasTpmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &ap, DeviceMemory<double> *x,
int incx);
Stream &ThenBlasTpmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &ap,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTpmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &ap,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasTpsv.
Stream &ThenBlasTpsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &ap, DeviceMemory<float> *x,
int incx);
Stream &ThenBlasTpsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &ap, DeviceMemory<double> *x,
int incx);
Stream &ThenBlasTpsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &ap,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTpsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &ap,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasTrmv.
Stream &ThenBlasTrmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx);
Stream &ThenBlasTrmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx);
Stream &ThenBlasTrmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTrmv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasTrsv.
Stream &ThenBlasTrsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx);
Stream &ThenBlasTrsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx);
Stream &ThenBlasTrsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx);
Stream &ThenBlasTrsv(blas::UpperLower uplo, blas::Transpose trans,
blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx);
// See BlasSupport::DoBlasGemm.
Stream &ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, float alpha,
const DeviceMemory<Eigen::half> &a, int lda,
const DeviceMemory<Eigen::half> &b, int ldb, float beta,
DeviceMemory<Eigen::half> *c, int ldc);
Stream &ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb, float beta,
DeviceMemory<float> *c, int ldc);
Stream &ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &b, int ldb, double beta,
DeviceMemory<double> *c, int ldc);
Stream &ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc);
Stream &ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc);
Stream &ThenBlasGemmWithProfiling(blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n,
uint64 k, float alpha,
const DeviceMemory<Eigen::half> &a, int lda,
const DeviceMemory<Eigen::half> &b, int ldb,
float beta, DeviceMemory<Eigen::half> *c,
int ldc,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithProfiling(blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n,
uint64 k, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb,
float beta, DeviceMemory<float> *c, int ldc,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithProfiling(blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n,
uint64 k, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &b, int ldb,
double beta, DeviceMemory<double> *c,
int ldc,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithProfiling(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta, DeviceMemory<std::complex<float>> *c, int ldc,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithProfiling(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta, DeviceMemory<std::complex<double>> *c, int ldc,
blas::ProfileResult *output_profile_result);
// See BlasSupport::DoBlasGemmWithAlgorithm.
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<Eigen::half> &alpha,
const DeviceMemory<Eigen::half> &a, int lda,
const DeviceMemory<Eigen::half> &b, int ldb,
const HostOrDeviceScalar<Eigen::half> &beta, DeviceMemory<Eigen::half> *c,
int ldc, blas::ComputationType computation_type,
blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<int> &alpha,
const DeviceMemory<int8> &a, int lda, const DeviceMemory<int8> &b,
int ldb, const HostOrDeviceScalar<int> &beta, DeviceMemory<int> *c,
int ldc, blas::ComputationType computation_type,
blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<float> &alpha,
const DeviceMemory<float> &a, int lda, const DeviceMemory<float> &b,
int ldb, const HostOrDeviceScalar<float> &beta, DeviceMemory<float> *c,
int ldc, blas::ComputationType computation_type,
blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<double> &alpha,
const DeviceMemory<double> &a, int lda, const DeviceMemory<double> &b,
int ldb, const HostOrDeviceScalar<double> &beta, DeviceMemory<double> *c,
int ldc, blas::ComputationType computation_type,
blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<std::complex<float>> &alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
const HostOrDeviceScalar<std::complex<float>> &beta,
DeviceMemory<std::complex<float>> *c, int ldc,
blas::ComputationType computation_type, blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
Stream &ThenBlasGemmWithAlgorithm(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, const HostOrDeviceScalar<std::complex<double>> &alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
const HostOrDeviceScalar<std::complex<double>> &beta,
DeviceMemory<std::complex<double>> *c, int ldc,
blas::ComputationType computation_type, blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result);
// See BlasSupport::DoBlasGemmBatched.
Stream &ThenBlasGemmBatched(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, float alpha,
const port::ArraySlice<DeviceMemory<Eigen::half> *> &a, int lda,
const port::ArraySlice<DeviceMemory<Eigen::half> *> &b, int ldb,
float beta, const port::ArraySlice<DeviceMemory<Eigen::half> *> &c,
int ldc, int batch_count);
Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb,
uint64 m, uint64 n, uint64 k, float alpha,
const port::ArraySlice<DeviceMemory<float> *> &a,
int lda,
const port::ArraySlice<DeviceMemory<float> *> &b,
int ldb, float beta,
const port::ArraySlice<DeviceMemory<float> *> &c,
int ldc, int batch_count);
Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb,
uint64 m, uint64 n, uint64 k, double alpha,
const port::ArraySlice<DeviceMemory<double> *> &a,
int lda,
const port::ArraySlice<DeviceMemory<double> *> &b,
int ldb, double beta,
const port::ArraySlice<DeviceMemory<double> *> &c,
int ldc, int batch_count);
Stream &ThenBlasGemmBatched(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<float> alpha,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &a, int lda,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &b, int ldb,
std::complex<float> beta,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &c, int ldc,
int batch_count);
Stream &ThenBlasGemmBatched(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<double> alpha,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &a, int lda,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &b, int ldb,
std::complex<double> beta,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &c, int ldc,
int batch_count);
Stream &ThenBlasGemmBatchedWithScratch(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, float alpha,
const port::ArraySlice<DeviceMemory<Eigen::half> *> &a, int lda,
const port::ArraySlice<DeviceMemory<Eigen::half> *> &b, int ldb,
float beta, const port::ArraySlice<DeviceMemory<Eigen::half> *> &c,
int ldc, int batch_count, ScratchAllocator *scratch_allocator);
Stream &ThenBlasGemmBatchedWithScratch(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, float alpha, const port::ArraySlice<DeviceMemory<float> *> &a,
int lda, const port::ArraySlice<DeviceMemory<float> *> &b, int ldb,
float beta, const port::ArraySlice<DeviceMemory<float> *> &c, int ldc,
int batch_count, ScratchAllocator *scratch_allocator);
Stream &ThenBlasGemmBatchedWithScratch(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, double alpha, const port::ArraySlice<DeviceMemory<double> *> &a,
int lda, const port::ArraySlice<DeviceMemory<double> *> &b, int ldb,
double beta, const port::ArraySlice<DeviceMemory<double> *> &c, int ldc,
int batch_count, ScratchAllocator *scratch_allocator);
Stream &ThenBlasGemmBatchedWithScratch(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<float> alpha,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &a, int lda,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &b, int ldb,
std::complex<float> beta,
const port::ArraySlice<DeviceMemory<std::complex<float>> *> &c, int ldc,
int batch_count, ScratchAllocator *scratch_allocator);
Stream &ThenBlasGemmBatchedWithScratch(
blas::Transpose transa, blas::Transpose transb, uint64 m, uint64 n,
uint64 k, std::complex<double> alpha,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &a, int lda,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &b, int ldb,
std::complex<double> beta,
const port::ArraySlice<DeviceMemory<std::complex<double>> *> &c, int ldc,
int batch_count, ScratchAllocator *scratch_allocator);
// See BlasSupport::DoBlasHemm.
Stream &ThenBlasHemm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc);
Stream &ThenBlasHemm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc);
// See BlasSupport::DoBlasHerk.
Stream &ThenBlasHerk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, float alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
float beta, DeviceMemory<std::complex<float>> *c,
int ldc);
Stream &ThenBlasHerk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, double alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
double beta, DeviceMemory<std::complex<double>> *c,
int ldc);
// See BlasSupport::DoBlasHer2k.
Stream &ThenBlasHer2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
float beta, DeviceMemory<std::complex<float>> *c,
int ldc);
Stream &ThenBlasHer2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
double beta, DeviceMemory<std::complex<double>> *c,
int ldc);
// See BlasSupport::DoBlasSymm.
Stream &ThenBlasSymm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &b, int ldb,
float beta, DeviceMemory<float> *c, int ldc);
Stream &ThenBlasSymm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &b, int ldb,
double beta, DeviceMemory<double> *c, int ldc);
Stream &ThenBlasSymm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc);
Stream &ThenBlasSymm(blas::Side side, blas::UpperLower uplo, uint64 m,
uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc);
// See BlasSupport::DoBlasSyrk.
Stream &ThenBlasSyrk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, float alpha, const DeviceMemory<float> &a,
int lda, float beta, DeviceMemory<float> *c, int ldc);
Stream &ThenBlasSyrk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, double alpha, const DeviceMemory<double> &a,
int lda, double beta, DeviceMemory<double> *c, int ldc);
Stream &ThenBlasSyrk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc);
Stream &ThenBlasSyrk(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc);
// See BlasSupport::DoBlasSyr2k.
Stream &ThenBlasSyr2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &b, int ldb,
float beta, DeviceMemory<float> *c, int ldc);
Stream &ThenBlasSyr2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &b, int ldb,
double beta, DeviceMemory<double> *c, int ldc);
Stream &ThenBlasSyr2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc);
Stream &ThenBlasSyr2k(blas::UpperLower uplo, blas::Transpose trans, uint64 n,
uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc);
// See BlasSupport::DoBlasTrmm.
Stream &ThenBlasTrmm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, float alpha, const DeviceMemory<float> &a,
int lda, DeviceMemory<float> *b, int ldb);
Stream &ThenBlasTrmm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, double alpha, const DeviceMemory<double> &a,
int lda, DeviceMemory<double> *b, int ldb);
Stream &ThenBlasTrmm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *b, int ldb);
Stream &ThenBlasTrmm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *b, int ldb);
// See BlasSupport::DoBlasTrsm.
Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, float alpha, const DeviceMemory<float> &a,
int lda, DeviceMemory<float> *b, int ldb);
Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, double alpha, const DeviceMemory<double> &a,
int lda, DeviceMemory<double> *b, int ldb);
Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *b, int ldb);
Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo,
blas::Transpose transa, blas::Diagonal diag, uint64 m,
uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *b, int ldb);
// See FftSupport::DoFft.
Stream &ThenFft(fft::Plan *plan,
const DeviceMemory<std::complex<float>> &input,
DeviceMemory<std::complex<float>> *output);
Stream &ThenFft(fft::Plan *plan,
const DeviceMemory<std::complex<double>> &input,
DeviceMemory<std::complex<double>> *output);
Stream &ThenFft(fft::Plan *plan, const DeviceMemory<float> &input,
DeviceMemory<std::complex<float>> *output);
Stream &ThenFft(fft::Plan *plan, const DeviceMemory<double> &input,
DeviceMemory<std::complex<double>> *output);
Stream &ThenFft(fft::Plan *plan,
const DeviceMemory<std::complex<float>> &input,
DeviceMemory<float> *output);
Stream &ThenFft(fft::Plan *plan,
const DeviceMemory<std::complex<double>> &input,
DeviceMemory<double> *output);
// Makes the RNG use the provided value as the basis for further generation.
// /dev/urandom (good) and /dev/random (better, but sometimes slow) are good
// sources of seed data if the default (high quality) sources are not
// desired.
// For most use cases, this function will not be necessary; each provided
// back-end implementation will be appropriately seeded by default.
// At a minimum 16 bytes of data are required in the seed buffer.
//
// To seed with good (non-reproducible) data:
// File* f = File::Open("/dev/random", "r");
// int64 bytes_read = f->Read(seed_data, bytes_to_read);
// < error checking >
// stream.ThenSetRngSeed(seed_data, bytes_read);
//
// To seed with reproducible data:
// uint64_t seed_data[2] = { <data> };
// stream.ThenSetRngSeed(seed_data, 16);
Stream &ThenSetRngSeed(const uint8 *seed, uint64 seed_bytes);
// Populates the memory indicated by values with uniform-random-distribution
// values. TODO(leary) seeding API/description
//
// Uses the type and size of the DeviceMemory to infer what data should be
// populated.
Stream &ThenPopulateRandUniform(DeviceMemory<float> *values);
Stream &ThenPopulateRandUniform(DeviceMemory<double> *values);
Stream &ThenPopulateRandUniform(DeviceMemory<std::complex<float>> *values);
Stream &ThenPopulateRandUniform(DeviceMemory<std::complex<double>> *values);
Stream &ThenPopulateRandGaussian(float mean, float stddev,
DeviceMemory<float> *values);
Stream &ThenPopulateRandGaussian(double mean, double stddev,
DeviceMemory<double> *values);
// Entrain onto the stream: a memcpy to a host destination from a GPU source
// of the given target size. host_dst must be a pointer to host memory
// allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and
// then registered with StreamExecutor::HostMemoryRegister.
Stream &ThenMemcpy(void *host_dst, const DeviceMemoryBase &gpu_src,
uint64 size);
// Entrain onto the stream: a memcpy to a GPU destination from a host source
// of the given target size. host_src must be a pointer to host memory
// allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and
// then registered with StreamExecutor::HostMemoryRegister.
Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const void *host_src,
uint64 size);
// Alternative interface for memcpying from device to host that takes an
// array slice. Checks that the destination size can accommodate the host
// slice size.
template <typename T>
Stream &ThenMemcpyD2H(const DeviceMemory<T> &gpu_src,
port::MutableArraySlice<T> host_dst) {
auto host_size = host_dst.size() * sizeof(T);
CHECK(gpu_src.size() == 0 || host_size >= gpu_src.size());
return ThenMemcpy(host_dst.begin(), gpu_src, host_size);
}
// Alternative interface for memcpying from host to device that takes an
// array slice. Checks that the destination size can accommodate the host
// slice size.
template <typename T>
Stream &ThenMemcpyH2D(port::ArraySlice<T> host_src,
DeviceMemory<T> *gpu_dst) {
auto host_size = host_src.size() * sizeof(T);
CHECK(gpu_dst->size() == 0 || gpu_dst->size() >= host_size);
return ThenMemcpy(gpu_dst, host_src.begin(), host_size);
}
// Entrain onto the stream: a memcpy to a GPU destination from a GPU source
// of the given target size. gpu_src/dst must be pointers to GPU memory and
// peer access must be enabled between their owning StreamExecutors.
Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src,
uint64 size);
// Calls to the device-to-device copy overload of ThenMemcpy -- useful for
// ensuring that the host pointer isn't getting confused accidentally with a
// device pointer if you're not doing metaprogramming against the API.
Stream &ThenMemcpyD2D(DeviceMemoryBase *gpu_dst,
const DeviceMemoryBase &gpu_src, uint64 size) {
return ThenMemcpy(gpu_dst, gpu_src, size);
}
// Entrain onto the stream: a memset of zero at a GPU location of size bytes.
// The location must not be null.
Stream &ThenMemZero(DeviceMemoryBase *location, uint64 size);
// Entrain onto the stream: a memset of a 32-bit pattern at a GPU location of
// size bytes, where bytes must be evenly 32-bit sized (i.e. evenly divisible
// by 4). The location must not be null.
Stream &ThenMemset32(DeviceMemoryBase *location, uint32 pattern, uint64 size);
// Enqueue a forward operation of the RNN model onto the stream.
// See DnnSupport::DoRnnForward for more details.
Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<Eigen::half> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<Eigen::half> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<Eigen::half> &input_c_data,
const DeviceMemory<Eigen::half> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
DeviceMemory<Eigen::half> *output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
DeviceMemory<Eigen::half> *output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
DeviceMemory<Eigen::half> *output_c_data,
bool is_training,
ScratchAllocator *reserve_space_allocator,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<float> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<float> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<float> &input_c_data,
const DeviceMemory<float> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
DeviceMemory<float> *output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
DeviceMemory<float> *output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
DeviceMemory<float> *output_c_data, bool is_training,
ScratchAllocator *reserve_space_allocator,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<double> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<double> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<double> &input_c_data,
const DeviceMemory<double> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
DeviceMemory<double> *output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
DeviceMemory<double> *output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
DeviceMemory<double> *output_c_data, bool is_training,
ScratchAllocator *reserve_space_allocator,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
// Enqueue a backward operation of the RNN model onto the stream.
// See DnnSupport::DoRnnBackward for more details.
Stream &ThenRnnBackward(
const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<Eigen::half> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<Eigen::half> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<Eigen::half> &input_c_data,
const DeviceMemory<Eigen::half> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
const DeviceMemory<Eigen::half> &output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
const DeviceMemory<Eigen::half> &output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
const DeviceMemory<Eigen::half> &output_c_data,
const DeviceMemory<Eigen::half> &output_backprop_data,
const DeviceMemory<Eigen::half> &output_h_backprop_data,
const DeviceMemory<Eigen::half> &output_c_backprop_data,
DeviceMemory<Eigen::half> *input_backprop_data,
DeviceMemory<Eigen::half> *input_h_backprop_data,
DeviceMemory<Eigen::half> *input_c_backprop_data,
DeviceMemory<Eigen::half> *params_backprop_data,
DeviceMemory<uint8> *reserve_space_data,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<float> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<float> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<float> &input_c_data,
const DeviceMemory<float> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
const DeviceMemory<float> &output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
const DeviceMemory<float> &output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
const DeviceMemory<float> &output_c_data,
const DeviceMemory<float> &output_backprop_data,
const DeviceMemory<float> &output_h_backprop_data,
const DeviceMemory<float> &output_c_backprop_data,
DeviceMemory<float> *input_backprop_data,
DeviceMemory<float> *input_h_backprop_data,
DeviceMemory<float> *input_c_backprop_data,
DeviceMemory<float> *params_backprop_data,
DeviceMemory<uint8> *reserve_space_data,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc,
const dnn::RnnSequenceTensorDescriptor &input_desc,
const DeviceMemory<double> &input_data,
const dnn::RnnStateTensorDescriptor &input_h_desc,
const DeviceMemory<double> &input_h_data,
const dnn::RnnStateTensorDescriptor &input_c_desc,
const DeviceMemory<double> &input_c_data,
const DeviceMemory<double> ¶ms,
const dnn::RnnSequenceTensorDescriptor &output_desc,
const DeviceMemory<double> &output_data,
const dnn::RnnStateTensorDescriptor &output_h_desc,
const DeviceMemory<double> &output_h_data,
const dnn::RnnStateTensorDescriptor &output_c_desc,
const DeviceMemory<double> &output_c_data,
const DeviceMemory<double> &output_backprop_data,
const DeviceMemory<double> &output_h_backprop_data,
const DeviceMemory<double> &output_c_backprop_data,
DeviceMemory<double> *input_backprop_data,
DeviceMemory<double> *input_h_backprop_data,
DeviceMemory<double> *input_c_backprop_data,
DeviceMemory<double> *params_backprop_data,
DeviceMemory<uint8> *reserve_space_data,
ScratchAllocator *workspace_allocator,
dnn::ProfileResult *output_profile_result);
// Enqueue onto the stream a operation that transforms a tensor.
// See DnnSupport::DoTransformTensor for more details.
Stream &ThenTransformTensor(const dnn::BatchDescriptor &input_desc,
dnn::DataType input_type,
const DeviceMemoryBase &input_data,
const dnn::BatchDescriptor &output_desc,
dnn::DataType output_type, float scale,
DeviceMemoryBase *output_data);
// The templated version of the above ThenTransformTensor. Useful when the
// input and output types are statically known.
template <typename InElemT, typename OutElemT>
Stream &ThenTransformTensor(const dnn::BatchDescriptor &input_desc,
const DeviceMemory<InElemT> &input_data,
const dnn::BatchDescriptor &output_desc,
DeviceMemory<OutElemT> *output_data) {
return ThenTransformTensor(input_desc, dnn::ToDataType<InElemT>(),
input_data, output_desc,
dnn::ToDataType<OutElemT>(), output_data);
}
// (Synchronously) block the host code waiting for the operations
// entrained on the stream (enqueued to this point in program
// execution) to complete.
//
// Returns an OK status if the blocking was successful and the stream is ok().
// Otherwise returns an error describing why the blocking failed.
port::Status BlockHostUntilDone() LOCKS_EXCLUDED(mu_);
// Warning! This method interacts with internal threads in
// sometimes-unpredictable ways and is intended for GPU-Executor-internal
// use
// only. Please check with a member of the FASTR team before making use of
// this method.
//
// Entrains onto the stream a function to be executed on the host at some
// point in the future.
// Async host callbacks DO NOT block the stream as device functions (or as
// synchronous host callbacks). No synchronization is possible with
// asynchronous callbacks; they are strictly fire-and-forget.
// This method is private due to the potential for undefined behavior with
// synchronization using OpenCL user events.
// The ONLY lifetime guarantee in these calls is that the StreamExecutor
// parameter will still be valid - this Stream may not be!
// Any callbacks requiring device API calls must use this method.
Stream &ThenEnqueueOnBackgroundThread(
std::function<void(StreamExecutor *)> task);
// Returns the (opaque) platform-specific backing object. Ownership is not
// transferred to the caller.
internal::StreamInterface *implementation() { return implementation_.get(); }
// Entrains onto the stream a callback to the host (from the device).
// Host callbacks block/occupy the stream just as device functions
// (execute one at a time, block later stream operations).
//
// Behavior is undefined when synchronizing using OpenCL user events.
// Behavior is undefined if host callbacks call device routines or insert
// them into any stream.
//
// On certain platforms, ThenDoHostCallback is expected to have significant
// negative effects on performance.
Stream &ThenDoHostCallback(std::function<void()> callback);
// Returns the StreamExecutor (parent object) associated with this stream.
StreamExecutor *parent() const {
CHECK(parent_ != nullptr);
return parent_;
}
// Returns the (internal usage) temporary-memory-allocation manager associated
// with this stream.
internal::TemporaryMemoryManager *temporary_memory_manager();
private:
friend class host::HostBlas; // for parent_.
friend class host::HostFft; // for parent_.
friend class host::HostRng; // for parent_.
template <typename... Args>
friend struct ThenBlasImpl; // for implementing ThenBlasXXX.
friend class ocl::CLBlas; // for parent_.
bool InErrorState() const LOCKS_EXCLUDED(mu_) {
tf_shared_lock lock(mu_);
return !ok_;
}
// Sets the error state if operation_retcode is false.
// This is a useful shorthand for many stream routines.
void CheckError(bool operation_retcode) LOCKS_EXCLUDED(mu_) {
if (operation_retcode) {
return;
}
mutex_lock lock(mu_);
ok_ = false;
}
void SetError() { CheckError(false /* = operation_retcode */); }
void SetErrorAndLogNoDnnSupport() {
SetError();
LOG(WARNING) << "attempting to perform DNN operation using StreamExecutor "
"without DNN support";
}
// The StreamExecutor that supports the operation of this stream.
StreamExecutor *parent_;
// The platform-dependent implementation that the StreamExecutor interface
// delegates to.
std::unique_ptr<internal::StreamInterface> implementation_;
// mutex that guards the allocation / error state flags.
// Mutable so that it can be obtained via const reader lock.
mutable mutex mu_;
// Whether Init() was successfully called to allocate this stream on the
// underlying platform. It simply flips from 0 to 1 with a sanity check.
// See StreamExecutor::AllocateStream.
bool allocated_ GUARDED_BY(mu_);
// Whether all operations have entrained successfully to the current program
// point.
bool ok_ GUARDED_BY(mu_);
// Sub-streams that are generated from this stream. Each element has a pointer
// to sub-stream and a boolean value indicating if this substream is ready to
// be reused.
std::vector<std::pair<std::unique_ptr<Stream>, bool>> sub_streams_
GUARDED_BY(mu_);
// Streams can allocate temporary memories to help with work they enqueue
// (e.g. for scratch memory spaces). This member tracks those allocations and
// notes when they can be reclaimed -- reclamation is attempted when
// BlockHostUntilDone() is called.
internal::TemporaryMemoryManager temporary_memory_manager_;
// Implementation of ThenConvolveBackwardBias that is shared by all types.
template <typename T>
Stream &ThenConvolveBackwardBiasImpl(
const dnn::BatchDescriptor &input_descriptor,
const DeviceMemory<T> &input_data,
const dnn::BatchDescriptor &bias_descriptor,
DeviceMemory<T> *backward_bias_data);
SE_DISALLOW_COPY_AND_ASSIGN(Stream);
};
////////////
// Inlines
template <typename T>
inline port::StatusOr<std::unique_ptr<TemporaryDeviceMemory<T>>>
Stream::AllocateTemporaryArray(uint64 element_count) {
return temporary_memory_manager_.AllocateArray<T>(element_count);
}
inline internal::TemporaryMemoryManager *Stream::temporary_memory_manager() {
return &temporary_memory_manager_;
}
template <>
struct Quantization<uint8> {
static constexpr dnn::QuantizedActivationMode kModeId =
dnn::QuantizedActivationMode::k8Bit;
};
template <>
struct Quantization<uint16> {
static constexpr dnn::QuantizedActivationMode kModeId =
dnn::QuantizedActivationMode::k16Bit;
};
template <>
struct Quantization<int32> {
static constexpr dnn::QuantizedActivationMode kModeId =
dnn::QuantizedActivationMode::k32Bit;
};
} // namespace stream_executor
#endif // TENSORFLOW_STREAM_EXECUTOR_STREAM_H_
| [
"davidstanke@gmail.com"
] | davidstanke@gmail.com |
629e49e4d50350464604885370edd0036d602001 | 8a77912f1e88b58198ca0d0dd872a4ad0382fecd | /src/SFMLContext.cpp | 66f64ce7ead5de49ef417eb67703d43951cb873c | [] | no_license | ccfreak2k/system65emu | 34cbca4c153aa2c102cbc54476e7c423c327969d | 528044f4dbe9abf56bd3cbfac14df665f7d3ba7d | refs/heads/master | 2021-01-10T13:34:02.586779 | 2015-09-10T08:08:33 | 2015-09-10T08:08:33 | 44,884,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include "SFMLContext.hpp"
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
const char *SFMLContext::m_szWindowTitle = "System65 Emulator";
SFMLContext::SFMLContext(int width, int height)
{
m_Window = new sf::Window(sf::VideoMode(width,height), m_szWindowTitle);
m_Window->setFramerateLimit(60);
}
SFMLContext::~SFMLContext()
{
delete m_Window;
}
void SFMLContext::Flip(void)
{
m_Window->display();
}
| [
"ccfreak2k@gmail.com"
] | ccfreak2k@gmail.com |
fea294a4f465334852fd371ffc2555b27522d8d9 | 3ce3e3e4e32228847db7b16b268b05a97d478dbf | /huawei/CountsNumberOne/CountsNumberOne/main.cpp | 2583dea132d437fac7da24c98b8fa630bcb71ef9 | [
"Apache-2.0"
] | permissive | RainChang/My_ACM_Exercises | 4d97073ed3da0fab63952dab61803fffe7e0edf0 | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | refs/heads/master | 2021-01-22T19:09:39.021713 | 2017-06-26T14:05:39 | 2017-06-26T14:05:39 | 85,173,294 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | //
// main.cpp
// CountsNumberOne
//
// Created by Rain on 09/03/2017.
// Copyright © 2017 Rain. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
cout<<~(-1)<<endl;
return 0;
}
| [
"rain@RaindeMacBook-Pro.local"
] | rain@RaindeMacBook-Pro.local |
9efe3bcb4c0ddba47448773d985b143abf4c146a | 44a4f7361a9c4cdd416fe34a8ca8f0bf5d688f58 | /MP2Node.h | b85bfde29f6ad65ea43c0ffd49097ea28770d56d | [] | no_license | mimikian/Key-Value-Store | 524e702e1a3b3622f1d9e1e13f66de2a0f805063 | 2288600895af44a678dcb20d6cbb240a780b95bb | refs/heads/master | 2021-01-12T08:25:55.215625 | 2016-12-15T17:00:07 | 2016-12-15T17:00:07 | 76,576,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,121 | h | /**********************************
* FILE NAME: MP2Node.h
*
* DESCRIPTION: MP2Node class header file
**********************************/
#ifndef MP2NODE_H_
#define MP2NODE_H_
/**
* Header files
*/
#include "stdincludes.h"
#include "EmulNet.h"
#include "Node.h"
#include "HashTable.h"
#include "Log.h"
#include "Params.h"
// #include "Message.h"
#include "Queue.h"
/**
* CLASS NAME: MP2Node
*
* DESCRIPTION: This class encapsulates all the key-value store functionality
* including:
* 1) Ring
* 2) Stabilization Protocol
* 3) Server side CRUD APIs
* 4) Client side CRUD APIs
*/
class Quorum {
public:
Quorum():quorumReached(false) {}
virtual ~Quorum() {}
int successCount = 0;
int failCount = 0;
bool quorumReached = false;
MessageType type;
string key;
string value;
bool got_reply[3];
int repliesCount =0;
bool commited = false;
Address addresses[3];
// Mp2Message messages[3];
// Mp2Message reply_messages[3];
};
class MP2Node {
private:
// Vector holding the next two neighbors in the ring who have my replicas
vector<Node> hasMyReplicas;
// Vector holding the previous two neighbors in the ring whose replicas I have
vector<Node> haveReplicasOf;
// Ring
vector<Node> oldRing;
vector<Node> ring;
// Hash Table
HashTable * ht;
// Member representing this member
Member *memberNode;
// Params object
Params *par;
// Object of EmulNet
EmulNet * emulNet;
// Object of Log
Log * log;
map<int, Quorum> quorum;
public:
MP2Node(Member *memberNode, Params *par, EmulNet *emulNet, Log *log, Address *addressOfMember);
Member * getMemberNode() {
return this->memberNode;
}
// ring functionalities
void updateRing();
vector<Node> getMembershipList();
size_t hashFunction(string key);
void findNeighbors();
// client side CRUD APIs
void clientCreate(string key, string value);
void clientRead(string key);
void clientUpdate(string key, string value);
void clientDelete(string key);
// Send message to replicas
void sendMessage(Mp2Message msg);
void sendReplyMessage(Mp2Message msg, MessageType reply_type);
vector<Node> checkRing(vector<Node> membershipList);
bool isNodeAlive(Address adr);
void checkFailedNodes();
void sendReplicationMessage(Address addr, string key, string value, ReplicaType replica);
// receive messages from Emulnet
bool recvLoop();
static int enqueueWrapper(void *env, char *buff, int size);
// handle messages from receiving queue
void checkMessages();
// coordinator dispatches messages to corresponding nodes
void dispatchMessages(Message message);
// find the addresses of nodes that are responsible for a key
vector<Node> findNodes(string key, vector<Node> myRing);
vector<Node> findNodes(string key);
// server
bool createKeyValue(string key, string value, ReplicaType replica);
string readKey(string key);
bool updateKeyValue(string key, string value, ReplicaType replica);
bool deletekey(string key);
// stabilization protocol - handle multiple failures
void stabilizationProtocol();
~MP2Node();
};
#endif /* MP2NODE_H_ */
| [
"Abanoub.aziz92@gmail.com"
] | Abanoub.aziz92@gmail.com |
ea1a9622b504f4447281a51e5d5a660a6df858ac | be0863609303ae28d2370eb24b075bc3c6c982f9 | /Energy_Shield/DemoQuickStart/ADE7753.h | 55b5eecf649f1dc54dfc14ae1f889c83a03b2ca0 | [] | no_license | JMCeron/Arduino | 96bf978338834d31d39aa41d3079a41f7b340555 | 25266100cfe605c03bece30f0643e57712be20fc | refs/heads/master | 2020-03-09T15:30:05.004677 | 2018-04-10T02:26:57 | 2018-04-10T02:26:57 | 128,847,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,496 | h |
/* ==================================================================================
File: ADE7753.h
Author: Eduard Martin
MCI Electronics
www.olimex.cl
Description: Header File, Data types, objects definition of WIZ610 Class.
Target Device: Arduino Duemilanove, Uno, Mega
==================================================================================
Copyright 2010 MCI electronics
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.
// ==================================================================================
//
// Original by E.M.U.
//
// Ver | dd mmm yyyy | Author | Description
// =====|=============|========|=====================================================
// 1.00 | 19 Nov 2010 | E.M | First release
// ==================================================================================*/
#ifndef ADE7753_H
#define ADE7753_H
/***
* Defines
*
*/
//Registers
#define WAVEFORM 0x01
#define AENERGY 0x02
#define RAENERGY 0x03
#define LAENERGY 0x04
#define VAENERGY 0x05
#define RVAENERGY 0x06
#define LVAENERGY 0x07
#define LVARENERGY 0x08
#define MODE 0x09
#define IRQEN 0x0A
#define STATUS 0x0B
#define RSTSTATUS 0x0C
#define CH1OS 0x0D
#define CH2OS 0x0E
#define GAIN 0x0F
#define PHCAL 0x10
#define APOS 0x11
#define WGAIN 0x12
#define WDIV 0x13
#define CFNUM 0x14
#define CFDEN 0x15
#define IRMS 0x16
#define VRMS 0x17
#define IRMSOS 0x18
#define VRMSOS 0x19
#define VAGAIN 0x1A
#define VADIV 0x1B
#define LINECYC 0x1C
#define ZXTOUT 0x1D
#define SAGCYC 0x1E
#define SAGLVL 0x1F
#define IPKLVL 0x20
#define VPKLVL 0x21
#define IPEAK 0x22
#define RSTIPEAK 0x23
#define VPEAK 0x24
#define RSTVPEAK 0x25
#define TEMP 0x26
#define PERIOD 0x27
#define TMODE 0x3D
#define CHKSUM 0x3E
#define DIEREV 0X3F
//bits
//of MODE register
#define DISHPF 0
#define DISLPF2 1
#define DISCF 2
#define DISSAG 3
#define ASUSPEND 4
#define TEMPSEL 5
#define SWRST 6
#define CYCMODE 7
#define DISCH1 8
#define DISCH2 9
#define SWAP 10
#define DTRT1 11
#define DTRT0 12
#define WAVSEL1 13
#define WAVSEL0 14
#define POAM 15
//constants
#define GAIN_1 0x0
#define GAIN_2 0x1
#define GAIN_4 0x2
#define GAIN_8 0x3
#define GAIN_16 0x4
#define INTEGRATOR_ON 1
#define INTEGRATOR_OFF 0
// Class Atributes
#define CS 10 // Chip Select ADE7753
#define WRITE 0x80
#define CLKIN 4000000 //ADE7753 frec, max 4MHz
#define METER_ID 42 //meter ID (used in xbee)
#define VOLTDIV 48 //By desing, rel 1/48
#define CURRDIV 50 //By desing, rel 1/48
#define NUMCYC 20
class ADE7753 {
private:
float kv,ki,ke;
//public methods
public:
ADE7753();
void setInterruptsMask(int i);
void setMode(int m);
void senseTemp(void);
void setInterrupts(int i);
void analogSetup(char gain_ch1, char gain_ch2,char os_ch1,char os_ch2,char scale_ch1,char integrator_ch1);
void frecuencySetup(int cfnum, int cfden);
void energySetup(int wgain, char wdiv, int apos, int vagain, char vadiv, char phcal);
void rmsSetup(int vrmsos, int irmsos);
void energyGain(int wgain, int vagain);
int getInterruptStatus(void);
int getresetInterruptStatus(void);
// void setCurrentOffset(int d);
// void setVoltageOffset(int d);
void setPowerOffset(int d);
void setPhaseCallibration(char d);
void setEnergyGain(char d);
void setActivePowerGain(int d);
void setActiveEnergyDivider(char d);
// void setFrecuencyDividerNumerator(int d);
// void setFrecuencyDividerDenominator(int d);
void setApparentPowerGain(int d);
void setApparentEnergyDivider(char d);
void setZeroCrossingTimeout(int d);
void setSagVoltageLevel(char d);
void setSagCycles(char d);
void setIPeakLevel(char d);
void setVPeakLevel(char d);
// void calibrateGain(int Imax, int I, int MeterConstant, long power);
void calibrateEnergyAccurateSource(int Imax, int I, int V, int MeterConstant, long power, int linecyc);
void calibrateEnergy(int CFnominal, int CFexpected);
void calibrateRMSOS(int v1,int v2,int i1,int i2);
void setLineCyc(int d);
void changeKV(float d);
void changeKI(float d);
void changeKE(float d);
void setKV(float d);
void setKI(float d);
void setKE(float d);
char chkSum(void);
char getTemp(void);
char getCH1Offset(void);
char getCH2Offset(void);
char getPhaseCallibration(void);
char getEnergyGain(void);
char getActiveEnergyDivider(void);
char getApparentEnergyDivider(void);
char getSagCycles(void);
char getSagVoltageLevel(void);
char getIPeakLevel(void);
char getVPeakLevel(void);
char waitKey(char * msg);
// int calibrate(int energy, int v, int i, int f, char phi, int meter_constant);
// int calibrateEnergyToFrecuency(int cfnum, int cfden, char wdiv);
int getWattGain(int load);
int getVoltageOffset(void);
int getCurrentOffset(void);
int getMode(void);
int getInterrupts(void);
int getStatus(void);
int resetStatus(void);
int getActivePowerOffset(void);
int getPeriod(void);
int getPowerOffset(void);
int getActivePowerGain(void);
int getFrecuencyDividerNumerator(void);
int getFrecuencyDividerDenominator(void);
int getZeroCrossingTimeout(void);
int getApparentPowerGain(void);
int getWattGain();
int getLineCyc();
long getWaveform(void);
long getActivePower(void);
long getVRMS(void);
long getIRMS(void);
long getLAENERGY(void);
long getLVAENERGY(void);
long getReactiveEnergy(void);
float getFPOWER(void);
long getActiveEnergy(void);
long getActiveEnergyReset(void);
long getApparentEnergy(void);
long getApparentEnergyReset(void);
long getApparentPower(void);
long getReactivePower(void);
long getIpeak(void);
long getIpeakReset(void);
long getVpeak(void);
long getVpeakReset(void);
long vrms();
long irms();
long energy();
long waitInterrupt2(unsigned int interrupt);
float getKV();
float getKI();
float getKE();
// long calV();
//private methods
private:
unsigned char read8(char reg);
unsigned int read16(char reg);
unsigned long read24(char reg);
void write16(char reg, int data);
void write8(char reg, char data);
void enableChip(void);
void disableChip(void);
long waitInterrupt(unsigned int interrupt);
// void analogSetup2(char gain_ch1, char gain_ch2,char os_ch1,char os_ch2,char scale_ch1,char integrator_ch1);
// long waitInterrupt3(unsigned int interrupt);
};
#endif
| [
"jose.ceronc@utem.cl"
] | jose.ceronc@utem.cl |
287ea63f3b97149952333b724f7463dac2c75c60 | f97088a7962793f9d39446176f54461a87b00e73 | /program 9/hTable.h | e40f173638db25b83a2daec8625626933c84991d | [] | no_license | andyoliv24/CSCI_340 | 1679f2475d85aa93c3a2e981c9e42e8f7d2412ca | 44d7ca67ac429e49628df5ed553126131df4d4a7 | refs/heads/master | 2022-12-10T20:30:18.939402 | 2020-08-24T20:45:39 | 2020-08-24T20:45:39 | 290,034,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | #include "Entry.h"
#ifndef H_HASH_TABLE
#define H_HASH_TABLE
#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
// class for hash table
class HT {
public:
HT ( const unsigned& = TBL_SZ ); // constructor
~HT ( ); // destructor
void insert ( const Entry& ); // inserts item in hash table
void search ( const string& ); // searches for item
void hTable_print ( ); // prints hash table entries
void pTable_print ( ); // prints hash table entries in sorted order
private:
unsigned hsize; // size of hash table
vector < list < Entry > > hTable; // hash table
vector < Entry* > pTable; // ptr table
int hash ( const string& ); // hash function
};
#endif
| [
"Andy_240311@hotmail.com"
] | Andy_240311@hotmail.com |
9e993a7b77d20f275674814370bf271b9e737d6f | 5758fdcffd2b4c8ce837f541f80887d128190e65 | /src/tasks/tasks.cpp | eaae9857faa4edf3241474dca71dc4c99a57bf8b | [
"MIT"
] | permissive | zsoltmazlo/indoor-controller1 | db7bd87bd122a651cdddb8d9702fbacd605ca9b4 | 1443e999dc6c18b06e969c83644762384b6576ec | refs/heads/master | 2021-04-03T07:17:53.737238 | 2018-03-09T21:58:30 | 2018-03-09T21:58:30 | 124,587,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,131 | cpp | #include "tasks.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <cmath>
#include "Configuration.h"
#include "debug.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "Configuration.h"
#include "DS18B20.hpp"
#include "ButtonEvent.h"
void tasks::display(void* args) {
auto task = tasks::Display{};
task(args);
}
void tasks::connection(void* args) {
auto task = tasks::Connection{};
task(args);
}
void tasks::button(void* args) {
debug::printf("BTTN | Button event manager task is started.\n");
// button events could fired very rapidly, thus we should have a big
// queue for that events
tasks::queues::buttonEventQueue = xQueueCreate(100, sizeof(ButtonEvent));
// we will save 4 samples of the button measurement, and send a message
// for each element
uint8_t sample_count = 0;
uint8_t samples = 0;
ButtonEvent event;
ButtonEvent prevEvent;
pinMode(Configuration::button_pin, INPUT);
TickType_t last_wake_time = xTaskGetTickCount();
for(;;) {
prevEvent = event;
// get one sample
samples <<= 1;
samples &= 0x0F;
samples |= digitalRead(Configuration::button_pin);
switch(samples) {
case 0x0F:
event = ButtonEvent::EV_HIGH;
break;
case 0x00:
event = ButtonEvent::EV_LOW;
break;
case 0x07:
case 0x03:
case 0x01:
event = ButtonEvent::EV_RISING;
break;
case 0x08:
case 0x0C:
case 0x0E:
event = ButtonEvent::EV_FALLING;
break;
}
if( prevEvent != event ) {
debug::printf("BTTN | Sending event: %d\n", event);
xQueueSend(tasks::queues::buttonEventQueue, &event, (TickType_t)10);
}
vTaskDelayUntil(&last_wake_time, 5ms);
}
}
void tasks::ledcontroller(void* args) {
// argument will hold the led index which could use to get the pin number
// and the queue as well
uint32_t index = (uint32_t)args;
uint8_t pin = Configuration::Led::potmeter_pin[index];
uint8_t pwm = Configuration::Led::pwm_pin[index];
debug::printf("LED%d | Led control task is started.\n POTMETER pin: %d\n PWM pin: %d\n", index, pin, pwm);
pinMode(pin, INPUT);
// start PWM handling (index could use as the analog channel)
ledcSetup(index, Configuration::Led::pwm_frequency, Configuration::Led::pwm_resolution);
ledcAttachPin(pwm, index);
uint16_t previous_measurement = 10000, current_measurement;
tasks::FrameSelectorMessage fsm;
fsm.frameIndex = 0;
fsm.interval = 5s;
float f;
constexpr float fivePercent = (1 << Configuration::Led::pwm_resolution) * 0.05;
// subscribe for topic too (it is sad that std::to_string is not an option)
char topic[16];
sprintf(topic, Configuration::Topics::ledcontrol, index);
::Connection::instance->subscribe(topic, [&](const std::string& message) {
debug::printf("LED%d | message received! %s\n", index, message.c_str());
StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.parse(message.c_str());
if (object.containsKey("value")) {
f = object["value"].as<float>();
xQueueSend(tasks::queues::ledQueue[index], &f, (TickType_t)10);
xQueueSend(tasks::queues::displayQueue, &fsm, (TickType_t)10);
ledcWrite(index, (uint16_t)(4096 * f / 100.0));
}
});
for (;;) {
current_measurement = analogRead(pin);
if (std::abs(current_measurement - previous_measurement) > Configuration::Led::potmeter_threshold) {
f = (float)current_measurement / fivePercent * 5.0;
previous_measurement = current_measurement;
// sending message
xQueueSend(tasks::queues::ledQueue[index], &f, (TickType_t)10);
xQueueSend(tasks::queues::displayQueue, &fsm, (TickType_t)10);
// also write PWM value to the output as well
ledcWrite(index, current_measurement);
vTaskDelay(50ms);
} else {
// task can rest until 100ms
vTaskDelay(100ms);
}
}
}
extern NTPClient ntpClient;
void tasks::temperature(void* args) {
debug::printf("TEMP | Task started\n");
float temp;
for (;;) {
// measure sensor value - also, we need to handle onewire communication as a critical section
auto measurement =
readSensorValue<Configuration::Temperature::sensor_pin, Configuration::Temperature::measurement_count,
Configuration::Temperature::measurement_resolution>();
if (measurement.second) {
temp = measurement.first;
xQueueSend(tasks::queues::temperatureQueue, &temp, (TickType_t)10);
// and send as an mqtt message as well
auto ts = String(ntpClient.getEpochTime()) + "000";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["timestamp"] = ts.c_str();
root["temperature"] = temp;
String output;
root.printTo(output);
::Connection::instance->publish(Configuration::Topics::sensor, output.c_str());
}
// measurement every 5min
vTaskDelay(Configuration::Temperature::measurement_interval);
}
}
void tasks::weather_update(void* args) {
static char message[100];
sprintf(message, "{\"client\": \"%s\", \"forecast_days\": 3}", Configuration::client_id);
for (;;) {
if (::Connection::instance->isConnected()) {
::Connection::instance->publish(Configuration::Topics::weather_req, message);
}
// check weather information every 5 minutes
vTaskDelay(5min);
}
}
QueueHandle_t tasks::queues::ledQueue[2];
QueueHandle_t tasks::queues::temperatureQueue;
QueueHandle_t tasks::queues::displayQueue;
QueueHandle_t tasks::queues::buttonEventQueue; | [
"zsolt.mazlo@gmail.com"
] | zsolt.mazlo@gmail.com |
90a093846899792ab6de8512eb0e979ee4d61783 | 29b8a3032a29e29720ab1abb4493d4a6b143dd79 | /src/LEDBlink.h | 057f27f0d786fa031d118f17d47bc1ba554be51d | [
"MIT"
] | permissive | iamdev/ESP8266-STM32IO-4CH-LCD | 9cbd328593da2d2163ba78da5c95a75dbc0d879f | b18e3214cb2c93c591191e0550234ba2d7892c2c | refs/heads/main | 2023-03-30T04:46:19.254961 | 2021-03-26T05:58:42 | 2021-03-26T05:58:42 | 351,637,167 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | #ifndef _LEDBlink_H
#define _LEDBlink_H
#include <Arduino.h>
class LEDBlink{
public:
LEDBlink(uint8_t pin,int onState=LOW);
void begin();
void loop();
void setPeriod(int period,int on_ms);
void setPattern(const int n,...);
void enable(bool en=true);
bool isEnabled() const {return _isEnabled;}
void on();
void off();
private:
uint8_t _ledPin;
bool _isEnabled;
uint16_t _pattern[32];
int _currentStep = 0;
int _step=0;
int _onState;
int _period_ms = 1000;
int _offset_ms = 0;
bool _state;
bool _nextState;
uint16_t _nextState_ms;
};
#endif /*_LEDBlink_H*/
| [
"kamon.dev@hotmail.com"
] | kamon.dev@hotmail.com |
735c3610496bcb7a3318dbb4c3994d1517dae345 | badbdcc98d5594feadc95a3538163518be43626c | /host-opengl-render/ReadBuffer.cpp | 39e167b68c7951c89be7d9f6011099af940152bb | [] | no_license | jacksunshine6/qemu-of-arm-android | 961dbd31f672c9d2aa751012c6237b468124a120 | ca2000f6cd42a0940df5deb386d46af48207d01e | refs/heads/master | 2023-01-07T23:22:12.555512 | 2020-11-08T02:30:38 | 2020-11-08T02:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | cpp | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ReadBuffer.h"
#include <string.h>
#include <assert.h>
#include <limits.h>
#include "ErrorLog.h"
ReadBuffer::ReadBuffer(IOStream *stream, size_t bufsize)
{
m_size = bufsize;
m_stream = stream;
m_buf = (unsigned char*)malloc(m_size*sizeof(unsigned char));
m_validData = 0;
m_readPtr = m_buf;
}
ReadBuffer::~ReadBuffer()
{
free(m_buf);
}
int ReadBuffer::getData()
{
if ((m_validData > 0) && (m_readPtr > m_buf)) {
memmove(m_buf, m_readPtr, m_validData);
}
// get fresh data into the buffer;
size_t len = m_size - m_validData;
if (len==0) {
//we need to inc our buffer
size_t new_size = m_size*2;
unsigned char* new_buf;
if (new_size < m_size) { // overflow check
new_size = INT_MAX;
}
new_buf = (unsigned char*)realloc(m_buf, new_size);
if (!new_buf) {
ERR("Failed to alloc %zu bytes for ReadBuffer\n", new_size);
return -1;
}
m_size = new_size;
m_buf = new_buf;
len = m_size - m_validData;
}
m_readPtr = m_buf;
if (NULL != m_stream->read(m_buf + m_validData, &len)) {
m_validData += len;
return len;
}
return -1;
}
void ReadBuffer::consume(size_t amount)
{
assert(amount <= m_validData);
m_validData -= amount;
m_readPtr += amount;
}
| [
"jianglin@xdja.com"
] | jianglin@xdja.com |
22983f366d49c1264cbf062ed8c0640ff5bf0d27 | 9586c70bf182ece97b7186cf370dfaec2173071c | /src/ufo/groundgnss/ZenithTotalDelayMetOffice/ObsGroundgnssMetOfficeTLAD.cc | b63d7f2c51c760d0ed7538a40a047628bfa585bd | [
"Apache-2.0"
] | permissive | scogre/ufo | 81cd44a762b146c6c9eaf49d78a271c596106c1f | 2af9b91433553ca473c72fcd131400a01c3aabdb | refs/heads/master | 2023-08-11T02:21:26.356648 | 2021-06-11T22:28:50 | 2021-06-11T22:28:50 | 415,057,301 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,360 | cc | /*
* (C) Copyright 2021 Met Office
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/groundgnss/ZenithTotalDelayMetOffice/ObsGroundgnssMetOfficeTLAD.h"
#include <ostream>
#include <string>
#include <vector>
#include "ioda/ObsSpace.h"
#include "ioda/ObsVector.h"
#include "oops/base/Variables.h"
#include "oops/util/Logger.h"
#include "ufo/GeoVaLs.h"
namespace ufo {
// -----------------------------------------------------------------------------
static LinearObsOperatorMaker<ObsGroundgnssMetOfficeTLAD>
makerGroundgnssMetOfficeTL_("GroundgnssMetOffice");
// -----------------------------------------------------------------------------
ObsGroundgnssMetOfficeTLAD::ObsGroundgnssMetOfficeTLAD(const ioda::ObsSpace & odb,
const eckit::Configuration & config)
: LinearObsOperatorBase(odb), keyOperGroundgnssMetOffice_(0), varin_()
{
const eckit::LocalConfiguration obsOptions(config, "obs options");
const eckit::Configuration * configc = &obsOptions;
ufo_groundgnss_metoffice_tlad_setup_f90(keyOperGroundgnssMetOffice_, &configc);
const std::vector<std::string> vv{"air_pressure_levels", "specific_humidity",
"geopotential_height", "geopotential_height_levels"};
varin_.reset(new oops::Variables(vv));
oops::Log::info() << "ObsGroundgnssMetOfficeTLAD vars: " << *varin_ << std::endl;
oops::Log::trace() << "ObsGroundgnssMetOfficeTLAD created" << std::endl;
}
// -----------------------------------------------------------------------------
ObsGroundgnssMetOfficeTLAD::~ObsGroundgnssMetOfficeTLAD() {
ufo_groundgnss_metoffice_tlad_delete_f90(keyOperGroundgnssMetOffice_);
oops::Log::trace() << "ObsGroundgnssMetOfficeTLAD destructed" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsGroundgnssMetOfficeTLAD::setTrajectory(const GeoVaLs & geovals, const ObsBias & bias,
ObsDiagnostics &) {
ufo_groundgnss_metoffice_tlad_settraj_f90(keyOperGroundgnssMetOffice_, geovals.toFortran(),
obsspace());
}
// -----------------------------------------------------------------------------
void ObsGroundgnssMetOfficeTLAD::simulateObsTL(
const GeoVaLs & geovals, ioda::ObsVector & ovec) const {
ufo_groundgnss_metoffice_simobs_tl_f90(keyOperGroundgnssMetOffice_, geovals.toFortran(),
obsspace(), ovec.size(), ovec.toFortran());
}
// -----------------------------------------------------------------------------
void ObsGroundgnssMetOfficeTLAD::simulateObsAD(
GeoVaLs & geovals, const ioda::ObsVector & ovec) const {
ufo_groundgnss_metoffice_simobs_ad_f90(keyOperGroundgnssMetOffice_, geovals.toFortran(),
obsspace(), ovec.size(), ovec.toFortran());
}
// -----------------------------------------------------------------------------
void ObsGroundgnssMetOfficeTLAD::print(std::ostream & os) const {
os << "ObsGroundgnssMetOfficeTLAD::print not implemented" << std::endl;
}
// -----------------------------------------------------------------------------
} // namespace ufo
| [
"noreply@github.com"
] | noreply@github.com |
50c75771544bf5927640da4c41c1f4c6cd935ea5 | be30e126df12d9ac6087ab8f82101c6b932121c8 | /game_sa/CCutsceneShadow.h | 0d4ac5b3269c11623ef61898da736cc471684169 | [] | no_license | ArnCarveris/gta-sa-plugin-sdk | fc53265bbce06de9276ad2a289e50505aaea2d52 | f64548b0f588856d2da6100cd1c69a5880f89fd2 | refs/heads/master | 2020-05-20T15:46:06.287895 | 2014-02-23T14:07:29 | 2014-02-23T14:07:29 | 34,955,493 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | h | #pragma once
#include "plugin\plugin.h"
#include "CShadowCamera.h"
#include "RenderWare.h"
#include "CSphere.h"
#pragma pack(push, 4)
class PLUGIN_API CCutsceneShadow
{
public:
class CPhysical *m_pOwner;
unsigned __int8 m_bCreated;
unsigned __int8 m_nIntensity;
CShadowCamera m_Camera;
unsigned __int8 m_bBlurred;
CShadowCamera m_BlurCamera;
unsigned __int32 m_dwBlurPasses;
unsigned __int8 m_bDrawMoreBlur;
unsigned __int32 m_dwRwObjectType;
RpLight *m_pLight;
CSphere m_BoundingSphere;
CSphere m_BaseSphere;
CCutsceneShadow();
~CCutsceneShadow();
RwFrame *SetLightProperties(float angle, float _unused_param, bool setLight);
void Destroy();
CShadowCamera *GetShadowCamera();
RwTexture *GetShadowRwTexture();
void DrawBorderAroundTexture(RwRGBA const& color);
// this creates all stuff for shadow processing (cameras, textures)
bool Create(bool isBlurred, int blurPasses, bool drawMoreBlur);
// this one registers shadow for entity
bool SetupForThisEntity(class CPhysical *owner);
// this updates texture and give it to us
RwTexture *Update();
};
#pragma pack(pop)
VALIDATE_SIZE(CCutsceneShadow, 0x4C); | [
"dk22_@mail.ru@a08e2604-8956-8f2e-fb63-2a67f058b60e"
] | dk22_@mail.ru@a08e2604-8956-8f2e-fb63-2a67f058b60e |
3206c841c8f185488410b82f22865ada5c66ab50 | d28cf0304cc6f4c8e23a3997761bccd0559def50 | /wrap-debug/wrap_mode.cpp | 04075ab4d7d70e0c5956dad2f2758962744ede43 | [] | no_license | xiangyubo/effective-cpp | 411255e0cc6b129a6104412b923dcd824eed15fc | ac76956483138faae8f7b42a1e4240ec0c1eba21 | refs/heads/master | 2020-05-20T06:26:36.845283 | 2014-09-17T00:12:56 | 2014-09-17T00:12:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 89 | cpp | #include"wrap_mode.h"
void wrap_mode::run(void *args)
{
if(_DEBUG)
{
func(args);
}
} | [
"xyb19910413@163.com"
] | xyb19910413@163.com |
1755716f2f293a6649751235f82318ccfa956daf | dacb73add7e2744e7ed05d034a51498a0d760562 | /src/LeastSquaresFit.cpp | cb48ef475818327f7b8c06bf6f7b30aff17a7e34 | [
"MIT"
] | permissive | Dusty-M/CSC_499_Progressive_Analytics | 7d5dad70f2d56975bbafe85015e6b268363b0a8b | 2c7a4f279b6c5ff097d872a7ca15cc4f136439dc | refs/heads/master | 2022-06-02T23:45:07.405174 | 2020-05-04T07:38:19 | 2020-05-04T07:38:19 | 237,876,114 | 0 | 0 | MIT | 2020-05-04T07:38:21 | 2020-02-03T03:17:31 | C++ | UTF-8 | C++ | false | false | 18,370 | cpp | // LeastSquaresFit.cpp
#include "LeastSquaresFit.hpp"
#include <iostream>
#include <utility> //std::pair
#include <numeric> // std::inner_product
#include <chrono>
#include <memory>
#include <algorithm> // std::sort
using vec_col_float = std::vector<ColumnData<float_data_type>>;
using vec_col_int = std::vector<ColumnData<int_data_type>>;
template<typename X_type, typename Y_type>
std::ostream &operator<<(std::ostream &os, const point<X_type, Y_type> &pt){
os << "(" << pt.x << ", " << pt.y << ")";
return os;
}
template std::ostream &operator<<(std::ostream &os,
const point<float_data_type, float_data_type> &pt);
template<typename X_type, typename Y_type>
std::ostream &operator<<(std::ostream &os, const summary<X_type, Y_type> &sum){
os << "proj: " << sum.proj << "\n"
<< "representative_pts: " << std::endl;
for(auto val : sum.representative_pts) {
os << "(" << val.x << ", " << val.y << "), ";
}
os << "SS_xx: " << sum.SS_xx << "\nSS_xy: " << sum.SS_xy << "\n"
<< "x_bar: " << sum.x_bar << "\ny_bar: " << sum.y_bar << "\n"
<< "count: " << sum.count << std::endl;
return os;
}
template std::ostream &operator<<(
std::ostream &os, const summary<float_data_type, float_data_type> &sum);
projection error( projection const p1, projection const p2) {
return projection { std::abs(p1.a_proj - p2.a_proj),
std::abs(p1.b_proj - p2.b_proj)};
}
std::ostream &operator << (std::ostream &s, projection const proj)
{
return s << "(" << proj.a_proj << ", " << proj.b_proj << ")";
}
// Provide a vector of points and a lambda function representing the project line of best fit
// and get_points returns a set of n points closest to dy
// Ie. if dy is set to -1.0, in points as close to a value of 1.0 below the line will be returned
template <typename Point_type>
std::vector<Point_type> get_points(const index_type n, const float_data_type dy,
const std::vector<Point_type> &all_points,
const std::function<float_data_type(float_data_type)> &&f_x) {
// testing code
for(auto pt : all_points) {
std::cout << "point: " << pt << ", error: " << (f_x(pt.x) - pt.y) << std::endl;
}
std::vector< Point_type > cur_rep_points {};
// Find point with error that is closest to the value of dy
auto iter {all_points.begin()};
float_data_type closest_error {std::abs((f_x(iter->x)) - iter->y)};
std::cout << "first element's error: " << closest_error << std::endl;
iter++;
while(iter != cur_rep_points.end()) {
float_data_type cur_error{std::abs(f_x(iter->x) - iter->y)};
std::cout << "cur_error :" << cur_error << std::endl;
if (std::abs(cur_error - dy) < std::abs(closest_error - dy)) {
closest_error = cur_error;
iter++;
} else {
// error must be equal or larger, therefore previous element contains min
// remove element from all_points, add it to cur_rep_points
// set up iterators on either side
// recall: vector::erase() returns an iterator to the element following
// the member being removed
cur_rep_points.push_back(*(--iter));
std::cout << "Choosing point with error: " << closest_error << std::endl;
break;
}
} // end of setup
// iter is now pointing to the closest point in all_points to the point with
// closest error to target error
// testing - checking contents of cur_rep_points
std::cout << "contents of cur_rep_points: " << cur_rep_points.at(0);
std::cout << ", size: " << cur_rep_points.size() << std::endl;
// two iterators will now be used:
// - one iterator (iter_back) will start one element past/behind iter. Each time an element
// pointed to by this iterator is added to cur_rep_points, the iterator
// will be incremented towards the end of the vector
// - one iterator (iter_front) will start one element before/in front of iter.
// This will be a reverse iterator. Each time and element pointed to by this iterator is
// added to cur_rep_points, the iterator will be incremented towards
// the front of the vector (still a ++ since it's a reverse iterator)
auto iter_back {iter + 1}; // iter_back now points to element after iter
// offset = number to increment iter_front.
// iter_front begins by pointing at back-most element.
// It needs to be moved so that it points at the element in front of iter
// iter - begin() is distance from front to iter
// therefore size() - (iter - begin()) = distance from back element to target element
auto offset = all_points.size() - (iter - all_points.begin());
auto iter_front {all_points.rbegin()};
iter_front += offset; // iter_front now points to element before iter
std::cout << "is iter_front at rend()?: " << (iter_front == all_points.rend()) << std::endl;
std::cout << "iter_front: " << *iter_front << ", iter_back" << *iter_back << std::endl;
auto tmp_iter {all_points.rbegin()};
// iter_front and iter_back are now pointing to elements on either side of iter
while(cur_rep_points.size() < all_points.size() && cur_rep_points.size() < n) {
// sanity check, this should never run, thus no exception is being thrown
if(iter_front == all_points.rend() && iter_back == all_points.end()) {
std::cout << "Error, trying to add representative points after all available points have been added already!" << std::endl;
exit(1);
}
if(iter_front == all_points.rend()) { // out of points to left of target point
// just add back point
cur_rep_points.push_back(*iter_back++);
} else if (iter_back == all_points.end()) { // out of points to right of target point
cur_rep_points.push_back(*iter_front++);
} else { // points exist on both sides, do comparison to choose which to add
auto error_front {f_x(iter_front->x) - iter_front->y};
auto error_back {f_x(iter_back->x) - iter_back->y};
if(std::abs(error_front - dy) < std::abs(error_back - dy)) { // front points is closer
cur_rep_points.push_back(*iter_front++);
} else { // back put is closer
cur_rep_points.push_back(*iter_back++);
}
}
} // end of while loop, all points added to cur_rep_points
return cur_rep_points;
}
template std::vector < point < float_data_type, float_data_type > >
get_points( const index_type n, const float_data_type dy,
const std::vector < point < float_data_type, float_data_type > > &all_points,
const std::function < float_data_type(float_data_type) > &&f_x);
template <typename X_type, typename Y_type>
void runProfile(const index_type num_segments, const CSVParser &csv,
const std::string &X_header, const std::string &Y_header,
const index_type header_row_index, const index_type first_data_row_index) {
using vec_cols_tX = std::vector<ColumnData<X_type>>;
using vec_cols_tY = std::vector<ColumnData<Y_type>>;
using time_nano_t = std::chrono::nanoseconds;
// If num_segments != 1, run the analysis with a single segment (non-progressive)
// to obtain the true y-intercept and slope. Use these values to determine
// the error during progressive calculations
// float_data_type a_actual, b_actual;
std::shared_ptr <projection> actual;
{ // scoping lsf
auto lsf {makeLeastSquaresFit<vec_cols_tX, vec_cols_tY>(
csv.makeSegments<X_type>(
X_header,
header_row_index,
first_data_row_index,
1),
csv.makeSegments<Y_type>(
Y_header,
header_row_index,
first_data_row_index,
1))};
lsf.calcNextProjection(); // performs complete calculation
// a_actual = lsf.getProja();
// b_actual = lsf.getProjb();
actual = std::make_shared<projection>
(projection {lsf.getProja(), lsf.getProjb()});
}
// Setup for progressive calculation
auto Xs {csv.makeSegments<X_type>(X_header,
header_row_index, first_data_row_index, num_segments)};
auto Ys {csv.makeSegments<Y_type>(Y_header,
header_row_index, first_data_row_index, num_segments)};
auto lsf {makeLeastSquaresFit<vec_cols_tX , vec_cols_tY>(Xs, Ys)};
index_type cur_seg {0};
auto start {std::chrono::system_clock::now()};
while(lsf.calcNextProjection()) {
projection cur_proj {lsf.getProja(), lsf.getProjb()};
std::cout << "Error: " << error(*actual, cur_proj);
auto cur {std::chrono::system_clock::now()};
std::cout << ", segment: " << cur_seg++ << ", Time elapsed" << ": "
<< std::chrono::duration_cast<time_nano_t>(cur - start).count() << " ns" << std::endl;
}
auto cur {std::chrono::system_clock::now()};
std::cout << "time elapsed [total]: "
<< std::chrono::duration_cast<time_nano_t>(cur - start).count()
<< " ns" << std::endl;
}
template void runProfile<float_data_type, float_data_type>(
const index_type num_segments, const CSVParser &csv,
const std::string &X_header, const std::string &Y_header,
const index_type header_row_index, const index_type first_row_data_index);
template <typename X_type, typename Y_type>
LeastSquaresFit<X_type, Y_type>::LeastSquaresFit(X_type X, Y_type Y):
_X {X}, _Y {Y},_x_bar {0}, _y_bar {0},
_SS_xx {0}, _SS_xy {0}, _a {0}, _b {0},
_count {0} {}
template class LeastSquaresFit<vec_col_int, vec_col_int>;
template class LeastSquaresFit<vec_col_float, vec_col_float>;
template <typename X_type, typename Y_type>
void LeastSquaresFit<X_type, Y_type>::init() {
_x_bar = calcAvg(_X);
_y_bar = calcAvg(_Y);
}
template <typename X_type, typename Y_type>
LeastSquaresFit<X_type, Y_type> makeLeastSquaresFit(
X_type X, Y_type Y) {
LeastSquaresFit<X_type, Y_type> lsf{X, Y};
lsf.init();
return lsf;
}
template LeastSquaresFit<vec_col_float, vec_col_float>
makeLeastSquaresFit(vec_col_float X, vec_col_float Y);
template <typename X_type, typename Y_type> // X_type/Y_type are std::vector<Columndata<T>>
segment<typename X_type::value_type, typename Y_type::value_type>
LeastSquaresFit<X_type, Y_type>::getNextSegment()
{
auto X = _X.at(_count);
auto Y = _Y.at(_count);
++_count;
return segment {X, Y, _x_bar, _y_bar};
};
template segment <typename vec_col_float::value_type, typename vec_col_float::value_type >
LeastSquaresFit<vec_col_float, vec_col_float>::getNextSegment();
template <typename X_type, typename Y_type>
bool LeastSquaresFit<X_type, Y_type>::calcNextProjection() {
if(_count == _X.size()) { // indicates no update to projection was made
return false;
}
const auto &X_cur_seg {_X.at(_count).data_raw};
const auto &Y_cur_seg {_Y.at(_count).data_raw};
// use inner product to calculate SS_xx and SS_xy
float_data_type init_SS_xx {-(X_cur_seg.size() * _x_bar * _x_bar)};
float_data_type init_SS_xy {-(Y_cur_seg.size() * _x_bar * _y_bar)};
float_data_type cur_SS_xx {std::inner_product(X_cur_seg.begin(), X_cur_seg.end(),
X_cur_seg.begin(), init_SS_xx)};
float_data_type cur_SS_xy {std::inner_product(X_cur_seg.begin(), X_cur_seg.end(),
Y_cur_seg.begin(), init_SS_xy)};
// now add cur_SS_xx and cur_SS_xy to persistent
// values, _SS_xx and _SS_xy
_SS_xx += cur_SS_xx;
_SS_xy += cur_SS_xy;
// update values of _a, _b based on new sums of squares
_b = _SS_xy / _SS_xx;
_a = _y_bar - _b * _x_bar;
++_count;
return true;
}
template bool LeastSquaresFit<vec_col_float, vec_col_float>::calcNextProjection();
template bool LeastSquaresFit<vec_col_int, vec_col_int>::calcNextProjection();
template <typename X_type, typename Y_type>
float_data_type LeastSquaresFit<X_type, Y_type>::getProja(){ return _a; }
template float_data_type LeastSquaresFit<vec_col_int, vec_col_int>::getProja();
template float_data_type LeastSquaresFit<vec_col_float, vec_col_float>::getProja();
template <typename X_type, typename Y_type>
float_data_type LeastSquaresFit<X_type, Y_type>::getProjb(){ return _b; }
template float_data_type LeastSquaresFit<vec_col_int, vec_col_int>::getProjb();
template float_data_type LeastSquaresFit<vec_col_float, vec_col_float>::getProjb();
template <typename X_type, typename Y_type>
std::ostream &operator<<(std::ostream &os, const LeastSquaresFit<X_type, Y_type> &lsf) {
std::cout << "_x_bar: " << lsf._x_bar << "\n"
<< "_y_bar: " << lsf._y_bar << "\n"
<< "_a: " << lsf._a << "\n"
<< "_b: " << lsf._b << "\n"
<< "_count: " << lsf._count << std::endl;
return os;
}
template std::ostream &operator<<(std::ostream &os,
const LeastSquaresFit<vec_col_int, vec_col_int> &lsf);
template std::ostream &operator<<(std::ostream &os,
const LeastSquaresFit<vec_col_float, vec_col_float> &lsf);
template <typename X_type, typename Y_type>
summary<X_type, Y_type> create_summary(segment<ColumnData<X_type>, ColumnData<Y_type>> seg)
{
summary<X_type, Y_type> cur_summary;
// transfer x_bar, y_bar from seg to summary
cur_summary.x_bar = seg.x_bar;
cur_summary.y_bar = seg.y_bar;
// Since this summary is being created by a segment of data directly
// the count will always be 1
cur_summary.count = 1;
// calculate SS_xx, SS_xy
float_data_type init_SS_xx {-(seg.X.data_raw.size() * seg.x_bar * seg.x_bar)};
float_data_type init_SS_xy {-(seg.Y.data_raw.size() * seg.x_bar * seg.y_bar)};
float_data_type cur_SS_xx {std::inner_product(seg.X.data_raw.begin(), seg.X.data_raw.end(),
seg.X.data_raw.begin(), init_SS_xx)};
float_data_type cur_SS_xy {std::inner_product(seg.X.data_raw.begin(), seg.X.data_raw.end(),
seg.Y.data_raw.begin(), init_SS_xy)};
// calculate projection
float_data_type cur_b_proj {cur_SS_xy / cur_SS_xx};
float_data_type cur_a_proj {seg.y_bar - cur_b_proj * seg.x_bar};
cur_summary.proj = projection{cur_a_proj, cur_b_proj};
// calculate representative points
// first, build vector of points
std::vector<point<X_type, Y_type>> all_points;
for(index_type i {0}; i < seg.X.data_raw.size(); ++i) {
auto cur_x = seg.X.data_raw.at(i);
auto cur_y = seg.Y.data_raw.at(i);
all_points.push_back(point<X_type, Y_type> {cur_x, cur_y});
}
// create lambda used to evaluate current projection
auto f_proj {[&cur_summary](X_type x_i)
{return cur_summary.proj.a_proj + x_i * cur_summary.proj.b_proj;}};
auto compare {[&f_proj](point<X_type, Y_type> p1, point<X_type, Y_type> p2) {
float_data_type error_p1, error_p2;
error_p1 = std::abs(f_proj(p1.x) - p1.y);
error_p2 = std::abs(f_proj(p2.x) - p2.y);
return error_p1 < error_p2;}
};
// sort points;
std::sort(all_points.begin(), all_points.end(), compare);
const float_data_type TARGET_ERROR {0.0};
cur_summary.representative_pts = get_points(10, TARGET_ERROR, all_points, f_proj);
return cur_summary;
}
template summary<float_data_type, float_data_type> create_summary<float_data_type, float_data_type>
(segment<ColumnData<float_data_type>, ColumnData<float_data_type>> seg);
template <typename X_type, typename Y_type>
summary<X_type, Y_type> create_summary(
summary<X_type, Y_type> s1, summary<X_type, Y_type> s2)
{
std::cout << "printing summaries" << std::endl;
std::cout << s1 << "\n\n" << s2 << std::endl;
// calculate slope and y intercept
float_data_type cur_SS_xx = s1.SS_xx + s2.SS_xx;
float_data_type cur_SS_xy = s1.SS_xy + s2.SS_xy;
float_data_type b = cur_SS_xy / cur_SS_xx;
float_data_type a = s1.y_bar - b * s1.x_bar;
projection cur_proj {a, b};
std::cout << "projection: " << cur_proj << std::endl;
// Calculate x_bar,y_bar
float_data_type cur_x_bar = ((s1.x_bar * s1.count) + (s2.x_bar * s2.count))
/ (s1.count + s2.count);
float_data_type cur_y_bar = ((s1.y_bar * s1.count) + (s2.y_bar * s2.count))
/ (s1.count + s2.count);
// create lambda function to evaluate current projection,
// useful for evaluating error
auto f_proj {[&cur_proj](X_type x_i)
{return cur_proj.a_proj + x_i * cur_proj.b_proj;}};
// select representative points from {s1.representative_pts UNION s2.representative_pts}
// sort points based on error.
// Note: when comparing a point to f(x) using the projection calculated
// above, f(x_i) = a + b * x_i, this is contained in f_proj lambda
// then error = f_proj(x_i) - y_i
//
// NOTE: abs value NOT used here intentionally
// By being sensitive to sign points can be gathered in equal
// quantity from above/below the line.
// calculate error for the ith representative point in each summary
// and add pair of error,point for each rep. point in both s1 and s2
// Add all representative points from both summaries to all_points
std::vector < point< X_type, Y_type > > all_points;
all_points.insert( all_points.begin(),
s1.representative_pts.begin(),
s1.representative_pts.end());
all_points.insert( all_points.begin(),
s2.representative_pts.begin(),
s2.representative_pts.end());
// lambda function used to compare points based on error
auto compare {[&f_proj](point<X_type, Y_type> p1, point<X_type, Y_type> p2) {
float_data_type error_p1, error_p2;
error_p1 = std::abs(f_proj(p1.x) - p1.y);
error_p2 = std::abs(f_proj(p2.x) - p2.y);
return error_p1 < error_p2;}
};
/*****************************************************
std::cout << "printing points before sorting" << std::endl;
for(auto pt : all_points) {
std::cout << pt << ", ";
}
std::cout << std::endl;
*****************************************************/
// sort points;
std::sort(all_points.begin(), all_points.end(), compare);
/*****************************************************
std::cout << "printing points after sorting" << std::endl;
for(auto pt : all_points) {
std::cout << pt << ", ";
}
std::cout << std::endl;
*****************************************************/
// pick most representative points
if(all_points.empty()) {
std::cout << "ERROR, all_points is empty, "
<< "neither summary contained rep points!" << std::endl;
}
// For now (temporary measure) representative points will consist of the 20
// points closest to the line. Later, this will be modified such that
// there will be some number of points taken nearest the line, as well
// as values located +/- 0.5 std dev from line, +/- 1.0 std dev, etc.
const float_data_type TARGET_ERROR {0.0};
std::vector < point <float_data_type, float_data_type > > cur_rep_points =
get_points(10, TARGET_ERROR, all_points, f_proj);
return
summary<float_data_type, float_data_type> {
cur_proj, // projection
cur_rep_points, // representative_pts
s1.SS_xx + s2.SS_xx, // SS_xx
s1.SS_xy + s2.SS_xy, // SS_xy
cur_x_bar, // x_bar
cur_y_bar, // y_bar
s1.count + s2.count}; // count
}
using float_summary_type = summary<float_data_type, float_data_type>;
template float_summary_type create_summary<float_data_type, float_data_type>
(float_summary_type s1, float_summary_type s2);
| [
"leodmiller@gmail.com"
] | leodmiller@gmail.com |
8d22b48030d6078f91caa219e1d7b97927d22d4f | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8381/Perelygin_Dmitry/Lab4/Deus_Vult/crusader_fabric.cpp | ec2013713215c86e6f5ca632a84a5f92ad8ece6c | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 707 | cpp | #include "crusader_fabric.h"
// Реализация параметризированного фабричного метода
Unit* Crusader_fabric::createWarrior ( Warrior_ID id, int new_name, class Field *new_field, Base* new_base )
{
Unit * p = nullptr;
switch (id)
{
case Infantryman_ID:
p = new Crusader(new_name,new_field, new_base);
break;
case Archer_ID:
p = new CrusaderArcher(new_name,new_field, new_base);
break;
case Horseman_ID:
p = new Knight(new_name,new_field, new_base);
break;
}
return p;
};
| [
"noreply@github.com"
] | noreply@github.com |
bcef4451cfd9025245683892619fc130a0d018df | 755683f02780fcbf4f274a3b45865127424c0e05 | /upgraded/upgraded.ino | c4811d6bfd0fffbbbb688772834246869805cee0 | [
"MIT"
] | permissive | kvatigabi/projectTechnology19 | aa78979d79bbde81174e944ad8d9b7fa31921ca1 | 931ea1354b33c92ce06752388ebd8ec6bca6fd55 | refs/heads/master | 2023-05-26T07:01:40.733233 | 2023-05-17T19:10:22 | 2023-05-17T19:10:22 | 242,745,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,026 | ino | #include <Servo.h>
#define LED_NOTIF A0 //notification led to let us know if changeLights is running
#define LED_G1 2
#define LED_Y1 3
#define LED_R1 4
#define LED_G2 5
#define LED_Y2 6
#define LED_R2 7
#define LED_G3 8
#define LED_Y3 9
#define LED_R3 10
#define TRIG 11
#define ECHO 12
#define SERVO_PIN 13
bool isTurned; //boolean to see if servo is turned. false right , true is front
int pinCount = 9; //this will be needed in pin initialize array
long duration;
int distance;
Servo servo1;
int ledPins[] = {
LED_G1, LED_Y1, LED_R1, LED_G2, LED_Y2, LED_R2, LED_G3, LED_Y3, LED_R3, SERVO_PIN, LED_NOTIF
};
void setup() {
// put your setup code here, to run once:
//initialise every pin in this array
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
digitalWrite(ledPins[thisPin], LOW);
}
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
digitalWrite(LED_G2, HIGH);//initial values
digitalWrite(LED_R1, HIGH);
digitalWrite(LED_R3, HIGH);
servo1.attach(SERVO_PIN);
servo1.write(10); //servo looks to the right as a starting point
isTurned = false;
Serial.begin(9600);
}
void loop() {
//this is the code for the sonar
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
duration = pulseIn(ECHO, HIGH);
distance = duration * 0.034 / 2;
Serial.print(F("distance in cm: "));
Serial.println(distance);
//this is were the magic happens
if ((distance < 14) && (!isTurned)) { // check if there is car in front and servo is NOT turned
digitalWrite(LED_NOTIF, HIGH);
servo1.write(70);//servo right
isTurned = true; // boolean to tell its looking front
changeLights();//change the lights!
digitalWrite(LED_NOTIF, LOW);
}
else if ((distance < 10) && (isTurned)) { //check if we have turned and there is a car ahead of us
digitalWrite(LED_NOTIF, HIGH);
servo1.write(10); //turn servo to right
isTurned = false; //set bool to false
changeLights();//change lights again
digitalWrite(LED_NOTIF, LOW);
}
delay(130);
}
//the changeLights function explains it self
void changeLights()
{
Serial.println(F("BEGIN CHANGE_LIGHTS FUN"));
digitalWrite(LED_R1, HIGH);
digitalWrite(LED_R3, HIGH);
digitalWrite(LED_G2, HIGH);
delay(8000);//how long green(only change this)
digitalWrite(LED_G2, LOW);
digitalWrite(LED_Y2, HIGH);
delay(3000);
digitalWrite(LED_Y2, LOW);
digitalWrite(LED_R2, HIGH);
delay(700);
digitalWrite(LED_R3, LOW);
digitalWrite(LED_R1, LOW);
digitalWrite(LED_G1, HIGH);
digitalWrite(LED_G3, HIGH);
delay(8000);//how long green (only change this)
digitalWrite(LED_G1, LOW);
digitalWrite(LED_G3, LOW);
digitalWrite(LED_Y1, HIGH);
digitalWrite(LED_Y3, HIGH);
delay(3000);
digitalWrite(LED_Y1, LOW);
digitalWrite(LED_Y3, LOW);
digitalWrite(LED_R1, HIGH);
digitalWrite(LED_R3, HIGH);
delay(700);
digitalWrite(LED_R2, LOW);
digitalWrite(LED_G2, HIGH);
}
| [
"kvatigabi@gmail.com"
] | kvatigabi@gmail.com |
06577aee9dca7a3948ee1a0d67d30ea5c3df36bb | e21752f3832a27bab5850ac8177a31ff06e93fbb | /src/Platform/Linux/System/Future.h | 0e5495f52eba5ce438b89889bbeb1489932e23ac | [] | no_license | Cryolitecoin/cryo | 9d76a84f80bd3e768505ad2493039df353e5b2c8 | 829637a0908bb558cb4fae5fb94448ebc003274e | refs/heads/master | 2020-04-15T19:25:56.992088 | 2019-01-12T16:29:20 | 2019-01-12T16:29:20 | 164,949,378 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | // Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2018 The Circle Foundation
// Copyright (c) 2019 The Cryo Network
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <future>
namespace System {
namespace Detail {
template<class T> using Future = std::future<T>;
template<class T> Future<T> async(std::function<T()>&& operation) {
return std::async(std::launch::async, std::move(operation));
}
}
}
| [
"38926162+Cryolitecoin@users.noreply.github.com"
] | 38926162+Cryolitecoin@users.noreply.github.com |
1cb2436a2f683f84d0555aece981a6496c81b693 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_TradeOption_SummerBash_Swimshirt_Alpha_parameters.hpp | 2923059550efc5292f96727505d06cabaa10f0c7 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 830 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_TradeOption_SummerBash_Swimshirt_Alpha_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function TradeOption_SummerBash_Swimshirt_Alpha.TradeOption_SummerBash_Swimshirt_Alpha_C.ExecuteUbergraph_TradeOption_SummerBash_Swimshirt_Alpha
struct UTradeOption_SummerBash_Swimshirt_Alpha_C_ExecuteUbergraph_TradeOption_SummerBash_Swimshirt_Alpha_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
79950d5f20e849ebd3ce5d39d6c501c5ee25f511 | 0f4164a87c940a2990933ea678acbe34aefec7a3 | /World.h | df1170bf16b7caa42db250a876ffabd2ad50286a | [] | no_license | jonsim/test-game | d851748430bddf441496032350ce1222692c269f | e0222cf355d18b8e8f434bdc0ccdfe27c9e66267 | refs/heads/master | 2020-05-20T06:04:43.865131 | 2012-07-29T19:16:20 | 2012-07-29T19:16:20 | 5,215,521 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | #ifndef WORLD_H
#define WORLD_H
//---------- INCLUDES ----------//
#include <Terrain/OgreTerrain.h>
#include <Terrain/OgreTerrainGroup.h>
//---------- DEFINITIONS ----------//
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
class World
{
public:
World (Ogre::SceneManager* sceneManager, Ogre::Light* sun);
virtual ~World (void);
Ogre::Vector3 getTerrainNormal (Ogre::Vector3 worldPosition);
float getTerrainHeight (Ogre::Vector3 worldPosition);
bool terrainRaycast (Ogre::Ray& ray, Ogre::Vector3* resultPosition);
void saveTerrainState (void);
private:
void defineTerrain (long x, long y);
void initBlendMaps (Ogre::Terrain* terrain);
void configureTerrainDefaults (Ogre::SceneManager* sceneManager, Ogre::Light* sun);
void setupWorld (void);
Ogre::TerrainGroup* mTerrainGroup;
Ogre::TerrainGlobalOptions* mTerrainGlobals;
// OgreBites::Label* mInfoLabel;
bool mTerrainsImported;
};
#endif // #ifndef WORLD_H
| [
"jonathansimmonds@gmail.com"
] | jonathansimmonds@gmail.com |
02d2868a62f33cc2bf7ba19974ce88c5821233cd | 1a6abd31e69d5e3ac7fb4f6089b5e5edbd1bce5a | /Main/Song.cpp | f0875bf8b4b71dd9c2f5e3eb6cf41b19f7e66b50 | [
"MIT"
] | permissive | ojasva/PecoBeat | 2b3b88bd7ba128b807756d472464931b9af976e0 | 1d2b070eeb467f97c3f19119bef69973b71b25e9 | refs/heads/master | 2020-04-12T05:44:01.980829 | 2018-12-18T18:32:31 | 2018-12-18T18:32:31 | 162,330,113 | 0 | 0 | null | 2018-12-18T18:30:39 | 2018-12-18T18:30:38 | null | UTF-8 | C++ | false | false | 5,380 | cpp | /*
* Copyrights (c):
* 2001 - 2008 , Werner Freytag.
* 2009, Haiku
* Distributed under the terms of the MIT License.
*
* Original Author:
* Werner Freytag <freytag@gmx.de>
*/
#include "Song.h"
#include <Alert.h>
#include <Looper.h>
#include <Message.h>
#include <MidiDefs.h>
#include <Window.h>
#include "App.h"
#include "MIDIProducer.h"
#include "PatternDefs.h"
#include "PatternRow.h"
#include "Ticker.h"
Song *gSong = 0;
Song::Song()
: BLooper("Beat Song", 50 ),
fPattern( 0 ),
fTicker( 0 )
{
Init();
Run();
fTicker = new Ticker( this );
}
Song::~Song() {
Stop();
if (fTicker) {
fTicker->Lock();
fTicker->Quit();
}
delete fPattern;
}
void Song::Init() {
fActiveNr = 0,
fLastFilledNr = -1;
fVelocityFactor = 1.0;
fCursorPosition = 0;
fIsPlaying = false;
fModified = false;
fPattern = new Pattern();
for (int i=0; i < (16 * 4); ++i) fPlayList[i] = -1;
}
void Song::SaveToMessage(BMessage &msg) {
msg.what = 'peco';
msg.AddString( "signature", "pecobeat" );
msg.AddFloat( "version", 1.0);
msg.AddInt32("speed", Speed() );
msg.AddInt32("velocity", Velocity() );
for(int i=0; i<=LastFilledNr(); ++i) {
msg.AddInt32("playlist", PlayListEntry(i));
}
for (int i=0; i<12; ++i) {
BMessage part_msg('part');
for (int j = 0; j<fPattern->CountItems(); ++j) {
BMessage row_msg('row');
PatternRow *row = (PatternRow *)fPattern->ItemAt(j);
if (i==0) {
row_msg.AddInt16("key", row->Key());
row_msg.AddInt32("velocity", row->Velocity());
}
for (int k=0; k<256; ++k) {
row_msg.AddInt8("note", row->Note( (i<<8) + k) );
}
part_msg.AddMessage("row", &row_msg);
}
msg.AddMessage("part", &part_msg);
}
}
status_t Song::LoadFromMessage(BMessage &msg) {
BString string;
float f;
int32 i32;
int16 i16;
int8 i8;
if (msg.what!='peco') return B_ERROR;
if (msg.FindString("signature", &string)!=B_OK) return B_ERROR;
if (string!="pecobeat") return B_ERROR;
if (msg.FindFloat("version", &f)!=B_OK) return B_ERROR;
if (f!=1.0) return B_ERROR;
delete fPattern;
Init();
if (msg.FindInt32("speed", &i32 )==B_OK) SetSpeed(i32);
if (msg.FindInt32("velocity", &i32 )==B_OK) SetVelocity(i32);
int32 j=-1;
for(int i=0; i<64 && (msg.FindInt32("playlist", i, &i32)==B_OK); ++i) {
if (i32<12) {
++j;
SetPlayListEntry(i, i32);
}
}
SetLastFilledNr(j);
BMessage part_msg;
for(int i=0; i<12 && (msg.FindMessage("part", i, &part_msg)==B_OK); ++i) {
BMessage row_msg;
for (int j = 0; part_msg.FindMessage("row", j, &row_msg)==B_OK; ++j) {
PatternRow *row;
if (!(row = (PatternRow *)fPattern->ItemAt(j))) {
row = new PatternRow();
fPattern->AddItem(row);
}
if (row_msg.FindInt16("key", &i16)==B_OK) row->SetKey(i16);
if (row_msg.FindInt32("velocity", &i32)==B_OK) row->SetVelocity(i32);
for (int k=0; k<256 && (row_msg.FindInt8("note", k, &i8 )==B_OK); ++k) {
row->SetNote( (i<<8) + k, i8 );
}
}
}
return B_OK;
}
void Song::PlaySong() {
fCursorPosition = fPlayList[fActiveNr]<<8;
fPlayMode = PLAY_SONG;
StartPlaying();
}
void Song::PlayPattern() {
fCursorPosition = (ActivePart()<<8) + fCursorPosition & 255;
fPlayMode = PLAY_PATTERN;
StartPlaying();
}
void Song::Stop() {
fCursorPosition = -1;
fTicker->Stop();
fIsPlaying = false;
for (int i = 0; i<fPattern->CountItems(); ++i ) {
PatternRow *row = (PatternRow *)(fPattern->ItemAt(i));
StopSound( row->Key(), row->Velocity() * fVelocityFactor );
}
}
void Song::StartPlaying() {
fTicker->Start();
fIsPlaying = true;
}
void Song::SetActiveNr( int32 nr ) {
fActiveNr = nr;
if (IsPlaying() && PlayMode()==PLAY_SONG) {
SetCursorPosition( (fCursorPosition & 255) + (PlayListEntry(nr)<<8) );
}
}
void Song::SetPlayListEntry( int32 entry, int32 part ) {
SetModified();
fPlayList[entry] = part;
}
void Song::SetSpeed( int32 speed ) {
fSpeed = speed;
fTicker->SetDelay( 3750000 / speed );
};
void Song::MessageReceived(BMessage *msg) {
switch ( msg->what ) {
case 'tick': {
if (fIsPlaying && fCursorPosition!=-1) {
UpdateCursor();
PlayAtCursor();
++fCursorPosition;
UpdateCursor();
}
} break;
case 'plys': {
PlaySong();
} break;
case 'plyp': {
PlayPattern();
} break;
case 'stop': {
Stop();
} break;
}
}
void Song::UpdateCursor() {
if (fPlayMode==PLAY_PATTERN) {
fCursorPosition = (ActivePart() << 8) + (fCursorPosition & 255);
}
else {
if ((fCursorPosition>>8) != fPlayList[fActiveNr]) {
if (fActiveNr==fLastFilledNr) {
fActiveNr = 0;
be_app->PostMessage('stop');
}
else {
fActiveNr++;
fCursorPosition = fPlayList[fActiveNr]<<8;
}
}
}
}
void Song::PlayAtCursor() {
if (fCursorPosition==-1) return;
for (int i = 0; i<fPattern->CountItems(); ++i ) {
PatternRow *row = (PatternRow *)(fPattern->ItemAt(i));
switch( row->Note(fCursorPosition) ) {
case NOTE_ON: PlaySound( row->Key(), row->Velocity() * fVelocityFactor ); break;
case NOTE_OFF: StopSound( row->Key(), row->Velocity() * fVelocityFactor ); break;
}
}
}
void Song::PlaySound( int32 key, int32 velocity ) {
StopSound( key, velocity );
gMidiProducer->SprayNoteOn( 10, key, (int)(velocity * fVelocityFactor) );
}
void Song::StopSound( int32 key, int32 velocity ) {
gMidiProducer->SprayNoteOff( 10, key, (int)(velocity * fVelocityFactor) );
}
| [
"mmadia@157b0fc8-90a9-4247-b30d-6697653e9eed"
] | mmadia@157b0fc8-90a9-4247-b30d-6697653e9eed |
1dfb0f2d377645f26973bcdafcd703165604356a | 1acdf59ed9bae5dbcdb53aad114f524e23ca6ad5 | /model.cpp | 7c19ae2cd4ecece2575fffc69767a254251e9a16 | [] | no_license | gantony/keystrokes-visualizer | c4e03b607dddd3b543c4942239b1bb03985e8314 | 3e275fa57785cdd2850ce017ec345f6b4642f9f5 | refs/heads/master | 2020-04-19T00:41:03.086338 | 2019-02-25T22:05:32 | 2019-02-25T22:05:32 | 167,853,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,469 | cpp | #include "model.h"
#include <QEvent>
#include <QKeyEvent>
#include <QDebug>
#include <QtGlobal>
Model::Model(QObject *parent) :
QAbstractListModel(parent),
onlyShowLasts(false),
numToShow(0)
{
Event e;
e.key = 10;
e.text = "TEST";
events.push_back(e);
}
int Model::rowCount(const QModelIndex &parent) const
{
if (onlyShowLasts) {
return qMin<int>(numToShow, events.size());
} else {
return events.size();
}
}
QVariant Model::data(const QModelIndex &index, int role) const
{
if ( role == Qt::DisplayRole ) {
if (onlyShowLasts) {
if (index.row() < numToShow){
int lastIndexShown = events.size() - 1;
int indexOf1stItemShow = qMax<int>(0, lastIndexShown - numToShow);
return events.at(indexOf1stItemShow + index.row()).text;
} else {
return QVariant();
}
} else {
if (index.row() < events.size()) {
return events.at(index.row()).text;
}
}
}
return QVariant();
}
bool Model::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug() << "Model::eventFilter() QEvent::KeyPress" << keyEvent->key() << keyEvent->text();
onKeyPressed(keyEvent->key(), keyEvent->text());
return true;
}
return false;
}
void Model::onKeyPressed(int code, const QString &text)
{
Event e;
e.key = code;
e.text = text;
if (onlyShowLasts) {
// When showing the last ones only, we are basically shifting everything one row up
// on every update, so we might as well reset the model to keep things simple...
// The reset is probably wastefull when we have a lot of non-visible rows.
// TODO: implement properly later. When (onlyShowLasts && events.size() >= numToShow)
beginResetModel();
events.push_back(e);
endResetModel();
} else {
beginInsertRows(createIndex(events.size()-1, 0), events.size(), events.size());
events.push_back(e);
endInsertRows();
}
}
void Model::limitToLast(int number)
{
beginResetModel();
onlyShowLasts = true;
numToShow = number;
endResetModel();
}
void Model::showEverything()
{
beginResetModel();
onlyShowLasts = false;
numToShow = 0;
endResetModel();
}
| [
"antony.guinard@gmail.com"
] | antony.guinard@gmail.com |
2a896d60d888f7979693401dbc3ded1d81bcbcb4 | ef2ea07785f8af5733246f61c91ff12fb09b7d7a | /leetcode/Sort List.cpp | 163b4a67b240a34da0a3a67c49e1bbac9725d403 | [] | no_license | baoxuezhao/solution_set | 35a77cd8db76d0d1334babf7e74647a517d8bcce | 56a4fdc6dcb3fe7879d5a1239de9c57af356d54d | refs/heads/master | 2021-10-02T21:51:12.607669 | 2018-12-01T09:27:36 | 2018-12-01T09:27:36 | 23,954,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,721 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//solution 1, need to find the middle node at each round.
class Solution {
public:
ListNode *sortList(ListNode *head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode *slow = head, *fast = head, *prev;
while(fast && fast->next)
{
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode *part1 = sortList(head);
ListNode *part2 = sortList(slow);
ListNode dummy(-1);
ListNode *cur = &dummy;
while(part1 || part2)
{
int val1 = part1? part1->val: INT_MAX;
int val2 = part2? part2->val: INT_MAX;
if(val1 <= val2)
{
cur->next = part1;
part1 = part1->next;
}
else
{
cur->next = part2;
part2 = part2->next;
}
cur = cur->next;
}
return dummy.next;
}
};
//solution 2, buttom up, without need to find the middle point at each round.
class Solution {
public:
ListNode *sortList(ListNode *head) {
if(head == NULL || head->next == NULL) return head;
int len = 0;
ListNode *cur = head;
while(cur)
{
len++;
cur = cur->next;
}
return sortutil(head, 0, len-1);
}
ListNode *sortutil(ListNode *&head, int left, int right)
{
if(left > right) return NULL;
if(left == right)
{
ListNode *ret = head;
head = head->next;
ret->next = NULL;
return ret;
}
int mid = left+(right-left)/2;
ListNode *lch = sortutil(head, left, mid);
ListNode *rch = sortutil(head, mid+1, right);
ListNode dummy(-1);
ListNode *cur = &dummy;
while(lch && rch)
{
if(lch->val < rch->val)
{
cur->next = lch;
lch = lch->next;
}
else
{
cur->next = rch;
rch = rch->next;
}
cur = cur->next;
}
while(lch)
{
cur->next = lch;
lch = lch->next;
cur = cur->next;
}
while(rch)
{
cur->next = rch;
rch = rch->next;
cur = cur->next;
}
return dummy.next;
}
};
| [
"baoxue.zhao@gmail.com"
] | baoxue.zhao@gmail.com |
aab38f4c4d4230a169f63ebc21f43cbd1b6bf247 | 628dce1a2795189d285317f6105bf7ead5e4e004 | /FPGA_Files/Projects_Testing/resizer/resizer/resizer.srcs/sources_1/bd/Pixel_Control/ip/Pixel_Control_auto_pc_0/sim/Pixel_Control_auto_pc_0_sc.cpp | 7a62eb682d59b9e80974777b8ddd3725045316a8 | [
"BSD-3-Clause"
] | permissive | mfkiwl/ReconHardware | a876a2a672cad386304fd58db52c83b36ebe2c48 | 75a3448eedefa4232fc250dd05aa6d0ca60bbc1a | refs/heads/master | 2023-05-13T18:44:27.532488 | 2021-03-13T04:04:27 | 2021-03-13T04:04:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,020 | cpp | // (c) Copyright 1995-2020 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
#include "Pixel_Control_auto_pc_0_sc.h"
#include "axi_protocol_converter.h"
#include <map>
#include <string>
Pixel_Control_auto_pc_0_sc::Pixel_Control_auto_pc_0_sc(const sc_core::sc_module_name& nm) : sc_core::sc_module(nm), mp_impl(NULL)
{
// configure connectivity manager
xsc::utils::xsc_sim_manager::addInstance("Pixel_Control_auto_pc_0", this);
// initialize module
xsc::common_cpp::properties model_param_props;
model_param_props.addLong("C_M_AXI_PROTOCOL", "2");
model_param_props.addLong("C_S_AXI_PROTOCOL", "1");
model_param_props.addLong("C_IGNORE_ID", "0");
model_param_props.addLong("C_AXI_ID_WIDTH", "12");
model_param_props.addLong("C_AXI_ADDR_WIDTH", "32");
model_param_props.addLong("C_AXI_DATA_WIDTH", "32");
model_param_props.addLong("C_AXI_SUPPORTS_WRITE", "1");
model_param_props.addLong("C_AXI_SUPPORTS_READ", "1");
model_param_props.addLong("C_AXI_SUPPORTS_USER_SIGNALS", "0");
model_param_props.addLong("C_AXI_AWUSER_WIDTH", "1");
model_param_props.addLong("C_AXI_ARUSER_WIDTH", "1");
model_param_props.addLong("C_AXI_WUSER_WIDTH", "1");
model_param_props.addLong("C_AXI_RUSER_WIDTH", "1");
model_param_props.addLong("C_AXI_BUSER_WIDTH", "1");
model_param_props.addLong("C_TRANSLATION_MODE", "2");
model_param_props.addString("C_FAMILY", "zynq");
mp_impl = new axi_protocol_converter("inst", model_param_props);
// initialize sockets
target_rd_socket = mp_impl->target_rd_socket;
target_wr_socket = mp_impl->target_wr_socket;
initiator_rd_socket = mp_impl->initiator_rd_socket;
initiator_wr_socket = mp_impl->initiator_wr_socket;
}
Pixel_Control_auto_pc_0_sc::~Pixel_Control_auto_pc_0_sc()
{
xsc::utils::xsc_sim_manager::clean();
delete mp_impl;
}
| [
"d.cain2740@gmail.com"
] | d.cain2740@gmail.com |
66be6efd7e849f0ccb89c0a78860d65906b68466 | d29e4e39225e2f70c67b9f0e464b5a4d77b7d540 | /3rdparty/indi-mgen/mgenautoguider.h | c4f3f90ce5bcc0f2fde1187e7551d6890969fb90 | [] | no_license | FrankGrossmann/indi | 3b781efb8c0539cacac064902c0c38041930e52d | 765adb1220a7f40dc8f88912415fe839ce26ecc3 | refs/heads/master | 2021-01-22T10:50:55.676311 | 2017-05-25T21:25:18 | 2017-05-25T21:25:18 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,817 | h | /*
INDI 3rd party driver
Lacerta MGen Autoguider INDI driver, implemented with help from
Tommy (teleskopaustria@gmail.com) and Zoltan (mgen@freemail.hu).
Teleskop & Mikroskop Zentrum (www.teleskop.austria.com)
A-1050 WIEN, Schönbrunner Strasse 96
+43 699 1197 0808 (Shop in Wien und Rechnungsanschrift)
A-4020 LINZ, Gärtnerstrasse 16
+43 699 1901 2165 (Shop in Linz)
Lacerta GmbH
UmsatzSt. Id. Nr.: AT U67203126
Firmenbuch Nr.: FN 379484s
Copyright (C) 2017 by TallFurryMan (eric.dejouhanet@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MGENAUTOGUIDER_H
#define MGENAUTOGUIDER_H
/** \file mgenautoguider.h
\brief This is a very simple INDI device for the Lacerta MGen Autoguider.
\author TallFurryMan (eric.dejouhanet@gmail.com)
Summary: this driver attempts to connect to a FTDI device with the VID:PID
of the MGen Autoguider on the USB bus. It tries to understand in which mode
the device is currently, eventually powers it on and switches it to
application mode in order to use its features. It then provides a view on
the remote user interface, and enables the end-user to navigate in that
interface by clicking buttons.
The Lacerta MGen driver communicates through libftdi1. It would be possible
to us the standard VCP driver "ftdi_sio" bundled with the Linux kernel
through a TTY standard device, but some operations such as turning the
device on or resetting would not be available.
In its current implementation, the INDI driver derives from INDI::CCD in
order to forward a view on the remote UI and a way to navigate in that UI.
However, none of the features of a CCD is implemented.
The connection algorithm tries to understand in which state the device is,
and tries to turn it on if it is in low power. The ability to turn the
device on is is especially useful as the default state of the power supplied
autoguider is low power. This feature would not possible with the standard
ftdi_sio driver.
\see 80-LacertaMgen.rules for an example of udev rules unbinding the MGen
device from driver ftdi_sio, leaving it free to communicate with libftdi1
and libusb. The rules detects the serial name "MGS05443" in events from
subsystems "usb" and "tty" to request the kernel to unbind the device from
driver "ftdi_sio".
The PID:VID identifier is harcoded to the default value for the Lacerta
MGen, although it could be entered as a driver property: 0x403:0x6001.
To use the Lacerta MGen in Ekos, connect Ekos to an INDI server executing
the driver. Once connected, Ekos will periodically (default is 0.25fps)
display the remote user interface in the preview panel of the FITS viewer.
You can then navigate using the buttons in the tab "Remote UI". To increase
the responsiveness of the remote UI, move the slider in tab "Remote UI" to
increase the frame rate value. Warning, a frame rate too high may drop the
connection (my tests show that it is the FITS viewer which seems to crack
under pressure, crashing Ekos and KStars). To stop frame updates once you
don't need them anymore (e.g. when everything is configured and guiding is
started), set the frame rate to 0. To improve the communication speed, you
may compress the frames and the expense of computing power on the INDI
server (this is disabled by default by INDI::CCD, but is recommended).
\todo Find a better way to display the remote user interface than a preview
panel from non-functional INDI::CCD :)
\todo Screen recognition, in order to define navigation scenarii providing
additional features (star detection, calibration, guider start/stop, PEC
measurement...)
\todo A proper client in Ekos providing calibration, guider start/stop and
frame fetching.
\todo Support BOOT and APPLICATION mode switch, in order to retrieve
additional versions and power the device off. No feature updating the
firmware is planned (too dangerous).
\todo Support Star Drift measurement function. This provides a measurement
of the periodic error of the mount.
\todo Support Random Displacement function. This allows a sequence of guided
captures to be offset randomly, improving the result of stacking the
captures. This requires a way to control the shutter of the guided CCD. MGen
offers control for open-collector shutter systems such as Canon EOS cameras.
\todo Support External Exposure function.
\todo Support Filesystem features to read logs and statistics files, and to
do housework in the available ~2MB.
*/
#include "indidevapi.h"
#include "indiccd.h"
class MGenAutoguider : public INDI::CCD
{
public:
MGenAutoguider();
virtual ~MGenAutoguider();
public:
static MGenAutoguider & instance();
public:
virtual bool ISNewNumber(char const * dev, char const * name, double values[], char * names[], int n);
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n);
public:
/** \brief Returning the current operational mode of the device.
* \return the current operational mode of the device.
*/
IOMode getOpMode() const;
protected:
/** \internal The device object used to communicate with the MGen.
*/
class MGenDevice * device;
protected:
/** \internal Version information retrieved from the device.
*/
struct version
{
struct timespec timestamp; /*!< The last time this structure was read from the device. */
struct firmware
{
IText text; /*!< Firmware version as read from the device. */
ITextVectorProperty property; /*!< Firmware version INDI property. */
} firmware;
} version;
protected:
struct voltage
{
struct timespec timestamp; /*!< The last time this structure was read from the device. */
struct numbers
{
INumber logic; /*!< Logic supply voltage, [4.8V,5.1V] with DC power, ~4.7V with USB power, stable over 4.5V. */
INumber input; /*!< DC input voltage, must be in [9V,15V] (max DC input 20V). */
INumber reference; /*!< Reference voltage, ~1.23V (more than 10% difference shows internal problem). */
} levels;
INumberVectorProperty property; /*!< Voltage INDI property. */
} voltage;
protected:
struct ui
{
int timer; /*!< The timer counting for the refresh event updating the remote user interface. */
struct timespec timestamp; /*!< The last time this structure was read from the device. */
struct framerate
{
INumber number; /*!< Frame rate value, in frames per second - more frames increase risk of disconnection. */
INumberVectorProperty property; /* Frame rate INDI property. */
} framerate;
struct buttons
{
ISwitch switches[6]; /*!< Button switches for ESC, SET, UP, LEFT, RIGHT and DOWN. */
ISwitchVectorProperty properties[2]; /*!< Button INDI properties, {ESC,SET} and {UP,LEFT,RIGHT,DOWN}. */
} buttons;
} ui;
protected:
struct heartbeat
{
struct timespec timestamp; /*!< The last time this structure was read from the device. */
unsigned int no_ack_count; /*!< Number of times device didn't acknowledge NOP1, used as connection keepalive. */
} heartbeat;
protected:
virtual bool initProperties();
virtual bool updateProperties();
virtual void TimerHit();
protected:
virtual bool Connect();
virtual bool Disconnect();
protected:
virtual const char *getDefaultName();
protected:
/** \internal Sending a NOP1 to the device to check it is still acknowledging.
* This function will be called periodically to check if the device is still alive.
* \return true if command was acknoldeged.
* \return false if command was not acknowledged, and disconnect the device after 5 failures.
*/
bool getHeartbeat();
};
#endif // MGENAUTOGUIDER_H
| [
"eric.dejouhanet@gmail.com"
] | eric.dejouhanet@gmail.com |
04765e18750f02c94f3f87c4e5a532eae5dd4226 | e95c718e8db049cf605ef3c8926de9dc4fc1631f | /10872.cpp | df5e9864e2565c53ddd3ac352ea4fd176ff76318 | [] | no_license | jsh15932/BOJ_Solve | d4aa202a7b6f19fa5cde7e3c4443eb8bc1dfd97f | b32cf323cf447188edef50e750ee37a8e4b8119d | refs/heads/master | 2022-11-23T04:04:00.934426 | 2022-11-17T14:00:01 | 2022-11-17T14:00:01 | 253,563,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int fac(int n) {
if(n == 0) {
return 1;
}
else return n * fac(n - 1);
}
int main() {
int n;
cin >> n;
cout << fac(n);
}
| [
"noreply@github.com"
] | noreply@github.com |
666e6982446098eb4e29fb579200a20b212bbc84 | d3390faaf4a661412b6d173b8964566d97fc81a8 | /addons/ares_compositions/Ares/Military Structures/Bunkers/Observation Bunker.hpp | 81862c318159d7856762b1df2c74f0ecbd29f35a | [
"MIT"
] | permissive | TacticalBaconDevs/TBMod | ce6b6dcdbc887fa642db93ce63433ba14e94f88c | acc54a6014758f2fcff7d305a816b3cb95c4180b | refs/heads/master | 2022-11-03T10:14:12.769187 | 2022-10-28T14:01:56 | 2022-10-28T14:01:56 | 142,904,755 | 11 | 2 | MIT | 2022-10-28T14:01:58 | 2018-07-30T17:05:47 | C++ | UTF-8 | C++ | false | false | 1,378 | hpp | class Object1 {side=8;vehicle="Land_BagBunker_Small_F";rank="";position[]={0.189453,1.06055,-0.00143886};dir=179.087;};
class Object2 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={-1.26758,-3.54688,-0.00243902};dir=0;};
class Object3 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={1.73242,-3.54102,-0.00243902};dir=0;};
class Object4 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={-1.12109,6.92383,-0.00243902};dir=0;};
class Object5 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={1.83398,6.94336,-0.00243902};dir=0;};
class Object6 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={-3.94531,6.08008,-0.00243902};dir=151.663;};
class Object7 {side=8;vehicle="Land_BagFence_Round_F";rank="";position[]={-6.31055,4.46289,-0.00274014};dir=109.179;};
class Object8 {side=8;vehicle="Land_BagFence_Long_F";rank="";position[]={4.61914,6.20703,-0.00243902};dir=204.108;};
class Object9 {side=8;vehicle="Land_BagFence_Round_F";rank="";position[]={6.96484,4.70117,-0.00274014};dir=250.372;};
class Object10 {side=8;vehicle="Land_Razorwire_F";rank="";position[]={-0.986328,12.4375,-0.00143886};dir=0;};
class Object11 {side=8;vehicle="Land_Razorwire_F";rank="";position[]={-5.47852,11.2734,-0.00144124};dir=143.987;};
class Object12 {side=8;vehicle="Land_Razorwire_F";rank="";position[]={9.48438,9.10742,-0.00144124};dir=212.471;}; | [
"noreply@github.com"
] | noreply@github.com |
39f56f3bde7b52daed009bee49d362e782e4d24b | b7d5640a8078e579f61d54f81858cc1dff3fa7ae | /GameClient/src/player/lobbyplayer.cpp | 4eb85b33d2dc0b97b6509612d0d9ed9a3d7560d4 | [] | no_license | gemini14/Typhon | 7497d225aa46abae881e77450466592dc0615060 | fa799896e13cdfaf40f65ff0981e7d98ad80a5f0 | refs/heads/master | 2016-09-06T14:34:11.048290 | 2011-10-22T07:12:33 | 2011-10-22T07:12:33 | 1,990,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include "player/lobbyplayer.h"
#include <cstring>
namespace Typhon
{
LobbyPlayer::LobbyPlayer()
: type(AI), name(L"Bot"), perfScore(0), ready(true), refreshTime(0)
{
memset(&sourceAddr, 0, sizeof sourceAddr);
sourceAddr.sin_family = AF_INET;
}
LobbyPlayer::~LobbyPlayer()
{
}
}
| [
"zwillinge14@gmail.com"
] | zwillinge14@gmail.com |
3ec96fde62547ca22ee542e29d3ce2d51e2a1f35 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /content/browser/frame_host/debug_urls.cc | f66e16a2ebc2c55c3c2e961a7a43dde5a9187d61 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 6,583 | 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 "content/browser/frame_host/debug_urls.h"
#include <vector>
#include "base/command_line.h"
#include "base/debug/asan_invalid_access.h"
#include "base/debug/profiler.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/url_constants.h"
#include "ppapi/buildflags/buildflags.h"
#include "url/gurl.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/ppapi_plugin_process_host.h" // nogncheck
#include "ppapi/proxy/ppapi_messages.h" // nogncheck
#endif
namespace content {
class ScopedAllowWaitForDebugURL {
private:
base::ThreadRestrictions::ScopedAllowWait wait;
};
namespace {
// Define the Asan debug URLs.
const char kAsanCrashDomain[] = "crash";
const char kAsanHeapOverflow[] = "/browser-heap-overflow";
const char kAsanHeapUnderflow[] = "/browser-heap-underflow";
const char kAsanUseAfterFree[] = "/browser-use-after-free";
#if defined(OS_WIN)
const char kAsanCorruptHeapBlock[] = "/browser-corrupt-heap-block";
const char kAsanCorruptHeap[] = "/browser-corrupt-heap";
#endif
void HandlePpapiFlashDebugURL(const GURL& url) {
#if BUILDFLAG(ENABLE_PLUGINS)
bool crash = url == kChromeUIPpapiFlashCrashURL;
std::vector<PpapiPluginProcessHost*> hosts;
PpapiPluginProcessHost::FindByName(
base::UTF8ToUTF16(kFlashPluginName), &hosts);
for (std::vector<PpapiPluginProcessHost*>::iterator iter = hosts.begin();
iter != hosts.end(); ++iter) {
if (crash)
(*iter)->Send(new PpapiMsg_Crash());
else
(*iter)->Send(new PpapiMsg_Hang());
}
#endif
}
bool IsAsanDebugURL(const GURL& url) {
if (!(url.is_valid() && url.SchemeIs(kChromeUIScheme) &&
url.DomainIs(kAsanCrashDomain) &&
url.has_path())) {
return false;
}
if (url.path_piece() == kAsanHeapOverflow ||
url.path_piece() == kAsanHeapUnderflow ||
url.path_piece() == kAsanUseAfterFree) {
return true;
}
#if defined(OS_WIN)
if (url.path_piece() == kAsanCorruptHeapBlock ||
url.path_piece() == kAsanCorruptHeap) {
return true;
}
#endif
return false;
}
bool HandleAsanDebugURL(const GURL& url) {
#if defined(ADDRESS_SANITIZER)
#if defined(OS_WIN)
if (url.path_piece() == kAsanCorruptHeapBlock) {
base::debug::AsanCorruptHeapBlock();
return true;
} else if (url.path_piece() == kAsanCorruptHeap) {
base::debug::AsanCorruptHeap();
return true;
}
#endif // OS_WIN
if (url.path_piece() == kAsanHeapOverflow) {
base::debug::AsanHeapOverflow();
} else if (url.path_piece() == kAsanHeapUnderflow) {
base::debug::AsanHeapUnderflow();
} else if (url.path_piece() == kAsanUseAfterFree) {
base::debug::AsanHeapUseAfterFree();
} else {
return false;
}
#endif
return true;
}
void HangCurrentThread() {
ScopedAllowWaitForDebugURL allow_wait;
base::WaitableEvent(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED)
.Wait();
}
} // namespace
bool HandleDebugURL(const GURL& url, ui::PageTransition transition) {
// Ensure that the user explicitly navigated to this URL, unless
// kEnableGpuBenchmarking is enabled by Telemetry.
bool is_telemetry_navigation =
base::CommandLine::ForCurrentProcess()->HasSwitch(
cc::switches::kEnableGpuBenchmarking) &&
(PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_TYPED));
if (!(transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) &&
!is_telemetry_navigation)
return false;
if (IsAsanDebugURL(url))
return HandleAsanDebugURL(url);
if (url == kChromeUIBrowserCrashURL) {
// Induce an intentional crash in the browser process.
CHECK(false);
return true;
}
if (url == kChromeUIBrowserUIHang) {
HangCurrentThread();
return true;
}
if (url == kChromeUIDelayedBrowserUIHang) {
// Webdriver-safe url to hang the ui thread. Webdriver waits for the onload
// event in javascript which needs a little more time to fire.
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&HangCurrentThread),
base::TimeDelta::FromSeconds(2));
return true;
}
if (url == kChromeUIGpuCleanURL) {
GpuProcessHost::CallOnIO(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
false /* force_create */,
base::Bind([](GpuProcessHost* host) {
if (host)
host->gpu_service()->DestroyAllChannels();
}));
return true;
}
if (url == kChromeUIGpuCrashURL) {
GpuProcessHost::CallOnIO(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
false /* force_create */,
base::Bind([](GpuProcessHost* host) {
if (host)
host->gpu_service()->Crash();
}));
return true;
}
#if defined(OS_ANDROID)
if (url == kChromeUIGpuJavaCrashURL) {
GpuProcessHost::CallOnIO(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
false /* force_create */,
base::Bind([](GpuProcessHost* host) {
if (host)
host->gpu_service()->ThrowJavaException();
}));
return true;
}
#endif
if (url == kChromeUIGpuHangURL) {
GpuProcessHost::CallOnIO(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
false /* force_create */,
base::Bind([](GpuProcessHost* host) {
if (host)
host->gpu_service()->Hang();
}));
return true;
}
if (url == kChromeUIPpapiFlashCrashURL || url == kChromeUIPpapiFlashHangURL) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&HandlePpapiFlashDebugURL, url));
return true;
}
return false;
}
} // namespace content
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
34cd1799f0259fe5f16c8c46bb286d1be78db35f | f8e7ef7df32f2c82894c0a24598ce39eea7ced64 | /mamigoShared/include/RWDecorator.h | 1898ef26eb27ca052f6dbde0b437ba5f40f489f8 | [] | no_license | Pyq2022/ImageSensor-ext | 29fc3877f4cb33e82dd6e19d36edd694a23db7e3 | 318a39a14c5e287374f62561c49cf8fc6b02e64f | refs/heads/master | 2023-03-17T00:42:00.436507 | 2020-08-11T07:59:44 | 2020-08-11T07:59:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | h | /*
* ReaderDecorator.h
*
* Created on: 07-Apr-2010
* Author: akhil
*/
#ifndef RWDECORATOR_H_
#define RWDECORATOR_H_
#include "ReaderWriter.h"
class RWDecorator: public ReaderWriter {
public:
RWDecorator(ReaderWriter *);
virtual ~RWDecorator();
virtual int Read(unsigned char *ptr,int numbytes,int starpos);
virtual int Write(unsigned char *ptr,int numbyte, int starpos);
virtual void Init(void *ptr);
private:
ReaderWriter *m_ReaderWriter;
};
#endif /* RWDECORATOR_H_ */
| [
"23217476+apotnuru@users.noreply.github.com"
] | 23217476+apotnuru@users.noreply.github.com |
d4615c7479d3646b68d4597d527f7a5d3fc247d1 | 7655ad7d6e8464a4e8b51b79ba870e3de40767c2 | /courseWork/courseWork/Parser.cpp | fb5bebe2126e47ea0a5e8caa31d2d186a904a18e | [] | no_license | Persik3D/ProgrammingTechnology | fdd1fac30b07aaffa362df279f82b8db72754132 | de218aa6dbcc30a758f906bc9a217932d5826de5 | refs/heads/master | 2020-05-20T16:44:18.615187 | 2019-05-11T09:37:51 | 2019-05-11T09:37:51 | 185,671,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,111 | cpp | #include "Parser.h"
#include <math.h>
#include <string>
#include <vector>
#include <cmath>
#include <cctype>
#include <cstring>
#include <stdexcept>
using namespace std;
string Parser::parse_token() {
while (isspace(input[n])) ++n;
if (isdigit(input[n])) {
string number;
while (isdigit(input[n]) || input[n] == '.') number.push_back(input[n++]);
return number;
}
if (isalpha(input[n])) {
string addr;
while (isalpha(input[n]) || isdigit(input[n])) addr.push_back(input[n++]);
return addr;
}
char tokens[] = { '+', '-', '*', '/' };
for (auto& t : tokens) {
if (input[n] == t) {
n++;
return string(1, t);
}
}
return "";
}
void Parser::parseA1(string addr, int& I, int& J)
{
string num, str;
for (string::size_type i = 0; i < addr.size(); ++i) {
if (isdigit(addr[i]))
num.push_back(addr[i]);
if (isalpha(addr[i]))
str.push_back(addr[i]);
}
int result = 0;
for (int i = str.size() - 1; i >= 0; i--) {
result += (str[i] - 64) * pow(26, str.size() - i - 1);
}
I = result - 1;
J = stoi(num) - 1;
}
Cell* Parser::find(string addr)
{
int i, j;
parseA1(addr, i, j);
return &(*table)[i][j];
}
Cell* Parser::parse_simple_expression() {
auto token = parse_token();
if (token.empty()) throw runtime_error("Invalid input");
if (isdigit(token[0]))
return new Cell(stoi(token));
if (isalpha(token[0]))
return find(token);
n--;
return new Cell(0);
}
int get_priority(const string& binary_op) {
if (binary_op == "+") return 1;
if (binary_op == "-") return 1;
if (binary_op == "*") return 2;
if (binary_op == "/") return 2;
return 0;
}
Cell* Parser::parse_binary_expression(int min_priority) {
auto left = parse_simple_expression();
for (;;) {
auto op = parse_token();
auto priority = get_priority(op);
if (priority <= min_priority) {
n -= op.size();
return left;
}
auto right = parse_binary_expression(priority);
left = new Cell(op[0], left, right);
}
}
Cell& Parser::parse(const string in) {
input = in;
n = 0;
if (input[n] != '=') throw runtime_error("Invalid input");
++n;
return *parse_binary_expression(0);
} | [
"mikov.e.p@gmail.com"
] | mikov.e.p@gmail.com |
df757bc57b2e00b163a5b721347642a009e08f8a | d0d5fac9b0635f75dc211ceb68d16e9b4399bb11 | /src/hiphop-php/hphp/runtime/ext/ext_reflection.ext_hhvm.cpp | a3d347cf8128743a6d9562a162e2641a353e3f05 | [
"PHP-3.01",
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | NeoTim/hiphop-php-docker | 2ebf60db2c08bb93aef94ec9fab4d548f8f09bf4 | 51ae1a35e387c05f936cf59ed9d23965554d4b87 | refs/heads/master | 2020-04-16T09:17:51.394473 | 2017-12-03T18:45:36 | 2017-12-03T18:45:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,459 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <runtime/ext_hhvm/ext_hhvm.h>
#include <runtime/base/builtin_functions.h>
#include <runtime/base/array/array_init.h>
#include <runtime/ext/ext.h>
#include <runtime/vm/class.h>
#include <runtime/vm/runtime.h>
#include <exception>
namespace HPHP {
/*
HPHP::Array HPHP::f_hphp_get_extension_info(HPHP::String const&)
_ZN4HPHP25f_hphp_get_extension_infoERKNS_6StringE
(return value) => rax
_rv => rdi
name => rsi
*/
Value* fh_hphp_get_extension_info(Value* _rv, Value* name) asm("_ZN4HPHP25f_hphp_get_extension_infoERKNS_6StringE");
TypedValue * fg1_hphp_get_extension_info(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_get_extension_info(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfArray;
tvCastToStringInPlace(args-0);
fh_hphp_get_extension_info((Value*)(rv), (Value*)(args-0));
if (rv->m_data.num == 0LL) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_get_extension_info(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if (IS_STRING_TYPE((args-0)->m_type)) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_hphp_get_extension_info((Value*)(&(rv)), (Value*)(args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_get_extension_info(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_get_extension_info", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Array HPHP::f_hphp_get_method_info(HPHP::Variant const&, HPHP::Variant const&)
_ZN4HPHP22f_hphp_get_method_infoERKNS_7VariantES2_
(return value) => rax
_rv => rdi
cname => rsi
name => rdx
*/
Value* fh_hphp_get_method_info(Value* _rv, TypedValue* cname, TypedValue* name) asm("_ZN4HPHP22f_hphp_get_method_infoERKNS_7VariantES2_");
TypedValue* fg_hphp_get_method_info(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_hphp_get_method_info((Value*)(&(rv)), (args-0), (args-1));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
throw_wrong_arguments_nr("hphp_get_method_info", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Array HPHP::f_hphp_get_closure_info(HPHP::Variant const&)
_ZN4HPHP23f_hphp_get_closure_infoERKNS_7VariantE
(return value) => rax
_rv => rdi
closure => rsi
*/
Value* fh_hphp_get_closure_info(Value* _rv, TypedValue* closure) asm("_ZN4HPHP23f_hphp_get_closure_infoERKNS_7VariantE");
TypedValue* fg_hphp_get_closure_info(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_hphp_get_closure_info((Value*)(&(rv)), (args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
throw_wrong_arguments_nr("hphp_get_closure_info", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_hphp_get_class_constant(HPHP::Variant const&, HPHP::Variant const&)
_ZN4HPHP25f_hphp_get_class_constantERKNS_7VariantES2_
(return value) => rax
_rv => rdi
cls => rsi
name => rdx
*/
TypedValue* fh_hphp_get_class_constant(TypedValue* _rv, TypedValue* cls, TypedValue* name) asm("_ZN4HPHP25f_hphp_get_class_constantERKNS_7VariantES2_");
TypedValue* fg_hphp_get_class_constant(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
fh_hphp_get_class_constant((&(rv)), (args-0), (args-1));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
throw_wrong_arguments_nr("hphp_get_class_constant", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Array HPHP::f_hphp_get_class_info(HPHP::Variant const&)
_ZN4HPHP21f_hphp_get_class_infoERKNS_7VariantE
(return value) => rax
_rv => rdi
name => rsi
*/
Value* fh_hphp_get_class_info(Value* _rv, TypedValue* name) asm("_ZN4HPHP21f_hphp_get_class_infoERKNS_7VariantE");
TypedValue* fg_hphp_get_class_info(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_hphp_get_class_info((Value*)(&(rv)), (args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
throw_wrong_arguments_nr("hphp_get_class_info", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Array HPHP::f_hphp_get_function_info(HPHP::String const&)
_ZN4HPHP24f_hphp_get_function_infoERKNS_6StringE
(return value) => rax
_rv => rdi
name => rsi
*/
Value* fh_hphp_get_function_info(Value* _rv, Value* name) asm("_ZN4HPHP24f_hphp_get_function_infoERKNS_6StringE");
TypedValue * fg1_hphp_get_function_info(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_get_function_info(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfArray;
tvCastToStringInPlace(args-0);
fh_hphp_get_function_info((Value*)(rv), (Value*)(args-0));
if (rv->m_data.num == 0LL) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_get_function_info(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if (IS_STRING_TYPE((args-0)->m_type)) {
rv._count = 0;
rv.m_type = KindOfArray;
fh_hphp_get_function_info((Value*)(&(rv)), (Value*)(args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_get_function_info(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_get_function_info", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_hphp_invoke(HPHP::String const&, HPHP::Array const&)
_ZN4HPHP13f_hphp_invokeERKNS_6StringERKNS_5ArrayE
(return value) => rax
_rv => rdi
name => rsi
params => rdx
*/
TypedValue* fh_hphp_invoke(TypedValue* _rv, Value* name, Value* params) asm("_ZN4HPHP13f_hphp_invokeERKNS_6StringERKNS_5ArrayE");
TypedValue * fg1_hphp_invoke(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_invoke(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if ((args-1)->m_type != KindOfArray) {
tvCastToArrayInPlace(args-1);
}
if (!IS_STRING_TYPE((args-0)->m_type)) {
tvCastToStringInPlace(args-0);
}
fh_hphp_invoke((rv), (Value*)(args-0), (Value*)(args-1));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_invoke(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfArray && IS_STRING_TYPE((args-0)->m_type)) {
fh_hphp_invoke((&(rv)), (Value*)(args-0), (Value*)(args-1));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_invoke(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_invoke", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_hphp_invoke_method(HPHP::Variant const&, HPHP::String const&, HPHP::String const&, HPHP::Array const&)
_ZN4HPHP20f_hphp_invoke_methodERKNS_7VariantERKNS_6StringES5_RKNS_5ArrayE
(return value) => rax
_rv => rdi
obj => rsi
cls => rdx
name => rcx
params => r8
*/
TypedValue* fh_hphp_invoke_method(TypedValue* _rv, TypedValue* obj, Value* cls, Value* name, Value* params) asm("_ZN4HPHP20f_hphp_invoke_methodERKNS_7VariantERKNS_6StringES5_RKNS_5ArrayE");
TypedValue * fg1_hphp_invoke_method(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_invoke_method(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if ((args-3)->m_type != KindOfArray) {
tvCastToArrayInPlace(args-3);
}
if (!IS_STRING_TYPE((args-2)->m_type)) {
tvCastToStringInPlace(args-2);
}
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
fh_hphp_invoke_method((rv), (args-0), (Value*)(args-1), (Value*)(args-2), (Value*)(args-3));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_invoke_method(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 4LL) {
if ((args-3)->m_type == KindOfArray && IS_STRING_TYPE((args-2)->m_type) && IS_STRING_TYPE((args-1)->m_type)) {
fh_hphp_invoke_method((&(rv)), (args-0), (Value*)(args-1), (Value*)(args-2), (Value*)(args-3));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_invoke_method(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_invoke_method", count, 4, 4, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_hphp_instanceof(HPHP::Object const&, HPHP::String const&)
_ZN4HPHP17f_hphp_instanceofERKNS_6ObjectERKNS_6StringE
(return value) => rax
obj => rdi
name => rsi
*/
bool fh_hphp_instanceof(Value* obj, Value* name) asm("_ZN4HPHP17f_hphp_instanceofERKNS_6ObjectERKNS_6StringE");
TypedValue * fg1_hphp_instanceof(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_instanceof(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfBoolean;
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
rv->m_data.num = (fh_hphp_instanceof((Value*)(args-0), (Value*)(args-1))) ? 1LL : 0LL;
return rv;
}
TypedValue* fg_hphp_instanceof(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if (IS_STRING_TYPE((args-1)->m_type) && (args-0)->m_type == KindOfObject) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_hphp_instanceof((Value*)(args-0), (Value*)(args-1))) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_instanceof(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_instanceof", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Object HPHP::f_hphp_create_object(HPHP::String const&, HPHP::Array const&)
_ZN4HPHP20f_hphp_create_objectERKNS_6StringERKNS_5ArrayE
(return value) => rax
_rv => rdi
name => rsi
params => rdx
*/
Value* fh_hphp_create_object(Value* _rv, Value* name, Value* params) asm("_ZN4HPHP20f_hphp_create_objectERKNS_6StringERKNS_5ArrayE");
TypedValue * fg1_hphp_create_object(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_create_object(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfObject;
if ((args-1)->m_type != KindOfArray) {
tvCastToArrayInPlace(args-1);
}
if (!IS_STRING_TYPE((args-0)->m_type)) {
tvCastToStringInPlace(args-0);
}
fh_hphp_create_object((Value*)(rv), (Value*)(args-0), (Value*)(args-1));
if (rv->m_data.num == 0LL)rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_create_object(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if ((args-1)->m_type == KindOfArray && IS_STRING_TYPE((args-0)->m_type)) {
rv._count = 0;
rv.m_type = KindOfObject;
fh_hphp_create_object((Value*)(&(rv)), (Value*)(args-0), (Value*)(args-1));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_create_object(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_create_object", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_hphp_get_property(HPHP::Object const&, HPHP::String const&, HPHP::String const&)
_ZN4HPHP19f_hphp_get_propertyERKNS_6ObjectERKNS_6StringES5_
(return value) => rax
_rv => rdi
obj => rsi
cls => rdx
prop => rcx
*/
TypedValue* fh_hphp_get_property(TypedValue* _rv, Value* obj, Value* cls, Value* prop) asm("_ZN4HPHP19f_hphp_get_propertyERKNS_6ObjectERKNS_6StringES5_");
TypedValue * fg1_hphp_get_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_get_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (!IS_STRING_TYPE((args-2)->m_type)) {
tvCastToStringInPlace(args-2);
}
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
fh_hphp_get_property((rv), (Value*)(args-0), (Value*)(args-1), (Value*)(args-2));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_get_property(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 3LL) {
if (IS_STRING_TYPE((args-2)->m_type) && IS_STRING_TYPE((args-1)->m_type) && (args-0)->m_type == KindOfObject) {
fh_hphp_get_property((&(rv)), (Value*)(args-0), (Value*)(args-1), (Value*)(args-2));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_get_property(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_get_property", count, 3, 3, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
void HPHP::f_hphp_set_property(HPHP::Object const&, HPHP::String const&, HPHP::String const&, HPHP::Variant const&)
_ZN4HPHP19f_hphp_set_propertyERKNS_6ObjectERKNS_6StringES5_RKNS_7VariantE
obj => rdi
cls => rsi
prop => rdx
value => rcx
*/
void fh_hphp_set_property(Value* obj, Value* cls, Value* prop, TypedValue* value) asm("_ZN4HPHP19f_hphp_set_propertyERKNS_6ObjectERKNS_6StringES5_RKNS_7VariantE");
TypedValue * fg1_hphp_set_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_set_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->m_data.num = 0LL;
rv->_count = 0;
rv->m_type = KindOfNull;
if (!IS_STRING_TYPE((args-2)->m_type)) {
tvCastToStringInPlace(args-2);
}
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if ((args-0)->m_type != KindOfObject) {
tvCastToObjectInPlace(args-0);
}
fh_hphp_set_property((Value*)(args-0), (Value*)(args-1), (Value*)(args-2), (args-3));
return rv;
}
TypedValue* fg_hphp_set_property(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 4LL) {
if (IS_STRING_TYPE((args-2)->m_type) && IS_STRING_TYPE((args-1)->m_type) && (args-0)->m_type == KindOfObject) {
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
fh_hphp_set_property((Value*)(args-0), (Value*)(args-1), (Value*)(args-2), (args-3));
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_set_property(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_set_property", count, 4, 4, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 4);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::Variant HPHP::f_hphp_get_static_property(HPHP::String const&, HPHP::String const&)
_ZN4HPHP26f_hphp_get_static_propertyERKNS_6StringES2_
(return value) => rax
_rv => rdi
cls => rsi
prop => rdx
*/
TypedValue* fh_hphp_get_static_property(TypedValue* _rv, Value* cls, Value* prop) asm("_ZN4HPHP26f_hphp_get_static_propertyERKNS_6StringES2_");
TypedValue * fg1_hphp_get_static_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_get_static_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if (!IS_STRING_TYPE((args-0)->m_type)) {
tvCastToStringInPlace(args-0);
}
fh_hphp_get_static_property((rv), (Value*)(args-0), (Value*)(args-1));
if (rv->m_type == KindOfUninit) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_get_static_property(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 2LL) {
if (IS_STRING_TYPE((args-1)->m_type) && IS_STRING_TYPE((args-0)->m_type)) {
fh_hphp_get_static_property((&(rv)), (Value*)(args-0), (Value*)(args-1));
if (rv.m_type == KindOfUninit) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_get_static_property(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_get_static_property", count, 2, 2, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 2);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
void HPHP::f_hphp_set_static_property(HPHP::String const&, HPHP::String const&, HPHP::Variant const&)
_ZN4HPHP26f_hphp_set_static_propertyERKNS_6StringES2_RKNS_7VariantE
cls => rdi
prop => rsi
value => rdx
*/
void fh_hphp_set_static_property(Value* cls, Value* prop, TypedValue* value) asm("_ZN4HPHP26f_hphp_set_static_propertyERKNS_6StringES2_RKNS_7VariantE");
TypedValue * fg1_hphp_set_static_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_set_static_property(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->m_data.num = 0LL;
rv->_count = 0;
rv->m_type = KindOfNull;
if (!IS_STRING_TYPE((args-1)->m_type)) {
tvCastToStringInPlace(args-1);
}
if (!IS_STRING_TYPE((args-0)->m_type)) {
tvCastToStringInPlace(args-0);
}
fh_hphp_set_static_property((Value*)(args-0), (Value*)(args-1), (args-2));
return rv;
}
TypedValue* fg_hphp_set_static_property(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 3LL) {
if (IS_STRING_TYPE((args-1)->m_type) && IS_STRING_TYPE((args-0)->m_type)) {
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
fh_hphp_set_static_property((Value*)(args-0), (Value*)(args-1), (args-2));
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_set_static_property(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_set_static_property", count, 3, 3, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 3);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
HPHP::String HPHP::f_hphp_get_original_class_name(HPHP::String const&)
_ZN4HPHP30f_hphp_get_original_class_nameERKNS_6StringE
(return value) => rax
_rv => rdi
name => rsi
*/
Value* fh_hphp_get_original_class_name(Value* _rv, Value* name) asm("_ZN4HPHP30f_hphp_get_original_class_nameERKNS_6StringE");
TypedValue * fg1_hphp_get_original_class_name(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) __attribute__((noinline,cold));
TypedValue * fg1_hphp_get_original_class_name(TypedValue* rv, HPHP::VM::ActRec* ar, int64_t count) {
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
rv->_count = 0;
rv->m_type = KindOfString;
tvCastToStringInPlace(args-0);
fh_hphp_get_original_class_name((Value*)(rv), (Value*)(args-0));
if (rv->m_data.num == 0LL) rv->m_type = KindOfNull;
return rv;
}
TypedValue* fg_hphp_get_original_class_name(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 1LL) {
if (IS_STRING_TYPE((args-0)->m_type)) {
rv._count = 0;
rv.m_type = KindOfString;
fh_hphp_get_original_class_name((Value*)(&(rv)), (Value*)(args-0));
if (rv.m_data.num == 0LL) rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
fg1_hphp_get_original_class_name(&rv, ar, count);
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
}
} else {
throw_wrong_arguments_nr("hphp_get_original_class_name", count, 1, 1, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 1);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
/*
bool HPHP::f_hphp_scalar_typehints_enabled()
_ZN4HPHP31f_hphp_scalar_typehints_enabledEv
(return value) => rax
*/
bool fh_hphp_scalar_typehints_enabled() asm("_ZN4HPHP31f_hphp_scalar_typehints_enabledEv");
TypedValue* fg_hphp_scalar_typehints_enabled(HPHP::VM::ActRec *ar) {
TypedValue rv;
int64_t count = ar->numArgs();
TypedValue* args UNUSED = ((TypedValue*)ar) - 1;
if (count == 0LL) {
rv._count = 0;
rv.m_type = KindOfBoolean;
rv.m_data.num = (fh_hphp_scalar_typehints_enabled()) ? 1LL : 0LL;
frame_free_locals_no_this_inl(ar, 0);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
} else {
throw_toomany_arguments_nr("hphp_scalar_typehints_enabled", 0, 1);
}
rv.m_data.num = 0LL;
rv._count = 0;
rv.m_type = KindOfNull;
frame_free_locals_no_this_inl(ar, 0);
memcpy(&ar->m_r, &rv, sizeof(TypedValue));
return &ar->m_r;
return &ar->m_r;
}
} // !HPHP
| [
"mikesjett@gmail.com"
] | mikesjett@gmail.com |
45dabe91c423b7866910fd031b48711574abf8c1 | 7b498c2b4a2b8b95f3cc28a26de78df09ad6c001 | /NewUser/NewUser.h | 587aacf40b9c7a34c636fa83d695a83b7719f50f | [] | no_license | luispaulot/tp2_pac | ede27365f01af0b6779f69ab98e2c8ffb0807808 | 6804ff7fa038b52a23b5e1916bd0a40b03557ba0 | refs/heads/master | 2016-09-05T17:02:59.379153 | 2015-06-10T02:50:53 | 2015-06-10T02:50:53 | 35,701,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,566 | h | ///-----------------------------------------------------------------
///
/// @file NewUser.h
/// @author LuisPaulo
/// Created: 07/06/2015 17:10:56
/// @section DESCRIPTION
/// NewUser class declaration
///
///------------------------------------------------------------------
#ifndef __NEWUSER_H__
#define __NEWUSER_H__
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/frame.h>
#else
#include <wx/wxprec.h>
#endif
//Do not add custom headers between
//Header Include Start and Header Include End.
//wxDev-C++ designer will remove them. Add custom headers after the block.
////Header Include Start
#include <wx/button.h>
#include <wx/textctrl.h>
#include <wx/stattext.h>
////Header Include End
////Dialog Style Start
#undef NewUser_STYLE
#define NewUser_STYLE wxCAPTION | wxSYSTEM_MENU | wxMINIMIZE_BOX | wxCLOSE_BOX
////Dialog Style End
class NewUser : public wxFrame
{
private:
DECLARE_EVENT_TABLE();
public:
NewUser(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("New User"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = NewUser_STYLE);
virtual ~NewUser();
void NewUserActivate(wxActivateEvent& event);
void WxEdit2Updated(wxCommandEvent& event);
void WxButton1Click(wxCommandEvent& event);
void NewUserActivate0(wxActivateEvent& event);
private:
//Do not add custom control declarations between
//GUI Control Declaration Start and GUI Control Declaration End.
//wxDev-C++ will remove them. Add custom code after the block.
////GUI Control Declaration Start
wxButton *WxButton1;
wxTextCtrl *WxEdit3;
wxTextCtrl *WxEdit2;
wxTextCtrl *WxEdit1;
wxStaticText *WxStaticText3;
wxStaticText *WxStaticText2;
wxStaticText *WxStaticText1;
////GUI Control Declaration End
private:
//Note: if you receive any error with these enum IDs, then you need to
//change your old form code that are based on the #define control IDs.
//#defines may replace a numeric value for the enum names.
//Try copy and pasting the below block in your old form header files.
enum
{
////GUI Enum Control ID Start
ID_WXBUTTON1 = 1007,
ID_WXEDIT3 = 1006,
ID_WXEDIT2 = 1005,
ID_WXEDIT1 = 1004,
ID_WXSTATICTEXT3 = 1003,
ID_WXSTATICTEXT2 = 1002,
ID_WXSTATICTEXT1 = 1001,
////GUI Enum Control ID End
ID_DUMMY_VALUE_ //don't remove this value unless you have other enum values
};
private:
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
};
#endif
| [
"luispaulo1011@gmail.com"
] | luispaulo1011@gmail.com |
c0dc990e9244b32839fa29b6333a4613566991a0 | 59563b85c7685596eb40fa351408d9e61f0acbbd | /src/kern/utf8.cpp | afebd6fb58c599fe4ec96837b54b0eefe7eb6cf1 | [] | no_license | Doloops/Xemeiah | 94c3a32a85a3fb3246da112e74b768b6bd298190 | d497cf9fce275943501bdf01f825edc5f3181bbd | refs/heads/master | 2020-12-24T18:03:57.183527 | 2014-12-01T14:13:27 | 2014-12-01T14:13:27 | 26,857,757 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | /*
* utf8.cpp
*
* Created on: 11 nov. 2009
* Author: francois
*/
#include <Xemeiah/kern/utf8.h>
#include <Xemeiah/dom/string.h>
#include <Xemeiah/auto-inline.hpp>
namespace Xem
{
String iso8859ToUtf8 ( const unsigned char* str, int size )
{
int buffsz = 32;
int buffit = 0;
unsigned char* buff = (unsigned char*) malloc ( buffsz );
buff[0] = '\0';
for ( int i = 0 ; i < size && str[i] ; i++ )
{
int d = str[i];
while ( buffit + 8 >= buffsz )
{
buffsz *= 2;
buff = (unsigned char*) realloc(buff,buffsz);
}
int res = utf8CodeToChar(d,&(buff[buffit]),8);
buffit += res;
}
return stringFromAllocedStr((char*)buff);
}
};
| [
"francois.barre@arondor.com"
] | francois.barre@arondor.com |
b9e77821acbb51e9d84eeb45eccdbd32f7b25979 | bb6ebff7a7f6140903d37905c350954ff6599091 | /chromeos/attestation/mock_attestation_flow.cc | b6eda5b3ab3f0da5343b4178e619ee3c0e0a2ada | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 1,646 | 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 "chromeos/attestation/mock_attestation_flow.h"
#include "base/memory/scoped_ptr.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::_;
using testing::DefaultValue;
using testing::Invoke;
namespace chromeos {
namespace attestation {
FakeServerProxy::FakeServerProxy() : result_(true) {}
FakeServerProxy::~FakeServerProxy() {}
void FakeServerProxy::SendEnrollRequest(const std::string& request,
const DataCallback& callback) {
callback.Run(result_, request + "_response");
}
void FakeServerProxy::SendCertificateRequest(const std::string& request,
const DataCallback& callback) {
callback.Run(result_, request + "_response");
}
MockServerProxy::MockServerProxy() {
DefaultValue<PrivacyCAType>::Set(DEFAULT_PCA);
}
MockServerProxy::~MockServerProxy() {}
void MockServerProxy::DeferToFake(bool success) {
fake_.set_result(success);
ON_CALL(*this, SendEnrollRequest(_, _))
.WillByDefault(Invoke(&fake_, &FakeServerProxy::SendEnrollRequest));
ON_CALL(*this, SendCertificateRequest(_, _))
.WillByDefault(Invoke(&fake_, &FakeServerProxy::SendCertificateRequest));
}
MockObserver::MockObserver() {}
MockObserver::~MockObserver() {}
MockAttestationFlow::MockAttestationFlow()
: AttestationFlow(NULL, NULL, scoped_ptr<ServerProxy>()) {}
MockAttestationFlow::~MockAttestationFlow() {}
} // namespace attestation
} // namespace chromeos
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
5ff1e0dd1295cf18ebfcc7fc353bb2ea260dced3 | a83ff33c6dd8f9b6646d43ea24024eed84a7d374 | /cmp_compressonatorlib/brotlig/BrotligCompute.cpp | 5af5db31e53e878577bf97210dfcf63b6ad89718 | [] | permissive | kopaka1822/Compressonator | 1f50391b665a7cff097ad87172a8a864c4ad623d | 0bea29d5ab01c688c8408edf50a8f13dfe7a915b | refs/heads/master | 2023-07-20T05:59:21.231992 | 2023-07-10T21:14:48 | 2023-07-10T21:14:48 | 215,336,862 | 0 | 0 | MIT | 2021-11-21T11:56:25 | 2019-10-15T15:46:36 | C++ | UTF-8 | C++ | false | false | 23,335 | cpp | //===============================================================================
// Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
//===============================================================================
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
// File Name: BrotligCompute.cpp
//
//////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <d3d12.h>
#include <D3Dcompiler.h>
#include <DirectXMath.h>
#include <dxcapi.h>
#include <stdexcept>
#include <iostream>
#include "BrotligCompute.h"
#include "DataStream.h"
using namespace BrotliG;
template<int N, typename T>
static inline T align(T a)
{
return (a + T(N) - 1) & ~(N - 1);
}
inline std::string HrToString(HRESULT hr)
{
char s_str[64] = {};
sprintf_s(s_str, "HRESULT of 0x%08X", static_cast<UINT>(hr));
return std::string(s_str);
}
class HrException : public std::runtime_error
{
public:
HrException(HRESULT hr) : std::runtime_error(HrToString(hr)), m_hr(hr) {}
HRESULT Error() const { return m_hr; }
private:
const HRESULT m_hr;
};
#define SAFE_RELEASE(p) if (p) (p)->Release()
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
throw HrException(hr);
}
}
// Assign a name to the object to aid with debugging.
#if defined(_DEBUG) || defined(DBG)
inline void SetName(ID3D12Object* pObject, LPCWSTR name)
{
pObject->SetName(name);
}
inline void SetNameIndexed(ID3D12Object* pObject, LPCWSTR name, UINT index)
{
WCHAR fullName[50];
if (swprintf_s(fullName, L"%s[%u]", name, index) > 0)
{
pObject->SetName(fullName);
}
}
#else
inline void SetName(ID3D12Object*, LPCWSTR)
{
}
inline void SetNameIndexed(ID3D12Object*, LPCWSTR, UINT)
{
}
#endif
// Naming helper for ComPtr<T>.
// Assigns the name of the variable as the name of the object.
// The indexed variant will include the index in the name of the object.
#define NAME_D3D12_OBJECT(x) SetName((x).Get(), L#x)
#define NAME_D3D12_OBJECT_INDEXED(x, n) SetNameIndexed((x)[n].Get(), L#x, n)
class PageStream
{
public:
static constexpr uint32_t sMaxTiles = (1 << 10) - 1;
static constexpr uint32_t sBrotligId = BROTLIG_STREAM_ID;
#pragma pack(push, 1)
struct Header
{
uint8_t id;
uint8_t magic;
uint16_t startTile;
uint32_t maxReadSizeIdx : 2;
uint32_t tileSizeIdx : 2;
uint32_t numTiles : 10;
uint32_t lastTileSize : 18;
inline bool IsValid() const
{
return id == (magic ^ 0xff);
}
inline size_t GetUncompressedSize() const
{
return numTiles * GetTileSize() -
(lastTileSize == 0 ? 0 : GetTileSize() - lastTileSize);
}
inline size_t GetTileSize() const
{
return BROTLIG_MIN_PAGE_SIZE << tileSizeIdx;
}
inline size_t GetMaxReadSize() const
{
return BROTLIG_MIN_MAX_READ_SIZE << maxReadSizeIdx;
}
};
#pragma pack(pop)
static_assert(sizeof(Header) == 8, "Tile stream header size overrun!");
};
// Helper function for acquiring the first available hardware adapter that supports Direct3D 12.
// If no such adapter can be found, *ppAdapter will be set to nullptr.
_Use_decl_annotations_
void BrotligCompute::GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter)
{
ComPtr<IDXGIAdapter1> adapter;
*ppAdapter = nullptr;
for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE || desc.VendorId == 0x8086 /* Intel */)
{
// Don't select the Basic Render Driver adapter.
// If you want a software adapter, pass in "/warp" on the command line.
continue;
}
// Check to see if the adapter supports Direct3D 12, but don't create the
// actual device yet.
if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, _uuidof(ID3D12Device), nullptr)))
{
wprintf(L"\nUsing: %s\n", desc.Description);
break;
}
}
*ppAdapter = adapter.Detach();
}
bool BrotligCompute::Setup(uint32_t maxStreamsPerLaunch, uint32_t launchSize)
{
if (!m_device && !InitDevice())
return false;
maxStreamsPerLaunch = std::min<uint32_t>(maxStreamsPerLaunch, BROTLIG_GPUD_DEFAULT_MAX_STREAMS_PER_LAUNCH);
if (!m_initialized || m_maxStreamsPerLaunch != maxStreamsPerLaunch ||
m_launchSize != launchSize)
{
m_maxStreamsPerLaunch = maxStreamsPerLaunch;
m_launchSize = launchSize;
InitResources();
}
m_initialized = true;
return true;
}
bool BrotligCompute::InitDevice()
{
UINT dxgiFactoryFlags = 0;
#if defined(_DEBUG)
// Enable the debug layer (requires the Graphics Tools "optional feature").
// NOTE: Enabling the debug layer after device creation will invalidate the active device.
{
ComPtr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
{
debugController->EnableDebugLayer();
// Enable additional debug layers.
dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
}
}
#endif
ComPtr<IDXGIFactory4> factory;
ThrowIfFailed(CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&factory)));
if (m_useWarpDevice)
{
ComPtr<IDXGIAdapter> warpAdapter;
ThrowIfFailed(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));
ThrowIfFailed(D3D12CreateDevice(
warpAdapter.Get(),
D3D_FEATURE_LEVEL_12_0,
IID_PPV_ARGS(&m_device)
));
DXGI_ADAPTER_DESC desc;
warpAdapter->GetDesc(&desc);
wprintf(L"\nUsing: %s\n", desc.Description);
}
else
{
ComPtr<IDXGIAdapter1> hardwareAdapter;
GetHardwareAdapter(factory.Get(), &hardwareAdapter);
ThrowIfFailed(D3D12CreateDevice(
hardwareAdapter.Get(),
D3D_FEATURE_LEVEL_12_0,
IID_PPV_ARGS(&m_device)
));
}
D3D12_FEATURE_DATA_SHADER_MODEL model{ D3D_SHADER_MODEL_6_5 };
ThrowIfFailed(m_device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)));
if (model.HighestShaderModel < D3D_SHADER_MODEL_6_0)
{
printf("Fatal: Device does not support Shader Model 6.0\n");
m_device.Reset();
return false;
}
return true;
}
void BrotligCompute::InitResources()
{
// Queue
{
D3D12_COMMAND_QUEUE_DESC queueDesc = { D3D12_COMMAND_LIST_TYPE_COMPUTE, 0, D3D12_COMMAND_QUEUE_FLAG_NONE };
ThrowIfFailed(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue)));
ThrowIfFailed(m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&m_commandAllocator)));
ThrowIfFailed(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE,
m_commandAllocator.Get(), nullptr, IID_PPV_ARGS(&m_commandList)));
ThrowIfFailed(m_device->CreateFence(0, D3D12_FENCE_FLAG_SHARED, IID_PPV_ARGS(&m_fence)));
m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
}
// Pipeline
{
// Compute root signature.
{
CD3DX12_ROOT_PARAMETER1 rootParameters[RootParametersCount];
rootParameters[RootSRVInput].InitAsShaderResourceView(0);
rootParameters[RootUAVControl].InitAsUnorderedAccessView(0);
rootParameters[RootUAVOutput].InitAsUnorderedAccessView(1);
CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC computeRootSignatureDesc;
computeRootSignatureDesc.Init_1_1(_countof(rootParameters), rootParameters, 0, nullptr);
ComPtr<ID3DBlob> signature;
ComPtr<ID3DBlob> error;
ThrowIfFailed(D3DX12SerializeVersionedRootSignature(&computeRootSignatureDesc,
D3D_ROOT_SIGNATURE_VERSION_1_1, &signature, &error));
if (error)
printf("Root signature creation failed with: %s\n", (LPCSTR)error->GetBufferPointer());
ThrowIfFailed(m_device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
IID_PPV_ARGS(&m_rootSignature)));
NAME_D3D12_OBJECT(m_rootSignature);
}
ComPtr<IDxcLibrary> library;
HRESULT hr;
ThrowIfFailed(DxcCreateInstance(CLSID_DxcLibrary, IID_PPV_ARGS(&library)));
ComPtr<IDxcCompiler> compiler;
ThrowIfFailed(DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler)));
ComPtr<IDxcIncludeHandler> includeHandler;
library->CreateIncludeHandler(&includeHandler);
uint32_t codePage = CP_UTF8;
ComPtr<IDxcBlobEncoding> sourceBlob;
hr = library->CreateBlobFromFile(p_sShaderName, &codePage, &sourceBlob);
if (FAILED(hr))
{
hr = library->CreateBlobFromFile(p_sAltShaderName, &codePage, &sourceBlob);
if (FAILED(hr))
{
wprintf(L"BrotligCompute.hlsl not found in the current directory. Also tried %s", p_sAltShaderName);
exit(-1);
}
}
// Check supported shader model and SIMD width and configure the decompressor kernel accordingly
D3D12_FEATURE_DATA_SHADER_MODEL model{ D3D_SHADER_MODEL_6_5 };
ThrowIfFailed(m_device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)));
D3D12_FEATURE_DATA_D3D12_OPTIONS1 options1;
ThrowIfFailed(m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options1, sizeof(options1)));
D3D12_FEATURE_DATA_D3D12_OPTIONS4 options4;
ThrowIfFailed(m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS4, &options4, sizeof(options4)));
printf("SIMD width of the machine: %d\n", options1.WaveLaneCountMin);
printf("Maximum supported shader model: %d.%d\n", model.HighestShaderModel >> 4, model.HighestShaderModel & 15);
printf("Wave intrinsics supported: ");
printf(options1.WaveOps ? "Yes\n" : "No\n");
printf("16-bit types supported: ");
printf(options4.Native16BitShaderOpsSupported ? "Yes\n" : "No\n");
bool bUseWaveIntrinsics = options1.WaveOps;
bool bUseWaveMatch = model.HighestShaderModel >= D3D_SHADER_MODEL_6_5;
bool b16bitTypes = options4.Native16BitShaderOpsSupported;
WCHAR simdWidth[32];
swprintf_s(simdWidth, L"-DSIMD_WIDTH=%d", options1.WaveLaneCountMin);
/*LPCWSTR args[] = {
L"-I..\\..\\brotlig\\src\\decoder\\",
L"-O3",
simdWidth,
L"",
bUseWaveIntrinsics ? L"-DUSE_WAVE_INTRINSICS" : L"",
bUseWaveMatch ? L"-DUSE_WAVE_MATCH" : L"",
b16bitTypes ? L"-enable-16bit-types" : L""
};*/
LPCWSTR args[] = {
L"-I..\\..\\brotlig\\src\\decoder\\"
};
static LPCWSTR shaderModelName[] = { L"cs_6_0", L"cs_6_1", L"cs_6_2", L"cs_6_3", L"cs_6_4", L"cs_6_5" };
ComPtr<IDxcOperationResult> result;
hr = compiler->Compile(sourceBlob.Get(), p_sShaderName, L"CSMain", shaderModelName[model.HighestShaderModel & 15], args, _countof(args), NULL, 0, includeHandler.Get(), &result);
if (SUCCEEDED(hr))
result->GetStatus(&hr);
if (FAILED(hr))
{
if (result)
{
ComPtr<IDxcBlobEncoding> errorsBlob;
hr = result->GetErrorBuffer(&errorsBlob);
if (SUCCEEDED(hr) && errorsBlob)
{
printf("Kernel compilation failed with: %s\n", (const char*)errorsBlob->GetBufferPointer());
exit(-1);
}
}
// Handle compilation error...
}
ComPtr<IDxcBlob> computeShader;
result->GetResult(&computeShader);
D3D12_COMPUTE_PIPELINE_STATE_DESC pipelineDesc = {};
pipelineDesc.pRootSignature = m_rootSignature.Get();
pipelineDesc.CS.BytecodeLength = computeShader->GetBufferSize();
pipelineDesc.CS.pShaderBytecode = computeShader->GetBufferPointer();
// ThrowIfFailed(m_device->CreateComputePipelineState(&pipelineDesc, IID_PPV_ARGS(&m_pipelineState)));
hr = m_device->CreateComputePipelineState(&pipelineDesc, IID_PPV_ARGS(&m_pipelineState));
if (!m_pipelineState) {
printf("Fatal: pipeline state creation failed\n");
exit(-1);
}
NAME_D3D12_OBJECT(m_pipelineState);
}
{
m_controlSize = sizeof(uint32_t) + 3 * sizeof(uint32_t) * m_maxStreamsPerLaunch;
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE + m_controlSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_uploadBuffer)));
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&m_inBuffer)));
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&m_outBuffer)));
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(m_controlSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&m_controlBuffer)));
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_READBACK),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&m_readbackBuffer)));
m_uploadBuffer->Map(0, nullptr, (void**)&m_pUploadPtr);
}
InitQueries();
}
void BrotligCompute::InitQueries()
{
D3D12_QUERY_HEAP_DESC heapDesc{};
heapDesc.Count = BROTLIG_GPUD_DEFAULT_MAX_QUERIES;
heapDesc.NodeMask = 0;
heapDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
m_device->CreateQueryHeap(&heapDesc, IID_PPV_ARGS(&m_queryHeap));
ThrowIfFailed(m_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_READBACK),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(BROTLIG_GPUD_DEFAULT_MAX_QUERIES * sizeof(uint64_t)),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&m_queryReadback)));
ThrowIfFailed(m_queryReadback->Map(0, nullptr, reinterpret_cast<void**>(&m_gpuTimes)));
}
void BrotligCompute::KickoffCompute()
{
ThrowIfFailed(m_commandList->Close());
ID3D12CommandList* ppCommandLists[] = { m_commandList.Get() };
m_commandQueue->ExecuteCommandLists(1, ppCommandLists);
UINT64 fenceValue = InterlockedIncrement(&m_fenceValue);
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), fenceValue));
ThrowIfFailed(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent));
WaitForSingleObject(m_fenceEvent, INFINITE);
ThrowIfFailed(m_commandAllocator->Reset());
ThrowIfFailed(m_commandList->Reset(m_commandAllocator.Get(), m_pipelineState.Get()));
}
void BrotligCompute::StartTimestamp(uint32_t idx)
{
assert(idx * 2 < BROTLIG_GPUD_DEFAULT_MAX_QUERIES);
m_commandList->EndQuery(m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, idx * 2);
}
void BrotligCompute::EndTimestamp(uint32_t idx)
{
assert(idx * 2 < BROTLIG_GPUD_DEFAULT_MAX_QUERIES);
m_commandList->EndQuery(m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, idx * 2 + 1);
// Resolve the data
const uint64_t dstOffset = idx * 2 * sizeof(uint64_t);
m_commandList->ResolveQueryData(m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP,
idx * 2, 2, m_queryReadback.Get(), dstOffset);
}
double BrotligCompute::GetDeltaTime(uint32_t idx)
{
assert(idx * 2 < BROTLIG_GPUD_DEFAULT_MAX_QUERIES);
uint64_t frequency;
m_commandQueue->GetTimestampFrequency(&frequency);
return 1e6 / frequency * (m_gpuTimes[idx * 2 + 1] - m_gpuTimes[idx * 2]);
}
uint32_t BrotligCompute::AddOutputBuffer(uint8_t* output)
{
static uint32_t ID = 1;
m_outputList[ID] = output;
return ID++;
}
void BrotligCompute::RemoveOutputBuffer(uint32_t outputId)
{
m_outputList.erase(outputId);
}
bool BrotligCompute::AddInput(const uint8_t* ptr, size_t size, size_t outsize, uint32_t outputId)
{
if (m_inputs.size() == m_maxStreamsPerLaunch ||
m_inBytes + align<BROTLIG_DATA_ALIGNMENT>(size) > BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE ||
m_outBytes + align<BROTLIG_DATA_ALIGNMENT>(outsize) > BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE)
{
return false;
}
auto* header = reinterpret_cast<const StreamHeader*>(ptr);
if (!header->Validate())
{
throw("Corrupt stream.\n");
}
if (header->Id != PageStream::sBrotligId)
{
throw("Incorrect stream format: %d\n", header->Id);
}
const size_t outputSize = header->UncompressedSize();
if (m_outBytes + align<BROTLIG_DATA_ALIGNMENT>(outputSize) > BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE)
{
if (m_inputs.size() == 0) throw("Staging buffer is too small");
return false;
}
if (m_outputList.find(outputId) == m_outputList.end())
{
throw("Output id not found");
}
memcpy(m_pUploadPtr + m_inBytes, ptr, size);
CompressedStream stream;
stream.inputPos = m_inBytes;
stream.inputSize = size;
stream.uncompPos = m_outBytes;
stream.uncompSize = outputSize;
stream.outputId = outputId;
m_inputs.push_back(stream);
m_inBytes += align<BROTLIG_DATA_ALIGNMENT>(size);
m_outBytes += align<BROTLIG_DATA_ALIGNMENT>(outputSize);
return true;
}
void BrotligCompute::ClearInputs()
{
m_inputs.clear();
m_inBytes = 0;
m_outBytes = 0;
}
bool BrotligCompute::Execute()
{
if (m_inputs.empty() || m_inBytes == 0)
return false;
uint32_t totalOutSize = 0;
// Prepare and upload the control stream
{
uint32_t* pControl = reinterpret_cast<uint32_t*>(m_pUploadPtr + BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE);
*pControl++ = static_cast<uint32_t>(m_inputs.size());
for (auto& stream : m_inputs)
{
*pControl++ = static_cast<uint32_t>(stream.inputPos);
*pControl++ = static_cast<uint32_t>(stream.uncompPos);
*pControl++ = 0;
}
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_controlBuffer.Get(),
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
m_commandList->CopyBufferRegion(m_controlBuffer.Get(), 0, m_uploadBuffer.Get(),
BROTLIG_GPUD_DEFAULT_MAX_TEMP_BUFFER_SIZE, 4 + m_inputs.size() * 12);
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_controlBuffer.Get(),
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
}
// Upload input (sub)streams
{
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_inBuffer.Get(),
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
m_commandList->CopyBufferRegion(m_inBuffer.Get(), 0, m_uploadBuffer.Get(), 0, m_inBytes);
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_inBuffer.Get(),
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON));
}
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_outBuffer.Get(),
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
m_commandList->SetPipelineState(m_pipelineState.Get());
m_commandList->SetComputeRootSignature(m_rootSignature.Get());
m_commandList->SetComputeRootShaderResourceView(RootSRVInput, m_inBuffer->GetGPUVirtualAddress());
m_commandList->SetComputeRootUnorderedAccessView(RootUAVOutput, m_outBuffer->GetGPUVirtualAddress());
m_commandList->SetComputeRootUnorderedAccessView(RootUAVControl, m_controlBuffer->GetGPUVirtualAddress());
StartTimestamp(0);
m_commandList->Dispatch(m_launchSize, 1, 1);
EndTimestamp(0);
// Download output
{
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_outBuffer.Get(),
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE));
m_commandList->CopyBufferRegion(m_readbackBuffer.Get(), 0, m_outBuffer.Get(), 0, m_outBytes);
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_outBuffer.Get(),
D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
}
KickoffCompute();
UINT8* pData = nullptr;
m_readbackBuffer->Map(0, nullptr, (void**)&pData);
for (const auto& stream : m_inputs)
{
const auto it2 = m_outputList.find(stream.outputId);
if (it2 != m_outputList.end())
{
const auto& output = it2->second;
UINT8* tptr = pData + stream.uncompPos;
memcpy(output,
tptr, stream.uncompSize);
}
}
m_inputs.clear();
m_inBytes = 0;
m_outBytes = 0;
m_readbackBuffer->Unmap(0, nullptr);
m_totalTime += GetDeltaTime(0);
return true;
} | [
"napatel@amd.com"
] | napatel@amd.com |
d7549e788ded3d2f6c6d04f1078f67ab619c167a | 350db570521d3fc43f07df645addb9d6e648c17e | /1016_Binary_String_With_Substrings_Representing_1_To_N/solution.cpp | 73bd03a1037004dc1570971216524a4771340825 | [] | no_license | benjaminhuanghuang/ben-leetcode | 2efcc9185459a1dd881c6e2ded96c42c5715560a | a2cd0dc5e098080df87c4fb57d16877d21ca47a3 | refs/heads/master | 2022-12-10T02:30:06.744566 | 2022-11-27T04:06:52 | 2022-11-27T04:06:52 | 236,252,145 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,377 | cpp | /*
1016. Binary String With Substrings Representing 1 To N
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/
*/
#include <string>
using namespace std;
/*
Java solution can use String n = Integer.toBinaryString(i);
*/
/*
https://xingxingpark.com/Leetcode-1016-Binary-String-With-Substrings-Representing-1-To-N/
由于题目中给了S.length最大为1000,我们考虑11位二进制数(也就是1024 - 2047)总共有 > 1000个
然而长度为1000的字符串,取连续的11位数(即长度为11的子串),总共只能取1000 - 10 = 990种 < 1000 => 不可能包含所有11位binary,所以N最多也就是11位数,其上限为2^11 = 2048
只需要算 > N/2的数,因为如果一个数k的二进制是S的子串,那么k/2只不过少了一位,一定也是S的子串,没有必要再算。
*/
class Solution
{
public:
bool queryString(string S, int N)
{
if (N >= 2048)
{
return false;
}
for (int i = N; i > N / 2; --i)
{
if (S.find(intToBinary(i)) == string::npos)
{
return false;
}
}
return true;
}
private:
string intToBinary(int N)
{
string binary = "";
while (N)
{
if (N & 1)
{
binary = "1" + binary;
}
else
{
binary = "0" + binary;
}
N /= 2;
}
return binary;
}
}; | [
"bhuang@rms.com"
] | bhuang@rms.com |
01c41045e101e2a403bfe25de9f18a3dc62e7228 | 1e6b977e350ea4619710909c5431769df62ea4e9 | /RobotOpenCV/Robot.h | 4b9ac6589fa2fbda07c94a60ed203af604592d03 | [] | no_license | 2ndAfterGod/Practice | c9b180e206321418f3cc51fe3ae253877471dd56 | 384100055ef1d89aac1de60ab111a12d9c3fd819 | refs/heads/master | 2022-11-14T12:13:53.661241 | 2020-07-06T14:07:37 | 2020-07-06T14:07:37 | 276,154,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | h | #pragma once
#include <opencv2/opencv.hpp>
#include <ctime>
#include "windowParam.h"
#include "ViewFrame.h"
// robot parameters
const int ROBO_WIDTH = 120, ROBO_HEIGHT = 40;
const float ROBOT_SPEED = 1.0;
class Robot
{
private:
int x = WINDOW_WIDTH / 2, y = WINDOW_HEIGHT - WINDOW_HEIGHT / 20,
width = ROBO_WIDTH, height = ROBO_HEIGHT;
float speed = ROBOT_SPEED;
ViewFrame cam;
public:
Robot();
void draw(cv::Mat frame); // drawing rules
void move(clock_t deltaTime, int key); // moving rules
void updateCam();
void showCam();
cv::Mat getCamFrame();
int getX()
{ return x; }
int getY()
{ return y; }
int getWidth()
{ return width; }
int getHeight()
{ return height; }
}; | [
"noreply@github.com"
] | noreply@github.com |
eac91f3a6d0ea5af610418e9ab530562bcb4eddb | 4b1ac97833bc7fe2c9a713f65609608c927c8195 | /CairoTagCloud.hpp | bf96d6c07271cae02732b55af4581843475364c1 | [] | no_license | esaule/bibtex_cloud | b8938471d94e1e75b6c6e97babc74a9097d6b556 | c7d4d57fb460c536b002147914dd6b2102a0d587 | refs/heads/master | 2023-02-23T23:34:41.553288 | 2013-10-27T20:18:19 | 2013-10-27T20:18:19 | 333,585,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,552 | hpp | #ifndef CAIRO_TAG_CLOUD
#define CAIRO_TAG_CLOUD
#include "cairo_graphic_controller.hpp"
#include <set>
class CairoTagCloud : public CairoGraphicController {
std::vector<std::pair<std::string, int > > count;
// float fontsize (int occurence) {return occurence;}
// float fontsize (int occurence) {return 3*sqrt((float)occurence)+5;}
float fontsize (int occurence) {return scale*(float)occurence+5;}
struct placement {
float x, y, w, h;
std::string tostring() const {
std::stringstream ss;
ss<<"("<<x<<", "<<y<<", "<<w<<", "<<h<<")";
return ss.str();
}
};
float scale;
std::map<std::string, placement > actual_placement;
//return true if collide
bool check_collision(const placement& p1, const placement& p2) {
float bl = p2.x;
float br = p2.x+p2.w;
float bt = p2.y+p2.h;
float bb = p2.y;
float al = p1.x;
float ar = p1.x+p1.w;
float at = p1.y+p1.h;
float ab = p1.y;
if (bl >= ar) return false;
if (br <= al) return false;
if (bb >= at) return false;
if (bt <= ab) return false;
return true;
}
bool within(const placement& p1, float x, float y) {
if (x< p1.x || x > p1.x+p1.w) return false;
if (y< p1.y || y > p1.y+p1.h) return false;
return true;
}
void compute_placement() {
bool verbose = false;
if (!refresh_placement) return;
std::cout<<"compute placement"<<std::endl;
refresh_placement = false;
actual_placement.clear();
for (auto ent : count) {
placement p;
bool cont = true;
int try_count = 0;
while (cont) {
try_count ++;
if (try_count == 50) break;
cont = false;
//compute tentative placement
p.h = fontsize(ent.second);
p.w = fontsize(ent.second)*ent.first.size();
if (p.w >= getSizeX() || p.h >= getSizeY()) {try_count = 50; break;}
p.x = rand() % (getSizeX()-(int) p.w);
p.y = p.h+ (rand() % ( getSizeY() - (int) p.y));
//check for collisions
for (auto ent : actual_placement) {
placement& pl = ent.second;
if (check_collision(p, pl))
cont = true;
if (cont) {
if (verbose)
std::cout<<"collide"<<p.tostring()<<" "<<pl.tostring()<<std::endl;
break;
}
}
}
if (try_count < 50)
actual_placement[ent.first] = p;
}
}
bool refresh_placement;
cairo_pattern_t * bgcolor;
cairo_pattern_t * fgcolor;
cairo_pattern_t * fgcolor_mp;
std::map<std::string, bool> marked_plus;
public:
void setTagCloud (std::vector<std::pair<std::string, int > >& c) {
refresh_placement = true;
count = c;
marked_plus.clear();
for (auto ent : count) {
marked_plus[ent.first] = false;
}
}
void scaleUp() {scale*=1.2; refresh_placement = true;}
void scaleDown() {scale/=1.2; refresh_placement = true;}
CairoTagCloud ( std::vector<std::pair<std::string, int > >& c ) {
setTagCloud (c);
scale = 1.;
bgcolor = cairo_pattern_create_rgb(1,1,1);
fgcolor = cairo_pattern_create_rgb(0,0,0);
fgcolor_mp = cairo_pattern_create_rgb(1,0,0);
}
virtual ~CairoTagCloud() {
cairo_pattern_destroy(bgcolor);
cairo_pattern_destroy(fgcolor);
cairo_pattern_destroy(fgcolor_mp);
}
void getMarkedPlus(std::set<std::string> & out) {
for (auto ent : marked_plus) {
if (ent.second)
out.insert (ent.first);
}
}
virtual void setSizeX(int sx){if (sx != getSizeX()) refresh_placement = true; CairoGraphicController::setSizeX(sx);}
virtual void setSizeY(int sy){if (sy != getSizeY()) refresh_placement = true; CairoGraphicController::setSizeY(sy); }
virtual void clickat(int x, int y) {
for (auto ent : actual_placement) {
if (within(ent.second, x, y)) {
marked_plus[ent.first] = ! (marked_plus[ent.first]);
break;
}
}
}
virtual void clickmove(int x, int y){}
virtual void clickrelease(int x, int y){}
virtual void render(cairo_t* cr) {
compute_placement();
//paint background
cairo_set_source(cr, bgcolor);
cairo_paint(cr);
//paint rectangles
cairo_set_source(cr, fgcolor);
for (auto pl : actual_placement) {
//cairo_rectangle(cr, pl.second.x, pl.second.y, pl.second.w, pl.second.h);
//cairo_stroke(cr);
cairo_move_to (cr, pl.second.x, pl.second.y + pl.second.h);
if (marked_plus[pl.first]) {
cairo_set_source(cr, fgcolor_mp);
}
else {
cairo_set_source(cr, fgcolor);
}
show_text (cr, pl.first, pl.second.h);
}
}
virtual bool quit() const{return false;}
};
#endif
| [
"esaule@uncc.edu"
] | esaule@uncc.edu |
799c44b9222bbb2efaf4d5af1ff3a5d172d5cd0e | ba9322f7db02d797f6984298d892f74768193dcf | /cms/include/alibabacloud/cms/model/QueryMetricListResult.h | 977cc043eb377cf2ba20c0d49173c4a5fded5fc1 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 1,673 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CMS_MODEL_QUERYMETRICLISTRESULT_H_
#define ALIBABACLOUD_CMS_MODEL_QUERYMETRICLISTRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/cms/CmsExport.h>
namespace AlibabaCloud
{
namespace Cms
{
namespace Model
{
class ALIBABACLOUD_CMS_EXPORT QueryMetricListResult : public ServiceResult
{
public:
QueryMetricListResult();
explicit QueryMetricListResult(const std::string &payload);
~QueryMetricListResult();
std::string getMessage()const;
std::string getPeriod()const;
std::string getCursor()const;
std::string getDatapoints()const;
std::string getCode()const;
std::string getSuccess()const;
protected:
void parse(const std::string &payload);
private:
std::string message_;
std::string period_;
std::string cursor_;
std::string datapoints_;
std::string code_;
std::string success_;
};
}
}
}
#endif // !ALIBABACLOUD_CMS_MODEL_QUERYMETRICLISTRESULT_H_ | [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
da1b06a3c529cebe1c0b982e5d7fdd91696ad264 | fe99af037f9dd498359f5ff8b6cc87042dad11da | /shape.cpp | 6d7b81235f7259de3ff35cf9c139139b13a54713 | [] | no_license | bfakhri/phys | d9d333fe8c84cdf400e15367f42c2c33ef86babb | d89e412bf993d3affdd15491f4125573344f2444 | refs/heads/master | 2021-01-22T10:18:39.199951 | 2017-09-18T22:30:34 | 2017-09-18T22:30:34 | 39,798,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,867 | cpp | #include "shape.h"
///////////////
// Constructors
///////////////
Shape::Shape()
{
// Scalar quantities
mass = 1;
// Vector quantities
// Translational
t_position.x = 0;
t_position.y = 0;
t_position.z = 0;
t_velocity.x = 0;
t_velocity.y = 0;
t_velocity.z = 0;
t_forces.x = 0;
t_forces.y = 0;
t_forces.z = 0;
t_pInf.x = 0;
t_pInf.y = 0;
t_pInf.z = 0;
// Rotational
r_position.x = 0;
r_position.y = 0;
r_position.z = 0;
r_velocity.x = 0;
r_velocity.y = 0;
r_velocity.z = 0;
r_forces.x = 0;
r_forces.y = 0;
r_forces.z = 0;
r_pInf.x = 0;
r_pInf.y = 0;
r_pInf.z = 0;
// Visual
collides = false;
color.x = 0.5;
color.y = 0.5;
color.z = 0.5;
};
Shape::Shape(double sMass, cart tPos, cart tVel, cart rPos, cart rVel)
{
// Scalar quantities
mass = sMass;
// Vector quantities
// Translational
t_position.x = tPos.x;
t_position.y = tPos.y;
t_position.z = tPos.z;
t_velocity.x = tVel.x;
t_velocity.y = tVel.y;
t_velocity.z = tVel.z;
t_forces.x = 0;
t_forces.y = 0;
t_forces.z = 0;
t_pInf.x = 0;
t_pInf.y = 0;
t_pInf.z = 0;
// Rotational
r_position.x = rPos.x;
r_position.y = rPos.y;
r_position.z = rPos.z;
r_velocity.x = rVel.x;
r_velocity.y = rVel.y;
r_velocity.z = rVel.z;
r_forces.x = 0;
r_forces.y = 0;
r_forces.z = 0;
r_pInf.x = 0;
r_pInf.y = 0;
r_pInf.z = 0;
// Visual
collides = false;
color.x = 0.5;
color.y = 0.5;
color.z = 0.5;
};
///////////
// Mutators
///////////
void Shape::t_addForce(cart force)
{
t_forces.x += force.x;
t_forces.y += force.y;
t_forces.z += force.z;
};
void Shape::r_addForce(cart force)
{
r_forces.x += force.x;
r_forces.y += force.y;
r_forces.z += force.z;
};
void Shape::t_addMomentum(cart p)
{
t_pInf.x += p.x;
t_pInf.y += p.y;
t_pInf.z += p.z;
}
void Shape::r_addMomentum(cart p)
{
r_pInf.x += p.x;
r_pInf.y += p.y;
r_pInf.z += p.z;
}
void Shape::r_addMomentum(cart p);
// Resets all forces to zero
void Shape::resetForces()
{
t_forces.x = 0;
t_forces.y = 0;
t_forces.z = 0;
r_forces.x = 0;
r_forces.y = 0;
r_forces.z = 0;
};
// Resets all forces to zero
void Shape::resetMomentum()
{
t_pInf.x = 0;
t_pInf.y = 0;
t_pInf.z = 0;
r_pInf.x = 0;
r_pInf.y = 0;
r_pInf.z = 0;
};
/////////////////
// Drawing Functs
/////////////////
void Shape::draw(cart origin)
{
// Setup the draw
glPushMatrix();
// Push everything forward so origin in not in the camera
glTranslatef(origin.x, origin.y, origin.z);
glTranslatef(t_position.x, t_position.y, t_position.z);
glRotatef(r_position.x, 1, 0 , 0);
glRotatef(r_position.y, 0, 1 , 0);
glRotatef(r_position.z, 0, 0 , 1);
// Set color to color of shape
if(collides)
glColor3f(0.0, 0, 0);
else
glColor3f(color.x, color.y, color.z);
// Actually draw it
drawShape();
// Reset the matrix
glPopMatrix();
}
/////////////////
// Physics Functs
/////////////////
cart Shape::moment(cart d)
{
cart mmnt = { momentCM().x + mass*(d.x*d.x),
momentCM().y + mass*(d.y*d.y),
momentCM().z + mass*(d.z*d.z)};
return mmnt;
}
////////////////
// Helper Functs
////////////////
void populateShapeVector(std::vector<Shape*> v)
{
// write this
}
void drawBoundaries(cart origin, cart min, cart max)
{
glPushMatrix();
// Go to physics origin
glTranslatef(origin.x, origin.y, origin.z);
glBegin(GL_QUADS);
// Back
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, max.y, min.z);
glVertex3f(min.x, max.y, min.z);
glVertex3f(min.x, min.y, min.z);
glVertex3f(max.x, min.y, min.z);
// Right
glColor3f(0.1, 0.1, 0.8);
glVertex3f(max.x, max.y, max.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, max.y, min.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, min.y, min.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(max.x, min.y, max.z);
// Top
glColor3f(0.1, 0.1, 0.8);
glVertex3f(max.x, max.y, max.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(min.x, max.y, max.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(min.x, max.y, min.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, max.y, min.z);
// Left
glColor3f(0.0, 0.0, 0.0);
glVertex3f(min.x, max.y, min.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(min.x, max.y, max.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(min.x, min.y, max.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(min.x, min.y, min.z);
/*// Bottom
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, min.y, min.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(max.x, min.y, max.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(min.x, min.y, max.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(min.x, min.y, min.z);
*/
// Bottom
glColor3f(0.0, 0.0, 0.0);
glVertex3f(max.x, min.y, min.z);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(min.x, min.y, min.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(min.x, min.y, max.z);
glColor3f(0.1, 0.1, 0.8);
glVertex3f(max.x, min.y, max.z);
glEnd();
glPopMatrix();
}
| [
"bfakhri@asu.edu"
] | bfakhri@asu.edu |
1523b80fdd68341cb3c1843a4847358514e870fd | 96dfee8bf91eb36f8aeb5b24ed77cb0f822b5916 | /sortdemo.cpp | 2b9736a5201809898bff005286a0a48095c58a53 | [] | no_license | Angelo-abel/CMake_Learning | b4019fdabc002fb75ef4efe2659df129fa3ec64f | 88eaf5c04ccbc1f952257cd105b2c099def111ef | refs/heads/main | 2023-07-08T18:35:02.406709 | 2021-08-19T09:27:48 | 2021-08-19T09:27:48 | 315,052,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,671 | cpp | #include <bits/stdc++.h>
using namespace std;
void swap(int *arr, int i, int j)
{
arr[i] = arr[i]^arr[j];
arr[j] = arr[i]^arr[j];
arr[i] = arr[i]^arr[j];
}
void QuickSort(int *arr, int left, int right)
{
if (left >= right)
return;
int i = left, j = right;
int base = arr[left];
while (i < j) {
while (i < j && arr[j] >= base)
j--;
while (i < j && arr[i] <= base)
i++;
if (i < j)
swap(arr, i, j);
}
// 基准数归位
arr[left] = arr[i];
arr[i] = base;
QuickSort(arr, left, i - 1);
QuickSort(arr, i + 1, right);
}
void Merge(int *arr, int len)
{
int temp[len];
int b = 0;
int l = 0;
int mid = len >> 1;
int r = mid;
while (l < mid && r < len) {
if (arr[l] <= arr[r])
temp[b++] = arr[l++];
else
temp[b++] = arr[r++];
}
while (l < mid)
temp[b++] = arr[l++];
while (r < len)
temp[b++] = arr[r++];
copy(temp, temp + len, arr);
}
void MergeSort(int *arr, int len)
{
if (len <= 1)
return;
else
{
int mid = len >> 1;
MergeSort(arr, mid);
MergeSort(arr + mid, len - mid);
Merge(arr, len);
}
}
void heapify(int *arr, int idx, int len)
{
int parent = idx;
int child = (parent << 1) + 1;
while (child < len) {
if ((child + 1) < len && arr[child + 1] > arr[child])
child++;
if (arr[parent] > arr[child])
break;
swap(arr, parent, child);
parent = child;
child = (child << 1) + 1;
}
}
void buildheap(int *arr, int size)
{
for (int i = (size >> 1) - 1; i >= 0; i--) {
heapify(arr, i, size);
}
}
void heapsort(int *arr, int size)
{
buildheap(arr, size);
for (int i = size - 1; i > 0; i--) {
swap(arr, 0, i);
heapify(arr, 0, i);
}
}
void test3()
{
vector<int> nums;
vector<int> nums1;
vector<int> nums2;
for (int i = 0; i< 10; i++) {
nums.push_back(rand()%100);
nums1.push_back(rand()%100);
nums2.push_back(rand()%100);
}
// QuickSort(&nums[0], 0, nums.size() - 1);
// for_each(nums.begin(), nums.end(), [](int a){cout << a << " ";});
// cout << endl;
// MergeSort(&nums1[0], nums1.size());
// for_each(nums1.begin(), nums1.end(), [](int a){cout << a << " ";});
// cout << endl;
heapsort(&nums2[0], nums2.size());
for_each(nums2.begin(), nums2.end(), [](int a){cout << a << " ";});
cout << endl;
}
// 归并排序与快速排序算法
int main(int argc, char**argv)
{
test3();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1da8e0361d79858a3a72cbe1e69c421b6eaa315b | 07ee17f9fb57c0ccc9e4fe2c18410bd3f3eeec34 | /darkstar/Tools/obsolete/StampTool/Inc/gridWindow.h | 001ddae9caa2495d3a5913a79f874bc324604c7d | [] | no_license | AlexHuck/TribesRebirth | 1ea6ba27bc2af10527259d4d6cd4561a1793bccd | cf52c2e8c63f3da79e38cb3c153288d12003b123 | refs/heads/master | 2021-09-11T00:35:45.407177 | 2021-08-29T14:36:56 | 2021-08-29T14:36:56 | 226,741,338 | 0 | 0 | null | 2019-12-08T22:30:13 | 2019-12-08T22:30:12 | null | UTF-8 | C++ | false | false | 3,882 | h | //------------------------------------------------------------------------------
// Description
//
// $Workfile$
// $Revision$
// $Author $
// $Modtime $
//
//------------------------------------------------------------------------------
#ifndef _GRIDWINDOW_H_
#define _GRIDWINDOW_H_
#include <gw.h>
#include <resManager.h>
#include <ts_material.h>
#include <string.h>
#include "LSTerrainStamp.h"
#include "inspectDlg.h"
class InspectDlg;
class GridWindow : public GWCanvas
{
private:
typedef GWCanvas Parent;
GWMenu gridMenu;
InspectDlg *inspector;
GFXPalette *palette;
ResourceManager *rsrcManager;
VolumeListEntry *volRStream;
private:
char *helpPath;
Resource<TSMaterialList> *phMaterialList;
LSTerrainStamp *stamp;
LSTerrainStamp *clipBoard; // for cut, paste, copy
Point2I selectedTile;
Int32 numTiles; // num of tile in lenght and width of display
Point2I origin;
char stamp_name[MAX_PATH];
char dml_name[MAX_PATH];
public:
GridWindow();
bool init(char *execPath);
// windows functions
void onCommand(int id, HWND hwndCtl, UINT codeNotify);
void onKey(UINT vk, BOOL fDown, int cRepeat, UINT flags);
void onLButtonDown(BOOL, int x, int y, UINT);
void onRButtonDown(BOOL b, int x, int y, UINT k);
void onMove(int x, int y);
void onOpenPalette();
void loadPalette(char *filename);
void onOpenDML();
void loadDML(char *filename);
void onNewTSP();
void onOpenTSP();
void loadTSP(char *filename);
void onSaveTSP(bool fSaveAs);
void saveTSP(char *filename);
void onDestroy();
// clipBoard functions
void onCut();
void onCopy();
void onPaste();
// functions for displaying the stamp
void render();
void drawTextures();
void drawGrid();
void drawFlatTiles();
void drawOrigin();
bool tileVisible(Point2I &tile);
// functions for updating guts of terrain stamp
void reset();
Point2I *getSelectedTile();
char *getDML_Name();
int getDML_MaxTexId();
char *getStampName();
void deleteTile(Point2I &tile);
int getStampClampValue();
void setStampClampValue(int clamp);
bool isTileFlat(Point2I &tile);
void setTileFlat(Point2I &tile, bool flat);
TextureInfo *getTileTexture(Point2I &tile);
void setTileTexture(Point2I &tile, TextureInfo &tex_info);
void invertYCoord(); // oops, I drew the stamp with Y positive toward the bottom
// of the window, Darkstar, has Y positive up the window
void setHoleFlag();
void setHoleTexID();
void moveStamp(Point2I &delta);
void displayErrDialog(char *fmt, ...);
};
//--------------------------------------
inline Point2I *GridWindow::getSelectedTile()
{
return &selectedTile;
}
//--------------------------------------
inline char *GridWindow::getDML_Name()
{
if (dml_name[0] =='\0')
return "None Specified";
return dml_name;
}
//--------------------------------------
inline int GridWindow::getDML_MaxTexId()
{
if (phMaterialList == NULL)
return -1;
return ((*phMaterialList)->getMaterialsCount() - 1);
}
//--------------------------------------
inline char *GridWindow::getStampName()
{
char *name;
if (stamp_name[0] =='\0')
return "Untitled";
name = strrchr(stamp_name, '\\');
if (name)
name++;
else
name = stamp_name;
return name;
}
//--------------------------------------
inline void GridWindow::deleteTile(Point2I &tile)
{
TextureInfo tex;
tex.textureID = -2;
setTileTexture(tile, tex);
setTileFlat(tile, false);
}
//--------------------------------------
inline int GridWindow::getStampClampValue()
{
return stamp->clamp_max_detail;
}
inline void GridWindow::setStampClampValue(int clamp)
{
stamp->clamp_max_detail = clamp;
}
#endif //_GRIDWINDOW_H_
| [
"altimormc@gmail.com"
] | altimormc@gmail.com |
ef86a642b87a59d7aadacf98b85274da674240d7 | 99d054f93c3dd45a80e99be05f3f64c2c568ea5d | /Online Judges/URI/Christmas Contest 2018 (F) Suspicious Gifts/main.cpp | 1a3df3189025abbfd907cec4400f409059fd1f77 | [
"MIT"
] | permissive | AnneLivia/Competitive-Programming | 65972d72fc4a0b37589da408e52ada19889f7ba8 | f4057e4bce37a636c85875cc80e5a53eb715f4be | refs/heads/master | 2022-12-23T11:52:04.299919 | 2022-12-12T16:20:05 | 2022-12-12T16:20:05 | 117,617,504 | 74 | 21 | MIT | 2019-11-14T03:11:58 | 2018-01-16T01:58:28 | C++ | UTF-8 | C++ | false | false | 1,331 | cpp | #include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
void toup(string& s){
for (int i = 0; i < (int)s.size(); i++) {
s[i] = toupper(s[i]);
}
}
int main()
{
int nc, kids, ns;
vector<string>aux;
string wish, p;
map<string,vector<string>>m;
while(cin >> nc >> kids) {
cin.ignore();
m.clear();
while(nc--) {
getline(cin,wish);
cin >> ns;
cin.ignore();
toup(wish);
aux.clear();
while(ns--) {
getline(cin,p);
toup(p);
aux.push_back(p);
}
m.insert(make_pair(wish,aux));
}
while(kids--) {
getline(cin,wish);
toup(wish);
stringstream split(wish);
int second = 0;
while(getline(split, p, ';')) {
second++;
if(second == 1) {
wish = p;
} else {
if(find(m.at(wish).begin(), m.at(wish).end(), p) == m.at(wish).end()) {
cout << "N\n";
} else {
cout << "Y\n";
}
}
}
}
}
return 0;
}
| [
"annelivia16@gmail.com"
] | annelivia16@gmail.com |
2ecac203d0fef9e689e663cfe32d38dfeefaca05 | b9845c4ae1f69708b6321ebfd88396be36247777 | /C371GroupProject/C371GroupProject/Camera.h | b18fee953e204bdece41887b0ea24c9a4349ed89 | [] | no_license | dsma1991/371Pro | ed502578ae26834457ed0f225c8ab1dd38d0179c | deca26de5ccefb2b63b67a591d31800625c0f64c | refs/heads/master | 2020-05-26T07:58:13.280143 | 2014-11-21T21:38:24 | 2014-11-21T21:38:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h | #pragma once
class Camera
{
public:
Camera(void);
~Camera(void);
enum CameraMode
{
Pan,
Rotate,
};
void moveCameraTo(double x, double y, double z, CameraMode mode); // move camera smoothly to destination
void snapCameraTo(double x, double y, double z, CameraMode mode); // move camera instantly to destination
void displayCamera(); // do the actual gluLookAt and calculations
void idle();
private:
double eyeX, eyeY, eyeZ, lookAtX, lookAtY, lookAtZ, upX, upY, upZ;
double destinationX, destinationY, destinationZ;
};
| [
"dsma1991@yahoo.com"
] | dsma1991@yahoo.com |
d98eaff864c8f7f4ce29cef8ce7ea6e665d540e2 | 09193f071c8be1ca34505f238cfc563e3c3921be | /tracker-pt/module/frame.hpp | 0569a3232e7e48c64d932a4f09a33e975ee942e3 | [
"LicenseRef-scancode-warranty-disclaimer",
"ISC"
] | permissive | opentrack/opentrack | 0b0961d4069b6d3c2a47008cf9f2f24da839626a | b04381b44e4fbbfcf88e5e74052464657cf7df25 | refs/heads/master | 2023-08-30T01:43:26.460075 | 2023-08-27T05:11:08 | 2023-08-27T05:11:08 | 9,753,283 | 2,918 | 464 | null | 2023-08-27T15:45:27 | 2013-04-29T17:03:00 | C++ | UTF-8 | C++ | false | false | 814 | hpp | #pragma once
#include "pt-api.hpp"
#include <opencv2/core/mat.hpp>
#include <QImage>
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wweak-vtables"
#endif
namespace pt_module {
struct Frame final : pt_frame
{
cv::Mat mat;
operator const cv::Mat&() const& { return mat; }
operator cv::Mat&() & { return mat; }
};
struct Preview final : pt_preview
{
Preview(int w, int h);
void set_last_frame(const pt_frame& frame) override;
QImage get_bitmap() override;
void draw_head_center(f x, f y) override;
operator cv::Mat&() { return frame_copy; }
operator cv::Mat const&() const { return frame_copy; }
private:
cv::Mat frame_copy, frame_out, frame_tmp;
};
} // ns pt_module
#ifdef __clang__
# pragma clang diagnostic pop
#endif
| [
"sthalik@misaki.pl"
] | sthalik@misaki.pl |
efe29fee4e7636fe266924dbd5b2f0c108316c07 | 85057c5b7179ecf863346b2ccb8b8cba0b9f1199 | /Maze-path.cpp | a13f6efc6376a04650a9a871678ef6aac7a1a2ad | [] | no_license | Aditya1445/CompCoding | f6b0b0f28ed3df03fadc5ae54b97f759a49e67ef | 397709decef774ed0e5b58ee4a30c851bfe172a1 | refs/heads/master | 2023-03-27T04:03:56.911649 | 2021-03-29T11:01:58 | 2021-03-29T11:01:58 | 311,781,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef vector<string> vs;
vs MazePath(int sr, int sc, int dr, int dc)
{
if (sr == dr && sc == dc)
{
vs bres;
bres.push_back("");
return bres;
}
vs hpath;
vs vpath;
if (sr < dr)
{
vpath = MazePath(sr + 1, sc, dr, dc);
}
if (sc < dc)
{
hpath = MazePath(sr, sc + 1, dr, dc);
}
vs p;
for (string h : hpath)
{
p.push_back("h" + h);
}
for (string v : vpath)
{
p.push_back("v" + v);
}
return p;
}
int main()
{
int n;
cin >> n;
int m;
cin >> m;
vs paths = MazePath(1, 1, n, m);
int cnt = 0;
cout << '[';
for (string str : paths) {
if (cnt != paths.size() - 1)
cout << str << ", ";
else
cout << str;
cnt++;
}
cout << ']';
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
3fba726c7c8e220675a8ad7b28b9609092233297 | 72ceff8ed4e124d71700472521327c3242894526 | /smacc2_sm_reference_library/sm_multi_stage_1/include/sm_multi_stage_1/states/ac_cycle_2/sti_ac_cycle_dwell_2.hpp | 5443707f7c5f4e2d79957c3790348af930384a94 | [
"Apache-2.0"
] | permissive | reelrbtx/SMACC2 | a56ea47bed56bcacf46a4b5fd1431897af550ae4 | ac61cb1599f215fd9f0927247596796fc53f82bf | refs/heads/master | 2023-09-05T02:57:13.097215 | 2021-11-24T20:00:59 | 2021-11-24T20:00:59 | 431,620,456 | 1 | 0 | Apache-2.0 | 2021-11-24T20:32:16 | 2021-11-24T20:32:15 | null | UTF-8 | C++ | false | false | 1,983 | hpp | // Copyright 2021 RobosoftAI 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.
namespace sm_multi_stage_1
{
namespace ac_cycle_2
{
// STATE DECLARATION
struct StiACCycleDwell2 : smacc2::SmaccState<StiACCycleDwell2, SsACCycle2>
{
using SmaccState::SmaccState;
// DECLARE CUSTOM OBJECT TAGS
struct TIMEOUT : ABORT{};
struct NEXT : SUCCESS{};
struct PREVIOUS : ABORT{};
struct RETURN : CANCEL{};
// TRANSITION TABLE
typedef mpl::list<
Transition<EvTimer<CbTimerCountdownOnce, OrTimer>, StiACCyclePulse2, SUCCESS>,
Transition<EvKeyPressP<CbDefaultKeyboardBehavior, OrKeyboard>, StiACCycleExpire2, PREVIOUS>,
Transition<EvKeyPressN<CbDefaultKeyboardBehavior, OrKeyboard>, StiACCyclePulse2, NEXT>
// Transition<EvKeyPressZ<CbDefaultKeyboardBehavior, OrKeyboard>, StObserve2, RETURN>,
// Transition<EvKeyPressX<CbDefaultKeyboardBehavior, OrKeyboard>, MsRecovery2, ABORT>
>reactions;
// STATE FUNCTIONS
static void staticConfigure()
{
configure_orthogonal<OrTimer, CbTimerCountdownOnce>(20);
configure_orthogonal<OrSubscriber, CbWatchdogSubscriberBehavior>();
configure_orthogonal<OrUpdatablePublisher, CbDefaultPublishLoop>();
configure_orthogonal<OrKeyboard, CbDefaultKeyboardBehavior>();
}
void runtimeConfigure() {}
void onEntry() { RCLCPP_INFO(getLogger(), "On Entry!"); }
void onExit() { RCLCPP_INFO(getLogger(), "On Exit!"); }
};
} // namespace ac_cycle_1
} // namespace sm_multi_stage_1
| [
"noreply@github.com"
] | noreply@github.com |
662547577cf0920c721966520af2c8a86f8792df | 2f78e134c5b55c816fa8ee939f54bde4918696a5 | /code_ps3/core/standardarchive.cpp | 479110307e78f8a5b5a00b51ef6d6b6e62980836 | [] | no_license | narayanr7/HeavenlySword | b53afa6a7a6c344e9a139279fbbd74bfbe70350c | a255b26020933e2336f024558fefcdddb48038b2 | refs/heads/master | 2022-08-23T01:32:46.029376 | 2020-05-26T04:45:56 | 2020-05-26T04:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | cpp | //*******************************************************************************
//
// StandardFile.cpp.
//
//******************************************************************************/
#include "core/standardarchive.h"
#include "core/waddef.h"
#include "core/fileio_ps3.h"
//*******************************************************************************
// Ctor.
//*******************************************************************************
StandardArchive::StandardArchive( const char *filename, int32_t archive_fd, const Wad::ArchiveHeader &archive_header, MediaTypes media_type )
: Archive( filename, archive_fd, archive_header, media_type )
{}
//*******************************************************************************
// Ctor.
//*******************************************************************************
StandardArchive::StandardArchive( const char *filename, int32_t archive_fd, const Wad::ArchiveHeader &archive_header, int32_t area_number, MediaTypes media_type )
: Archive( filename, archive_fd, archive_header, area_number, media_type )
{}
//*******************************************************************************
// Dtor.
//*******************************************************************************
StandardArchive::~StandardArchive()
{}
//*******************************************************************************
// Attempt to open the given file from the archive.
//*******************************************************************************
bool StandardArchive::OpenFile( const char *filename, File *file, Mem::MEMORY_CHUNK chunk, uint32_t alignment ) const
{
UNUSED( chunk );
UNUSED( alignment );
// Check the passed File object.
ntError_p( file != NULL, ("You must pass a valid File object constructed using the default ctor.") );
ntError_p( file->m_CompressedFile == NULL, ("The passed File object must not previously have been setup.") );
# ifdef USE_FIOS_FOR_SYNCH_IO
ntError_p( file->m_iFileHandle == -1, ("The passed File object must not previously have been setup.") );
# else
ntError_p( false, ("You must use FIOS to enable support for compressed archives.") );
# endif
uint32_t hash = GetHash( filename );
const Wad::ArchiveFileData *file_data = GetFileData( hash );
if ( file_data == NULL )
{
return false;
}
// Because this is an UNCOMPRESSED (standard) archive, the m_CompressedDataOffset
// and m_CompressedDataLength members of Wad::ArchiveFileData are actually the uncompressed versions.
off_t subfile_offset = file_data->m_CompressedDataOffset + m_DataOffset;
ssize_t subfile_length = file_data->m_UncompressedDataLength;
file->m_iFileHandle = FileManager::openSubFile( m_ArchiveName.GetString(), O_RDONLY, m_MediaType, subfile_offset, subfile_length );
ntError_p( file->m_iFileHandle >= 0, ("Failed to open archive %s from media-type %i.", m_ArchiveName.GetString(), (uint32_t)m_MediaType) )
return file->m_iFileHandle >= 0;
}
| [
"hopefullyidontgetbanned735@gmail.com"
] | hopefullyidontgetbanned735@gmail.com |
7090e5e00c2870a1367e9ea7e7d7f56fb9fb3949 | bfdca88b15f1e76290aff8373b0fb2cd1e19dc86 | /ProjectEuler/Problem2.cpp | b4312abfa05db9d6a657f39d18541d889c338ad0 | [] | no_license | ZLWedge/PracticeRepo | c2535d7976ac411bc54f3c41365f7f29d0640c50 | 6280372a0bbb019327225e82847854ba808b45d5 | refs/heads/master | 2021-01-18T12:10:46.082888 | 2014-12-22T06:27:31 | 2014-12-22T06:27:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 223 | cpp | #include <iostream>
int main(){
int a = 1;
int b = 2;
int c = 0;
int total = 0;
while (b<4000000){
c=a+b;
if (b % 2 == 0){
total += b;
a=b;
b=c;
}
}
std::cout << total;
return 0;
} | [
"zlapstun@gmail.com"
] | zlapstun@gmail.com |
739a093a474675784b76f159e4b6dcb3591e8b6a | bfef2d9568a0c8e06dddf67074071c3e05e324a6 | /Lex.cpp | 066680c64e1e03e3dd49faf492966ae73eadaa39 | [
"MIT"
] | permissive | meteorcloudy/Compiler | 07754ed73694f3c121bb910d5e656587dafaff14 | 2b678f9f172c92d992078e5769d816d2e753f766 | refs/heads/master | 2018-12-29T00:16:53.884453 | 2014-05-20T07:35:34 | 2014-05-20T07:35:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,557 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#define $BEGIN 1
#define $END 2
#define $INTEGER 3
#define $IF 4
#define $THEN 5
#define $ELSE 6
#define $FUNCTION 7
#define $READ 8
#define $WRITE 9
#define $SYMBOL 10
#define $CONSTANT 11
#define $EQU 12
#define $NEQU 13
#define $LE 14
#define $L 15
#define $GE 16
#define $G 17
#define $SUB 18
#define $MUL 19
#define $ASSIGN 20
#define $LPAR 21
#define $RPAR 22
#define $SEM 23
#define $EOLN 24
#define $EOF 25
using namespace std;
string Name[] = {"",
"$BEGIN",
"$END",
"$INTEGER",
"$IF",
"$THEN",
"$ELSE",
"$FUNCTION",
"$READ",
"$WRITE",
"$SYMBOL",
"$CONSTANT",
"$EQU",
"$NEQU",
"$LE",
"$L",
"$GE",
"$G",
"$SUB",
"$MUL",
"$ASSIGN",
"$LPAR",
"$RPAR",
"$SEM",
"$EOLN",
"$EOF"
};
struct BinExp
{
string val;
int type;
BinExp() {}
BinExp(string s,int x){
val = s;
type = x;
}
void print(){
cout << val <<" " << type <<endl;
}
};
string fileName;
string code;
int pos;
ofstream fout;
int line;
string getfileName(string s){
int pos = s.find(".");
return s.substr(0,pos);
}
bool isletter(char x){
if (x>='a'&&x<='z') return true;
if (x>='A'&&x<='Z') return true;
if (x=='_') return true;
return false;
}
bool isdigit(char x){
return (x>='0')&&(x<='9');
}
int getState(int now,char x){
switch (now){
case 0 :
if (x=='\n'||x==' '||x=='\t') return 0;
if (isletter(x)) return 1;
if (isdigit(x)) return 3;
switch(x)
{
case '=' : return 5;
case '-' : return 6;
case '*' : return 7;
case '(' : return 8;
case ')' : return 9;
case '<' : return 10;
case '>' : return 14;
case ':' : return 17;
case ';' : return 20;
default : return 21;
}
case 1 :
if (isletter(x)||isdigit(x)) return 1;
return 2;
case 3 :
if (isdigit(x)) return 3;
return 4;
case 10 :
switch (x){
case '=' : return 11;
case '>' : return 12;
default : return 13;
}
break;
case 14 :
switch (x){
case '=' : return 15;
default : return 16;
}
break;
case 17 :
switch (x){
case '=' : return 18;
default : return 19;
}
break;
}
return -1;
}
int isReserve(string s){
if (s=="begin") return $BEGIN;
if (s=="end") return $END;
if (s=="integer") return $INTEGER;
if (s=="if") return $IF;
if (s=="then") return $THEN;
if (s=="else") return $ELSE;
if (s=="function") return $FUNCTION;
if (s=="read") return $READ;
if (s=="write") return $WRITE;
return $SYMBOL;
}
void error(int line,string msg){
fout << "***LINE:"<< line <<" " << msg <<endl;;
}
BinExp Lex(string code,int &pos){
char x;
BinExp err("",-1);
int Now = 0;
int st = pos;
int Len = code.length();
int ID;
string val;
while (pos<Len){
if (pos>0&&code[pos-1]=='\n')
{
line++;
BinExp("EOLN",$EOLN).print();
}
x = code[pos++];
//if (x=='\n') line++;
switch (Now=getState(Now,x)){
case 0:
st = pos;
break;
case 2 :
pos--;
//if (code[pos]=='\n') line--;
val = code.substr(st,pos-st);
ID = isReserve(val);
return BinExp(val,ID);
case 4 :
pos--;
//if (code[pos]=='\n') line--;
return BinExp(code.substr(st,pos-st),$CONSTANT);
case 5 :
return BinExp("=",$EQU);
case 6 :
return BinExp("-",$SUB);
case 7 :
return BinExp("*",$MUL);
case 8 :
return BinExp("(",$LPAR);
case 9 :
return BinExp(")",$RPAR);
case 11 :
return BinExp("<=",$LE);
case 12 :
return BinExp("<>",$NEQU);
case 13 :
pos--;
//if (code[pos]=='\n') line--;
return BinExp("<",$L);
case 15 :
return BinExp(">=",$GE);
case 16 :
pos--;
//if (code[pos]=='\n') line--;
return BinExp(">",$G);
case 18 :
return BinExp(":=",$ASSIGN);
case 19 :
error(line,"\""+code.substr(st,pos-st)+"\" -> '=' expected before "+code.substr(pos-1,1));
return err;
case 20 :
return BinExp(";",$SEM);
case 21 :
error(line,"\""+code.substr(st,1)+"\" -> unknown character");
return err;
}
}
return err;
}
int main(int arg,char **args)
{
fileName = getfileName(string(args[1]));
fout.open((fileName+".lex.err").c_str());
ifstream fin(args[1]);
freopen((fileName+".dyd").c_str(),"w",stdout);
if (!fin.is_open()){
fout << "can't open file!" <<endl;
return 0;
} else {
code = "";
string tmp;
while (!fin.eof()){
getline(fin,tmp);
code += tmp + "\n";
}
int pos=0;
line = 1;
BinExp res;
do {
res = Lex(code,pos);
if (res.type!=-1)
res.print();
} while (res.type != -1);
BinExp("EOF",$EOF).print();
}
return 0;
} | [
"pengyun199311@gmail.com"
] | pengyun199311@gmail.com |
f51156026f2afb506d2b8b3fb26c818c4008b1a8 | 771a5f9d99fdd2431b8883cee39cf82d5e2c9b59 | /SDK/BP_GlitterbeardLoreBook_FeatheredFriends_functions.cpp | ba1f6104fdeeb7636f370bc304f6f06fa5c7085a | [
"MIT"
] | permissive | zanzo420/Sea-Of-Thieves-SDK | 6305accd032cc95478ede67d28981e041c154dce | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | refs/heads/master | 2023-03-25T22:25:21.800004 | 2021-03-20T00:51:04 | 2021-03-20T00:51:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | cpp | // Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_GlitterbeardLoreBook_FeatheredFriends.BP_GlitterbeardLoreBook_FeatheredFriends_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_GlitterbeardLoreBook_FeatheredFriends_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_GlitterbeardLoreBook_FeatheredFriends.BP_GlitterbeardLoreBook_FeatheredFriends_C.UserConstructionScript");
ABP_GlitterbeardLoreBook_FeatheredFriends_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_GlitterbeardLoreBook_FeatheredFriends_C::AfterRead()
{
AModalInteractionProxy::AfterRead();
READ_PTR_FULL(NPCDialog, UNPCDialogComponent);
READ_PTR_FULL(Books, UStaticMeshComponent);
READ_PTR_FULL(DefaultSceneRoot, USceneComponent);
}
void ABP_GlitterbeardLoreBook_FeatheredFriends_C::BeforeDelete()
{
AModalInteractionProxy::BeforeDelete();
DELE_PTR_FULL(NPCDialog);
DELE_PTR_FULL(Books);
DELE_PTR_FULL(DefaultSceneRoot);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"40242723+alxalx14@users.noreply.github.com"
] | 40242723+alxalx14@users.noreply.github.com |
4fc49d0c3564adb5604a514e31bdb6a3b3478463 | b8765e762b1087505189506a35cffce43638fba7 | /question/UVa/11383/x.cpp | 1b509a00d7e9617bd4ce9c341581a52d6bedd4b9 | [] | no_license | yaoling1997/desktop | 0d0782f44cca18ac97e806e919fc7c6446872a00 | 1053d1a30b1e45e82ceec90cfd3b31eec361c1e2 | refs/heads/master | 2022-02-17T12:50:54.349782 | 2019-05-18T06:13:03 | 2019-05-18T06:13:03 | 120,167,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cpp | #include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn= 600,oo= 1e6;
int c[maxn][maxn],s[maxn],t[maxn],lx[maxn],ly[maxn],d[maxn];
int n,i,j,ans;
bool match(int o){
s[o]= 1;int i;
for (i= 1;i<=n;i++)
if (!t[i] && c[o][i]==lx[o]+ly[i]){
t[i]= 1;
if (!d[i]||match(d[i])){
d[i]= o;
return 1;
}
}
return 0;
}
void update(){
int i,j,a= oo;
for (i= 1;i<=n;i++)
if (s[i])
for (j= 1;j<=n;j++)
if (!t[j])
a= min(a,lx[i]+ly[j]-c[i][j]);
for (i= 1;i<=n;i++){
if (s[i]) lx[i]-= a;
if (t[i]) ly[i]+= a;
}
}
int main()
{
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
while(scanf("%d",&n)!=EOF){
ans= 0;
for (i= 1;i<=n;i++)
for (j= 1;j<=n;j++)
scanf("%d",&c[i][j]);
for (i= 1;i<=n;i++){
lx[i]= ly[i]= d[i]= 0;
for (j= 1;j<=n;j++)
lx[i]= max(lx[i],c[i][j]);
}
for (i= 1;i<=n;i++)
for(;;){
for (j= 1;j<=n;j++) s[j]= t[j]= 0;
if (match(i)) break;
else update();
}
for (i= 1;i<n;i++){
printf("%d ",lx[i]);
ans+= lx[i];
}ans+= lx[i];printf("%d\n",lx[i]);
for (i= 1;i<n;i++){
printf("%d ",ly[i]);
ans+= ly[i];
}ans+= ly[i];printf("%d\n",ly[i]);
printf("%d\n",ans);
}
return 0;
}
| [
"379145124@qq.com"
] | 379145124@qq.com |
e7860b3bae36ad0cfa01ae3595f5862e33059bdc | 2ff2f41c6fe48a4961513ca6deefbc5b393c406e | /topi/include/topi/cuda/extern.h | 475ab6ba8a19898647f5660294d45117049fdbdd | [
"Apache-2.0"
] | permissive | zhiics/tvm | 9f5a39c6373349800b9255d74225d5dd65aba70f | 4782b1fc153d6614808f542155d58188f2dc8255 | refs/heads/master | 2021-12-21T03:24:31.176090 | 2018-09-05T22:48:37 | 2018-09-05T22:48:37 | 143,820,078 | 6 | 2 | Apache-2.0 | 2020-05-13T00:54:21 | 2018-08-07T04:34:08 | C++ | UTF-8 | C++ | false | false | 1,893 | h | /*!
* Copyright (c) 2017 by Contributors
* \file cuda/extern.h
* \brief CUDA schedule for extern followed by injective operations
*/
#ifndef TOPI_CUDA_EXTERN_H_
#define TOPI_CUDA_EXTERN_H_
#include "topi/tags.h"
#include "topi/detail/fuse.h"
#include "tvm/tvm.h"
#include "tvm/build_module.h"
namespace topi {
using namespace tvm;
namespace cuda {
/*!
* \brief Schedule a given operation representing one of the outputs of an
* external function which is followed by injective operations.
*
* \param target The target to generate a schedule for.
* \param op The operation representing the output followed by injective operations.
* \param sch The schedule to apply this scheduling to
*
* \return The schedule given by sch
*/
inline Schedule ScheduleOutputForExtern(Target target, Operation op, Schedule sch) {
auto x = op.output(0);
auto fused = detail::Fuse(sch[x], sch[x]->op.as<ComputeOpNode>()->axis);
auto num_thread = target->max_num_threads;
IterVar bx, tx;
sch[x].split(fused, num_thread, &bx, &tx);
sch[x].bind(bx, tvm::thread_axis(Range(), "blockIdx.x"));
sch[x].bind(tx, tvm::thread_axis(Range(), "threadIdx.x"));
return sch;
}
/*!
* \brief Schedule an extern op followed by injective operations.
* For example, cudnn kernel + bias add + relu
*
* \param target The target to generate a schedule for.
* \param outs The output tensors.
*
* \return A schedule for the op.
*/
inline Schedule schedule_extern(const Target& target, Array<Tensor> outs) {
Array<Operation> out_ops;
for (auto t : outs) {
out_ops.push_back(t->op);
}
auto s = create_schedule(out_ops);
tvm::schedule::AutoInlineInjective(s);
for (auto out : outs) {
if (out->op->derived_from<ExternOpNode>()) {
continue;
}
ScheduleOutputForExtern(target, out->op, s);
}
return s;
}
} // namespace cuda
} // namespace topi
#endif // TOPI_CUDA_EXTERN_H_
| [
"tqchen@users.noreply.github.com"
] | tqchen@users.noreply.github.com |
bcb753bb9a707d91fcc5ee92bedb8577f3b6709b | ad4229bf23443427d3a1b2980792197ff92b1c39 | /src/atlaas.cpp | a121ad44c1c8058bf6936007dcd666bb02dbb06d | [
"BSD-2-Clause"
] | permissive | benEnsta/atlaas | c572555362196c69718df4b87f88716f4c0c43f5 | 4af2e53a9c35e86b84b8449d475750c67b85d2e2 | refs/heads/master | 2021-01-16T17:36:09.501545 | 2014-04-02T15:46:25 | 2014-04-02T15:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,373 | cpp | /*
* atlaas.cpp
*
* Atlas at LAAS
*
* author: Pierrick Koch <pierrick.koch@laas.fr>
* created: 2013-10-08
* license: BSD
*/
#include <cassert>
#include <atlaas/atlaas.hpp>
namespace atlaas {
/**
* Merge point cloud in the internal model
* with the sensor to world transformation,
* and slide, save, load tiles.
*
* @param cloud: point cloud in the sensor frame
* @param transformation: sensor to world transformation
*/
void atlaas::merge(points& cloud, const matrix& transformation) {
// transform the cloud from sensor to custom frame
transform(cloud, transformation);
sensor_xy = matrix_to_point(transformation);
// slide map while needed
while ( slide() );
// use dynamic merge
dynamic(cloud);
}
void atlaas::dynamic(const points& cloud) {
// clear the dynamic map (zeros)
cell_info_t zeros{}; // value-initialization w/empty initializer
std::fill(dyninter.begin(), dyninter.end(), zeros);
// merge the point-cloud
rasterize(cloud, dyninter);
// merge the dynamic atlaas with internal data
merge();
}
void atlaas::tile_load(int sx, int sy) {
std::string filepath = tilepath(current[0] + sx, current[1] + sy);
if ( ! file_exists( filepath ) )
return; // no file to load
tile.load(filepath);
assert( tile.bands.size() == MAP_NAMES.size() );
assert( tile.bands[0].size() == sw * sh );
// update each cell time if bases differ
long diff = time_base - std::stol(tile.get_meta("TIME", "0"));
size_t idx = 0, eoi = 0;
for (auto it = internal.begin() + sw * sx + sh * width * sy,
end = it + sh * width; it < end; it += width - sw)
for (eoi += sw; idx < eoi; idx++) {
// tile to map
(*it)[N_POINTS] = tile.bands[N_POINTS][idx];
(*it)[Z_MAX] = tile.bands[Z_MAX][idx];
(*it)[Z_MIN] = tile.bands[Z_MIN][idx];
(*it)[Z_MEAN] = tile.bands[Z_MEAN][idx];
(*it)[VARIANCE] = tile.bands[VARIANCE][idx];
(*it)[TIME] = tile.bands[TIME][idx];
(*it)[DIST_SQ] = tile.bands[DIST_SQ][idx];
if ( diff and (*it)[N_POINTS] > 0.9 )
(*it)[TIME] -= diff;
it++;
}
}
void atlaas::tile_save(int sx, int sy) const {
// re-init the IO cache in case a load corrupted its meta-data
// reset meta-data (important for TIME)
tile.copy_meta_only(meta);
tile.names = MAP_NAMES;
tile.set_size(N_RASTER, sw, sh);
size_t idx = 0, eoi = 0;
for (auto it = internal.begin() + sw * sx + sh * width * sy,
end = it + sh * width; it < end; it += width - sw)
for (eoi += sw; idx < eoi; idx++) {
// map to tile
tile.bands[N_POINTS][idx] = (*it)[N_POINTS];
tile.bands[Z_MAX][idx] = (*it)[Z_MAX];
tile.bands[Z_MIN][idx] = (*it)[Z_MIN];
tile.bands[Z_MEAN][idx] = (*it)[Z_MEAN];
tile.bands[VARIANCE][idx] = (*it)[VARIANCE];
tile.bands[TIME][idx] = (*it)[TIME];
tile.bands[DIST_SQ][idx] = (*it)[DIST_SQ];
it++;
}
const auto& utm = meta.point_pix2utm( sx * sw, sy * sh);
// update map transform used for merging the pointcloud
tile.set_transform(utm[0], utm[1], meta.get_scale_x(), meta.get_scale_y());
tile.save( tilepath(current[0] + sx, current[1] + sy) );
}
/**
* Merge a point cloud in the internal model
*
* @param cloud: point cloud in the custom frame
* @param inter: an internal container of cells
*/
void atlaas::rasterize(const points& cloud, cells_info_t& inter) const {
size_t index;
float z_mean, n_pts, new_z;
// merge point-cloud in internal structure
for (const auto& point : cloud) {
index = meta.index_custom(point[0], point[1]);
if (index >= inter.size() )
continue; // point is outside the map
auto& info = inter[ index ];
new_z = point[2];
n_pts = info[N_POINTS];
if (n_pts < 1) {
info[N_POINTS] = 1;
info[Z_MAX] = new_z;
info[Z_MIN] = new_z;
info[Z_MEAN] = new_z;
info[VARIANCE] = 0;
info[DIST_SQ] = distance_sq(sensor_xy, {{point[0], point[1]}});
} else {
z_mean = info[Z_MEAN];
// increment N_POINTS
info[N_POINTS]++;
// update Z_MAX
if (new_z > info[Z_MAX])
info[Z_MAX] = new_z;
// update Z_MIN
if (new_z < info[Z_MIN])
info[Z_MIN] = new_z;
/* Incremental mean and variance updates (according to Knuth's bible,
Vol. 2, section 4.2.2). The actual variance will later be divided
by the number of samples plus 1. */
info[Z_MEAN] = (z_mean * n_pts + new_z) / info[N_POINTS];
info[VARIANCE] += (new_z - z_mean) * (new_z - info[Z_MEAN]);
}
}
}
/**
* Merge dynamic dtm
*/
void atlaas::merge() {
bool is_vertical;
size_t index = 0;
float time_ref = get_reference_time();
auto it = internal.begin();
for (auto& dyninfo : dyninter) {
if ( dyninfo[N_POINTS] > 0 ) {
/* compute the real variance (according to Knuth's bible) */
if (dyninfo[N_POINTS] > 2)
dyninfo[VARIANCE] /= dyninfo[N_POINTS] - 1;
is_vertical = dyninfo[VARIANCE] > variance_threshold;
if ( (*it)[N_POINTS] < 1 || dyninfo[N_POINTS] > 2 &&
(*it)[DIST_SQ] - dyninfo[DIST_SQ] > 25 ) {
// init
*it = dyninfo;
} else if ( is_vertical == (*it)[VARIANCE] > variance_threshold) {
// same state
// if the cells are flat and differ more than 10cm, swap
if (!is_vertical && (( (*it)[Z_MEAN] - dyninfo[Z_MEAN] ) > 0.1 )) {
gndinter[index] = *it;
*it = dyninfo;
// TODO (*it)[DYNAMIC] += 1.0;
} else {
merge(*it, dyninfo);
}
} else if ( is_vertical ) {
// was flat, backup the cell in ground swap
gndinter[index] = *it;
*it = dyninfo;
// TODO (*it)[DYNAMIC] += 1.0;
} else {
// was vertical, revert ground and merge
*it = gndinter[index];
merge(*it, dyninfo);
// TODO (*it)[DYNAMIC] += 1.0;
// TODO gndinter[index] = zeros; ???
}
(*it)[TIME] = time_ref;
}
it++;
index++;
}
}
/**
* Merge the two cells src and dst into dst
*/
void atlaas::merge(cell_info_t& dst, const cell_info_t& src) const {
if ( dst[N_POINTS] < 1 ) {
dst = src;
return;
}
float z_mean, new_n_pts;
new_n_pts = src[N_POINTS] + dst[N_POINTS];
z_mean = dst[Z_MEAN];
if (dst[Z_MAX] < src[Z_MAX])
dst[Z_MAX] = src[Z_MAX];
if (dst[Z_MIN] > src[Z_MIN])
dst[Z_MIN] = src[Z_MIN];
dst[Z_MEAN] = ( (z_mean * dst[N_POINTS]) + (src[Z_MEAN] * src[N_POINTS]) )
/ new_n_pts;
// compute the global variance
dst[VARIANCE] = ( src[VARIANCE] * (src[N_POINTS] - 1)
+ dst[VARIANCE] * (dst[N_POINTS] - 1)
) / (new_n_pts - 1);
dst[N_POINTS] = new_n_pts;
}
} // namespace atlaas
| [
"pierrick.koch@gmail.com"
] | pierrick.koch@gmail.com |
8f362ef52f46483a6e4f705bde4eda4df0546d3a | 0ba8576e02f77c413dec6dccdfd85c1b76b356ba | /nypc파티.cpp | b794cecf310a3c5a246717ab029e36bf89163336 | [] | no_license | ltnscp9028/C_plus_plus | 2fb99fac7595c8cad34aecced4695849f4bfa50d | 92d6d89e3250735c9ee7fc49ee0f1726bb9b2e2f | refs/heads/master | 2022-04-30T08:22:49.036614 | 2022-04-19T20:28:21 | 2022-04-19T20:28:21 | 205,290,886 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | cpp | #include<bits/stdc++.h>
using namespace std;
int arr[100050];
int n,q,w;
vector<int>v[200005];
set<int>s;
set<int>::iterator it;
void LB(){
}
main(){
scanf("%d %d",&n,&q);
for(int i=1;i<=n;i++){
scanf("%d",&arr[i]);
s.insert(arr[i]);
v[arr[i]].push_back(i);
}
//n upperbound - lowerbound
for(int i=0;i<q;i++){
int fs,fe,ss,se;
int asd=0;
//1 4
scanf("%d %d %d %d",&fs,&fe,&ss,&se);
for(it=s.begin();it!=s.end();it++){
//1,2,3,4(set s)
int iitt = *it;
auto onep = lower_bound(v[iitt].begin(),v[iitt].end(),fs);
auto twop = lower_bound(v[iitt].begin(),v[iitt].end(),ss);
auto vend= v[iitt].end();
if((*onep>fe || onep==vend) && *twop<=se && twop!= vend ){
asd = 1;
break;
}
if((*twop>se || twop==vend) && *onep<=fe && onep!= vend ){
asd = 1;
break;
}
}
puts(asd==1 ? "NO" : "YES");
}
}
| [
"ltnscp9028@gmail.com"
] | ltnscp9028@gmail.com |
478878c8ee6994ddbb77e237942b0dcfff263191 | cb6c5cf210f7da4c42fe547adeb26800ec2dc33d | /src/swf/intersection.h | af80124a4c35481915797366a622d01651b1faef | [] | no_license | magnusl/FlashPlayer | c4fd4ae00089f68eb549ab9bc5bc7a76cc169a99 | 57c873edea93e8fbf989d46c6fd29203293db5f6 | refs/heads/master | 2020-03-07T10:16:41.267126 | 2018-03-30T12:57:06 | 2018-03-30T12:57:06 | 127,427,652 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | #include <vector>
#include "gfxShape.h"
namespace swf
{
namespace gfx
{
bool isPathInside(const std::vector<Edge_t> & a_OuterEdges, const std::vector<Edge_t> & a_InnerEdges);
bool isPointInside(const Point_t<int32_t> & a_Point, const std::vector<Edge_t> & a_Edges);
bool TestPointTwips(const Shape_t & a_Shape, Point_t<int32_t> & a_Point);
}
} | [
"magnus586@hotmail.com"
] | magnus586@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.