blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f066c5cdad92a1b3bf44986cea46e9a01a0187a | 0d3a915c65a4d8468303eda569ce6bcb0d4d1157 | /OpenFOAM/ERCOFTAC-SIG15/case09.3/0/omega | 7050151fed8ad1fdc66a746e2b50a81c4199b517 | [] | no_license | opencae/VandV.old | 5efc515f26e989713aab602eb43aaa215ba80fda | b5aec159b9a205366e4c5bf4851f4868290f8ef8 | refs/heads/master | 2021-07-20T02:31:08.658938 | 2017-10-30T07:35:02 | 2017-10-30T07:35:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
object omega;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 -1 0 0 0 0];
internalField uniform 110.805;
boundaryField
{
inlet
{
type fixedValue;
value uniform 110.805;
}
outlet
{
type zeroGradient;
}
synthetic
{
type fixedValue;
value uniform 137.13364595545134818288;
}
wall
{
type omegaWallFunction;
value $internalField;
}
front
{
type empty;
}
}
// ************************************************************************* //
| [
"masashi.imano@gmail.com"
] | masashi.imano@gmail.com | |
5f19ea7947a8938ed9042f17b7af9fab413100fb | fca22e8e83e1026ae09cec9194a43e3f883c44cb | /ui/views/widget/native_widget_private.h | a56e5a6db851cd62800fb21bfed2694f9ecabeb3 | [
"BSD-3-Clause"
] | permissive | Chingliu/WTL-DUI | 409a1001f3b8a9b3ab86c51adeb128f27d0439cd | 232638c56378a8b2e621e8403be939d34d3c91a0 | refs/heads/master | 2021-01-15T14:24:00.135731 | 2013-08-14T08:00:20 | 2013-08-14T08:00:20 | 14,512,988 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,027 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
#pragma once
#include "base/string16.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/ime/input_method_delegate.h"
#include "ui/views/widget/native_widget.h"
namespace gfx {
class Rect;
}
namespace ui {
class OSExchangeData;
}
namespace views {
class InputMethod;
class TooltipManager;
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetPrivate interface
//
// A NativeWidget subclass internal to views that provides Widget a conduit for
// communication with a backend-specific native widget implementation.
//
// Many of the methods here are pass-thrus for Widget, and as such there is no
// documentation for them here. In that case, see methods of the same name in
// widget.h.
//
// IMPORTANT: This type is intended for use only by the views system and for
// NativeWidget implementations. This file should not be included
// in code that does not fall into one of these use cases.
//
class VIEWS_EXPORT NativeWidgetPrivate : public NativeWidget,
public internal::InputMethodDelegate {
public:
virtual ~NativeWidgetPrivate() {}
// Creates an appropriate default NativeWidgetPrivate implementation for the
// current OS/circumstance.
static NativeWidgetPrivate* CreateNativeWidget(
internal::NativeWidgetDelegate* delegate);
static NativeWidgetPrivate* GetNativeWidgetForNativeView(
gfx::NativeView native_view);
static NativeWidgetPrivate* GetNativeWidgetForNativeWindow(
gfx::NativeWindow native_window);
// Retrieves the top NativeWidgetPrivate in the hierarchy containing the given
// NativeView, or NULL if there is no NativeWidgetPrivate that contains it.
static NativeWidgetPrivate* GetTopLevelNativeWidget(
gfx::NativeView native_view);
static void GetAllChildWidgets(gfx::NativeView native_view,
Widget::Widgets* children);
static void ReparentNativeView(gfx::NativeView native_view,
gfx::NativeView new_parent);
// Returns true if any mouse button is currently down.
static bool IsMouseButtonDown();
// Initializes the NativeWidget.
virtual void InitNativeWidget(const Widget::InitParams& params) = 0;
// Returns a NonClientFrameView for the widget's NonClientView, or NULL if
// the NativeWidget wants no special NonClientFrameView.
virtual NonClientFrameView* CreateNonClientFrameView() = 0;
virtual void UpdateFrameAfterFrameChange() = 0;
virtual bool ShouldUseNativeFrame() const = 0;
virtual void FrameTypeChanged() = 0;
// Returns the Widget associated with this NativeWidget. This function is
// guaranteed to return non-NULL for the lifetime of the NativeWidget.
virtual Widget* GetWidget() = 0;
virtual const Widget* GetWidget() const = 0;
// Returns the NativeView/Window associated with this NativeWidget.
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
// Returns the topmost Widget in a hierarchy.
virtual Widget* GetTopLevelWidget() = 0;
// Returns the Compositor, or NULL if there isn't one associated with this
// NativeWidget.
virtual const ui::Compositor* GetCompositor() const = 0;
virtual ui::Compositor* GetCompositor() = 0;
// See description in View for details.
virtual void CalculateOffsetToAncestorWithLayer(gfx::Point* offset,
ui::Layer** layer_parent) = 0;
// Notifies the NativeWidget that a view was removed from the Widget's view
// hierarchy.
virtual void ViewRemoved(View* view) = 0;
// Sets/Gets a native window property on the underlying native window object.
// Returns NULL if the property does not exist. Setting the property value to
// NULL removes the property.
virtual void SetNativeWindowProperty(const char* name, void* value) = 0;
virtual void* GetNativeWindowProperty(const char* name) const = 0;
// Returns the native widget's tooltip manager. Called from the View hierarchy
// to update tooltips.
virtual TooltipManager* GetTooltipManager() const = 0;
// Returns true if a system screen reader is active for the NativeWidget.
virtual bool IsScreenReaderActive() const = 0;
// Notify native Accessibility clients of an event.
virtual void SendNativeAccessibilityEvent(
View* view,
ui::AccessibilityTypes::Event event_type) = 0;
// Sets or releases event capturing for this native widget.
virtual void SetCapture() = 0;
virtual void ReleaseCapture() = 0;
// Returns true if this native widget is capturing events.
virtual bool HasCapture() const = 0;
// Returns the InputMethod for this native widget.
// Note that all widgets in a widget hierarchy share the same input method.
// TODO(suzhe): rename to GetInputMethod() when NativeWidget implementation
// class doesn't inherit Widget anymore.
virtual InputMethod* CreateInputMethod() = 0;
// Centers the window and sizes it to the specified size.
virtual void CenterWindow(const gfx::Size& size) = 0;
// Retrieves the window's current restored bounds and "show" state, for
// persisting.
virtual void GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const = 0;
// Sets the NativeWindow title.
virtual void SetWindowTitle(const string16& title) = 0;
// Sets the Window icons. |window_icon| is a 16x16 icon suitable for use in
// a title bar. |app_icon| is a larger size for use in the host environment
// app switching UI.
virtual void SetWindowIcons(const SkBitmap& window_icon,
const SkBitmap& app_icon) = 0;
// Update native accessibility properties on the native window.
virtual void SetAccessibleName(const string16& name) = 0;
virtual void SetAccessibleRole(ui::AccessibilityTypes::Role role) = 0;
virtual void SetAccessibleState(ui::AccessibilityTypes::State state) = 0;
// Initializes the modal type of the window to |modal_type|. Called from
// NativeWidgetDelegate::OnNativeWidgetCreated() before the widget is
// initially parented.
virtual void InitModalType(ui::ModalType modal_type) = 0;
// See method documentation in Widget.
virtual gfx::Rect GetWindowScreenBounds() const = 0;
virtual gfx::Rect GetClientAreaScreenBounds() const = 0;
virtual gfx::Rect GetRestoredBounds() const = 0;
virtual void SetBounds(const gfx::Rect& bounds) = 0;
virtual void SetSize(const gfx::Size& size) = 0;
virtual void StackAbove(gfx::NativeView native_view) = 0;
virtual void StackAtTop() = 0;
virtual void StackBelow(gfx::NativeView native_view) = 0;
virtual void SetShape(gfx::NativeRegion shape) = 0;
virtual void Close() = 0;
virtual void CloseNow() = 0;
virtual void Show() = 0;
virtual void Hide() = 0;
// Invoked if the initial show should maximize the window. |restored_bounds|
// is the bounds of the window when not maximized.
virtual void ShowMaximizedWithBounds(const gfx::Rect& restored_bounds) = 0;
virtual void ShowWithWindowState(ui::WindowShowState show_state) = 0;
virtual bool IsVisible() const = 0;
virtual void Activate() = 0;
virtual void Deactivate() = 0;
virtual bool IsActive() const = 0;
virtual void SetAlwaysOnTop(bool always_on_top) = 0;
virtual void Maximize() = 0;
virtual void Minimize() = 0;
virtual bool IsMaximized() const = 0;
virtual bool IsMinimized() const = 0;
virtual void Restore() = 0;
virtual void SetFullscreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetOpacity(unsigned char opacity) = 0;
virtual void SetUseDragFrame(bool use_drag_frame) = 0;
virtual void FlashFrame(bool flash) = 0;
virtual bool IsAccessibleWidget() const = 0;
virtual void RunShellDrag(View* view,
const ui::OSExchangeData& data,
const gfx::Point& location,
int operation) = 0;
virtual void SchedulePaintInRect(const gfx::Rect& rect) = 0;
virtual void SetCursor(gfx::NativeCursor cursor) = 0;
virtual void ClearNativeFocus() = 0;
virtual void FocusNativeView(gfx::NativeView native_view) = 0;
virtual gfx::Rect GetWorkAreaBoundsInScreen() const = 0;
virtual void SetInactiveRenderingDisabled(bool value) = 0;
virtual Widget::MoveLoopResult RunMoveLoop() = 0;
virtual void EndMoveLoop() = 0;
virtual void SetVisibilityChangedAnimationsEnabled(bool value) = 0;
// Overridden from NativeWidget:
virtual internal::NativeWidgetPrivate* AsNativeWidgetPrivate() OVERRIDE;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
| [
"xshellinit@qq.com"
] | xshellinit@qq.com |
f2a1adf8c9ed2f157d059353fef66b28f6e7ed41 | b3cb24f908158ee51b611a7b9ce545ac0636f994 | /MyWebServer/Thread/CountDownLatch.h | 21b3403dc7c91fd864cdf8390fa00a358e79a669 | [] | no_license | VVZzzz/MyWebServer | 1a5f52a39dbbace4cf5b5e502adfbfb6bf8b1ef1 | 831a3791ce1ed95b6db19edb28735a324c1e5fa5 | refs/heads/master | 2021-02-15T13:13:17.071419 | 2020-06-14T03:30:25 | 2020-06-14T03:30:25 | 244,901,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | h | #pragma once
#include "Condition.h"
#include "Mutex.h"
#include "noncopyable.h"
//倒计时
//参考muduo2.2节讲述的CountDownLatch
//这里主要是为了当主线程开启子线程时,子线程一定已接收线程数据并开始真正执行函数时,
//主线程才从外层start返回
class CountDownLatch : noncopyable
{
public:
explicit CountDownLatch(int count); //倒数几次
void wait(); //等待计数变为0
void countDown(); //计数减一
int getCount() const;
private:
//注意此处mutex_为mutable变量,原因是
//对于getCount这个const函数,虽然是const但我们需要
//对mutex进行加锁才能读count,mutable使得在const函数中
//也能修改这个变量
mutable MutexLock mutex_;
Condition condition_;
int count_;
}; | [
"vvzz_run@outlook.com"
] | vvzz_run@outlook.com |
7914a9514426bf69ab2cc54b6251246baba9b7a6 | f99f44821c0f5b7a1a4e694031f142f29d5359cf | /tunnel/redirector/NatsToSocksRedirector.h | f255f52cb57c948e6c00c819167cec2bcc542f3c | [] | no_license | MaksimTimokhin/nats_tunnel | 44e69e87acd04628f25cdfd667a092e268cf1a02 | a96caf46cced058d94d1bb285487fc36bea45707 | refs/heads/master | 2022-03-06T15:17:49.409981 | 2019-10-20T10:24:57 | 2019-10-20T10:24:57 | 216,343,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | h | #pragma once
#include <nats/Nats.h>
#include <atomic>
#include <shared_mutex>
#include <thread>
#include "ConcurrentHashMap.hpp"
#include "IRedirector.h"
#include "SocketDescriptors.h"
class NatsToSocksRedirector : public IRedirector {
public:
NatsToSocksRedirector(nats::Client *nats_client, std::string listen_subject,
int threads_count = kDefaultConcurrencyLevel)
: nats_client_(nats_client),
listen_subject_(std::move(listen_subject)),
threads_count_(threads_count),
sockets_(0, threads_count) {
}
void Start() override;
void Stop() override;
bool IsRunning() const override;
bool AddSocket(const std::string &socket_id,
const SocketDescriptor &socket_descriptor) override;
bool RemoveSocket(const std::string &socket_id) override;
private:
nats::Client *nats_client_;
const std::string listen_subject_;
const int threads_count_;
ConcurrentHashMap<std::string, SocketDescriptor> sockets_;
std::vector<std::thread> workers_;
mutable std::shared_mutex run_mutex_; // these fields are described in tunnel/Connector.h
std::atomic_bool is_running_{false};
};
| [
"maximtim@outlook.com"
] | maximtim@outlook.com |
98007d6047b6a3a83d54290af5c5c74ad48586c0 | 4f1e23621aca6628315e8b521324c9cca76518a4 | /tests/System/ContextGroupTimeoutTests.cpp | 85376d65930df74e9ff5db0ac63f12303dfb60a6 | [] | no_license | blockchain-next/TycheCash | 63c5eccfe14041277f48530d73f311b242835b5f | 16cd2a9c6ab2a6670672663f86bb99551cc0c69a | refs/heads/master | 2021-05-03T05:10:37.783962 | 2019-03-23T04:28:13 | 2019-03-23T04:28:13 | 120,633,620 | 6 | 6 | null | 2019-03-23T04:28:14 | 2018-02-07T15:34:04 | C++ | UTF-8 | C++ | false | false | 1,966 | cpp | // Copyright (c) 2017-2018 The TycheCash developers ; Originally forked from Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <gtest/gtest.h>
#include <System/ContextGroupTimeout.h>
#include <System/InterruptedException.h>
using namespace System;
class ContextGroupTimeoutTest : public testing::Test {
public:
ContextGroupTimeoutTest() : contextGroup(dispatcher), timer(dispatcher) {
}
Dispatcher dispatcher;
ContextGroup contextGroup;
Timer timer;
};
TEST_F(ContextGroupTimeoutTest, timeoutHappens) {
auto begin = std::chrono::high_resolution_clock::now();
ContextGroupTimeout groupTimeout(dispatcher, contextGroup, std::chrono::milliseconds(100));
contextGroup.spawn([&] {
EXPECT_THROW(Timer(dispatcher).sleep(std::chrono::milliseconds(200)), InterruptedException);
});
contextGroup.wait();
ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - begin).count(), 50);
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(150));
}
TEST_F(ContextGroupTimeoutTest, timeoutSkipped) {
auto begin = std::chrono::high_resolution_clock::now();
{
ContextGroupTimeout op(dispatcher, contextGroup, std::chrono::milliseconds(200));
contextGroup.spawn([&] {
EXPECT_NO_THROW(Timer(dispatcher).sleep(std::chrono::milliseconds(100)));
});
contextGroup.wait();
}
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) > std::chrono::milliseconds(50));
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(150));
}
TEST_F(ContextGroupTimeoutTest, noOperation) {
ContextGroupTimeout op(dispatcher, contextGroup, std::chrono::milliseconds(100));
}
| [
"tychecoin@gmail.com"
] | tychecoin@gmail.com |
f5b0e1fb95b84fca9ac300d1810c92e42ae8290a | d2f523d4ae9f17e833aacd995775eeaa4ef4195d | /main.cpp~ | c1753553b774d6d5a6db5b99fee2133237d3a449 | [] | no_license | Pixie18/PROJET_C- | 8b540d685d42598ea3041c1420a10ad82fcb090b | cd09a3539025f61814485be6b6cee18eceb7cb5c | refs/heads/master | 2020-03-16T20:19:03.840362 | 2018-05-10T21:18:23 | 2018-05-10T21:18:23 | 132,954,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | #include <QApplication>
#include <QtGui>
#include "main_window.hpp"
#include "client.hpp"
#include "controller.hpp"
int main(int argc, char* argv[]){
// Récupération des arguments
if (argc != 4){
qDebug() << "Usage: " << argv[0] << " username server port";
return -1;
}
QString username(argv[1]);
QString server(argv[2]);
int port = QString(argv[3]).toInt();
// Mise en place de l'application
QApplication app(argc, argv);
MainWindow window;
Client client(username, server, port);
Controller controller(&client, &window);
// Lancement de la boucle événementielle.
return app.exec();
}
| [
"noreply@github.com"
] | Pixie18.noreply@github.com | |
97aece57286f3dd270619d37c84f011a33c2563a | 5d3cb198de3736ec95578c0445269ef3d6acd720 | /Strings/Manacher.cpp | b9a245f6b2991c1dcfaa8f2b7fbff3f1b56ae17e | [] | no_license | amb-lucas/Competitive-Programming | 23dac2432065f2d7769a3169d614848c0f15ded4 | 1ded61fc0788112599c295090e3c8cfa5690970c | refs/heads/master | 2021-06-08T20:45:22.904434 | 2021-05-11T20:44:43 | 2021-05-11T20:44:43 | 178,054,679 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 747 | cpp |
vector<int> findOdd(string &str){
int n = str.size();
vector<int> d1(n);
for(int i=0, l=0, r=-1, k; i<n; i++){
if(i>r) k = 1;
else k = min(d1[l+r-i], r-i+1);
while(0 <= i-k && i+k < n && str[i-k] == str[i+k]) k++;
d1[i] = k--;
if(i+k > r){
l = i-k;
r = i+k;
}
}
return d1;
}
vector<int> findEven(string &str){
int n = str.size();
vector<int> d2(n);
for(int i=0, l=0, r=-1, k; i<n; i++){
if(i > r) k = 0;
else k = min(d2[l+r-i+1], r-i+1);
while(0 <= i-k-1 && i+k < n && str[i-k-1] == str[i+k]) k++;
d2[i] = k--;
if(i+k > r){
l = i-k-1;
r = i+k;
}
}
return d2;
}
| [
"noreply@github.com"
] | amb-lucas.noreply@github.com |
edf5950b9d670f750427c70963e4063a91ce2a11 | 7429210b640c3769c5f64a4f405706bd0adc911b | /Demo/Demo/InfoWindow.h | 66e453ea8d6a5d6251dfcb7458d331a77b25bbfa | [] | no_license | AleyshaBradbury/Demo | e2447187834f878541903b5147e349b06bf60266 | e997c81bc22bf7bea241da93b0c63109da6d708c | refs/heads/master | 2023-05-14T09:58:14.362255 | 2021-06-03T13:59:11 | 2021-06-03T13:59:11 | 356,325,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | h | #pragma once
#include <SFML/Graphics.hpp>
#include "Button.h"
#include "GeneralFunctions.h"
using namespace std;
class Player;
class InfoWindow : public sf::RectangleShape
{
public:
InfoWindow();
void InitialisePlayer(Player* player);
void Collsion();
void Render();
bool isAlive();
void SetAlive(bool a);
void ShowWindow(bool reward, int num);
void SetStats();
private:
struct StatChanges {
bool alive = true;
sf::Text stat_text_;
Button* button_ = nullptr;
};
void InitialiseStatChanges();
StatChanges InitialiseStatChangesDetails(float positionY, StatChanges stat);
bool HandleStatChange(sf::Vector2f mouse_position);
bool alive_ = false;
bool reward_ = false;
Player* player_ = nullptr;
std::vector<StatChanges> Stat_Changes_;
Button* skip_button_ = nullptr;
sf::Vector2f window_size_ = sf::Vector2f(450.0f, 350.0f);
sf::Vector2f button_size_ = sf::Vector2f(80.0f, 40.0f);
int num_ = 0;
};
| [
"1702233@uad.ac.uk"
] | 1702233@uad.ac.uk |
d2df341491408ea57c81d9244072aad8feca8a2c | b244bc8b106c69a613592cb4237a90d7e012693a | /src/base/device/packedbuffers/chunkgeometry.cpp | e00342dfca417aebd08c830d12d5d4067d7d0a57 | [] | no_license | nodegraph/ngsinternal | f84239345cfefc6db231b5863f76c1ffdc7c9c0b | 66b274d009a42825caa3fe91afa84464cfdefca8 | refs/heads/master | 2023-03-20T20:59:06.763829 | 2021-03-07T19:14:15 | 2021-03-07T19:14:15 | 345,431,910 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,507 | cpp | #include <base/device/deviceheadersgl.h>
#include <base/device/devicedebug.h>
#include <base/device/packedbuffers/chunkgeometry.h>
#include <boost/math/special_functions/round.hpp>
#include <cmath>
#include <cassert>
#include <iostream>
namespace ngs {
ChunkGeometry::ChunkGeometry(ElementID id) :
// Dimensions. - default is a 512 x 512 allocation.
_x(0), _y(0), _width(512), _height(512), _depth(1), _num_channels(4), _dim_interpretation(2),
// Element Type.
_element_id(id), // float is the default
// Size and Alignment
_alignment_bytes(1)
{
}
int ChunkGeometry::get_element_size_bytes(ElementID elementId){
switch (elementId) {
case FloatElement:
return sizeof(float);
case HalfElement:
return sizeof(half);
case IntElement:
return sizeof(int);
case UIntElement:
return sizeof(unsigned int);
case ShortElement:
return sizeof(short);
case UShortElement:
return sizeof(unsigned short);
case CharElement:
return sizeof(char);
case UCharElement:
return sizeof(unsigned char);
default:
assert(false && "an unknown element type was encountered");
}
return 0;
}
int ChunkGeometry::get_element_size_bytes() const {
return get_element_size_bytes(_element_id);
}
bool ChunkGeometry::element_is_signed() const {
switch (_element_id) {
case FloatElement:
return true;
case HalfElement:
return true;
case IntElement:
return true;
case UIntElement:
return false;
case ShortElement:
return true;
case UShortElement:
return false;
case CharElement:
return true;
case UCharElement:
return false;
default:
assert(false && "an unknown element type was encountered");
}
return false;
}
// Size related getters.
int ChunkGeometry::get_num_elements() const {
return _width * _height * _depth * _num_channels;
}
int ChunkGeometry::get_num_bytes() const {
return get_width_stride_bytes()*_height*_depth;
}
int ChunkGeometry::get_width_stride_bytes() const {
if (get_element_size_bytes() >= _alignment_bytes) {
return _num_channels * _width * get_element_size_bytes();
}
float a = static_cast<float>(_alignment_bytes);
float s = static_cast<float>(get_element_size_bytes());
float n = static_cast<float>(_num_channels);
float l = static_cast<float>(_width);
float stride = boost::math::round((a / s) * ceilf(n * l * s / a) * s);
return static_cast<int>(stride);
}
int ChunkGeometry::get_height_stride_bytes() const {
return _height * get_width_stride_bytes();
}
int ChunkGeometry::get_byte_offset(int column, int row, int plane) const {
return (plane * get_height_stride_bytes()) + (row * get_width_stride_bytes())
+ (column * _num_channels * get_element_size_bytes());
}
// Operators.
bool ChunkGeometry::operator!=(const ChunkGeometry& right) const {
return !operator==(right);
}
bool ChunkGeometry::operator==(const ChunkGeometry& right) const {
if (_x != right._x) {
return false;
}
if (_y != right._y) {
return false;
}
if (_width != right._width) {
return false;
}
if (_height != right._height) {
return false;
}
if (_depth != right._depth) {
return false;
}
if (_num_channels != right._num_channels) {
return false;
}
if (_dim_interpretation != right._dim_interpretation) {
return false;
}
if (_element_id != right._element_id) {
return false;
}
if (_alignment_bytes != right._alignment_bytes) {
return false;
}
return true;
}
}
| [
"nodegraph@gmail.com"
] | nodegraph@gmail.com |
e11dc4ff1be6fdae4947a35f034b7cbd76284c53 | fff51ce0217560150ceaa5da9bcaf61a78da122c | /200125_FuD_CodeComplete.ino | 813cb0a875a1bd36a37632a82e007b85849fdf76 | [] | no_license | Laurenz-Cz/ToolTime-1 | 9a7c8b8df23449558f685501f8980e3a402bae1f | bd622f22552e2c8972d44901e515748e3ac94309 | refs/heads/master | 2020-12-09T06:58:56.422589 | 2020-02-14T19:58:57 | 2020-02-14T19:58:57 | 233,229,924 | 2 | 1 | null | 2020-01-11T22:00:21 | 2020-01-11T12:42:11 | null | UTF-8 | C++ | false | false | 10,675 | ino | int degree = 0; //gibt an, in welcher Stellung sich das Fahrzeug befindet - Start ist bei 0
//--------------Motoren-----------------------------------
//Motoren
int in1 = 8; //rechte Seite
int in2 = 7; //rechte Seite
int in3 = 4; //linke Seite
int in4 = 2; //linke Seite
//Drehzahlregulierung
int ENA = 3; //Drehzahlregelung rechte Seite
int ENB = 9; //Drehzahlregelung linke Seite
int SPEED = 150; //Analoge Werte geben die Geschwindigkeit zum geradeaus Fahren vor (0-255)
int SpeedDrehen = 200; //Analoge Werte geben die Geschwindigkeit für das Drehen des Fahrzeugs vor (0-255)
//--------------Ultraschallsensoren---------------------------
// Ultraschallsensor vorne
int trigPin1 = 12;
int echoPin1 = 13;
long dauer1 = 0;
long frontSensor = 0;
// Ultraschallsensor rechts
int trigPin2 = 10;
int echoPin2 = 11;
long dauer2 = 0;
long rightSensor = 0;
// Ultraschallsensor links
int trigPin3 = 6;
int echoPin3 = 5;
long dauer3 = 0;
long leftSensor = 0;
void setup()
{
//------------------MOTORSTEUERUNG--------------------------
pinMode(in1, OUTPUT); //rechte Seite
pinMode(in2, OUTPUT); //rechte Seite
pinMode(in3, OUTPUT); //linke Seite
pinMode(in4, OUTPUT); //linke Seite
//------------------Ultraschallsensoren-----------------------
// Ultraschallsensor 1
//Serial.begin(9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
// Ultraschallsensor 2
//Serial.begin(9600);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
// Ultraschallsensor 3
//Serial.begin(9600);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
}
void loop()
{
//---------------Ultraschallsensoren-----------------------
//Ultraschallsensor vorne
digitalWrite(trigPin1, LOW);
delay(5);
digitalWrite(trigPin1, HIGH);
delay(10);
digitalWrite(trigPin1, LOW);
dauer1 = pulseIn(echoPin1, HIGH);
frontSensor = (dauer1/2) * 0.03432;
//Serial.print(frontSensor);
//Serial.print(" cm");
delay(100);
// Ultraschallsensor rechts
digitalWrite(trigPin2, LOW);
delay(5);
digitalWrite(trigPin2, HIGH);
delay(10);
digitalWrite(trigPin2, LOW);
dauer2 = pulseIn(echoPin2, HIGH);
rightSensor = (dauer2/2) * 0.03432;
//Serial.print(rightSensor);
//Serial.print(" cm");
delay(100);
// Ultraschallsensor links
digitalWrite(trigPin3, LOW);
delay(5);
digitalWrite(trigPin3, HIGH);
delay(10);
digitalWrite(trigPin3, LOW);
dauer3 = pulseIn(echoPin3, HIGH);
leftSensor = (dauer3/2) * 0.03432;
//Serial.print(leftSensor);
//Serial.print(" cm");
delay(100);
if(frontSensor <= 30) //war vorher auf Wert 20 eingestellet (Reaktion zu langsam)
{
//Fahrzeug bleibt stehen
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(2000);
if(leftSensor <= 20 && rightSensor > 20)
{
if(degree == 0)
{
degree -= 90;
//drehen nach rechts um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(650);
}
else if(degree == -90)
{
degree = 90;
//drehen nach rechts um 180 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(1300); //Doppeltes Delay
}
else if(degree == 90)
{
degree = 0;
// drehen nach rechts um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(650);
}
}
else if(rightSensor <= 20 && leftSensor > 20)
{
if(degree == 0)
{
degree += 90;
// drehen nach links um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(650);
}
else if(degree == 90)
{
degree -= 90;
//drehen nach links um 180 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(1300); //Doppelter Delay
}
else if(degree == -90)
{
degree = 0;
// drehen nach links um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(650);
}
}
else if(rightSensor <= 20 && leftSensor <= 20)
{
if(degree == 90)
{
degree -= 90;
//drehen nach rechts um 180 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(1300); //doppelt Delay
}
else if(degree = -90)
{
degree = 90;
//drehen nach links um 180 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(1300); //Doppeltes Delay
}
}
else if(rightSensor > 20 && leftSensor > 20)
{
if(degree == 90)
{
degree = 0;
//drehen nach rechts um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(650);
}
else if(degree == -90)
{
degree = 0;
//drehen nach links um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(650);
}
}
else
{
if(degree == 0)
{
randomTurn();
}
}
}
//Folgender Abschnitt: Wenn der Abstand zu allen Sensoren größer als der definierte Wert ist, dann dreht das Fahrzeug wieder auf 0°
//und fährt anschließend wieder gerade aus. (Wenn es auf -90° steht --> Drehung nach links, bei +90° --> Drehung nach rechts)
else if(frontSensor > 20 && leftSensor > 20 && rightSensor > 20)
{
if(degree == 90)
{
degree = 0;
//drehen nach rechts um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(650);
//-------------TESTBLOCK----------------------
// vorwärts fahren
analogWrite(ENA, SPEED); //speed 0 - 255
analogWrite(ENB, SPEED); //speed 0 - 255
digitalWrite(in1, LOW); //linke Seite
digitalWrite(in2, HIGH); //linke Seite
digitalWrite(in3, LOW); //rechte Seite
digitalWrite(in4, HIGH); //rechte Seite
//--------------------------------------------
}
else if(degree == -90)
{
degree = 0;
//drehen nach links um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(650);
//-------------TESTBLOCK----------------------
// vorwärts fahren
analogWrite(ENA, SPEED); //speed 0 - 255
analogWrite(ENB, SPEED); //speed 0 - 255
digitalWrite(in1, LOW); //linke Seite
digitalWrite(in2, HIGH); //linke Seite
digitalWrite(in3, LOW); //rechte Seite
digitalWrite(in4, HIGH); //rechte Seite
//--------------------------------------------
}
else
{
//-------------TESTBLOCK----------------------
// vorwärts fahren
analogWrite(ENA, SPEED); //speed 0 - 255
analogWrite(ENB, SPEED); //speed 0 - 255
digitalWrite(in1, LOW); //linke Seite
digitalWrite(in2, HIGH); //linke Seite
digitalWrite(in3, LOW); //rechte Seite
digitalWrite(in4, HIGH); //rechte Seite
//--------------------------------------------
}
}
}
void randomTurn()
{
int rand = random(0,2);
if(rand == 0)
{
degree += 90;
//Fahrzeug bleibt stehen
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(2000);
//drehen nach links um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(650);
}
else
{
degree -= 90;
//Fahrzeug bleibt stehen
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(2000);
// drehen nach rechts um 90 grad
analogWrite(ENA, SpeedDrehen); //speed 0 - 255
analogWrite(ENB, SpeedDrehen); //speed 0 - 255
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(650);
}
}
| [
"noreply@github.com"
] | Laurenz-Cz.noreply@github.com |
9da3fdd6ea8473e9d386455d9501b964d3c92eab | 455ecd26f1439cd4a44856c743b01d711e3805b6 | /java/include/com.google.android.gms.gcm.R_attr.hpp | e81d4a19d1be9d21ce8c53d2439402e8689e5a93 | [] | no_license | lbguilherme/duvidovc-app | 00662bf024f82a842c808673109b30fe2b70e727 | f7c86ea812d2ae8dd892918b65ea429e9906531c | refs/heads/master | 2021-03-24T09:17:17.834080 | 2015-09-08T02:32:44 | 2015-09-08T02:32:44 | 33,072,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | hpp | #pragma once
#include "../src/java-core.hpp"
#include <jni.h>
#include <cstdint>
#include <memory>
#include <vector>
#include "java.lang.Object.hpp"
namespace com {
namespace google {
namespace android {
namespace gms {
namespace gcm {
class R_attr : public virtual ::java::lang::Object {
public:
static jclass _class;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreorder"
explicit R_attr(jobject _obj) : ::java::lang::Object(_obj) {}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreorder"
R_attr(const ::com::google::android::gms::gcm::R_attr& x) : ::java::lang::Object((jobject)0) {obj = x.obj;}
R_attr(::com::google::android::gms::gcm::R_attr&& x) : ::java::lang::Object((jobject)0) {obj = x.obj; x.obj = JavaObjectHolder((jobject)0);}
#pragma GCC diagnostic pop
::com::google::android::gms::gcm::R_attr& operator=(const ::com::google::android::gms::gcm::R_attr& x) {obj = x.obj; return *this;}
::com::google::android::gms::gcm::R_attr& operator=(::com::google::android::gms::gcm::R_attr&& x) {obj = std::move(x.obj); return *this;}
R_attr();
};
}
}
}
}
}
| [
"dev@lbguilherme.com"
] | dev@lbguilherme.com |
c2ac775349adf18c78a9df6f32a7672e81550557 | bb09a2d17f6ea34ed6f5180c4c2820a4dff8d0a2 | /NotesWindow.cpp | 0150e41dcb944d7983e321fa74ba15329d448d20 | [
"MIT"
] | permissive | rafaelgc/SplitQt | cb942c2c89f83a4dbe7d0c30622d66b598c79e5a | c4dae474fff0bba14f0f64ff485e3e3e19a9f399 | refs/heads/master | 2021-09-16T12:42:18.822445 | 2018-06-20T21:34:03 | 2018-06-20T21:34:03 | 60,573,508 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,110 | cpp | #include "NotesWindow.hpp"
NotesWindow::NotesWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::NotesWindow){
ui->setupUi(this);
currentNoteId = -1;
modified = false;
ui->splitter->setStretchFactor(0,1);
ui->splitter->setStretchFactor(1,2);
orderByName = new SmallButton(this);
orderByName->setText(tr("Nombre"));
orderByName->setCheckable(true);
orderByName->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
orderByName->setToolTip(tr("Ordenar por nombre."));
ui->horizontalLayout->addWidget(orderByName);
orderByDate = new SmallButton(this);
orderByDate->setText(tr("Fecha"));
orderByDate->setCheckable(true);
orderByDate->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
orderByDate->setToolTip(tr("Ordenar por fecha de creación."));
ui->horizontalLayout->addWidget(orderByDate);
desc = new SmallButton(this);
desc->setText(tr("Desc."));
desc->setCheckable(true);
desc->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
desc->setColors(QColor(238,228,176));
desc->setToolTip(tr("Ordenar de manera descendente."));
ui->horizontalLayout->addWidget(desc);
orderByDate->setChecked(true);
notesList = ui->notesList;
notesList->installEventFilter(this);
contextMenu = new QMenu(this);
QAction *deleteAction = new QAction(QIcon(":/icons/trash.png"),tr("Eliminar"),contextMenu);
contextMenu->addAction(deleteAction);
QObject::connect(deleteAction,SIGNAL(triggered()),this,SLOT(deleteSelectedNote()));
QObject::connect(orderByName,SIGNAL(clicked()),this,SLOT(orderByNameClicked()));
QObject::connect(orderByDate,SIGNAL(clicked()),this,SLOT(orderByDateClicked()));
QObject::connect(desc,SIGNAL(clicked()),this,SLOT(orderDesc()));
QObject::connect(notesList,SIGNAL(itemSelectionChanged()),this,SLOT(selectionChanged()));
QObject::connect(notesList,SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this,SLOT(currentItemChanged(QListWidgetItem*,QListWidgetItem*)));
QObject::connect(ui->noteEdit,SIGNAL(textChanged()),this,SLOT(textModified()));
QObject::connect(ui->actionSave,SIGNAL(triggered()),this,SLOT(save()));
QObject::connect(ui->actionNewNote,SIGNAL(triggered()),this,SLOT(newNote()));
}
NotesWindow::~NotesWindow()
{
delete ui;
}
void NotesWindow::show()
{
QMainWindow::show();
notesDb.connect();
constructList();
cleanAndBlockEdition(true);
}
void NotesWindow::closeEvent(QCloseEvent *)
{
notesDb.close();
}
bool NotesWindow::eventFilter(QObject *object, QEvent *event)
{
if (event->type()==QEvent::ContextMenu){
QContextMenuEvent *contextEvent = static_cast<QContextMenuEvent*>(event);
QListWidgetItem *item = notesList->itemAt(contextEvent->pos());
if (item){
contextMenu->exec(notesList->mapToGlobal(contextEvent->pos()));
}
}
return QObject::eventFilter(object,event);
}
void NotesWindow::orderByNameClicked()
{
orderByDate->setChecked(!orderByName->isChecked());
constructList();
}
void NotesWindow::orderByDateClicked(){
orderByName->setChecked(!orderByDate->isChecked());
constructList();
}
void NotesWindow::orderDesc()
{
constructList();
}
void NotesWindow::selectionChanged()
{
cleanAndBlockEdition(false);
int index = notesList->currentRow();
if (index>=0){
int nextNoteId = notesList->item(index)->data(Qt::UserRole).toInt();
if (nextNoteId!=currentNoteId){
currentNoteId = nextNoteId;
ui->noteEdit->blockSignals(true);
ui->noteEdit->setPlainText(notesDb.getNoteString(currentNoteId));
ui->noteEdit->blockSignals(false);
}
}
}
void NotesWindow::currentItemChanged(QListWidgetItem *current, QListWidgetItem *)
{
if (currentNoteId!=current->data(Qt::UserRole).toInt()){
askForSave();
}
}
void NotesWindow::save()
{
if (currentNoteId<0){
return;
}
if (notesDb.updateNote(currentNoteId,ui->noteEdit->toPlainText()))
{
setModified(false);
}
}
void NotesWindow::textModified()
{
setModified(true);
}
void NotesWindow::deleteSelectedNote()
{
currentNoteId = -1;
notesDb.deleteNote(notesList->currentItem()->data(Qt::UserRole).toInt());
constructList();
cleanAndBlockEdition(true);
}
void NotesWindow::newNote()
{
askForSave();
bool ok = false;
QString name = QInputDialog::getText(this,tr("Nombre"),tr("Nombre de la nota: "),QLineEdit::Normal,"",&ok);
if (ok){
bool insertOk = false;
currentNoteId = notesDb.newNote(name,&insertOk);
if (insertOk){
constructList();
//Se selecciona la nota.
for (int i = 0; i<notesList->count(); i++){
if (notesList->item(i)->data(Qt::UserRole).toInt()==currentNoteId){
notesList->setCurrentRow(i);
break;
}
}
//Se limpia el textedit.
ui->noteEdit->blockSignals(true);
ui->noteEdit->clear();
ui->noteEdit->blockSignals(false);
}
else{
QMessageBox::warning(this,tr("Error"),tr("No se pudo crear la nota."));
}
}
}
void NotesWindow::setModified(bool modified)
{
setWindowModified(modified);
this->modified = modified;
}
void NotesWindow::cleanAndBlockEdition(bool state)
{
ui->noteEdit->blockSignals(true);
ui->noteEdit->setEnabled(!state);
if (state){
ui->noteEdit->clear();
}
ui->noteEdit->blockSignals(false);
}
void NotesWindow::cleanList()
{
for (int i=notesList->count(); i>0; i--){
delete notesList->takeItem(i-1);
}
}
void NotesWindow::makeList()
{
int orderSelected = NotesDbInterface::ORDER_BY_DATE;
if (orderByName->isChecked()){
orderSelected = NotesDbInterface::ORDER_BY_NAME;
}
std::vector<NoteData> notesData = notesDb.getNotesInfo(orderSelected,desc->isChecked());
for (unsigned int i = 0; i<notesData.size(); i++){
QListWidgetItem *item = new QListWidgetItem(notesData[i].getName());
item->setToolTip(notesData[i].getDate().toString(QLocale::system().dateFormat()));
item->setData(Qt::UserRole,QVariant(notesData[i].getId()));
notesList->addItem(item);
}
}
void NotesWindow::constructList()
{
notesList->blockSignals(true);
cleanList();
makeList();
notesList->blockSignals(false);
}
void NotesWindow::askForSave()
{
if (modified && notesList->currentRow()>=0){
int result = QMessageBox::information(this,
tr("Confirmación"),
tr("La nota actual no está guardada, ¿quieres guardarla?"),
QDialogButtonBox::Yes,
QDialogButtonBox::No);
if (result==QDialogButtonBox::No){
modified = false;
}
else if (result==QDialogButtonBox::Yes){
save();
}
}
}
| [
"rafag.1858@hotmail.es"
] | rafag.1858@hotmail.es |
49fa6968b2a76de9b895d6ef0956e59ad16aff3f | 33035c05aad9bca0b0cefd67529bdd70399a9e04 | /src/boost_spirit_home_karma_nonterminal_rule.hpp | f66e4c91deebfd8e41dfb7e78ef2caab84d75c5e | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | elvisbugs/BoostForArduino | 7e2427ded5fd030231918524f6a91554085a8e64 | b8c912bf671868e2182aa703ed34076c59acf474 | refs/heads/master | 2023-03-25T13:11:58.527671 | 2021-03-27T02:37:29 | 2021-03-27T02:37:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56 | hpp | #include <boost/spirit/home/karma/nonterminal/rule.hpp>
| [
"k@kekyo.net"
] | k@kekyo.net |
4b5a808acbde871701270d333c00aa39e9f249dd | f556d0c63551f3e3cd138f01b081dfd299c57225 | /WDL/IPlug/CParamSmooth.h | 943af739f082424318ea190e90aa167ca9de4dff | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | michaeldonovan/wdl-md | 78e0a2f59b32e8b0d7547bec7ca5815e5893a16c | 2148c1ef7a327dabcf9c6281c3bb425e0e064503 | refs/heads/master | 2021-01-15T16:14:47.438742 | 2016-04-20T00:01:00 | 2016-04-20T00:01:00 | 49,093,121 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | //
// CParamSmooth.h
//
// Author: alexirae@gmail.com
// from musicdsp.org archives
//
#ifndef CParamSmooth_hpp
#define CParamSmooth_hpp
class CParamSmooth
{
public:
CParamSmooth(double smoothingTimeInMs, double samplingRate);
CParamSmooth();
~CParamSmooth(){};
void init(double smoothingTimeInMs, double samplingRate);
double process(double in);
private:
double a, b, z;
};
#endif /* CParamSmooth_hpp */
| [
"michael.donovan.audio@gmail.com"
] | michael.donovan.audio@gmail.com |
f8eb30dea42ae92db6c7af2bbc8242343244cd80 | 65e8a94511a192439e9c21206d88a0a03d978a5f | /Q4.cpp | d7c3f28c80f2fc55639c806b6da5b6a52773b8ca | [] | no_license | lihao1992/CodingInterview | 6af1b8f745f19230652121bcf7b1c77aeeda9212 | 34f386780071ec1d65d768fea8232032108ce022 | refs/heads/master | 2021-01-22T08:02:24.867406 | 2017-09-25T10:56:49 | 2017-09-25T10:56:49 | 92,597,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | /*二维数组的查找*/
#include<iostream>
#include<vector>
using namespace std;
// 从矩阵的最右上角的数开始与target比较,每次可以删掉一行或和一列,这样就可以缩小查找范围
bool findNumber(vector<int>& matrix, int m, int n, int target){
bool found = false;
if(matrix.empty() || m<=0 || n<=0)
return false;
int i = 0;
int j = n-1;
while(i<m && j>=0){
if(matrix[i*n+j] == target){
found = true;
break;
}
if(matrix[i*n+j] < target){
++i;
}
else
--j;
}
return found;
}
int main(){
vector<int> matrix = {1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
cout << findNumber(matrix, 4, 4, 9) << endl;
//return findNumber(matrix, 4, 4, 7);
return 0;
} | [
"lihao_me@sina.com"
] | lihao_me@sina.com |
8662ec186893b1eff01cce69e8d939e3f580055d | aade1e73011f72554e3bd7f13b6934386daf5313 | /Contest/Petrozavodsk/Winter2020Day5/B.cpp | 62789338c34581296f557fc0f0b8ce70e26181c7 | [] | no_license | edisonhello/waynedisonitau123 | 3a57bc595cb6a17fc37154ed0ec246b145ab8b32 | 48658467ae94e60ef36cab51a36d784c4144b565 | refs/heads/master | 2022-09-21T04:24:11.154204 | 2022-09-18T15:23:47 | 2022-09-18T15:23:47 | 101,478,520 | 34 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,588 | cpp | #include <bits/stdc++.h>
using namespace std;
#define double long double
double val[1 << 22];
vector<int> o;
vector<double> x;
vector<double> y;
int main() {
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
for (int mask = 2; mask < (1 << n); ++mask) {
o.clear();
int nn = __builtin_popcount(mask);
for (int i = 0; i < n; ++i) if (mask & (1 << i)) o.push_back(i);
if (nn == 1) continue;
x.resize(nn);
y.resize(nn);
for (int i = 0; i < nn; ++i) {
x[i] = val[mask ^ (1 << o[i])];
y[i] = a[o[i]];
}
if (nn > 10) {
bool same = 1;
for (int i = 1; i < nn; ++i) {
if (a[o[i - 1]] != a[o[i]]) same = 0;
}
if (same) { val[mask] = a[o[0]]; continue; }
}
double zu = 1, zd = 0;
for (int i = 0; i < nn; ++i) if (x[i] < y[i]) {
zu += y[i] / (x[i] - y[i]);
zd += 1 / (x[i] - y[i]);
}
double z = zu / zd;
while (true) {
double nzu = 1, nzd = 0;
for (int i = 0; i < nn; ++i) if (x[i] < y[i] && y[i] > z) {
nzu += y[i] / (x[i] - y[i]);
nzd += 1 / (x[i] - y[i]);
}
double nz = nzu / nzd;
if (abs(nz - z) < 1e-9) break;
z = nz;
// cerr << "x = ";
// for (double i : x) cerr << i << ' ';
// cerr << endl;
// cerr << "y = ";
// for (double i : y) cerr << i << ' ';
// cerr << endl;
// cerr << "z = " << z << " = " << nzu << " / " << nzd << endl;
}
val[mask] = z;
}
cout << fixed << setprecision(12);
cout << val[(1 << n) - 1] << '\n';
}
| [
"edisonhello@hotmail.com"
] | edisonhello@hotmail.com |
d4791cd546ab536da919e70531b63c0586f62ab7 | e21e405049fbd7c1973a8f89bc508db788622540 | /main.cpp | aff8f8fce17bfc3ba6a22b28ff929e4a82539e30 | [] | no_license | ajhalme/human-patterns | 734def9f59c353d93a3b65ecec1d141f01a79786 | adecd472509c8991e43d30419cc2ea4d8cb8a2d2 | refs/heads/master | 2020-08-03T09:53:32.872408 | 2019-10-13T20:52:38 | 2019-10-13T20:52:38 | 211,709,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | cpp | #include "humanpatterns.h"
#include <QApplication>
using namespace std;
int main(int argc, char *argv[])
{
cout << "HUMAN PATTERNS - Antti Halme, 2019" << endl;
QString configFile("/home/ajhalme/projects/humanpatterns-qt/config.yaml");
vector<string> args(argv, argv+argc);
if (args.size() == 2) {
configFile = QString::fromStdString(args[1]);
} else if (args.size() > 2) {
cout << "Too many parameters. Terminating." << endl;
return -1;
}
cout << "Loading configuration from: ";
cout << configFile.toStdString();
cout << endl;
QApplication a(argc, argv);
HumanPatterns w(nullptr, &configFile);
w.show();
return a.exec();
}
| [
"antti.halme@iki.fi"
] | antti.halme@iki.fi |
1bf95e26ad8b89b0e22a737085eb06cc11be0454 | b668ffd1b625b7a5b30b69ce2df39e4adb9aadc9 | /cpp08/ex01/main.cpp | e2f3db7dd921a08f72f424b269a550bff8f4b2be | [] | no_license | felixoff/C_plus_plus_by_Felx | 4c1e6cd1c2da5ecb15b5f302b4bc7221c3973c4d | 005cb015aaf2d296b3785527af9d63192840947c | refs/heads/master | 2023-04-19T16:41:16.965742 | 2021-05-23T12:05:29 | 2021-05-23T12:05:29 | 356,531,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | cpp | #include "span.hpp"
int main()
{
Span sp = Span(23000);
sp.addNumber(5);
sp.addNumber(3);
sp.addNumber(17);
sp.addNumber(9);
sp.addNumber(11);
std::cout << sp.shortestSpan() << std::endl;
std::cout << sp.longestSpan() << std::endl;
std::multiset<int> multi_pulti_set;
for (int i = 20; i < 10020; i++)
multi_pulti_set.insert(i);
std::multiset<int>::iterator start = multi_pulti_set.begin();
std::multiset<int>::iterator end = multi_pulti_set.end();
sp.addNumber(start,end);
std::cout << sp.shortestSpan() << std::endl;
std::cout << sp.longestSpan() << std::endl;
} | [
"sjennett@ox-a5.msk.21-school.ru"
] | sjennett@ox-a5.msk.21-school.ru |
a9e3195d3399f3cc575edd6f3562201aa28e0a57 | 4b3c6e82b99aaf798aff751675324c64807f7947 | /cocos2d/cocos/platform/android/glextwrapperandroid.cpp | f1ed421856c023880b53fa9f1077a5786b38bb7f | [] | no_license | liang94huai/SimpleTest | 70fd82bfa2481aebd24809e268666db6801ce4db | 1975c5c671117797a4b780a3f78c81c54f42d1ac | refs/heads/master | 2020-05-02T12:33:46.182330 | 2018-09-05T01:46:41 | 2018-09-05T01:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,125 | cpp | #define glClearDepth glClearDepthf
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define glGenVertexArrays glGenVertexArraysOES
#define glBindVertexArray glBindVertexArrayOES
#define glMapBuffer glMapBufferOES
#define glUnmapBuffer glUnmapBufferOES
#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES
#define GL_WRITE_ONLY GL_WRITE_ONLY_OES
// GL_GLEXT_PROTOTYPES isn't defined in glplatform.h on android ndk r7
// we manually define it here
#include <GLES2/gl2platform.h>
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES 1
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#undef GL_OES_EGL_image
#undef GL_OES_get_program_binary
#undef GL_OES_mapbuffer
#undef GL_OES_texture_3D
#undef GL_OES_vertex_array_object
#undef GL_AMD_performance_monitor
#undef GL_EXT_discard_framebuffer
#undef GL_EXT_multi_draw_arrays
#undef GL_IMG_multisampled_render_to_texture
#undef GL_NV_fence
#undef GL_NV_coverage_sample
#undef GL_QCOM_driver_control
#undef GL_QCOM_extended_get
#undef GL_QCOM_extended_get2
#undef GL_QCOM_tiled_rendering
#include "glwrapperandroid.h"
#include "glextwrapperandroid.h"
#include "base/CCMacros.h"
#include <pthread.h>
extern pthread_t MAIN_THREAD_ID;
//extern void printBackTraceTologToConsole(const char* data);
//bool gl_error = false;
void doCommonGLCheck() {
#if 0
if( MAIN_THREAD_ID != pthread_self()){
cocos2d::log("cocos2d: GL thread error" );
return;
}
GLenum err = glGetError();
if( err != GL_NO_ERROR )
{
cocos2d::log("cocos2d: GL error:0x%04X",err );
return;
}
#endif
}
//void if_glwrapper::glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image)
//{
// ::glEGLImageTargetTexture2DOES(target,image);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image)
//{
// ::glEGLImageTargetRenderbufferStorageOES(target,image);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary)
//{
// ::glGetProgramBinaryOES(program,bufSize,length,binaryFormat,binary);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glProgramBinaryOES (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length)
//{
// ::glProgramBinaryOES(program,binaryFormat,binary,length);
// doCommonGLCheck();
//}
//
//
void* if_glwrapper::glMapBufferOES (GLenum target, GLenum access)
{
void* ret =
::glMapBufferOES(target,access);
doCommonGLCheck();
return ret;
}
GLboolean if_glwrapper::glUnmapBufferOES (GLenum target)
{
GLboolean ret =
::glUnmapBufferOES(target);
doCommonGLCheck();
return ret;
}
//
//
//void if_glwrapper::glGetBufferPointervOES (GLenum target, GLenum pname, GLvoid** params)
//{
// ::glGetBufferPointervOES(target,pname,params);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels)
//{
// ::glTexImage3DOES(target,level,internalformat,width,height,depth,border,format,type,pixels);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels)
//{
// ::glTexSubImage3DOES(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
//{
// ::glCopyTexSubImage3DOES(target,level,xoffset,yoffset,zoffset,x,y,width,height);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data)
//{
// ::glCompressedTexImage3DOES(target,level,internalformat,width,height,depth,border,imageSize,data);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data)
//{
// ::glCompressedTexSubImage3DOES(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset)
//{
// ::glFramebufferTexture3DOES(target,attachment,textarget,texture,level,zoffset);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glBindVertexArrayOES (GLuint array)
//{
// ::glBindVertexArrayOES(array);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays)
//{
// ::glDeleteVertexArraysOES(n,arrays);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGenVertexArraysOES (GLsizei n, GLuint *arrays)
//{
// ::glGenVertexArraysOES(n,arrays);
// doCommonGLCheck();
//}
//
//
//GLboolean if_glwrapper::glIsVertexArrayOES (GLuint array)
//{
// GLboolean ret =
// ::glIsVertexArrayOES(array);
// doCommonGLCheck();
// return ret;
//}
//
//
//void if_glwrapper::glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups)
//{
// ::glGetPerfMonitorGroupsAMD(numGroups,groupsSize,groups);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters)
//{
// ::glGetPerfMonitorCountersAMD(group,numCounters,maxActiveCounters,counterSize,counters);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString)
//{
// ::glGetPerfMonitorGroupStringAMD(group,bufSize,length,groupString);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString)
//{
// ::glGetPerfMonitorCounterStringAMD(group,counter,bufSize,length,counterString);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, GLvoid *data)
//{
// ::glGetPerfMonitorCounterInfoAMD(group,counter,pname,data);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors)
//{
// ::glGenPerfMonitorsAMD(n,monitors);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors)
//{
// ::glDeletePerfMonitorsAMD(n,monitors);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList)
//{
// ::glSelectPerfMonitorCountersAMD(monitor,enable,group,numCounters,countersList);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glBeginPerfMonitorAMD (GLuint monitor)
//{
// ::glBeginPerfMonitorAMD(monitor);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glEndPerfMonitorAMD (GLuint monitor)
//{
// ::glEndPerfMonitorAMD(monitor);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten)
//{
// ::glGetPerfMonitorCounterDataAMD(monitor,pname,dataSize,data,bytesWritten);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments)
//{
// ::glDiscardFramebufferEXT(target,numAttachments,attachments);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glMultiDrawArraysEXT (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount)
//{
// ::glMultiDrawArraysEXT(mode,first,count,primcount);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount)
//{
// ::glMultiDrawElementsEXT(mode,count,type,indices,primcount);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glRenderbufferStorageMultisampleIMG (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
//{
// ::glRenderbufferStorageMultisampleIMG(target,samples,internalformat,width,height);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glFramebufferTexture2DMultisampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples)
//{
// ::glFramebufferTexture2DMultisampleIMG(target,attachment,textarget,texture,level,samples);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glDeleteFencesNV (GLsizei n, const GLuint *fences)
//{
// ::glDeleteFencesNV(n,fences);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGenFencesNV (GLsizei n, GLuint *fences)
//{
// ::glGenFencesNV(n,fences);
// doCommonGLCheck();
//}
//
//
//GLboolean if_glwrapper::glIsFenceNV (GLuint fence)
//{
// GLboolean ret =
// ::glIsFenceNV(fence);
// doCommonGLCheck();
// return ret;
//}
//
//
//GLboolean if_glwrapper::glTestFenceNV (GLuint fence)
//{
// GLboolean ret =
// ::glTestFenceNV(fence);
// doCommonGLCheck();
// return ret;
//}
//
//
//void if_glwrapper::glGetFenceivNV (GLuint fence, GLenum pname, GLint *params)
//{
// ::glGetFenceivNV(fence,pname,params);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glFinishFenceNV (GLuint fence)
//{
// ::glFinishFenceNV(fence);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glSetFenceNV (GLuint fence, GLenum condition)
//{
// ::glSetFenceNV(fence,condition);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glCoverageMaskNV (GLboolean mask)
//{
// ::glCoverageMaskNV(mask);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glCoverageOperationNV (GLenum operation)
//{
// ::glCoverageOperationNV(operation);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls)
//{
// ::glGetDriverControlsQCOM(num,size,driverControls);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString)
//{
// ::glGetDriverControlStringQCOM(driverControl,bufSize,length,driverControlString);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glEnableDriverControlQCOM (GLuint driverControl)
//{
// ::glEnableDriverControlQCOM(driverControl);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glDisableDriverControlQCOM (GLuint driverControl)
//{
// ::glDisableDriverControlQCOM(driverControl);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures)
//{
// ::glExtGetTexturesQCOM(textures,maxTextures,numTextures);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers)
//{
// ::glExtGetBuffersQCOM(buffers,maxBuffers,numBuffers);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers)
//{
// ::glExtGetRenderbuffersQCOM(renderbuffers,maxRenderbuffers,numRenderbuffers);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers)
//{
// ::glExtGetFramebuffersQCOM(framebuffers,maxFramebuffers,numFramebuffers);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params)
//{
// ::glExtGetTexLevelParameterivQCOM(texture,face,level,pname,params);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param)
//{
// ::glExtTexObjectStateOverrideiQCOM(target,pname,param);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid *texels)
//{
// ::glExtGetTexSubImageQCOM(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,texels);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetBufferPointervQCOM (GLenum target, GLvoid **params)
//{
// ::glExtGetBufferPointervQCOM(target,params);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders)
//{
// ::glExtGetShadersQCOM(shaders,maxShaders,numShaders);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms)
//{
// ::glExtGetProgramsQCOM(programs,maxPrograms,numPrograms);
// doCommonGLCheck();
//}
//
//
//GLboolean if_glwrapper::glExtIsProgramBinaryQCOM (GLuint program)
//{
// GLboolean ret =
// ::glExtIsProgramBinaryQCOM(program);
// doCommonGLCheck();
// return ret;
//}
//
//
//void if_glwrapper::glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length)
//{
// ::glExtGetProgramBinarySourceQCOM(program,shadertype,source,length);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask)
//{
// ::glStartTilingQCOM(x,y,width,height,preserveMask);
// doCommonGLCheck();
//}
//
//
//void if_glwrapper::glEndTilingQCOM (GLbitfield preserveMask)
//{
// ::glEndTilingQCOM(preserveMask);
// doCommonGLCheck();
//}
| [
"liudi@im30.net"
] | liudi@im30.net |
1d2a0401292f470533a069d5631d1fcfefd31d45 | 99739874971c9e19f50c64caaf23bea54e713826 | /String/String-test.cpp | 7fda8776245821316bb783116c625b3979baeb57 | [] | no_license | virtualdust/CPP_EXERCISE | dcc030a6300ed22589b737ae669bd82b1be22550 | fc1722f1c32369a43c6eea6ddbdf4e082042edd0 | refs/heads/master | 2023-06-09T02:35:28.565966 | 2021-07-06T11:09:30 | 2021-07-06T11:09:30 | 174,671,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | cpp | /*************************************************************************
> File Name: String-test.cpp
> Author: ylvis
> Mail: ylvis1024@gmail.com
> Created Time: 日 12/ 8 02:25:10 2019
************************************************************************/
#include<iostream>
#include "String.h"
using namespace std;
int main(){
//before
String s1;
String s2("hello");
cout << (void*)&(s1.get_c_str()[0]) << endl;
cout << (void*)&(s2.get_c_str()[0]) << endl;
//after assignment
s1 = s2;
cout << (void*)&(s1.get_c_str()[0]) << endl;
cout << (void*)&(s2.get_c_str()[0]) << endl;
}
| [
"ylvis1024@gmail.com"
] | ylvis1024@gmail.com |
5a9f17a19f209e329fe82804f04cb11e6007648d | 85467fe8d791de2b641a34120e4d0a2fb68d2165 | /shared/html5/NetHTTP_HTML5.cpp | 068c4f5e807211aa046283646635eb7d40d131b7 | [
"XFree86-1.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bexpg000/ArduboySimulator | 5d4602009e28624015ea84b9379a76ae048e0050 | 8aaa69ec975d4e5c0bd61ab94570fb16960aab83 | refs/heads/master | 2021-06-27T19:10:47.190077 | 2017-09-13T01:27:04 | 2017-09-13T01:27:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,642 | cpp | #include "PlatformPrecomp.h"
/*
Note: html5 builds automatically use NetHTTP_HTML5.cpp instead of NetHTTP.cpp. The usage is the same but internally they use
emscripten_async_wget2_data. Due to javascript security issues, you can only download files on website the .html is hosted on, unless
cross scripting privileges are setup.
*/
#include "Network/NetHTTP.h"
#include "Network/NetUtils.h"
#include "BaseApp.h"
#include "util/TextScanner.h"
#include <emscripten/emscripten.h>
#define NET_END_MARK_CHECK_DELAY_MS 333
#define C_END_DOWNLOAD_MARKER_STRING "RTENDMARKERBS1001"
#define C_DEFAULT_IDLE_TIMEOUT_MS (25*1000)
NetHTTP::NetHTTP()
{
m_emscriptenWgetHandle = -1;
m_pFile = NULL;
Reset(true);
}
void NetHTTP::KillConnectionIfNeeded()
{
if (m_emscriptenWgetHandle != -1)
{
#ifdef _DEBUG
LogMsg("Aborting emscripten wget handle %d",m_emscriptenWgetHandle );
#endif
emscripten_async_wget2_abort(m_emscriptenWgetHandle);
m_emscriptenWgetHandle = -1;
}
}
NetHTTP::~NetHTTP()
{
KillConnectionIfNeeded();
if (m_pFile)
{
fclose(m_pFile);
RemoveFile(m_fileName);
m_pFile = NULL;
}
}
void NetHTTP::Reset(bool bClearPostdata)
{
KillConnectionIfNeeded();
if (m_pFile)
{
fclose(m_pFile);
RemoveFile(m_fileName);
m_pFile = NULL;
}
m_endOfDataSignal = END_OF_DATA_SIGNAL_RTSOFT_MARKER; //don't change the default, Seth's software relies on it
m_state = STATE_IDLE;
m_error = ERROR_NONE;
m_timer = 0;
m_idleTimeOutMS = C_DEFAULT_IDLE_TIMEOUT_MS;
m_expectedFileBytes= 0;
m_downloadData.clear();
m_replyHeader.clear();
m_query.clear();
if (bClearPostdata)
{
m_postData.clear();
}
m_bytesWrittenToFile = 0;
}
void NetHTTP::Setup( string serverName, int port, string query, eEndOfDataSignal eodSignal )
{
if (!IsInString(serverName, "://"))
{
//add http so it won't freak later
serverName = "http://"+serverName;
}
m_endOfDataSignal = eodSignal;
m_serverName = serverName;
m_port = port;
m_query = query;
}
bool NetHTTP::SetFileOutput(const string &fName)
{
assert(!m_pFile);
m_pFile = fopen(fName.c_str(), "wb");
m_fileName = fName; //save for later so we can delete this file if anything goes wrong
if (!m_pFile)
{
LogMsg("Unable to write to %s", m_fileName.c_str());
OnError(ERROR_WRITING_FILE);
return false;
}
return true;
}
bool NetHTTP::AddPostData( const string &name, const byte *pData, int len/*=-1*/ )
{
if (m_postData.length() != 0)
{
//adding to other named post data, so we need a separator
m_postData += "&";
}
//at this stage we need to encode it for safe html transfer, before we get the length
/*
URLEncoder encoder;
encoder.encodeData((const byte*)name.c_str(), name.length(), m_postData);
m_postData += '=';
if (len == -1) len = strlen((const char*) pData);
encoder.encodeData(pData, len, m_postData);
*/
m_postData += name+'='+string((char*)pData);
#ifdef _DEBUG
/*
LogMsg("Postdata is now %s", m_postData.c_str());
URLDecoder decoder;
string encoded;
encoder.encodeData(pData, len, encoded);
vector<byte> decoded = decoder.decodeData(encoded);
int sizeOfDecoded = decoded.size();
LogMsg("Size of decoded should be %u", decoded.size());
assert(memcmp(pData, &decoded[0], len) == 0 && "Encryption of string error, they don't match");
*/
#endif
return true;
}
string NetHTTP::BuildHTTPHeader()
{
return "";
}
bool NetHTTP::Start()
{
m_bytesWrittenToFile = 0;
m_error = ERROR_NONE;
m_downloadData.clear();
m_downloadHeader.clear();
m_expectedFileBytes = 0;
#ifdef _DEBUG
LogMsg("Opening %s on port %d with postdata of %s", m_serverName.c_str(), m_port, m_postData.c_str());
#endif
string header, stCommand;
if (m_postData.length() > 0)
{
stCommand = "POST";
} else
{
stCommand = "GET";
}
string finalURL = m_serverName+"/"+m_query;
m_emscriptenWgetHandle = emscripten_async_wget2_data( finalURL.c_str(), stCommand.c_str(), m_postData.c_str(), this, 1, NetHTTP::onLoaded, NetHTTP::onError, NetHTTP::onProgress);
#ifdef _DEBUG
LogMsg("Final URL is %s. Postdata is %s. Handle is %d", finalURL.c_str(), m_postData.c_str(), m_emscriptenWgetHandle);
#endif
return true;
}
bool CheckCharVectorForString(vector<char> &v, string marker, int *pIndexOfMarkerEndPosOut)
{
int correctCount = 0;
assert(marker.size() > 0);
for (unsigned int i=0; i < v.size(); i++)
{
if (v[i] == marker[correctCount] )
{
//so far so good
correctCount++;
if (correctCount == marker.size())
{
if (pIndexOfMarkerEndPosOut)
{
*pIndexOfMarkerEndPosOut = i+1;
}
return true; //found it
}
} else
{
//nah
correctCount = 0;
}
}
return false;
}
int NetHTTP::ScanDownloadedHeader()
{
TextScanner t(m_downloadHeader.c_str());
string temp = t.GetParmString("Content-Length", 1, ":");
m_expectedFileBytes = atoi(temp.c_str());
int resultCode = atol(SeparateStringSTL(t.m_lines[0], 1, ' ').c_str());
switch (resultCode)
{
case 404:
OnError(ERROR_404_FILE_NOT_FOUND);
break;
case 301: //moved permanently
case 302: //moved temporarily
string url = t.GetParmString("Location:",1, " ");
if (!url.empty())
{
string domain;
string request;
int port = 80;
BreakDownURLIntoPieces(url, domain, request, port);
string fNameTemp = m_fileName;
Reset(false); //end connection, setup new one
if (!fNameTemp.empty())
{
SetFileOutput(fNameTemp);
}
Setup(domain, port, request, m_endOfDataSignal);
Start();
}
}
return resultCode;
}
void NetHTTP::Update()
{
}
void NetHTTP::OnError(eError e)
{
m_error = e;
m_state = STATE_ABORT;
KillConnectionIfNeeded();
}
void NetHTTP::FinishDownload()
{
m_emscriptenWgetHandle = -1;
if (m_pFile)
{
fclose(m_pFile);
m_pFile = NULL;
m_state = STATE_FINISHED;
return;
}
m_state = STATE_FINISHED;
}
const byte * NetHTTP::GetDownloadedData()
{
if (m_downloadData.empty())
{
return NULL;
}
return (const byte*)&m_downloadData[0];
}
int NetHTTP::GetDownloadedBytes()
{
if (m_pFile || m_bytesWrittenToFile != 0)
{
return m_bytesWrittenToFile;
}
if (m_downloadData.size() == 0) return 0;
return m_downloadData.size()-1; //the -1 is for the null we added
}
void NetHTTP::SetBuffer(const char *pData, int byteSize)
{
m_expectedFileBytes = byteSize;
m_downloadData.resize(byteSize+1); //1 extra so we can add a null
memcpy((char*)&m_downloadData[0], pData, byteSize); //never do this at home, kids
m_downloadData[byteSize]=0; //set the NULL too
if (m_endOfDataSignal == END_OF_DATA_SIGNAL_RTSOFT_MARKER)
{
//er.. there has to be a better way then this, but whatever, I don't use rtsoft markers much and when I do it's tiny strings
string temp = (char*)&m_downloadData[0];
//remove the marker
StringReplace(C_END_DOWNLOAD_MARKER_STRING, "",temp);
//move it back
string crap;
m_downloadData = vector<char>(temp.begin(), temp.end());
if (m_downloadData[m_downloadData.size()-1] != 0)
{
m_downloadData.push_back(char(0)); //add the null
}
}
if (m_pFile)
{
fwrite(GetDownloadedData(), GetDownloadedBytes(), 1, m_pFile);
}
}
void NetHTTP::onLoaded( unsigned int handle, void* parent, void * file, unsigned int byteSize)
{
#ifdef _DEBUG
LogMsg("Finished download - got %d bytes", byteSize);
#endif
NetHTTP *pMe = (NetHTTP*)parent;
pMe->SetBuffer((const char*)file, byteSize);
pMe->FinishDownload();
//http* req = reinterpret_cast<http*>(parent);
//req->onLoaded(file);
}
void NetHTTP::onError(unsigned int handle, void* parent, int statuserror, const char *message)
{
//#ifdef _DEBUG
LogMsg("Got error %d (%s) - keep in mind you have to run this from the same website you're downloading from!", statuserror, message);
//#endif
eError error = ERROR_CANT_RESOLVE_URL;
if (statuserror == 404) error = ERROR_404_FILE_NOT_FOUND;
NetHTTP *pMe = (NetHTTP*)parent;
pMe->OnError(error);
}
void NetHTTP::SetProgress(int bytesDownloaded, int totalBytes)
{
m_expectedFileBytes = totalBytes;
m_bytesWrittenToFile = bytesDownloaded;
}
void NetHTTP::onProgress(unsigned int handle, void* parent, int bytesDownloaded, int totalBytes)
{
NetHTTP *pMe = (NetHTTP*)parent;
pMe->SetProgress(bytesDownloaded, totalBytes);
#ifdef _DEBUG
LogMsg("progress %d of %d", bytesDownloaded, totalBytes);
#endif
}
| [
"seth@353e56fe-9613-0410-8469-b96ad8e6f29c"
] | seth@353e56fe-9613-0410-8469-b96ad8e6f29c |
532b0daf53f3e7ded209226c9632c2d741dde96b | 4b64e9be4d95fa4ccc94cb7b4019e9817136c87b | /Code Forces/Code forces Div 2/Code forces A and B and Compilation Errors.cpp | ef4ee4a795863053158c0f68bf537e5f8082afd7 | [] | no_license | hasan032/Competitive-Programming-Solutions | 3eac451a0015dc7ff1ccc424670cfc22a4789daf | b933c68174cf83a702cc5ea17ecedb735c6ed5b9 | refs/heads/master | 2020-03-31T11:45:55.669442 | 2018-10-06T08:26:16 | 2018-10-06T08:26:16 | 152,189,961 | 1 | 0 | null | 2018-10-09T04:57:59 | 2018-10-09T04:57:59 | null | UTF-8 | C++ | false | false | 416 | cpp | #include <iostream>
using namespace std;
int main(void){
int n, sum1= 0, sum2= 0, sum3= 0, temp;
cin>>n;
for(int i= 0; i<n; i++){
cin>>temp;
sum1+= temp;
}
for(int i= 0; i<n-1; i++){
cin>>temp;
sum2+= temp;
}
for(int i= 0; i<n-2; i++){
cin>>temp;
sum3+= temp;
}
cout<< sum1-sum2 <<"\n" << sum2 - sum3 <<"\n";
return 0;
}
| [
"anonta9865@gmail.com"
] | anonta9865@gmail.com |
090015fe2bb613bc502be8d5db338d37c16a3617 | a6cabe4236778f411d9a850d2435a2a24e87de85 | /MameBake3DLib/examples/ThirdPartyLibs/BussIK/MatrixRmn.cpp | 6338ce064b8791a858a3bc5c14f80476e2f470b5 | [] | no_license | lvjunsetup/MameBake3D | 27e447246467e39dc49ae96109a5706359c39c62 | af5e869e8a204aa356f0b061f31ed03fbccb74f3 | refs/heads/master | 2021-09-29T01:44:08.612094 | 2018-11-22T13:24:05 | 2018-11-22T13:24:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,620 | cpp | #include "stdafx.h"
/*
*
* Mathematics Subpackage (VrMath)
*
*
* Author: Samuel R. Buss, sbuss@ucsd.edu.
* Web page: http://math.ucsd.edu/~sbuss/MathCG
*
*
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.
*
*
*/
//
// MatrixRmn.cpp: Matrix over reals (Variable dimensional vector)
//
// Not very sophisticated yet. Needs more functionality
// To do: better handling of resizing.
//
#include "MatrixRmn.h"
MatrixRmn MatrixRmn::WorkMatrix; // Temporary work matrix
// Fill the diagonal entries with the value d. The rest of the matrix is unchanged.
void MatrixRmn::SetDiagonalEntries( double d )
{
long diagLen = Min( NumRows, NumCols );
double* dPtr = x;
for ( ; diagLen>0; diagLen-- ) {
*dPtr = d;
dPtr += NumRows+1;
}
}
// Fill the diagonal entries with values in vector d. The rest of the matrix is unchanged.
void MatrixRmn::SetDiagonalEntries( const VectorRn& d )
{
long diagLen = Min( NumRows, NumCols );
assert ( d.length == diagLen );
double* dPtr = x;
double* from = d.x;
for ( ; diagLen>0; diagLen-- ) {
*dPtr = *(from++);
dPtr += NumRows+1;
}
}
// Fill the superdiagonal entries with the value d. The rest of the matrix is unchanged.
void MatrixRmn::SetSuperDiagonalEntries( double d )
{
long sDiagLen = Min( NumRows, (long)(NumCols-1) );
double* to = x + NumRows;
for ( ; sDiagLen>0; sDiagLen-- ) {
*to = d;
to += NumRows+1;
}
}
// Fill the superdiagonal entries with values in vector d. The rest of the matrix is unchanged.
void MatrixRmn::SetSuperDiagonalEntries( const VectorRn& d )
{
long sDiagLen = Min( (long)(NumRows-1), NumCols );
assert ( sDiagLen == d.length );
double* to = x + NumRows;
double* from = d.x;
for ( ; sDiagLen>0; sDiagLen-- ) {
*to = *(from++);
to += NumRows+1;
}
}
// Fill the subdiagonal entries with the value d. The rest of the matrix is unchanged.
void MatrixRmn::SetSubDiagonalEntries( double d )
{
long sDiagLen = Min( NumRows, NumCols ) - 1;
double* to = x + 1;
for ( ; sDiagLen>0; sDiagLen-- ) {
*to = d;
to += NumRows+1;
}
}
// Fill the subdiagonal entries with values in vector d. The rest of the matrix is unchanged.
void MatrixRmn::SetSubDiagonalEntries( const VectorRn& d )
{
long sDiagLen = Min( NumRows, NumCols ) - 1;
assert ( sDiagLen == d.length );
double* to = x + 1;
double* from = d.x;
for ( ; sDiagLen>0; sDiagLen-- ) {
*to = *(from++);
to += NumRows+1;
}
}
// Set the i-th column equal to d.
void MatrixRmn::SetColumn(long i, const VectorRn& d )
{
assert ( NumRows==d.GetLength() );
double* to = x+i*NumRows;
const double* from = d.x;
for ( i=NumRows; i>0; i-- ) {
*(to++) = *(from++);
}
}
// Set the i-th column equal to d.
void MatrixRmn::SetRow(long i, const VectorRn& d )
{
assert ( NumCols==d.GetLength() );
double* to = x+i;
const double* from = d.x;
for ( i=NumRows; i>0; i-- ) {
*to = *(from++);
to += NumRows;
}
}
// Sets a "linear" portion of the array with the values from a vector d
// The first row and column position are given by startRow, startCol.
// Successive positions are found by using the deltaRow, deltaCol values
// to increment the row and column indices. There is no wrapping around.
void MatrixRmn::SetSequence( const VectorRn& d, long startRow, long startCol, long deltaRow, long deltaCol )
{
long length = d.length;
assert( startRow>=0 && startRow<NumRows && startCol>=0 && startCol<NumCols );
assert( startRow+(length-1)*deltaRow>=0 && startRow+(length-1)*deltaRow<NumRows );
assert( startCol+(length-1)*deltaCol>=0 && startCol+(length-1)*deltaCol<NumCols );
double *to = x + startRow + NumRows*startCol;
double *from = d.x;
long stride = deltaRow + NumRows*deltaCol;
for ( ; length>0; length-- ) {
*to = *(from++);
to += stride;
}
}
// The matrix A is loaded, in into "this" matrix, based at (0,0).
// The size of "this" matrix must be large enough to accomodate A.
// The rest of "this" matrix is left unchanged. It is not filled with zeroes!
void MatrixRmn::LoadAsSubmatrix( const MatrixRmn& A )
{
assert( A.NumRows<=NumRows && A.NumCols<=NumCols );
int extraColStep = NumRows - A.NumRows;
double *to = x;
double *from = A.x;
for ( long i=A.NumCols; i>0; i-- ) { // Copy columns of A, one per time thru loop
for ( long j=A.NumRows; j>0; j-- ) { // Copy all elements of this column of A
*(to++) = *(from++);
}
to += extraColStep;
}
}
// The matrix A is loaded, in transposed order into "this" matrix, based at (0,0).
// The size of "this" matrix must be large enough to accomodate A.
// The rest of "this" matrix is left unchanged. It is not filled with zeroes!
void MatrixRmn::LoadAsSubmatrixTranspose( const MatrixRmn& A )
{
assert( A.NumRows<=NumCols && A.NumCols<=NumRows );
double* rowPtr = x;
double* from = A.x;
for ( long i=A.NumCols; i>0; i-- ) { // Copy columns of A, once per loop
double* to = rowPtr;
for ( long j=A.NumRows; j>0; j-- ) { // Loop copying values from the column of A
*to = *(from++);
to += NumRows;
}
rowPtr ++;
}
}
// Calculate the Frobenius Norm (square root of sum of squares of entries of the matrix)
double MatrixRmn::FrobeniusNorm() const
{
return sqrt( FrobeniusNormSq() );
}
// Multiply this matrix by column vector v.
// Result is column vector "result"
void MatrixRmn::Multiply( const VectorRn& v, VectorRn& result ) const
{
assert ( v.GetLength()==NumCols && result.GetLength()==NumRows );
double* out = result.GetPtr(); // Points to entry in result vector
const double* rowPtr = x; // Points to beginning of next row in matrix
for ( long j = NumRows; j>0; j-- ) {
const double* in = v.GetPtr();
const double* m = rowPtr++;
*out = 0.0f;
for ( long i = NumCols; i>0; i-- ) {
*out += (*(in++)) * (*m);
m += NumRows;
}
out++;
}
}
// Multiply transpose of this matrix by column vector v.
// Result is column vector "result"
// Equivalent to mult by row vector on left
void MatrixRmn::MultiplyTranspose( const VectorRn& v, VectorRn& result ) const
{
assert ( v.GetLength()==NumRows && result.GetLength()==NumCols );
double* out = result.GetPtr(); // Points to entry in result vector
const double* colPtr = x; // Points to beginning of next column in matrix
for ( long i=NumCols; i>0; i-- ) {
const double* in=v.GetPtr();
*out = 0.0f;
for ( long j = NumRows; j>0; j-- ) {
*out += (*(in++)) * (*(colPtr++));
}
out++;
}
}
// Form the dot product of a vector v with the i-th column of the array
double MatrixRmn::DotProductColumn( const VectorRn& v, long colNum ) const
{
assert ( v.GetLength()==NumRows );
double* ptrC = x+colNum*NumRows;
double* ptrV = v.x;
double ret = 0.0;
for ( long i = NumRows; i>0; i-- ) {
ret += (*(ptrC++))*(*(ptrV++));
}
return ret;
}
// Add a constant to each entry on the diagonal
MatrixRmn& MatrixRmn::AddToDiagonal( double d ) // Adds d to each diagonal entry
{
long diagLen = Min( NumRows, NumCols );
double* dPtr = x;
for ( ; diagLen>0; diagLen-- ) {
*dPtr += d;
dPtr += NumRows+1;
}
return *this;
}
// Add a vector to the entries on the diagonal
MatrixRmn& MatrixRmn::AddToDiagonal( const VectorRn& dVec ) // Adds dVec to the diagonal entries
{
long diagLen = Min( NumRows, NumCols );
double* dPtr = x;
for (int i = 0; i < diagLen && i < dVec.GetLength(); ++i) {
*dPtr += dVec[i];
dPtr += NumRows+1;
}
return *this;
}
// Multiply two MatrixRmn's
MatrixRmn& MatrixRmn::Multiply( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
assert( A.NumCols == B.NumRows && A.NumRows == dst.NumRows && B.NumCols == dst.NumCols );
long length = A.NumCols;
double *bPtr = B.x; // Points to beginning of column in B
double *dPtr = dst.x;
for ( long i = dst.NumCols; i>0; i-- ) {
double *aPtr = A.x; // Points to beginning of row in A
for ( long j = dst.NumRows; j>0; j-- ) {
*dPtr = DotArray( length, aPtr, A.NumRows, bPtr, 1 );
dPtr++;
aPtr++;
}
bPtr += B.NumRows;
}
return dst;
}
// Multiply two MatrixRmn's, Transpose the first matrix before multiplying
MatrixRmn& MatrixRmn::TransposeMultiply( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
assert( A.NumRows == B.NumRows && A.NumCols == dst.NumRows && B.NumCols == dst.NumCols );
long length = A.NumRows;
double *bPtr = B.x; // bPtr Points to beginning of column in B
double *dPtr = dst.x;
for ( long i = dst.NumCols; i>0; i-- ) { // Loop over all columns of dst
double *aPtr = A.x; // aPtr Points to beginning of column in A
for ( long j = dst.NumRows; j>0; j-- ) { // Loop over all rows of dst
*dPtr = DotArray( length, aPtr, 1, bPtr, 1 );
dPtr ++;
aPtr += A.NumRows;
}
bPtr += B.NumRows;
}
return dst;
}
// Multiply two MatrixRmn's. Transpose the second matrix before multiplying
MatrixRmn& MatrixRmn::MultiplyTranspose( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
assert( A.NumCols == B.NumCols && A.NumRows == dst.NumRows && B.NumRows == dst.NumCols );
long length = A.NumCols;
double *bPtr = B.x; // Points to beginning of row in B
double *dPtr = dst.x;
for ( long i = dst.NumCols; i>0; i-- ) {
double *aPtr = A.x; // Points to beginning of row in A
for ( long j = dst.NumRows; j>0; j-- ) {
*dPtr = DotArray( length, aPtr, A.NumRows, bPtr, B.NumRows );
dPtr++;
aPtr++;
}
bPtr++;
}
return dst;
}
// Solves the equation (*this)*xVec = b;
// Uses row operations. Assumes *this is square and invertible.
// No error checking for divide by zero or instability (except with asserts)
void MatrixRmn::Solve( const VectorRn& b, VectorRn* xVec ) const
{
assert ( NumRows==NumCols && NumCols==xVec->GetLength() && NumRows==b.GetLength() );
// Copy this matrix and b into an Augmented Matrix
MatrixRmn& AugMat = GetWorkMatrix( NumRows, NumCols+1 );
AugMat.LoadAsSubmatrix( *this );
AugMat.SetColumn( NumRows, b );
// Put into row echelon form with row operations
AugMat.ConvertToRefNoFree();
// Solve for x vector values using back substitution
double* xLast = xVec->x+NumRows-1; // Last entry in xVec
double* endRow = AugMat.x+NumRows*NumCols-1; // Last entry in the current row of the coefficient part of Augmented Matrix
double* bPtr = endRow+NumRows; // Last entry in augmented matrix (end of last column, in augmented part)
for ( long i = NumRows; i>0; i-- ) {
double accum = *(bPtr--);
// Next loop computes back substitution terms
double* rowPtr = endRow; // Points to entries of the current row for back substitution.
double* xPtr = xLast; // Points to entries in the x vector (also for back substitution)
for ( long j=NumRows-i; j>0; j-- ) {
accum -= (*rowPtr)*(*(xPtr--));
rowPtr -= NumCols; // Previous entry in the row
}
assert( *rowPtr != 0.0 ); // Are not supposed to be any free variables in this matrix
*xPtr = accum/(*rowPtr);
endRow--;
}
}
// ConvertToRefNoFree
// Converts the matrix (in place) to row echelon form
// For us, row echelon form allows any non-zero values, not just 1's, in the
// position for a lead variable.
// The "NoFree" version operates on the assumption that no free variable will be found.
// Algorithm uses row operations and row pivoting (only).
// Augmented matrix is correctly accomodated. Only the first square part participates
// in the main work of row operations.
void MatrixRmn::ConvertToRefNoFree()
{
// Loop over all columns (variables)
// Find row with most non-zero entry.
// Swap to the highest active row
// Subtract appropriately from all the lower rows (row op of type 3)
long numIters = Min(NumRows,NumCols);
double* rowPtr1 = x;
const long diagStep = NumRows+1;
long lenRowLeft = NumCols;
for ( ; numIters>1; numIters-- ) {
// Find row with most non-zero entry.
double* rowPtr2 = rowPtr1;
double maxAbs = fabs(*rowPtr1);
double *rowPivot = rowPtr1;
long i;
for ( i=numIters-1; i>0; i-- ) {
const double& newMax = *(++rowPivot);
if ( newMax > maxAbs ) {
maxAbs = *rowPivot;
rowPtr2 = rowPivot;
}
else if ( -newMax > maxAbs ) {
maxAbs = -newMax;
rowPtr2 = rowPivot;
}
}
// Pivot step: Swap the row with highest entry to the current row
if ( rowPtr1 != rowPtr2 ) {
double *to = rowPtr1;
for ( long i=lenRowLeft; i>0; i-- ) {
double temp = *to;
*to = *rowPtr2;
*rowPtr2 = temp;
to += NumRows;
rowPtr2 += NumRows;
}
}
// Subtract this row appropriately from all the lower rows (row operation of type 3)
rowPtr2 = rowPtr1;
for ( i=numIters-1; i>0; i-- ) {
rowPtr2++;
double* to = rowPtr2;
double* from = rowPtr1;
assert( *from != 0.0 );
double alpha = (*to)/(*from);
*to = 0.0;
for ( long j=lenRowLeft-1; j>0; j-- ) {
to += NumRows;
from += NumRows;
*to -= (*from)*alpha;
}
}
// Update for next iteration of loop
rowPtr1 += diagStep;
lenRowLeft--;
}
}
// Calculate the c=cosine and s=sine values for a Givens transformation.
// The matrix M = ( (c, -s), (s, c) ) in row order transforms the
// column vector (a, b)^T to have y-coordinate zero.
void MatrixRmn::CalcGivensValues( double a, double b, double *c, double *s )
{
double denomInv = sqrt(a*a + b*b);
if ( denomInv==0.0 ) {
*c = 1.0;
*s = 0.0;
}
else {
denomInv = 1.0/denomInv;
*c = a*denomInv;
*s = -b*denomInv;
}
}
// Applies Givens transform to columns i and i+1.
// Equivalent to postmultiplying by the matrix
// ( c -s )
// ( s c )
// with non-zero entries in rows i and i+1 and columns i and i+1
void MatrixRmn::PostApplyGivens( double c, double s, long idx )
{
assert ( 0<=idx && idx<NumCols );
double *colA = x + idx*NumRows;
double *colB = colA + NumRows;
for ( long i = NumRows; i>0; i-- ) {
double temp = *colA;
*colA = (*colA)*c + (*colB)*s;
*colB = (*colB)*c - temp*s;
colA++;
colB++;
}
}
// Applies Givens transform to columns idx1 and idx2.
// Equivalent to postmultiplying by the matrix
// ( c -s )
// ( s c )
// with non-zero entries in rows idx1 and idx2 and columns idx1 and idx2
void MatrixRmn::PostApplyGivens( double c, double s, long idx1, long idx2 )
{
assert ( idx1!=idx2 && 0<=idx1 && idx1<NumCols && 0<=idx2 && idx2<NumCols );
double *colA = x + idx1*NumRows;
double *colB = x + idx2*NumRows;
for ( long i = NumRows; i>0; i-- ) {
double temp = *colA;
*colA = (*colA)*c + (*colB)*s;
*colB = (*colB)*c - temp*s;
colA++;
colB++;
}
}
// ********************************************************************************************
// Singular value decomposition.
// Return othogonal matrices U and V and diagonal matrix with diagonal w such that
// (this) = U * Diag(w) * V^T (V^T is V-transpose.)
// Diagonal entries have all non-zero entries before all zero entries, but are not
// necessarily sorted. (Someday, I will write ComputedSortedSVD that handles
// sorting the eigenvalues by magnitude.)
// ********************************************************************************************
void MatrixRmn::ComputeSVD( MatrixRmn& U, VectorRn& w, MatrixRmn& V ) const
{
assert ( U.NumRows==NumRows && V.NumCols==NumCols
&& U.NumRows==U.NumCols && V.NumRows==V.NumCols
&& w.GetLength()==Min(NumRows,NumCols) );
// double temp=0.0;
VectorRn& superDiag = VectorRn::GetWorkVector( w.GetLength()-1 ); // Some extra work space. Will get passed around.
// Choose larger of U, V to hold intermediate results
// If U is larger than V, use U to store intermediate results
// Otherwise use V. In the latter case, we form the SVD of A transpose,
// (which is essentially identical to the SVD of A).
MatrixRmn* leftMatrix;
MatrixRmn* rightMatrix;
if ( NumRows >= NumCols ) {
U.LoadAsSubmatrix( *this ); // Copy A into U
leftMatrix = &U;
rightMatrix = &V;
}
else {
V.LoadAsSubmatrixTranspose( *this ); // Copy A-transpose into V
leftMatrix = &V;
rightMatrix = &U;
}
// Do the actual work to calculate the SVD
// Now matrix has at least as many rows as columns
CalcBidiagonal( *leftMatrix, *rightMatrix, w, superDiag );
ConvertBidiagToDiagonal( *leftMatrix, *rightMatrix, w, superDiag );
}
void MatrixRmn::ComputeInverse( MatrixRmn& R) const
{
assert ( this->NumRows==this->NumCols );
MatrixRmn U(this->NumRows, this->NumCols);
VectorRn w(this->NumRows);
MatrixRmn V(this->NumRows, this->NumCols);
this->ComputeSVD(U, w, V);
assert(this->DebugCheckSVD(U, w , V));
double PseudoInverseThresholdFactor = 0.01;
double pseudoInverseThreshold = PseudoInverseThresholdFactor*w.MaxAbs();
MatrixRmn VD(this->NumRows, this->NumCols);
MatrixRmn D(this->NumRows, this->NumCols);
D.SetZero();
long diagLength = w.GetLength();
double* wPtr = w.GetPtr();
for ( long i = 0; i < diagLength; ++i ) {
double alpha = *(wPtr++);
if ( fabs(alpha)>pseudoInverseThreshold ) {
D.Set(i, i, 1.0/alpha);
}
}
Multiply(V,D,VD);
MultiplyTranspose(VD,U,R);
}
// ************************************************ CalcBidiagonal **************************
// Helper routine for SVD computation
// U is a matrix to be bidiagonalized.
// On return, U and V are orthonormal and w holds the new diagonal
// elements and superDiag holds the super diagonal elements.
void MatrixRmn::CalcBidiagonal( MatrixRmn& U, MatrixRmn& V, VectorRn& w, VectorRn& superDiag )
{
assert ( U.NumRows>=V.NumRows );
// The diagonal and superdiagonal entries of the bidiagonalized
// version of the U matrix
// are stored in the vectors w and superDiag (temporarily).
// Apply Householder transformations to U.
// Householder transformations come in pairs.
// First, on the left, we map a portion of a column to zeros
// Second, on the right, we map a portion of a row to zeros
const long rowStep = U.NumCols;
const long diagStep = U.NumCols+1;
double *diagPtr = U.x;
double* wPtr = w.x;
double* superDiagPtr = superDiag.x;
long colLengthLeft = U.NumRows;
long rowLengthLeft = V.NumCols;
while (true) {
// Apply a Householder xform on left to zero part of a column
SvdHouseholder( diagPtr, colLengthLeft, rowLengthLeft, 1, rowStep, wPtr );
if ( rowLengthLeft==2 ) {
*superDiagPtr = *(diagPtr+rowStep);
break;
}
// Apply a Householder xform on the right to zero part of a row
SvdHouseholder( diagPtr+rowStep, rowLengthLeft-1, colLengthLeft, rowStep, 1, superDiagPtr );
rowLengthLeft--;
colLengthLeft--;
diagPtr += diagStep;
wPtr++;
superDiagPtr++;
}
int extra = 0;
diagPtr += diagStep;
wPtr++;
if ( colLengthLeft > 2 ) {
extra = 1;
// Do one last Householder transformation when the matrix is not square
colLengthLeft--;
SvdHouseholder( diagPtr, colLengthLeft, 1, 1, 0, wPtr );
}
else {
*wPtr = *diagPtr;
}
// Form U and V from the Householder transformations
V.ExpandHouseholders( V.NumCols-2, 1, U.x+U.NumRows, U.NumRows, 1 );
U.ExpandHouseholders( V.NumCols-1+extra, 0, U.x, 1, U.NumRows );
// Done with bidiagonalization
return;
}
// Helper routine for CalcBidiagonal
// Performs a series of Householder transformations on a matrix
// Stores results compactly into the matrix: The Householder vector u (normalized)
// is stored into the first row/column being transformed.
// The leading term of that row (= plus/minus its magnitude is returned
// separately into "retFirstEntry"
void MatrixRmn::SvdHouseholder( double* basePt,
long colLength, long numCols, long colStride, long rowStride,
double* retFirstEntry )
{
// Calc norm of vector u
double* cPtr = basePt;
double norm = 0.0;
long i;
for ( i=colLength; i>0 ; i-- ) {
norm += Square( *cPtr );
cPtr += colStride;
}
norm = sqrt(norm); // Norm of vector to reflect to axis e_1
// Handle sign issues
double imageVal; // Choose sign to maximize distance
if ( (*basePt) < 0.0 ) {
imageVal = norm;
norm = 2.0*norm*(norm-(*basePt));
}
else {
imageVal = -norm;
norm = 2.0*norm*(norm+(*basePt));
}
norm = sqrt(norm); // Norm is norm of reflection vector
if ( norm==0.0 ) { // If the vector being transformed is equal to zero
// Force to zero in case of roundoff errors
cPtr = basePt;
for ( i=colLength; i>0; i-- ) {
*cPtr = 0.0;
cPtr += colStride;
}
*retFirstEntry = 0.0;
return;
}
*retFirstEntry = imageVal;
// Set up the normalized Householder vector
*basePt -= imageVal; // First component changes. Rest stay the same.
// Normalize the vector
norm = 1.0/norm; // Now it is the inverse norm
cPtr = basePt;
for ( i=colLength; i>0 ; i-- ) {
*cPtr *= norm;
cPtr += colStride;
}
// Transform the rest of the U matrix with the Householder transformation
double *rPtr = basePt;
for ( long j=numCols-1; j>0; j-- ) {
rPtr += rowStride;
// Calc dot product with Householder transformation vector
double dotP = DotArray( colLength, basePt, colStride, rPtr, colStride );
// Transform with I - 2*dotP*(Householder vector)
AddArrayScale( colLength, basePt, colStride, rPtr, colStride, -2.0*dotP );
}
}
// ********************************* ExpandHouseholders ********************************************
// The matrix will be square.
// numXforms = number of Householder transformations to concatenate
// Each Householder transformation is represented by a unit vector
// Each successive Householder transformation starts one position later
// and has one more implied leading zero
// basePt = beginning of the first Householder transform
// colStride, rowStride: Householder xforms are stored in "columns"
// numZerosSkipped is the number of implicit zeros on the front each
// Householder transformation vector (only values supported are 0 and 1).
void MatrixRmn::ExpandHouseholders( long numXforms, int numZerosSkipped, const double* basePt, long colStride, long rowStride )
{
// Number of applications of the last Householder transform
// (That are not trivial!)
long numToTransform = NumCols-numXforms+1-numZerosSkipped;
assert( numToTransform>0 );
if ( numXforms==0 ) {
SetIdentity();
return;
}
// Handle the first one separately as a special case,
// "this" matrix will be treated to simulate being preloaded with the identity
long hDiagStride = rowStride+colStride;
const double* hBase = basePt + hDiagStride*(numXforms-1); // Pointer to the last Householder vector
const double* hDiagPtr = hBase + colStride*(numToTransform-1); // Pointer to last entry in that vector
long i;
double* diagPtr = x+NumCols*NumRows-1; // Last entry in matrix (points to diagonal entry)
double* colPtr = diagPtr-(numToTransform-1); // Pointer to column in matrix
for ( i=numToTransform; i>0; i-- ) {
CopyArrayScale( numToTransform, hBase, colStride, colPtr, 1, -2.0*(*hDiagPtr) );
*diagPtr += 1.0; // Add back in 1 to the diagonal entry (since xforming the identity)
diagPtr -= (NumRows+1); // Next diagonal entry in this matrix
colPtr -= NumRows; // Next column in this matrix
hDiagPtr -= colStride;
}
// Now handle the general case
// A row of zeros must be in effect added to the top of each old column (in each loop)
double* colLastPtr = x + NumRows*NumCols - numToTransform - 1;
for ( i = numXforms-1; i>0; i-- ) {
numToTransform++; // Number of non-trivial applications of this Householder transformation
hBase -= hDiagStride; // Pointer to the beginning of the Householder transformation
colPtr = colLastPtr;
for ( long j = numToTransform-1; j>0; j-- ) {
// Get dot product
double dotProd2N = -2.0*DotArray( numToTransform-1, hBase+colStride, colStride, colPtr+1, 1 );
*colPtr = dotProd2N*(*hBase); // Adding onto zero at initial point
AddArrayScale( numToTransform-1, hBase+colStride, colStride, colPtr+1, 1, dotProd2N );
colPtr -= NumRows;
}
// Do last one as a special case (may overwrite the Householder vector)
CopyArrayScale( numToTransform, hBase, colStride, colPtr, 1, -2.0*(*hBase) );
*colPtr += 1.0; // Add back one one as identity
// Done with this Householder transformation
colLastPtr --;
}
if ( numZerosSkipped!=0 ) {
assert( numZerosSkipped==1 );
// Fill first row and column with identity (More generally: first numZerosSkipped many rows and columns)
double* d = x;
*d = 1;
double* d2 = d;
for ( i=NumRows-1; i>0; i-- ) {
*(++d) = 0;
*(d2+=NumRows) = 0;
}
}
}
// **************** ConvertBidiagToDiagonal ***********************************************
// Do the iterative transformation from bidiagonal form to diagonal form using
// Givens transformation. (Golub-Reinsch)
// U and V are square. Size of U less than or equal to that of U.
void MatrixRmn::ConvertBidiagToDiagonal( MatrixRmn& U, MatrixRmn& V, VectorRn& w, VectorRn& superDiag ) const
{
// These two index into the last bidiagonal block (last in the matrix, it will be
// first one handled.
long lastBidiagIdx = V.NumRows-1;
long firstBidiagIdx = 0;
double eps = 1.0e-15 * Max(w.MaxAbs(), superDiag.MaxAbs());
while ( true ) {
bool workLeft = UpdateBidiagIndices( &firstBidiagIdx, &lastBidiagIdx, w, superDiag, eps );
if ( !workLeft ) {
break;
}
// Get ready for first Givens rotation
// Push non-zero to M[2,1] with Givens transformation
double* wPtr = w.x+firstBidiagIdx;
double* sdPtr = superDiag.x+firstBidiagIdx;
double extraOffDiag=0.0;
if ( (*wPtr)==0.0 ) {
ClearRowWithDiagonalZero( firstBidiagIdx, lastBidiagIdx, U, wPtr, sdPtr, eps );
if ( firstBidiagIdx>0 ) {
if ( NearZero( *(--sdPtr), eps ) ) {
*sdPtr = 0.0;
}
else {
ClearColumnWithDiagonalZero( firstBidiagIdx, V, wPtr, sdPtr, eps );
}
}
continue;
}
// Estimate an eigenvalue from bottom four entries of M
// This gives a lambda value which will shift the Givens rotations
// Last four entries of M^T * M are ( ( A, B ), ( B, C ) ).
double A;
A = (firstBidiagIdx<lastBidiagIdx-1) ? Square(superDiag[lastBidiagIdx-2]): 0.0;
double BSq = Square(w[lastBidiagIdx-1]);
A += BSq; // The "A" entry of M^T * M
double C = Square(superDiag[lastBidiagIdx-1]);
BSq *= C; // The squared "B" entry
C += Square(w[lastBidiagIdx]); // The "C" entry
double lambda; // lambda will hold the estimated eigenvalue
lambda = sqrt( Square((A-C)*0.5) + BSq ); // Use the lambda value that is closest to C.
if ( A > C ) {
lambda = -lambda;
}
lambda += (A+C)*0.5; // Now lambda equals the estimate for the last eigenvalue
double t11 = Square(w[firstBidiagIdx]);
double t12 = w[firstBidiagIdx]*superDiag[firstBidiagIdx];
double c, s;
CalcGivensValues( t11-lambda, t12, &c, &s );
ApplyGivensCBTD( c, s, wPtr, sdPtr, &extraOffDiag, wPtr+1 );
V.PostApplyGivens( c, -s, firstBidiagIdx );
long i;
for ( i=firstBidiagIdx; i<lastBidiagIdx-1; i++ ) {
// Push non-zero from M[i+1,i] to M[i,i+2]
CalcGivensValues( *wPtr, extraOffDiag, &c, &s );
ApplyGivensCBTD( c, s, wPtr, sdPtr, &extraOffDiag, extraOffDiag, wPtr+1, sdPtr+1 );
U.PostApplyGivens( c, -s, i );
// Push non-zero from M[i,i+2] to M[1+2,i+1]
CalcGivensValues( *sdPtr, extraOffDiag, &c, &s );
ApplyGivensCBTD( c, s, sdPtr, wPtr+1, &extraOffDiag, extraOffDiag, sdPtr+1, wPtr+2 );
V.PostApplyGivens( c, -s, i+1 );
wPtr++;
sdPtr++;
}
// Push non-zero value from M[i+1,i] to M[i,i+1] for i==lastBidiagIdx-1
CalcGivensValues( *wPtr, extraOffDiag, &c, &s );
ApplyGivensCBTD( c, s, wPtr, &extraOffDiag, sdPtr, wPtr+1 );
U.PostApplyGivens( c, -s, i );
// DEBUG
// DebugCalcBidiagCheck( V, w, superDiag, U );
}
}
// This is called when there is a zero diagonal entry, with a non-zero superdiagonal entry on the same row.
// We use Givens rotations to "chase" the non-zero entry across the row; when it reaches the last
// column, it is finally zeroed away.
// wPtr points to the zero entry on the diagonal. sdPtr points to the non-zero superdiagonal entry on the same row.
void MatrixRmn::ClearRowWithDiagonalZero( long firstBidiagIdx, long lastBidiagIdx, MatrixRmn& U, double *wPtr, double *sdPtr, double eps )
{
double curSd = *sdPtr; // Value being chased across the row
*sdPtr = 0.0;
long i=firstBidiagIdx+1;
while (true) {
// Rotate row i and row firstBidiagIdx (Givens rotation)
double c, s;
CalcGivensValues( *(++wPtr), curSd, &c, &s );
U.PostApplyGivens( c, -s, i, firstBidiagIdx );
*wPtr = c*(*wPtr) - s*curSd;
if ( i==lastBidiagIdx ) {
break;
}
curSd = s*(*(++sdPtr)); // New value pops up one column over to the right
*sdPtr = c*(*sdPtr);
i++;
}
}
// This is called when there is a zero diagonal entry, with a non-zero superdiagonal entry in the same column.
// We use Givens rotations to "chase" the non-zero entry up the column; when it reaches the last
// column, it is finally zeroed away.
// wPtr points to the zero entry on the diagonal. sdPtr points to the non-zero superdiagonal entry in the same column.
void MatrixRmn::ClearColumnWithDiagonalZero( long endIdx, MatrixRmn& V, double *wPtr, double *sdPtr, double eps )
{
double curSd = *sdPtr; // Value being chased up the column
*sdPtr = 0.0;
long i = endIdx-1;
while ( true ) {
double c, s;
CalcGivensValues( *(--wPtr), curSd, &c, &s );
V.PostApplyGivens( c, -s, i, endIdx );
*wPtr = c*(*wPtr) - s*curSd;
if ( i==0 ) {
break;
}
curSd = s*(*(--sdPtr)); // New value pops up one row above
if ( NearZero( curSd, eps ) ) {
break;
}
*sdPtr = c*(*sdPtr);
i--;
}
}
// Matrix A is ( ( a c ) ( b d ) ), i.e., given in column order.
// Mult's G[c,s] times A, replaces A.
void MatrixRmn::ApplyGivensCBTD( double cosine, double sine, double *a, double *b, double *c, double *d )
{
double temp = *a;
*a = cosine*(*a) - sine*(*b);
*b = sine*temp + cosine*(*b);
temp = *c;
*c = cosine*(*c) - sine*(*d);
*d = sine*temp + cosine*(*d);
}
// Now matrix A given in row order, A = ( ( a b c ) ( d e f ) ).
// Return G[c,s] * A, replace A. d becomes zero, no need to return.
// Also, it is certain the old *c value is taken to be zero!
void MatrixRmn::ApplyGivensCBTD( double cosine, double sine, double *a, double *b, double *c,
double d, double *e, double *f )
{
*a = cosine*(*a) - sine*d;
double temp = *b;
*b = cosine*(*b) - sine*(*e);
*e = sine*temp + cosine*(*e);
*c = -sine*(*f);
*f = cosine*(*f);
}
// Helper routine for SVD conversion from bidiagonal to diagonal
bool MatrixRmn::UpdateBidiagIndices( long *firstBidiagIdx, long *lastBidiagIdx, VectorRn& w, VectorRn& superDiag, double eps )
{
long lastIdx = *lastBidiagIdx;
double* sdPtr = superDiag.GetPtr( lastIdx-1 ); // Entry above the last diagonal entry
while ( NearZero(*sdPtr, eps) ) {
*(sdPtr--) = 0.0;
lastIdx--;
if ( lastIdx == 0 ) {
return false;
}
}
*lastBidiagIdx = lastIdx;
long firstIdx = lastIdx-1;
double* wPtr = w.GetPtr( firstIdx );
while ( firstIdx > 0 ) {
if ( NearZero( *wPtr, eps ) ) { // If this diagonal entry (near) zero
*wPtr = 0.0;
break;
}
if ( NearZero(*(--sdPtr), eps) ) { // If the entry above the diagonal entry is (near) zero
*sdPtr = 0.0;
break;
}
wPtr--;
firstIdx--;
}
*firstBidiagIdx = firstIdx;
return true;
}
// ******************************************DEBUG STUFFF
bool MatrixRmn::DebugCheckSVD( const MatrixRmn& U, const VectorRn& w, const MatrixRmn& V ) const
{
// Special SVD test code
MatrixRmn IV( V.GetNumRows(), V.GetNumColumns() );
IV.SetIdentity();
MatrixRmn VTV( V.GetNumRows(), V.GetNumColumns() );
MatrixRmn::TransposeMultiply( V, V, VTV );
IV -= VTV;
double error = IV.FrobeniusNorm();
MatrixRmn IU( U.GetNumRows(), U.GetNumColumns() );
IU.SetIdentity();
MatrixRmn UTU( U.GetNumRows(), U.GetNumColumns() );
MatrixRmn::TransposeMultiply( U, U, UTU );
IU -= UTU;
error += IU.FrobeniusNorm();
MatrixRmn Diag( U.GetNumRows(), V.GetNumRows() );
Diag.SetZero();
Diag.SetDiagonalEntries( w );
MatrixRmn B(U.GetNumRows(), V.GetNumRows() );
MatrixRmn C(U.GetNumRows(), V.GetNumRows() );
MatrixRmn::Multiply( U, Diag, B );
MatrixRmn::MultiplyTranspose( B, V, C );
C -= *this;
error += C.FrobeniusNorm();
bool ret = ( fabs(error)<=1.0e-13*w.MaxAbs() );
assert ( ret );
return ret;
}
bool MatrixRmn::DebugCheckInverse( const MatrixRmn& MInv ) const
{
assert ( this->NumRows==this->NumCols );
assert ( MInv.NumRows==MInv.NumCols );
MatrixRmn I(this->NumRows, this->NumCols);
I.SetIdentity();
MatrixRmn MMInv(this->NumRows, this->NumCols);
Multiply(*this, MInv, MMInv);
I -= MMInv;
double error = I.FrobeniusNorm();
bool ret = ( fabs(error)<=1.0e-13 );
assert ( ret );
return ret;
}
bool MatrixRmn::DebugCalcBidiagCheck( const MatrixRmn& U, const VectorRn& w, const VectorRn& superDiag, const MatrixRmn& V ) const
{
// Special SVD test code
MatrixRmn IV( V.GetNumRows(), V.GetNumColumns() );
IV.SetIdentity();
MatrixRmn VTV( V.GetNumRows(), V.GetNumColumns() );
MatrixRmn::TransposeMultiply( V, V, VTV );
IV -= VTV;
double error = IV.FrobeniusNorm();
MatrixRmn IU( U.GetNumRows(), U.GetNumColumns() );
IU.SetIdentity();
MatrixRmn UTU( U.GetNumRows(), U.GetNumColumns() );
MatrixRmn::TransposeMultiply( U, U, UTU );
IU -= UTU;
error += IU.FrobeniusNorm();
MatrixRmn DiagAndSuper( U.GetNumRows(), V.GetNumRows() );
DiagAndSuper.SetZero();
DiagAndSuper.SetDiagonalEntries( w );
if ( this->GetNumRows()>=this->GetNumColumns() ) {
DiagAndSuper.SetSequence( superDiag, 0, 1, 1, 1 );
}
else {
DiagAndSuper.SetSequence( superDiag, 1, 0, 1, 1 );
}
MatrixRmn B(U.GetNumRows(), V.GetNumRows() );
MatrixRmn C(U.GetNumRows(), V.GetNumRows() );
MatrixRmn::Multiply( U, DiagAndSuper, B );
MatrixRmn::MultiplyTranspose( B, V, C );
C -= *this;
error += C.FrobeniusNorm();
bool ret = ( fabs(error)<1.0e-13*Max(w.MaxAbs(),superDiag.MaxAbs()) );
assert ( ret );
return ret;
}
| [
"info@ochakkolab.moo.jp"
] | info@ochakkolab.moo.jp |
0820db83cae8a4b962f595e584233aa705510941 | e42995b855822303228eb8f436e121f0da082ebd | /ElanToggle/ElanToggle.cpp | 7aafc14abc0fec103ca5426a3ae9e5e4985f9f7a | [] | no_license | jeiea/ElanToggle | ea13d976e066343760bfbea2c34a50c0c951fd87 | 426713aaac5709199c65f4190befa00c3761774f | refs/heads/master | 2020-06-01T20:00:10.256167 | 2019-06-08T16:27:39 | 2019-06-08T16:27:39 | 190,909,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,293 | cpp | /// ElanToggle.cpp
/// jeiea, for toggle of elan touchpad function
#include "ElanToggle.h"
#include "framework.h"
using namespace std;
struct Error {
DWORD errorCode;
LPCTSTR message;
static Error fromLastError(LPCTSTR message) {
return Error{GetLastError(), message};
}
};
wstring GetErrorString(DWORD lastError) {
LPWSTR messageBuffer = nullptr;
size_t size = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&messageBuffer, 0, NULL);
wstring message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
void ErrorMessageBox(LPCTSTR caption, DWORD errorCode = 0) {
DWORD code = errorCode ? errorCode : GetLastError();
wstring msg = GetErrorString(code);
MessageBox(nullptr, msg.data(), caption, MB_OK);
}
void DispatchUpdateEvent() {
LPCTSTR regPath = _T("Global\\ETDCombo_UpdateRegistry");
HANDLE eventHandle = OpenEvent(EVENT_MODIFY_STATE, FALSE, regPath);
if (eventHandle == nullptr || eventHandle == INVALID_HANDLE_VALUE) {
throw Error::fromLastError(_T("OpenEvent failed"));
}
int setResult = SetEvent(eventHandle);
if (setResult == 0) {
throw Error::fromLastError(_T("SetEvent failed"));
}
CloseHandle(eventHandle);
}
void SetTouchpadActivation(bool enable) {
LPCTSTR elanDeviceKey = _T("Software\\Elantech\\DeviceInformation");
LPCTSTR touchpadVal = _T("Port0_MasterEnable");
DWORD onOff = enable;
LSTATUS setResult =
RegSetKeyValue(HKEY_CURRENT_USER, elanDeviceKey, touchpadVal, REG_DWORD,
&onOff, sizeof(onOff));
if (setResult != ERROR_SUCCESS) {
throw Error::fromLastError(_T("RegOpenKeyEx failed"));
}
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine,
_In_ int nCmdShow) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
try {
SetTouchpadActivation(false);
DispatchUpdateEvent();
}
catch (Error e) {
ErrorMessageBox(e.message, e.errorCode);
return 1;
}
return 0;
}
| [
"solum5013@gmail.com"
] | solum5013@gmail.com |
79453f441a1bc35b8ff64d5e56fb4ec7858f1848 | 8741753121dd16938f224babb3a407eea85ce0c8 | /Median.cpp | ab406a5803bb21df0272e10ec5166be93f5a7de8 | [
"Apache-2.0"
] | permissive | mcunator/TrackProcessor | 5859ee3a0d6502c2bd40b38b7aef77094a3ed6e7 | d991696542822b7136fffa797741b2ed9e4d66c4 | refs/heads/master | 2023-05-03T23:10:09.197291 | 2017-11-07T17:33:02 | 2017-11-07T17:33:02 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,964 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#include <math.h>
#pragma hdrstop
#include "Median.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
__fastcall Median::Median()
{
m_bAverage = false;
m_dAverageFactor = 0.65;
}
__fastcall Median::~Median()
{
//TODO: Add your source code here
}
void __fastcall Median::Sort(double * arr, int n)
{
int i, j;
double tmp;
for(i = 1; i < n; ++i) // цикл проходов, i - номер прохода
{
tmp = arr[i];
for (j = i - 1; j >= 0 && arr[j] > tmp; --j) // поиск места элемента в готовой последовательности
arr[j + 1] = arr[j]; // сдвигаем элемент направо, пока не дошли
arr[j + 1] = tmp; // место найдено, вставить элемент
}
}
void __fastcall Median::SetAverage(bool value)
{
if(m_bAverage != value) m_bAverage = value;
}
bool __fastcall Median::GetAverage()
{
return m_bAverage;
}
void __fastcall Median::SetAverageFactor(double value)
{
if(m_dAverageFactor != value) m_dAverageFactor = value;
}
double __fastcall Median::GetAverageFactor()
{
return m_dAverageFactor;
}
double __fastcall Median::GetMedian(double * arr, int n)
{
double *sort_arr = new double[n];
double dMedian;
int nMedIndex = n / 2;
bool isEven = ((n % 2) == 0);
for(int i = 0; i < n; i++) sort_arr[i] = arr[i];
Sort(sort_arr, n);
if(m_bAverage)
dMedian = m_dAverageFactor * sort_arr[nMedIndex] +
(1.0 - m_dAverageFactor) * (sort_arr[nMedIndex - 1] + sort_arr[nMedIndex + 1]) / 2.0;
else
{
if(isEven) dMedian = (sort_arr[nMedIndex - 1] + sort_arr[nMedIndex]) / 2.0;
else dMedian = sort_arr[nMedIndex];
}
delete [] sort_arr;
return dMedian;
} | [
"algous@gmail.com"
] | algous@gmail.com |
0526627d677bdf04f03187d10f64b5420dd09fe0 | e354a51eef332858855eac4c369024a7af5ff804 | /msgrouterruleset.cpp | 2d9f89d33e0fe39b252cb7e9057ee44c6bd92fcd | [] | no_license | cjus/msgCourierLite | 0f9c1e05b71abf820c55f74a913555eec2267bb4 | 9efc1d54737ba47620a03686707b31b1eeb61586 | refs/heads/master | 2020-04-05T22:41:39.141740 | 2010-09-05T18:43:12 | 2010-09-05T18:43:12 | 887,172 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp | /* msgrouterruleset.cpp
Copyright (C) 2005 Carlos Justiniano
cjus@chessbrain.net, cjus34@yahoo.com, cjus@users.sourceforge.net
msgrouterruleset.cpp is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
msgrouterruleset.cpp was developed by Carlos Justiniano for use on the
msgCourier project and the ChessBrain Project and is now distributed in
the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License
along with main.cpp; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
@file msgrouterruleset.cpp
@brief Message Router Rule
@author Carlos Justiniano
@attention Copyright (C) 2005 Carlos Justiniano, GNU GPL Licence (see source file header)
cMsgRouterRuleSet is used by the cMsgRouterRulesEngine.
*/
#include "exception.h"
#include "log.h"
#include "msgrouterruleset.h"
using namespace std;
cMsgRouterRuleSet::cMsgRouterRuleSet(string &RuleName, string &RouteTo)
{
try
{
m_RuleSetName = RuleName;
m_RouteTo = RouteTo;
}
catch (exception const &e)
{
LOGALL(e.what());
}
}
cMsgRouterRuleSet::~cMsgRouterRuleSet()
{
try
{
for (m_RuleSetIterator = m_RuleSet.begin();
m_RuleSetIterator != m_RuleSet.end();
m_RuleSetIterator++)
{
delete (*m_RuleSetIterator);
}
m_RuleSet.erase(m_RuleSet.begin(),m_RuleSet.end());
}
catch (exception const &e)
{
LOGALL(e.what());
}
}
void cMsgRouterRuleSet::AddRule(cMsgRouterRule::eMsgRouterLocationType Location,
cMsgRouterRule::eMsgRouterOperationType OperationType,
string &MatchPattern, string &Value)
{
cMsgRouterRule *pRule;
MC_NEW(pRule, cMsgRouterRule());
try
{
pRule->m_Location = Location;
pRule->m_OperationType = OperationType;
pRule->m_MatchPattern = MatchPattern;
pRule->m_Value = Value;
m_RuleSet.push_back(pRule);
}
catch (exception const &e)
{
LOGALL(e.what());
}
}
cMsgRouterRule *cMsgRouterRuleSet::GetFirstRule()
{
cMsgRouterRule *pRule = NULL;
try
{
m_RuleSetIterator = m_RuleSet.begin();
pRule = (*m_RuleSetIterator);
}
catch (exception const &e)
{
LOGALL(e.what());
}
return pRule;
}
cMsgRouterRule *cMsgRouterRuleSet::GetNextRule()
{
cMsgRouterRule *pRule = NULL;
try
{
m_RuleSetIterator++;
if (m_RuleSetIterator == m_RuleSet.end())
return 0;
pRule = (*m_RuleSetIterator);
}
catch (exception const &e)
{
LOGALL(e.what());
}
return pRule;
}
| [
"carlos.justiniano@gmail.com"
] | carlos.justiniano@gmail.com |
d802394e6d55f77f33cf7e648b3c369b3bba7c1c | 0570750c6d8e28d837f9e4f7dc825c968c874fb4 | /build/Android/Preview/app/src/main/include/Outracks.Simulator.Cl-804a3b28.h | 1b4f5f4182476b3ddc63ea101163ab7174fe4b30 | [] | no_license | theaustinthompson/maryjane | b3671d950aad58fd2ed490bda8aa1113aedf5a97 | b4ddf76aa2a2caae77765435d0315cf9111d6626 | refs/heads/master | 2021-04-12T08:37:47.311922 | 2018-03-27T23:06:47 | 2018-03-27T23:06:47 | 126,034,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,086 | h | // This file was generated based on C:/Users/borde_000/AppData/Local/Fusetools/Packages/Fuse.Preview.Core/0.1.0/Reflection/ReflectionExtensions.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Outracks{namespace Simulator{namespace Bytecode{struct Signature;}}}}
namespace g{namespace Outracks{namespace Simulator{namespace Bytecode{struct TypeMemberName;}}}}
namespace g{namespace Outracks{namespace Simulator{namespace Bytecode{struct TypeName;}}}}
namespace g{namespace Outracks{namespace Simulator{namespace Client{struct ReflectionExtensions;}}}}
namespace g{
namespace Outracks{
namespace Simulator{
namespace Client{
// internal static extern class ReflectionExtensions :11
// {
uClassType* ReflectionExtensions_typeof();
void ReflectionExtensions__CheckArgumentTypes_fn(uArray* paramTypes, uArray* argumentTypes, bool* __retval);
void ReflectionExtensions__FindConstructor_fn(uType* type, uArray* paramTypes, uFunction** __retval);
void ReflectionExtensions__FindEventAddFunction_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uObject* delegateObj, uFunction** __retval);
void ReflectionExtensions__FindEventRemoveFunction_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uObject* delegateObj, uFunction** __retval);
void ReflectionExtensions__FindField_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* fieldName, uField** __retval);
void ReflectionExtensions__FindFunction_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* memberName, uArray* paramTypes, uFunction** __retval);
void ReflectionExtensions__FindFunctionOverload_fn(uArray* functions, uArray* paramTypes, uFunction** __retval);
void ReflectionExtensions__FindFunctionsByName_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* memberName, uArray** __retval);
void ReflectionExtensions__FindPropertyGetter_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uFunction** __retval);
void ReflectionExtensions__FindPropertySetter_fn(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uType* argType, uFunction** __retval);
void ReflectionExtensions__FindType_fn(::g::Outracks::Simulator::Bytecode::TypeName* typeName, uType** __retval);
void ReflectionExtensions__FindTypes_fn(uArray* typeName, uArray** __retval);
void ReflectionExtensions__GetParameterTypes_fn(::g::Outracks::Simulator::Bytecode::Signature* methodSignature, uArray** __retval);
void ReflectionExtensions__GetTypes_fn(uArray* objects, uArray** __retval);
struct ReflectionExtensions : uObject
{
static uSStrong<uString*> PropGetPrefix_;
static uSStrong<uString*>& PropGetPrefix() { return ReflectionExtensions_typeof()->Init(), PropGetPrefix_; }
static uSStrong<uString*> PropSetPrefix_;
static uSStrong<uString*>& PropSetPrefix() { return ReflectionExtensions_typeof()->Init(), PropSetPrefix_; }
static uSStrong<uString*> EventAdderPrefix_;
static uSStrong<uString*>& EventAdderPrefix() { return ReflectionExtensions_typeof()->Init(), EventAdderPrefix_; }
static uSStrong<uString*> EventRemovePrefix_;
static uSStrong<uString*>& EventRemovePrefix() { return ReflectionExtensions_typeof()->Init(), EventRemovePrefix_; }
static uSStrong< ::g::Outracks::Simulator::Bytecode::TypeMemberName*> ConstructorName_;
static uSStrong< ::g::Outracks::Simulator::Bytecode::TypeMemberName*>& ConstructorName() { return ReflectionExtensions_typeof()->Init(), ConstructorName_; }
static bool CheckArgumentTypes(uArray* paramTypes, uArray* argumentTypes);
static uFunction* FindConstructor(uType* type, uArray* paramTypes);
static uFunction* FindEventAddFunction(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uObject* delegateObj);
static uFunction* FindEventRemoveFunction(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uObject* delegateObj);
static uField* FindField(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* fieldName);
static uFunction* FindFunction(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* memberName, uArray* paramTypes);
static uFunction* FindFunctionOverload(uArray* functions, uArray* paramTypes);
static uArray* FindFunctionsByName(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* memberName);
static uFunction* FindPropertyGetter(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName);
static uFunction* FindPropertySetter(uType* type, ::g::Outracks::Simulator::Bytecode::TypeMemberName* typeMemberName, uType* argType);
static uType* FindType(::g::Outracks::Simulator::Bytecode::TypeName* typeName);
static uArray* FindTypes(uArray* typeName);
static uArray* GetParameterTypes(::g::Outracks::Simulator::Bytecode::Signature* methodSignature);
static uArray* GetTypes(uArray* objects);
};
// }
}}}} // ::g::Outracks::Simulator::Client
| [
"austin@believeinthompson.com"
] | austin@believeinthompson.com |
c0d50b4881d814dcfb4a5c864b0299761ab76076 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/query/apps/cxxflt/cxx.cxx | 848b1dac908098dc67a92b01b6cde5bc88cb5aa5 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 28,841 | cxx | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 2000.
//
// File: CXX.CXX
//
// Contents: C and C++ Filter
//
// Classes: CxxFilter
//
// History: 26-Jun-92 BartoszM Created
// 17-Oct-94 BartoszM Rewrote
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::CxxScanner, public
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
CxxScanner::CxxScanner ()
: _pStream(0),
_fIgnorePreamble(FALSE),
_fScanningPrepro(FALSE),
_fIdFound(FALSE),
_cLines( 0 )
{
_buf[0] = L'\0';
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::Init, public
//
// Arguments: [pStream] -- stream for text
//
// History: 24-Nov-93 AmyA Created
//
//----------------------------------------------------------------------------
void CxxScanner::Init ( CFilterTextStream * pStream )
{
_pStream = pStream;
// Position scanner on a token
Accept();
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::NextToken, public
//
// Arguments: [c] -- lookahead character
//
// Returns: Recognized token
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
CToken CxxScanner::NextToken( int c )
{
BOOL fFirstTime = TRUE;
// Loop until a token is recognized
for(;;)
{
switch (c)
{
case -1: // UNICODE EOF
_token = tEnd;
return _token;
case L'\n':
_cLines++;
_fScanningPrepro = FALSE;
c = _pStream->GetChar();
break;
case L'{':
_token = tLBrace;
return _token;
case L'}':
_token = tRBrace;
return _token;
case L';':
_token = tSemi;
return _token;
case L',':
if ( _fIgnorePreamble )
{
// skip comma in the preamble
c = _pStream->GetChar();
break;
}
_token = tComma;
return _token;
case L'*':
if ( _fIgnorePreamble )
{
// skip star in the preamble
c = _pStream->GetChar();
break;
}
_token = tStar;
return _token;
case L'#': // not a token!
// consume preprocessor command
_fScanningPrepro = TRUE;
c = _pStream->GetChar();
break;
case L'(':
if ( _fIgnorePreamble )
{
// skip parentheses in the preamble
c = _pStream->GetChar();
break;
}
_token = tLParen;
return _token;
case L')':
if ( _fIgnorePreamble )
{
// skip parentheses in the preamble
c = _pStream->GetChar();
break;
}
_token = tRParen;
return _token;
case L':':
c = _pStream->GetChar();
// ignore colons in the preamble
if ( !_fIgnorePreamble && c == L':')
{
_token = tDoubleColon;
return _token;
}
break;
case L'/': // not a token!
// consume comment
c = EatComment();
break;
case L'"': // not a token!
// consume string literal
c = EatString();
break;
case L'\'': // not a token!
// consume character literal
c = EatCharLiteral();
break;
default:
// We don't really care about indentifiers.
// We store them in the buffer so that when
// we recognize a real token like :: or (
// we can retrieve them.
// Look out for 'class' 'struct' and 'union' though.
if ( iswalpha((wint_t)c) || (c == L'_') || (c == L'~') )
{
_fIdFound = TRUE;
// in preamble skip names except for the first
// one, which is the name of the procedure
if ( _fIgnorePreamble && !fFirstTime )
{
c = SkipName(c);
continue;
}
else
{
c = LoadName (c);
fFirstTime = FALSE;
}
if (!_fIgnorePreamble)
{
// look for class/struct/union keywords
if ( wcscmp(_buf, L"class" ) == 0 )
{
_token = tClass;
return _token;
}
else if ( wcscmp(_buf, L"struct") == 0 )
{
_token = tStruct;
return _token;
}
else if ( wcscmp(_buf, L"union" ) == 0 )
{
_token = tUnion;
return _token;
}
else if ( wcscmp(_buf, L"interface" ) == 0 )
{
_token = tInterface;
return _token;
}
else if ( wcscmp(_buf, L"typedef" ) == 0 )
{
_token = tTypedef;
return _token;
}
else if ( wcscmp(_buf, L"enum" ) == 0 )
{
_token = tEnum;
return _token;
}
}
if ( _fScanningPrepro )
{
if ( wcscmp(_buf, L"define" ) == 0 )
{
_token = tDefine;
c = LoadName(c);
return _token;
}
else if ( wcscmp(_buf, L"include" ) == 0 )
{
_token = tInclude;
c = LoadIncludeFileName(c);
return _token;
}
else
{
c = EatPrepro();
_fScanningPrepro = FALSE;
}
}
}
else // not recognized, continue scanning
{
c = _pStream->GetChar();
}
break;
} // end of switch
} // end of infinite loop
return _token;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::SkipName, public
//
// Returns: Next character after identifier
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::SkipName(int c)
{
int i = 0;
do
{
c = _pStream->GetChar();
i++;
}
while ( (iswalnum((wint_t)c) || (c == L'_')) && (i < MAXIDENTIFIER) );
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::LoadName, public
//
// Synopsis: Scans and copies identifier into scanner's buffer
//
// Arguments: [c] -- GetChar character
//
// Returns: Next character after identifier
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::LoadName(int c)
{
WCHAR * pCur = _buf;
_pStream->GetRegion ( _region, -1, 0 );
int i = 0;
do
{
_buf[i++] = (WCHAR)c;
c = _pStream->GetChar();
}
while ( (iswalnum((wint_t)c) || (c == L'_')) && (i < MAXIDENTIFIER));
_region.cwcExtent = i;
// c is not a symbol character
_buf[i] = L'\0';
//DbgPrint("LoadName: =================> %ws\n", _buf);
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::LoadIncludeFileName, public
//
// Synopsis: Scans and copies a file name following a
// #include statement to internal buffer
// If a path exists, it is ignored.
// A '.' is converted to '_' because searching an id
// with a '.' does not seem to work with ci.
// For example,
// #include <\foo\bar\fname.h> --> fname_h
//
// Arguments: [c] -- GetChar character
//
// Returns: Next character after the #include stmt
//
// History: 10-June-2000 kumarp Created
//
//----------------------------------------------------------------------------
int CxxScanner::LoadIncludeFileName(int c)
{
WCHAR * pCur = _buf;
int i = 0;
// skip chars preceeding the file name
do
{
c = _pStream->GetChar();
}
while ((c == L'\t') || (c == L' ') || (c == L'"') || (c == L'<'));
_pStream->GetRegion ( _region, -1, 0 );
do
{
_buf[i++] = (WCHAR)c;
if ((c == L'\\') || (c == L'/'))
{
// ignore path
i = 0;
_pStream->GetRegion ( _region, 0, 0 );
}
c = _pStream->GetChar();
// if (c == L'.')
// {
// c = L'_';
// }
}
while ((iswalnum((wint_t)c) || ( c == L'.' ) ||
(c == L'_') || (c == L'\\') || (c == L'/')) &&
(i < MAXIDENTIFIER));
_region.cwcExtent = i;
_buf[i] = L'\0';
c = EatPrepro();
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::EatComment, public
//
// Synopsis: Eats comments
//
// Returns: First non-comment character
//
// Requires: Leading '/' found and scanned
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::EatComment()
{
int c = _pStream->GetChar();
if ( c == L'*')
{
// C style comment
while ((c = _pStream->GetChar()) != EOF )
{
while ( c == L'*' )
{
c = _pStream->GetChar();
if ( c == EOF )
return EOF;
if ( c == L'/' )
return _pStream->GetChar();
}
}
}
else if ( c == L'/' )
{
// C++ style comment
while ((c = _pStream->GetChar()) != EOF )
{
if ( c == L'\n' )
break;
}
}
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::EatString, public
//
// Synopsis: Eats string literal
//
// Returns: First non-string character
//
// Requires: Leading '"' found and scanned
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::EatString()
{
int c;
while ((c = _pStream->GetChar()) != EOF )
{
if ( c == L'"' )
{
c = _pStream->GetChar();
break;
}
// eat backslashes
// skip escaped quotes
if ( c == L'\\' )
{
c = _pStream->GetChar();
if ( c == EOF )
return EOF;
}
}
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::EatCharLiteral, public
//
// Synopsis: Eats character literal
//
// Returns: First non-char-literal character
//
// Requires: Leading apostrophe ' found and scanned
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::EatCharLiteral()
{
int c;
while ((c = _pStream->GetChar()) != EOF )
{
if ( c == L'\'' )
{
c = _pStream->GetChar();
break;
}
// eat backslashes
// skip escaped quotes
if ( c == L'\\' )
{
c = _pStream->GetChar();
if ( c == EOF )
return EOF;
}
}
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxScanner::EatPrepro, public
//
// Synopsis: Eats preprocessor commands. Possibly multi-line.
//
// Returns: First non-preprocessor character
//
// Requires: Leading # found and scanned
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
int CxxScanner::EatPrepro()
{
int c;
_fScanningPrepro = FALSE;
while ((c = _pStream->GetChar()) != EOF && (c != L'\n'))
{
if ( c == L'\\' ) // skip whatever follows backslash
{
c = _pStream->GetChar();
if (c == L'\r')
c = _pStream->GetChar();
if ( c == EOF )
return EOF;
}
}
return c;
}
//+---------------------------------------------------------------------------
//
// Member: CxxParser::CxxParser, public
//
// Synopsis: Initialize parser
//
// Arguments: [pStm] -- stream
// [drep] -- data repository
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
CxxParser::CxxParser ()
: _scope(0),
_inClass(0),
_fParsingTypedef(FALSE),
_fParsingFnPtrTypedef(FALSE),
_iVal(0)
{
_strClass[0] = L'\0';
_strName[0] = L'\0';
_attribute.ulKind = PRSPEC_LPWSTR;
_attribute.lpwstr = PROP_CLASS;
_psVal[Function].ulKind = PRSPEC_LPWSTR;
_psVal[Function].lpwstr = PROP_FUNC;
_psVal[Class].ulKind = PRSPEC_LPWSTR;
_psVal[Class].lpwstr = PROP_CLASS;
_psVal[Lines].ulKind = PRSPEC_LPWSTR;
_psVal[Lines].lpwstr = PROP_LINES;
_aVal[Function] = 0;
_aVal[Class] = 0;
_aVal[Lines] = 0;
}
CxxParser::~CxxParser()
{
delete _aVal[Function];
delete _aVal[Class];
delete _aVal[Lines];
}
//+---------------------------------------------------------------------------
//
// Member: CxxParser::Init, public
//
// Synopsis: Initialize parser
//
// Arguments: [pStream] -- stream
//
// History: 24-Nov-93 AmyA Created
//
//----------------------------------------------------------------------------
void CxxParser::Init ( CFilterTextStream * pStream )
{
_scan.Init(pStream);
_token = _scan.Token();
}
//+---------------------------------------------------------------------------
//
// Member: CxxParser::Parse, public
//
// Synopsis: Parse the file
//
// History: 26-Jun-92 BartoszM Created
//
//----------------------------------------------------------------------------
BOOL CxxParser::Parse()
{
_cwcCopiedClass = 0;
_cwcCopiedName = 0;
while ( _token != tEnd)
{
switch ( _token )
{
case tTypedef:
if ( !_fParsingTypedef )
{
_fParsingTypedef = TRUE;
_typedefScope = _scope;
}
_token = _scan.Accept();
break;
case tSemi:
if ( _fParsingTypedef && ( _scope == _typedefScope ))
{
ASSERT(_fParsingFnPtrTypedef == FALSE);
SetName();
//DbgPrint("tSemi: name: %ws, scope: %d\n", _strName, _scope);
PutFunction();
_fParsingTypedef = FALSE;
_token = _scan.Accept();
return TRUE;
}
_token = _scan.Accept();
break;
case tComma:
if ( _fParsingTypedef && ( _scope == _typedefScope ))
{
ASSERT(_fParsingFnPtrTypedef == FALSE);
SetName();
//DbgPrint("tComma: name: %ws, scope: %d\n", _strName, _scope);
PutFunction();
_token = _scan.Accept();
return TRUE;
}
_token = _scan.Accept();
break;
case tEnum:
//DbgPrint("tEnum\n");
//_scan.IgnorePreamble(TRUE);
_token = _scan.Accept();
//_scan.IgnorePreamble(FALSE);
if ( _token == tLBrace )
{
// Good, we're inside a enum definition
_scope++;
SetName();
//DbgPrint("tEnum: %ws\n", _strName);
PutFunction();
_token = _scan.Accept();
return TRUE;
}
// otherwise it was a false alarm
break;
case tClass:
case tStruct:
case tUnion:
case tInterface:
// We have to recognize stuff like this:
// class FOO : public bar:a, private b {
// ----- --
// text between 'class' and left brace is
// a preamble that the scanner will skip
// If it's only a forward declaration, we
// will stop at a semicolon and ignore the
// whole business.
#if CIDBG == 1
_classToken = _token;
#endif // CIDBG == 1
// scan through stuff like
// : public foo, private bar
_scan.IgnorePreamble(TRUE);
_token = _scan.Accept();
_scan.IgnorePreamble(FALSE);
// Ignore embedded classes
if ( _inClass == 0 )
SetClass(); // record class name for later
if ( _token == tLBrace )
{
// Good, we're inside a class definition
_inClass++;
_scope++;
PutClass ();
_token = _scan.Accept();
return TRUE;
}
// otherwise it was a false alarm
break;
case tDoubleColon:
// Here we deal with constructs like
// FOO::FOO ( int x ) : bar(state::ok), (true) {
// -- - --
// Text between left paren and left brace is preamble
// and the scanner skips it. If we hit a semicolon
// rather than left brace, we ignore the whole
// construct (it was an invocation or something)
SetClass(); // record class name just in case
_token = _scan.Accept();
if ( _token == tLParen )
{
SetName(); // record method name just in case
_scan.IgnorePreamble(TRUE);
_token = _scan.Accept();
_scan.IgnorePreamble(FALSE);
if ( _token == tLBrace )
{
// Yes, we have method definition
_scope++;
_token = _scan.Accept();
PutMethod();
return TRUE;
}
// otherwise it was a false alarm
}
break;
case tLParen:
if ( _fParsingTypedef && ( _scope == _typedefScope ))
{
//
// at present we only support fn-ptr typedefs
// of the following type:
//
// typedef void (*FnPtr1) ( int i, float f );
//
//SetName();
//DbgPrint("tLParen: name: %ws, scope: %d\n", _strName, _scope);
_scan.SetIdFound(FALSE);
_token = _scan.Accept();
if ( ( _token == tStar ) && !_scan.IdFound() )
{
_fParsingFnPtrTypedef = TRUE;
}
else
{
//PutFunction();
_fParsingTypedef = FALSE;
_fParsingFnPtrTypedef = FALSE;
}
_token = _scan.Accept();
}
else
{
SetName(); // record procedure name just in case
// It may be an inline constructor
// skip argument list and constructor stuff like
// : Parent(blah), member(blah)
_scan.IgnorePreamble(TRUE);
_token = _scan.Accept();
_scan.IgnorePreamble(FALSE);
if ( _token == tLBrace )
{
// Yes, it's a definition
if ( _inClass )
{
// inline method definition inside class definition
_scope++;
_token = _scan.Accept();
PutInlineMethod();
return TRUE;
}
else if ( _scope == 0 )
{
// function definitions
// in outer scope
_scope++;
PutFunction();
_token = _scan.Accept();
return TRUE;
}
// else continue--false alarm
}
}
break;
case tRParen:
if ( _fParsingFnPtrTypedef && ( _scope == _typedefScope ))
{
SetName();
//DbgPrint("tRParen: name: %ws, scope: %d\n", _strName, _scope);
PutFunction();
_fParsingTypedef = FALSE;
_fParsingFnPtrTypedef = FALSE;
_token = _scan.Accept();
return TRUE;
}
_token = _scan.Accept();
break;
case tEnd:
return FALSE;
case tLBrace:
// keep track of scope
_scope++;
_token = _scan.Accept();
break;
case tRBrace:
// keep track of scope and (nested) class scope
_scope--;
if ( _inClass > _scope )
{
_inClass--;
}
_token = _scan.Accept();
break;
case tDefine:
SetName();
_regionName.cwcStart++;
_regionName.cwcExtent--;
PutFunction();
_scan.EatPrepro();
_token = _scan.Accept();
return TRUE;
case tInclude:
SetName();
PutFunction();
_token = _scan.Accept();
return TRUE;
default:
_token = _scan.Accept();
}
}
if ( _aVal[Lines] == 0 )
{
_aVal[Lines] = new CPropVar;
if ( 0 == _aVal[Lines] )
THROW( CException( E_OUTOFMEMORY ) );
}
_aVal[Lines]->SetUI4( _scan.Lines() );
return FALSE; // we only end up here if _token == tEnd
}
void CxxParser::PutClass ()
{
_tokenType = ttClass;
_attribute.lpwstr = PROP_CLASS;
_strName[0] = L'\0';
#if 0
if ( _aVal[Class] == 0 )
{
_aVal[Class] = new CPropVar;
if ( 0 == _aVal[Class] )
THROW( CException( E_OUTOFMEMORY ) );
}
_aVal[Class]->SetLPWSTR( _strClass, _aVal[Class]->Count() );
#endif
// PROP_CLASS, _strClass
//DbgPrint("PutClass: class: %ws\n", _strClass);
#if CIDBG == 1
if ( _classToken == tClass )
{
cxxDebugOut((DEB_ITRACE,"class %ws\n", _strClass ));
}
else if ( _classToken == tStruct )
{
cxxDebugOut((DEB_ITRACE, "struct %ws\n", _strClass ));
}
else if ( _classToken == tUnion )
{
cxxDebugOut((DEB_ITRACE, "union %ws\n", _strClass ));
}
else if ( _classToken == tInterface )
{
cxxDebugOut((DEB_ITRACE, "interface %ws\n", _strClass ));
}
#endif // CIDBG == 1
}
void CxxParser::PutMethod ()
{
_tokenType = ttMethod;
_attribute.lpwstr = PROP_FUNC;
#if 0
if ( _aVal[Function] == 0 )
{
_aVal[Function] = new CPropVar;
if ( 0 == _aVal[Function] )
THROW( CException( E_OUTOFMEMORY ) );
}
_aVal[Function]->SetLPWSTR( _strName, _aVal[Function]->Count() );
#endif
cxxDebugOut((DEB_ITRACE, "%ws::%ws\n", _strClass, _strName ));
}
void CxxParser::PutInlineMethod ()
{
_tokenType = ttInlineMethod;
_attribute.lpwstr = PROP_FUNC;
#if 0
if ( _aVal[Function] == 0 )
{
_aVal[Function] = new CPropVar;
if ( 0 == _aVal[Function] )
THROW( CException( E_OUTOFMEMORY ) );
}
_aVal[Function]->SetLPWSTR( _strName, _aVal[Function]->Count() );
#endif
cxxDebugOut((DEB_ITRACE, "%ws::%ws\n", _strClass, _strName ));
}
void CxxParser::PutFunction ()
{
_tokenType = ttFunction;
_attribute.lpwstr = PROP_FUNC;
_strClass[0] = L'\0';
#if 0
if ( _aVal[Function] == 0 )
{
_aVal[Function] = new CPropVar;
if ( 0 == _aVal[Function] )
THROW( CException( E_OUTOFMEMORY ) );
}
_aVal[Function]->SetLPWSTR( _strName, _aVal[Function]->Count() );
#endif
//DbgPrint("PutFunction: func: %ws\n", _strName);
cxxDebugOut((DEB_ITRACE, "function %ws\n", _strName ));
}
void CxxParser::GetRegion ( FILTERREGION& region )
{
switch (_tokenType)
{
case ttClass:
region = _regionClass;
break;
case ttFunction:
case ttInlineMethod:
case ttMethod:
region = _regionName;
break;
}
}
BOOL CxxParser::GetTokens ( ULONG * pcwcBuffer, WCHAR * awcBuffer )
{
ULONG cwc = *pcwcBuffer;
*pcwcBuffer = 0;
if (_strClass[0] != L'\0')
{
// We have a class name
WCHAR * strClass = _strClass + _cwcCopiedClass;
ULONG cwcClass = wcslen( strClass );
if ( cwcClass > cwc )
{
wcsncpy( awcBuffer, strClass, cwc );
_cwcCopiedClass += cwc;
return FALSE;
}
wcscpy( awcBuffer, strClass );
*pcwcBuffer = cwcClass;
_cwcCopiedClass += cwcClass;
awcBuffer[(*pcwcBuffer)++] = L' ';
}
if (_strName[0] == L'\0')
{
// it was only a class name
awcBuffer[*pcwcBuffer] = L'\0';
return TRUE;
}
cwc -= *pcwcBuffer;
WCHAR * awc = awcBuffer + *pcwcBuffer;
WCHAR * strName = _strName + _cwcCopiedName;
ULONG cwcName = wcslen( strName );
if ( cwcName > cwc )
{
wcsncpy( awc, strName, cwc );
_cwcCopiedName += cwc;
return FALSE;
}
wcscpy( awc, strName );
*pcwcBuffer += cwcName;
_cwcCopiedName += cwcName;
return TRUE;
}
BOOL CxxParser::GetValueAttribute( PROPSPEC & ps )
{
for ( ; _iVal <= Lines && 0 == _aVal[_iVal]; _iVal++ )
continue;
if ( _iVal > Lines )
return FALSE;
else
{
ps = _psVal[_iVal];
return TRUE;
}
}
PROPVARIANT * CxxParser::GetValue()
{
if ( _iVal > Lines )
return 0;
CPropVar * pTemp = _aVal[_iVal];
_aVal[_iVal] = 0;
_iVal++;
return (PROPVARIANT *)(void *)pTemp;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
01c692bfc851dec06b5ecdc88dec48bf7ed4dd6a | b538b8cdaac6d1e428a71db43b0ff054c688ad7d | /main_estadisticas.cpp | c9a090b13fb53163668b7d25cd328fbb1ef633cc | [] | no_license | GRADO-ULL/AEDA-Practica7-AVL-1516 | e19112458a144d01c78da9e07acb21be725d905b | e3a91a986d4ac52b4cd4586222f6618e5a0615b0 | refs/heads/master | 2021-01-13T12:44:52.286601 | 2017-01-10T11:10:08 | 2017-01-10T11:10:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,849 | cpp | #include<iostream>
#include<stdlib.h>
#include<vector>
#include "DNI.h"
#include "nodo.h"
#include "arbol.h"
using namespace std;
template <class TDATO>
bool comprobar_aleatorios_dni(vector<TDATO> v_aleatorios, int valor)
{
int contador = 0;
bool encontrado = false;
while(contador < v_aleatorios.size() && encontrado != true)
{
if(v_aleatorios[contador].get_value() == valor)
{
encontrado = true;
}
contador++;
}
return encontrado;
}
template <class TDATO>
void inicializacion_vector(vector<TDATO> &v, Arbol<TDATO> &arbol_, int tamanio)
{
v.resize(tamanio);
for(int i=0;i<tamanio;i++)
{
srand(clock());
int aux = 30000000 + rand()%(80000001-30000000);
while(comprobar_aleatorios_dni(v,aux))
{
aux = 30000000 + rand()%(80000001-30000000);
}
DNI d(aux);
v[i] = d;
arbol_.insertar(d);
}
}
bool comprobar_aleatorios_pruebas(vector<int> v_aleatorios, int valor)
{
int contador = 0;
bool encontrado = false;
while(contador < v_aleatorios.size() && encontrado != true)
{
if(v_aleatorios[contador] == valor)
{
encontrado = true;
}
contador++;
}
return encontrado;
}
void generar_aleatorios(vector<int> &v, int limite_inferior, int limite_superior)
{
for(int i=0;i<v.size();i++)
{
srand(clock());
int aux_p = limite_inferior+rand()%(((limite_superior + 1 ) -1) -limite_inferior);
while(comprobar_aleatorios_pruebas(v,aux_p))
{
aux_p = limite_inferior+rand()%(((limite_superior + 1 ) -1) -limite_inferior);
}
v[i] = aux_p;
/*cout << v[i];
if(i < v.size()-1)
{
cout << ",";
}*/
}
}
int main()
{
vector<TDATO> muestra; //Vector de tamanio 2N
vector<int> pruebas_busqueda;
vector<int> pruebas_insercion;
Arbol<TDATO> a1;
int numero_nodos = 0;
int numero_pruebas = 0;
cout << "-----PRACTICA 6. ARBOLES BINARIOS DE BUSQUEDA.-----" << endl;
cout << "Modo estadistico." << endl;
cout << "Introduzca numero de nodos[N]:";
cin >> numero_nodos;
cout << "Introduzca numero de pruebas[P]:";
cin >> numero_pruebas;
inicializacion_vector(muestra,a1, numero_nodos*2);
cout << "-----------------------------" << endl;
cout << "Fase de Busqueda." << endl;
cout << "Genero aleatorios para las pruebas." << endl;
//cout << "Vector de pruebas de dimension " << numero_pruebas << ": ";
pruebas_busqueda.resize(numero_pruebas);
generar_aleatorios(pruebas_busqueda,0,numero_nodos);
cout << endl;
int maximo_busqueda = 0;
int minimo_busqueda = 100000000;
double suma_busqueda = 0;
double media_busqueda = 0;
DNI::comparaciones = 0;
for(int i=0;i<numero_pruebas;i++)
{
a1.buscar(muestra[pruebas_busqueda[i]]);
//cout << "DNI::comparaciones: " << DNI::comparaciones << endl;
if(maximo_busqueda<DNI::comparaciones)
maximo_busqueda = DNI::comparaciones;
if(minimo_busqueda>DNI::comparaciones)
minimo_busqueda = DNI::comparaciones;
suma_busqueda += DNI::comparaciones;
DNI::comparaciones = 0;
}
media_busqueda = suma_busqueda / numero_pruebas;
cout << endl;
cout << "-----------------------------" << endl;
cout << "Fase de insercion." << endl;
pruebas_insercion.resize(numero_pruebas);
cout << "Genero aleatorios para las pruebas." << endl;
//cout << "Vector de pruebas de dimension " << numero_pruebas << ": ";
int maximo_insercion = 0;
int minimo_insercion = 100000000;
double suma_insercion = 0;
double media_insercion = 0;
//Inicializando vector
generar_aleatorios(pruebas_insercion,numero_nodos,2*numero_nodos);
DNI::comparaciones = 0;
for(int i=0;i<numero_pruebas;i++)
{
a1.buscar(muestra[pruebas_insercion[i]]);
//cout << "DNI::comparaciones: " << DNI::comparaciones << endl;
if(maximo_insercion<DNI::comparaciones)
maximo_insercion = DNI::comparaciones;
if(minimo_insercion>DNI::comparaciones)
minimo_insercion = DNI::comparaciones;
suma_insercion += DNI::comparaciones;
DNI::comparaciones = 0;
}
media_insercion = suma_insercion / numero_pruebas;
cout << endl;
cout << "-----------------------------" << endl;
cout << "ESTADISTICAS" << endl;
cout << "\t\tN\tP\tMinimo\tMedio\tMaximo"<<endl;
cout << "Busqueda\t"<<numero_nodos<<"\t"<<numero_pruebas<<"\t"<<minimo_busqueda<<"\t"<<media_busqueda<<"\t"<<maximo_busqueda<<endl;
cout << "Insercion\t"<<numero_nodos<<"\t"<<numero_pruebas<<"\t"<<minimo_insercion<<"\t"<<media_insercion<<"\t"<<maximo_insercion<<endl;
cout << endl;
return 0;
} | [
"alu0100763492@ull.edu.es"
] | alu0100763492@ull.edu.es |
fb619913e797b3e1b8828628b44468a7eb98eac2 | 0533dc09967a4d94ee89a6b19edf3c51358966c3 | /include/ATHandler.hpp | 002fb45a762b106684f7b29d49f07e2929e2dfc1 | [] | no_license | mewanthahayesh/ArduinoBasicWifiNode | a6d91856fdd2d81a1f9680ae55db1724244903b0 | ff01c35487f687c6b77d439b99cec390711ed4fc | refs/heads/master | 2020-11-24T06:07:33.814439 | 2019-12-17T05:43:33 | 2019-12-17T05:43:33 | 228,000,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | hpp | #ifndef ATHANDLER
#define ATHANDLER
#include <Arduino.h>
#include <SoftwareSerial.h>
typedef struct {
const char* expectedResponse;
unsigned long timeout;
char* responseBuf;
uint16_t responseBufLen;
}ATResponseConfig;
class ATHandler{
private:
SoftwareSerial* espSerial;
public:
void sendAT(const char* atcommand,uint16_t len); //function to send AT commands to the ESP
int receiveATResponse(ATResponseConfig responseRecv); //to receive AT responses from ESP
void initESP8266SerialComm(SoftwareSerial* espSerial); //initializes the serial port to communicate
};
#endif | [
"hayeshkaluarachchi@gmail.com"
] | hayeshkaluarachchi@gmail.com |
426daae5bc9de43f70c6aff412b6fd75c99cc2b0 | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.hxx | 9a25236c809e279fa9ab8f82864f30740296cc5e | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"Zlib",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Spencer-86",
"Apache-2.0",
"FSFUL",
"LicenseRef-scancode-public-domain",
"Libpng",
"BSD-2-Clause"
] | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 4,989 | hxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkVectorNeighborhoodOperatorImageFilter_hxx
#define itkVectorNeighborhoodOperatorImageFilter_hxx
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkVectorNeighborhoodInnerProduct.h"
#include "itkImageRegionIterator.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkProgressReporter.h"
namespace itk
{
template< typename TInputImage, typename TOutputImage >
void
VectorNeighborhoodOperatorImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method. this should
// copy the output requested region to the input requested region
Superclass::GenerateInputRequestedRegion();
// get pointers to the input and output
InputImagePointer inputPtr =
const_cast< InputImageType * >( this->GetInput() );
if ( !inputPtr )
{
return;
}
// get a copy of the input requested region (should equal the output
// requested region)
typename TInputImage::RegionType inputRequestedRegion;
inputRequestedRegion = inputPtr->GetRequestedRegion();
// pad the input requested region by the operator radius
inputRequestedRegion.PadByRadius( m_Operator.GetRadius() );
// crop the input requested region at the input's largest possible region
if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) )
{
inputPtr->SetRequestedRegion(inputRequestedRegion);
return;
}
else
{
// Couldn't crop the region (requested region is outside the largest
// possible region). Throw an exception.
// store what we tried to request (prior to trying to crop)
inputPtr->SetRequestedRegion(inputRequestedRegion);
// build an exception
InvalidRequestedRegionError e(__FILE__, __LINE__);
e.SetLocation(ITK_LOCATION);
e.SetDescription("Requested region is (at least partially) outside the largest possible region.");
e.SetDataObject(inputPtr);
throw e;
}
}
template< typename TInputImage, typename TOutputImage >
void
VectorNeighborhoodOperatorImageFilter< TInputImage, TOutputImage >
::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType threadId)
{
typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< InputImageType > BFC;
typedef typename BFC::FaceListType FaceListType;
VectorNeighborhoodInnerProduct< InputImageType > smartInnerProduct;
BFC faceCalculator;
FaceListType faceList;
// Allocate output
OutputImageType * output = this->GetOutput();
const InputImageType *input = this->GetInput();
// Break the input into a series of regions. The first region is free
// of boundary conditions, the rest with boundary conditions. Note,
// we pass in the input image and the OUTPUT requested region. We are
// only concerned with centering the neighborhood operator at the
// pixels that correspond to output pixels.
faceList = faceCalculator( input, outputRegionForThread,
m_Operator.GetRadius() );
typename FaceListType::iterator fit;
// support progress methods/callbacks
ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );
ImageRegionIterator< OutputImageType > it;
// Process non-boundary region and then each of the boundary faces.
// These are N-d regions which border the edge of the buffer.
ConstNeighborhoodIterator< InputImageType > bit;
for ( fit = faceList.begin(); fit != faceList.end(); ++fit )
{
bit =
ConstNeighborhoodIterator< InputImageType >(m_Operator.GetRadius(),
input, *fit);
it = ImageRegionIterator< OutputImageType >(output, *fit);
bit.GoToBegin();
while ( !bit.IsAtEnd() )
{
it.Value() = smartInnerProduct(bit, m_Operator);
++bit;
++it;
progress.CompletedPixel();
}
}
}
} // end namespace itk
#endif
| [
"ruizhi@csail.mit.edu"
] | ruizhi@csail.mit.edu |
57b278f95bf2cb20d1dc8af3cf1434addd42d053 | 233bb1e4117bc5ef95b0360881fe95a7ba3ffb70 | /main.cpp | 7a93053f2db4e0817bfee33ef8f7c2e9b447e1b2 | [] | no_license | hyoyup/Raytracing | 3c5e116a7f2f15e0e7bdf408af139907932c809d | d4b7c51d47caae02f58f7c87a90ce12cefc87ef7 | refs/heads/master | 2020-03-27T09:32:31.615521 | 2018-08-27T20:36:37 | 2018-08-27T20:36:37 | 146,350,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,269 | cpp | ///////////////////////////////////////////////////////////////////////
// Provides the framework a raytracer.
//
// Gary Herron
// updated by Hyoyup Chung in 2018
//
// Copyright 2012 DigiPen Institute of Technology
////////////////////////////////////////////////////////////////////////
#include <fstream>
#include <sstream>
#include <vector>
#include <string.h>
#include <ctime>
#include <iostream>
#ifdef _WIN32
// Includes for Windows
#include <windows.h>
#include <cstdlib>
#include <limits>
#include <crtdbg.h>
#else
// Includes for Linux
#include <stdlib.h>
#include <time.h>
#include <chrono>
#endif
#include "geom.h"
//#include "raytrace.h"
#include "Scene.h"
#include "Ray.h"
#include "Shape.h"
// Read a scene file by parsing each line as a command and calling
// scene->Command(...) with the results.
void ReadScene(const std::string inName, Scene* scene)
{
std::ifstream input(inName.c_str());
if (input.fail()) {
std::cerr << "File not found: " << inName << std::endl;
fflush(stderr);
exit(-1); }
// For each line in file
for (std::string line; getline(input, line); ) {
std::vector<std::string> strings;
std::vector<float> floats;
// Parse as parallel lists of strings and floats
std::stringstream lineStream(line);
for (std::string s; lineStream >> s; ) { // Parses space-separated strings until EOL
float f;
//std::stringstream(s) >> f; // Parses an initial float into f, or zero if illegal
if (!(std::stringstream(s) >> f)) f = nan(""); // An alternate that produced NANs
floats.push_back(f);
strings.push_back(s); }
if (strings.size() == 0) continue; // Skip blanks lines
if (strings[0][0] == '#') continue; // Skip comment lines
// Pass the line's data to Command(...)
scene->Command(strings, floats);
}
input.close();
}
////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
//bool linearEnabled = true; // for benchmark linear vs KdBVH
float p_diff = 0.7f;
float p_spec = 0.3f;
float p_refr = 0.0f; // NO Refraction for proj3
Scene* scene = new Scene(p_diff,p_spec,p_refr);
// Read the command line argument
std::string inName = (argc > 1) ? argv[1] : "testscene.scn";
std::string hdrName = "testscene";
//hdrName.replace(hdrName.size()-3, hdrName.size(), "hdr");
// Read the scene, calling scene.Command for each line.
ReadScene(inName, scene);
scene->Finit();
// Allocate and clear an image array
Color *image = new Color[scene->width*scene->height];
for (int y=0; y<scene->height; y++)
for (int x=0; x<scene->width; x++)
image[y*scene->width + x] = Color(0,0,0);
int writeEvery = 64;
int endAt = 64;
std::cout << "every: "<< writeEvery <<std::endl;
std::cout << "end at: "<< endAt <<std::endl;
std::cout << "KdBVH: Raytracer starting now...\n";
auto start = std::chrono::high_resolution_clock::now();
scene->TraceImageKdBVH(image, hdrName, writeEvery, endAt);
auto end = std::chrono::high_resolution_clock::now();
auto dur = end - start;
auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
std::cout << "\ttime in seconds: " << f_secs.count() << '\n';
std::cout << "KdBVH: Raytracer finished...\n\n";
// RayTrace the image using KdBVH
// std::cout << "KdBVH: Raytracer starting now...\n";
// auto start = std::chrono::high_resolution_clock::now();
// scene->TraceImageKdBVH(image, 1);
// auto end = std::chrono::high_resolution_clock::now();
// auto dur = end - start;
// auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
// std::cout << "\ttime in seconds: " << f_secs.count() << '\n';
// std::cout << "KdBVH: Raytracer finished...\n\n";
// Write the image
//WriteHdrImage(hdrName, scene->width, scene->height, image);
delete[] image;
delete scene;
}
| [
"noreply@github.com"
] | hyoyup.noreply@github.com |
1624ebcdaadd7688dd3d36b3617581b4889c61bd | ac227cc22d5f5364e5d029a2cef83816a6954590 | /applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_NODE_VECTOR_FIELD.cpp | d748e7853123abf809b0db19f75d0e80f7edbf17 | [
"BSD-3-Clause"
] | permissive | schinmayee/nimbus | 597185bc8bac91a2480466cebc8b337f5d96bd2e | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | refs/heads/master | 2020-03-11T11:42:39.262834 | 2018-04-18T01:28:23 | 2018-04-18T01:28:23 | 129,976,755 | 0 | 0 | BSD-3-Clause | 2018-04-17T23:33:23 | 2018-04-17T23:33:23 | null | UTF-8 | C++ | false | false | 3,518 | cpp | #ifndef COMPILE_WITHOUT_DYADIC_SUPPORT
//#####################################################################
// Copyright 2004-2005, Frank Losasso, Andrew Selle.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Grids_Dyadic/DYADIC_GRID_ITERATOR_NODE.h>
#include <PhysBAM_Geometry/Basic_Geometry/ORIENTED_BOX.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_GRID.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_NODE_VECTOR_FIELD.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_SLICE.h>
using namespace PhysBAM;
//#####################################################################
// Update
//#####################################################################
template<class T> void OPENGL_OCTREE_NODE_VECTOR_FIELD<T>::
Update()
{
vector_field.Resize(0);
vector_locations.Resize(0);
if(V.m==0) return;
ARRAY<bool> active(grid.number_of_nodes);
if(this->slice && this->slice->Is_Slice_Mode()){
int number_of_active_nodes=0;
OPENGL_OCTREE_SLICE* slice=(OPENGL_OCTREE_SLICE*)this->slice;
for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_All_Nodes());iterator.Valid();iterator.Next())
if(abs(iterator.Location()[slice->axis]-slice->position)<.00001){number_of_active_nodes++;active(iterator.Node_Index())=true;}
vector_field.Resize(number_of_active_nodes);
vector_locations.Resize(number_of_active_nodes);
int current_node=0;
for(int i=1;i<=grid.number_of_nodes;i++)if(active(i)){current_node++;
vector_locations(current_node)=grid.Node_Location(i);
vector_field(current_node)=V(i);}}
else{
vector_field.Resize(grid.number_of_nodes);
vector_locations.Resize(grid.number_of_nodes);
for(int i=1;i<=grid.number_of_nodes;i++){
vector_locations(i)=grid.Node_Location(i);
vector_field(i)=V(i);}}
}
//#####################################################################
// Slice_Has_Changed
//#####################################################################
template<class T> void OPENGL_OCTREE_NODE_VECTOR_FIELD<T>::
Slice_Has_Changed()
{
Update();
}
//#####################################################################
// Bounding_Box
//#####################################################################
template<class T> RANGE<VECTOR<float,3> > OPENGL_OCTREE_NODE_VECTOR_FIELD<T>::
Bounding_Box() const
{
return World_Space_Box(RANGE<VECTOR<float,3> >(grid.uniform_grid.domain));
}
//#####################################################################
// Print_Selection_Info
//#####################################################################
template<class T> void OPENGL_OCTREE_NODE_VECTOR_FIELD<T>::
Print_Selection_Info(std::ostream& output_stream,OPENGL_SELECTION* current_selection) const
{
if(current_selection && current_selection->type==OPENGL_SELECTION::OCTREE_NODE){
int index=((OPENGL_SELECTION_OCTREE_NODE<T>*)current_selection)->index;
output_stream<<V(index);}
output_stream<<std::endl;
}
//#####################################################################
template class OPENGL_OCTREE_NODE_VECTOR_FIELD<float>;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class OPENGL_OCTREE_NODE_VECTOR_FIELD<double>;
#endif
#endif
| [
"quhang@stanford.edu"
] | quhang@stanford.edu |
c46bf69883272311ab1f79de940a45d72fa7c3c5 | a00d005ff31b85fae96e35b90c34bb810d1e9c5a | /source/i18n/uspoof_impl.cpp | 995ecdac19eb020fa81f9b8218ae8af67c39ea8a | [
"LicenseRef-scancode-unicode",
"BSD-3-Clause",
"ICU",
"NAIST-2003",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | auxten/static-libicu | 91de4644497ff720defb4a9925c9863d96e0a725 | 174f351c74cc6c2e85e8a2d26400eec0d90ccac1 | refs/heads/master | 2020-06-06T21:02:20.972289 | 2019-06-20T05:32:38 | 2019-06-20T05:32:38 | 192,851,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,467 | cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2008-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*/
#include "unicode/utypes.h"
#include "unicode/uspoof.h"
#include "unicode/uchar.h"
#include "unicode/uniset.h"
#include "unicode/utf16.h"
#include "utrie2.h"
#include "cmemory.h"
#include "cstring.h"
#include "scriptset.h"
#include "umutex.h"
#include "udataswp.h"
#include "uassert.h"
#include "ucln_in.h"
#include "uspoof_impl.h"
#if !UCONFIG_NO_NORMALIZATION
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SpoofImpl)
SpoofImpl::SpoofImpl(SpoofData *data, UErrorCode& status) {
construct(status);
fSpoofData = data;
}
SpoofImpl::SpoofImpl(UErrorCode& status) {
construct(status);
// TODO: Call this method where it is actually needed, instead of in the
// constructor, to allow for lazy data loading. See #12696.
fSpoofData = SpoofData::getDefault(status);
}
SpoofImpl::SpoofImpl() {
UErrorCode status = U_ZERO_ERROR;
construct(status);
// TODO: Call this method where it is actually needed, instead of in the
// constructor, to allow for lazy data loading. See #12696.
fSpoofData = SpoofData::getDefault(status);
}
void SpoofImpl::construct(UErrorCode& status) {
fChecks = USPOOF_ALL_CHECKS;
fSpoofData = NULL;
fAllowedCharsSet = NULL;
fAllowedLocales = NULL;
fRestrictionLevel = USPOOF_HIGHLY_RESTRICTIVE;
if (U_FAILURE(status)) { return; }
UnicodeSet *allowedCharsSet = new UnicodeSet(0, 0x10ffff);
fAllowedCharsSet = allowedCharsSet;
fAllowedLocales = uprv_strdup("");
if (fAllowedCharsSet == NULL || fAllowedLocales == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
allowedCharsSet->freeze();
}
// Copy Constructor, used by the user level clone() function.
SpoofImpl::SpoofImpl(const SpoofImpl &src, UErrorCode &status) :
fChecks(USPOOF_ALL_CHECKS), fSpoofData(NULL), fAllowedCharsSet(NULL) ,
fAllowedLocales(NULL) {
if (U_FAILURE(status)) {
return;
}
fChecks = src.fChecks;
if (src.fSpoofData != NULL) {
fSpoofData = src.fSpoofData->addReference();
}
fAllowedCharsSet = static_cast<const UnicodeSet *>(src.fAllowedCharsSet->clone());
fAllowedLocales = uprv_strdup(src.fAllowedLocales);
if (fAllowedCharsSet == NULL || fAllowedLocales == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
fRestrictionLevel = src.fRestrictionLevel;
}
SpoofImpl::~SpoofImpl() {
if (fSpoofData != NULL) {
fSpoofData->removeReference(); // Will delete if refCount goes to zero.
}
delete fAllowedCharsSet;
uprv_free((void *)fAllowedLocales);
}
// Cast this instance as a USpoofChecker for the C API.
USpoofChecker *SpoofImpl::asUSpoofChecker() {
return exportForC();
}
//
// Incoming parameter check on Status and the SpoofChecker object
// received from the C API.
//
const SpoofImpl *SpoofImpl::validateThis(const USpoofChecker *sc, UErrorCode &status) {
auto* This = validate(sc, status);
if (U_FAILURE(status)) {
return NULL;
}
if (This->fSpoofData != NULL && !This->fSpoofData->validateDataVersion(status)) {
return NULL;
}
return This;
}
SpoofImpl *SpoofImpl::validateThis(USpoofChecker *sc, UErrorCode &status) {
return const_cast<SpoofImpl *>
(SpoofImpl::validateThis(const_cast<const USpoofChecker *>(sc), status));
}
void SpoofImpl::setAllowedLocales(const char *localesList, UErrorCode &status) {
UnicodeSet allowedChars;
UnicodeSet *tmpSet = NULL;
const char *locStart = localesList;
const char *locEnd = NULL;
const char *localesListEnd = localesList + uprv_strlen(localesList);
int32_t localeListCount = 0; // Number of locales provided by caller.
// Loop runs once per locale from the localesList, a comma separated list of locales.
do {
locEnd = uprv_strchr(locStart, ',');
if (locEnd == NULL) {
locEnd = localesListEnd;
}
while (*locStart == ' ') {
locStart++;
}
const char *trimmedEnd = locEnd-1;
while (trimmedEnd > locStart && *trimmedEnd == ' ') {
trimmedEnd--;
}
if (trimmedEnd <= locStart) {
break;
}
const char *locale = uprv_strndup(locStart, (int32_t)(trimmedEnd + 1 - locStart));
localeListCount++;
// We have one locale from the locales list.
// Add the script chars for this locale to the accumulating set of allowed chars.
// If the locale is no good, we will be notified back via status.
addScriptChars(locale, &allowedChars, status);
uprv_free((void *)locale);
if (U_FAILURE(status)) {
break;
}
locStart = locEnd + 1;
} while (locStart < localesListEnd);
// If our caller provided an empty list of locales, we disable the allowed characters checking
if (localeListCount == 0) {
uprv_free((void *)fAllowedLocales);
fAllowedLocales = uprv_strdup("");
tmpSet = new UnicodeSet(0, 0x10ffff);
if (fAllowedLocales == NULL || tmpSet == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
tmpSet->freeze();
delete fAllowedCharsSet;
fAllowedCharsSet = tmpSet;
fChecks &= ~USPOOF_CHAR_LIMIT;
return;
}
// Add all common and inherited characters to the set of allowed chars.
UnicodeSet tempSet;
tempSet.applyIntPropertyValue(UCHAR_SCRIPT, USCRIPT_COMMON, status);
allowedChars.addAll(tempSet);
tempSet.applyIntPropertyValue(UCHAR_SCRIPT, USCRIPT_INHERITED, status);
allowedChars.addAll(tempSet);
// If anything went wrong, we bail out without changing
// the state of the spoof checker.
if (U_FAILURE(status)) {
return;
}
// Store the updated spoof checker state.
tmpSet = static_cast<UnicodeSet *>(allowedChars.clone());
const char *tmpLocalesList = uprv_strdup(localesList);
if (tmpSet == NULL || tmpLocalesList == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_free((void *)fAllowedLocales);
fAllowedLocales = tmpLocalesList;
tmpSet->freeze();
delete fAllowedCharsSet;
fAllowedCharsSet = tmpSet;
fChecks |= USPOOF_CHAR_LIMIT;
}
const char * SpoofImpl::getAllowedLocales(UErrorCode &/*status*/) {
return fAllowedLocales;
}
// Given a locale (a language), add all the characters from all of the scripts used with that language
// to the allowedChars UnicodeSet
void SpoofImpl::addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status) {
UScriptCode scripts[30];
int32_t numScripts = uscript_getCode(locale, scripts, UPRV_LENGTHOF(scripts), &status);
if (U_FAILURE(status)) {
return;
}
if (status == U_USING_DEFAULT_WARNING) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
UnicodeSet tmpSet;
int32_t i;
for (i=0; i<numScripts; i++) {
tmpSet.applyIntPropertyValue(UCHAR_SCRIPT, scripts[i], status);
allowedChars->addAll(tmpSet);
}
}
// Computes the augmented script set for a code point, according to UTS 39 section 5.1.
void SpoofImpl::getAugmentedScriptSet(UChar32 codePoint, ScriptSet& result, UErrorCode& status) {
result.resetAll();
result.setScriptExtensions(codePoint, status);
if (U_FAILURE(status)) { return; }
// Section 5.1 step 1
if (result.test(USCRIPT_HAN, status)) {
result.set(USCRIPT_HAN_WITH_BOPOMOFO, status);
result.set(USCRIPT_JAPANESE, status);
result.set(USCRIPT_KOREAN, status);
}
if (result.test(USCRIPT_HIRAGANA, status)) {
result.set(USCRIPT_JAPANESE, status);
}
if (result.test(USCRIPT_KATAKANA, status)) {
result.set(USCRIPT_JAPANESE, status);
}
if (result.test(USCRIPT_HANGUL, status)) {
result.set(USCRIPT_KOREAN, status);
}
if (result.test(USCRIPT_BOPOMOFO, status)) {
result.set(USCRIPT_HAN_WITH_BOPOMOFO, status);
}
// Section 5.1 step 2
if (result.test(USCRIPT_COMMON, status) || result.test(USCRIPT_INHERITED, status)) {
result.setAll();
}
}
// Computes the resolved script set for a string, according to UTS 39 section 5.1.
void SpoofImpl::getResolvedScriptSet(const UnicodeString& input, ScriptSet& result, UErrorCode& status) const {
getResolvedScriptSetWithout(input, USCRIPT_CODE_LIMIT, result, status);
}
// Computes the resolved script set for a string, omitting characters having the specified script.
// If USCRIPT_CODE_LIMIT is passed as the second argument, all characters are included.
void SpoofImpl::getResolvedScriptSetWithout(const UnicodeString& input, UScriptCode script, ScriptSet& result, UErrorCode& status) const {
result.setAll();
ScriptSet temp;
UChar32 codePoint;
for (int32_t i = 0; i < input.length(); i += U16_LENGTH(codePoint)) {
codePoint = input.char32At(i);
// Compute the augmented script set for the character
getAugmentedScriptSet(codePoint, temp, status);
if (U_FAILURE(status)) { return; }
// Intersect the augmented script set with the resolved script set, but only if the character doesn't
// have the script specified in the function call
if (script == USCRIPT_CODE_LIMIT || !temp.test(script, status)) {
result.intersect(temp);
}
}
}
// Computes the set of numerics for a string, according to UTS 39 section 5.3.
void SpoofImpl::getNumerics(const UnicodeString& input, UnicodeSet& result, UErrorCode& /*status*/) const {
result.clear();
UChar32 codePoint;
for (int32_t i = 0; i < input.length(); i += U16_LENGTH(codePoint)) {
codePoint = input.char32At(i);
// Store a representative character for each kind of decimal digit
if (u_charType(codePoint) == U_DECIMAL_DIGIT_NUMBER) {
// Store the zero character as a representative for comparison.
// Unicode guarantees it is codePoint - value
result.add(codePoint - (UChar32)u_getNumericValue(codePoint));
}
}
}
// Computes the restriction level of a string, according to UTS 39 section 5.2.
URestrictionLevel SpoofImpl::getRestrictionLevel(const UnicodeString& input, UErrorCode& status) const {
// Section 5.2 step 1:
if (!fAllowedCharsSet->containsAll(input)) {
return USPOOF_UNRESTRICTIVE;
}
// Section 5.2 step 2
// Java use a static UnicodeSet for this test. In C++, avoid the static variable
// and just do a simple for loop.
UBool allASCII = TRUE;
for (int32_t i=0, length=input.length(); i<length; i++) {
if (input.charAt(i) > 0x7f) {
allASCII = FALSE;
break;
}
}
if (allASCII) {
return USPOOF_ASCII;
}
// Section 5.2 steps 3:
ScriptSet resolvedScriptSet;
getResolvedScriptSet(input, resolvedScriptSet, status);
if (U_FAILURE(status)) { return USPOOF_UNRESTRICTIVE; }
// Section 5.2 step 4:
if (!resolvedScriptSet.isEmpty()) {
return USPOOF_SINGLE_SCRIPT_RESTRICTIVE;
}
// Section 5.2 step 5:
ScriptSet resolvedNoLatn;
getResolvedScriptSetWithout(input, USCRIPT_LATIN, resolvedNoLatn, status);
if (U_FAILURE(status)) { return USPOOF_UNRESTRICTIVE; }
// Section 5.2 step 6:
if (resolvedNoLatn.test(USCRIPT_HAN_WITH_BOPOMOFO, status)
|| resolvedNoLatn.test(USCRIPT_JAPANESE, status)
|| resolvedNoLatn.test(USCRIPT_KOREAN, status)) {
return USPOOF_HIGHLY_RESTRICTIVE;
}
// Section 5.2 step 7:
if (!resolvedNoLatn.isEmpty()
&& !resolvedNoLatn.test(USCRIPT_CYRILLIC, status)
&& !resolvedNoLatn.test(USCRIPT_GREEK, status)
&& !resolvedNoLatn.test(USCRIPT_CHEROKEE, status)) {
return USPOOF_MODERATELY_RESTRICTIVE;
}
// Section 5.2 step 8:
return USPOOF_MINIMALLY_RESTRICTIVE;
}
int32_t SpoofImpl::findHiddenOverlay(const UnicodeString& input, UErrorCode&) const {
bool sawLeadCharacter = false;
for (int32_t i=0; i<input.length();) {
UChar32 cp = input.char32At(i);
if (sawLeadCharacter && cp == 0x0307) {
return i;
}
uint8_t combiningClass = u_getCombiningClass(cp);
// Skip over characters except for those with combining class 0 (non-combining characters) or with
// combining class 230 (same class as U+0307)
U_ASSERT(u_getCombiningClass(0x0307) == 230);
if (combiningClass == 0 || combiningClass == 230) {
sawLeadCharacter = isIllegalCombiningDotLeadCharacter(cp);
}
i += U16_LENGTH(cp);
}
return -1;
}
static inline bool isIllegalCombiningDotLeadCharacterNoLookup(UChar32 cp) {
return cp == u'i' || cp == u'j' || cp == u'ı' || cp == u'ȷ' || cp == u'l' ||
u_hasBinaryProperty(cp, UCHAR_SOFT_DOTTED);
}
bool SpoofImpl::isIllegalCombiningDotLeadCharacter(UChar32 cp) const {
if (isIllegalCombiningDotLeadCharacterNoLookup(cp)) {
return true;
}
UnicodeString skelStr;
fSpoofData->confusableLookup(cp, skelStr);
UChar32 finalCp = skelStr.char32At(skelStr.moveIndex32(skelStr.length(), -1));
if (finalCp != cp && isIllegalCombiningDotLeadCharacterNoLookup(finalCp)) {
return true;
}
return false;
}
// Convert a text format hex number. Utility function used by builder code. Static.
// Input: UChar *string text. Output: a UChar32
// Input has been pre-checked, and will have no non-hex chars.
// The number must fall in the code point range of 0..0x10ffff
// Static Function.
UChar32 SpoofImpl::ScanHex(const UChar *s, int32_t start, int32_t limit, UErrorCode &status) {
if (U_FAILURE(status)) {
return 0;
}
U_ASSERT(limit-start > 0);
uint32_t val = 0;
int i;
for (i=start; i<limit; i++) {
int digitVal = s[i] - 0x30;
if (digitVal>9) {
digitVal = 0xa + (s[i] - 0x41); // Upper Case 'A'
}
if (digitVal>15) {
digitVal = 0xa + (s[i] - 0x61); // Lower Case 'a'
}
U_ASSERT(digitVal <= 0xf);
val <<= 4;
val += digitVal;
}
if (val > 0x10ffff) {
status = U_PARSE_ERROR;
val = 0;
}
return (UChar32)val;
}
//-----------------------------------------
//
// class CheckResult Implementation
//
//-----------------------------------------
CheckResult::CheckResult() {
clear();
}
USpoofCheckResult* CheckResult::asUSpoofCheckResult() {
return exportForC();
}
//
// Incoming parameter check on Status and the CheckResult object
// received from the C API.
//
const CheckResult* CheckResult::validateThis(const USpoofCheckResult *ptr, UErrorCode &status) {
return validate(ptr, status);
}
CheckResult* CheckResult::validateThis(USpoofCheckResult *ptr, UErrorCode &status) {
return validate(ptr, status);
}
void CheckResult::clear() {
fChecks = 0;
fNumerics.clear();
fRestrictionLevel = USPOOF_UNDEFINED_RESTRICTIVE;
}
int32_t CheckResult::toCombinedBitmask(int32_t enabledChecks) {
if ((enabledChecks & USPOOF_AUX_INFO) != 0 && fRestrictionLevel != USPOOF_UNDEFINED_RESTRICTIVE) {
return fChecks | fRestrictionLevel;
} else {
return fChecks;
}
}
CheckResult::~CheckResult() {
}
//----------------------------------------------------------------------------------------------
//
// class SpoofData Implementation
//
//----------------------------------------------------------------------------------------------
UBool SpoofData::validateDataVersion(UErrorCode &status) const {
if (U_FAILURE(status) ||
fRawData == NULL ||
fRawData->fMagic != USPOOF_MAGIC ||
fRawData->fFormatVersion[0] != USPOOF_CONFUSABLE_DATA_FORMAT_VERSION ||
fRawData->fFormatVersion[1] != 0 ||
fRawData->fFormatVersion[2] != 0 ||
fRawData->fFormatVersion[3] != 0) {
status = U_INVALID_FORMAT_ERROR;
return FALSE;
}
return TRUE;
}
static UBool U_CALLCONV
spoofDataIsAcceptable(void *context,
const char * /* type */, const char * /*name*/,
const UDataInfo *pInfo) {
if(
pInfo->size >= 20 &&
pInfo->isBigEndian == U_IS_BIG_ENDIAN &&
pInfo->charsetFamily == U_CHARSET_FAMILY &&
pInfo->dataFormat[0] == 0x43 && // dataFormat="Cfu "
pInfo->dataFormat[1] == 0x66 &&
pInfo->dataFormat[2] == 0x75 &&
pInfo->dataFormat[3] == 0x20 &&
pInfo->formatVersion[0] == USPOOF_CONFUSABLE_DATA_FORMAT_VERSION
) {
UVersionInfo *version = static_cast<UVersionInfo *>(context);
if(version != NULL) {
uprv_memcpy(version, pInfo->dataVersion, 4);
}
return TRUE;
} else {
return FALSE;
}
}
// Methods for the loading of the default confusables data file. The confusable
// data is loaded only when it is needed.
//
// SpoofData::getDefault() - Return the default confusables data, and call the
// initOnce() if it is not available. Adds a reference
// to the SpoofData that the caller is responsible for
// decrementing when they are done with the data.
//
// uspoof_loadDefaultData - Called once, from initOnce(). The resulting SpoofData
// is shared by all spoof checkers using the default data.
//
// uspoof_cleanupDefaultData - Called during cleanup.
//
static UInitOnce gSpoofInitDefaultOnce = U_INITONCE_INITIALIZER;
static SpoofData* gDefaultSpoofData;
static UBool U_CALLCONV
uspoof_cleanupDefaultData(void) {
if (gDefaultSpoofData) {
// Will delete, assuming all user-level spoof checkers were closed.
gDefaultSpoofData->removeReference();
gDefaultSpoofData = nullptr;
gSpoofInitDefaultOnce.reset();
}
return TRUE;
}
static void U_CALLCONV uspoof_loadDefaultData(UErrorCode& status) {
UDataMemory *udm = udata_openChoice(nullptr, "cfu", "confusables",
spoofDataIsAcceptable,
nullptr, // context, would receive dataVersion if supplied.
&status);
if (U_FAILURE(status)) { return; }
gDefaultSpoofData = new SpoofData(udm, status);
if (U_FAILURE(status)) {
delete gDefaultSpoofData;
gDefaultSpoofData = nullptr;
return;
}
if (gDefaultSpoofData == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
ucln_i18n_registerCleanup(UCLN_I18N_SPOOFDATA, uspoof_cleanupDefaultData);
}
SpoofData* SpoofData::getDefault(UErrorCode& status) {
umtx_initOnce(gSpoofInitDefaultOnce, &uspoof_loadDefaultData, status);
if (U_FAILURE(status)) { return NULL; }
gDefaultSpoofData->addReference();
return gDefaultSpoofData;
}
SpoofData::SpoofData(UDataMemory *udm, UErrorCode &status)
{
reset();
if (U_FAILURE(status)) {
return;
}
fUDM = udm;
// fRawData is non-const because it may be constructed by the data builder.
fRawData = reinterpret_cast<SpoofDataHeader *>(
const_cast<void *>(udata_getMemory(udm)));
validateDataVersion(status);
initPtrs(status);
}
SpoofData::SpoofData(const void *data, int32_t length, UErrorCode &status)
{
reset();
if (U_FAILURE(status)) {
return;
}
if ((size_t)length < sizeof(SpoofDataHeader)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
if (data == NULL) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
void *ncData = const_cast<void *>(data);
fRawData = static_cast<SpoofDataHeader *>(ncData);
if (length < fRawData->fLength) {
status = U_INVALID_FORMAT_ERROR;
return;
}
validateDataVersion(status);
initPtrs(status);
}
// Spoof Data constructor for use from data builder.
// Initializes a new, empty data area that will be populated later.
SpoofData::SpoofData(UErrorCode &status) {
reset();
if (U_FAILURE(status)) {
return;
}
fDataOwned = true;
// The spoof header should already be sized to be a multiple of 16 bytes.
// Just in case it's not, round it up.
uint32_t initialSize = (sizeof(SpoofDataHeader) + 15) & ~15;
U_ASSERT(initialSize == sizeof(SpoofDataHeader));
fRawData = static_cast<SpoofDataHeader *>(uprv_malloc(initialSize));
fMemLimit = initialSize;
if (fRawData == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_memset(fRawData, 0, initialSize);
fRawData->fMagic = USPOOF_MAGIC;
fRawData->fFormatVersion[0] = USPOOF_CONFUSABLE_DATA_FORMAT_VERSION;
fRawData->fFormatVersion[1] = 0;
fRawData->fFormatVersion[2] = 0;
fRawData->fFormatVersion[3] = 0;
initPtrs(status);
}
// reset() - initialize all fields.
// Should be updated if any new fields are added.
// Called by constructors to put things in a known initial state.
void SpoofData::reset() {
fRawData = NULL;
fDataOwned = FALSE;
fUDM = NULL;
fMemLimit = 0;
fRefCount = 1;
fCFUKeys = NULL;
fCFUValues = NULL;
fCFUStrings = NULL;
}
// SpoofData::initPtrs()
// Initialize the pointers to the various sections of the raw data.
//
// This function is used both during the Trie building process (multiple
// times, as the individual data sections are added), and
// during the opening of a Spoof Checker from prebuilt data.
//
// The pointers for non-existent data sections (identified by an offset of 0)
// are set to NULL.
//
// Note: During building the data, adding each new data section
// reallocs the raw data area, which likely relocates it, which
// in turn requires reinitializing all of the pointers into it, hence
// multiple calls to this function during building.
//
void SpoofData::initPtrs(UErrorCode &status) {
fCFUKeys = NULL;
fCFUValues = NULL;
fCFUStrings = NULL;
if (U_FAILURE(status)) {
return;
}
if (fRawData->fCFUKeys != 0) {
fCFUKeys = (int32_t *)((char *)fRawData + fRawData->fCFUKeys);
}
if (fRawData->fCFUStringIndex != 0) {
fCFUValues = (uint16_t *)((char *)fRawData + fRawData->fCFUStringIndex);
}
if (fRawData->fCFUStringTable != 0) {
fCFUStrings = (UChar *)((char *)fRawData + fRawData->fCFUStringTable);
}
}
SpoofData::~SpoofData() {
if (fDataOwned) {
uprv_free(fRawData);
}
fRawData = NULL;
if (fUDM != NULL) {
udata_close(fUDM);
}
fUDM = NULL;
}
void SpoofData::removeReference() {
if (umtx_atomic_dec(&fRefCount) == 0) {
delete this;
}
}
SpoofData *SpoofData::addReference() {
umtx_atomic_inc(&fRefCount);
return this;
}
void *SpoofData::reserveSpace(int32_t numBytes, UErrorCode &status) {
if (U_FAILURE(status)) {
return NULL;
}
if (!fDataOwned) {
UPRV_UNREACHABLE;
}
numBytes = (numBytes + 15) & ~15; // Round up to a multiple of 16
uint32_t returnOffset = fMemLimit;
fMemLimit += numBytes;
fRawData = static_cast<SpoofDataHeader *>(uprv_realloc(fRawData, fMemLimit));
fRawData->fLength = fMemLimit;
uprv_memset((char *)fRawData + returnOffset, 0, numBytes);
initPtrs(status);
return (char *)fRawData + returnOffset;
}
int32_t SpoofData::serialize(void *buf, int32_t capacity, UErrorCode &status) const {
int32_t dataSize = fRawData->fLength;
if (capacity < dataSize) {
status = U_BUFFER_OVERFLOW_ERROR;
return dataSize;
}
uprv_memcpy(buf, fRawData, dataSize);
return dataSize;
}
int32_t SpoofData::size() const {
return fRawData->fLength;
}
//-------------------------------
//
// Front-end APIs for SpoofData
//
//-------------------------------
int32_t SpoofData::confusableLookup(UChar32 inChar, UnicodeString &dest) const {
// Perform a binary search.
// [lo, hi), i.e lo is inclusive, hi is exclusive.
// The result after the loop will be in lo.
int32_t lo = 0;
int32_t hi = length();
do {
int32_t mid = (lo + hi) / 2;
if (codePointAt(mid) > inChar) {
hi = mid;
} else if (codePointAt(mid) < inChar) {
lo = mid;
} else {
// Found result. Break early.
lo = mid;
break;
}
} while (hi - lo > 1);
// Did we find an entry? If not, the char maps to itself.
if (codePointAt(lo) != inChar) {
dest.append(inChar);
return 1;
}
// Add the element to the string builder and return.
return appendValueTo(lo, dest);
}
int32_t SpoofData::length() const {
return fRawData->fCFUKeysSize;
}
UChar32 SpoofData::codePointAt(int32_t index) const {
return ConfusableDataUtils::keyToCodePoint(fCFUKeys[index]);
}
int32_t SpoofData::appendValueTo(int32_t index, UnicodeString& dest) const {
int32_t stringLength = ConfusableDataUtils::keyToLength(fCFUKeys[index]);
// Value is either a char (for strings of length 1) or
// an index into the string table (for longer strings)
uint16_t value = fCFUValues[index];
if (stringLength == 1) {
dest.append((UChar)value);
} else {
dest.append(fCFUStrings + value, stringLength);
}
return stringLength;
}
U_NAMESPACE_END
U_NAMESPACE_USE
//-----------------------------------------------------------------------------
//
// uspoof_swap - byte swap and char encoding swap of spoof data
//
//-----------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
UErrorCode *status) {
if (status == NULL || U_FAILURE(*status)) {
return 0;
}
if(ds==NULL || inData==NULL || length<-1 || (length>0 && outData==NULL)) {
*status=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
//
// Check that the data header is for spoof data.
// (Header contents are defined in gencfu.cpp)
//
const UDataInfo *pInfo = (const UDataInfo *)((const char *)inData+4);
if(!( pInfo->dataFormat[0]==0x43 && /* dataFormat="Cfu " */
pInfo->dataFormat[1]==0x66 &&
pInfo->dataFormat[2]==0x75 &&
pInfo->dataFormat[3]==0x20 &&
pInfo->formatVersion[0]==USPOOF_CONFUSABLE_DATA_FORMAT_VERSION &&
pInfo->formatVersion[1]==0 &&
pInfo->formatVersion[2]==0 &&
pInfo->formatVersion[3]==0 )) {
udata_printError(ds, "uspoof_swap(): data format %02x.%02x.%02x.%02x "
"(format version %02x %02x %02x %02x) is not recognized\n",
pInfo->dataFormat[0], pInfo->dataFormat[1],
pInfo->dataFormat[2], pInfo->dataFormat[3],
pInfo->formatVersion[0], pInfo->formatVersion[1],
pInfo->formatVersion[2], pInfo->formatVersion[3]);
*status=U_UNSUPPORTED_ERROR;
return 0;
}
//
// Swap the data header. (This is the generic ICU Data Header, not the uspoof Specific
// header). This swap also conveniently gets us
// the size of the ICU d.h., which lets us locate the start
// of the uspoof specific data.
//
int32_t headerSize=udata_swapDataHeader(ds, inData, length, outData, status);
//
// Get the Spoof Data Header, and check that it appears to be OK.
//
//
const uint8_t *inBytes =(const uint8_t *)inData+headerSize;
SpoofDataHeader *spoofDH = (SpoofDataHeader *)inBytes;
if (ds->readUInt32(spoofDH->fMagic) != USPOOF_MAGIC ||
ds->readUInt32(spoofDH->fLength) < sizeof(SpoofDataHeader))
{
udata_printError(ds, "uspoof_swap(): Spoof Data header is invalid.\n");
*status=U_UNSUPPORTED_ERROR;
return 0;
}
//
// Prefight operation? Just return the size
//
int32_t spoofDataLength = ds->readUInt32(spoofDH->fLength);
int32_t totalSize = headerSize + spoofDataLength;
if (length < 0) {
return totalSize;
}
//
// Check that length passed in is consistent with length from Spoof data header.
//
if (length < totalSize) {
udata_printError(ds, "uspoof_swap(): too few bytes (%d after ICU Data header) for spoof data.\n",
spoofDataLength);
*status=U_INDEX_OUTOFBOUNDS_ERROR;
return 0;
}
//
// Swap the Data. Do the data itself first, then the Spoof Data Header, because
// we need to reference the header to locate the data, and an
// inplace swap of the header leaves it unusable.
//
uint8_t *outBytes = (uint8_t *)outData + headerSize;
SpoofDataHeader *outputDH = (SpoofDataHeader *)outBytes;
int32_t sectionStart;
int32_t sectionLength;
//
// If not swapping in place, zero out the output buffer before starting.
// Gaps may exist between the individual sections, and these must be zeroed in
// the output buffer. The simplest way to do that is to just zero the whole thing.
//
if (inBytes != outBytes) {
uprv_memset(outBytes, 0, spoofDataLength);
}
// Confusables Keys Section (fCFUKeys)
sectionStart = ds->readUInt32(spoofDH->fCFUKeys);
sectionLength = ds->readUInt32(spoofDH->fCFUKeysSize) * 4;
ds->swapArray32(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// String Index Section
sectionStart = ds->readUInt32(spoofDH->fCFUStringIndex);
sectionLength = ds->readUInt32(spoofDH->fCFUStringIndexSize) * 2;
ds->swapArray16(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// String Table Section
sectionStart = ds->readUInt32(spoofDH->fCFUStringTable);
sectionLength = ds->readUInt32(spoofDH->fCFUStringTableLen) * 2;
ds->swapArray16(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// And, last, swap the header itself.
// int32_t fMagic // swap this
// uint8_t fFormatVersion[4] // Do not swap this, just copy
// int32_t fLength and all the rest // Swap the rest, all is 32 bit stuff.
//
uint32_t magic = ds->readUInt32(spoofDH->fMagic);
ds->writeUInt32((uint32_t *)&outputDH->fMagic, magic);
if (outputDH->fFormatVersion != spoofDH->fFormatVersion) {
uprv_memcpy(outputDH->fFormatVersion, spoofDH->fFormatVersion, sizeof(spoofDH->fFormatVersion));
}
// swap starting at fLength
ds->swapArray32(ds, &spoofDH->fLength, sizeof(SpoofDataHeader)-8 /* minus magic and fFormatVersion[4] */, &outputDH->fLength, status);
return totalSize;
}
#endif
| [
"pengcheng.wang@covenantsql.io"
] | pengcheng.wang@covenantsql.io |
2270c3545e4a4509c2ce2f1043419547656452be | 407c96d904cf46a5f95217e44071f999783698a3 | /src/MultiversX/Transaction.h | cf9c62fa7eb8169b1b13db02d938a56bc60f8552 | [
"BSD-3-Clause",
"LicenseRef-scancode-protobuf",
"LGPL-2.1-only",
"Swift-exception",
"MIT",
"BSL-1.0",
"Apache-2.0"
] | permissive | trustwallet/wallet-core | dfeb276ddf1e3faf46c82f0a0cda2551e9c873f6 | 0c8e2e58aa8eb1360e4a6b03df91fb2de97e3caa | refs/heads/master | 2023-08-21T11:58:43.983035 | 2023-08-18T10:51:13 | 2023-08-18T10:51:13 | 170,738,310 | 2,311 | 1,283 | Apache-2.0 | 2023-09-08T11:26:39 | 2019-02-14T18:25:54 | C++ | UTF-8 | C++ | false | false | 1,129 | h | // Copyright © 2017-2023 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#pragma once
#include <string>
namespace TW::MultiversX {
enum TransactionOptions : uint32_t {
Default = 0,
// Not applicable for applications based on TW Core (as of April 2023).
HashSign = 1,
// Whether the transaction is guarded (using a guardian account).
// Generally speaking, applications can ignore this option (though some can choose to implement guarded transactions).
Guarded = 2
};
class Transaction {
public:
uint64_t nonce;
std::string sender;
std::string senderUsername;
std::string receiver;
std::string receiverUsername;
std::string guardian;
std::string value;
std::string data;
uint64_t gasPrice;
uint64_t gasLimit;
std::string chainID;
uint32_t version;
TransactionOptions options;
Transaction();
bool hasGuardian() const;
};
} // namespace TW::MultiversX
| [
"noreply@github.com"
] | trustwallet.noreply@github.com |
c53eb0a89cea7eada966bced4fd142d8e5f5e363 | b342a5656125324b16699d971516eab7cc3788b8 | /Arduino/Arduino_LoRa_Gateway/Arduino_LoRa_Gateway.ino | fd7819660d5b0ce855e45f7e8a986e0cecae699a | [] | no_license | zigit/LowCostLoRaGw | 2eab28cec8eed88bf5e9bfb0f54564258f4e741a | 61c44feabc3bbe39a460630ceb692907ea33fa94 | refs/heads/master | 2020-03-29T20:16:04.188882 | 2016-02-17T21:09:35 | 2016-02-17T21:09:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,644 | ino | /*
* LoRa gateway to receive and send command
*
* Copyright (C) 2015-2016 Congduc Pham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the program. If not, see <http://www.gnu.org/licenses/>.
*
*****************************************************************************
* Version: 1.1
* Design: C. Pham
* Implementation: C. Pham
*
* waits for command or data on serial port or from the LoRa module
* - command starts with /@ and ends with #
*
* LoRa parameters
* - /@M1#: set LoRa mode 1
* - /@C12#: use channel 12 (868MHz)
* - /@PL/H/M#: set power to Low, High or Max
* - /@A9#: set node addr to 9
* - /@W34#: set sync word to 0x34
* - /@ON# or /@OFF#: power on/off the LoRa module
*
* Use of ACK
* - /@ACK#hello w/ack : sends the message and request an ACK
* - /@ACKON# enables ACK (for all messages)
* - /@ACKOFF# disables ACK
*
* CAD, DIFS/SIFS mechanism, RSSI checking, extended IFS
* - /@CAD# performs an SIFS CAD, i.e. 3 or 6 CAD depending on the LoRa mode
* - /@CADON3# uses 3 CAD when sending data (normally SIFS is 3 or 6 CAD, DIFS=3SIFS)
* - /@CADOFF# disables CAD (IFS) when sending data
* - /@RSSI# toggles checking of RSSI before transmission and after CAD
* - /@EIFS# toggles for extended IFS wait
* if compiled with IS_RCV_GATEWAY
* - just connect the Arduino board with LoRa module
* - use any serial tool to view data that is received
* - with a python script to read serial port, all received data could be forwarded to another application through
* standart output
* - remote configuration needs to be allowed by unlocking the gateway with command '/@U' with an unlock pin
* - '/@U1234#'
* - allowed commands for a gateway are
* - M, C, P, A, ON, OFF
* - ACKON, ACKOFF (if using unmodified SX1272 lib)
*
* if compiled with IS_SEND_GATEWAY
* - can read from serial port to send input data (ASCII format)
* - remote configuration needs to be allowed by unlocking the gateway with command '/@U' with an unlock pin
* - '/@U1234#'
* - accepts all the command set of a receive gateway
* - periodic sending of packet for range test
* - /@T5000#: send a message at regular time interval of 5000ms. Use /@T0# to disable periodic sending
* - /@TR5000#: send a message at random time interval between [2000, 5000]ms.
* - /@Z200# sets the packet payload size to 200
* - the command /@D specifies the destination node for sending remote commands
* - /@D56#: set the destination node to be 56, this is permanent, until the next D command
* - /@D58#hello: send hello to node 56, destination addr is only for this message
* - /@D4#/@C1#Q30#: send the command string /@C1#Q30# to node 4
* - the S command sends a string of arbitrary size
* - /@S50# sends a 50B user payload packet filled with '#'. The real size is 55B with the Libelium header
*
* if compiled with LORA_LAS
* - add LAS support
* - sending message will use LAS service
* - /@LASS# prints LAS statistics
* - /@LASR# resets LAS service
* - /@LASON# enables LAS service
* - /@LASOFF# disables LAS service
* - if IS_SEND_GATEWAY
* - /@REG# sends a REG message
* - if IS_RCV_GATEWAY
* - /@LASI# initiate the INITrestart/INIT procedure that ask end-devices to send the REG msg
*
* IMPORTANT NOTICE
* - the gateway use data prefix to indicate data received from radio. The prefix is 2 bytes: 0xFF0xFE
* - the post-processing stage looks for this sequence to dissect the data, according to the format adopted by the sender
* - if you use our LoRa_Temp example, then the packet format as expected by the post-processing script is as follows:
* - without application key and without encryption, payload starts immediately: [payload]
* - without application key and with encryption: original (clear) format is [size(1B)][payload]. size is the real size of the clear payload
* - if application key is used, without encryption: [AppKey(4B)][payload]
* - if application key is used, with encryption: original (clear) format is [AppKey(4B)][size(1B)][payload]. size is the real size of the clear payload
* - for more details on the underlying packet format used by our modified SX1272 library
* - refer to the SX1272.h
* - see http://cpham.perso.univ-pau.fr/LORA/RPIgateway.html
*
*/
/* Change logs
*
* Jan, 22th, 2016. v1.1
* Add advanced configuration options when running on Linux (Raspberry typically)
* - options are: --mode 4 --bw 500 --cr 5 --sf 12 --freq 868.1 --ch 10 --sw 34 --raw
* Add raw output option in the Linux version. The gateway will forward all the payload without any interpretation
* - this feature is implemented in the SX1272 library, see the corresponding CHANGES.log file
* - this is useful when the packet interpretation is left to the post-processing stage (e.g. for LoRaWAN)
* Dec, 30th, 2015. v1.0
* SX1272 library has been modified to allow for sync word setting, a new mode 11 is introduced to test with LoRaWAN
* BW=125kHz, CR=4/5 and SF=7. When using mode 11, sync word is set to 0x34. Normally, use the newly defined CH_18_868=868.1MHz
* Add possibility to set the sync word
* - /@W34# set the sync word to 0x34
* Nov, 13th, 2015. v0.9
* SX1272 library has been modified to support dynamic ACK request using the retry field of the packet header
* Gateway now always use receivePacketTimeout() and sender either use sendPacketTimeout() or sendPacketTimeoutACK()
* Nov, 10th, 2015. v0.8a
* Add an unlock pin to allow the gateway to accept remote commands
* A limited number of attempts is allowed
* - /@U1234#: try to unlock with pin 1234. To lock, issue the same command again.
* Oct, 8th, 2015. v0.8
* Can change packet size for periodic packet transmission
* - /@Z200# sets the packet payload size to 200. The real size is 205B with the Libelium header.
* Maximum size that can be indicated is then 250.
* Add possibility to send periodically at random time interval
* - /@TR5000#: send a message at random time interval between [2000, 5000]ms.
* Check RSSI value before transmitting a packet. This is done after successful CAD
* - CAD must be ON
* - /@RSSI# toggles checking of RSSI, must be above -90dBm to transmit, otherwise, repeat 10 times
* Sep, 22nd, 2015. v0.7
* Add ACK support when sending packets
* - /@ACKON# enables ACK
* - /@ACKOFF# disables ACK
* Can use extended IFS wait to:
* - CAD must be ON
* - wait a random number of CAD after a successful IFS
* - perform an IFS one more time before packet tranmission
* - /@EIFS# toggles for extended IFS wait
* Jul, 1st, 2015. v0.6
* Add support of the LoRa Activity Sharing (LAS) mechanism (device side), uncomment #define LORA_LAS
* - sending message will use LAS service
* - /@LASS# prints LAS statistics
* - /@LASR# resets LAS service
* - /@LASON# enables LAS service
* - /@LASOFF# disables LAS service
* - /@REG# sends a REG message if IS_SEND_GATEWAY
* - /@INIT# sends an INIT(0,delay) message for restarting if IS_SEND_GATEWAY
* June, 29th, 2015. v0.5
* Add a CAD_TEST behavior to see continuously channel activity, uncomment #define CAD_TEST
* Add LoRa ToA computation when sending data
* Add CAD test when sending data
* - /@CADON3# uses 3 CAD when sending data (normally SIFS is 3 or 6 CAD, DIFS=3SIFS)
* - /@CADOFF# disables CAD when sending data
* Add CAD feature for testing
* - /@CAD# performs an SIFS CAD, i.e. 3 or 6 CAD depending on the LoRa mode
* Add ON and OFF command to power on/off the LoRa module
* - /@ON# or /@OFF#
* Add the S command to send a string of arbitrary size
* - /@S50# sends a 50B user payload packet filled with '#'. The real size is 55B with the Libelium header
* The gateway can accept command from serial or from the LoRa module
* May, 11th, 2015. v0.4
* Add periodic sending of packet for range test
* - /@T5000#: send a message every 5s. Use /@T0# to disable periodic sending
* Apr, 17th, 2015. v0.3
* Add possibility to configure the LoRa operation mode
* - /@M1#: set LoRa mode 1
* - /@C12#: use channel 12 (868MHz)
* - /@PL/H/M#: set power to Low, High or Max
* - /@A9#: set node addr to 9
* Apr, 16th, 2015. v0.2
* Integration of receive gateway and send gateway:
* - #define IS_SEND_GATEWAY will produce a sending gateway to send remote commands
* Apr, 14th, 2015. v0.1
* First version of receive gateway
*/
// Include the SX1272
#include "SX1272.h"
// IMPORTANT
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// please uncomment only 1 choice
//
// uncomment if your radio is an HopeRF RFM92W or RFM95W
//#define RADIO_RFM92_95
// uncomment if your radio is a Modtronix inAirB (the one with +20dBm features), if inAir9, leave commented
//#define RADIO_INAIR9B
// uncomment if you only know that it has 20dBm feature
//#define RADIO_20DBM
///////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef RASPBERRY
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#endif
#ifdef ARDUINO
// and SPI library on Arduino platforms
#include <SPI.h>
#define PRINTLN Serial.println("")
#define PRINT_CSTSTR(fmt,param) Serial.print(F(param))
#define PRINT_STR(fmt,param) Serial.print(param)
#define PRINT_VALUE(fmt,param) Serial.print(param)
#define FLUSHOUTPUT Serial.flush();
#else
#define PRINTLN printf("\n")
#define PRINT_CSTSTR(fmt,param) printf(fmt,param)
#define PRINT_STR(fmt,param) PRINT_CSTSTR(fmt,param)
#define PRINT_VALUE(fmt,param) PRINT_CSTSTR(fmt,param)
#define FLUSHOUTPUT fflush(stdout);
#endif
#ifdef DEBUG
#define DEBUGLN PRINTLN
#define DEBUG_CSTSTR(fmt,param) PRINT_CSTSTR(fmt,param)
#define DEBUG_STR(fmt,param) PRINT_CSTSTR(fmt,param)
#define DEBUG_VALUE(fmt,param) PRINT_VALUE(fmt,param)
#else
#define DEBUGLN
#define DEBUG_CSTSTR(fmt,param)
#define DEBUG_STR(fmt,param)
#define DEBUG_VALUE(fmt,param)
#endif
//#define RECEIVE_ALL
//#define IS_RCV_GATEWAY
#//define IS_SEND_GATEWAY
//#define CAD_TEST
//#define LORA_LAS
//#define WINPUT
//#define WITH_SEND_LED
// the special mode to test BW=125MHz, CR=4/5, SF=7
// on the 868.1MHz channel
//#define LORAMODE 11
#define LORAMODE 4
// use the dynamic ACK feature of our modified SX1272 lib
#define GW_AUTO_ACK
#ifdef WITH_SEND_LED
#define SEND_LED 44
#endif
#define DEFAULT_DEST_ADDR 1
#ifdef IS_SEND_GATEWAY
#define LORA_ADDR 6
// packet size for periodic sending
uint8_t MSS=40;
#else
#define LORA_ADDR 1
// to unlock remote configuration feature
#define UNLOCK_PIN 1234
// will use 0xFF0xFE to prefix data received from LoRa, so that post-processing stage can differenciate
// data received from radio
#define WITH_DATA_PREFIX
#ifdef WITH_DATA_PREFIX
#define DATA_PREFIX_0 0xFF
#define DATA_PREFIX_1 0xFE
#endif
#endif
#ifdef LORA_LAS
#include "LoRaActivitySharing.h"
#ifdef IS_SEND_GATEWAY
// acting as an end-device
LASDevice loraLAS(LORA_ADDR,LAS_DEFAULT_ALPHA,DEFAULT_DEST_ADDR);
#else
// acting as the LR-BS
LASBase loraLAS = LASBase();
#endif
#endif
int dest_addr=DEFAULT_DEST_ADDR;
char cmd[260]="****************";
char sprintf_buf[100];
int msg_sn=0;
// number of retries to unlock remote configuration feature
uint8_t unlocked_try=3;
boolean unlocked=false;
boolean receivedFromSerial=false;
boolean receivedFromLoRa=false;
boolean withAck=false;
#ifndef ARDUINO
char keyPressBuff[30];
uint8_t keyIndex=0;
int ch;
#endif
uint32_t loraChannelArray[9]={CH_10_868,CH_11_868,CH_12_868,CH_13_868,CH_14_868,CH_15_868,CH_16_868,CH_17_868,CH_18_868};
// configuration variables
//////////////////////////
bool radioON=false;
bool RSSIonSend=true;
uint8_t loraMode=LORAMODE;
uint8_t loraChannelIndex=0;
uint32_t loraChannel=loraChannelArray[loraChannelIndex];
#if defined RADIO_RFM92_95 || defined RADIO_INAIR9B || defined RADIO_20DBM
// HopeRF 92W/95W and inAir9B need the PA_BOOST
// so 'x' set the PA_BOOST but then limit the power to +14dBm
char loraPower='x';
#else
// other radio board such as Libelium LoRa or inAir9 do not need the PA_BOOST
// so 'M' set the output power to 15 to get +14dBm
char loraPower='M';
#endif
uint8_t loraAddr=LORA_ADDR;
unsigned int inter_pkt_time=0;
unsigned int random_inter_pkt_time=0;
long last_periodic_sendtime=0;
unsigned long startDoCad, endDoCad;
bool extendedIFS=true;
uint8_t SIFS_cad_number;
uint8_t send_cad_number=0;
uint8_t SIFS_value[11]={0, 183, 94, 44, 47, 23, 24, 12, 12, 7, 4};
uint8_t CAD_value[11]={0, 62, 31, 16, 16, 8, 9, 5, 3, 1, 1};
bool optAESgw=false;
uint16_t optBW=0;
uint8_t optSF=0;
uint8_t optCR=0;
uint8_t optCH=0;
bool optRAW=false;
double optFQ=-1.0;
uint8_t optSW=0x12;
//////////////////////////
#if defined ARDUINO && not defined _VARIANT_ARDUINO_DUE_X_
int freeMemory () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#endif
long getCmdValue(int &i, char* strBuff=NULL) {
char seqStr[7]="******";
int j=0;
// character '#' will indicate end of cmd value
while ((char)cmd[i]!='#' && (i < strlen(cmd)) && j<strlen(seqStr)) {
seqStr[j]=(char)cmd[i];
i++;
j++;
}
// put the null character at the end
seqStr[j]='\0';
if (strBuff) {
strcpy(strBuff, seqStr);
}
else
return (atol(seqStr));
}
void startConfig() {
int e;
// has customized LoRa settings
if (optBW!=0 || optCR!=0 || optSF!=0) {
e = sx1272.setCR(optCR-4);
PRINT_CSTSTR("%s","^$LoRa CR ");
PRINT_VALUE("%d", optCR);
PRINT_CSTSTR("%s",": state ");
PRINT_VALUE("%d", e);
PRINTLN;
e = sx1272.setSF(optSF);
PRINT_CSTSTR("%s","^$LoRa SF ");
PRINT_VALUE("%d", optSF);
PRINT_CSTSTR("%s",": state ");
PRINT_VALUE("%d", e);
PRINTLN;
e = sx1272.setBW( (optBW==125)?BW_125:((optBW==250)?BW_250:BW_500) );
PRINT_CSTSTR("%s","^$LoRa BW ");
PRINT_VALUE("%d", optBW);
PRINT_CSTSTR("%s",": state ");
PRINT_VALUE("%d", e);
PRINTLN;
// indicate that we have a custom setting
loraMode=0;
if (optSF<10)
SIFS_cad_number=6;
else
SIFS_cad_number=3;
}
else {
// Set transmission mode and print the result
PRINT_CSTSTR("%s","^$LoRa mode ");
PRINT_VALUE("%d", loraMode);
PRINTLN;
e = sx1272.setMode(loraMode);
PRINT_CSTSTR("%s","^$Setting mode: state ");
PRINT_VALUE("%d", e);
PRINTLN;
#ifdef LORA_LAS
loraLAS.setSIFS(loraMode);
#endif
if (loraMode>7)
SIFS_cad_number=6;
else
SIFS_cad_number=3;
}
// Select frequency channel
if (loraMode==11) {
// if we start with mode 11, then switch to 868.1MHz for LoRaWAN test
// Note: if you change to mode 11 later using command /@M11# for instance, you have to use /@C18# to change to the correct channel
e = sx1272.setChannel(CH_18_868);
PRINT_CSTSTR("%s","^$Channel CH_18_868: state ");
}
else {
// work also for loraMode 0
e = sx1272.setChannel(loraChannel);
if (optFQ>0.0) {
PRINT_CSTSTR("%s","^$Frequency ");
PRINT_VALUE("%f", optFQ);
PRINT_CSTSTR("%s",": state ");
}
else {
PRINT_CSTSTR("%s","^$Channel CH_1");
PRINT_VALUE("%d", loraChannelIndex);
PRINT_CSTSTR("%s","_868: state ");
}
}
PRINT_VALUE("%d", e);
PRINTLN;
// Select output power (Max, High or Low)
e = sx1272.setPower(loraPower);
PRINT_CSTSTR("%s","^$Set LoRa Power to ");
PRINT_VALUE("%c",loraPower);
PRINTLN;
PRINT_CSTSTR("%s","^$Power: state ");
PRINT_VALUE("%d", e);
PRINTLN;
// get preamble length
e = sx1272.getPreambleLength();
PRINT_CSTSTR("%s","^$Get Preamble Length: state ");
PRINT_VALUE("%d", e);
PRINTLN;
PRINT_CSTSTR("%s","^$Preamble Length: ");
PRINT_VALUE("%d", sx1272._preamblelength);
PRINTLN;
// Set the node address and print the result
//e = sx1272.setNodeAddress(loraAddr);
sx1272._nodeAddress=loraAddr;
e=0;
PRINT_CSTSTR("%s","^$LoRa addr ");
PRINT_VALUE("%d", loraAddr);
PRINT_CSTSTR("%s",": state ");
PRINT_VALUE("%d", e);
PRINTLN;
if (optAESgw)
PRINT_CSTSTR("%s","^$Handle AES encrypted data\n");
if (optRAW) {
PRINT_CSTSTR("%s","^$Raw format, not assuming any header in reception\n");
// when operating n raw format, the SX1272 library do not decode the packet header but will pass all the payload to stdout
// note that in this case, the gateway may process packet that are not addressed explicitly to it as the dst field is not checked at all
// this would be similar to a promiscuous sniffer, but most of real LoRa gateway works this way
sx1272._rawFormat=true;
}
// Print a success message
PRINT_CSTSTR("%s","^$SX1272/76 configured ");
#ifdef IS_SEND_GATEWAY
PRINT_CSTSTR("%s","as device. Waiting serial input for serial-RF bridge\n");
#else
PRINT_CSTSTR("%s","as LR-BS. Waiting RF input for transparent RF-serial bridge\n");
#endif
}
void setup()
{
int e;
#ifdef ARDUINO
delay(3000);
randomSeed(analogRead(14));
#else
srand (time(NULL));
#endif
#ifdef _VARIANT_ARDUINO_DUE_X_
Serial.begin(115200);
#else
// Open serial communications and wait for port to open:
Serial.begin(38400);
#ifdef ARDUINO
// Print a start message
Serial.print(freeMemory());
Serial.println(F(" bytes of free memory."));
#endif
#endif
// Power ON the module
e = sx1272.ON();
PRINT_CSTSTR("%s","^$**********Power ON: state ");
PRINT_VALUE("%d", e);
PRINTLN;
e = sx1272.getSyncWord();
if (!e) {
PRINT_CSTSTR("%s","^$Default sync word: 0x");
#ifdef ARDUINO
Serial.print(sx1272._syncWord, HEX);
#else
PRINT_VALUE("%X", sx1272._syncWord);
#endif
PRINTLN;
}
if (optSW!=0x12) {
e = sx1272.setSyncWord(optSW);
PRINT_CSTSTR("%s","^$Set sync word to 0x");
#ifdef ARDUINO
Serial.print(optSW, HEX);
#else
PRINT_VALUE("%X", optSW);
#endif
PRINTLN;
PRINT_CSTSTR("%s","^$LoRa sync word: state ");
PRINT_VALUE("%d",e);
PRINTLN;
}
if (!e) {
radioON=true;
startConfig();
}
FLUSHOUTPUT;
delay(1000);
#ifdef LORA_LAS
loraLAS.ON(LAS_ON_WRESET);
#ifdef IS_SEND_GATEWAY
//delay(random(LAS_REG_RAND_MIN,LAS_REG_RAND_MAX));
//loraLAS.sendReg();
#endif
#endif
#ifdef CAD_TEST
PRINT_CSTSTR("%s","Do CAD test\n");
#endif
}
// we could use the CarrierSense function added in the SX1272 library, but it is more convenient to duplicate it here
// so that we could easily modify it for testing
void CarrierSense() {
int e;
bool carrierSenseRetry=false;
if (send_cad_number) {
do {
do {
// check for free channel (SIFS/DIFS)
startDoCad=millis();
e = sx1272.doCAD(send_cad_number);
endDoCad=millis();
PRINT_CSTSTR("%s","--> CAD duration ");
PRINT_VALUE("%ld",endDoCad-startDoCad);
PRINTLN;
if (!e) {
PRINT_CSTSTR("%s","OK1\n");
if (extendedIFS) {
// wait for random number of CAD
#ifdef ARDUINO
uint8_t w = random(1,8);
#else
uint8_t w = rand() % 8 + 1;
#endif
PRINT_CSTSTR("%s","--> waiting for ");
PRINT_VALUE("%d",w);
PRINT_CSTSTR("%s"," CAD = ");
PRINT_VALUE("%d",CAD_value[loraMode]*w);
PRINTLN;
delay(CAD_value[loraMode]*w);
// check for free channel (SIFS/DIFS) once again
startDoCad=millis();
e = sx1272.doCAD(send_cad_number);
endDoCad=millis();
PRINT_CSTSTR("%s","--> CAD duration ");
PRINT_VALUE("%ld",endDoCad-startDoCad);
PRINTLN;
if (!e)
PRINT_CSTSTR("%s","OK2");
else
PRINT_CSTSTR("%s","###2");
PRINTLN;
}
}
else {
PRINT_CSTSTR("%s","###1\n");
// wait for random number of DIFS
#ifdef ARDUINO
uint8_t w = random(1,8);
#else
uint8_t w = rand() % 8 + 1;
#endif
PRINT_CSTSTR("%s","--> waiting for ");
PRINT_VALUE("%d",w);
PRINT_CSTSTR("%s"," DIFS (DIFS=3SIFS) = ");
PRINT_VALUE("%d",SIFS_value[loraMode]*3*w);
PRINTLN;
delay(SIFS_value[loraMode]*3*w);
PRINT_CSTSTR("%s","--> retry\n");
}
} while (e);
// CAD is OK, but need to check RSSI
if (RSSIonSend) {
e=sx1272.getRSSI();
uint8_t rssi_retry_count=10;
if (!e) {
PRINT_CSTSTR("%s","--> RSSI ");
PRINT_VALUE("%d", sx1272._RSSI);
PRINTLN;
while (sx1272._RSSI > -90 && rssi_retry_count) {
delay(1);
sx1272.getRSSI();
PRINT_CSTSTR("%s","--> RSSI ");
PRINT_VALUE("%d", sx1272._RSSI);
PRINTLN;
rssi_retry_count--;
}
}
else
PRINT_CSTSTR("%s","--> RSSI error\n");
if (!rssi_retry_count)
carrierSenseRetry=true;
else
carrierSenseRetry=false;
}
} while (carrierSenseRetry);
}
}
void loop(void)
{
int i=0, e;
int cmdValue;
///////////////////////
// ONLY FOR TESTING CAD
#ifdef CAD_TEST
startDoCad=millis();
e = sx1272.doCAD(SIFS_cad_number);
endDoCad=millis();
PRINT_CSTSTR("%s","--> SIFS duration ");
PRINT_VALUE("%ld", endDoCad-startDoCad);
PRINTLN;
if (!e)
PRINT_CSTSTR("%s","OK");
else
PRINT_CSTSTR("%s","###");
PRINTLN;
delay(200);
startDoCad=millis();
e = sx1272.doCAD(SIFS_cad_number*3);
endDoCad=millis();
PRINT_CSTSTR("%s","--> DIFS duration ");
PRINT_VALUE("%ld", endDoCad-startDoCad);
PRINTLN;
if (!e)
PRINT_CSTSTR("%s","OK");
else
PRINT_CSTSTR("%s","###");
PRINTLN;
delay(200);
#endif
// ONLY FOR TESTING CAD
///END/////////////////
//////////////////////////
// START OF PERIODIC TASKS
receivedFromSerial=false;
receivedFromLoRa=false;
#ifdef LORA_LAS
// call periodically to be able to detect the start of a new cycle
loraLAS.checkCycle();
#endif
// check if we received data from the input serial port
if (Serial.available()) {
i=0;
while (Serial.available() && i<80) {
cmd[i]=Serial.read();
i++;
delay(50);
}
cmd[i]='\0';
PRINT_CSTSTR("%s","Rcv serial: ");
PRINT_STR("%s",cmd);
PRINTLN;
receivedFromSerial=true;
}
// handle keyboard input from a UNIX terminal
#if not defined ARDUINO && defined WINPUT
while (unistd::read(0, &ch, 1)) {
if (ch == '\n') {
strcpy(cmd,keyPressBuff);
PRINT_CSTSTR("%s","Cmd from keyboard: ");
PRINT_STR("%s",cmd);
PRINTLN;
keyIndex=0;
receivedFromSerial=true;
}
else {
// backspace
if (ch == 127 || ch==8) {
keyIndex--;
}
else {
keyPressBuff[keyIndex]=(char)ch;
keyIndex++;
}
}
keyPressBuff[keyIndex]='\0';
PRINT_CSTSTR("%s","keyboard input : ");
PRINT_STR("%s",keyPressBuff);
PRINTLN;
}
#endif
if (radioON && !receivedFromSerial) {
///////////////////////////////////////////////////////
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
#ifdef IS_SEND_GATEWAY
// periodic message sending? (mainly for tests)
if (inter_pkt_time)
if (millis()-last_periodic_sendtime > (random_inter_pkt_time?random_inter_pkt_time:inter_pkt_time)) {
PRINT_CSTSTR("%s","inter_pkt ");
PRINT_VALUE("%ld",millis()-last_periodic_sendtime);
PRINTLN;
sprintf(cmd, "msg %3.d***", msg_sn++);
for (i=strlen(cmd); i<MSS; i++)
cmd[i]='*';
cmd[i]='\0';
PRINT_CSTSTR("%s","Sending : ");
PRINT_STR("%s",cmd);
PRINTLN;
CarrierSense();
PRINT_CSTSTR("%s","Packet number ");
PRINT_VALUE("%d",sx1272._packetNumber);
PRINTLN;
long startSend=millis();
#ifdef WITH_SEND_LED
digitalWrite(SEND_LED, HIGH);
#endif
e = sx1272.sendPacketTimeout(dest_addr, (uint8_t*)cmd, strlen(cmd), 10000);
#ifdef WITH_SEND_LED
digitalWrite(SEND_LED, LOW);
#endif
PRINT_CSTSTR("%s","LoRa Sent in ");
PRINT_VALUE("%ld",millis()-startSend);
PRINTLN;
PRINT_CSTSTR("%s","Packet sent, state ");
PRINT_VALUE("%d",e);
PRINTLN;
//Serial.flush();
if (random_inter_pkt_time) {
#ifdef ARDUINO
random_inter_pkt_time=random(2000,inter_pkt_time);
#else
random_inter_pkt_time = rand() % inter_pkt_time + 2000;
#endif
PRINT_CSTSTR("%s","next in ");
PRINT_VALUE("%ld",random_inter_pkt_time);
PRINTLN;
}
last_periodic_sendtime=millis();
}
// TODO
// the end-device should also open a receiving window to receive
// INIT & UPDT messages
e=1;
#ifndef CAD_TEST
// open a receive window
uint16_t w_timer=1000;
if (loraMode==1)
w_timer=2500;
e = sx1272.receivePacketTimeout(w_timer);
#endif
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
///END/////////////////////////////////////////////////
#else
///////////////////////////////////////////////////////
// ONLY FOR BASE STATION RECEIVING MESSAGES FROM DEVICE
uint16_t w_timer=1000;
if (loraMode==1)
w_timer=2500;
e=1;
#ifndef CAD_TEST
// check if we received data from the receiving LoRa module
#ifdef RECEIVE_ALL
e = sx1272.receiveAll(w_timer);
#else
#ifdef GW_AUTO_ACK
e = sx1272.receivePacketTimeout(w_timer);
if (!e && sx1272._requestACK_indicator) {
sprintf(sprintf_buf,"^$ACK requested by %d\n", sx1272.packet_received.src);
PRINT_STR("%s",sprintf_buf);
}
#else
// Receive message
if (withAck)
e = sx1272.receivePacketTimeoutACK(w_timer);
else
e = sx1272.receivePacketTimeout(w_timer);
#endif
#endif
#endif
#endif
// ONLY FOR BASE STATION RECEIVING MESSAGES FROM DEVICE
///END/////////////////////////////////////////////////
if (!e) {
int a=0, b=0;
uint8_t tmp_length;
receivedFromLoRa=true;
sx1272.getSNR();
sx1272.getRSSIpacket();
tmp_length=sx1272._payloadlength;
sprintf(sprintf_buf,"--- rxlora. dst=%d type=0x%.2X src=%d seq=%d len=%d SNR=%d RSSIpkt=%d BW=%d CR=4/%d SF=%d\n",
sx1272.packet_received.dst,
sx1272.packet_received.type,
sx1272.packet_received.src,
sx1272.packet_received.packnum,
tmp_length,
sx1272._SNR,
sx1272._RSSIpacket,
(sx1272._bandwidth==BW_125)?125:((sx1272._bandwidth==BW_250)?250:500),
sx1272._codingRate+4,
sx1272._spreadingFactor);
PRINT_STR("%s",sprintf_buf);
// provide a short output for external program to have information about the received packet
// ^psrc_id,seq,len,SNR,RSSI
sprintf(sprintf_buf,"^p%d,%d,%d,%d,%d,%d,%d\n",
sx1272.packet_received.dst,
sx1272.packet_received.type,
sx1272.packet_received.src,
sx1272.packet_received.packnum,
tmp_length,
sx1272._SNR,
sx1272._RSSIpacket);
PRINT_STR("%s",sprintf_buf);
// ^rbw,cr,sf
sprintf(sprintf_buf,"^r%d,%d,%d\n",
(sx1272._bandwidth==BW_125)?125:((sx1272._bandwidth==BW_250)?250:500),
sx1272._codingRate+4,
sx1272._spreadingFactor);
PRINT_STR("%s",sprintf_buf);
// for Linux-based gateway only
///////////////////////////////
#ifndef ARDUINO
char buffer[30];
int millisec;
struct tm* tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec>=1000) { // Allow for rounding up to nearest second
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 30, "%Y-%m-%dT%H:%M:%S", tm_info);
sprintf(sprintf_buf, "^t%s.%03d\n", buffer, millisec);
PRINT_STR("%s",sprintf_buf);
#endif
#ifdef LORA_LAS
if (loraLAS.isLASMsg(sx1272.packet_received.data)) {
//tmp_length=sx1272.packet_received.length-OFFSET_PAYLOADLENGTH;
tmp_length=sx1272._payloadlength;
int v=loraLAS.handleLASMsg(sx1272.packet_received.src,
sx1272.packet_received.data,
tmp_length);
if (v==DSP_DATA) {
a=LAS_DSP+DATA_HEADER_LEN+1;
#ifdef WITH_DATA_PREFIX
PRINT_STR("%c",(char)DATA_PREFIX_0);
PRINT_STR("%c",(char)DATA_PREFIX_1);
#endif
}
else
// don't print anything
a=tmp_length;
}
else
PRINT_CSTSTR("%s","No LAS header. Write raw data\n");
#else
#ifdef WITH_DATA_PREFIX
PRINT_STR("%c",(char)DATA_PREFIX_0);
PRINT_STR("%c",(char)DATA_PREFIX_1);
#endif
#endif
for ( ; a<tmp_length; a++,b++) {
PRINT_STR("%c",(char)sx1272.packet_received.data[a]);
cmd[b]=(char)sx1272.packet_received.data[a];
}
// strlen(cmd) will be correct as only the payload is copied
cmd[b]='\0';
PRINTLN;
FLUSHOUTPUT;
#if not defined ARDUINO && defined WINPUT
// if we received something, display again the current input
// that has still not be terminated
if (keyIndex) {
PRINT_CSTSTR("%s","keyboard input : ");
PRINT_STR("%s",keyPressBuff);
PRINTLN;
}
#endif
}
}
if (receivedFromSerial || receivedFromLoRa) {
boolean sendCmd=false;
boolean withTmpAck=false;
int forTmpDestAddr=-1;
i=0;
if (cmd[i]=='/' && cmd[i+1]=='@') {
PRINT_CSTSTR("%s","^$Parsing command\n");
i=2;
PRINT_CSTSTR("%s","^$");
PRINT_STR("%s",cmd);
PRINTLN;
if ( (receivedFromLoRa && cmd[i]!='U' && !unlocked) || !unlocked_try) {
PRINT_CSTSTR("%s","^$Remote config locked\n");
// just assign an unknown command
cmd[i]='*';
}
switch (cmd[i]) {
#ifdef IS_SEND_GATEWAY
///////////////////////////////////////////////////////
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
case 'D':
i++;
cmdValue=getCmdValue(i);
i++;
// cannot set dest addr greater than 255
if (cmdValue > 255)
cmdValue = 255;
// cannot set dest addr lower than 0, 0 is broadcast
if (cmdValue < 0)
cmdValue = 0;
// only a D command
if (i==strlen(cmd)) {
// set dest addr permanently
dest_addr=cmdValue;
PRINT_CSTSTR("%s","Set LoRa dest addr to ");
PRINT_VALUE("%d",dest_addr);
PRINTLN;
}
else {
// only for the following ASCII command
forTmpDestAddr=cmdValue;
PRINT_CSTSTR("%s","Set LoRa dest addr FOR THIS ASCII STRING to ");
PRINT_VALUE("%d",forTmpDestAddr);
PRINTLN;
sendCmd=true;
}
break;
case 'T':
i++;
if (cmd[i]=='R') {
random_inter_pkt_time=1;
i++;
}
else
random_inter_pkt_time=0;
cmdValue=getCmdValue(i);
inter_pkt_time=cmdValue;
if (inter_pkt_time) {
PRINT_CSTSTR("%s","Set inter-packet time to ");
PRINT_VALUE("%ld",inter_pkt_time);
PRINTLN;
last_periodic_sendtime=millis();
}
else {
PRINT_CSTSTR("%s","Disable periodic send\n");
}
if (random_inter_pkt_time)
#ifdef ARDUINO
random_inter_pkt_time=random(2000,inter_pkt_time);
#else
random_inter_pkt_time = rand() % inter_pkt_time + 2000;
#endif
break;
// set the pkt size default is 40
// "Z250#"
case 'Z':
i++;
cmdValue=getCmdValue(i);
// cannot set pkt size greater than MAX_PKT_SIZE
if (cmdValue > 250)
cmdValue = 250;
// cannot set pkt size smaller than MAX_PKT_SIZE
if (cmdValue < 10)
cmdValue = 10;
// set new pkt size
MSS=cmdValue;
PRINT_CSTSTR("%s","Set MSS to ");
PRINT_VALUE("%d",MSS);
PRINTLN;
break;
case 'S':
i++;
cmdValue=getCmdValue(i);
i++;
if (cmdValue>250) {
PRINT_CSTSTR("%s","No more than 250B\n");
}
else {
int k=0;
for (k=0; k<cmdValue; k++)
cmd[k+i]='#';
cmd[k+i]='\0';
sendCmd=true;
}
break;
case 'R':
#ifdef LORA_LAS
if (cmd[i+1]=='E' && cmd[i+2]=='G') {
PRINT_CSTSTR("%s","^$Send LAS REG msg\n");
loraLAS.sendReg();
}
#endif
if (cmd[i+1]=='S' && cmd[i+2]=='S' && cmd[i+3]=='I') {
RSSIonSend = !RSSIonSend;
if (RSSIonSend)
PRINT_CSTSTR("%s","RSSI ON\n");
else
PRINT_CSTSTR("%s","RSSI OFF\n");
}
break;
case 'E':
if (cmd[i+1]=='I' && cmd[i+2]=='F' && cmd[i+3]=='S') {
extendedIFS = !extendedIFS;
if (extendedIFS)
PRINT_CSTSTR("%s","EIFS ON\n");
else
PRINT_CSTSTR("%s","EIFS OFF\n");
}
break;
#endif
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
///END/////////////////////////////////////////////////
#ifdef IS_RCV_GATEWAY
case 'U':
if (unlocked_try) {
i++;
cmdValue=getCmdValue(i);
if (cmdValue==UNLOCK_PIN) {
unlocked=!unlocked;
if (unlocked)
PRINT_CSTSTR("%s","^$Unlocked\n");
else
PRINT_CSTSTR("%s","^$Locked\n");
}
else
unlocked_try--;
if (unlocked_try==0)
PRINT_CSTSTR("%s","^$Bad pin\n");
}
break;
#endif
case 'M':
i++;
cmdValue=getCmdValue(i);
// cannot set mode greater than 11 (11 being the LoRaWAN test mode)
if (cmdValue > 11)
cmdValue = 4;
// cannot set mode lower than 0
if (cmdValue < 0)
cmdValue = 4;
// set dest addr
loraMode=cmdValue;
PRINT_CSTSTR("%s","^$Set LoRa mode to ");
PRINT_VALUE("%d",loraMode);
PRINTLN;
// Set transmission mode and print the result
e = sx1272.setMode(loraMode);
PRINT_CSTSTR("%s","^$LoRa mode: state ");
PRINT_VALUE("%d",e);
PRINTLN;
#ifdef LORA_LAS
loraLAS.setSIFS(loraMode);
#endif
// get preamble length
e = sx1272.getPreambleLength();
PRINT_CSTSTR("%s","Get Preamble Length: state ");
PRINT_VALUE("%d",e);
PRINTLN;
PRINT_CSTSTR("%s","Preamble Length: ");
PRINT_VALUE("%d",sx1272._preamblelength);
PRINTLN;
break;
case 'W':
i++;
cmdValue=getCmdValue(i);
// we expect an HEX format value
cmdValue = (cmdValue / 10)*16 + (cmdValue % 10);
// cannot set sync word greater than 255
if (cmdValue > 255)
cmdValue = 0x12;
// cannot set sync word lower than 0
if (cmdValue <= 0)
cmdValue = 0x12;
PRINT_CSTSTR("%s","^$Set sync word to 0x");
#ifdef ARDUINO
Serial.print(cmdValue, HEX);
#else
PRINT_VALUE("%X", cmdValue);
#endif
PRINTLN;
e = sx1272.setSyncWord(cmdValue);
PRINT_CSTSTR("%s","^$LoRa sync word: state ");
PRINT_VALUE("%d",e);
PRINTLN;
break;
case 'C':
if (cmd[i+1]=='A' && cmd[i+2]=='D') {
if (cmd[i+3]=='O' && cmd[i+4]=='N') {
i=i+5;
cmdValue=getCmdValue(i);
// cannot set send_cad_number greater than 255
if (cmdValue > 255)
cmdValue = 255;
send_cad_number=cmdValue;
PRINT_CSTSTR("%s","Set send_cad_number to ");
PRINT_VALUE("%d",send_cad_number);
PRINTLN;
break;
}
if (cmd[i+3]=='O' && cmd[i+4]=='F' && cmd[i+5]=='F' ) {
send_cad_number=0;
break;
}
startDoCad=millis();
e = sx1272.doCAD(SIFS_cad_number);
endDoCad=millis();
PRINT_CSTSTR("%s","--> SIFS duration ");
PRINT_VALUE("%ld",endDoCad-startDoCad);
PRINTLN;
if (!e)
PRINT_CSTSTR("%s","OK");
else
PRINT_CSTSTR("%s","###");
PRINTLN;
}
else {
i++;
cmdValue=getCmdValue(i);
// cannot set channel greater than 17
if (cmdValue > 18)
cmdValue = 10;
// cannot set channel lower than 10
if (cmdValue < 10)
cmdValue = 10;
// set channel
loraChannelIndex=cmdValue-10;
loraChannel=loraChannelArray[loraChannelIndex];
PRINT_CSTSTR("%s","^$Set LoRa channel to ");
PRINT_VALUE("%d",cmdValue);
PRINTLN;
// Select frequency channel
e = sx1272.setChannel(loraChannel);
PRINT_CSTSTR("%s","^$Setting Channel: state ");
PRINT_VALUE("%d",e);
PRINTLN;
PRINT_CSTSTR("%s","Time: ");
PRINT_VALUE("%d",sx1272._stoptime-sx1272._starttime);
PRINTLN;
}
break;
case 'P':
if (cmd[i+1]=='L' || cmd[i+1]=='H' || cmd[i+1]=='M' || cmd[i+1]=='x' || cmd[i+1]=='X' ) {
loraPower=cmd[i+1];
PRINT_CSTSTR("%s","^$Set LoRa Power to ");
PRINT_VALUE("%c",loraPower);
PRINTLN;
// Select frequency channel
e = sx1272.setPower(loraPower);
PRINT_CSTSTR("%s","^$Setting Power: state ");
PRINT_VALUE("%d",e);
PRINTLN;
}
else
PRINT_CSTSTR("%s","Invalid Power. L, H, M, x or X accepted.\n");
break;
case 'A':
if (cmd[i+1]=='C' && cmd[i+2]=='K') {
if (cmd[i+3]=='#') {
// point to the start of the message, skip /@ACK#
i=6;
withTmpAck=true;
sendCmd=true;
}
else {
if (cmd[i+3]=='O' && cmd[i+4]=='N') {
withAck=true;
PRINT_CSTSTR("%s","^$ACK enabled\n");
}
if (cmd[i+3]=='O' && cmd[i+4]=='F' && cmd[i+5]=='F') {
withAck=false;
PRINT_CSTSTR("%s","^$ACK disabled\n");
}
}
}
else {
i++;
cmdValue=getCmdValue(i);
// cannot set addr greater than 255
if (cmdValue > 255)
cmdValue = 255;
// cannot set addr lower than 1 since 0 is broadcast
if (cmdValue < 1)
cmdValue = LORA_ADDR;
// set node addr
loraAddr=cmdValue;
PRINT_CSTSTR("%s","^$Set LoRa node addr to ");
PRINT_VALUE("%d",loraAddr);
PRINTLN;
// Set the node address and print the result
e = sx1272.setNodeAddress(loraAddr);
PRINT_CSTSTR("%s","^$Setting LoRa node addr: state ");
PRINT_VALUE("%d",e);
PRINTLN;
}
break;
case 'O':
if (cmd[i+1]=='N') {
PRINT_CSTSTR("%s","^$Setting LoRa module to ON");
// Power ON the module
e = sx1272.ON();
PRINT_CSTSTR("%s","^$Setting power ON: state ");
PRINT_VALUE("%d",e);
PRINTLN;
if (!e) {
radioON=true;
startConfig();
}
delay(500);
}
else
if (cmd[i+1]=='F' && cmd[i+2]=='F') {
PRINT_CSTSTR("%s","^$Setting LoRa module to OFF\n");
// Power OFF the module
sx1272.OFF();
radioON=false;
}
else
PRINT_CSTSTR("%s","Invalid command. ON or OFF accepted.\n");
break;
#ifdef LORA_LAS
// act as an LR-BS if IS_RCV_GATEWAY or an end-device if IS_SEND_GATEWAY
case 'L':
if (cmd[i+1]=='A' && cmd[i+2]=='S') {
if (cmd[i+3]=='S')
loraLAS.showLAS();
if (cmd[i+3]=='R') {
loraLAS.reset();
loraLAS.showLAS();
}
if (cmd[i+3]=='O' && cmd[i+4]=='N')
loraLAS.ON(LAS_ON_NORESET);
if (cmd[i+3]=='O' && cmd[i+4]=='F' && cmd[i+5]=='F')
loraLAS.OFF();
#ifdef IS_RCV_GATEWAY
// only the base station can sent an INIT restart message
// sends an init restart
if (cmd[i+3]=='I') {
loraLAS.sendInit(LAS_INIT_RESTART);
}
#endif
}
break;
#endif
default:
PRINT_CSTSTR("%s","Unrecognized cmd\n");
break;
}
FLUSHOUTPUT;
}
else
sendCmd=true;
#ifdef IS_SEND_GATEWAY
///////////////////////////////////////////////////////
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
if (sendCmd && receivedFromSerial) {
uint8_t pl=strlen((char*)(&cmd[i]));
PRINT_CSTSTR("%s","Sending. Length is ");
PRINT_VALUE("%d",pl);
PRINTLN;
PRINT_STR("%s",(char*)(&cmd[i]));
PRINTLN;
#ifdef LORA_LAS
if (forTmpDestAddr>=0)
e = loraLAS.sendData(forTmpDestAddr, (uint8_t*)(&cmd[i]), pl, 0,
LAS_FIRST_DATAPKT+LAS_LAST_DATAPKT, withAck | withTmpAck);
else
e = loraLAS.sendData(dest_addr, (uint8_t*)(&cmd[i]), pl, 0,
LAS_FIRST_DATAPKT+LAS_LAST_DATAPKT, withAck | withTmpAck);
if (e==TOA_OVERUSE) {
PRINT_CSTSTR("%s","^$Not sent, TOA_OVERUSE\n");
}
if (e==LAS_LBT_ERROR) {
PRINT_CSTSTR("%s","^$LBT error\n");
}
if (e==LAS_SEND_ERROR || e==LAS_ERROR) {
PRINT_CSTSTR("%s","Send error\n");
}
#else
// only the DIFS/SIFS mechanism
// we chose to have a complete control code insytead of using the implementation of the LAS class
// for better debugging and tests features if needed.
PRINT_CSTSTR("%s","Payload size is ");
PRINT_VALUE("%d",pl);
PRINTLN;
uint32_t toa = sx1272.getToA(pl+5);
PRINT_CSTSTR("%s","ToA is w/5B Libelium header ");
PRINT_VALUE("%d",toa);
PRINTLN;
long startSend, endSend;
long startSendCad;
startSendCad=millis();
CarrierSense();
startSend=millis();
#ifdef WITH_SEND_LED
digitalWrite(SEND_LED, HIGH);
#endif
PRINT_CSTSTR("%s","Packet number ");
PRINT_VALUE("%d",sx1272._packetNumber);
PRINTLN;
// to test with appkey + encrypted
//sx1272.setPacketType(PKT_TYPE_DATA | PKT_FLAG_DATA_WAPPKEY | PKT_FLAG_DATA_ENCRYPTED);
sx1272.setPacketType(PKT_TYPE_DATA);
if (forTmpDestAddr>=0) {
if (withAck)
e = sx1272.sendPacketTimeoutACK(forTmpDestAddr, (uint8_t*)(&cmd[i]), pl, 10000);
else
e = sx1272.sendPacketTimeout(forTmpDestAddr, (uint8_t*)(&cmd[i]), pl, 10000);
}
else {
if (withAck || withTmpAck)
e = sx1272.sendPacketTimeoutACK(dest_addr, (uint8_t*)(&cmd[i]), pl, 10000);
else
e = sx1272.sendPacketTimeout(dest_addr, (uint8_t*)(&cmd[i]), pl, 10000);
}
#ifdef WITH_SEND_LED
digitalWrite(SEND_LED, LOW);
#endif
endSend=millis();
if ((withAck || withTmpAck) && !e) {
sx1272.getSNR();
sx1272.getRSSIpacket();
sprintf(sprintf_buf,"--- rxlora ACK. SNR=%d RSSIpkt=%d\n",
sx1272._SNR,
sx1272._RSSIpacket);
PRINT_STR("%s",sprintf_buf);
PRINT_CSTSTR("%s","LoRa (ACK) Sent in ");
}
else
PRINT_CSTSTR("%s","LoRa Sent in ");
PRINT_VALUE("%ld",endSend-startSend);
PRINTLN;
PRINT_CSTSTR("%s","LoRa Sent w/CAD in ");
PRINT_VALUE("%ld",endSend-startSendCad);
PRINTLN;
#endif
PRINT_CSTSTR("%s","Packet sent, state ");
PRINT_VALUE("%d",e);
PRINTLN;
//Serial.flush();
}
#endif
// ONLY FOR END-DEVICE SENDING MESSAGES TO BASE STATION
///END/////////////////////////////////////////////////
} // end of "if (receivedFromSerial || receivedFromLoRa)"
}
// for Linux-based gateway only
///////////////////////////////
#ifndef ARDUINO
#ifdef WINPUT
// when CTRL-C is pressed
// set back the correct terminal settings
void INThandler(int sig)
{
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
PRINT_CSTSTR("%s","Bye.\n");
exit(0);
}
#endif
int main (int argc, char *argv[]){
int opt=0;
//Specifying the expected options
static struct option long_options[] = {
{"mode", required_argument, 0, 'a' },
{"aes", no_argument, 0, 'b' },
{"bw", required_argument, 0, 'c' },
{"cr", required_argument, 0, 'd' },
{"sf", required_argument, 0, 'e' },
{"raw", no_argument, 0, 'f' },
{"freq", required_argument, 0, 'g' },
{"ch", required_argument, 0, 'h' },
{"sw", required_argument, 0, 'i' },
{0, 0, 0, 0}
};
int long_index=0;
while ((opt = getopt_long(argc, argv,"a:bc:d:e:fg:h:i:",
long_options, &long_index )) != -1) {
switch (opt) {
case 'a' : loraMode = atoi(optarg);
break;
case 'b' : optAESgw=true;
break;
case 'c' : optBW = atoi(optarg);
// 125, 250 or 500
// setBW() will correct the optBW value
break;
case 'd' : optCR = atoi(optarg);
// 5, 6, 7 or 8
// setCR() will correct the optCR value
break;
case 'e' : optSF = atoi(optarg);
// 6, 7, 8, 9, 10, 11 or 12
break;
case 'f' : optRAW=true;
break;
case 'g' : optFQ=atof(optarg);
// in MHz
// e.g. 868.1
loraChannel=optFQ*1000000.0*RH_LORA_FCONVERT;
break;
case 'h' : optCH=true;
loraChannelIndex=atoi(optarg)-10;
loraChannel=loraChannelArray[loraChannelIndex];
break;
case 'i' : uint8_t sw=atoi(optarg);
// assume that sw is expressed in hex value
optSW = (sw / 10)*16 + (sw % 10);
break;
//default: print_usage();
// exit(EXIT_FAILURE);
}
}
#ifdef WINPUT
// set termios options to remove echo and to have non blocking read from
// standard input (e.g. keyboard)
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
// non-blocking noncanonical mode
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
// VMIN and VTIME are 0 for non-blocking
old.c_cc[VMIN] = 0;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
// we catch the CTRL-C key
signal(SIGINT, INThandler);
#endif
setup();
while(1){
loop();
}
return (0);
}
#endif
| [
"cpham@MacBookProRetina-de-Congduc-Pham.local"
] | cpham@MacBookProRetina-de-Congduc-Pham.local |
e45fd2b0f72059f7806e24d642c63bac525d3aca | f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e | /sc-virt/src/lib/Target/X86/X86TargetTransformInfo.cpp | f44a8c6620289a22c2b289d09d9f34618f844ff2 | [
"MIT",
"NCSA"
] | permissive | archercreat/dta-vs-osc | 2f495f74e0a67d3672c1fc11ecb812d3bc116210 | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | refs/heads/main | 2023-08-01T01:54:05.925289 | 2021-09-05T21:00:35 | 2021-09-05T21:00:35 | 438,047,267 | 1 | 1 | MIT | 2021-12-13T22:45:20 | 2021-12-13T22:45:19 | null | UTF-8 | C++ | false | false | 65,096 | cpp | //===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a TargetTransformInfo analysis pass specific to the
/// X86 target machine. It uses the target's detailed information to provide
/// more precise answers to certain TTI queries, while letting the target
/// independent and default TTI implementations handle the rest.
///
//===----------------------------------------------------------------------===//
#include "X86TargetTransformInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/BasicTTIImpl.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/CostTable.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
#define DEBUG_TYPE "x86tti"
//===----------------------------------------------------------------------===//
//
// X86 cost model.
//
//===----------------------------------------------------------------------===//
TargetTransformInfo::PopcntSupportKind
X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
// TODO: Currently the __builtin_popcount() implementation using SSE3
// instructions is inefficient. Once the problem is fixed, we should
// call ST->hasSSE3() instead of ST->hasPOPCNT().
return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
}
unsigned X86TTIImpl::getNumberOfRegisters(bool Vector) {
if (Vector && !ST->hasSSE1())
return 0;
if (ST->is64Bit()) {
if (Vector && ST->hasAVX512())
return 32;
return 16;
}
return 8;
}
unsigned X86TTIImpl::getRegisterBitWidth(bool Vector) {
if (Vector) {
if (ST->hasAVX512()) return 512;
if (ST->hasAVX()) return 256;
if (ST->hasSSE1()) return 128;
return 0;
}
if (ST->is64Bit())
return 64;
return 32;
}
unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
// If the loop will not be vectorized, don't interleave the loop.
// Let regular unroll to unroll the loop, which saves the overflow
// check and memory check cost.
if (VF == 1)
return 1;
if (ST->isAtom())
return 1;
// Sandybridge and Haswell have multiple execution ports and pipelined
// vector units.
if (ST->hasAVX())
return 4;
return 2;
}
int X86TTIImpl::getArithmeticInstrCost(
unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
TTI::OperandValueProperties Opd2PropInfo) {
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
if (ISD == ISD::SDIV &&
Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
// On X86, vector signed division by constants power-of-two are
// normally expanded to the sequence SRA + SRL + ADD + SRA.
// The OperandValue properties many not be same as that of previous
// operation;conservatively assume OP_None.
int Cost = 2 * getArithmeticInstrCost(Instruction::AShr, Ty, Op1Info,
Op2Info, TargetTransformInfo::OP_None,
TargetTransformInfo::OP_None);
Cost += getArithmeticInstrCost(Instruction::LShr, Ty, Op1Info, Op2Info,
TargetTransformInfo::OP_None,
TargetTransformInfo::OP_None);
Cost += getArithmeticInstrCost(Instruction::Add, Ty, Op1Info, Op2Info,
TargetTransformInfo::OP_None,
TargetTransformInfo::OP_None);
return Cost;
}
static const CostTblEntry AVX2UniformConstCostTable[] = {
{ ISD::SRA, MVT::v4i64, 4 }, // 2 x psrad + shuffle.
{ ISD::SDIV, MVT::v16i16, 6 }, // vpmulhw sequence
{ ISD::UDIV, MVT::v16i16, 6 }, // vpmulhuw sequence
{ ISD::SDIV, MVT::v8i32, 15 }, // vpmuldq sequence
{ ISD::UDIV, MVT::v8i32, 15 }, // vpmuludq sequence
};
if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
ST->hasAVX2()) {
if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry AVX512CostTable[] = {
{ ISD::SHL, MVT::v16i32, 1 },
{ ISD::SRL, MVT::v16i32, 1 },
{ ISD::SRA, MVT::v16i32, 1 },
{ ISD::SHL, MVT::v8i64, 1 },
{ ISD::SRL, MVT::v8i64, 1 },
{ ISD::SRA, MVT::v8i64, 1 },
};
if (ST->hasAVX512()) {
if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry AVX2CostTable[] = {
// Shifts on v4i64/v8i32 on AVX2 is legal even though we declare to
// customize them to detect the cases where shift amount is a scalar one.
{ ISD::SHL, MVT::v4i32, 1 },
{ ISD::SRL, MVT::v4i32, 1 },
{ ISD::SRA, MVT::v4i32, 1 },
{ ISD::SHL, MVT::v8i32, 1 },
{ ISD::SRL, MVT::v8i32, 1 },
{ ISD::SRA, MVT::v8i32, 1 },
{ ISD::SHL, MVT::v2i64, 1 },
{ ISD::SRL, MVT::v2i64, 1 },
{ ISD::SHL, MVT::v4i64, 1 },
{ ISD::SRL, MVT::v4i64, 1 },
};
// Look for AVX2 lowering tricks.
if (ST->hasAVX2()) {
if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
(Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
// On AVX2, a packed v16i16 shift left by a constant build_vector
// is lowered into a vector multiply (vpmullw).
return LT.first;
if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry XOPCostTable[] = {
// 128bit shifts take 1cy, but right shifts require negation beforehand.
{ ISD::SHL, MVT::v16i8, 1 },
{ ISD::SRL, MVT::v16i8, 2 },
{ ISD::SRA, MVT::v16i8, 2 },
{ ISD::SHL, MVT::v8i16, 1 },
{ ISD::SRL, MVT::v8i16, 2 },
{ ISD::SRA, MVT::v8i16, 2 },
{ ISD::SHL, MVT::v4i32, 1 },
{ ISD::SRL, MVT::v4i32, 2 },
{ ISD::SRA, MVT::v4i32, 2 },
{ ISD::SHL, MVT::v2i64, 1 },
{ ISD::SRL, MVT::v2i64, 2 },
{ ISD::SRA, MVT::v2i64, 2 },
// 256bit shifts require splitting if AVX2 didn't catch them above.
{ ISD::SHL, MVT::v32i8, 2 },
{ ISD::SRL, MVT::v32i8, 4 },
{ ISD::SRA, MVT::v32i8, 4 },
{ ISD::SHL, MVT::v16i16, 2 },
{ ISD::SRL, MVT::v16i16, 4 },
{ ISD::SRA, MVT::v16i16, 4 },
{ ISD::SHL, MVT::v8i32, 2 },
{ ISD::SRL, MVT::v8i32, 4 },
{ ISD::SRA, MVT::v8i32, 4 },
{ ISD::SHL, MVT::v4i64, 2 },
{ ISD::SRL, MVT::v4i64, 4 },
{ ISD::SRA, MVT::v4i64, 4 },
};
// Look for XOP lowering tricks.
if (ST->hasXOP()) {
if (const auto *Entry = CostTableLookup(XOPCostTable, ISD, LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry AVX2CustomCostTable[] = {
{ ISD::SHL, MVT::v32i8, 11 }, // vpblendvb sequence.
{ ISD::SHL, MVT::v16i16, 10 }, // extend/vpsrlvd/pack sequence.
{ ISD::SRL, MVT::v32i8, 11 }, // vpblendvb sequence.
{ ISD::SRL, MVT::v16i16, 10 }, // extend/vpsrlvd/pack sequence.
{ ISD::SRA, MVT::v32i8, 24 }, // vpblendvb sequence.
{ ISD::SRA, MVT::v16i16, 10 }, // extend/vpsravd/pack sequence.
{ ISD::SRA, MVT::v2i64, 4 }, // srl/xor/sub sequence.
{ ISD::SRA, MVT::v4i64, 4 }, // srl/xor/sub sequence.
// Vectorizing division is a bad idea. See the SSE2 table for more comments.
{ ISD::SDIV, MVT::v32i8, 32*20 },
{ ISD::SDIV, MVT::v16i16, 16*20 },
{ ISD::SDIV, MVT::v8i32, 8*20 },
{ ISD::SDIV, MVT::v4i64, 4*20 },
{ ISD::UDIV, MVT::v32i8, 32*20 },
{ ISD::UDIV, MVT::v16i16, 16*20 },
{ ISD::UDIV, MVT::v8i32, 8*20 },
{ ISD::UDIV, MVT::v4i64, 4*20 },
};
// Look for AVX2 lowering tricks for custom cases.
if (ST->hasAVX2()) {
if (const auto *Entry = CostTableLookup(AVX2CustomCostTable, ISD,
LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry
SSE2UniformConstCostTable[] = {
// We don't correctly identify costs of casts because they are marked as
// custom.
// Constant splats are cheaper for the following instructions.
{ ISD::SHL, MVT::v16i8, 1 }, // psllw.
{ ISD::SHL, MVT::v32i8, 2 }, // psllw.
{ ISD::SHL, MVT::v8i16, 1 }, // psllw.
{ ISD::SHL, MVT::v16i16, 2 }, // psllw.
{ ISD::SHL, MVT::v4i32, 1 }, // pslld
{ ISD::SHL, MVT::v8i32, 2 }, // pslld
{ ISD::SHL, MVT::v2i64, 1 }, // psllq.
{ ISD::SHL, MVT::v4i64, 2 }, // psllq.
{ ISD::SRL, MVT::v16i8, 1 }, // psrlw.
{ ISD::SRL, MVT::v32i8, 2 }, // psrlw.
{ ISD::SRL, MVT::v8i16, 1 }, // psrlw.
{ ISD::SRL, MVT::v16i16, 2 }, // psrlw.
{ ISD::SRL, MVT::v4i32, 1 }, // psrld.
{ ISD::SRL, MVT::v8i32, 2 }, // psrld.
{ ISD::SRL, MVT::v2i64, 1 }, // psrlq.
{ ISD::SRL, MVT::v4i64, 2 }, // psrlq.
{ ISD::SRA, MVT::v16i8, 4 }, // psrlw, pand, pxor, psubb.
{ ISD::SRA, MVT::v32i8, 8 }, // psrlw, pand, pxor, psubb.
{ ISD::SRA, MVT::v8i16, 1 }, // psraw.
{ ISD::SRA, MVT::v16i16, 2 }, // psraw.
{ ISD::SRA, MVT::v4i32, 1 }, // psrad.
{ ISD::SRA, MVT::v8i32, 2 }, // psrad.
{ ISD::SRA, MVT::v2i64, 4 }, // 2 x psrad + shuffle.
{ ISD::SRA, MVT::v4i64, 8 }, // 2 x psrad + shuffle.
{ ISD::SDIV, MVT::v8i16, 6 }, // pmulhw sequence
{ ISD::UDIV, MVT::v8i16, 6 }, // pmulhuw sequence
{ ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence
{ ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence
};
if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
ST->hasSSE2()) {
// pmuldq sequence.
if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
return LT.first * 15;
if (const auto *Entry = CostTableLookup(SSE2UniformConstCostTable, ISD,
LT.second))
return LT.first * Entry->Cost;
}
if (ISD == ISD::SHL &&
Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
MVT VT = LT.second;
// Vector shift left by non uniform constant can be lowered
// into vector multiply (pmullw/pmulld).
if ((VT == MVT::v8i16 && ST->hasSSE2()) ||
(VT == MVT::v4i32 && ST->hasSSE41()))
return LT.first;
// v16i16 and v8i32 shifts by non-uniform constants are lowered into a
// sequence of extract + two vector multiply + insert.
if ((VT == MVT::v8i32 || VT == MVT::v16i16) &&
(ST->hasAVX() && !ST->hasAVX2()))
ISD = ISD::MUL;
// A vector shift left by non uniform constant is converted
// into a vector multiply; the new multiply is eventually
// lowered into a sequence of shuffles and 2 x pmuludq.
if (VT == MVT::v4i32 && ST->hasSSE2())
ISD = ISD::MUL;
}
static const CostTblEntry SSE2CostTable[] = {
// We don't correctly identify costs of casts because they are marked as
// custom.
// For some cases, where the shift amount is a scalar we would be able
// to generate better code. Unfortunately, when this is the case the value
// (the splat) will get hoisted out of the loop, thereby making it invisible
// to ISel. The cost model must return worst case assumptions because it is
// used for vectorization and we don't want to make vectorized code worse
// than scalar code.
{ ISD::SHL, MVT::v16i8, 26 }, // cmpgtb sequence.
{ ISD::SHL, MVT::v32i8, 2*26 }, // cmpgtb sequence.
{ ISD::SHL, MVT::v8i16, 32 }, // cmpgtb sequence.
{ ISD::SHL, MVT::v16i16, 2*32 }, // cmpgtb sequence.
{ ISD::SHL, MVT::v4i32, 2*5 }, // We optimized this using mul.
{ ISD::SHL, MVT::v8i32, 2*2*5 }, // We optimized this using mul.
{ ISD::SHL, MVT::v2i64, 4 }, // splat+shuffle sequence.
{ ISD::SHL, MVT::v4i64, 2*4 }, // splat+shuffle sequence.
{ ISD::SRL, MVT::v16i8, 26 }, // cmpgtb sequence.
{ ISD::SRL, MVT::v32i8, 2*26 }, // cmpgtb sequence.
{ ISD::SRL, MVT::v8i16, 32 }, // cmpgtb sequence.
{ ISD::SRL, MVT::v16i16, 2*32 }, // cmpgtb sequence.
{ ISD::SRL, MVT::v4i32, 16 }, // Shift each lane + blend.
{ ISD::SRL, MVT::v8i32, 2*16 }, // Shift each lane + blend.
{ ISD::SRL, MVT::v2i64, 4 }, // splat+shuffle sequence.
{ ISD::SRL, MVT::v4i64, 2*4 }, // splat+shuffle sequence.
{ ISD::SRA, MVT::v16i8, 54 }, // unpacked cmpgtb sequence.
{ ISD::SRA, MVT::v32i8, 2*54 }, // unpacked cmpgtb sequence.
{ ISD::SRA, MVT::v8i16, 32 }, // cmpgtb sequence.
{ ISD::SRA, MVT::v16i16, 2*32 }, // cmpgtb sequence.
{ ISD::SRA, MVT::v4i32, 16 }, // Shift each lane + blend.
{ ISD::SRA, MVT::v8i32, 2*16 }, // Shift each lane + blend.
{ ISD::SRA, MVT::v2i64, 12 }, // srl/xor/sub sequence.
{ ISD::SRA, MVT::v4i64, 2*12 }, // srl/xor/sub sequence.
// It is not a good idea to vectorize division. We have to scalarize it and
// in the process we will often end up having to spilling regular
// registers. The overhead of division is going to dominate most kernels
// anyways so try hard to prevent vectorization of division - it is
// generally a bad idea. Assume somewhat arbitrarily that we have to be able
// to hide "20 cycles" for each lane.
{ ISD::SDIV, MVT::v16i8, 16*20 },
{ ISD::SDIV, MVT::v8i16, 8*20 },
{ ISD::SDIV, MVT::v4i32, 4*20 },
{ ISD::SDIV, MVT::v2i64, 2*20 },
{ ISD::UDIV, MVT::v16i8, 16*20 },
{ ISD::UDIV, MVT::v8i16, 8*20 },
{ ISD::UDIV, MVT::v4i32, 4*20 },
{ ISD::UDIV, MVT::v2i64, 2*20 },
};
if (ST->hasSSE2()) {
if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
return LT.first * Entry->Cost;
}
static const CostTblEntry AVX1CostTable[] = {
// We don't have to scalarize unsupported ops. We can issue two half-sized
// operations and we only need to extract the upper YMM half.
// Two ops + 1 extract + 1 insert = 4.
{ ISD::MUL, MVT::v16i16, 4 },
{ ISD::MUL, MVT::v8i32, 4 },
{ ISD::SUB, MVT::v8i32, 4 },
{ ISD::ADD, MVT::v8i32, 4 },
{ ISD::SUB, MVT::v4i64, 4 },
{ ISD::ADD, MVT::v4i64, 4 },
// A v4i64 multiply is custom lowered as two split v2i64 vectors that then
// are lowered as a series of long multiplies(3), shifts(4) and adds(2)
// Because we believe v4i64 to be a legal type, we must also include the
// split factor of two in the cost table. Therefore, the cost here is 18
// instead of 9.
{ ISD::MUL, MVT::v4i64, 18 },
};
// Look for AVX1 lowering tricks.
if (ST->hasAVX() && !ST->hasAVX2()) {
MVT VT = LT.second;
if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, VT))
return LT.first * Entry->Cost;
}
// Custom lowering of vectors.
static const CostTblEntry CustomLowered[] = {
// A v2i64/v4i64 and multiply is custom lowered as a series of long
// multiplies(3), shifts(4) and adds(2).
{ ISD::MUL, MVT::v2i64, 9 },
{ ISD::MUL, MVT::v4i64, 9 },
};
if (const auto *Entry = CostTableLookup(CustomLowered, ISD, LT.second))
return LT.first * Entry->Cost;
// Special lowering of v4i32 mul on sse2, sse3: Lower v4i32 mul as 2x shuffle,
// 2x pmuludq, 2x shuffle.
if (ISD == ISD::MUL && LT.second == MVT::v4i32 && ST->hasSSE2() &&
!ST->hasSSE41())
return LT.first * 6;
// Fallback to the default implementation.
return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
}
int X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
Type *SubTp) {
// We only estimate the cost of reverse and alternate shuffles.
if (Kind != TTI::SK_Reverse && Kind != TTI::SK_Alternate)
return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
if (Kind == TTI::SK_Reverse) {
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
int Cost = 1;
if (LT.second.getSizeInBits() > 128)
Cost = 3; // Extract + insert + copy.
// Multiple by the number of parts.
return Cost * LT.first;
}
if (Kind == TTI::SK_Alternate) {
// 64-bit packed float vectors (v2f32) are widened to type v4f32.
// 64-bit packed integer vectors (v2i32) are promoted to type v2i64.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
// The backend knows how to generate a single VEX.256 version of
// instruction VPBLENDW if the target supports AVX2.
if (ST->hasAVX2() && LT.second == MVT::v16i16)
return LT.first;
static const CostTblEntry AVXAltShuffleTbl[] = {
{ISD::VECTOR_SHUFFLE, MVT::v4i64, 1}, // vblendpd
{ISD::VECTOR_SHUFFLE, MVT::v4f64, 1}, // vblendpd
{ISD::VECTOR_SHUFFLE, MVT::v8i32, 1}, // vblendps
{ISD::VECTOR_SHUFFLE, MVT::v8f32, 1}, // vblendps
// This shuffle is custom lowered into a sequence of:
// 2x vextractf128 , 2x vpblendw , 1x vinsertf128
{ISD::VECTOR_SHUFFLE, MVT::v16i16, 5},
// This shuffle is custom lowered into a long sequence of:
// 2x vextractf128 , 4x vpshufb , 2x vpor , 1x vinsertf128
{ISD::VECTOR_SHUFFLE, MVT::v32i8, 9}
};
if (ST->hasAVX())
if (const auto *Entry = CostTableLookup(AVXAltShuffleTbl,
ISD::VECTOR_SHUFFLE, LT.second))
return LT.first * Entry->Cost;
static const CostTblEntry SSE41AltShuffleTbl[] = {
// These are lowered into movsd.
{ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
{ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
// packed float vectors with four elements are lowered into BLENDI dag
// nodes. A v4i32/v4f32 BLENDI generates a single 'blendps'/'blendpd'.
{ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
{ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
// This shuffle generates a single pshufw.
{ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
// There is no instruction that matches a v16i8 alternate shuffle.
// The backend will expand it into the sequence 'pshufb + pshufb + or'.
{ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}
};
if (ST->hasSSE41())
if (const auto *Entry = CostTableLookup(SSE41AltShuffleTbl, ISD::VECTOR_SHUFFLE,
LT.second))
return LT.first * Entry->Cost;
static const CostTblEntry SSSE3AltShuffleTbl[] = {
{ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, // movsd
{ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, // movsd
// SSE3 doesn't have 'blendps'. The following shuffles are expanded into
// the sequence 'shufps + pshufd'
{ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
{ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
{ISD::VECTOR_SHUFFLE, MVT::v8i16, 3}, // pshufb + pshufb + or
{ISD::VECTOR_SHUFFLE, MVT::v16i8, 3} // pshufb + pshufb + or
};
if (ST->hasSSSE3())
if (const auto *Entry = CostTableLookup(SSSE3AltShuffleTbl,
ISD::VECTOR_SHUFFLE, LT.second))
return LT.first * Entry->Cost;
static const CostTblEntry SSEAltShuffleTbl[] = {
{ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, // movsd
{ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, // movsd
{ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, // shufps + pshufd
{ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, // shufps + pshufd
// This is expanded into a long sequence of four extract + four insert.
{ISD::VECTOR_SHUFFLE, MVT::v8i16, 8}, // 4 x pextrw + 4 pinsrw.
// 8 x (pinsrw + pextrw + and + movb + movzb + or)
{ISD::VECTOR_SHUFFLE, MVT::v16i8, 48}
};
// Fall-back (SSE3 and SSE2).
if (const auto *Entry = CostTableLookup(SSEAltShuffleTbl,
ISD::VECTOR_SHUFFLE, LT.second))
return LT.first * Entry->Cost;
return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
}
return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
}
int X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
// FIXME: Need a better design of the cost table to handle non-simple types of
// potential massive combinations (elem_num x src_type x dst_type).
static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
{ ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 1 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i64, 1 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 1 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i64, 1 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i64, 1 },
{ ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 1 },
{ ISD::FP_TO_UINT, MVT::v4i64, MVT::v4f32, 1 },
{ ISD::FP_TO_UINT, MVT::v8i64, MVT::v8f32, 1 },
{ ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
{ ISD::FP_TO_UINT, MVT::v4i64, MVT::v4f64, 1 },
{ ISD::FP_TO_UINT, MVT::v8i64, MVT::v8f64, 1 },
};
// TODO: For AVX512DQ + AVX512VL, we also have cheap casts for 128-bit and
// 256-bit wide vectors.
static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
{ ISD::FP_EXTEND, MVT::v8f64, MVT::v8f32, 1 },
{ ISD::FP_EXTEND, MVT::v8f64, MVT::v16f32, 3 },
{ ISD::FP_ROUND, MVT::v8f32, MVT::v8f64, 1 },
{ ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 1 },
{ ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 1 },
{ ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 1 },
{ ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 1 },
// v16i1 -> v16i32 - load + broadcast
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1, 2 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1, 2 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 1 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 1 },
{ ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 1 },
{ ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i32, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i32, 1 },
{ ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i1, 4 },
{ ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i1, 3 },
{ ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i8, 2 },
{ ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 2 },
{ ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i16, 2 },
{ ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 2 },
{ ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 1 },
{ ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i32, 1 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i64, 26 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i64, 26 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i1, 4 },
{ ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i1, 3 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 2 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i8, 2 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 2 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i8, 2 },
{ ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 2 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 5 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i16, 2 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 2 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i16, 2 },
{ ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 2 },
{ ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 2 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 1 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 1 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 1 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i32, 1 },
{ ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 1 },
{ ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 5 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 5 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 12 },
{ ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i64, 26 },
{ ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
{ ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
{ ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f32, 1 },
{ ISD::FP_TO_UINT, MVT::v16i32, MVT::v16f32, 1 },
};
static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i1, 3 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i1, 3 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 3 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 3 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 3 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 3 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
{ ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1 },
{ ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 2 },
{ ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 2 },
{ ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 2 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 2 },
{ ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 2 },
{ ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 4 },
{ ISD::FP_EXTEND, MVT::v8f64, MVT::v8f32, 3 },
{ ISD::FP_ROUND, MVT::v8f32, MVT::v8f64, 3 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 8 },
};
static const TypeConversionCostTblEntry AVXConversionTbl[] = {
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i1, 6 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i1, 4 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 7 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 4 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 6 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 4 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 7 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 4 },
{ ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
{ ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 6 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 4 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 4 },
{ ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 4 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 4 },
{ ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 5 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 4 },
{ ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 4 },
{ ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 4 },
{ ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 9 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i1, 3 },
{ ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i1, 8 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i8, 3 },
{ ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 8 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 3 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i16, 3 },
{ ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 5 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i32, 1 },
{ ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 1 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 7 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i1, 7 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i1, 6 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 2 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i8, 2 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 5 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i16, 2 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 5 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 6 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 6 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 6 },
{ ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 9 },
// The generic code to compute the scalar overhead is currently broken.
// Workaround this limitation by estimating the scalarization overhead
// here. We have roughly 10 instructions per scalar element.
// Multiply that by the vector width.
// FIXME: remove that when PR19268 is fixed.
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 10 },
{ ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 20 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i64, 13 },
{ ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i64, 13 },
{ ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
{ ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 7 },
// This node is expanded into scalarized operations but BasicTTI is overly
// optimistic estimating its cost. It computes 3 per element (one
// vector-extract, one scalar conversion and one vector-insert). The
// problem is that the inserts form a read-modify-write chain so latency
// should be factored in too. Inflating the cost per element by 1.
{ ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f32, 8*4 },
{ ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f64, 4*4 },
{ ISD::FP_EXTEND, MVT::v4f64, MVT::v4f32, 1 },
{ ISD::FP_ROUND, MVT::v4f32, MVT::v4f64, 1 },
};
static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 2 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 2 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 2 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 2 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
{ ISD::ZERO_EXTEND, MVT::v4i16, MVT::v4i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i16, MVT::v4i8, 2 },
{ ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 2 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 2 },
{ ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
{ ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 4 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 4 },
{ ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i16, 2 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 1 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 1 },
{ ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
{ ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 3 },
{ ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 6 },
};
static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
// These are somewhat magic numbers justified by looking at the output of
// Intel's IACA, running some kernels and making sure when we take
// legalization into account the throughput will be overestimated.
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
{ ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
{ ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 5 },
{ ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
{ ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
{ ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
{ ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
{ ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
{ ISD::ZERO_EXTEND, MVT::v4i16, MVT::v4i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i16, MVT::v4i8, 6 },
{ ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
{ ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 3 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 4 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 8 },
{ ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
{ ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 2 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 6 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 6 },
{ ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 3 },
{ ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 9 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 12 },
{ ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
{ ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 2 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 10 },
{ ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 3 },
{ ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
{ ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 6 },
{ ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 8 },
{ ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 3 },
{ ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 5 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i16, 4 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 2 },
{ ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 3 },
{ ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 3 },
{ ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 3 },
{ ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 4 },
{ ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 7 },
{ ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 5 },
{ ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 10 },
};
std::pair<int, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
std::pair<int, MVT> LTDest = TLI->getTypeLegalizationCost(DL, Dst);
if (ST->hasSSE2() && !ST->hasAVX()) {
if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
LTDest.second, LTSrc.second))
return LTSrc.first * Entry->Cost;
}
EVT SrcTy = TLI->getValueType(DL, Src);
EVT DstTy = TLI->getValueType(DL, Dst);
// The function getSimpleVT only handles simple value types.
if (!SrcTy.isSimple() || !DstTy.isSimple())
return BaseT::getCastInstrCost(Opcode, Dst, Src);
if (ST->hasDQI())
if (const auto *Entry = ConvertCostTableLookup(AVX512DQConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
if (ST->hasAVX512())
if (const auto *Entry = ConvertCostTableLookup(AVX512FConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
if (ST->hasAVX2()) {
if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
}
if (ST->hasAVX()) {
if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
}
if (ST->hasSSE41()) {
if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
}
if (ST->hasSSE2()) {
if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
DstTy.getSimpleVT(),
SrcTy.getSimpleVT()))
return Entry->Cost;
}
return BaseT::getCastInstrCost(Opcode, Dst, Src);
}
int X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
MVT MTy = LT.second;
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
static const CostTblEntry SSE2CostTbl[] = {
{ ISD::SETCC, MVT::v2i64, 8 },
{ ISD::SETCC, MVT::v4i32, 1 },
{ ISD::SETCC, MVT::v8i16, 1 },
{ ISD::SETCC, MVT::v16i8, 1 },
};
static const CostTblEntry SSE42CostTbl[] = {
{ ISD::SETCC, MVT::v2f64, 1 },
{ ISD::SETCC, MVT::v4f32, 1 },
{ ISD::SETCC, MVT::v2i64, 1 },
};
static const CostTblEntry AVX1CostTbl[] = {
{ ISD::SETCC, MVT::v4f64, 1 },
{ ISD::SETCC, MVT::v8f32, 1 },
// AVX1 does not support 8-wide integer compare.
{ ISD::SETCC, MVT::v4i64, 4 },
{ ISD::SETCC, MVT::v8i32, 4 },
{ ISD::SETCC, MVT::v16i16, 4 },
{ ISD::SETCC, MVT::v32i8, 4 },
};
static const CostTblEntry AVX2CostTbl[] = {
{ ISD::SETCC, MVT::v4i64, 1 },
{ ISD::SETCC, MVT::v8i32, 1 },
{ ISD::SETCC, MVT::v16i16, 1 },
{ ISD::SETCC, MVT::v32i8, 1 },
};
static const CostTblEntry AVX512CostTbl[] = {
{ ISD::SETCC, MVT::v8i64, 1 },
{ ISD::SETCC, MVT::v16i32, 1 },
{ ISD::SETCC, MVT::v8f64, 1 },
{ ISD::SETCC, MVT::v16f32, 1 },
};
if (ST->hasAVX512())
if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasAVX2())
if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasAVX())
if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSE42())
if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSE2())
if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy);
}
int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
ArrayRef<Type *> Tys, FastMathFlags FMF) {
static const CostTblEntry XOPCostTbl[] = {
{ ISD::BITREVERSE, MVT::v4i64, 4 },
{ ISD::BITREVERSE, MVT::v8i32, 4 },
{ ISD::BITREVERSE, MVT::v16i16, 4 },
{ ISD::BITREVERSE, MVT::v32i8, 4 },
{ ISD::BITREVERSE, MVT::v2i64, 1 },
{ ISD::BITREVERSE, MVT::v4i32, 1 },
{ ISD::BITREVERSE, MVT::v8i16, 1 },
{ ISD::BITREVERSE, MVT::v16i8, 1 },
{ ISD::BITREVERSE, MVT::i64, 3 },
{ ISD::BITREVERSE, MVT::i32, 3 },
{ ISD::BITREVERSE, MVT::i16, 3 },
{ ISD::BITREVERSE, MVT::i8, 3 }
};
static const CostTblEntry AVX2CostTbl[] = {
{ ISD::BITREVERSE, MVT::v4i64, 5 },
{ ISD::BITREVERSE, MVT::v8i32, 5 },
{ ISD::BITREVERSE, MVT::v16i16, 5 },
{ ISD::BITREVERSE, MVT::v32i8, 5 },
{ ISD::BSWAP, MVT::v4i64, 1 },
{ ISD::BSWAP, MVT::v8i32, 1 },
{ ISD::BSWAP, MVT::v16i16, 1 }
};
static const CostTblEntry AVX1CostTbl[] = {
{ ISD::BITREVERSE, MVT::v4i64, 10 },
{ ISD::BITREVERSE, MVT::v8i32, 10 },
{ ISD::BITREVERSE, MVT::v16i16, 10 },
{ ISD::BITREVERSE, MVT::v32i8, 10 },
{ ISD::BSWAP, MVT::v4i64, 4 },
{ ISD::BSWAP, MVT::v8i32, 4 },
{ ISD::BSWAP, MVT::v16i16, 4 }
};
static const CostTblEntry SSSE3CostTbl[] = {
{ ISD::BITREVERSE, MVT::v2i64, 5 },
{ ISD::BITREVERSE, MVT::v4i32, 5 },
{ ISD::BITREVERSE, MVT::v8i16, 5 },
{ ISD::BITREVERSE, MVT::v16i8, 5 },
{ ISD::BSWAP, MVT::v2i64, 1 },
{ ISD::BSWAP, MVT::v4i32, 1 },
{ ISD::BSWAP, MVT::v8i16, 1 }
};
static const CostTblEntry SSE2CostTbl[] = {
{ ISD::BSWAP, MVT::v2i64, 7 },
{ ISD::BSWAP, MVT::v4i32, 7 },
{ ISD::BSWAP, MVT::v8i16, 7 }
};
unsigned ISD = ISD::DELETED_NODE;
switch (IID) {
default:
break;
case Intrinsic::bitreverse:
ISD = ISD::BITREVERSE;
break;
case Intrinsic::bswap:
ISD = ISD::BSWAP;
break;
}
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
MVT MTy = LT.second;
// Attempt to lookup cost.
if (ST->hasXOP())
if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasAVX2())
if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasAVX())
if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSSE3())
if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSE2())
if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
return LT.first * Entry->Cost;
return BaseT::getIntrinsicInstrCost(IID, RetTy, Tys, FMF);
}
int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
ArrayRef<Value *> Args, FastMathFlags FMF) {
return BaseT::getIntrinsicInstrCost(IID, RetTy, Args, FMF);
}
int X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
assert(Val->isVectorTy() && "This must be a vector type");
Type *ScalarType = Val->getScalarType();
if (Index != -1U) {
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
// This type is legalized to a scalar type.
if (!LT.second.isVector())
return 0;
// The type may be split. Normalize the index to the new type.
unsigned Width = LT.second.getVectorNumElements();
Index = Index % Width;
// Floating point scalars are already located in index #0.
if (ScalarType->isFloatingPointTy() && Index == 0)
return 0;
}
// Add to the base cost if we know that the extracted element of a vector is
// destined to be moved to and used in the integer register file.
int RegisterFileMoveCost = 0;
if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
RegisterFileMoveCost = 1;
return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
}
int X86TTIImpl::getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
assert (Ty->isVectorTy() && "Can only scalarize vectors");
int Cost = 0;
for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
if (Insert)
Cost += getVectorInstrCost(Instruction::InsertElement, Ty, i);
if (Extract)
Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, i);
}
return Cost;
}
int X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
unsigned AddressSpace) {
// Handle non-power-of-two vectors such as <3 x float>
if (VectorType *VTy = dyn_cast<VectorType>(Src)) {
unsigned NumElem = VTy->getVectorNumElements();
// Handle a few common cases:
// <3 x float>
if (NumElem == 3 && VTy->getScalarSizeInBits() == 32)
// Cost = 64 bit store + extract + 32 bit store.
return 3;
// <3 x double>
if (NumElem == 3 && VTy->getScalarSizeInBits() == 64)
// Cost = 128 bit store + unpack + 64 bit store.
return 3;
// Assume that all other non-power-of-two numbers are scalarized.
if (!isPowerOf2_32(NumElem)) {
int Cost = BaseT::getMemoryOpCost(Opcode, VTy->getScalarType(), Alignment,
AddressSpace);
int SplitCost = getScalarizationOverhead(Src, Opcode == Instruction::Load,
Opcode == Instruction::Store);
return NumElem * Cost + SplitCost;
}
}
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
"Invalid Opcode");
// Each load/store unit costs 1.
int Cost = LT.first * 1;
// This isn't exactly right. We're using slow unaligned 32-byte accesses as a
// proxy for a double-pumped AVX memory interface such as on Sandybridge.
if (LT.second.getStoreSize() == 32 && ST->isUnalignedMem32Slow())
Cost *= 2;
return Cost;
}
int X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy,
unsigned Alignment,
unsigned AddressSpace) {
VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy);
if (!SrcVTy)
// To calculate scalar take the regular cost, without mask
return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace);
unsigned NumElem = SrcVTy->getVectorNumElements();
VectorType *MaskTy =
VectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
if ((Opcode == Instruction::Load && !isLegalMaskedLoad(SrcVTy)) ||
(Opcode == Instruction::Store && !isLegalMaskedStore(SrcVTy)) ||
!isPowerOf2_32(NumElem)) {
// Scalarization
int MaskSplitCost = getScalarizationOverhead(MaskTy, false, true);
int ScalarCompareCost = getCmpSelInstrCost(
Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr);
int BranchCost = getCFInstrCost(Instruction::Br);
int MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
int ValueSplitCost = getScalarizationOverhead(
SrcVTy, Opcode == Instruction::Load, Opcode == Instruction::Store);
int MemopCost =
NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
Alignment, AddressSpace);
return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
}
// Legalize the type.
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
auto VT = TLI->getValueType(DL, SrcVTy);
int Cost = 0;
if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
LT.second.getVectorNumElements() == NumElem)
// Promotion requires expand/truncate for data and a shuffle for mask.
Cost += getShuffleCost(TTI::SK_Alternate, SrcVTy, 0, nullptr) +
getShuffleCost(TTI::SK_Alternate, MaskTy, 0, nullptr);
else if (LT.second.getVectorNumElements() > NumElem) {
VectorType *NewMaskTy = VectorType::get(MaskTy->getVectorElementType(),
LT.second.getVectorNumElements());
// Expanding requires fill mask with zeroes
Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, 0, MaskTy);
}
if (!ST->hasAVX512())
return Cost + LT.first*4; // Each maskmov costs 4
// AVX-512 masked load/store is cheapper
return Cost+LT.first;
}
int X86TTIImpl::getAddressComputationCost(Type *Ty, bool IsComplex) {
// Address computations in vectorized code with non-consecutive addresses will
// likely result in more instructions compared to scalar code where the
// computation can more often be merged into the index mode. The resulting
// extra micro-ops can significantly decrease throughput.
unsigned NumVectorInstToHideOverhead = 10;
if (Ty->isVectorTy() && IsComplex)
return NumVectorInstToHideOverhead;
return BaseT::getAddressComputationCost(Ty, IsComplex);
}
int X86TTIImpl::getReductionCost(unsigned Opcode, Type *ValTy,
bool IsPairwise) {
std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
MVT MTy = LT.second;
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
// We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
// and make it as the cost.
static const CostTblEntry SSE42CostTblPairWise[] = {
{ ISD::FADD, MVT::v2f64, 2 },
{ ISD::FADD, MVT::v4f32, 4 },
{ ISD::ADD, MVT::v2i64, 2 }, // The data reported by the IACA tool is "1.6".
{ ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "3.5".
{ ISD::ADD, MVT::v8i16, 5 },
};
static const CostTblEntry AVX1CostTblPairWise[] = {
{ ISD::FADD, MVT::v4f32, 4 },
{ ISD::FADD, MVT::v4f64, 5 },
{ ISD::FADD, MVT::v8f32, 7 },
{ ISD::ADD, MVT::v2i64, 1 }, // The data reported by the IACA tool is "1.5".
{ ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "3.5".
{ ISD::ADD, MVT::v4i64, 5 }, // The data reported by the IACA tool is "4.8".
{ ISD::ADD, MVT::v8i16, 5 },
{ ISD::ADD, MVT::v8i32, 5 },
};
static const CostTblEntry SSE42CostTblNoPairWise[] = {
{ ISD::FADD, MVT::v2f64, 2 },
{ ISD::FADD, MVT::v4f32, 4 },
{ ISD::ADD, MVT::v2i64, 2 }, // The data reported by the IACA tool is "1.6".
{ ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "3.3".
{ ISD::ADD, MVT::v8i16, 4 }, // The data reported by the IACA tool is "4.3".
};
static const CostTblEntry AVX1CostTblNoPairWise[] = {
{ ISD::FADD, MVT::v4f32, 3 },
{ ISD::FADD, MVT::v4f64, 3 },
{ ISD::FADD, MVT::v8f32, 4 },
{ ISD::ADD, MVT::v2i64, 1 }, // The data reported by the IACA tool is "1.5".
{ ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "2.8".
{ ISD::ADD, MVT::v4i64, 3 },
{ ISD::ADD, MVT::v8i16, 4 },
{ ISD::ADD, MVT::v8i32, 5 },
};
if (IsPairwise) {
if (ST->hasAVX())
if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSE42())
if (const auto *Entry = CostTableLookup(SSE42CostTblPairWise, ISD, MTy))
return LT.first * Entry->Cost;
} else {
if (ST->hasAVX())
if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
return LT.first * Entry->Cost;
if (ST->hasSSE42())
if (const auto *Entry = CostTableLookup(SSE42CostTblNoPairWise, ISD, MTy))
return LT.first * Entry->Cost;
}
return BaseT::getReductionCost(Opcode, ValTy, IsPairwise);
}
/// \brief Calculate the cost of materializing a 64-bit value. This helper
/// method might only calculate a fraction of a larger immediate. Therefore it
/// is valid to return a cost of ZERO.
int X86TTIImpl::getIntImmCost(int64_t Val) {
if (Val == 0)
return TTI::TCC_Free;
if (isInt<32>(Val))
return TTI::TCC_Basic;
return 2 * TTI::TCC_Basic;
}
int X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
if (BitSize == 0)
return ~0U;
// Never hoist constants larger than 128bit, because this might lead to
// incorrect code generation or assertions in codegen.
// Fixme: Create a cost model for types larger than i128 once the codegen
// issues have been fixed.
if (BitSize > 128)
return TTI::TCC_Free;
if (Imm == 0)
return TTI::TCC_Free;
// Sign-extend all constants to a multiple of 64-bit.
APInt ImmVal = Imm;
if (BitSize & 0x3f)
ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
// Split the constant into 64-bit chunks and calculate the cost for each
// chunk.
int Cost = 0;
for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
int64_t Val = Tmp.getSExtValue();
Cost += getIntImmCost(Val);
}
// We need at least one instruction to materialize the constant.
return std::max(1, Cost);
}
int X86TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
Type *Ty) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
// There is no cost model for constants with a bit size of 0. Return TCC_Free
// here, so that constant hoisting will ignore this constant.
if (BitSize == 0)
return TTI::TCC_Free;
unsigned ImmIdx = ~0U;
switch (Opcode) {
default:
return TTI::TCC_Free;
case Instruction::GetElementPtr:
// Always hoist the base address of a GetElementPtr. This prevents the
// creation of new constants for every base constant that gets constant
// folded with the offset.
if (Idx == 0)
return 2 * TTI::TCC_Basic;
return TTI::TCC_Free;
case Instruction::Store:
ImmIdx = 0;
break;
case Instruction::ICmp:
// This is an imperfect hack to prevent constant hoisting of
// compares that might be trying to check if a 64-bit value fits in
// 32-bits. The backend can optimize these cases using a right shift by 32.
// Ideally we would check the compare predicate here. There also other
// similar immediates the backend can use shifts for.
if (Idx == 1 && Imm.getBitWidth() == 64) {
uint64_t ImmVal = Imm.getZExtValue();
if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
return TTI::TCC_Free;
}
ImmIdx = 1;
break;
case Instruction::And:
// We support 64-bit ANDs with immediates with 32-bits of leading zeroes
// by using a 32-bit operation with implicit zero extension. Detect such
// immediates here as the normal path expects bit 31 to be sign extended.
if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
return TTI::TCC_Free;
// Fallthrough
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::Or:
case Instruction::Xor:
ImmIdx = 1;
break;
// Always return TCC_Free for the shift value of a shift instruction.
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
if (Idx == 1)
return TTI::TCC_Free;
break;
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::IntToPtr:
case Instruction::PtrToInt:
case Instruction::BitCast:
case Instruction::PHI:
case Instruction::Call:
case Instruction::Select:
case Instruction::Ret:
case Instruction::Load:
break;
}
if (Idx == ImmIdx) {
int NumConstants = (BitSize + 63) / 64;
int Cost = X86TTIImpl::getIntImmCost(Imm, Ty);
return (Cost <= NumConstants * TTI::TCC_Basic)
? static_cast<int>(TTI::TCC_Free)
: Cost;
}
return X86TTIImpl::getIntImmCost(Imm, Ty);
}
int X86TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
Type *Ty) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
// There is no cost model for constants with a bit size of 0. Return TCC_Free
// here, so that constant hoisting will ignore this constant.
if (BitSize == 0)
return TTI::TCC_Free;
switch (IID) {
default:
return TTI::TCC_Free;
case Intrinsic::sadd_with_overflow:
case Intrinsic::uadd_with_overflow:
case Intrinsic::ssub_with_overflow:
case Intrinsic::usub_with_overflow:
case Intrinsic::smul_with_overflow:
case Intrinsic::umul_with_overflow:
if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
return TTI::TCC_Free;
break;
case Intrinsic::experimental_stackmap:
if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
return TTI::TCC_Free;
break;
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint_i64:
if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
return TTI::TCC_Free;
break;
}
return X86TTIImpl::getIntImmCost(Imm, Ty);
}
// Return an average cost of Gather / Scatter instruction, maybe improved later
int X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy, Value *Ptr,
unsigned Alignment, unsigned AddressSpace) {
assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
unsigned VF = SrcVTy->getVectorNumElements();
// Try to reduce index size from 64 bit (default for GEP)
// to 32. It is essential for VF 16. If the index can't be reduced to 32, the
// operation will use 16 x 64 indices which do not fit in a zmm and needs
// to split. Also check that the base pointer is the same for all lanes,
// and that there's at most one variable index.
auto getIndexSizeInBits = [](Value *Ptr, const DataLayout& DL) {
unsigned IndexSize = DL.getPointerSizeInBits();
GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
if (IndexSize < 64 || !GEP)
return IndexSize;
unsigned NumOfVarIndices = 0;
Value *Ptrs = GEP->getPointerOperand();
if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
return IndexSize;
for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
if (isa<Constant>(GEP->getOperand(i)))
continue;
Type *IndxTy = GEP->getOperand(i)->getType();
if (IndxTy->isVectorTy())
IndxTy = IndxTy->getVectorElementType();
if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
!isa<SExtInst>(GEP->getOperand(i))) ||
++NumOfVarIndices > 1)
return IndexSize; // 64
}
return (unsigned)32;
};
// Trying to reduce IndexSize to 32 bits for vector 16.
// By default the IndexSize is equal to pointer size.
unsigned IndexSize = (VF >= 16) ? getIndexSizeInBits(Ptr, DL) :
DL.getPointerSizeInBits();
Type *IndexVTy = VectorType::get(IntegerType::get(SrcVTy->getContext(),
IndexSize), VF);
std::pair<int, MVT> IdxsLT = TLI->getTypeLegalizationCost(DL, IndexVTy);
std::pair<int, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, SrcVTy);
int SplitFactor = std::max(IdxsLT.first, SrcLT.first);
if (SplitFactor > 1) {
// Handle splitting of vector of pointers
Type *SplitSrcTy = VectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
AddressSpace);
}
// The gather / scatter cost is given by Intel architects. It is a rough
// number since we are looking at one instruction in a time.
const int GSOverhead = 2;
return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
Alignment, AddressSpace);
}
/// Return the cost of full scalarization of gather / scatter operation.
///
/// Opcode - Load or Store instruction.
/// SrcVTy - The type of the data vector that should be gathered or scattered.
/// VariableMask - The mask is non-constant at compile time.
/// Alignment - Alignment for one element.
/// AddressSpace - pointer[s] address space.
///
int X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
bool VariableMask, unsigned Alignment,
unsigned AddressSpace) {
unsigned VF = SrcVTy->getVectorNumElements();
int MaskUnpackCost = 0;
if (VariableMask) {
VectorType *MaskTy =
VectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
MaskUnpackCost = getScalarizationOverhead(MaskTy, false, true);
int ScalarCompareCost =
getCmpSelInstrCost(Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()),
nullptr);
int BranchCost = getCFInstrCost(Instruction::Br);
MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
}
// The cost of the scalar loads/stores.
int MemoryOpCost = VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
Alignment, AddressSpace);
int InsertExtractCost = 0;
if (Opcode == Instruction::Load)
for (unsigned i = 0; i < VF; ++i)
// Add the cost of inserting each scalar load into the vector
InsertExtractCost +=
getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
else
for (unsigned i = 0; i < VF; ++i)
// Add the cost of extracting each element out of the data vector
InsertExtractCost +=
getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
}
/// Calculate the cost of Gather / Scatter operation
int X86TTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *SrcVTy,
Value *Ptr, bool VariableMask,
unsigned Alignment) {
assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
unsigned VF = SrcVTy->getVectorNumElements();
PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
if (!PtrTy && Ptr->getType()->isVectorTy())
PtrTy = dyn_cast<PointerType>(Ptr->getType()->getVectorElementType());
assert(PtrTy && "Unexpected type for Ptr argument");
unsigned AddressSpace = PtrTy->getAddressSpace();
bool Scalarize = false;
if ((Opcode == Instruction::Load && !isLegalMaskedGather(SrcVTy)) ||
(Opcode == Instruction::Store && !isLegalMaskedScatter(SrcVTy)))
Scalarize = true;
// Gather / Scatter for vector 2 is not profitable on KNL / SKX
// Vector-4 of gather/scatter instruction does not exist on KNL.
// We can extend it to 8 elements, but zeroing upper bits of
// the mask vector will add more instructions. Right now we give the scalar
// cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter instruction is
// better in the VariableMask case.
if (VF == 2 || (VF == 4 && !ST->hasVLX()))
Scalarize = true;
if (Scalarize)
return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment, AddressSpace);
return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
}
bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy) {
Type *ScalarTy = DataTy->getScalarType();
int DataWidth = isa<PointerType>(ScalarTy) ?
DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
return (DataWidth >= 32 && ST->hasAVX()) ||
(DataWidth >= 8 && ST->hasBWI());
}
bool X86TTIImpl::isLegalMaskedStore(Type *DataType) {
return isLegalMaskedLoad(DataType);
}
bool X86TTIImpl::isLegalMaskedGather(Type *DataTy) {
// This function is called now in two cases: from the Loop Vectorizer
// and from the Scalarizer.
// When the Loop Vectorizer asks about legality of the feature,
// the vectorization factor is not calculated yet. The Loop Vectorizer
// sends a scalar type and the decision is based on the width of the
// scalar element.
// Later on, the cost model will estimate usage this intrinsic based on
// the vector type.
// The Scalarizer asks again about legality. It sends a vector type.
// In this case we can reject non-power-of-2 vectors.
if (isa<VectorType>(DataTy) && !isPowerOf2_32(DataTy->getVectorNumElements()))
return false;
Type *ScalarTy = DataTy->getScalarType();
int DataWidth = isa<PointerType>(ScalarTy) ?
DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
// AVX-512 allows gather and scatter
return DataWidth >= 32 && ST->hasAVX512();
}
bool X86TTIImpl::isLegalMaskedScatter(Type *DataType) {
return isLegalMaskedGather(DataType);
}
bool X86TTIImpl::areInlineCompatible(const Function *Caller,
const Function *Callee) const {
const TargetMachine &TM = getTLI()->getTargetMachine();
// Work this as a subsetting of subtarget features.
const FeatureBitset &CallerBits =
TM.getSubtargetImpl(*Caller)->getFeatureBits();
const FeatureBitset &CalleeBits =
TM.getSubtargetImpl(*Callee)->getFeatureBits();
// FIXME: This is likely too limiting as it will include subtarget features
// that we might not care about for inlining, but it is conservatively
// correct.
return (CallerBits & CalleeBits) == CalleeBits;
}
| [
"sebi@quantstamp.com"
] | sebi@quantstamp.com |
7c38f28c6662f1deaf263612ee645431c53a8341 | 1919e6986186fdb0b34d757188ee9c0b104ca4a1 | /src/firmware/ResetButton.cpp | ba8e16b5585a5f8dd40a0c110cbed14c971804ed | [] | no_license | sokolov19830711/ONREMOTE | 8de1d5c7cab755b6fd4571e7e36bb59e4c67412c | 20ce453433f53eaf2e299637e96107d8567bc0b2 | refs/heads/master | 2023-03-24T23:38:30.644198 | 2021-03-28T08:43:38 | 2021-03-28T08:43:38 | 310,211,722 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | cpp | #include "ResetButton.h"
#include "PcReset.h"
#include "TricolorLED.h"
#include "Beeper.h"
void ResetButton::process()
{
if (getInstance().isValueChanged() && getInstance().getCurrentValue() != getInstance().getIdleValue())
{
PcReset::on();
}
getInstance().resetValueChanged();
}
| [
"sokolov19830711@gmail.com"
] | sokolov19830711@gmail.com |
5badd9ceaa299ec755f8cc497fd0bc893a409989 | 94dcc118f9492896d6781e5a3f59867eddfbc78a | /llvm/tools/clang/lib/Format/FormatToken.h | d80bd0af5f006363152eee5c63b27910f9abfafd | [
"Apache-2.0",
"NCSA"
] | permissive | vusec/safeinit | 43fd500b5a832cce2bd87696988b64a718a5d764 | 8425bc49497684fe16e0063190dec8c3c58dc81a | refs/heads/master | 2021-07-07T11:46:25.138899 | 2021-05-05T10:40:52 | 2021-05-05T10:40:52 | 76,794,423 | 22 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 20,766 | h | //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the declaration of the FormatToken, a wrapper
/// around Token with additional information related to formatting.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include <memory>
namespace clang {
namespace format {
#define LIST_TOKEN_TYPES \
TYPE(ArrayInitializerLSquare) \
TYPE(ArraySubscriptLSquare) \
TYPE(AttributeParen) \
TYPE(BinaryOperator) \
TYPE(BitFieldColon) \
TYPE(BlockComment) \
TYPE(CastRParen) \
TYPE(ConditionalExpr) \
TYPE(ConflictAlternative) \
TYPE(ConflictEnd) \
TYPE(ConflictStart) \
TYPE(CtorInitializerColon) \
TYPE(CtorInitializerComma) \
TYPE(DesignatedInitializerPeriod) \
TYPE(DictLiteral) \
TYPE(ForEachMacro) \
TYPE(FunctionAnnotationRParen) \
TYPE(FunctionDeclarationName) \
TYPE(FunctionLBrace) \
TYPE(FunctionTypeLParen) \
TYPE(ImplicitStringLiteral) \
TYPE(InheritanceColon) \
TYPE(InlineASMBrace) \
TYPE(InlineASMColon) \
TYPE(JavaAnnotation) \
TYPE(JsComputedPropertyName) \
TYPE(JsFatArrow) \
TYPE(JsTypeColon) \
TYPE(JsTypeOperator) \
TYPE(JsTypeOptionalQuestion) \
TYPE(LambdaArrow) \
TYPE(LambdaLSquare) \
TYPE(LeadingJavaAnnotation) \
TYPE(LineComment) \
TYPE(MacroBlockBegin) \
TYPE(MacroBlockEnd) \
TYPE(ObjCBlockLBrace) \
TYPE(ObjCBlockLParen) \
TYPE(ObjCDecl) \
TYPE(ObjCForIn) \
TYPE(ObjCMethodExpr) \
TYPE(ObjCMethodSpecifier) \
TYPE(ObjCProperty) \
TYPE(ObjCStringLiteral) \
TYPE(OverloadedOperator) \
TYPE(OverloadedOperatorLParen) \
TYPE(PointerOrReference) \
TYPE(PureVirtualSpecifier) \
TYPE(RangeBasedForLoopColon) \
TYPE(RegexLiteral) \
TYPE(SelectorName) \
TYPE(StartOfName) \
TYPE(TemplateCloser) \
TYPE(TemplateOpener) \
TYPE(TemplateString) \
TYPE(TrailingAnnotation) \
TYPE(TrailingReturnArrow) \
TYPE(TrailingUnaryOperator) \
TYPE(UnaryOperator) \
TYPE(Unknown)
enum TokenType {
#define TYPE(X) TT_##X,
LIST_TOKEN_TYPES
#undef TYPE
NUM_TOKEN_TYPES
};
/// \brief Determines the name of a token type.
const char *getTokenTypeName(TokenType Type);
// Represents what type of block a set of braces open.
enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
// The packing kind of a function's parameters.
enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
class TokenRole;
class AnnotatedLine;
/// \brief A wrapper around a \c Token storing information about the
/// whitespace characters preceding it.
struct FormatToken {
FormatToken() {}
/// \brief The \c Token.
Token Tok;
/// \brief The number of newlines immediately before the \c Token.
///
/// This can be used to determine what the user wrote in the original code
/// and thereby e.g. leave an empty line between two function definitions.
unsigned NewlinesBefore = 0;
/// \brief Whether there is at least one unescaped newline before the \c
/// Token.
bool HasUnescapedNewline = false;
/// \brief The range of the whitespace immediately preceding the \c Token.
SourceRange WhitespaceRange;
/// \brief The offset just past the last '\n' in this token's leading
/// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
unsigned LastNewlineOffset = 0;
/// \brief The width of the non-whitespace parts of the token (or its first
/// line for multi-line tokens) in columns.
/// We need this to correctly measure number of columns a token spans.
unsigned ColumnWidth = 0;
/// \brief Contains the width in columns of the last line of a multi-line
/// token.
unsigned LastLineColumnWidth = 0;
/// \brief Whether the token text contains newlines (escaped or not).
bool IsMultiline = false;
/// \brief Indicates that this is the first token.
bool IsFirst = false;
/// \brief Whether there must be a line break before this token.
///
/// This happens for example when a preprocessor directive ended directly
/// before the token.
bool MustBreakBefore = false;
/// \brief The raw text of the token.
///
/// Contains the raw token text without leading whitespace and without leading
/// escaped newlines.
StringRef TokenText;
/// \brief Set to \c true if this token is an unterminated literal.
bool IsUnterminatedLiteral = 0;
/// \brief Contains the kind of block if this token is a brace.
BraceBlockKind BlockKind = BK_Unknown;
TokenType Type = TT_Unknown;
/// \brief The number of spaces that should be inserted before this token.
unsigned SpacesRequiredBefore = 0;
/// \brief \c true if it is allowed to break before this token.
bool CanBreakBefore = false;
/// \brief \c true if this is the ">" of "template<..>".
bool ClosesTemplateDeclaration = false;
/// \brief Number of parameters, if this is "(", "[" or "<".
///
/// This is initialized to 1 as we don't need to distinguish functions with
/// 0 parameters from functions with 1 parameter. Thus, we can simply count
/// the number of commas.
unsigned ParameterCount = 0;
/// \brief Number of parameters that are nested blocks,
/// if this is "(", "[" or "<".
unsigned BlockParameterCount = 0;
/// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
/// the surrounding bracket.
tok::TokenKind ParentBracket = tok::unknown;
/// \brief A token can have a special role that can carry extra information
/// about the token's formatting.
std::unique_ptr<TokenRole> Role;
/// \brief If this is an opening parenthesis, how are the parameters packed?
ParameterPackingKind PackingKind = PPK_Inconclusive;
/// \brief The total length of the unwrapped line up to and including this
/// token.
unsigned TotalLength = 0;
/// \brief The original 0-based column of this token, including expanded tabs.
/// The configured TabWidth is used as tab width.
unsigned OriginalColumn = 0;
/// \brief The length of following tokens until the next natural split point,
/// or the next token that can be broken.
unsigned UnbreakableTailLength = 0;
// FIXME: Come up with a 'cleaner' concept.
/// \brief The binding strength of a token. This is a combined value of
/// operator precedence, parenthesis nesting, etc.
unsigned BindingStrength = 0;
/// \brief The nesting level of this token, i.e. the number of surrounding (),
/// [], {} or <>.
unsigned NestingLevel = 0;
/// \brief Penalty for inserting a line break before this token.
unsigned SplitPenalty = 0;
/// \brief If this is the first ObjC selector name in an ObjC method
/// definition or call, this contains the length of the longest name.
///
/// This being set to 0 means that the selectors should not be colon-aligned,
/// e.g. because several of them are block-type.
unsigned LongestObjCSelectorName = 0;
/// \brief Stores the number of required fake parentheses and the
/// corresponding operator precedence.
///
/// If multiple fake parentheses start at a token, this vector stores them in
/// reverse order, i.e. inner fake parenthesis first.
SmallVector<prec::Level, 4> FakeLParens;
/// \brief Insert this many fake ) after this token for correct indentation.
unsigned FakeRParens = 0;
/// \brief \c true if this token starts a binary expression, i.e. has at least
/// one fake l_paren with a precedence greater than prec::Unknown.
bool StartsBinaryExpression = false;
/// \brief \c true if this token ends a binary expression.
bool EndsBinaryExpression = false;
/// \brief Is this is an operator (or "."/"->") in a sequence of operators
/// with the same precedence, contains the 0-based operator index.
unsigned OperatorIndex = 0;
/// \brief If this is an operator (or "."/"->") in a sequence of operators
/// with the same precedence, points to the next operator.
FormatToken *NextOperator = nullptr;
/// \brief Is this token part of a \c DeclStmt defining multiple variables?
///
/// Only set if \c Type == \c TT_StartOfName.
bool PartOfMultiVariableDeclStmt = false;
/// \brief If this is a bracket, this points to the matching one.
FormatToken *MatchingParen = nullptr;
/// \brief The previous token in the unwrapped line.
FormatToken *Previous = nullptr;
/// \brief The next token in the unwrapped line.
FormatToken *Next = nullptr;
/// \brief If this token starts a block, this contains all the unwrapped lines
/// in it.
SmallVector<AnnotatedLine *, 1> Children;
/// \brief Stores the formatting decision for the token once it was made.
FormatDecision Decision = FD_Unformatted;
/// \brief If \c true, this token has been fully formatted (indented and
/// potentially re-formatted inside), and we do not allow further formatting
/// changes.
bool Finalized = false;
bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
bool is(TokenType TT) const { return Type == TT; }
bool is(const IdentifierInfo *II) const {
return II && II == Tok.getIdentifierInfo();
}
bool is(tok::PPKeywordKind Kind) const {
return Tok.getIdentifierInfo() &&
Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
}
template <typename A, typename B> bool isOneOf(A K1, B K2) const {
return is(K1) || is(K2);
}
template <typename A, typename B, typename... Ts>
bool isOneOf(A K1, B K2, Ts... Ks) const {
return is(K1) || isOneOf(K2, Ks...);
}
template <typename T> bool isNot(T Kind) const { return !is(Kind); }
bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
return Tok.isObjCAtKeyword(Kind);
}
bool isAccessSpecifier(bool ColonRequired = true) const {
return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
(!ColonRequired || (Next && Next->is(tok::colon)));
}
/// \brief Determine whether the token is a simple-type-specifier.
bool isSimpleTypeSpecifier() const;
bool isObjCAccessSpecifier() const {
return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
Next->isObjCAtKeyword(tok::objc_protected) ||
Next->isObjCAtKeyword(tok::objc_package) ||
Next->isObjCAtKeyword(tok::objc_private));
}
/// \brief Returns whether \p Tok is ([{ or a template opening <.
bool opensScope() const {
return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
TT_TemplateOpener);
}
/// \brief Returns whether \p Tok is )]} or a template closing >.
bool closesScope() const {
return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
TT_TemplateCloser);
}
/// \brief Returns \c true if this is a "." or "->" accessing a member.
bool isMemberAccess() const {
return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
!isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
TT_LambdaArrow);
}
bool isUnaryOperator() const {
switch (Tok.getKind()) {
case tok::plus:
case tok::plusplus:
case tok::minus:
case tok::minusminus:
case tok::exclaim:
case tok::tilde:
case tok::kw_sizeof:
case tok::kw_alignof:
return true;
default:
return false;
}
}
bool isBinaryOperator() const {
// Comma is a binary operator, but does not behave as such wrt. formatting.
return getPrecedence() > prec::Comma;
}
bool isTrailingComment() const {
return is(tok::comment) &&
(is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
}
/// \brief Returns \c true if this is a keyword that can be used
/// like a function call (e.g. sizeof, typeid, ...).
bool isFunctionLikeKeyword() const {
switch (Tok.getKind()) {
case tok::kw_throw:
case tok::kw_typeid:
case tok::kw_return:
case tok::kw_sizeof:
case tok::kw_alignof:
case tok::kw_alignas:
case tok::kw_decltype:
case tok::kw_noexcept:
case tok::kw_static_assert:
case tok::kw___attribute:
return true;
default:
return false;
}
}
/// \brief Returns actual token start location without leading escaped
/// newlines and whitespace.
///
/// This can be different to Tok.getLocation(), which includes leading escaped
/// newlines.
SourceLocation getStartOfNonWhitespace() const {
return WhitespaceRange.getEnd();
}
prec::Level getPrecedence() const {
return getBinOpPrecedence(Tok.getKind(), true, true);
}
/// \brief Returns the previous token ignoring comments.
FormatToken *getPreviousNonComment() const {
FormatToken *Tok = Previous;
while (Tok && Tok->is(tok::comment))
Tok = Tok->Previous;
return Tok;
}
/// \brief Returns the next token ignoring comments.
const FormatToken *getNextNonComment() const {
const FormatToken *Tok = Next;
while (Tok && Tok->is(tok::comment))
Tok = Tok->Next;
return Tok;
}
/// \brief Returns \c true if this tokens starts a block-type list, i.e. a
/// list that should be indented with a block indent.
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
return is(TT_ArrayInitializerLSquare) ||
(is(tok::l_brace) &&
(BlockKind == BK_Block || is(TT_DictLiteral) ||
(!Style.Cpp11BracedListStyle && NestingLevel == 0)));
}
/// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
}
private:
// Disallow copying.
FormatToken(const FormatToken &) = delete;
void operator=(const FormatToken &) = delete;
};
class ContinuationIndenter;
struct LineState;
class TokenRole {
public:
TokenRole(const FormatStyle &Style) : Style(Style) {}
virtual ~TokenRole();
/// \brief After the \c TokenAnnotator has finished annotating all the tokens,
/// this function precomputes required information for formatting.
virtual void precomputeFormattingInfos(const FormatToken *Token);
/// \brief Apply the special formatting that the given role demands.
///
/// Assumes that the token having this role is already formatted.
///
/// Continues formatting from \p State leaving indentation to \p Indenter and
/// returns the total penalty that this formatting incurs.
virtual unsigned formatFromToken(LineState &State,
ContinuationIndenter *Indenter,
bool DryRun) {
return 0;
}
/// \brief Same as \c formatFromToken, but assumes that the first token has
/// already been set thereby deciding on the first line break.
virtual unsigned formatAfterToken(LineState &State,
ContinuationIndenter *Indenter,
bool DryRun) {
return 0;
}
/// \brief Notifies the \c Role that a comma was found.
virtual void CommaFound(const FormatToken *Token) {}
protected:
const FormatStyle &Style;
};
class CommaSeparatedList : public TokenRole {
public:
CommaSeparatedList(const FormatStyle &Style)
: TokenRole(Style), HasNestedBracedList(false) {}
void precomputeFormattingInfos(const FormatToken *Token) override;
unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
bool DryRun) override;
unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
bool DryRun) override;
/// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
void CommaFound(const FormatToken *Token) override {
Commas.push_back(Token);
}
private:
/// \brief A struct that holds information on how to format a given list with
/// a specific number of columns.
struct ColumnFormat {
/// \brief The number of columns to use.
unsigned Columns;
/// \brief The total width in characters.
unsigned TotalWidth;
/// \brief The number of lines required for this format.
unsigned LineCount;
/// \brief The size of each column in characters.
SmallVector<unsigned, 8> ColumnSizes;
};
/// \brief Calculate which \c ColumnFormat fits best into
/// \p RemainingCharacters.
const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
/// \brief The ordered \c FormatTokens making up the commas of this list.
SmallVector<const FormatToken *, 8> Commas;
/// \brief The length of each of the list's items in characters including the
/// trailing comma.
SmallVector<unsigned, 8> ItemLengths;
/// \brief Precomputed formats that can be used for this list.
SmallVector<ColumnFormat, 4> Formats;
bool HasNestedBracedList;
};
/// \brief Encapsulates keywords that are context sensitive or for languages not
/// properly supported by Clang's lexer.
struct AdditionalKeywords {
AdditionalKeywords(IdentifierTable &IdentTable) {
kw_final = &IdentTable.get("final");
kw_override = &IdentTable.get("override");
kw_in = &IdentTable.get("in");
kw_of = &IdentTable.get("of");
kw_CF_ENUM = &IdentTable.get("CF_ENUM");
kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
kw_NS_ENUM = &IdentTable.get("NS_ENUM");
kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
kw_async = &IdentTable.get("async");
kw_await = &IdentTable.get("await");
kw_finally = &IdentTable.get("finally");
kw_from = &IdentTable.get("from");
kw_function = &IdentTable.get("function");
kw_import = &IdentTable.get("import");
kw_is = &IdentTable.get("is");
kw_let = &IdentTable.get("let");
kw_var = &IdentTable.get("var");
kw_yield = &IdentTable.get("yield");
kw_abstract = &IdentTable.get("abstract");
kw_assert = &IdentTable.get("assert");
kw_extends = &IdentTable.get("extends");
kw_implements = &IdentTable.get("implements");
kw_instanceof = &IdentTable.get("instanceof");
kw_interface = &IdentTable.get("interface");
kw_native = &IdentTable.get("native");
kw_package = &IdentTable.get("package");
kw_synchronized = &IdentTable.get("synchronized");
kw_throws = &IdentTable.get("throws");
kw___except = &IdentTable.get("__except");
kw_mark = &IdentTable.get("mark");
kw_extend = &IdentTable.get("extend");
kw_option = &IdentTable.get("option");
kw_optional = &IdentTable.get("optional");
kw_repeated = &IdentTable.get("repeated");
kw_required = &IdentTable.get("required");
kw_returns = &IdentTable.get("returns");
kw_signals = &IdentTable.get("signals");
kw_qsignals = &IdentTable.get("Q_SIGNALS");
kw_slots = &IdentTable.get("slots");
kw_qslots = &IdentTable.get("Q_SLOTS");
}
// Context sensitive keywords.
IdentifierInfo *kw_final;
IdentifierInfo *kw_override;
IdentifierInfo *kw_in;
IdentifierInfo *kw_of;
IdentifierInfo *kw_CF_ENUM;
IdentifierInfo *kw_CF_OPTIONS;
IdentifierInfo *kw_NS_ENUM;
IdentifierInfo *kw_NS_OPTIONS;
IdentifierInfo *kw___except;
// JavaScript keywords.
IdentifierInfo *kw_async;
IdentifierInfo *kw_await;
IdentifierInfo *kw_finally;
IdentifierInfo *kw_from;
IdentifierInfo *kw_function;
IdentifierInfo *kw_import;
IdentifierInfo *kw_is;
IdentifierInfo *kw_let;
IdentifierInfo *kw_var;
IdentifierInfo *kw_yield;
// Java keywords.
IdentifierInfo *kw_abstract;
IdentifierInfo *kw_assert;
IdentifierInfo *kw_extends;
IdentifierInfo *kw_implements;
IdentifierInfo *kw_instanceof;
IdentifierInfo *kw_interface;
IdentifierInfo *kw_native;
IdentifierInfo *kw_package;
IdentifierInfo *kw_synchronized;
IdentifierInfo *kw_throws;
// Pragma keywords.
IdentifierInfo *kw_mark;
// Proto keywords.
IdentifierInfo *kw_extend;
IdentifierInfo *kw_option;
IdentifierInfo *kw_optional;
IdentifierInfo *kw_repeated;
IdentifierInfo *kw_required;
IdentifierInfo *kw_returns;
// QT keywords.
IdentifierInfo *kw_signals;
IdentifierInfo *kw_qsignals;
IdentifierInfo *kw_slots;
IdentifierInfo *kw_qslots;
};
} // namespace format
} // namespace clang
#endif
| [
"amilburn@zall.org"
] | amilburn@zall.org |
adb850cf067d0f4fd8861e088824a4f3d73c1700 | 6d162c19c9f1dc1d03f330cad63d0dcde1df082d | /qrenderdoc/3rdparty/scintilla/src/XPM.h | 631fe138659fe9ba5d3be0fd735d89f03b7de899 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-scintilla"
] | permissive | baldurk/renderdoc | 24efbb84446a9d443bb9350013f3bfab9e9c5923 | a214ffcaf38bf5319b2b23d3d014cf3772cda3c6 | refs/heads/v1.x | 2023-08-16T21:20:43.886587 | 2023-07-28T22:34:10 | 2023-08-15T09:09:40 | 17,253,131 | 7,729 | 1,358 | MIT | 2023-09-13T09:36:53 | 2014-02-27T15:16:30 | C++ | UTF-8 | C++ | false | false | 2,660 | h | // Scintilla source code edit control
/** @file XPM.h
** Define a classes to hold image data in the X Pixmap (XPM) and RGBA formats.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef XPM_H
#define XPM_H
#ifdef SCI_NAMESPACE
namespace Scintilla {
#endif
/**
* Hold a pixmap in XPM format.
*/
class XPM {
int height;
int width;
int nColours;
std::vector<unsigned char> pixels;
ColourDesired colourCodeTable[256];
char codeTransparent;
ColourDesired ColourFromCode(int ch) const;
void FillRun(Surface *surface, int code, int startX, int y, int x);
public:
explicit XPM(const char *textForm);
explicit XPM(const char *const *linesForm);
~XPM();
void Init(const char *textForm);
void Init(const char *const *linesForm);
/// Decompose image into runs and use FillRectangle for each run
void Draw(Surface *surface, PRectangle &rc);
int GetHeight() const { return height; }
int GetWidth() const { return width; }
void PixelAt(int x, int y, ColourDesired &colour, bool &transparent) const;
private:
static std::vector<const char *>LinesFormFromTextForm(const char *textForm);
};
/**
* A translucent image stored as a sequence of RGBA bytes.
*/
class RGBAImage {
// Private so RGBAImage objects can not be copied
RGBAImage(const RGBAImage &);
RGBAImage &operator=(const RGBAImage &);
int height;
int width;
float scale;
std::vector<unsigned char> pixelBytes;
public:
RGBAImage(int width_, int height_, float scale_, const unsigned char *pixels_);
explicit RGBAImage(const XPM &xpm);
virtual ~RGBAImage();
int GetHeight() const { return height; }
int GetWidth() const { return width; }
float GetScale() const { return scale; }
float GetScaledHeight() const { return height / scale; }
float GetScaledWidth() const { return width / scale; }
int CountBytes() const;
const unsigned char *Pixels() const;
void SetPixel(int x, int y, ColourDesired colour, int alpha=0xff);
};
/**
* A collection of RGBAImage pixmaps indexed by integer id.
*/
class RGBAImageSet {
typedef std::map<int, RGBAImage*> ImageMap;
ImageMap images;
mutable int height; ///< Memorize largest height of the set.
mutable int width; ///< Memorize largest width of the set.
public:
RGBAImageSet();
~RGBAImageSet();
/// Remove all images.
void Clear();
/// Add an image.
void Add(int ident, RGBAImage *image);
/// Get image by id.
RGBAImage *Get(int ident);
/// Give the largest height of the set.
int GetHeight() const;
/// Give the largest width of the set.
int GetWidth() const;
};
#ifdef SCI_NAMESPACE
}
#endif
#endif
| [
"baldurk@baldurk.org"
] | baldurk@baldurk.org |
856b3182da13295d61ae32da607d8c2e7d52e8cb | 92627592590948d9432f12f6ffdca482f2012f02 | /例3-17系统函数.cpp | 2e61c0ce14dd8134947218b1e28bfb645de6e17c | [] | no_license | Yorkzhang19961122/CPP_Examples_Tsinghua | 2f8b35d98d444f54a04a54b38be09dc52fe4b2a2 | 51977bc89dcc9ad90887db45846649b87398f489 | refs/heads/main | 2022-12-31T18:58:43.342432 | 2020-10-19T10:42:30 | 2020-10-19T10:42:30 | 305,277,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | // 例3-17系统函数.cpp :
//
#include <iostream>
#include<cmath>
using namespace std;
const double PI = 3.1415926;
int main(){
double angle;
cout << "Please input an angle:";
cin >> angle; // 输入角度值
double radian = angle * PI / 180; //转为弧度值
cout << "sin(" << angle << ")=" << sin(radian) << endl;
cout << "cos(" << angle << ")=" << cos(radian) << endl;
cout << "tan(" << angle << ")=" << tan(radian) << endl;
return 0;
}
| [
"zyk961122@gmail.com"
] | zyk961122@gmail.com |
64649d2fccf68bca7df154777b214a607bef36de | 1ab99d93f7c64bc55559adfabb9c3d270d4692a0 | /dz5/VVectorDef.hpp | 2bcfeab018a89c338bc709938c1c3d2bf416b3d3 | [] | no_license | vadymtolkachev/track-cpp | 9bf74188ae02173aa2b1f033bccb42da8786f793 | 6ce9e932f77e6088e2907dfef926ec42094be77f | refs/heads/master | 2021-10-28T03:44:14.199644 | 2019-04-21T16:17:29 | 2019-04-21T16:17:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,906 | hpp | #pragma once
#include <stdexcept>
template <typename DataType>
VVector<DataType>::VVector() noexcept:
m_size(0),
m_capacity(0),
m_data(nullptr)
{}
template <typename DataType>
VVector<DataType>::VVector(const VVector &vec):
m_size(vec.m_size),
m_capacity(vec.m_capacity),
m_data(new DataType[m_capacity])
{
for(unsigned i = 0; i < m_size; ++i)
m_data[i] = vec.m_data[i];
}
template <typename DataType>
VVector<DataType>::VVector(VVector &&vec) noexcept:
m_size(vec.m_size),
m_capacity(vec.m_capacity),
m_data(vec.m_data)
{
vec.m_data = nullptr;
}
template <typename DataType>
VVector<DataType>::~VVector() noexcept
{
clear();
}
template <typename DataType>
unsigned VVector<DataType>::getSize() const noexcept
{
return m_size;
}
template <typename DataType>
bool VVector<DataType>::isEmpty() const noexcept
{
return m_size == 0;
}
template <typename DataType>
DataType &VVector<DataType>::at(const unsigned index)
{
if(index > m_size)
throw std::runtime_error("Index overflow");
return m_data[index];
}
template <typename DataType>
const DataType &VVector<DataType>::at(const unsigned index) const
{
if(index > m_size)
throw std::runtime_error("Index overflow");
return m_data[index];
}
template <typename DataType>
DataType &VVector<DataType>::operator[](const unsigned index) noexcept
{
return m_data[index];
}
template <typename DataType>
const DataType &VVector<DataType>::operator[](const unsigned index) const noexcept
{
return m_data[index];
}
template <typename DataType>
VVector<DataType> &VVector<DataType>::operator=(const VVector &vec) noexcept
{
this->~VVector();
new(this) VVector(vec);
return *this;
}
template <typename DataType>
VVector<DataType> &VVector<DataType>::operator=(VVector &&vec) noexcept
{
swap(vec);
return *this;
}
template <typename DataType>
void VVector<DataType>::swap(VVector &vec) noexcept
{
std::swap(m_size, vec.m_size);
std::swap(m_capacity, vec.m_capacity);
std::swap(m_data, vec.m_data);
}
template <typename DataType>
void VVector<DataType>::push(const DataType &data)
{
if(!m_capacity)
{
m_data = new DataType[VECTOR_SIZE];
m_capacity = VECTOR_SIZE;
}
else if(m_capacity == m_size)
{
DataType *tmp = new DataType[2*m_capacity];
for(unsigned i = 0; i < m_size; ++i)
tmp[i] = m_data[i];
delete[] m_data;
m_data = tmp;
m_capacity *= 2;
}
m_data[m_size++] = data;
}
template <typename DataType>
void VVector<DataType>::pop()
{
if(!m_size)
throw std::runtime_error("Pop: underflow");
if(m_capacity == 4*m_size)
{
DataType *tmp = new DataType[2*m_size]();
m_capacity = 2*m_size;
m_size--;
for(unsigned i = 0; i < m_size; ++i)
tmp[i] = m_data[i];
delete[] m_data;
m_data = tmp;
}
else
{
m_size--;
}
}
template <typename DataType>
void VVector<DataType>::clear() noexcept
{
delete[] m_data;
m_data = nullptr;
m_size = 0;
m_capacity = 0;
} | [
"vadtolkachev@gmail.com"
] | vadtolkachev@gmail.com |
083f2756b8f6d111530a48a63a0b1f5cd4aeb2df | e40c23af4daf5813af3dc24fc87665d1d832fdb0 | /src/qt/bitcoingui.cpp | 37769f8e0abc9d74f770c70480da3089943c2982 | [
"MIT"
] | permissive | numbercoin/numbercoin1.0.0.2 | 959993793c9105cf897744771b7c4675ecff183f | 9b8ca9eaaac17c34bb66b3d365a2bbf6893dc406 | refs/heads/master | 2021-01-01T17:05:38.109390 | 2014-06-26T07:37:30 | 2014-06-26T07:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,086 | cpp | /*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QFileDialog>
#include <QDesktopServices>
#include <QTimer>
#include <QDragEnterEvent>
#include <QUrl>
#include <QStyle>
#include <iostream>
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0)
{
resize(850, 550);
setWindowTitle(tr("NumberCoin") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create the tray icon (or setup the dock icon)
createTrayIcon();
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
signVerifyMessageDialog = new SignVerifyMessageDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = qApp->style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
// this->setStyleSheet("background-color: #ceffee;");
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Clicking on "Verify Message" in the address book sends you to the verify message tab
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
gotoOverviewPage();
}
BitcoinGUI::~BitcoinGUI()
{
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setToolTip(tr("Show general overview of wallet"));
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a NumberCoin address"));
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setToolTip(tr("Browse transaction history"));
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setToolTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About NumberCoin"), this);
aboutAction->setToolTip(tr("Show information about NumberCoin"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setToolTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for NumberCoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setToolTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export the data in the current tab to a file"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(exportAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
// QString ss("QMenuBar::item { background-color: #ceffee; color: black }");
// appMenuBar->setStyleSheet(ss);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
trayIcon->setToolTip(tr("NumberCoin client") + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
rpcConsole->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if(walletModel)
{
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus(walletModel->getEncryptionStatus());
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip(tr("NumberCoin client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
trayIconMenu = dockIconHandler->dockMenu();
dockIconHandler->setMainWindow((QMainWindow *)this);
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
notificator = new Notificator(qApp->applicationName(), trayIcon);
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to NumberCoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// don't show / hide progress bar and its label if we have no connection to the network
if (!clientModel || clientModel->getNumConnections() == 0)
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
return;
}
QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
QString tooltip;
if(count < nTotalBlocks)
{
int nRemainingBlocks = nTotalBlocks - count;
float nPercentageDone = count / (nTotalBlocks * 0.01f);
if (strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(tr("Synchronizing with network..."));
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
progressBar->setMaximum(nTotalBlocks);
progressBar->setValue(count);
progressBar->setVisible(true);
}
tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
}
else
{
if (strStatusBarWarnings.isEmpty())
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
}
// Override progressBarLabel text and hide progress bar, when we have warnings to display
if (!strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(strStatusBarWarnings);
progressBarLabel->setVisible(true);
progressBar->setVisible(false);
}
tooltip = tr("Current difficulty is %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
QString text;
// Represent time from last generated block in human readable text
if(secs <= 0)
{
// Fully up to date. Leave text empty.
}
else if(secs < 60)
{
text = tr("%n second(s) ago","",secs);
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
overviewPage->showOutOfSyncWarning(false);
}
else
{
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
syncIconMovie->start();
overviewPage->showOutOfSyncWarning(true);
}
if(!text.isEmpty())
{
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1.").arg(text);
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
{
// Report errors from network/worker thread
if(modal)
{
QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
} else {
notificator->notify(Notificator::Critical, title, message);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(
BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
if(!walletModel || !clientModel)
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On new transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
TransactionTableModel::ToAddress, parent)
.data(Qt::DecorationRole));
notificator->notify(Notificator::Information,
(amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
.arg(type)
.arg(address), icon);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (sendCoinsPage->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
gotoSendCoinsPage();
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid NumberCoin address or malformed URI parameters."));
}
event->acceptProposedAction();
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
showNormalIfMinimized();
gotoSendCoinsPage();
}
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid NumberCoin address or malformed URI parameters."));
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus(walletModel->getEncryptionStatus());
}
void BitcoinGUI::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if(!filename.isEmpty()) {
if(!walletModel->backupWallet(filename)) {
QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
}
}
}
void BitcoinGUI::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void BitcoinGUI::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if(walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
| [
"numbercoin@gmail.com"
] | numbercoin@gmail.com |
d5b3ef586475974d354c1a68956ca89975e5fcfc | f7a24278ac3f44b9b9c8e19440d1700d42423488 | /testsElementos/testmotor.cpp | 97136fed9438c990d549c111d60a3124110629a3 | [] | no_license | BackupTheBerlios/simple | db38c7807859d8c35db0dda667b7b383f4997d6c | 2184a5c842ae2af7f7d6ad7bc18e396c4a52eb97 | refs/heads/master | 2016-09-05T21:58:11.201603 | 2006-06-01T06:36:11 | 2006-06-01T06:36:11 | 40,069,092 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 3,563 | cpp | #include "motor.h"
#include "unit++.h"
using namespace unitpp;
using namespace std;
namespace
{
class PruebaMotor: public suite
{
void PruebaValoresMotor()
{
Voltaje* vReposo = new Voltaje (0.0);
Voltaje* vGiroCW = new Voltaje (5.0);
Voltaje* vGiroCCW= new Voltaje (-5.0);
Giro* giroReposo = new Giro ("stop");
Giro* giroCW = new Giro ("cw");
Giro* giroCCW = new Giro ("ccw");
unsigned int rpm=1200;
Motor* m=new Motor(vReposo,giroReposo,vGiroCW,giroCW,
vGiroCCW, giroCCW, rpm);
/* Comprobamos si los valores se quedan en el motor*/
Voltaje *vActual;
Giro *gActual;
vActual=(Voltaje*)m->getEntradaPorPosicion();
assert_eq ("Voltaje en reposo del motor",
vReposo->getValor(), vActual->getValor() );
gActual=(Giro*) m->getSalidaPorPosicion();
assert_eq ("Giro en reposo del motor",
giroReposo->getValor(), gActual->getValor() );
unsigned int velocidad=m->getRPM();
assert_eq ("Velocidad rpm", rpm, velocidad);
/* Probamos a cambiar las entradas*/
/* żEl motor gira en sentido cw?*/
m->setEntrada(vGiroCW);
gActual=(Giro*) m->getSalidaPorPosicion();
assert_eq ("Giro en sentido horario del motor",
giroCW->getValor(), gActual->getValor() );
/* żEl motor gira en sentido ccw?*/
m->setEntrada(vGiroCCW);
gActual=(Giro*) m->getSalidaPorPosicion();
assert_eq ("Giro en sentido anti-horario del motor",
giroCCW->getValor(), gActual->getValor() );
}
void PruebaGetters()
{
Voltaje* vReposo = new Voltaje (0.0);
Voltaje* vGiroCW = new Voltaje (5.0);
Voltaje* vGiroCCW= new Voltaje (-5.0);
Giro* giroReposo = new Giro ("stop");
Giro* giroCW = new Giro ("cw");
Giro* giroCCW = new Giro ("ccw");
unsigned int rpm=1200;
Motor* m=new Motor(vReposo,giroReposo,vGiroCW,giroCW,
vGiroCCW, giroCCW, rpm);
/* Comprobamos los voltajes con los getter*/
Voltaje* v;
v=m->getVoltajeReposo();
assert_eq ("Voltaje en reposo con getter",
vReposo->getValor(), v->getValor() );
v=m->getVoltajeGiroCW();
assert_eq("Voltaje en CW con getter",
vGiroCW->getValor(), v->getValor() );
v=m->getVoltajeGiroCCW();
assert_eq ("Voltaje en CCW con getter",
vGiroCCW->getValor(), v->getValor() );
/* Comprobamos los giros con los getter*/
Giro* g;
int codigo_comparacion;
g=m->getGiroReposo();
#ifdef DEBUG_MOTOR
cout << "Giro en reposo es " << g->getValor() << endl;
#endif
codigo_comparacion=strcmp(giroReposo->getValor(), g->getValor());
assert_eq("Giro en reposo con getter",0, codigo_comparacion );
g=m->getGiroCW();
#ifdef DEBUG_MOTOR
cout << "Giro en CW es " << g->getValor() << endl;
#endif
codigo_comparacion=strcmp(giroCW->getValor(), g->getValor());
assert_eq("Giro en CW con getter",0, codigo_comparacion);
g=m->getGiroCCW();
#ifdef DEBUG_MOTOR
cout << "Giro en CCW es " << g->getValor() << endl;
#endif
codigo_comparacion=strcmp(giroCCW->getValor(), g->getValor());
assert_eq("Giro en CCW con getter",0, codigo_comparacion);
}
public:
PruebaMotor():suite ("Prueba del motor")
{
add ("Prueba de valores del motor", testcase
(this, "PruebaValores motor",
&PruebaMotor::PruebaValoresMotor));
add ("Prueba de los metodos getter", testcase
(this, "Prueba de getters",
&PruebaMotor::PruebaGetters));
suite::main().add("PruebaMotores", this);
}
}; /*Fin de la clase*/
PruebaMotor *pMotor=new PruebaMotor();
}
| [
"oscargg"
] | oscargg |
0684441394611585b20ec66f6e39a8564ba36010 | 835934c3035770bd2fb0cea752bbe5c93b8ddc83 | /VTKHeaders/vtkQuadraticQuad.h | da4478403600f593429b56d5469ade4968490276 | [
"MIT"
] | permissive | jmah/OsiriX-Quad-Buffered-Stereo | d257c9fc1e9be01340fe652f5bf9d63f5c84cde1 | 096491358a5d4d8a0928dc03d7183ec129720c56 | refs/heads/master | 2016-09-05T11:08:48.274221 | 2007-05-02T15:06:45 | 2007-05-02T15:06:45 | 3,008,660 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,502 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkQuadraticQuad.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkQuadraticQuad - cell represents a parabolic, 8-node isoparametric quad
// .SECTION Description
// vtkQuadraticQuad is a concrete implementation of vtkNonLinearCell to
// represent a two-dimensional, 8-node isoparametric parabolic quadrilateral
// element. The interpolation is the standard finite element, quadratic
// isoparametric shape function. The cell includes a mid-edge node for each
// of the four edges of the cell. The ordering of the eight points defining
// the cell are point ids (0-3,4-7) where ids 0-3 define the four corner
// vertices of the quad; ids 4-7 define the midedge nodes (0,1), (1,2),
// (2,3), (3,0).
// .SECTION See Also
// vtkQuadraticEdge vtkQuadraticTriangle vtkQuadraticTetra
// vtkQuadraticHexahedron vtkQuadraticWedge vtkQuadraticPyramid
#ifndef __vtkQuadraticQuad_h
#define __vtkQuadraticQuad_h
#include "vtkNonLinearCell.h"
class vtkPolyData;
class vtkQuadraticEdge;
class vtkQuad;
class vtkPointData;
class vtkCellData;
class vtkDataArray;
class vtkDoubleArray;
class VTK_FILTERING_EXPORT vtkQuadraticQuad : public vtkNonLinearCell
{
public:
static vtkQuadraticQuad *New();
vtkTypeRevisionMacro(vtkQuadraticQuad,vtkNonLinearCell);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Implement the vtkCell API. See the vtkCell API for descriptions
// of these methods.
int GetCellType() {return VTK_QUADRATIC_QUAD;};
int GetCellDimension() {return 2;}
int GetNumberOfEdges() {return 4;}
int GetNumberOfFaces() {return 0;}
vtkCell *GetEdge(int);
vtkCell *GetFace(int) {return 0;}
int CellBoundary(int subId, double pcoords[3], vtkIdList *pts);
void Contour(double value, vtkDataArray *cellScalars,
vtkPointLocator *locator, vtkCellArray *verts,
vtkCellArray *lines, vtkCellArray *polys,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd);
int EvaluatePosition(double x[3], double* closestPoint,
int& subId, double pcoords[3],
double& dist2, double *weights);
void EvaluateLocation(int& subId, double pcoords[3], double x[3],
double *weights);
int Triangulate(int index, vtkIdList *ptIds, vtkPoints *pts);
void Derivatives(int subId, double pcoords[3], double *values,
int dim, double *derivs);
virtual double *GetParametricCoords();
// Description:
// Clip this quadratic quad using scalar value provided. Like contouring,
// except that it cuts the quad to produce linear triangles.
void Clip(double value, vtkDataArray *cellScalars,
vtkPointLocator *locator, vtkCellArray *polys,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd,
int insideOut);
// Description:
// Line-edge intersection. Intersection has to occur within [0,1] parametric
// coordinates and with specified tolerance.
int IntersectWithLine(double p1[3], double p2[3], double tol, double& t,
double x[3], double pcoords[3], int& subId);
// Description:
// Quadratic quad specific methods.
static void InterpolationFunctions(double pcoords[3], double weights[8]);
static void InterpolationDerivs(double pcoords[3], double derivs[16]);
protected:
vtkQuadraticQuad();
~vtkQuadraticQuad();
vtkQuadraticEdge *Edge;
vtkQuad *Quad;
vtkPointData *PointData;
vtkCellData *CellData;
vtkDoubleArray *CellScalars;
vtkDoubleArray *Scalars;
void Subdivide(double *weights);
void InterpolateAttributes(vtkPointData *inPd, vtkCellData *inCd, vtkIdType cellId, vtkDataArray *cellScalars);
private:
vtkQuadraticQuad(const vtkQuadraticQuad&); // Not implemented.
void operator=(const vtkQuadraticQuad&); // Not implemented.
};
#endif
| [
"me@JonathonMah.com"
] | me@JonathonMah.com |
d9a90a9537af2947ea5937acd8aa6b2da0fdee0c | 53855cbb261b745d4e24ee1e8ab05893d23ac4da | /bagman/src/Point.cpp | 88f7ff606e1e003ff2e59f48be4c16f526332739 | [] | no_license | umeshdei/bagman | 463e56274b93c0e6b7ddc93abbb1aa671a95118a | 32047d91113c38d9166fc38f71fe52c1c22584ff | refs/heads/master | 2021-01-09T21:57:23.830140 | 2010-12-10T11:52:53 | 2010-12-10T11:52:53 | 46,894,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 966 | cpp | /*
* Point.cpp
*
* Created on: 25-10-2010
* Author: qba
*/
#include "Point.h"
Point::Point(int piX, int piY) {
_iX = piX;
_iY = piY;
}
Point *Point::generateRandomPoint(int piMaxX, int piMaxY) {
Point *ptReturn = new Point();
ptReturn->setX(rand() % piMaxX);
ptReturn->setY(rand() % piMaxY);
return ptReturn;
}
int Point::getDistanceBetweenPoints(Point *pptFirstPoint, Point *pptSecondPoint) {
int iReturnValue;
int iDiffX = abs(pptFirstPoint->getX() - pptSecondPoint->getX());
int iDiffY = abs(pptFirstPoint->getY() - pptSecondPoint->getY());
iReturnValue = (int) sqrt (iDiffX * iDiffX + iDiffY * iDiffY);
return iReturnValue;
}
int Point::getDistanceFromPoint(Point *pptPoint) {
return Point::getDistanceBetweenPoints(this, pptPoint);
}
Point::Point() {
}
Point::~Point() {
}
void Point::setX(int piX) {
_iX = piX;
}
void Point::setY(int piY) {
_iY = piY;
}
int Point::getX() {
return _iX;
}
int Point::getY() {
return _iY;
}
| [
"grzmiel@gmail.com"
] | grzmiel@gmail.com |
c3d3870bde9e6ddd1dad16e24c3a37cb504ed556 | c8045482eee9dc90e8c771cff43014260552d804 | /common/PlayerGame.h | 26e99e23bcbae2263b5219e07a71b3c4d161826b | [] | no_license | 15831944/Sea3D | f93257063aebff2b3cd2ec5b37976f8736e4ef02 | 828d94b1b5784ff72a41aa504c9e5c4f00199c6f | refs/heads/master | 2023-03-20T09:50:21.310838 | 2011-06-09T02:22:07 | 2011-06-09T02:22:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,000 | h | /*
* Settlers3D - Copyright (C) 2001-2003 Jason Fugate (jfugate@settlers3d.net)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
#if !defined(AFX_PLAYERGAME_H__7FAE43F7_B11C_49DE_9959_85E8DB2D1115__INCLUDED_)
#define AFX_PLAYERGAME_H__7FAE43F7_B11C_49DE_9959_85E8DB2D1115__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//////////////////////////////////////////////////////////////////////
// include files
//////////////////////////////////////////////////////////////////////
#include "define.h"
#include "Player.h"
//////////////////////////////////////////////////////////////////////
// class which holds information about one player's game
//////////////////////////////////////////////////////////////////////
class CPlayerGame : public CObject
{
public:
DECLARE_SERIAL(CPlayerGame)
//{{AFX_VIRTUAL(CPlayerGame)
public:
//conditional include
#ifndef AI_DLL
virtual void Serialize(CArchive& ar);
#endif
//}}AFX_VIRTUAL
CPlayerGame();
CPlayerGame(const CPlayerGame &data);
virtual ~CPlayerGame();
//assignment operator
CPlayerGame &operator =(const CPlayerGame &data);
//streamline copy function
void copy(const CPlayerGame &data);
//can this person trade?
BOOL canTrade(void);
//how many cards does this player hold?
int totalCards(void);
//conditional include
#ifndef AI_DLL
//total and playable dev cards
int totalDevCards(void);
int playDevCards(void);
//initialize function
void initPlayer(int iSize);
//copies bought dev cards to playable dev cards at the end of a turn
void copyDevCards(void);
int *getCardsBought(void) {return m_iCardBought;}
//////////////////////////////////////////////////////////////////
// network functions
//////////////////////////////////////////////////////////////////
void SerializeToMessage(CNDKMessage &msg);
void SerializeFromMessage(CNDKMessage &msg);
#endif
public:
//////////////////////////////////////////////////////////////////////
// all the data
//////////////////////////////////////////////////////////////////////
//the player
CPlayer m_player;
//player color
//COLORREF m_color; //RETIRED IN VERSION 0.8.1
int m_iColor;
//temporary variable for use in reloading network games
BOOL m_bJoined;
//cities and settlements
vector <int> m_iSettlements;
vector <int> m_iCities;
//the number of points the player has
int m_iPoints;
//current amounts of resources
int m_iRes[5];
//the amount of jungles
int m_nJungles;
//trade offers used this turn
int m_nTradeOffers;
//amounts of resources gained through various means
int m_iResBoard[5];
int m_iResStolen[6][5];
int m_iResDev[5];
int m_iResGold[5];
int m_iResDiscover[5];
//amounts of resources lost through various means
int m_iLostBoard[6][5];
int m_iLostStolen[6][5];
int m_iLostRoll[5];
//the number of items in stock
int m_nStockRoads;
int m_nStockShips;
int m_nStockCities;
int m_nStockSettle;
//whether they've gotten bonuses for building on islands
BOOL m_bBonus1;
BOOL m_bBonus2;
//the player's home island (in Great Crossing maps)
int m_nHomeIsland; //ADDED IN 1.0.4
int m_nTradePoints; //ADDED IN 1.0.4
//the number of development cards in hand, playable, and played
int m_iCardBought[5]; //cards bought on this turn and not playable
int m_iCardHeld[5]; //cards playable on this turn
int m_iCardPlayed[5]; //cards played to date
//has the player played a card on this turn?
BOOL m_bPlayedCard;
//has the player placed a building on this turn?
BOOL m_bPlacedBuild;
//has the player moved a ship on this turn?
BOOL m_bMovedShip;
//does this player have largest army?
BOOL m_bLargestArmy;
//the length of their roads
int m_iRoadLength;
//does this player have longest road?
BOOL m_bLongestRoad;
//number of trades with the bank
int m_iTradesBank[3];
//number of trades with other people
int m_iTradesOthers[6];
//cards traded to the bank
int m_iBankTradeTo[5];
int m_iBankTradeFrom[5];
//cards traded to others
int m_iOtherTradeTo[6][5];
//cads received from others
int m_iOtherTradeFrom[6][5];
//the number of seconds this player is taking per turn
vector <int> m_iTurnTime;
private:
//conditional include
#ifndef AI_DLL
//////////////////////////////////////////////////////////////////////
// serialize methods
//////////////////////////////////////////////////////////////////////
void save(CArchive &ar);
void load(CArchive &ar);
#endif
};
#endif // !defined(AFX_PLAYERGAME_H__7FAE43F7_B11C_49DE_9959_85E8DB2D1115__INCLUDED_)
| [
"saladyears@gmail.com"
] | saladyears@gmail.com |
d3cd6532fc4cb9a89dc7ebc66b8d0b156835c9b1 | b79f92411e9fbd3196908a7f74fb53fc2055cd63 | /src/new_delete_operators/track_new_delete.cpp | ab64bb58387764b62ab70286dd2cd40b0d06b33a | [
"Beerware"
] | permissive | victorcruceru/my_tour_of_cplusplus | e793f7467a9a13c874fae0ed3e79a13db0b4e0ea | e589ce99c4a3044b393abf019e45e29d42c8dbc1 | refs/heads/master | 2022-02-11T03:44:23.340430 | 2022-01-23T16:30:55 | 2022-01-23T16:30:55 | 164,347,369 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,931 | cpp | /*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Victor Cruceru wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
/*
* Description: Trying the replaced new/ deleted operators
*/
#include <cstdlib>
#include <string>
#include "track_new_delete.hpp"
// Dummy class used to check replaced new/ delete on a real class instance
struct Dummy {
uint32_t d1 = 0;
uint64_t d2 = 0;
Dummy(void){
std::cout << "INFO: Dummy Constructor invoked" << std::endl;
}
~Dummy(void){
std::cout << "INFO Dummy Destructor invoked" << std::endl;
}
};
int main(){
AllocHelper::set_tracing(true);
char* x1 = ::new char;
double* x2 = ::new double;
std::uint64_t* x3 = ::new std::uint64_t[10];
Dummy* d = new Dummy;
Dummy* d_array = new Dummy[2];
std::cout << "::new counter = " << AllocHelper::get_new_count()
<< ", ::delete counter = " << AllocHelper::get_delete_count()
<< ", total bytes allocated = " << AllocHelper::get_total_bytes()
<< std::endl;
AllocHelper::dump_used();
::delete x1;
::delete x2;
::delete [] x3;
::delete d; //comment this line to generate a "leak"
::delete [] d_array;
std::cout << "::new counter = " << AllocHelper::get_new_count()
<< ", ::delete counter = " << AllocHelper::get_delete_count()
<< ", total bytes allocated = " << AllocHelper::get_total_bytes()
<< std::endl;
std::cout << "Number of *leaks* = " << AllocHelper::get_leaks_count()
<< std::endl;
AllocHelper::dump_used();
return (EXIT_SUCCESS);
} | [
"victor.cruceru@gmail.com"
] | victor.cruceru@gmail.com |
2bc685f08ec372d3af2a1454c09d0bdb1eaa0f5a | 4540b627dfeda33422e49e89b44ce9589f7c3e0a | /generators/EffectSet.cpp | 71cd039ecaa27eb3a171fb0e2646cb5d722c2916 | [] | no_license | romanchom/libLunaEsp32 | f88bba2f6c8b8c0f9cc06e51f6f4f1e655489aca | 42c4922e5676407af7ba0dc77b50f2c278d02183 | refs/heads/master | 2022-02-24T09:36:10.711744 | 2022-01-30T12:42:01 | 2022-01-30T12:42:01 | 153,509,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #include "EffectSet.hpp"
#include "Effect.hpp"
namespace luna
{
EffectSet::EffectSet(std::vector<std::tuple<std::string, Effect *>> && effects) :
mEffects(std::move(effects))
{}
Effect * EffectSet::find(std::string const & name)
{
for (auto & [effectName, effect] : mEffects) {
if (effectName == name) {
return effect;
}
}
return nullptr;
}
std::vector<std::tuple<std::string, Configurable *>> EffectSet::children()
{
return {mEffects.begin(), mEffects.end()};
}
}
| [
"romanchom@gmail.com"
] | romanchom@gmail.com |
62aea14b67001342ca801c771ed242b27db22d84 | 76957b84c5c97ac08dd2baea6cd3d5db96d26012 | /common_project/tool_kits/game/view/base/chess_basket/player_wrapper_in_basket.cpp | 70b6183e3534e74b013d0093da4aa8b8fd72941f | [] | no_license | luchengbiao/base | 4e14e71b9c17ff4d2f2c064ec4f5eb7e9ce09ac8 | f8af675e01b0fee31a2b648eb0b95d0c115d68ff | refs/heads/master | 2021-06-27T12:04:29.620264 | 2019-04-29T02:39:32 | 2019-04-29T02:39:32 | 136,405,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,240 | cpp | #include "player_wrapper_in_basket.h"
#include <QWidget>
#include "game/view/base/operational_layer/operational_hook_layer.h"
#include "game/view/base/operational_layer/operational_layer.h"
#include "game/view/player_bar/player_bar.h"
#include "game/public/structs/vs_player_info/vs_player_info.h"
GAME_NAMESPACE_BEGIN
PlayerWrapperInBasket::PlayerWrapperInBasket(PlayerBar* player_bar, QWidget* player_turn_mask, UIOperationalHookLayer* operational_hook_layer)
: player_bar_(player_bar)
, player_turn_mask_(player_turn_mask)
, operational_hook_layer_(operational_hook_layer)
{}
void PlayerWrapperInBasket::ShowPlayeBar()
{
if (!player_bar_.isNull())
{
player_bar_->show();
}
}
void PlayerWrapperInBasket::HidePlayeBar()
{
if (!player_bar_.isNull())
{
player_bar_->hide();
}
}
void PlayerWrapperInBasket::SetPlayeBarVisible(bool visible)
{
visible ? ShowPlayeBar() : HidePlayeBar();
}
void PlayerWrapperInBasket::SetPlayerInfo(const VSPlayerInfo& player_info)
{
if (!player_bar_.isNull())
{
player_bar_->SetPlayerInfo(player_info);
}
}
void PlayerWrapperInBasket::ShowTurnMask()
{
if (!player_turn_mask_.isNull())
{
player_turn_mask_->show();
}
}
void PlayerWrapperInBasket::HideTurnMask()
{
if (!player_turn_mask_.isNull())
{
player_turn_mask_->hide();
}
}
void PlayerWrapperInBasket::SetTurnMaskVisible(bool visible)
{
visible ? ShowTurnMask() : HideTurnMask();
}
void PlayerWrapperInBasket::SetGeometryOfTurnMask(const QRect& geometry)
{
if (!player_turn_mask_.isNull())
{
player_turn_mask_->setGeometry(geometry);
}
}
void PlayerWrapperInBasket::SetGeometryOfOperationalHookLayer(const QRect& geometry)
{
if (!operational_hook_layer_.isNull())
{
operational_hook_layer_->setGeometry(geometry);
}
}
void PlayerWrapperInBasket::AssociateOperationalLayer(UIOperationalLayer* operational_layer)
{
if (!operational_hook_layer_.isNull())
{
operational_hook_layer_->AssociateOperationalLayer(operational_layer);
}
}
void PlayerWrapperInBasket::Reset(PlayerBar* player_bar, QWidget* player_turn_mask, UIOperationalHookLayer* operational_hook_layer)
{
player_bar_ = player_bar;
player_turn_mask_ = player_turn_mask;
operational_hook_layer_ = operational_hook_layer;
}
GAME_NAMESPACE_END | [
"993925668@qq.com"
] | 993925668@qq.com |
a611020423e231e46b28593d82d4c33b81f27790 | c66fdbfebe0060bfe414a72abec5355cf4b13e15 | /Display/Rectangle.cpp | 7512c0e3b145219dd778cab2e9a83e9e187896da | [
"Unlicense"
] | permissive | sagbonkh/Sokoban_Solver | e3a8683dfa1f40338038cffeb344ea0a17b7c274 | 96290f4d85d36ff2591eca96c7d4d694e0763b8d | refs/heads/master | 2023-02-24T18:19:13.425026 | 2020-08-08T19:45:21 | 2020-08-08T19:46:54 | 332,570,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | // Copyright Tobias Faller 2016
#include "Display/Rectangle.h"
#include "Map/Coordinate.h"
#include "Display/Size.h"
namespace Sokoban {
Rectangle::Rectangle() :
x(0), y(0), width(0), height(0) {
}
Rectangle::Rectangle(uint32_t posX, uint32_t posY, uint32_t w, uint32_t h) :
x(posX), y(posY), width(w), height(h) {
}
Rectangle::Rectangle(const Coordinate &coordinate, const Size &size) :
x(coordinate.x), y(coordinate.y), width(size.width), height(size.height) {
}
uint32_t Rectangle::getX() const {
return x;
}
uint32_t Rectangle::getY() const {
return y;
}
Coordinate Rectangle::getPosition() const {
return std::move(Coordinate(x, y));
}
uint32_t Rectangle::getWidth() const {
return width;
}
uint32_t Rectangle::getHeight() const {
return height;
}
Size Rectangle::getSize() const {
return std::move(Size(width, height));
}
void Rectangle::setX(uint32_t posX) {
x = posX;
}
void Rectangle::setY(uint32_t posY) {
y = posY;
}
void Rectangle::setPosition(const Coordinate &coordinate) {
x = coordinate.x;
y = coordinate.y;
}
void Rectangle::setWidth(uint32_t w) {
width = w;
}
void Rectangle::setHeight(uint32_t h) {
height = h;
}
void Rectangle::setSize(const Size &size) {
width = size.width;
height = size.height;
}
} // namespace Sokoban
| [
"sagbonkh@sfu.ca"
] | sagbonkh@sfu.ca |
d51679ec49909db3e7af31484152c6ca8fa8cab6 | 09ef74892eab208e0f154ee05f71c02bc6343fbf | /tests/bindSingleAsThree.cpp | 0cdfeafa3c0eb19aefa5f07aec525dcd16c91946 | [
"MIT"
] | permissive | ptLong/Infectorpp2 | fcbc1e3b49eb18c7b79460dd5240c9fcab2fd314 | d10357b0a5b2870f2a198caf1146928a0146a882 | refs/heads/master | 2021-01-18T07:46:44.076603 | 2015-09-15T11:36:24 | 2015-09-15T11:38:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | cpp | /*******************************************************************************
Copyright (C) 2015 Dario Oliveri
See copyright notice in LICENSE.md
*******************************************************************************/
#include <InfectorContainer.hpp>
#include <priv/ExceptionHandling.hpp>
#undef NDEBUG
#include <assert.h>
class ServiceA{
public:
virtual ~ServiceA(){}
virtual void * asA() = 0;
};
class ServiceB{
public:
virtual ~ServiceB(){}
virtual void * asB() = 0;
};
class ServiceC{
public:
virtual ~ServiceC(){}
virtual void * asC() = 0;
};
class ABC: public ServiceA, public ServiceB, public ServiceC {
int val = 3;
public:
ABC(){
}
void * asA() override { return val==3? this: nullptr; }
void * asB() override { return val==3? this: nullptr; }
void * asC() override { return val==3? this: nullptr; }
};
int bindSingleAsThree( int argc, char**){
using namespace Infector;
Container ioc;
ioc.bindSingleAs< ABC, ServiceA, ServiceB, ServiceC>();
ioc.wire< ABC>();
auto context = ioc.createPrototypeContext();
auto A = context.buildSingle< ServiceA>();
auto B = context.buildSingle< ServiceB>();
auto C = context.buildSingle< ServiceC>();
assert( A->asA() == B->asB());
assert( C->asC() == B->asB());
assert( A->asA() != nullptr);
return 0;
} | [
"github.com/Darelbi"
] | github.com/Darelbi |
9bee933fc08c6cc2f3883687eb52d6599e8284e9 | dd6b6da760c32ac6830c52aa2f4d5cce17e4d408 | /magma-2.5.0/src/zhetrd_he2hb.cpp | 1f54d5ec531ec6deaff7e2ed8eb0282a3d398603 | [] | no_license | uumami/hit_and_run | 81584b4f68cf25a2a1140baa3ee88f9e1844b672 | dfda812a52bbd65e02753b9abcb9f54aeb4e8184 | refs/heads/master | 2023-03-13T16:48:37.975390 | 2023-02-28T05:04:58 | 2023-02-28T05:04:58 | 139,909,134 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,199 | cpp | /*
-- MAGMA (version 2.5.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2019
@author Azzam Haidar
@author Stan Tomov
@precisions normal z -> s d c
*/
#include <cuda_runtime.h>
#include "magma_internal.h"
#include "trace.h"
/***************************************************************************//**
Purpose
-------
ZHETRD_HE2HB reduces a complex Hermitian matrix A to real symmetric
band-diagonal form T by an orthogonal similarity transformation:
Q**H * A * Q = T.
This version stores the triangular matrices T used in the accumulated
Householder transformations (I - V T V').
Arguments
---------
@param[in]
uplo magma_uplo_t
- = MagmaUpper: Upper triangle of A is stored;
- = MagmaLower: Lower triangle of A is stored.
@param[in]
n INTEGER
The order of the matrix A. n >= 0.
@param[in]
nb INTEGER
The inner blocking. nb >= 0.
@param[in,out]
A COMPLEX_16 array, dimension (LDA,N)
On entry, the Hermitian matrix A. If UPLO = MagmaUpper, the leading
N-by-N upper triangular part of A contains the upper
triangular part of the matrix A, and the strictly lower
triangular part of A is not referenced. If UPLO = MagmaLower, the
leading N-by-N lower triangular part of A contains the lower
triangular part of the matrix A, and the strictly upper
triangular part of A is not referenced.
On exit, if UPLO = MagmaUpper, the Upper band-diagonal of A is
overwritten by the corresponding elements of the
band-diagonal matrix T, and the elements above the band
diagonal, with the array TAU, represent the orthogonal
matrix Q as a product of elementary reflectors; if UPLO
= MagmaLower, the the Lower band-diagonal of A is overwritten by
the corresponding elements of the band-diagonal
matrix T, and the elements below the band-diagonal, with
the array TAU, represent the orthogonal matrix Q as a product
of elementary reflectors. See Further Details.
@param[in]
lda INTEGER
The leading dimension of the array A. LDA >= max(1,N).
@param[out]
tau COMPLEX_16 array, dimension (N-1)
The scalar factors of the elementary reflectors (see Further
Details).
@param[out]
work (workspace) COMPLEX_16 array, dimension (MAX(1,LWORK))
On exit, if INFO = 0, WORK[0] returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array WORK. LWORK >= 1.
For optimum performance LWORK >= N*NB, where NB is the
optimal blocksize.
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the WORK array, returns
this value as the first entry of the WORK array, and no error
message related to LWORK is issued by XERBLA.
@param[out]
dT COMPLEX_16 array on the GPU, dimension N*NB,
where NB is the optimal blocksize.
On exit dT holds the upper triangular matrices T from the
accumulated Householder transformations (I - V T V') used
in the factorization. The nb x nb matrices T are ordered
consecutively in memory one after another.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
Further Details
---------------
If UPLO = MagmaUpper, the matrix Q is represented as a product of elementary
reflectors
Q = H(n-1) . . . H(2) H(1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a complex scalar, and v is a complex vector with
v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in
A(1:i-1,i+1), and tau in TAU(i).
If UPLO = MagmaLower, the matrix Q is represented as a product of elementary
reflectors
Q = H(1) H(2) . . . H(n-1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a complex scalar, and v is a complex vector with
v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i),
and tau in TAU(i).
The contents of A on exit are illustrated by the following examples
with n = 5:
if UPLO = MagmaUpper: if UPLO = MagmaLower:
( d e v2 v3 v4 ) ( d )
( d e v3 v4 ) ( e d )
( d e v4 ) ( v1 e d )
( d e ) ( v1 v2 e d )
( d ) ( v1 v2 v3 e d )
where d and e denote diagonal and off-diagonal elements of T, and vi
denotes an element of the vector defining H(i).
@ingroup magma_hetrd_he2hb
*******************************************************************************/
extern "C" magma_int_t
magma_zhetrd_he2hb(
magma_uplo_t uplo, magma_int_t n, magma_int_t nb,
magmaDoubleComplex *A, magma_int_t lda,
magmaDoubleComplex *tau,
magmaDoubleComplex *work, magma_int_t lwork,
magmaDoubleComplex_ptr dT,
magma_int_t *info)
{
#ifdef HAVE_clBLAS
#define dA(a_1,a_2) (dA, (dA_offset + ((a_2)-1)*(ldda) + (a_1)-1))
#define dT(a_1) (dT, (dT_offset + ((a_1)-1)*(lddt)))
#else
#define dA(a_1,a_2) (dA + ((a_2)-1)*(ldda) + (a_1)-1)
#define dT(a_1) (dT + ((a_1)-1)*(lddt))
#endif
#define A(a_1,a_2) ( A + ((a_2)-1)*( lda) + (a_1)-1)
#define tau_ref(a_1) (tau + (a_1)-1)
magma_int_t ldda = magma_roundup( n, 32 );
magma_int_t lddt = nb;
magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magmaDoubleComplex c_neg_half = MAGMA_Z_NEG_HALF;
magmaDoubleComplex c_one = MAGMA_Z_ONE;
magmaDoubleComplex c_zero = MAGMA_Z_ZERO;
double d_one = MAGMA_D_ONE;
magma_int_t pm, pn, indi, indj, pk;
magma_int_t pm_old=0, pn_old=0, indi_old=0, indj_old=0;
magma_int_t i;
magma_int_t lwkopt;
*info = 0;
bool upper = (uplo == MagmaUpper);
bool lquery = (lwork == -1);
if (! upper && uplo != MagmaLower) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (lda < max(1,n)) {
*info = -4;
} else if (lwork < 1 && ! lquery) {
*info = -9;
}
/* Determine the block size. */
lwkopt = n * nb;
if (*info == 0) {
work[0] = magma_zmake_lwork( lwkopt );
}
if (*info != 0)
return *info;
else if (lquery)
return *info;
/* Quick return if possible */
if (n == 0) {
work[0] = c_one;
return *info;
}
magmaDoubleComplex *dA;
if (MAGMA_SUCCESS != magma_zmalloc( &dA, (n + 2*nb)*ldda )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
// limit to 16 threads
magma_int_t orig_threads = magma_get_lapack_numthreads();
magma_set_lapack_numthreads( min(orig_threads,16) );
/* Use the first panel of dA as work space */
magmaDoubleComplex *dwork = dA + n*ldda;
magmaDoubleComplex *dW = dwork + nb*ldda;
#ifdef TRACING
char buf[80];
#endif
magma_queue_t queues[2];
magma_device_t cdev;
magma_getdevice( &cdev );
magma_queue_create( cdev, &queues[0] );
magma_queue_create( cdev, &queues[1] );
trace_init( 1, 1, 3, queues );
lwork -= nb*nb;
magmaDoubleComplex *hT = work + lwork;
memset( hT, 0, nb*nb*sizeof(magmaDoubleComplex));
magma_event_t Pupdate_event;
cudaEventCreateWithFlags(&Pupdate_event,cudaEventDisableTiming);
//magma_event_create(&Pupdate_event);
if (upper) {
printf("ZHETRD_HE2HB is not yet implemented for upper matrix storage. Exit.\n");
return MAGMA_ERR_NOT_IMPLEMENTED;
} else {
/* Copy the matrix to the GPU */
if (1 <= n-nb) {
trace_gpu_start( 0, 0, "set", "set A" );
magma_zsetmatrix_async( (n-nb), (n-nb),
A(nb+1, nb+1), lda,
dA(nb+1, nb+1), ldda, queues[0] );
trace_gpu_end( 0, 0 );
}
/* Reduce the lower triangle of A */
for (i = 1; i <= n-nb; i += nb) {
indi = i+nb;
indj = i;
pm = n - i - nb + 1;
//pn = min(i+nb-1, n-nb) -i + 1;
pn = nb;
/* Get the current panel (no need for the 1st iteration) */
if (i > 1 ) {
// magma_zpanel_to_q copy the upper oof diagonal part of
// the matrix to work to be restored later. acctually
// the zero's and one's putted are not used this is only
// because we don't have a function that copy only the
// upper part of A to be restored after copying the
// lookahead panel that has been computted from GPU to CPU.
magma_zpanel_to_q(MagmaUpper, pn-1, A(i, i+1), lda, work);
trace_gpu_start( 0, 1, "get", "get panel" );
//magma_queue_sync( queues[0] );
magma_queue_wait_event(queues[1], Pupdate_event); //, 0);
magma_zgetmatrix_async( (pm+pn), pn,
dA( i, i), ldda,
A ( i, i), lda, queues[1] );
trace_gpu_end( 0, 1 );
trace_gpu_start( 0, 2, "her2k", "her2k" );
magma_zher2k( MagmaLower, MagmaNoTrans, pm_old-pn_old, pn_old, c_neg_one,
dA(indi_old+pn_old, indj_old), ldda,
dW + pn_old, pm_old, d_one,
dA(indi_old+pn_old, indi_old+pn_old), ldda, queues[0] );
trace_gpu_end( 0, 2 );
trace_cpu_start( 0, "sync", "sync on 1" );
magma_queue_sync( queues[1] );
trace_cpu_end( 0 );
magma_zq_to_panel(MagmaUpper, pn-1, A(i, i+1), lda, work);
}
/* ==========================================================
QR factorization on a panel starting nb off of the diagonal.
Prepare the V and T matrices.
========================================================== */
#ifdef TRACING
snprintf( buf, sizeof(buf), "panel %lld", (long long) i );
#endif
trace_cpu_start( 0, "geqrf", buf );
lapackf77_zgeqrf(&pm, &pn, A(indi, indj), &lda,
tau_ref(i), work, &lwork, info);
/* Form the matrix T */
pk=min(pm,pn);
lapackf77_zlarft( MagmaForwardStr, MagmaColumnwiseStr,
&pm, &pk, A(indi, indj), &lda,
tau_ref(i), hT, &nb);
/* Prepare V - put 0s in the upper triangular part of the panel
(and 1s on the diagonal), temporaly storing the original in work */
magma_zpanel_to_q(MagmaUpper, pk, A(indi, indj), lda, work);
trace_cpu_end( 0 );
/* Send V from the CPU to the GPU */
trace_gpu_start( 0, 0, "set", "set V and T" );
magma_zsetmatrix_async( pm, pk,
A(indi, indj), lda,
dA(indi, indj), ldda, queues[0] );
/* Send the triangular factor T to the GPU */
magma_zsetmatrix_async( pk, pk,
hT, nb,
dT(i), lddt, queues[0] );
trace_gpu_end( 0, 0 );
/* ==========================================================
Compute W:
1. X = A (V T)
2. W = X - 0.5* V * (T' * (V' * X))
========================================================== */
/* dwork = V T */
trace_cpu_start( 0, "sync", "sync on 0" );
// this sync is done here to be sure that the copy has been finished
// because below we made a restore magma_zq_to_panel and this restore need
// to ensure that the copy has been finished. we did it here to allow
// overlapp of restore with next gemm and symm.
magma_queue_sync( queues[0] );
trace_cpu_end( 0 );
trace_gpu_start( 0, 2, "gemm", "work = V*T" );
magma_zgemm( MagmaNoTrans, MagmaNoTrans, pm, pk, pk,
c_one, dA(indi, indj), ldda,
dT(i), lddt,
c_zero, dwork, pm, queues[0] );
trace_gpu_end( 0, 2 );
/* dW = X = A*V*T. dW = A*dwork */
trace_gpu_start( 0, 2, "hemm", "X = A*work" );
magma_zhemm( MagmaLeft, uplo, pm, pk,
c_one, dA(indi, indi), ldda,
dwork, pm,
c_zero, dW, pm, queues[0] );
trace_gpu_end( 0, 2 );
/* restore the panel */
magma_zq_to_panel(MagmaUpper, pk, A(indi, indj), lda, work);
/* dwork = V*T already ==> dwork' = T'*V'
* compute T'*V'*X ==> dwork'*W ==>
* dwork + pm*nb = ((T' * V') * X) = dwork' * X = dwork' * W */
trace_gpu_start( 0, 2, "gemm", "work = T'*V'*X" );
magma_zgemm( MagmaConjTrans, MagmaNoTrans, pk, pk, pm,
c_one, dwork, pm,
dW, pm,
c_zero, dwork + pm*nb, nb, queues[0] );
trace_gpu_end( 0, 2 );
/* W = X - 0.5 * V * T'*V'*X
* = X - 0.5 * V * (dwork + pm*nb) = W - 0.5 * V * (dwork + pm*nb) */
trace_gpu_start( 0, 2, "gemm", "W = X - 0.5*V*(T'*V'*X)" );
magma_zgemm( MagmaNoTrans, MagmaNoTrans, pm, pk, pk,
c_neg_half, dA(indi, indj), ldda,
dwork + pm*nb, nb,
c_one, dW, pm, queues[0] );
trace_gpu_end( 0, 2 );
/* ==========================================================
Update the unreduced submatrix A(i+ib:n,i+ib:n), using
an update of the form: A := A - V*W' - W*V'
========================================================== */
if (i + nb <= n-nb) {
// There would be next iteration;
// do lookahead - update the next panel
trace_gpu_start( 0, 2, "gemm", "gemm 4 next panel left" );
magma_zgemm( MagmaNoTrans, MagmaConjTrans, pm, pn, pn, c_neg_one,
dA(indi, indj), ldda,
dW, pm, c_one,
dA(indi, indi), ldda, queues[0] );
trace_gpu_end( 0, 2 );
trace_gpu_start( 0, 2, "gemm", "gemm 5 next panel right" );
magma_zgemm( MagmaNoTrans, MagmaConjTrans, pm, pn, pn, c_neg_one,
dW, pm,
dA(indi, indj), ldda, c_one,
dA(indi, indi), ldda, queues[0] );
trace_gpu_end( 0, 2 );
magma_event_record(Pupdate_event, queues[0]);
}
else {
/* no look-ahead as this is last iteration */
trace_gpu_start( 0, 2, "her2k", "her2k last iteration" );
magma_zher2k( MagmaLower, MagmaNoTrans, pk, pk, c_neg_one,
dA(indi, indj), ldda,
dW, pm, d_one,
dA(indi, indi), ldda, queues[0] );
trace_gpu_end( 0, 2 );
}
indi_old = indi;
indj_old = indj;
pm_old = pm;
pn_old = pn;
} // end loop for (i)
/* Send the last block to the CPU */
pk = min(pm,pn);
if (1 <= n-nb) {
magma_zpanel_to_q(MagmaUpper, pk-1, A(n-pk+1, n-pk+2), lda, work);
trace_gpu_start( 0, 2, "get", "get last block" );
magma_zgetmatrix( pk, pk,
dA(n-pk+1, n-pk+1), ldda,
A(n-pk+1, n-pk+1), lda, queues[0] );
trace_gpu_end( 0, 2 );
magma_zq_to_panel(MagmaUpper, pk-1, A(n-pk+1, n-pk+2), lda, work);
}
}// end of LOWER
trace_finalize( "zhetrd_he2hb.svg", "trace.css" );
magma_queue_sync( queues[0] );
magma_queue_sync( queues[1] );
magma_event_destroy( Pupdate_event );
magma_queue_destroy( queues[0] );
magma_queue_destroy( queues[1] );
magma_free( dA );
magma_set_lapack_numthreads( orig_threads );
return *info;
} /* magma_zhetrd_he2hb */
| [
"vazcorm@gmail.com"
] | vazcorm@gmail.com |
c612ed01fd67967c451c4b98ad45e68d7f972f64 | d990692dd7afdbb2a235ad03ac5209b4f3bb0df9 | /ipc/chromium/src/base/test_file_util_win.cc | f6a5becfbd2a4e927d949bef1e0dda215cf4957e | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | walkero-gr/timberwolf | 5c33158a19dfeb3781c72c6732d45747d9a3c19e | 90ca7da29b6089d1b14f5ff1d08e586aa2ec041f | refs/heads/master | 2022-09-15T11:13:14.252767 | 2022-09-04T12:39:59 | 2022-09-04T12:39:59 | 291,531,351 | 0 | 0 | NOASSERTION | 2020-08-30T18:46:51 | 2020-08-30T18:46:51 | null | UTF-8 | C++ | false | false | 5,668 | cc | // Copyright (c) 2008 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 "base/test_file_util.h"
#include <windows.h>
#include <vector>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/scoped_handle.h"
namespace file_util {
// We could use GetSystemInfo to get the page size, but this serves
// our purpose fine since 4K is the page size on x86 as well as x64.
static const ptrdiff_t kPageSize = 4096;
bool EvictFileFromSystemCache(const FilePath& file) {
// Request exclusive access to the file and overwrite it with no buffering.
ScopedHandle file_handle(
CreateFile(file.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL));
if (!file_handle)
return false;
// Get some attributes to restore later.
BY_HANDLE_FILE_INFORMATION bhi = {0};
CHECK(::GetFileInformationByHandle(file_handle, &bhi));
// Execute in chunks. It could be optimized. We want to do few of these since
// these operations will be slow without the cache.
// Non-buffered reads and writes need to be sector aligned and since sector
// sizes typically range from 512-4096 bytes, we just use the page size.
// The buffer size is twice the size of a page (minus one) since we need to
// get an aligned pointer into the buffer that we can use.
char buffer[2 * kPageSize - 1];
// Get an aligned pointer into buffer.
char* read_write = reinterpret_cast<char*>(
reinterpret_cast<ptrdiff_t>(buffer + kPageSize - 1) & ~(kPageSize - 1));
DCHECK((reinterpret_cast<int>(read_write) % kPageSize) == 0);
// If the file size isn't a multiple of kPageSize, we'll need special
// processing.
bool file_is_page_aligned = true;
int total_bytes = 0;
DWORD bytes_read, bytes_written;
for (;;) {
bytes_read = 0;
ReadFile(file_handle, read_write, kPageSize, &bytes_read, NULL);
if (bytes_read == 0)
break;
if (bytes_read < kPageSize) {
// Zero out the remaining part of the buffer.
// WriteFile will fail if we provide a buffer size that isn't a
// sector multiple, so we'll have to write the entire buffer with
// padded zeros and then use SetEndOfFile to truncate the file.
ZeroMemory(read_write + bytes_read, kPageSize - bytes_read);
file_is_page_aligned = false;
}
// Move back to the position we just read from.
// Note that SetFilePointer will also fail if total_bytes isn't sector
// aligned, but that shouldn't happen here.
DCHECK((total_bytes % kPageSize) == 0);
SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN);
if (!WriteFile(file_handle, read_write, kPageSize, &bytes_written, NULL) ||
bytes_written != kPageSize) {
DCHECK(false);
return false;
}
total_bytes += bytes_read;
// If this is false, then we just processed the last portion of the file.
if (!file_is_page_aligned)
break;
}
if (!file_is_page_aligned) {
// The size of the file isn't a multiple of the page size, so we'll have
// to open the file again, this time without the FILE_FLAG_NO_BUFFERING
// flag and use SetEndOfFile to mark EOF.
file_handle.Set(NULL);
file_handle.Set(CreateFile(file.value().c_str(), GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL));
CHECK(SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN) !=
INVALID_SET_FILE_POINTER);
CHECK(::SetEndOfFile(file_handle));
}
// Restore the file attributes.
CHECK(::SetFileTime(file_handle, &bhi.ftCreationTime, &bhi.ftLastAccessTime,
&bhi.ftLastWriteTime));
return true;
}
// Like CopyFileNoCache but recursively copies all files and subdirectories
// in the given input directory to the output directory.
bool CopyRecursiveDirNoCache(const std::wstring& source_dir,
const std::wstring& dest_dir) {
// Try to create the directory if it doesn't already exist.
if (!CreateDirectory(dest_dir)) {
if (GetLastError() != ERROR_ALREADY_EXISTS)
return false;
}
std::vector<std::wstring> files_copied;
std::wstring src(source_dir);
file_util::AppendToPath(&src, L"*");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile(src.c_str(), &fd);
if (fh == INVALID_HANDLE_VALUE)
return false;
do {
std::wstring cur_file(fd.cFileName);
if (cur_file == L"." || cur_file == L"..")
continue; // Skip these special entries.
std::wstring cur_source_path(source_dir);
file_util::AppendToPath(&cur_source_path, cur_file);
std::wstring cur_dest_path(dest_dir);
file_util::AppendToPath(&cur_dest_path, cur_file);
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// Recursively copy a subdirectory. We stripped "." and ".." already.
if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) {
FindClose(fh);
return false;
}
} else {
// Copy the file.
if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) {
FindClose(fh);
return false;
}
// We don't check for errors from this function, often, we are copying
// files that are in the repository, and they will have read-only set.
// This will prevent us from evicting from the cache, but these don't
// matter anyway.
EvictFileFromSystemCache(FilePath::FromWStringHack(cur_dest_path));
}
} while (FindNextFile(fh, &fd));
FindClose(fh);
return true;
}
} // namespace file_util
| [
"benjamin@smedbergs.us"
] | benjamin@smedbergs.us |
6dc2d8a8333f352d4d9fb0468f4cfbbeadab13c0 | e0de6b4e69f27fceefc95392abab9548132828e7 | /sketch_may25a/sketch_may25a.ino | e12fccc994faf08e48d57fbedc1965f281f85f4b | [] | no_license | CS6/myArduino | 146a7df7dde132411a0a45e62fbe2ba9af594499 | 05fa5ce4f79c46c74a1aba825a8115c9fa313729 | refs/heads/master | 2021-07-18T21:17:12.472243 | 2017-10-26T10:09:31 | 2017-10-26T10:09:31 | 108,394,776 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | ino | const int seg7[]={11,10,9,8,7,6,5,4};
const int scan[]={3,2,1,0};
const int prowpin[]={12,13};
int delaytime=5;
char TAB[]={0xFF,0xFE,0xFD,0xFC,0xFB,0xFA,0xF9,0xF8,0xF7};
int ii,jj,zz,hh;
int ScanLine=0;
void setup() {
// put your setup code here, to run once:
for(ii=0;ii<7;ii++){
pinMode(seg7[ii],OUTPUT);
}
for(ii=0;ii<4;ii++)
{
pinMode(scan[ii],OUTPUT);
digitalWrite(scan[ii],LOW);
}
for(zz=0;zz<2;zz++)
{
pinMode(prowpin[zz],OUTPUT);
digitalWrite(prowpin[zz],HIGH);
}
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available())
{
delaytime=Serial.parseInt();
Serial.print(delaytime);
Serial.println("MS");
}
OutPort(TAB[2]);
}
void OutPort(byte dat){
for(jj=0;jj<8;jj++)
{
if(dat%2==1)
digitalWrite(seg7[jj],HIGH);
else
digitalWrite(seg7[jj],LOW);
dat=dat/2;
}
}
| [
"e31217@gmail.com"
] | e31217@gmail.com |
b17208cab602901c74c49495dc8d658573949b66 | c5494f730af1f52640ebe08b629d10977c530e17 | /Include/Om/Detail/MethodPointer.h | aa2e963d6e446e00084a86919aec12960c875af3 | [] | no_license | koden-km/ObjectModel | 1230fe29656d5078f195ad1d5e3a145f20c5006c | 4b86f6f65bca786c2d51615af93edbad62556cb0 | refs/heads/master | 2016-09-05T12:12:39.939353 | 2014-03-12T13:59:45 | 2014-03-12T13:59:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,324 | h | // (C) 2009 Christian.Schladetsch@Gmail.com.
// (C) 2009 Blue Lion Software Limited.
#pragma once
#include "Om/Pointer.h"
namespace Detail
{
template <bool IsKonst, bool IsVoid, int Arity, class Return, class Klass, class Args>
struct MethodPointer;
//----------------------------------------------------------- arity = 0
struct MethodPointerBase0
{
template <class OI>
void AddArgs(OI)
{
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, false, 0, Return, Klass, Args> : MethodPointerBase0
{
typedef Return (Klass::*Method)();
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
stack.push_back(object.New((Deref<Klass>(object).*method)()));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, false, 0, Return, Klass, Args> : MethodPointerBase0
{
typedef Return (Klass::*Method)() const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
stack.push_back(object.New((Deref<Klass>(object).*method)()));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, true, 0, Return, Klass, Args> : MethodPointerBase0
{
typedef Return (Klass::*Method)();
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
(Deref<Klass>(object).*method)();
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, true, 0, Return, Klass, Args> : MethodPointerBase0
{
typedef Return (Klass::*Method)() const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
(Deref<Klass>(object).*method)();
}
};
//----------------------------------------------------------- arity = 1
template <class Args>
struct MethodPointerBase1 : MethodPointerBase0
{
typedef typename boost::mpl::at_c<Args, 0>::type A0;
typedef typename BaseType<A0>::Type B0;
typedef Pointer<B0> P0;
template <class OI>
void AddArgs(OI P)
{
MethodPointerBase0::AddArgs(P);
*P++ = Type::MakeType<A0>::Create();
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, false, 1, Return, Klass, Args> : MethodPointerBase1<Args>
{
typedef Return (Klass::*Method)(A0);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, false, 1, Return, Klass, Args> : MethodPointerBase1<Args>
{
typedef Return (Klass::*Method)(A0) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, true, 1, Return, Klass, Args> : MethodPointerBase1<Args>
{
typedef Return (Klass::*Method)(A0);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0);
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, true, 1, Return, Klass, Args> : MethodPointerBase1<Args>
{
typedef Return (Klass::*Method)(A0) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0);
}
};
//----------------------------------------------------------- arity = 2
template <class Args>
struct MethodPointerBase2 : MethodPointerBase1<Args>
{
typedef typename boost::mpl::at_c<Args, 1>::type A1;
typedef typename BaseType<A1>::Type B1;
typedef Pointer<B1> P1;
template <class OI>
void AddArgs(OI P)
{
MethodPointerBase1<Args>::AddArgs(P);
*P++ = Type::MakeType<A1>::Create();
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, false, 2, Return, Klass, Args> : MethodPointerBase2<Args>
{
typedef Return (Klass::*Method)(A0,A1);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P1 a1 = stack.pop();
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0, *a1)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, false, 2, Return, Klass, Args> : MethodPointerBase2<Args>
{
typedef Return (Klass::*Method)(A0,A1) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P1 a1 = stack.pop();
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0, *a1)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, true, 2, Return, Klass, Args> : MethodPointerBase2<Args>
{
typedef Return (Klass::*Method)(A0,A1);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P1 a1 = stack.pop();
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0, *a1);
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, true, 2, Return, Klass, Args> : MethodPointerBase2<Args>
{
typedef Return (Klass::*Method)(A0, A1) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P1 a1 = stack.pop();
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0, *a1);
}
};
//----------------------------------------------------------- arity = 3
template <class Args>
struct MethodPointerBase3 : MethodPointerBase2<Args>
{
typedef typename boost::mpl::at_c<Args, 2>::type A2;
typedef typename BaseType<A2>::Type B2;
typedef Pointer<B2> P2;
template <class OI>
void AddArgs(OI P)
{
MethodPointerBase2<Args>::AddArgs(P);
*P++ = Type::MakeType<A2>::Create();
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, false, 3, Return, Klass, Args> : MethodPointerBase3<Args>
{
typedef Return (Klass::*Method)(A0,A1,A2);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P2 a2 = stack.pop();
P1 a1 = stack.pop();
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0, *a1, *a2)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, false, 3, Return, Klass, Args> : MethodPointerBase3<Args>
{
typedef Return (Klass::*Method)(A0,A1,A2) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P2 a2 = stack.pop();
P1 a1 = stack.pop();
P0 a0 = stack.pop();
stack.push_back(object.New((Deref<Klass>(object).*method)(*a0, *a1, *a2)));
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<false, true, 3, Return, Klass, Args> : MethodPointerBase3<Args>
{
typedef Return (Klass::*Method)(A0,A1,A2);
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object &object, Vector &stack) const
{
P2 a2 = stack.pop();
P1 a1 = stack.pop();
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0, *a1, *a2);
}
};
template <class Return, class Klass, class Args>
struct MethodPointer<true, true, 3, Return, Klass, Args> : MethodPointerBase3<Args>
{
typedef Return (Klass::*Method)(A0, A1,A2) const;
Method method;
MethodPointer(Method M) : method(M) { }
void operator()(Object const &object, Vector &stack) const
{
P2 a2 = stack.pop();
P1 a1 = stack.pop();
P0 a0 = stack.pop();
(Deref<Klass>(object).*method)(*a0, *a1, *a2);
}
};
template <class Rty, class Klass, class Args, bool Konst>
struct MakeMethodPointer
{
typedef MethodPointer<Konst, boost::is_same<void, Rty>::value, boost::mpl::size<Args>::value, Rty, Klass, Args> Type;
};
}
//EOF
| [
"christian.schladetsch@gmail.com"
] | christian.schladetsch@gmail.com |
5a1e67245d58040a4f623cc962eda4c55034fba1 | 6b86d8b823b8203bd3feb46259239a7768a63db3 | /server/src/lua/bind/mem_alloc_lua.cc | 44fe4dee007602d5890040a633354856dd8694a7 | [] | no_license | Time0o/CPPBind_examples | 43c424c2ae28b4b452bbdcb9b285b0806af65ff8 | 14b195d489c10cd656dcfe5dc6c7c33db05b3259 | refs/heads/master | 2023-04-29T06:18:41.279056 | 2021-05-23T10:45:38 | 2021-05-23T10:45:38 | 364,952,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,658 | cc | #define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "/home/timo/github/projects/cppbind/generate/cppbind/lua/lua_util.h"
#include "/home/timo/github/l4re/l4/pkg/l4re-core/l4re/include/mem_alloc"
#include "/home/timo/github/projects/cppbind/generate/cppbind/type_info.h"
namespace cppbind::type_info {
type_instance<L4Re::Mem_alloc> _ZTSN4L4Re9Mem_allocE;
type_instance<L4::Cap<L4Re::Dataspace>> _ZTSN2L43CapIN4L4Re9DataspaceEEE;
}
namespace
{
int l4_re_mem_alloc_alloc(lua_State *L)
{
if (lua_gettop(L) < 3 || lua_gettop(L) > 5)
return luaL_error(L, "function expects between 3 and 5 arguments");
using namespace L4Re;
const L4Re::Mem_alloc * ___self;
long _size;
const L4::Cap<L4Re::Dataspace> * _mem;
unsigned long _flags = 0;
unsigned long _align = 0;
luaL_checktype(L, 1, LUA_TUSERDATA);
___self = cppbind::type_info::typed_pointer_cast<const L4Re::Mem_alloc>(*static_cast<void **>(lua_touserdata(L, 1)));
luaL_checktype(L, 2, LUA_TNUMBER);
_size = cppbind::lua::tointegral<long>(L, 2);
luaL_checktype(L, 3, LUA_TUSERDATA);
_mem = cppbind::type_info::typed_pointer_cast<L4::Cap<L4Re::Dataspace>>(*static_cast<void **>(lua_touserdata(L, 3)));
if (lua_gettop(L) < 4) goto function_call;
luaL_checktype(L, 4, LUA_TNUMBER);
_flags = cppbind::lua::tointegral<unsigned long>(L, 4);
if (lua_gettop(L) < 5) goto function_call;
luaL_checktype(L, 5, LUA_TNUMBER);
_align = cppbind::lua::tointegral<unsigned long>(L, 5);
function_call:
auto __out = ___self->alloc(_size, *_mem, _flags, _align);
cppbind::lua::pushintegral(L, __out);
return 1;
}
int l4_re_mem_alloc_free(lua_State *L)
{
if (lua_gettop(L) != 2)
return luaL_error(L, "function expects 2 arguments");
using namespace L4Re;
const L4Re::Mem_alloc * ___self;
const L4::Cap<L4Re::Dataspace> * _mem;
luaL_checktype(L, 1, LUA_TUSERDATA);
___self = cppbind::type_info::typed_pointer_cast<const L4Re::Mem_alloc>(*static_cast<void **>(lua_touserdata(L, 1)));
luaL_checktype(L, 2, LUA_TUSERDATA);
_mem = cppbind::type_info::typed_pointer_cast<L4::Cap<L4Re::Dataspace>>(*static_cast<void **>(lua_touserdata(L, 2)));
auto __out = ___self->free(*_mem);
cppbind::lua::pushintegral(L, __out);
return 1;
}
void _register(lua_State *L)
{
lua_createtable(L, 0, 0);
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "L4Cap");
lua_createtable(L, 0, 0);
lua_pushinteger(L, L4Re::Mem_alloc::Continuous);
lua_setfield(L, -2, "MEM_ALLOC_CONTINUOUS");
lua_pushinteger(L, L4Re::Mem_alloc::Pinned);
lua_setfield(L, -2, "MEM_ALLOC_PINNED");
lua_pushinteger(L, L4Re::Mem_alloc::Super_pages);
lua_setfield(L, -2, "MEM_ALLOC_SUPER_PAGES");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "Dataspace");
lua_createtable(L, 0, 0);
lua_setfield(L, -2, "MemAlloc");
lua_setfield(L, -2, "L4Re");
}
void _createmetatables(lua_State *L)
{
cppbind::lua::createmetatable(L, "METATABLE__ZTSN4L4Re9Mem_allocE",
{
{"alloc", l4_re_mem_alloc_alloc},
{"free", l4_re_mem_alloc_free}
});
}
extern "C"
{
LUALIB_API int luaopen_mem_alloc(lua_State *L)
{
_register(L);
_createmetatables(L);
return 1;
}
} // extern "C"
} // namespace | [
"timonicolai@arcor.de"
] | timonicolai@arcor.de |
71d64bb85d96cbce7eb2b593d5aa233674caae90 | 573a66e4f4753cc0f145de8d60340b4dd6206607 | /JS-CS-Detection-byExample/Dataset (ALERT 5 GB)/362764/shogun-2.1.0/shogun-2.1.0/tests/unit/lib/SGVector_unittest.cc | c46f9852ff68a9cb864614a5e13e7ce6324d445e | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | mkaouer/Code-Smells-Detection-in-JavaScript | 3919ec0d445637a7f7c5f570c724082d42248e1b | 7130351703e19347884f95ce6d6ab1fb4f5cfbff | refs/heads/master | 2023-03-09T18:04:26.971934 | 2022-03-23T22:04:28 | 2022-03-23T22:04:28 | 73,915,037 | 8 | 3 | null | 2023-02-28T23:00:07 | 2016-11-16T11:47:44 | null | UTF-8 | C++ | false | false | 4,366 | cc | #include <shogun/lib/SGVector.h>
#include <shogun/mathematics/Math.h>
#include <gtest/gtest.h>
using namespace shogun;
TEST(SGVectorTest,ctor)
{
SGVector<float64_t> a(10);
EXPECT_EQ(a.vlen, 10);
a.zero();
for (int i=0; i < 10; ++i)
EXPECT_EQ(0, a[i]);
a.set_const(3.3);
for (int i=0; i < 10; ++i)
EXPECT_EQ(3.3, a[i]);
float64_t* a_clone = SGVector<float64_t>::clone_vector(a.vector, a.vlen);
for (int i=0; i < 10; ++i)
EXPECT_EQ(a_clone[i], a[i]);
SGVector<float64_t> b(a_clone, 10);
EXPECT_EQ(b.vlen, 10);
for (int i=0; i < 10; ++i)
EXPECT_EQ(b[i], a[i]);
/* test copy ctor */
SGVector<float64_t> c(b);
EXPECT_EQ(c.vlen, b.vlen);
for (int i=0; i < c.vlen; ++i)
EXPECT_EQ(b[i], c[i]);
}
TEST(SGVectorTest,setget)
{
SGVector<index_t> v(4);
v[0]=12;
v[1]=1;
v[2]=7;
v[3]=9;
EXPECT_EQ(v[0], 12);
EXPECT_EQ(v[1], 1);
EXPECT_EQ(v[2], 7);
EXPECT_EQ(v[3], 9);
v.set_element(3,0);
v.set_element(2,1);
v.set_element(1,2);
v.set_element(0,3);
EXPECT_EQ(v[0], 3);
EXPECT_EQ(v[1], 2);
EXPECT_EQ(v[2], 1);
EXPECT_EQ(v[3], 0);
}
TEST(SGVectorTest,add)
{
SGVector<float64_t> a(10);
SGVector<float64_t> b(10);
a.random(0.0, 1024.0);
b.random(0.0, 1024.0);
float64_t* b_clone = SGVector<float64_t>::clone_vector(b.vector, b.vlen);
SGVector<float64_t> c(b_clone, 10);
c.add(a);
for (int i=0; i < c.vlen; ++i)
EXPECT_EQ(c[i], a[i]+b[i]);
c = a + a;
EXPECT_EQ(c.vlen, 10);
for (int i=0; i < c.vlen; ++i)
EXPECT_EQ(c[i], 2*a[i]);
}
TEST(SGVectorTest,dot)
{
SGVector<float64_t> a(10);
a.random(0.0, 1024.0);
float64_t dot_val = 0.0;
for (int32_t i = 0; i < a.vlen; ++i)
dot_val += a[i]*a[i];
float64_t error = CMath::abs (dot_val - a.dot(a.vector,a.vector, a.vlen));
EXPECT_TRUE(error < 10E-10);
}
TEST(SGVectorTest,norm)
{
SGVector<float64_t> a(10);
a.random(-50.0, 1024.0);
/* check l-2 norm */
float64_t l2_norm = CMath::sqrt(a.dot(a.vector,a.vector, a.vlen));
float64_t error = CMath::abs(l2_norm - SGVector<float64_t>::twonorm(a.vector, a.vlen));
EXPECT_TRUE(error < 10E-12);
float64_t l1_norm = 0.0;
for (int32_t i = 0; i < a.vlen; ++i)
l1_norm += CMath::abs(a[i]);
EXPECT_EQ(l1_norm, SGVector<float64_t>::onenorm(a.vector, a.vlen));
SGVector<float64_t> b(10);
b.set_const(1.0);
EXPECT_EQ(10.0,SGVector<float64_t>::qsq(b.vector, b.vlen, 0.5));
EXPECT_EQ(100,SGVector<float64_t>::qnorm(b.vector, b.vlen, 0.5));
}
TEST(SGVectorTest,misc)
{
SGVector<float64_t> a(10);
a.random(-1024.0, 1024.0);
/* test, min, max, sum */
int arg_max = 0, arg_max_abs = 0;
float64_t min = 1025, max = -1025, sum = 0.0, max_abs = -1, sum_abs = 0.0;
for (int32_t i = 0; i < a.vlen; ++i)
{
sum += a[i];
sum_abs += CMath::abs(a[i]);
if (CMath::abs(a[i]) > max_abs)
{
max_abs = CMath::abs(a[i]);
arg_max_abs=i;
}
if (a[i] > max)
{
max = a[i];
arg_max=i;
}
if (a[i] < min)
min = a[i];
}
EXPECT_EQ(min, SGVector<float64_t>::min(a.vector,a.vlen));
EXPECT_EQ(max, SGVector<float64_t>::max(a.vector,a.vlen));
EXPECT_EQ(arg_max, SGVector<float64_t>::arg_max(a.vector,1, a.vlen, NULL));
EXPECT_EQ(max_abs, SGVector<float64_t>::max_abs(a.vector,a.vlen));
EXPECT_EQ(arg_max_abs, SGVector<float64_t>::arg_max_abs(a.vector, 1, a.vlen, NULL));
EXPECT_EQ(sum, SGVector<float64_t>::sum(a.vector,a.vlen));
EXPECT_DOUBLE_EQ(sum_abs, SGVector<float64_t>::sum_abs(a.vector, a.vlen));
/* test ::vector_multiply(...) */
SGVector<float64_t> c(10);
SGVector<float64_t>::vector_multiply(c.vector, a.vector, a.vector, a.vlen);
for (int32_t i = 0; i < c.vlen; ++i)
EXPECT_EQ(c[i], a[i]*a[i]);
/* test ::add(...) */
SGVector<float64_t>::add(c.vector, 1.5, a.vector, 1.3, a.vector, a.vlen);
for (int32_t i = 0; i < a.vlen; ++i)
EXPECT_EQ(c[i],1.5*a[i]+1.3*a[i]);
/* tests ::add_scalar */
SGVector<float64_t>::scale_vector(-1.0,a.vector, a.vlen);
float64_t* a_clone = SGVector<float64_t>::clone_vector(a.vector, a.vlen);
SGVector<float64_t> b(a_clone, 10);
SGVector<float64_t>::add_scalar(1.1, b.vector, b.vlen);
for (int32_t i = 0; i < b.vlen; ++i)
EXPECT_EQ(b[i],a[i]+1.1);
float64_t* b_clone = SGVector<float64_t>::clone_vector(b.vector, b.vlen);
SGVector<float64_t> d(b_clone, b.vlen);
SGVector<float64_t>::vec1_plus_scalar_times_vec2(d.vector, 1.3, d.vector, b.vlen);
for (int32_t i = 0; i < d.vlen; ++i)
EXPECT_DOUBLE_EQ(d[i],b[i]+1.3*b[i]);
}
| [
"mmkaouer@umich.edu"
] | mmkaouer@umich.edu |
4dff1d1e63c2d0b0b756f2fc0b60aab6467af8b5 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14022/function14022_schedule_26/function14022_schedule_26.cpp | 05050c4a5c6f0436a777f17c516044e64ba734fa | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,001 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14022_schedule_26");
constant c0("c0", 64), c1("c1", 64), c2("c2", 64), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i0, i3}, p_int32);
input input01("input01", {i0, i1, i2}, p_int32);
input input02("input02", {i2}, p_int32);
input input03("input03", {i3}, p_int32);
input input04("input04", {i1, i2}, p_int32);
input input05("input05", {i3}, p_int32);
input input06("input06", {i1}, p_int32);
input input07("input07", {i0, i3}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i0, i3) + input01(i0, i1, i2) + input02(i2) - input03(i3) - input04(i1, i2) - input05(i3) * input06(i1) - input07(i0, i3));
comp0.tile(i0, i1, i2, 64, 64, 64, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {64, 64}, p_int32, a_input);
buffer buf01("buf01", {64, 64, 64}, p_int32, a_input);
buffer buf02("buf02", {64}, p_int32, a_input);
buffer buf03("buf03", {64}, p_int32, a_input);
buffer buf04("buf04", {64, 64}, p_int32, a_input);
buffer buf05("buf05", {64}, p_int32, a_input);
buffer buf06("buf06", {64}, p_int32, a_input);
buffer buf07("buf07", {64, 64}, p_int32, a_input);
buffer buf0("buf0", {64, 64, 64, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
input05.store_in(&buf05);
input06.store_in(&buf06);
input07.store_in(&buf07);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf07, &buf0}, "../data/programs/function14022/function14022_schedule_26/function14022_schedule_26.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
5b179989dbb256cd86d5152645627075270027fa | 8a92aa7d9f97269de27489f494e5249505e7645d | /Examen Oct 15/Examen Oct 15/Pizarra.h | 02bf7d4a870b880b6c8612349a13f696fe440275 | [
"MIT"
] | permissive | AlbertoTrapiello/SII-ADOO | 0f5fb098407ad821394d1d73ded1c7490934dab5 | 9a7ba5dcd450c6b6b3e0932f5a62d0be28733bbf | refs/heads/master | 2021-07-23T02:16:32.216387 | 2019-01-23T17:48:22 | 2019-01-23T17:48:22 | 147,925,200 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,154 | h | #ifndef _PIZARRA_
#define _PIZARRA_
#include <vector>
#include <algorithm>
#include "Figura.h"
#include <iostream>
using namespace std;
void listar(Figura *);
class Pizarra
{
vector <Figura *> figuras;
public:
Pizarra() {}
void add_Figuras(Figura * pFigura)
{
figuras.push_back(pFigura);
}
void list()
{
for_each (figuras.begin(), figuras.end(), listar);
}
float sumar_areas()
{
float area = 0;
for (int i = 0; i < figuras.size(); i++)
{
area += figuras[i]->getarea();
cout << "Area " << i << " : " << area << endl;
}
return area;
}
//falta el destructor de Pizarra que es un bucle que delete cada Figura del vector
~Pizarra()//Creo que es así
{
for (int i = 0; i < figuras.size(); i++)
{
delete figuras[i];
}
figuras.clear();
}
};
void listar (Figura * pFig)
{
pFig->list();//debido a que list es polimórfica (viene de la calse abstracta Figuras)
}
//Me tengo que llevar el cout del sistema, que permite que sean polimórficas.
//La solución del examen hace que sean amigas y que por tanto no sean polimórficas, pero ya no necesetas llevar el promt dels sistema (cout creo)
#endif // !_PIZARRA_ | [
"albertotrapiello@gmail.com"
] | albertotrapiello@gmail.com |
c82600d2a4e4175906560b280df15c1a6fb46b16 | 9e4a00de1ec07e7e88872ef60c42a49bf65dc2b0 | /Code/Projects/Eld/src/Components/wbcompeldpowerteleport.h | af89359c3668776fd415dbaf8ad91036d1ae7f8e | [
"Zlib"
] | permissive | ptitSeb/Eldritch | 6a5201949b13f6cd95d3d75928e375bdf785ffca | 3cd6831a4eebb11babec831e2fc59361411ad57f | refs/heads/master | 2021-07-10T18:45:05.892756 | 2021-04-25T14:16:19 | 2021-04-25T14:16:19 | 39,091,718 | 6 | 4 | NOASSERTION | 2021-04-25T14:16:20 | 2015-07-14T18:03:07 | C | UTF-8 | C++ | false | false | 645 | h | #ifndef WBCOMPELDPOWERTELEPORT_H
#define WBCOMPELDPOWERTELEPORT_H
#include "wbeldcomponent.h"
#include "wbentityref.h"
class WBCompEldPowerTeleport : public WBEldComponent
{
public:
WBCompEldPowerTeleport();
virtual ~WBCompEldPowerTeleport();
DEFINE_WBCOMP( EldPowerTeleport, WBEldComponent );
virtual int GetTickOrder() { return ETO_NoTick; }
virtual void HandleEvent( const WBEvent& Event );
virtual uint GetSerializationSize();
virtual void Save( const IDataStream& Stream );
virtual void Load( const IDataStream& Stream );
private:
void TryTeleport() const;
WBEntityRef m_Beacon;
};
#endif // WBCOMPELDPOWERTELEPORT_H
| [
"rajdakin@gmail.com"
] | rajdakin@gmail.com |
8dac4bfecda1e8346415c24268ceb50b16aee35e | 90e64a6679a16401e762b447a0a1c6d7d5815815 | /TSE/SFXVariants.cpp | 2dc0c282b88b54f8cc3f1fa856b7f10f8a65b4b2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | kronosaur/Mammoth | a339f3860e01612c47fdbfc3aa1d657b5fd25a4b | a73df3f356201ecffd6590303d5cd52edd040a92 | refs/heads/master | 2021-04-19T00:26:33.936970 | 2019-01-08T01:11:51 | 2019-01-08T01:11:51 | 28,847,176 | 5 | 14 | NOASSERTION | 2018-12-26T08:09:11 | 2015-01-06T04:47:28 | C++ | UTF-8 | C++ | false | false | 5,710 | cpp | // SFXVariants.cpp
//
// CEffectVariantCreator class
// Copyright (c) 2012 by Kronosaur Productions, LLC. All Rights Reserved.
#include "PreComp.h"
#define MAX_VALUE_ATTRIB CONSTLIT("maxValue")
class CEffectVariantPainter : public IEffectPainter
{
public:
CEffectVariantPainter (CEffectVariantCreator *pCreator);
~CEffectVariantPainter (void);
// IEffectPainter virtuals
virtual CEffectCreator *GetCreator (void) { return m_pCreator; }
virtual void Paint (CG32bitImage &Dest, int x, int y, SViewportPaintCtx &Ctx);
private:
CEffectVariantCreator *m_pCreator;
TArray<CEffectPainterRef> m_Cache;
};
CEffectVariantCreator::CEffectVariantCreator (void)
// CEffectVariantCreator constructor
{
}
CEffectVariantCreator::~CEffectVariantCreator (void)
// CEffectVariantCreator destructor
{
int i;
for (i = 0; i < m_Effects.GetCount(); i++)
delete m_Effects[i].pEffect;
}
CEffectVariantCreator::SEntry *CEffectVariantCreator::ChooseVariant (int iVariantValue, int *retiIndex)
// ChooseVariant
//
// Choose a variant
{
int i;
for (i = 0; i < m_Effects.GetCount() - 1; i++)
{
// If the maxValue property for this effect is less than or equal to
// the variant value, then we choose this effect.
if (iVariantValue <= m_Effects[i].iMaxValue)
{
if (retiIndex)
*retiIndex = i;
return &m_Effects[i];
}
}
// If we get this far then we choose the last effect as a default
if (retiIndex)
*retiIndex = m_Effects.GetCount() - 1;
return &m_Effects[m_Effects.GetCount() - 1];
}
ALERROR CEffectVariantCreator::CreateEffect (CSystem *pSystem,
CSpaceObject *pAnchor,
const CVector &vPos,
const CVector &vVel,
int iRotation,
int iVariant,
ICCItem *pData,
CSpaceObject **retpEffect)
// CreateEffect
//
// Creates an effect object
{
return ChooseVariant(iVariant)->pEffect->CreateEffect(pSystem, pAnchor, vPos, vVel, iRotation, iVariant, pData, retpEffect);
}
IEffectPainter *CEffectVariantCreator::OnCreatePainter (CCreatePainterCtx &Ctx)
// CreatePainter
//
// Creates a painter
{
// For backwards compatibility, if we have a damage descriptor, then we
// create the appropriate variant based on damage.
//
// Newer code should use the <GetParameter> functionality instead of
// variants.
SDamageCtx *pDamageCtx = Ctx.GetDamageCtx();
if (pDamageCtx)
return ChooseVariant(pDamageCtx->iDamage)->pEffect->CreatePainter(Ctx);
// Otherwise, just create us as a variant. This is used in the case of
// shield effects, which paint different variants at runtime.
return new CEffectVariantPainter(this);
}
int CEffectVariantCreator::GetLifetime (void)
// GetLifetime
//
// Returns the lifetime of the effect
{
int iTotalLifetime = 0;
for (int i = 0; i < m_Effects.GetCount(); i++)
{
int iLifetime = m_Effects[i].pEffect->GetLifetime();
if (iLifetime == -1)
{
iTotalLifetime = -1;
break;
}
else if (iLifetime > iTotalLifetime)
iTotalLifetime = iLifetime;
}
return iTotalLifetime;
}
ALERROR CEffectVariantCreator::OnEffectCreateFromXML (SDesignLoadCtx &Ctx, CXMLElement *pDesc, const CString &sUNID)
// OnEffectCreateFromXML
//
// Creates from XML
{
ALERROR error;
int i;
// Allocate the creator array
int iCount = pDesc->GetContentElementCount();
if (iCount == 0)
{
Ctx.sError = CONSTLIT("<Variants> effect must have at least one sub-element.");
return ERR_FAIL;
}
m_Effects.InsertEmpty(iCount);
for (i = 0; i < iCount; i++)
{
CString sSubUNID = strPatternSubst(CONSTLIT("%s/%d"), sUNID, i);
CXMLElement *pCreatorDesc = pDesc->GetContentElement(i);
if (error = CEffectCreator::CreateFromXML(Ctx, pCreatorDesc, sSubUNID, &m_Effects[i].pEffect))
return error;
m_Effects[i].iMaxValue = pCreatorDesc->GetAttributeInteger(MAX_VALUE_ATTRIB);
}
return NOERROR;
}
ALERROR CEffectVariantCreator::OnEffectBindDesign (SDesignLoadCtx &Ctx)
// OnEffectBindDesign
//
// Resolve loading
{
ALERROR error;
for (int i = 0; i < m_Effects.GetCount(); i++)
if (error = m_Effects[i].pEffect->BindDesign(Ctx))
return error;
return NOERROR;
}
void CEffectVariantCreator::OnEffectMarkResources (void)
// OnEffectMarkResources
//
// Mark images used by this effect
{
for (int i = 0; i < m_Effects.GetCount(); i++)
m_Effects[i].pEffect->MarkImages();
}
void CEffectVariantCreator::SetLifetime (int iLifetime)
// SetLifetime
//
// Sets the lifetime
{
for (int i = 0; i < m_Effects.GetCount(); i++)
m_Effects[i].pEffect->SetLifetime(iLifetime);
}
void CEffectVariantCreator::SetVariants (int iVariants)
// SetVariants
//
// Sets the variants
{
for (int i = 0; i < m_Effects.GetCount(); i++)
m_Effects[i].pEffect->SetVariants(iVariants);
}
// CEffectVariantPainter object -----------------------------------------------
CEffectVariantPainter::CEffectVariantPainter (CEffectVariantCreator *pCreator) : m_pCreator(pCreator)
// CEffectVariantPainter constructor
{
m_Cache.InsertEmpty(pCreator->GetVariantCount());
}
CEffectVariantPainter::~CEffectVariantPainter (void)
// CEffectVariantPainter destructor
{
int i;
for (i = 0; i < m_Cache.GetCount(); i++)
m_Cache[i].Delete();
}
void CEffectVariantPainter::Paint (CG32bitImage &Dest, int x, int y, SViewportPaintCtx &Ctx)
// Paint
//
// Paint the effect
{
// Find the appropriate effect
int iIndex = m_pCreator->GetVariantCreatorIndex(Ctx.iVariant);
if (m_Cache[iIndex].IsEmpty())
{
CEffectCreator *pCreator = m_pCreator->GetVariantCreator(iIndex);
m_Cache[iIndex].Set(pCreator->CreatePainter(CCreatePainterCtx()));
}
// Paint
m_Cache[iIndex]->Paint(Dest, x, y, Ctx);
}
| [
"public@neurohack.com"
] | public@neurohack.com |
1c15c9e8f37c6d4e065baf9d4fb0e9c82b5df75b | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/InnerDetector/InDetDetDescrCnv/InDetIdCnv/src/SiliconIDDetDescrCnv.h | f27cff6cf5ba3abba289f183bd6a9bb9bd19f225 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,168 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
/***************************************************************************
InDet DetDescrCnv package
-----------------------------------------
***************************************************************************/
//<doc><file> $Id: SiliconIDDetDescrCnv.h,v 1.3 2007-01-01 10:47:18 dquarrie Exp $
//<version> $Name: not supported by cvs2svn $
#ifndef INDETMGRDETDESCRCNV_SILICONIDDETDESCRCNV_H
# define INDETMGRDETDESCRCNV_SILICONIDDETDESCRCNV_H
//<<<<<< INCLUDES >>>>>>
#include "DetDescrCnvSvc/DetDescrConverter.h"
//<<<<<< PUBLIC DEFINES >>>>>>
//<<<<<< PUBLIC CONSTANTS >>>>>>
//<<<<<< PUBLIC TYPES >>>>>>
class SiliconID;
//<<<<<< PUBLIC VARIABLES >>>>>>
//<<<<<< PUBLIC FUNCTIONS >>>>>>
//<<<<<< CLASS DECLARATIONS >>>>>>
/**
** This class is a converter for the SiliconID an IdHelper which is
** stored in the detector store. This class derives from
** DetDescrConverter which is a converter of the DetDescrCnvSvc.
**
**/
class SiliconIDDetDescrCnv: public DetDescrConverter {
friend class CnvFactory<SiliconIDDetDescrCnv>;
public:
virtual long int repSvcType() const;
virtual StatusCode initialize();
virtual StatusCode finalize();
virtual StatusCode createObj(IOpaqueAddress* pAddr, DataObject*& pObj);
// Storage type and class ID (used by CnvFactory)
static long storageType();
static const CLID& classID();
protected:
SiliconIDDetDescrCnv(ISvcLocator* svcloc);
private:
/// The helper - only will create it once
SiliconID* m_siliconId;
};
//<<<<<< INLINE PUBLIC FUNCTIONS >>>>>>
//<<<<<< INLINE MEMBER FUNCTIONS >>>>>>
#endif // INDETMGRDETDESCRCNV_SILICONIDDETDESCRCNV_H
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
5e0381ce4b19fc92faac0abef305439bfcd1c78f | c5f23bc3b0e5b106357f6ef8a403a3ef41cd17d3 | /EventoService/Main.cpp | 8b246766f93166bc9c757af52295daf777a2e86e | [] | no_license | twolkerl/ed_fadergs | 0f691f4b50a1ea9bdb65a5cae16c84e85a18ddb5 | b0dea680debe0aca63958e2cb3268f6f525f6d5f | refs/heads/master | 2021-09-07T21:49:16.870022 | 2018-03-01T14:31:34 | 2018-03-01T14:31:34 | 108,329,943 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,656 | cpp | /*
ESTRUTURA DE DADOS 2017/2
Autores: Tiago Wolker Leite / Eduardo Moraes de Mello Alves / Bruno Vicente Alves
Data: 05/11/2017
Última atualização: 03/12/2017
Sistema EventoService.
*/
// -- BIBLIOTECAS --
#include "controller/EventoServiceFuncoes.h"
//#include "controller/FuncoesTeste.h" // retirar as barras para utilizar as funções de teste
// -- CONSTANTES --
// -- PROGRAMA PRINCIPAL --
main() {
setlocale(LC_ALL, "portuguese");
ListaEventos *listaEventos = NULL, *filaReclamacoes = NULL, *pilhaComentarios = NULL, *eventosAtendidos = NULL;
int opcao;
do {
switch (opcao = menu_principal()) {
case 1:
// Cadastrar evento
cadastrar_evento(&listaEventos);
break;
case 2:
// Encaminhar eventos
encaminhar_eventos(&listaEventos, &filaReclamacoes, &pilhaComentarios);
break;
case 3:
// Apresentar eventos
apresentar_evento(listaEventos, filaReclamacoes, pilhaComentarios, eventosAtendidos);
break;
case 4:
// Consumir eventos
menu_consumir_eventos(&filaReclamacoes, &pilhaComentarios, &eventosAtendidos);
break;
case 5:
// Informações eventos
menu_info_eventos(listaEventos, filaReclamacoes, pilhaComentarios, eventosAtendidos);
break;
// case 100: // Função para testar
// cad_dez(&listaEventos, RECLAMACAO);
// cad_dez(&filaReclamacoes, RECLAMACAO);
// cad_dez(&pilhaComentarios, COMENTARIO);
// break;
case 0:
// Sair
printf("Sistema encerrado...\n");
break;
default:
// Inválido
printf("Opção inválida...\n");
}
printf("\n");
system("pause");
system("cls");
} while (opcao != 0);
}
| [
"tiago.wolker.leite@gmail.com"
] | tiago.wolker.leite@gmail.com |
ef77306c4ae217be8167f9cbdd0c873dd53d0011 | 91285aab23d96d1594dec160f8eada42feb99493 | /Course Project/2011 Rocky Mountain Regional Contest/5740 complete/5740.cpp | 843b6b3beca974d985b5c6250c7fc7ec892dd5f8 | [] | no_license | TylerSiwy/Programming-Contest-Solutions | b2d3daf5115999cf54e6c9e0d63a9610715f2142 | e504d3da99fd6033003881a6e130256abecd1393 | refs/heads/master | 2022-12-19T06:33:39.659786 | 2020-09-23T22:40:39 | 2020-09-23T22:40:39 | 296,226,915 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,221 | cpp | // Author: Tyler Siwy
// Date: March 6, 2020
// Approach: Fill a vector of our range with 0's. Then index using our
// citizenshipDay to fill in 1's for residence days and 2's for landing days.
// For each vacation trip, add 0's in the appropriate indices This allows us to
// count half days since once we count the array we simply divide by 2. If we
// haven't found the answer, offset the next check by the difference between the
// count and 1095.
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using namespace std::rel_ops;
struct Date {
int yyyy;
int mm;
int dd;
// no dates before 1753
static int const BASE_YEAR = 1753;
// Enumerated type for names of the days of the week
enum dayName { SUN, MON, TUE, WED, THU, FRI, SAT };
// Is a date valid
static bool validDate(int yr, int mon, int day) {
return yr >= BASE_YEAR && mon >= 1 && mon <= 12 && day > 0 &&
day <= daysIn(mon, yr);
}
bool isValid() const { return validDate(yyyy, mm, dd); }
// Constructor to create a specific date. If the date is invalid,
// the behaviour is undefined
Date(int yr = 1970, int mon = 1, int day = 1) {
yyyy = yr;
mm = mon;
dd = day;
}
// Returns the day of the week for this
dayName dayOfWeek() const {
int a = (14 - mm) / 12;
int y = yyyy - a;
int m = mm + 12 * a - 2;
return (dayName)((dd + y + y / 4 - y / 100 + y / 400 + 31 * m / 12) % 7);
}
// comparison operators
bool operator==(const Date &d) const {
return dd == d.dd && mm == d.mm && yyyy == d.yyyy;
}
bool operator<(const Date &d) const {
return yyyy < d.yyyy || (yyyy == d.yyyy && mm < d.mm) ||
(yyyy == d.yyyy && mm == d.mm && dd < d.dd);
}
// Returns true if yr is a leap year
static bool leapYear(int y) {
return (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0));
}
// number of days in this month
static int daysIn(int m, int y) {
switch (m) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (leapYear(y)) {
return 29;
} else {
return 28;
}
default:
return 31;
}
}
void addDay(int n = 1) {
dd += n;
while (dd > daysIn(mm, yyyy)) {
dd -= daysIn(mm, yyyy);
if (++mm > 12) {
mm = 1;
yyyy++;
}
}
while (dd < 1) {
if (--mm < 1) {
mm = 12;
yyyy--;
}
dd += daysIn(mm, yyyy);
}
}
// add n months to the date: complexity is about n/12 iterations
void addMonth(int n = 1) {
mm += n;
while (mm > 12) {
mm -= 12;
yyyy++;
}
while (mm < 1) {
mm += 12;
yyyy--;
}
if (dd > daysIn(mm, yyyy)) {
dd = daysIn(mm, yyyy);
}
}
// add n years to the date
void addYear(int n = 1) {
yyyy += n;
if (!leapYear(yyyy) && mm == 2 && dd == 29) {
dd = 28;
}
}
// number of days since 1753/01/01, including the current date
int dFSt() const {
int c = 0;
Date d(BASE_YEAR, 1, 1);
Date d2(d);
d2.addYear(1);
while (d2 < *this) {
c += leapYear(d.yyyy) ? 366 : 365;
d = d2;
d2.addYear(1);
}
d2 = d;
d2.addMonth(1);
while (d2 < *this) {
c += daysIn(d.mm, d.yyyy);
d = d2;
d2.addMonth(1);
}
while (d <= *this) {
d.addDay();
c++;
}
return c;
}
};
// Reads a date in yyyy/mm/dd format, assumes date is valid and in the
// right format
istream &operator>>(istream &is, Date &d) {
char c;
return is >> d.mm >> c >> d.dd >> c >> d.yyyy;
}
// print date in yyyy/mm/dd format
ostream &operator<<(ostream &os, const Date &d) {
os << d.mm << '/' << d.dd << '/' << d.yyyy;
return os;
}
int check(const Date &residenceD, const Date &landDay, Date citizenshipDay,
vector<pair<Date, Date>> &trips);
int main() {
Date residenceD;
while (cin >> residenceD && cin) {
// Preprocess input
Date landD;
cin >> landD;
int travels;
cin >> travels;
vector<pair<Date, Date>> trips;
for (int i = 0; i < travels; i++) {
Date d1, d2;
cin >> d1 >> d2;
trips.push_back(make_pair(d1, d2));
}
Date citizenshipDay = landD;
// Try best case scenario first
citizenshipDay.addDay(1095 - (((landD.dFSt() - residenceD.dFSt()) / 2)));
// Used to offset our day for the next iteration since we know that we will
// have to increase by at least our difference.
int daysLeft = 0;
while (true) {
daysLeft = check(residenceD, landD, citizenshipDay, trips);
if (daysLeft <= 0)
break;
// Skip ahead to the next possible case by adding the daysLeft
citizenshipDay.addDay(daysLeft);
}
cout << citizenshipDay << endl;
}
return 0;
}
int check(const Date &residenceD, const Date &landDay, Date citizenshipDay,
vector<pair<Date, Date>> &trips) {
vector<int> days(1460, 0);
Date startDate = citizenshipDay;
startDate.addDay(-1460);
int landingDate = landDay.dFSt() - startDate.dFSt();
int residenceDate = residenceD.dFSt() - startDate.dFSt();
// Fill the graph with days at 1 and 2 for residence days and landing days
for (int i = max(residenceDate, 0); i < days.size(); i++) {
if (i < landingDate)
days[i] = 1;
else
days[i] = 2;
}
// Process trips
for (auto t : trips) {
int start = t.first.dFSt() - startDate.dFSt();
int end = t.second.dFSt() - startDate.dFSt();
if (start < 0) {
// If both sides are too small, disregard this case
if (end < 0)
continue;
start = 0;
}
if (end >= days.size()) {
// If both sides are too large, disregard this case
if (start > days.size())
continue;
end = days.size() - 1;
}
// Add our zeros for the vacation dates at our valid date locations
for (int i = start; i <= end; i++)
days.at(i) = 0;
}
int count = 0;
// Count the values in the int array, divide by 2 to account for half days in
// the residence period.
for (unsigned int i = 0; i < days.size(); i++)
count += days.at(i);
count /= 2;
return 1095 - count;
}
| [
"tyler.siwy@outlook.com"
] | tyler.siwy@outlook.com |
a6fd813e013c0f7079de150f18682eaef114a6b3 | ce7027f75f1dfdf603145eb1eb32aefbb7a43ece | /contrib/rpl/rgtl/rgtl_octree_objects.h | 024845977087bfda55029c772465f920259dc968 | [
"BSL-1.0"
] | permissive | InsightSoftwareConsortium/vxl | e85d26d63c4ccbba447b533456feb1df74768817 | e26938b1673f862b6681104dd4b94352e5990df0 | refs/heads/master | 2021-01-22T11:54:37.895936 | 2018-02-09T05:01:32 | 2018-02-09T05:01:32 | 46,090,490 | 0 | 2 | null | 2016-05-06T21:49:15 | 2015-11-13T00:52:35 | C++ | UTF-8 | C++ | false | false | 3,717 | h | #ifndef rgtl_octree_objects_h
#define rgtl_octree_objects_h
//:
// \file
// \brief Store a set of objects in an octree for efficient spatial queries.
// \author Brad King
// \date March 2007
// \copyright
// Copyright 2006-2009 Brad King, Chuck Stewart
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file rgtl_license_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
#include <vector>
#include <vcl_compiler.h>
class rgtl_serialize_access;
template <unsigned int D> class rgtl_octree_cell_bounds;
template <unsigned int D> class rgtl_object_array;
template <unsigned int D> class rgtl_octree_objects_internal;
//: Store a fixed set of objects in a spatial structure for efficient lookup.
//
// Given an array of objects with a few basic operations defined by
// rgtl_object_array, stores the objects in an efficient octree-based
// spatial structure. The structure supports several spatial queries
// on the set of objects. It features a distance transform that
// efficiently pre-computes distances from all octree leaf centers to
// their nearest object points. This is used to significantly reduce
// the initial sphere radius for closest object queries.
template <unsigned int D>
class rgtl_octree_objects
{
public:
typedef rgtl_object_array<D> object_array_type;
typedef rgtl_octree_cell_bounds<D> bounds_type;
//: Construct with a set of objects, the region of interest, and a maximum subdivision level.
rgtl_octree_objects(object_array_type const& objs,
bounds_type const& b, int ml);
//: Default constructor should be used only just before loading a previously serialized instance.
rgtl_octree_objects(object_array_type const& oa);
//: Destruct.
~rgtl_octree_objects();
//: Query the given hyper-sphere for objects its volume intersects.
// Returns the number of objects found.
int query_sphere(double const center[D], double radius,
std::vector<int>& ids) const;
//: Query the given object for other objects its volume intersects.
// Returns the number of objects found. Note that the given id is
// treated opaquely and passed back to the object_intersects_box
// and object_intersects_object callbacks. It may therefore be out
// of range which is useful in querying the objects with another
// object not in the set.
int query_object(int id, std::vector<int>& ids) const;
//: Query the k closest objects to the given point.
// Returns the number of objects found. Any combination of the object ids,
// squared distances, and closest point locations may be obtained.
// Pass null pointers to for the results not desired. If a
// non-negative value is given for bound_squared no objects outside
// the squared distance bound will be returned. This optionally
// limits the search to a user-specified sphere.
int query_closest(double const p[D], int k, int* ids,
double* squared_distances, double* points,
double bound_squared = -1) const;
//: Compute the nth-order distance transform on the leaf cell centers.
// This speeds up query_closest for query points inside the
// bounds and k<=n by providing a smaller initial bound.
bool compute_distance_transform(int n = 1) const;
//: Enable/Disable query_closest debug output if support is compiled in.
void set_query_closest_debug(bool b);
private:
// Internal implementation details.
typedef rgtl_octree_objects_internal<D> internal_type;
internal_type* internal_;
friend class rgtl_serialize_access;
template <class Serializer> void serialize(Serializer& sr);
};
#endif // rgtl_octree_objects_h
| [
"dan@visionsystemsinc.com"
] | dan@visionsystemsinc.com |
6ff6c622a6381ed5f2cc40911b56eae63aabfe1d | 60bb67415a192d0c421719de7822c1819d5ba7ac | /blazetest/src/mathtest/dvecsvecmult/VHaVCa.cpp | 414103e0b4064e518eba29edf01e99322ac419e0 | [
"BSD-3-Clause"
] | permissive | rtohid/blaze | 48decd51395d912730add9bc0d19e617ecae8624 | 7852d9e22aeb89b907cb878c28d6ca75e5528431 | refs/heads/master | 2020-04-16T16:48:03.915504 | 2018-12-19T20:29:42 | 2018-12-19T20:29:42 | 165,750,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,004 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dvecsvecmult/VHaVCa.cpp
// \brief Source file for the VHaVCa dense vector/sparse vector multiplication math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/HybridVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecsvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHaVCa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Vector type definitions
using VHa = blaze::HybridVector<TypeA,128UL>;
using VCa = blaze::CompressedVector<TypeA>;
// Creator type definitions
using CVHa = blazetest::Creator<VHa>;
using CVCa = blazetest::Creator<VCa>;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_DVECSVECMULT_OPERATION_TEST( CVHa( i ), CVCa( i, j ) );
}
}
// Running tests with large vectors
RUN_DVECSVECMULT_OPERATION_TEST( CVHa( 127UL ), CVCa( 127UL, 13UL ) );
RUN_DVECSVECMULT_OPERATION_TEST( CVHa( 128UL ), CVCa( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/sparse vector multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
3fe2da53f03302dcf748b30bc689f1df1973d431 | 1a2190b96ca17719d2b41a5fbcac6043cf9f08e4 | /Treinos/2012-10-11-PacNW2011/h.cpp | 2ea8ee5b51b00246a3966639e3c23ee5367250bd | [] | no_license | eliasm2/problem-solving | 13c1abbf397bb41683fccb3490b0113c36ce9010 | 15becf49315b5defb8c1267e0c43ce1579dcae1a | refs/heads/master | 2020-09-07T07:12:17.112311 | 2018-07-20T17:27:43 | 2018-07-20T17:27:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | #include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
double a, b, c, d, m, t;
double f(double x){
return a * pow(x, 3.0) + b * pow(x, 2.0) + c * pow(x, 1.0) + d;
}
int main(){
while (cin >> a >> b >> c >> d >> m >> t) {
double lo = 0.0, hi = 2e9, cnt = 100;
while (cnt--) {
double mid = (lo + hi)/2.0;
if (t < f(mid)*m) {
hi = mid;
} else {
lo = mid;
}
}
printf("%.2lf\n", double(int(lo*100.0))/100.0);
}
return 0;
}
| [
"paulocezar.ufg@gmail.com"
] | paulocezar.ufg@gmail.com |
990172e7ef273a6622cfe8763595e2af7174b420 | d8fae632eea27363db565597decdd1b184f74d70 | /project1/specialtriag.cpp | 46ca5887fe7998c8a36191685b3abc47fd5926ab | [] | no_license | tlgjerberg/fys3150projects | be01cb4f31eb25a78af019df24ae7f8186a6448f | 54a680720f77254a041949db913f9fb929d03933 | refs/heads/master | 2021-07-16T03:51:55.066905 | 2018-12-30T23:17:56 | 2018-12-30T23:17:56 | 145,989,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,047 | cpp | #include <cstdlib>
#include <cmath>
#include <iostream>
#include <fstream>
#include <ctime>
#include <iomanip>
using namespace std;
inline double f( double x){return 100.0*exp(-10*x);} //Analyical function f(x)
//Closed form solution of f
inline double closed_form(double x){return 1 - (1 - exp(-10))*x - exp(-10*x);}
int main(int argc, char* argv[])
{
int n = atoi(argv[1]);
double h = 1.0/double (n+1);
double hh = h*h;
double *d = new double[n+2]; //Declare array for diagonal
double *b = new double[n+2]; //Declare array for right-hand side
double *x = new double[n+2]; //Declare array for x to be used in function f
double *a = new double[n+1]; //Declare array for elements directly below the diagonal
double *c = new double[n+1];
double *f_cf = new double[n+2];
double *u = new double[n+2];
double temp;
//Setting start and endpoints
x[0] = 0; x[n+1] = 1; b[0] = b[n+2] = 0; a[0] = 0; c[0] = 0; d[0] = d[n+2] = 0;
f_cf[0] = f_cf[n+2] = 0; u[0] = u[n+2] = 0;
// Compute arrays that have been declared.
for (int i = 1; i < n+2; i++){
x[i] = i*h;
b[i] = hh*f(x[i]);
f_cf[i] = closed_form(x[i]);
d[i] = 2;
}
clock_t c_start = clock(); //CPU time clock start
//Gaussian elimination start
for (int i = 2; i < n+2; i++){
temp = 1/d[i-1];
d[i] = d[i] - temp;
b[i] = b[i] + b[i-1]*temp;
}
for (int j = n; j > 0; j--){
u[j] = (b[j] - ((-1)*u[j+1]))/d[j];
}
clock_t c_end = clock(); //CPU time clock stop
ofstream tfile; //Setting up file for time output
//Writing n and CPU-time in milliseconds to file for each run of the program
tfile.open("time1b.txt", ofstream::app);
tfile << n << " " << 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << endl;
tfile.close()
cout << fixed << setprecision(2) << "CPU time used: "
<< 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << " ms\n";
// Printing x, numerical and analytical to file
ofstream ofile;
char *sol_array;
ofile.open("sol_array.txt");
for (int i = 0; i < n+2; i++)
{
ofile << x[i] << " " << u[i] << " " << f_cf[i] << endl;
}
ofile.close();
return 0;
}
| [
"torgje@hotmail.com"
] | torgje@hotmail.com |
c14c71ba2c5992a7cec05efdaa52c03880dfd278 | 65d7680ef26b5ddfcbf0ca9a22e71dfa8c755e20 | /LCS Dynamic Programming/LCS Dynamic Programming/LCS Dynamic Programming.cpp | 39423325dd5643320da995466f0c4645274f63a0 | [] | no_license | Virato913/Analisis_y_algoritmos | c0fee3fea7883bf4b7ea3cc555b8d02ce4dda1eb | abb623ef13a7e5d3888c62f863cdbeaffaca259c | refs/heads/master | 2020-05-18T21:06:09.786231 | 2019-08-15T20:25:58 | 2019-08-15T20:25:58 | 184,650,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | #include <vector>
#include <iostream>
#include <cmath>
#include <chrono>
void lcs(std::string X, std::string Y, unsigned int m, unsigned int n) {
std::vector<std::vector<unsigned int>> L(0);
L.resize(m + 1);
for(auto& it : L) {
it.resize(n + 1);
}
for(unsigned int i = 0; i < m + 1; ++i) {
for(unsigned int j = 0; j < n + 1; ++j) {
if(i == 0 || j == 0) {
L[i][j] = 0;
}
else {
if(X[i - 1] == Y[j - 1]) {
L[i][j] = L[i - 1][j - 1] + 1;
}
else {
L[i][j] = static_cast<unsigned int>(std::fmax(L[i - 1][j], L[i][j - 1]));
}
}
}
}
unsigned int index = L[m][n];
std::string lcs("");
lcs.resize(index + 1);
unsigned int i = m;
unsigned int j = n;
while((i > 0) && (j > 0)) {
if(X[i - 1] == Y[j - 1]) {
lcs[index - 1] = X[i - 1];
--i;
--j;
--index;
}
else {
if(L[i - 1][j] > L[i][j - 1]) {
--i;
}
else {
--j;
}
}
}
std::cout << "La subsecuencia mas larga comun de " <<
X.c_str() << " y de " << Y.c_str() << " es " << lcs.c_str() << std::endl;
}
int main() {
std::string X("TTCGCATCGGGTTG");
std::string Y("TGACCGTGTGTCACG");
std::chrono::time_point<std::chrono::steady_clock> start =
std::chrono::high_resolution_clock::now();
std::cout << "---Dynamic Programming---" << std::endl;
lcs(X, Y, X.size(), Y.size());
std::chrono::time_point<std::chrono::steady_clock> end =
std::chrono::high_resolution_clock::now();
std::cout << "Terminado en: " <<
std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / 1e+9 <<
" segundos." << std::endl;
return 0;
}
| [
"idv16c.jvilla@uartesdigitales.edu.mx"
] | idv16c.jvilla@uartesdigitales.edu.mx |
31b0f59c5ff582acc1325e578bf5ec517f9dd984 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Runtime/D3D12RHI/Private/D3D12VertexDeclaration.cpp | c00b8e02d4102177bb747a4f456d85f652180022 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 6,482 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
D3D12VertexDeclaration.cpp: D3D vertex declaration RHI implementation.
=============================================================================*/
#include "D3D12RHIPrivate.h"
/**
* Key used to look up vertex declarations in the cache.
*/
struct FD3D12VertexDeclarationKey
{
/** Vertex elements in the declaration. */
FD3D12VertexElements VertexElements;
/** Hash of the vertex elements. */
uint32 Hash;
uint16 StreamStrides[MaxVertexElementCount];
/** Initialization constructor. */
explicit FD3D12VertexDeclarationKey(const FVertexDeclarationElementList& InElements)
{
uint16 UsedStreamsMask = 0;
FMemory::Memzero(StreamStrides);
for (int32 ElementIndex = 0; ElementIndex < InElements.Num(); ElementIndex++)
{
const FVertexElement& Element = InElements[ElementIndex];
D3D12_INPUT_ELEMENT_DESC D3DElement = { 0 };
D3DElement.InputSlot = Element.StreamIndex;
D3DElement.AlignedByteOffset = Element.Offset;
switch (Element.Type)
{
case VET_Float1: D3DElement.Format = DXGI_FORMAT_R32_FLOAT; break;
case VET_Float2: D3DElement.Format = DXGI_FORMAT_R32G32_FLOAT; break;
case VET_Float3: D3DElement.Format = DXGI_FORMAT_R32G32B32_FLOAT; break;
case VET_Float4: D3DElement.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break;
case VET_PackedNormal: D3DElement.Format = DXGI_FORMAT_R8G8B8A8_UNORM; break; //TODO: uint32 doesn't work because D3D12 squishes it to 0 in the IA-VS conversion
case VET_UByte4: D3DElement.Format = DXGI_FORMAT_R8G8B8A8_UINT; break; //TODO: SINT, blendindices
case VET_UByte4N: D3DElement.Format = DXGI_FORMAT_R8G8B8A8_UNORM; break;
case VET_Color: D3DElement.Format = DXGI_FORMAT_B8G8R8A8_UNORM; break;
case VET_Short2: D3DElement.Format = DXGI_FORMAT_R16G16_SINT; break;
case VET_Short4: D3DElement.Format = DXGI_FORMAT_R16G16B16A16_SINT; break;
case VET_Short2N: D3DElement.Format = DXGI_FORMAT_R16G16_SNORM; break;
case VET_Half2: D3DElement.Format = DXGI_FORMAT_R16G16_FLOAT; break;
case VET_Half4: D3DElement.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; break;
case VET_Short4N: D3DElement.Format = DXGI_FORMAT_R16G16B16A16_SNORM; break;
case VET_UShort2: D3DElement.Format = DXGI_FORMAT_R16G16_UINT; break;
case VET_UShort4: D3DElement.Format = DXGI_FORMAT_R16G16B16A16_UINT; break;
case VET_UShort2N: D3DElement.Format = DXGI_FORMAT_R16G16_UNORM; break;
case VET_UShort4N: D3DElement.Format = DXGI_FORMAT_R16G16B16A16_UNORM; break;
case VET_URGB10A2N: D3DElement.Format = DXGI_FORMAT_R10G10B10A2_UNORM; break;
default: UE_LOG(LogD3D12RHI, Fatal, TEXT("Unknown RHI vertex element type %u"), (uint8)InElements[ElementIndex].Type);
};
D3DElement.SemanticName = "ATTRIBUTE";
D3DElement.SemanticIndex = Element.AttributeIndex;
D3DElement.InputSlotClass = Element.bUseInstanceIndex ? D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA : D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
// This is a divisor to apply to the instance index used to read from this stream.
D3DElement.InstanceDataStepRate = Element.bUseInstanceIndex ? 1 : 0;
if ((UsedStreamsMask & 1 << Element.StreamIndex) != 0)
{
ensure(StreamStrides[Element.StreamIndex] == Element.Stride);
}
else
{
UsedStreamsMask = UsedStreamsMask | (1 << Element.StreamIndex);
StreamStrides[Element.StreamIndex] = Element.Stride;
}
VertexElements.Add(D3DElement);
}
// Sort by stream then offset.
struct FCompareDesc
{
FORCEINLINE bool operator()(const D3D12_INPUT_ELEMENT_DESC& A, const D3D12_INPUT_ELEMENT_DESC &B) const
{
return ((int32)A.AlignedByteOffset + A.InputSlot * MAX_uint16) < ((int32)B.AlignedByteOffset + B.InputSlot * MAX_uint16);
}
};
Sort(VertexElements.GetData(), VertexElements.Num(), FCompareDesc());
// Hash once.
Hash = FCrc::MemCrc_DEPRECATED(VertexElements.GetData(), VertexElements.Num()*sizeof(D3D12_INPUT_ELEMENT_DESC));
Hash = FCrc::MemCrc_DEPRECATED(StreamStrides, sizeof(StreamStrides), Hash);
}
};
/** Hashes the array of D3D12 vertex element descriptions. */
uint32 GetTypeHash(const FD3D12VertexDeclarationKey& Key)
{
return Key.Hash;
}
/** Compare two vertex declaration keys. */
bool operator==(const FD3D12VertexDeclarationKey& A, const FD3D12VertexDeclarationKey& B)
{
return A.VertexElements == B.VertexElements;
}
/** Global cache of vertex declarations. */
struct FVertexDeclarationCache
{
FORCEINLINE FVertexDeclarationRHIRef* Find(FD3D12VertexDeclarationKey Key)
{
FScopeLock RWGuard(&LockGuard);
return Cache.Find(Key);
}
FORCEINLINE FVertexDeclarationRHIRef& Add(const FD3D12VertexDeclarationKey& InKey, const FVertexDeclarationRHIRef& InValue)
{
FScopeLock RWGuard(&LockGuard);
return Cache.Add(InKey, InValue);
}
FORCEINLINE FVertexDeclarationRHIRef* FindOrAdd(const FD3D12VertexDeclarationKey& InKey, const FVertexDeclarationRHIRef& InValue)
{
FScopeLock RWGuard(&LockGuard);
FVertexDeclarationRHIRef* VertexDeclarationRefPtr = Cache.Find(InKey);
if (VertexDeclarationRefPtr == nullptr)
{
VertexDeclarationRefPtr = &Cache.Add(InKey, InValue);
}
return VertexDeclarationRefPtr;
}
FCriticalSection LockGuard;
TMap<FD3D12VertexDeclarationKey, FVertexDeclarationRHIRef> Cache;
};
FVertexDeclarationCache GVertexDeclarationCache;
FVertexDeclarationRHIRef FD3D12DynamicRHI::CreateVertexDeclaration_RenderThread(class FRHICommandListImmediate& RHICmdList, const FVertexDeclarationElementList& Elements)
{
return GDynamicRHI->RHICreateVertexDeclaration(Elements);
}
FVertexDeclarationRHIRef FD3D12DynamicRHI::RHICreateVertexDeclaration(const FVertexDeclarationElementList& Elements)
{
// Construct a key from the elements.
FD3D12VertexDeclarationKey Key(Elements);
// Check for a cached vertex declaration. Add to the cache if it doesn't exist.
FVertexDeclarationRHIRef* VertexDeclarationRefPtr = GVertexDeclarationCache.FindOrAdd(Key, new FD3D12VertexDeclaration(Key.VertexElements, Key.StreamStrides));
// The cached declaration must match the input declaration!
check(VertexDeclarationRefPtr);
check(IsValidRef(*VertexDeclarationRefPtr));
FD3D12VertexDeclaration* D3D12VertexDeclaration = (FD3D12VertexDeclaration*)VertexDeclarationRefPtr->GetReference();
checkSlow(D3D12VertexDeclaration->VertexElements == Key.VertexElements);
return *VertexDeclarationRefPtr;
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
3bb37912ba10096330f0af997ae2a0d8b656ecf8 | 791c27e89ac6c51709bc996ab4a66742573a489d | /BOJ/3055.cpp | 3d16e64d77f8f88251f1c5682e0a2fe872c01966 | [] | no_license | JeongYeonUk/Problem | 6f031abed61c6229f3da86c20b188fc4481ed46d | 12ff42c72e0c91ab4a2927f17c874d791362530d | refs/heads/master | 2021-06-27T10:51:52.409707 | 2020-12-14T15:48:31 | 2020-12-14T15:48:31 | 188,515,199 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,009 | cpp | #include <iostream>
#include <queue>
#include <cstring>
using namespace std;
#define endl '\n'
typedef long long ll;
const int INF = 987654321;
const int dx[] = { 1,0,-1,0 };
const int dy[] = { 0,1,0,-1 };
struct INFO {
int y, x;
};
int r, c;
INFO start, dest;
queue<INFO> river;
char map[50][50];
int cache[50][50];
int bfs() {
queue<INFO> mole;
mole.push(start);
cache[start.y][start.x] = 1;
int riverSize, moleSize;
while (!mole.empty()) {
riverSize = (int)river.size();
for (int i = 0; i < riverSize; ++i) {
INFO cur = river.front(); river.pop();
for (int dir = 0; dir < 4; ++dir) {
INFO next;
next.y = cur.y + dy[dir];
next.x = cur.x + dx[dir];
if (next.y < 0 || next.x < 0 || next.x >= c || next.y >= r) {
continue;
}
if (map[next.y][next.x] == '.') {
map[next.y][next.x] = '*';
river.push({ next.y, next.x });
}
}
}
moleSize = mole.size();
for (int i = 0; i < moleSize; ++i) {
INFO cur = mole.front(); mole.pop();
if (map[cur.y][cur.x] == 'D') {
return cache[cur.y][cur.x] - 1;
}
for (int dir = 0; dir < 4; ++dir) {
INFO next;
next.y = cur.y + dy[dir];
next.x = cur.x + dx[dir];
if (next.y < 0 || next.x < 0 || next.x >= c || next.y >= r) {
continue;
}
if (map[next.y][next.x] == '*' || map[next.y][next.x] == 'X') {
continue;
}
if (cache[next.y][next.x] == 0) {
cache[next.y][next.x] = cache[cur.y][cur.x] + 1;
mole.push({ next.y, next.x });
}
}
}
}
return -1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
cin >> r >> c;
for (int y = 0; y < r; ++y) {
for (int x = 0; x < c; ++x) {
cin >> map[y][x];
if (map[y][x] == 'S') {
start = { y,x };
}
else if (map[y][x] == '*') {
river.push({ y,x });
}
else if (map[y][x] == 'D') {
dest = { y,x };
}
}
}
int ret = bfs();
if (ret == -1) {
cout << "KAKTUS" << endl;
}
else {
cout << ret << endl;
}
return 0;
}
| [
"vire3064@gmail.com"
] | vire3064@gmail.com |
a9a103dd59d151cf373b113bce087bbd7f630518 | a283563f58064cb78239dfb12f7efaa77f793b1c | /src/CRandomGenerator.cpp | e6f4f6d12002ff25b1a951a09728871e4ca0c742 | [] | no_license | vadimostanin/libkohonen | eea419bd2e806731625b41153f21ec1a27aeb9e4 | c76e07a6d29fa445a11c1f22e5396d2c91e403fb | refs/heads/master | 2020-06-03T20:43:53.710591 | 2015-08-25T05:51:33 | 2015-08-25T05:51:33 | 41,311,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | /*
* CRandomGenerator.cpp
*
* Created on: Jan 27, 2015
* Author: vostanin
*/
#include "CRandomGenerator.h"
#include <ctime>
#include <cstdlib>
CRandomGenerator::CRandomGenerator( double range_low, double range_high, double range_precision ):
m_Low( range_low ), m_High( range_high ), m_Precision( range_precision )
{
// TODO Auto-generated constructor stub
srand(time(NULL));
}
CRandomGenerator::~CRandomGenerator()
{
// TODO Auto-generated destructor stub
}
double CRandomGenerator::getValue()
{
return ((int)rand()%(int)(1.0/m_Precision))/(float) (1.0/m_Precision) - 0.5;
}
void CRandomGenerator::fillVector( vector<double> & values )
{
size_t values_count = values.size();
for( size_t value_i = 0 ; value_i < values_count ; value_i++ )
{
values[value_i] = getValue();
}
}
| [
"popcorn@bk.ru"
] | popcorn@bk.ru |
c014afdb16ea2c10ded0682ef159bb3c98b9021b | 3407f1d148de3d8087686806eba3d2d5f9f141b4 | /Source/Model.h | 2aaa65edb53bda151c0baf7dc6aa384c4b26456b | [] | no_license | mpue/Trio2 | 379baa0b52d3362cbe32751fc4049bc85146c775 | abef968b684a762d351095f4df75b6a2855aa014 | refs/heads/master | 2021-04-01T14:33:21.650854 | 2020-03-18T09:54:19 | 2020-03-18T09:54:19 | 248,193,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,777 | h | /*
==============================================================================
Model.h
Created: 4 Jun 2016 8:56:23pm
Author: Matthias Pueski
==============================================================================
*/
#ifndef MODEL_H_INCLUDED
#define MODEL_H_INCLUDED
#include "Voice.h"
#include "Filter.h"
#include "MultimodeFilter.h"
#include "ADSR.h"
#include "Oszillator.h"
#include "Sine.h"
#include "MultimodeOscillator.h"
#include "Sequencer.h"
#include "../JuceLibraryCode/JuceHeader.h"
#include <vector>
using namespace std;
class Model : public ChangeBroadcaster, public ChangeListener {
public:
Model();
Model(vector<Voice*> voices, MultimodeFilter* mainFilter, vector <Trio::ADSR*> modEnv, MultimodeOscillator* lfo1, MultimodeOscillator* lfo2, Sequencer* seq, int sampleRate);
~Model();
void changeListenerCallback (ChangeBroadcaster* source) override;
float getOsc1Pitch();
void setOsc1Pitch(int pitch);
float getOsc2Pitch();
void setOsc2Pitch(int pitch);
float getOsc3Pitch();
void setOsc3Pitch(int pitch);
float getOsc1Fine();
void setOsc1Fine(float fine);
float getOsc2Fine();
void setOsc2Fine(float fine);
float getOsc3Fine();
void setOsc3Fine(float fine);
float getOsc1Volume();
void setOsc1Volume(float volume);
float getOsc2Volume();
void setOsc2Volume(float volume);
float getOsc3Volume();
void setOsc3Volume(float volume);
float getAmpEnvAttack();
void setAmpEnvAttack(float attack);
float getAmpEnvDecay();
void setAmpEnvDecay(float decay);
float getAmpEnvSustain();
void setAmpEnvSustain(float sustain);
float getAmpEnvRelease();
void setAmpEnvRelease(float release);
float getFilterEnvAttack(int index);
void setFilterEnvAttack(int index, float attack);
float getFilterEnvDecay(int index);
void setFilterEnvDecay(int index, float decay);
float getFilterEnvSustain(int index);
void setFilterEnvSustain(int index, float sustain);
float getFilterEnvRelease(int index);
void setFilterEnvRelease(int index, float release);
float getFilterCutoff();
void setFilterCutoff(float cutoff);
float getFilterResonance();
void setFilterResonance(float resonance);
float getFilterModAmount();
void setFilterModAmount(float amount);
int getFilterMode();
void setFilterMode(int mode);
float getVolume();
void setVolume(float volume);
float getLfo1Amount();
void setLfo1Amount(float amount);
float getLfo1Rate();
void setLfo1Rate(float rate);
float getLfo2Amount();
void setLfo2Amount(float amount);
float getLfo2Rate();
void setLfo2Rate(float rate);
int getModsource();
void setModsource(int source);
int getMod1Target();
void setMod1Target(int target);
int getMod2Target();
void setMod2Target(int target);
void setEnvelopes(vector<Trio::ADSR*> envelopes);
vector <Trio::ADSR*> getModEnvelopes();
void setFilter(MultimodeFilter* filter);
MultimodeFilter* getFilter();
void setLfo1(MultimodeOscillator* osc);
MultimodeOscillator* getLfo1();
void setLfo2(MultimodeOscillator* osc);
MultimodeOscillator* getLfo2();
void setVoices(vector<Voice*>);
vector<Voice*> getVoices();
void setSequencer(Sequencer* sequencer);
Sequencer* getSequencer();
void setCurrentModEnvIdx(int idx);
int getCurrentModEnvIdx();
void setSampleRate(float sampleRate);
void setGlobalTranspose(int transpose);
int getGlobalTranspose();
void setPitchbendRange(int range);
int getPitchbendRange();
private:
float volume;
float filterCutoff;
float filterResonance;
int osc1Pitch;
int osc2Pitch;
int osc3Pitch;
float osc1Fine;
float osc2Fine;
float osc3Fine;
float osc1Volume;
float osc2Volume;
float osc3Volume;
float ampEnvAttack;
float ampEnvDecay;
float ampEnvSustain;
float ampEnvRelease;
float filterEnvAttack[3] = { 0 };
float filterEnvDecay[3] = { 0 };
float filterEnvSustain[3] = { 0 };
float filterEnvRelease[3] = { 0 };
float filterModAmount;
vector<Voice*> voices;
MultimodeFilter* mainFilter;
vector <Trio::ADSR* > modEnv;
MultimodeOscillator* lfo1;
MultimodeOscillator* lfo2;
int sampleRate;
float lfo1Rate;
float lfo1Amount;
float lfo2Rate;
float lfo2Amount;
int modsource;
int mod1target;
int mod2target;
int currentModEnvIdx = 0;
Sequencer* seq;
int globalTranspose = 0;
int pitchbendRange = 2;
};
#endif // MODEL_H_INCLUDED
| [
"matthias@pueski.de"
] | matthias@pueski.de |
894617b0df3a80ad4fce199001e119d258347c1b | c37d94eaedb6d0277b0e44740705e5e1a5d56454 | /配置工具(1) Tool/class/KMGCfgView.cpp | 554f19c94cdb28a4e4c139cb229a065961706d4a | [] | no_license | 15831944/blogs | 6d4e9c5111f06b268b30a7275d9cc6375b5f0108 | 1fa6a94d6b6a0b3d000fc3bfce13ac9f87deab64 | refs/heads/master | 2022-01-06T23:44:05.536952 | 2018-10-13T02:15:10 | 2018-10-13T02:15:10 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 32,080 | cpp | // KMGCfgView.cpp : implementation file
//
#include "stdafx.h"
#include "demo.h"
#include "KMGCfgView.h"
#include "stdafx.h"
#include "MyFun.h"
#include "ReadPzkIni.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CToolTipCtrl kmg_ToolTipCtr;//tooltips提示
extern int KMG_Select[KMG_SWITCH_KIND][KMG_SELECT];//看门狗 读取prot_select里面的数据到数组
extern int KMG_FACT_SELECT[KMG_SELECT];//实际的值大小
/////////////////////////////////////////////////////////////////////////////
// CKMGCfgView dialog
IMPLEMENT_DYNCREATE(CKMGCfgView, CFormView)//通过DECLARE_DYNCREATE宏来使用IMPLEMENT_DYNCREATE宏,以允许CObject派生类对象在运行时自动建立。class,baseclass
CKMGCfgView::CKMGCfgView()
: CFormView(CKMGCfgView::IDD)
{
//{{AFX_DATA_INIT(CKMGCfgView)
m_Version = _T("");
m_Check1 = FALSE;
m_Check2 = FALSE;
m_Check3 = FALSE;
m_Check4 = FALSE;
m_Check5 = FALSE;
m_SboNum = 0;
m_SwitchNum = 0;
m_Check6 = FALSE;
bEverEdited = false;
CMode = mPzkIni.KMGFile.Cfg.V_ConnectMode;
m_FixActTime = mPzkIni.KMGFile.Cfg.FixActTime;;
//}}AFX_DATA_INIT
}
void CKMGCfgView::DoDataExchange(CDataExchange* pDX)//对话框数据提取、
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CKMGCfgView)
DDX_Control(pDX, IDC_COMBO2, m_Enable);
DDX_Control(pDX, IDC_EDIT3, m_Input);
DDX_Control(pDX, IDC_LIST1, m_List1);
DDX_Control(pDX, IDC_COMBO1, m_KMGType);
DDX_Text(pDX, IDC_EDIT1, m_Version);
DDX_Check(pDX, IDC_CHECK1, m_Check1);
DDX_Check(pDX, IDC_CHECK2, m_Check2);
DDX_Check(pDX, IDC_CHECK3, m_Check3);
DDX_Check(pDX, IDC_CHECK4, m_Check4);
DDX_Check(pDX, IDC_CHECK5, m_Check5);
DDX_Text(pDX, IDC_EDIT4, m_SboNum);
DDX_Text(pDX, IDC_EDIT5, m_SwitchNum);
DDX_Check(pDX, IDC_CHECK6, m_Check6);
DDX_Text(pDX, IDC_EDIT6, m_FixActTime);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CKMGCfgView, CFormView)
//{{AFX_MSG_MAP(CKMGCfgView)
ON_BN_CLICKED(IDC_CHECK1, OnCheck1)
ON_BN_CLICKED(IDC_CHECK2, OnCheck2)
ON_BN_CLICKED(IDC_CHECK3, OnCheck3)
ON_BN_CLICKED(IDC_CHECK4, OnCheck4)
ON_BN_CLICKED(IDC_CHECK5, OnCheck5)
ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1)
ON_CBN_SELCHANGE(IDC_COMBO1, OnSelchangeCombo1)
ON_BN_CLICKED(IDC_RADIO1, OnRadio1)
ON_BN_CLICKED(IDC_RADIO2, OnRadio2)
ON_EN_CHANGE(IDC_EDIT4, OnChangeEdit4)
ON_EN_KILLFOCUS(IDC_EDIT4, OnKillfocusEdit4)
ON_EN_CHANGE(IDC_EDIT5, OnChangeEdit5)
ON_EN_KILLFOCUS(IDC_EDIT5, OnKillfocusEdit5)
ON_BN_CLICKED(IDC_BUTTON1, OnSave)
ON_EN_KILLFOCUS(IDC_EDIT3, OnKillfocusEdit3)
ON_CBN_KILLFOCUS(IDC_COMBO2, OnKillfocusCombo2)
ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
ON_BN_CLICKED(IDC_RADIO3, OnRadio3)
ON_BN_CLICKED(IDC_CHECK6, OnCheck6)
ON_BN_CLICKED(IDC_RADIO4, OnRadio4)
ON_BN_CLICKED(IDC_RADIO5, OnRadio5)
ON_BN_CLICKED(IDC_RADIO6, OnRadio6)
ON_EN_KILLFOCUS(IDC_EDIT6, OnKillfocusEdit6)
ON_EN_CHANGE(IDC_EDIT6, OnChangeEdit6)
//}}AFX_MSG_MAP
ON_MESSAGE(SAVE_FILE,OnMsgSaveFile)//消息ID和映射message的函数
ON_MESSAGE(UNSAVE_FILE,OnMsgUnSaveFile)//它的作用是绑定一个自定义的消息和该消息的响应函数。
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CKMGCfgView message handlers
#ifdef _DEBUG
void CKMGCfgView::AssertValid() const
{
CFormView::AssertValid();
}
void CKMGCfgView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif //_DEBUG AssertValid函数是用来判断表达式的合法性或正确性,如果不正确或不合法则终止程序并返回相应的提示信息 如AssertValid(t==0);//用来判断t是否等于0,如果t!=0则终止程序
//Dump函数一般用来显示debug信息的,其函数中的内容一般在debug时,在debug窗口中才能看到
void CKMGCfgView::LoadKMGConfig()//工具显示数据:开关类型、数据表
{
int addItem;
listArray[0]->DeleteAllItems();
int type = m_KMGType.GetCurSel();//故障类型组合框内容项 0为保护定值设定
if(type ==0)
{
SwitchType=mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Type;//开关类型
if(SwitchType==0)//断路器选中
{
((CButton*)GetDlgItem(IDC_RADIO1))->SetCheck(1);//根据switchtype,显示相应的radio状态
}
else if(SwitchType==1)//负荷开关选中
{
((CButton*)GetDlgItem(IDC_RADIO2))->SetCheck(1);
}
else if(SwitchType==2)//组合电器选中
{
((CButton*)GetDlgItem(IDC_RADIO3))->SetCheck(1);
}
m_SboNum=mPzkIni.KMGFileTemp.Line[type].LineCfg.SBO_Num;//#线路SBO号
m_SwitchNum=mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Num;//#线路开关号
int index;
for(int i=0; i<=KMG_FACT_SELECT[SwitchType]; i++)//每种开关类型有几个数据 ,KMG_FACT_SELECT哪里来,0-9 1-3 2-3
{
index=KMG_Select[SwitchType][i];//switchtype:开关类型 i:第几个数据
addItem = listArray[0]->InsertItem(i, Str(i), 0);
listArray[0]->SetItemData(addItem, mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Type);//?
listArray[0]->SetItemText(addItem, 1, mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Name);
if(mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable == 255)
{
listArray[0]->SetItemText(addItem, 2, "动作");
}
else if(mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable == 1)
{
listArray[0]->SetItemText(addItem, 2, "告警");
}
else if(mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable == 0)
{
listArray[0]->SetItemText(addItem, 2, "退出");
}
listArray[0]->SetItemText(addItem, 3, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Value1));
listArray[0]->SetItemText(addItem, 4, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Time));
listArray[0]->SetItemText(addItem, 5, mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Unit);
}
}
else if(type ==1 || type ==2 || type ==3 || type ==4 || type==5 )
{
addItem = listArray[0]->InsertItem(0, Str(0), 0);
listArray[0]->SetItemData(addItem, mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Line);
if(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable == 255)//KMGItem[0]?,只有一行数据
{
listArray[0]->SetItemText(addItem, 1, "投入");
}
else if(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable == 0)
{
listArray[0]->SetItemText(addItem, 1, "退出");
}
listArray[0]->SetItemText(addItem, 2, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value1));
listArray[0]->SetItemText(addItem, 3, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value2));
listArray[0]->SetItemText(addItem, 4, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Time));
listArray[0]->SetItemText(addItem, 5, mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Unit);
}
else if(type ==6 || type ==7)
{
addItem = listArray[0]->InsertItem(0, Str(0), 0);
listArray[0]->SetItemData(addItem, mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Line);
if(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable == 255)
{
listArray[0]->SetItemText(addItem, 1, "投入");
}
else if(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable == 0)
{
listArray[0]->SetItemText(addItem, 1, "退出");
}
listArray[0]->SetItemText(addItem, 2, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value1));
// listArray[0]->SetItemText(addItem, 3, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value2));
listArray[0]->SetItemText(addItem, 3, Str(mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Time));
listArray[0]->SetItemText(addItem, 4, mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Unit);
}
UpdateData(UPDATE_WRITE);//UpdateData(FALSE);把m_txt的数据刷新到画面控件上去。UpdateData(TRUE)是将控件的状态传给其关联的变量,
}
void CKMGCfgView::InitListCtrl()
{
int i=0;
CSize sz;
sz.cx = sz.cy = 30;
// listArray[0] = &m_List1;
int type = m_KMGType.GetCurSel();
/***********清空,否则会产生下拉框*************/
/********http://bbs.csdn.net/topics/50390421*******/
m_List1.DeleteAllItems();//首先清空listview
int iCount,j=0;
iCount = m_List1.GetHeaderCtrl()->GetItemCount();
for(j = 0; j < iCount; j++)
{
m_List1.DeleteColumn(0);
}
for(j = 0; j < iCount; j++)
{
m_List1.GetHeaderCtrl()->DeleteItem(0);
}
listArray[0] = &m_List1;
//listArray[0]->DeleteAllItems();
if(type == 0)
{
listArray[0]->SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);//设置当前的列表视图控件扩展的样式
listArray[0]->ApproximateViewRect(sz,1);//指定显示列表视图控件项所需的宽度和高度?
listArray[0]->InsertColumn(i++, "序号", LVCFMT_LEFT, 40, -1);//i++为列号,内容,居中,宽度
listArray[0]->InsertColumn(i++, "名称", LVCFMT_LEFT, 160, -1);
listArray[0]->InsertColumn(i++, "动作/告警", LVCFMT_CENTER, 75, -1);
listArray[0]->InsertColumn(i++, "定值", LVCFMT_CENTER, 75, -1);
listArray[0]->InsertColumn(i++, "时间", LVCFMT_CENTER, 80, -1);
listArray[0]->InsertColumn(i++, "定值单位/备注", LVCFMT_CENTER, 141, -1);
// AfxMessageBox("111111111");
}
else if(type ==1 || type ==2 || type ==3 || type ==4 || type==5 )
{
listArray[0]->SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
listArray[0]->ApproximateViewRect(sz,1);//ApproximateViewRect指定显示列表视图控件项所需的宽度和高度
listArray[0]->InsertColumn(i++, "线路号", LVCFMT_LEFT, 64, -1);
listArray[0]->InsertColumn(i++, "投入/退出", LVCFMT_CENTER, 92, -1);
listArray[0]->InsertColumn(i++, "上限值", LVCFMT_CENTER, 85, -1);
listArray[0]->InsertColumn(i++, "下限值", LVCFMT_CENTER, 85, -1);
listArray[0]->InsertColumn(i++, "时间", LVCFMT_CENTER, 95, -1);
listArray[0]->InsertColumn(i++, "定值单位/备注", LVCFMT_CENTER, 151, -1);
// AfxMessageBox("2222222222222");
}
else if(type ==6 || type ==7)
{
listArray[0]->SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
listArray[0]->ApproximateViewRect(sz,1);
listArray[0]->InsertColumn(i++, "线路号", LVCFMT_CENTER, 90, -1);
listArray[0]->InsertColumn(i++, "投入/退出", LVCFMT_CENTER, 110, -1);
listArray[0]->InsertColumn(i++, "定值", LVCFMT_CENTER, 110, -1);
listArray[0]->InsertColumn(i++, "时间", LVCFMT_CENTER, 110, -1);
listArray[0]->InsertColumn(i++, "定值单位/备注", LVCFMT_CENTER, 152, -1);
// AfxMessageBox("333333333333");
}
CRect rect;//?
listArray[0]->GetWindowRect(&rect);//该函数返回指定窗口的边框矩形的尺寸。该尺寸以相对于屏幕坐标左上角的屏幕坐标给出。
rect.top -= 80;
rect.bottom -= 80;
LoadKMGConfig();
}
void CKMGCfgView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
//为了防止出现不一致的情况,确实也出现过了。
memcpy(&(mPzkIni.KMGFileTemp),&(mPzkIni.KMGFile),sizeof(KMGCfgStru));
//初始为0, 颜色变灰
GetDlgItem(IDC_CHECK3)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK4)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK5)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK1)->EnableWindow(TRUE);//复选框允许或禁止输入
GetDlgItem(IDC_CHECK2)->EnableWindow(TRUE);
GetDlgItem(IDC_CHECK6)->EnableWindow(TRUE);
kmg_ToolTipCtr.Create(this);//给电压接线方式添加提示
kmg_ToolTipCtr.AddTool(GetDlgItem(IDC_RADIO4),_T("一侧线电压Uab接终端的U1a端子,另一侧线电压Ucb接终端的U1c端子"));//添加
kmg_ToolTipCtr.AddTool(GetDlgItem(IDC_RADIO5),_T("一侧三相电压接终端的U1a/U1b/U1c,另一侧三相电压接终端的U2a/U2b/U2c"));//添加
kmg_ToolTipCtr.AddTool(GetDlgItem(IDC_RADIO6),_T("三相电压接终端的U1a/U1b/U1c"));//添加
kmg_ToolTipCtr.SetMaxTipWidth(300);
kmg_ToolTipCtr.Activate(TRUE);
kmg_ToolTipCtr.SetDelayTime(TTDT_INITIAL, 0);
kmg_ToolTipCtr.SetDelayTime(TTDT_AUTOPOP, 90000);
m_KMGType.ResetContent();//Removes all items from a list box.
m_KMGType.AddString("保护定值设定");
m_KMGType.AddString("电流回路-越限告警定值设定");//故障类型:组合框列表框combo1
m_KMGType.AddString("电压回路-越限告警定值设定");
m_KMGType.AddString("零序电流回路-越限告警定值设定");
m_KMGType.AddString("零序电压回路-越限告警定值设定");
m_KMGType.AddString("过负荷告警定值设定");
m_KMGType.AddString("相间短路故障配置");
m_KMGType.AddString("单相接地故障配置");
m_KMGType.SetCurSel(0);//本函数在组合框的列表框中选择一个字符串。必要时列表框会滚动,以使该字符串在列表的可视区内 (列表是可见的时 )。编辑控件中 的文本将相应地变为选中的字符串。此前在列表框中的选择将不复存在。当前选项为0
m_Enable.ResetContent();//保护定值设定中 动作告警投退组合框列表框combo2
m_Enable.AddString("动作");
m_Enable.AddString("告警");
m_Enable.AddString("退出");
m_Enable.SetCurSel(0);
GetDlgItem(IDC_RADIO1)->EnableWindow(TRUE);//该函数允许/禁止指定的窗口或控件接受鼠标和键盘的输入,若该参数为TRUE,则窗口被允许
GetDlgItem(IDC_RADIO2)->EnableWindow(TRUE);//RADIO3呢?
GetDlgItem(IDC_EDIT4)->EnableWindow(TRUE);//?
GetDlgItem(IDC_EDIT5)->EnableWindow(TRUE);
m_Version = mPzkIni.KMGFileTemp.Cfg.Version;//版本号
// m_PNumPerLine = mPzkIni.KMGFileTemp.Cfg.ProtNumPerLine;//每条线路多少保护
if(mPzkIni.KMGFileTemp.Cfg.Prot_YXEnable == 255)//保护虚遥信使能
{
m_Check1 = true;//IDC_CHECK1的值
}
else
{
m_Check1 = false;
}
if(mPzkIni.KMGFileTemp.Cfg.Prot_MsgEnable == 255)//保护信息上报使能
{
m_Check2 = true;
}
else
{
m_Check2 = false;
}
if(mPzkIni.KMGFileTemp.Cfg.Byd_SOEEnable == 255)//越限告警SOE使能
{
m_Check3 = true;
}
else
{
m_Check3 = false;
}
if(mPzkIni.KMGFileTemp.Cfg.Flt_YXEnable == 255)//故障检测分相上报使能
{
m_Check4 = true;
}
else
{
m_Check4 = false;
}
if(mPzkIni.KMGFileTemp.Cfg.Flt_RepEnable == 255)//故障报文上报使能
{
m_Check5 = true;
}
else
{
m_Check5= false;
}
if(mPzkIni.KMGFileTemp.Cfg.Flt_RcwEnable == 255)//故障录波使能
{
m_Check6 = true;
}
else
{
m_Check6= false;
}
//接线方式
if(CMode==0)
((CButton *)GetDlgItem(IDC_RADIO4))->SetCheck(1);
else if(CMode ==1)
((CButton *)GetDlgItem(IDC_RADIO5))->SetCheck(1);
else if(CMode ==2)
((CButton *)GetDlgItem(IDC_RADIO6))->SetCheck(1);
UpdateData(UPDATE_WRITE);//值更新到控件
UpdateData(UPDATE_READ);//控件的值更新到变量
InitListCtrl();//调用初始化列表框函数
}
LRESULT CKMGCfgView::OnMsgUnSaveFile(WPARAM wParam, LPARAM lParam)//?
{
// OnCANCEl();
return TRUE;
}
LRESULT CKMGCfgView::OnMsgSaveFile(WPARAM wParam, LPARAM lParam)//?
{
if(bEverEdited)//true or false
{
int i = AfxMessageBox("保存当前对保护项配置所做的修改吗?",MB_YESNOCANCEL);
if(i == IDYES)
OnSave();
else if(i == IDCANCEL)
{
// bCloseWindow = false;
return FALSE;//?
}
else
;//OnCancel();
}
return TRUE;
}
void CKMGCfgView::OnCheck1() //保护虚遥信使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check1 == true)
{
mPzkIni.KMGFileTemp.Cfg.Prot_YXEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Prot_YXEnable=0;
}
}
void CKMGCfgView::OnCheck2() //保护信息上报使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check2 == true)
{
mPzkIni.KMGFileTemp.Cfg.Prot_MsgEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Prot_MsgEnable=0;
}
}
void CKMGCfgView::OnCheck3() //越限告警SOE使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check3 == true)
{
mPzkIni.KMGFileTemp.Cfg.Byd_SOEEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Byd_SOEEnable=0;
}
}
void CKMGCfgView::OnCheck4() //故障检测分相上报使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check4 == true)
{
mPzkIni.KMGFileTemp.Cfg.Flt_YXEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Flt_YXEnable=0;
}
}
void CKMGCfgView::OnCheck5() //故障报文上报使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check5 == true)
{
mPzkIni.KMGFileTemp.Cfg.Flt_RepEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Flt_RepEnable=0;
}
}
void CKMGCfgView::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
CString srr;
CString CheckStr;
bool Check;
CString str;
CComboBox *pCombo;
HWND pWnd;
Invalidate();
HWND hWnd1 = ::GetDlgItem (m_hWnd,IDC_LIST1);
LPNMITEMACTIVATE temp = (LPNMITEMACTIVATE) pNMHDR;
RECT rect;
//get the row number
nItem = temp->iItem;
//get the column number
nSubItem = temp->iSubItem;
if(nItem < 0)
return;
if(nSubItem == 0)
return;
int type = m_KMGType.GetCurSel();//故障类型组合框内容项 0为保护定值设定
if(type ==0)
{
if(nSubItem == 2)
{
pWnd = ::GetDlgItem(m_hWnd,IDC_COMBO2);
pCombo = (CComboBox *)GetDlgItem(IDC_COMBO2);
str = m_List1.GetItemText(nItem, nSubItem);
if(str.Compare("动作") == 0)
pCombo->SetCurSel(0);
else if(str.Compare("告警") == 0)
pCombo->SetCurSel(1);
else if(str.Compare("退出") == 0)
pCombo->SetCurSel(2);
}
else if(nSubItem == 3 || nSubItem == 4 )
{
pWnd = ::GetDlgItem(m_hWnd,IDC_EDIT3);
pCombo = (CComboBox *)GetDlgItem(IDC_EDIT3);
m_Input.SetWindowText(m_List1.GetItemText(nItem, nSubItem));
}
else
return;
}
if(type ==1 || type ==2 || type ==3 || type ==4 || type==5 )
{
if(nSubItem == 1)
{
pWnd = ::GetDlgItem(m_hWnd,IDC_COMBO2);
pCombo = (CComboBox *)GetDlgItem(IDC_COMBO2);
str = m_List1.GetItemText(nItem, nSubItem);
if(str.Compare("投入") == 0)
pCombo->SetCurSel(0);
else if(str.Compare("退出") == 0)
pCombo->SetCurSel(1);
}
else if(nSubItem == 2 || nSubItem == 3 || nSubItem == 4 )
{
pWnd = ::GetDlgItem(m_hWnd,IDC_EDIT3);
pCombo = (CComboBox *)GetDlgItem(IDC_EDIT3);
m_Input.SetWindowText(m_List1.GetItemText(nItem, nSubItem));
}
else
return;
}
else if(type ==6 || type ==7)
{
if(nSubItem == 1)
{
pWnd = ::GetDlgItem(m_hWnd,IDC_COMBO2);
pCombo = (CComboBox *)GetDlgItem(IDC_COMBO2);
str = m_List1.GetItemText(nItem, nSubItem);
if(str.Compare("投入") == 0)
pCombo->SetCurSel(0);
else if(str.Compare("退出") == 0)
pCombo->SetCurSel(1);
}
else if(nSubItem == 2 || nSubItem == 3 )
{
pWnd = ::GetDlgItem(m_hWnd,IDC_EDIT3);
pCombo = (CComboBox *)GetDlgItem(IDC_EDIT3);
m_Input.SetWindowText(m_List1.GetItemText(nItem, nSubItem));
}
else
return;
}
// if(nItem ==0)
// return;
pCombo->SetItemHeight(-1,12);
//Retrieve the text of the selected subItem
//from the list
RECT rect1,rect2;
// this macro is used to retrieve the Rectanle
// of the selected SubItem
ListView_GetSubItemRect(hWnd1,temp->iItem,
temp->iSubItem,LVIR_BOUNDS,&rect);
//Get the Rectange of the listControl
::GetWindowRect(temp->hdr.hwndFrom,&rect1);
//Get the Rectange of the Dialog
::GetWindowRect(m_hWnd,&rect2);
int x=rect1.left-rect2.left;
int y=rect1.top-rect2.top;
::SetWindowPos(pWnd,
HWND_TOP,rect.left+x+1,rect.top+y,
rect.right-rect.left+4,
rect.bottom-rect.top+3,NULL);
::ShowWindow(pWnd,SW_SHOW);
::SetFocus(pWnd);
*pResult = 0;
}
void CKMGCfgView::OnSelchangeCombo1() //OnInitialUpdate中是初始状态,此处为更改combo1
{
// TODO: Add your control notification handler code here
if(m_KMGType.GetCurSel()==0)//radio 开关类型激活与禁止
{
m_Enable.ResetContent();
m_Enable.AddString("动作");
m_Enable.AddString("告警");
m_Enable.AddString("退出");
GetDlgItem(IDC_RADIO1)->EnableWindow(TRUE);
GetDlgItem(IDC_RADIO2)->EnableWindow(TRUE);
GetDlgItem(IDC_RADIO3)->EnableWindow(TRUE);
}
else
{
m_Enable.ResetContent();
m_Enable.AddString("投入");
m_Enable.AddString("退出");
GetDlgItem(IDC_RADIO1)->EnableWindow(FALSE);
GetDlgItem(IDC_RADIO2)->EnableWindow(FALSE);
GetDlgItem(IDC_RADIO3)->EnableWindow(FALSE);
}
int type = m_KMGType.GetCurSel();
if(type == 0)// 保护 1 2 6 复选框激活与禁止
{
GetDlgItem(IDC_CHECK3)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK4)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK5)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK1)->EnableWindow(TRUE);
GetDlgItem(IDC_CHECK2)->EnableWindow(TRUE);
GetDlgItem(IDC_CHECK6)->EnableWindow(TRUE);
}
else if(type >=1 && type <=5 )//告警 3
{
GetDlgItem(IDC_CHECK1)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK2)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK4)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK5)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK6)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK3)->EnableWindow(TRUE);
}
else if( type == 6 || type == 7 )//故障 4 5
{
GetDlgItem(IDC_CHECK1)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK2)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK3)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK6)->EnableWindow(FALSE);
GetDlgItem(IDC_CHECK4)->EnableWindow(TRUE);
GetDlgItem(IDC_CHECK5)->EnableWindow(TRUE);
}
InitListCtrl();//当选择复选框时comb1,调用列表框函数和配置函数,如果不调用会咋样?
LoadKMGConfig();
}
void CKMGCfgView::OnRadio1() //开关类型--断路器 此处为选择radio,赋值,调用函数控件显示
{
int type = m_KMGType.GetCurSel();
mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Type=0;
SwitchType=0;
LoadKMGConfig();
}
void CKMGCfgView::OnRadio2()//开关类型--负荷开关
{
int type = m_KMGType.GetCurSel();
mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Type=1;
SwitchType=1;
LoadKMGConfig();
}
void CKMGCfgView::OnChangeEdit4() //#线路SBO号
{
bEverEdited = true;//产生变化
UpdateData(true);//界面到程序
int type = m_KMGType.GetCurSel();
mPzkIni.KMGFileTemp.Line[type].LineCfg.SBO_Num=m_SboNum;//#线路SBO号
}
void CKMGCfgView::OnKillfocusEdit4() //#线路SBO号
{
UpdateData(UPDATE_READ);
if(m_SboNum > 50)
{
AfxMessageBox("线路SBO号不能超过"+Str(50));
m_SboNum = 50;
UpdateData(UPDATE_WRITE);
}
if(m_SboNum < 0)
{
AfxMessageBox("线路SBO号不能小于"+Str(0));
m_SboNum = 0;
UpdateData(UPDATE_WRITE);
}
}
void CKMGCfgView::OnChangeEdit5() //线路开关号
{
bEverEdited = true;//产生变化
UpdateData(true);//界面到程序
int type = m_KMGType.GetCurSel();
mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Num=m_SwitchNum;//线路开关号
}
void CKMGCfgView::OnKillfocusEdit5() //线路开关号
{
UpdateData(UPDATE_READ);
if(m_SwitchNum > 50)
{
AfxMessageBox("线路开关号不能超过"+Str(50));
m_SwitchNum = 50;
UpdateData(UPDATE_WRITE);
}
if(m_SwitchNum < 0)
{
AfxMessageBox("线路开关号不能小于"+Str(0));
m_SwitchNum = 0;
UpdateData(UPDATE_WRITE);
}
}
void CKMGCfgView::OnSave()
{
UpdateData(true);//界面到变量
mPzkIni.KMGFile.Cfg.Version=mPzkIni.KMGFileTemp.Cfg.Version;//版本号 ==其实没变化
//m_PNumPerLine = mPzkIni.SXJZSFileTemp.Cfg.ProtNumPerLine;//每条线路多少保护 ==没变化
mPzkIni.KMGFile.Cfg.Prot_YXEnable=mPzkIni.KMGFileTemp.Cfg.Prot_YXEnable;//保护虚遥信使能
mPzkIni.KMGFile.Cfg.Prot_MsgEnable=mPzkIni.KMGFileTemp.Cfg.Prot_MsgEnable;//保护信息上报使能
mPzkIni.KMGFile.Cfg.Byd_SOEEnable=mPzkIni.KMGFileTemp.Cfg.Byd_SOEEnable;//越限告警SOE使能
mPzkIni.KMGFile.Cfg.Flt_YXEnable=mPzkIni.KMGFileTemp.Cfg.Flt_YXEnable;//故障检测分相上报使能
mPzkIni.KMGFile.Cfg.Flt_RepEnable=mPzkIni.KMGFileTemp.Cfg.Flt_RepEnable;//故障报文上报使能
mPzkIni.KMGFile.Cfg.Flt_RcwEnable=mPzkIni.KMGFileTemp.Cfg.Flt_RcwEnable;//故障录波使能
mPzkIni.KMGFile.Cfg.FixActTime=m_FixActTime; //保护动作固有时间
mPzkIni.KMGFile.Cfg.V_ConnectMode=CMode;//接线方式
int i;
int j;
for(i=0;i<8;i++)
{
if(i == 0 )
{
mPzkIni.KMGFile.Line[i].LineCfg.Switch_Type=mPzkIni.KMGFileTemp.Line[i].LineCfg.Switch_Type;//开关类型
mPzkIni.KMGFile.Line[i].LineCfg.SBO_Num=mPzkIni.KMGFileTemp.Line[i].LineCfg.SBO_Num;//#线路SBO号
mPzkIni.KMGFile.Line[i].LineCfg.Switch_Num=mPzkIni.KMGFileTemp.Line[i].LineCfg.Switch_Num;//#线路开关号
for(j=0;j<mPzkIni.KMGFileTemp.Cfg.ProtNumPerLine;j++)//全部保存一遍 0-每条线路保护数
{
mPzkIni.KMGFile.Line[i].KMGItem[j].Type = mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Type;
mPzkIni.KMGFile.Line[i].KMGItem[j].Name = mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Name;
mPzkIni.KMGFile.Line[i].KMGItem[j].Enable=mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Enable;
mPzkIni.KMGFile.Line[i].KMGItem[j].Value1 =mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Value1;
mPzkIni.KMGFile.Line[i].KMGItem[j].Time = mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Time;
mPzkIni.KMGFile.Line[i].KMGItem[j].Unit = mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Unit;
}
}
else if(i ==1 || i ==2 || i ==3 || i ==4 || i==5 )
{
mPzkIni.KMGFile.Line[i].KMGItem[0].Line = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Line;
mPzkIni.KMGFile.Line[i].KMGItem[0].Enable=mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Enable;
mPzkIni.KMGFile.Line[i].KMGItem[0].Value1 = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value1;
mPzkIni.KMGFile.Line[i].KMGItem[0].Value2 = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value2;
mPzkIni.KMGFile.Line[i].KMGItem[0].Time = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Time;
mPzkIni.KMGFile.Line[i].KMGItem[0].Unit = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Unit;
}
else if(i == 6 || i == 7)
{
mPzkIni.KMGFile.Line[i].KMGItem[0].Line = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Line;
mPzkIni.KMGFile.Line[i].KMGItem[0].Enable=mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Enable;
mPzkIni.KMGFile.Line[i].KMGItem[0].Value1 = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value1;
mPzkIni.KMGFile.Line[i].KMGItem[0].Time = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Time;
mPzkIni.KMGFile.Line[i].KMGItem[0].Unit = mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Unit;
}
}
bEverEdited = false;
mPzkIni.EverModified = true;
}
void CKMGCfgView::OnKillfocusEdit3()//编辑各种内容
{
CString str;
m_Input.GetWindowText(str);
listArray[0]->SetItemText(nItem, nSubItem, str);
int type = m_KMGType.GetCurSel();
if(type == 0 )
{
int index = KMG_Select[SwitchType][nItem];//保存数据数组的第某个开关的下标
if(nSubItem == 3)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Value1=myatof(str);
}
else if(nSubItem == 4)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Time=myatof(str);
}
}
else if(type ==1 || type ==2 || type ==3 || type ==4 || type==5 )
{
if(nSubItem == 2)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value1=myatof(str);
}
else if(nSubItem == 3)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value2=myatof(str);
}
else if(nSubItem == 4)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Time=myatof(str);
}
}
else if(type == 6 || type == 7)
{
if(nSubItem == 2)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Value1=myatof(str);
}
else if(nSubItem == 3)
{
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Time=myatof(str);
}
}
m_Input.ShowWindow(SW_HIDE);
bEverEdited = true;
}
void CKMGCfgView::OnKillfocusCombo2() //动作/告警/退出 鼠标选择组合框控件显示,赋值
{
int type = m_KMGType.GetCurSel();//得到当前故障类型
int index = KMG_Select[SwitchType][nItem];//保存数据数组的第某个开关的下标
if(type == 0)
{
if(m_Enable.GetCurSel() == 0)
{
listArray[0]->SetItemText(nItem, nSubItem, "动作");
mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable=255;
}
else if(m_Enable.GetCurSel() == 1)
{
listArray[0]->SetItemText(nItem, nSubItem, "告警");
mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable=1;
}
else if(m_Enable.GetCurSel() == 2)
{
listArray[0]->SetItemText(nItem, nSubItem, "退出");
mPzkIni.KMGFileTemp.Line[type].KMGItem[index].Enable=0;
}
}
else
{
if(m_Enable.GetCurSel() == 0)
{
listArray[0]->SetItemText(nItem, nSubItem, "投入");
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable=255;
}
else if(m_Enable.GetCurSel() == 1)
{
listArray[0]->SetItemText(nItem, nSubItem, "退出");
mPzkIni.KMGFileTemp.Line[type].KMGItem[0].Enable=0;
}
}
m_Enable.ShowWindow(SW_HIDE);
bEverEdited = true;
}
void CKMGCfgView::OnButton2() //取消
{
int j;
int i = m_KMGType.GetCurSel();//得到当前故障类型
if(i == 0 )
{
mPzkIni.KMGFileTemp.Line[i].LineCfg.Switch_Type=mPzkIni.KMGFile.Line[i].LineCfg.Switch_Type;//开关类型
mPzkIni.KMGFileTemp.Line[i].LineCfg.SBO_Num=mPzkIni.KMGFile.Line[i].LineCfg.SBO_Num;//#线路SBO号
mPzkIni.KMGFileTemp.Line[i].LineCfg.Switch_Num=mPzkIni.KMGFile.Line[i].LineCfg.Switch_Num;//#线路开关号
for(j=0;j<mPzkIni.KMGFileTemp.Cfg.ProtNumPerLine;j++)//全部保存一遍 0-每条线路保护数
{
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Type = mPzkIni.KMGFile.Line[i].KMGItem[j].Type;
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Name = mPzkIni.KMGFile.Line[i].KMGItem[j].Name;
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Enable=mPzkIni.KMGFile.Line[i].KMGItem[j].Enable;
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Value1 =mPzkIni.KMGFile.Line[i].KMGItem[j].Value1;
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Time = mPzkIni.KMGFile.Line[i].KMGItem[j].Time;
mPzkIni.KMGFileTemp.Line[i].KMGItem[j].Unit = mPzkIni.KMGFile.Line[i].KMGItem[j].Unit;
}
}
else if(i ==1 || i ==2 || i ==3 || i ==4 || i==5 )
{
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Line = mPzkIni.KMGFile.Line[i].KMGItem[0].Line;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Enable=mPzkIni.KMGFile.Line[i].KMGItem[0].Enable;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value1 = mPzkIni.KMGFile.Line[i].KMGItem[0].Value1;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value2 = mPzkIni.KMGFile.Line[i].KMGItem[0].Value2;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Time = mPzkIni.KMGFile.Line[i].KMGItem[0].Time;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Unit = mPzkIni.KMGFile.Line[i].KMGItem[0].Unit;
}
else if(i == 6 || i == 7)
{
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Line = mPzkIni.KMGFile.Line[i].KMGItem[0].Line;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Enable=mPzkIni.KMGFile.Line[i].KMGItem[0].Enable;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Value1 = mPzkIni.KMGFile.Line[i].KMGItem[0].Value1;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Time = mPzkIni.KMGFile.Line[i].KMGItem[0].Time;
mPzkIni.KMGFileTemp.Line[i].KMGItem[0].Unit = mPzkIni.KMGFile.Line[i].KMGItem[0].Unit;
}
else
;
LoadKMGConfig();
}
void CKMGCfgView::OnRadio3() //开关类型--组合电器
{
// TODO: Add your control notification handler code here
int type = m_KMGType.GetCurSel();
mPzkIni.KMGFileTemp.Line[type].LineCfg.Switch_Type=2;
SwitchType=2;
LoadKMGConfig();
}
void CKMGCfgView::OnCheck6()// 故障录波使能
{
bEverEdited = true;
UpdateData(true);//界面到程序
if(m_Check6 == true)
{
mPzkIni.KMGFileTemp.Cfg.Flt_RcwEnable=255;
}
else
{
mPzkIni.KMGFileTemp.Cfg.Flt_RcwEnable=0;
}
}
BOOL CKMGCfgView::PreTranslateMessage(MSG* pMsg)//tooltip重载父窗口的 BOOL PreTranslateMessage(MSG* pMsg) ,在函数中调用 m_tt.RelayEvent(pMsg)
{
if(IsWindow(kmg_ToolTipCtr.m_hWnd))//为啥要加判断
{
kmg_ToolTipCtr.RelayEvent(pMsg);
}
return CFormView::PreTranslateMessage(pMsg);
//CFormView
}
void CKMGCfgView::OnRadio4()
{
bEverEdited = true;
CMode=0;
}
void CKMGCfgView::OnRadio5()
{
bEverEdited = true;
CMode=1;
}
void CKMGCfgView::OnRadio6()
{
bEverEdited = true;
CMode=2;
}
void CKMGCfgView::OnKillfocusEdit6()
{
// TODO: Add your control notification handler code here
UpdateData(UPDATE_READ);
if(m_FixActTime > 45)
{
AfxMessageBox("最大固有时间不能超过"+Str(45)+Str("ms"));
m_FixActTime = 45;
UpdateData(UPDATE_WRITE);
}
if(m_FixActTime < 30)
{
AfxMessageBox("最小固有时间不能小于"+Str(30)+Str("ms"));
m_FixActTime = 30;
UpdateData(UPDATE_WRITE);
}
}
void CKMGCfgView::OnChangeEdit6()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CFormView::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
bEverEdited = true;
}
| [
"weifeng19911024@163.com"
] | weifeng19911024@163.com |
e68ef2449210ab416228b95320df5ef66d7a33b8 | 22b7620b308a405ff748526784d239f0d4c0c4e7 | /Dice Roller/dieMain.cpp | 8f810c47aba8040a2a36537b2d99e71856f9002e | [] | no_license | Holly-Buteau/Cpp-Projects | f8cf6d60ffd21ba0649f3102646a586000ab8431 | ded528a6db61abcdad86442aa11d2fb84c8abab9 | refs/heads/master | 2021-01-10T17:52:39.982406 | 2016-03-31T19:12:26 | 2016-03-31T19:12:26 | 55,166,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | cpp | /*********************************************************************
* ** Program Filename: dieMain.cpp
* ** Author: Holly Buteau
* ** Date: January 24, 2016
* ** Description: main file for game
* ** Input: none
* ** Output: none
* *********************************************************************/
#include "game.hpp"
#include "Die.hpp"
#include "LoadedDie.hpp"
#include<iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
Game game;
game.getRounds();
game.getSides();
game.getDieType();
game.scoreCalculator();
game.winner();
return 0;
}
| [
"buteauh@oregonstate.edu"
] | buteauh@oregonstate.edu |
8302d73b4f3a6827bc6283b445d83021e5bf0f07 | d38b7a1dab0bb815816769d5e573a3e9242345e2 | /Src/mvCapture.cpp | 126e642df82a37c350d4fb5e34a1f49083bff116 | [
"MIT"
] | permissive | junxigauss/MVision | f9c32063e8ec61f7ea499c6fcfb6790f913a4d22 | 122d91513356547748c70ddacf5f146b6a3e5dd5 | refs/heads/master | 2021-01-21T07:45:10.778757 | 2015-06-14T02:55:13 | 2015-06-14T02:55:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include "mvCapture.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
using namespace mv;
Capture::Capture(DataBase *pDataBase, int device) : m_pDataBase(pDataBase) {
m_IsCapOK = m_Cap.open(device);
}
bool mv::Capture::IsOpen() const {
return m_Cap.isOpened();
}
DataBase* mv::Capture::GetFrame() {
if (!m_IsCapOK) {
return nullptr;
}
// TODO: Get Mat From m_Cap.read()
//m_Cap.read();
return m_pDataBase;
} | [
"changjiezhao@foxmail.com"
] | changjiezhao@foxmail.com |
efc854161463a7264c6455da87fc4d1eca83a90a | 82dc89eb359b2a281acc0bf3c0d3ea6a6ec86ab3 | /Using C++/Sorting/SelectionSort.cpp | 692d84b7dc39d0e807860c0b757482a8691cb013 | [] | no_license | siddhanthramani/Data-Structures-and-Algorithms | d03a8c26a3a0f8a9168ebb9a3bd2e629a5432df2 | f99988724736a277116adfb3a560e1824df5e6f0 | refs/heads/master | 2022-11-19T18:15:26.169508 | 2020-07-22T06:34:12 | 2020-07-22T06:34:12 | 281,594,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | cpp | //Selection sort is used to sort an array.
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main(){
int n,min_value,min_index,temp;
cout << "Enter size of array : ";
cin >> n;
int a[n];
//creating the array
for(int i = 0;i < n; i++){
cout << "\nEnter the value at row = ";
cout << i+1;
cout << " : ";
cin >> a[i];
}
//displaying the array
cout << "The array is \n";
for(int i = 0;i < n; i++){
cout << a[i];
cout << "\t";
}
for(int i = 0; i < n-1; i++){
min_value = a[i];
min_index = i; //this is important. If you forget to write this and sorting during some iteration is not required,
//then, the previous value of 'j' will be stored in this variable leading to false output. Ex n=5, and input 6,5,4,3,2
//will result in wring output
for(int j = i+1; j < n; j++){
if(a[j] < min_value){
min_value = a[j];
min_index = j;
}
}
temp = a[i];
a[i] = min_value;
a[min_index] = temp;
}
//displaying the sorted array
cout << "\nThe sorted array is \n";
for(int i = 0;i < n; i++){
cout << a[i];
cout << "\t";
}
}
| [
"dhanth20@gmail.com"
] | dhanth20@gmail.com |
2d9e17326eb5742f3bd1eced14a0aca0ecac3ee8 | c9f3b50a6e46b09afd944466516973fbfaeda10e | /Data Structures/5-Binary Tree/Dynamic Binary Tree/QueueAsArray.h | c29f72b9cf8e3d87b1baaf9a18778b5f12dfe30b | [] | no_license | nikolaninigit/NikolaRepository | 7a9b06b982e24bd9976d3d057ae482541f334b3e | 51322091ba4269113322f3893a9cac18d006193f | refs/heads/master | 2020-06-02T04:29:03.571827 | 2013-11-11T18:57:21 | 2013-11-11T18:57:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,395 | h | // Class for Queue data structure
template<class T>
class QueueAsArray
{
public:
T *data;
int head;
int tail;
int size;
int numOfElements;
public:
QueueAsArray(int vel)
{
size=vel;
numOfElements=0;
data=new T[size];
head=tail=-1;
}
bool isEmpty()
{
return (numOfElements==0);
}
int numberOfElements()
{
return numOfElements;
}
~QueueAsArray()
{
delete [] data;
}
T getHead() // gets value of element from the begining but doesn't removes it
{
if(numOfElements==0)
throw "Queue is smpty;";
return data[head];
}
void enqueue(T obj) // adding new element to the end of the queue
{
if(numOfElements==size)
throw "Red je pun";
else
{
tail++;
// checking if it is end of the queue
if(tail==size)
tail=0; // if end is reached, set tail to 0
data[tail]=obj;
if(numOfElements==0) // if there was no elements at the begining
head=tail;
numOfElements++;
}
}
T dequeue()
{
if(numOfElements==0)
throw "Red je prazan";
else
{
T result=data[head];
head++;
if(head==size) // when everything is deleted, head becomes 0
head=0;
numOfElements--;
if(numOfElements==0)
head=tail=-1;
return result;
}
}
void print()
{
for(int i=0;i<numOfElements;i++)
cout<<data[i]<<" ";
}
}; | [
"nikkolica@gmail.com"
] | nikkolica@gmail.com |
27d9e02b42d9d4fe986d985d2b612ff80d1f4ea7 | 1033609e705e0b432f8a0760d32befa92c2b9cb5 | /branches/0.5/svn.h | 5fba596337fb8c8cf0a942ea14f62a165985f257 | [] | no_license | BackupTheBerlios/cb-svn-svn | 5b89c2c5445cf7a51575cf08c0eaaf832074b266 | 6b512f58bbb56fbc186ca26d5c934e1fe83173af | refs/heads/master | 2020-04-02T00:14:00.063607 | 2005-10-26T13:52:08 | 2005-10-26T13:52:08 | 40,614,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,290 | h | // This file is part of the Code::Blocks SVN Plugin
// Copyright (C) 2005 Thomas Denk
//
// This program is licensed under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2 of the License,
// or (at your option) any later version.
// $HeadURL$
// $Id$
#ifndef SVN_H
#define SVN_H
#include <wx/wx.h>
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include "precompile.h"
#include <manager.h>
#include <configmanager.h>
#include <sdk_events.h>
#include <projectmanager.h>
#include <projectbuildtarget.h>
#include "toolrunner.h"
#include "svnrunner.h"
#include "cvsrunner.h"
#include "tortoiserunner.h"
#include "smart.h"
WX_DECLARE_HASH_MAP( int, wxString, wxIntegerHash, wxIntegerEqual, IdToStringHash );
class MRUList : public wxArrayString
{
public:
void Add(wxString s)
{
int idx;
while((idx = Index(s, false)) != wxNOT_FOUND)
RemoveAt(idx);
Insert(s, 0);
};
};
class SubversionPlugin : public cbPlugin
{
IdToStringHash fileProperties;
smart<SVNRunner> svn;
smart<TortoiseRunner> tortoise;
smart<TortoiseCVSRunner> tortoisecvs;
smart<CVSRunner> cvs;
smart<DiffRunner> diff3;
smart<ToolRunner> binutils;
public:
SubversionPlugin();
~SubversionPlugin()
{}
;
int Configure()
{
CodeBlocksEvent e;
Preferences(e);
return 0;
};
void BuildMenu(wxMenuBar* menuBar)
{}
;
bool SubversionPlugin::BuildToolBar(wxToolBar* toolBar)
{
return false;
};
void BuildModuleMenu(const ModuleType type, wxMenu* menu, const wxString& arg);
void Build_CVS_ModuleMenu(wxMenu* menu, const wxString& arg);
void BuildProjectMenu(wxMenu* menu, wxString name, wxString target);
void BuildFileMenu(wxMenu* menu, wxString name, wxString target);
void BuildMgrMenu(wxMenu* menu);
void AppendCommonMenus(wxMenu *menu, wxString target, bool isProject, bool isLocked);
void OnAttach();
void OnRelease(bool appShutDown);
void OnTimer(wxTimerEvent& event);
void SearchBinaries();
void Preferences(wxCommandEvent& event);
void SetUser(wxCommandEvent& event);
void Add(wxCommandEvent& event);
void Delete(wxCommandEvent& event);
void Lock(wxCommandEvent& event);
void PropIgnore(wxCommandEvent& event);
void PropMime(wxCommandEvent& event);
void PropExec(wxCommandEvent& event);
void PropNeedsLock(wxCommandEvent& event);
void PropExt(wxCommandEvent& event);
void PropKeywords(wxCommandEvent& event);
void TransactionSuccess(wxCommandEvent& event);
void TransactionFailure(wxCommandEvent& event);
void ReRun(wxCommandEvent& event);
void Checkout(wxCommandEvent& event);
void Import(wxCommandEvent& event);
void Commit(wxCommandEvent& event);
void Update(wxCommandEvent& event);
void Revert(wxCommandEvent& event);
void Diff(wxCommandEvent& event);
void Patch(wxCommandEvent& event);
void EditConflicts(wxCommandEvent& event);
void OnFatTortoiseFunctionality(wxCommandEvent& event);
void OnFatTortoiseCVSFunctionality(wxCommandEvent& event);
void CVSUpdate(wxCommandEvent& event);
void CVSLogin(wxCommandEvent& event);
void EditProperty(wxCommandEvent& event);
void DoResolve(const wxString& conflicting);
void Resolved(wxCommandEvent& event);
void Release(wxCommandEvent& event);
wxArrayString ExtractFilesWithStatus(const char what, unsigned int pos = 0);
void ExtractFilesWithStatus(const char what, wxArrayString& ret, unsigned int pos = 0);
char ParseStatusOutputForFile(const wxString& what);
void AutoOpenProjects(const wxString& rootdir, bool recursive, bool others);
void InitToolrunners();
void ReloadEditors(const wxArrayString& filenames);
void ReOpenEditor(const wxString& filenames);
void TamperWithWindowsRegistry();
wxString NastyFind(const wxString& name);
void ReadConfig();
void WriteConfig();
wxString GetCheckoutDir();
wxString LocalPath(const wxString& target)
{
return LocalPath(GetSelectionsProject(), target);
};
wxString LocalPath(const wxString& base, const wxString& target)
{
wxFileName fn(target);
fn.MakeRelativeTo(base);
return fn.GetFullPath();
};
wxString GetActiveProject()
{
cbProject* currentProject = Manager::Get()->GetProjectManager()->GetActiveProject();
if (!currentProject)
return wxEmptyString;
return currentProject->GetCommonTopLevelPath();
};
wxString GetSelection()
{
wxTreeCtrl* tree = Manager::Get()->GetProjectManager()->GetTree();
FileTreeData* ftd = (FileTreeData*) tree->GetItemData(tree->GetSelection());
if(!ftd) // please don't crash us if nothing is selected
return wxEmptyString;
if(ProjectFile *f = ftd->GetProject()->GetFile(ftd->GetFileIndex()))
return f->file.GetFullPath();
else
return ftd->GetProject()->GetCommonTopLevelPath();
};
wxString GetSelectionsProject()
{
wxTreeCtrl* tree = Manager::Get()->GetProjectManager()->GetTree();
FileTreeData* ftd = (FileTreeData*) tree->GetItemData(tree->GetSelection());
if(!ftd) // please don't crash us if nothing is selected
return wxEmptyString;
return ftd->GetProject()->GetCommonTopLevelPath();
};
bool IsProject(const wxString& arg)
{
ProjectsArray* array = Manager::Get()->GetProjectManager()->GetProjects();
if (array)
{
unsigned int n = array->GetCount();
for (unsigned int i = 0; i < n; ++i)
{
cbProject* cur = array->Item(i);
if (cur && cur->GetTitle() == arg)
return true;
}
}
return false;
}
void DisableCheckExternals()
{
chkmod_status = ConfigManager::Get()->Read("/environment/check_modified_files",1); // evil stuff: tamper with c::b settings
ConfigManager::Get()->Write("/environment/check_modified_files", false); // to prevent a race that occurs on lengthy operations
}
void ResetCheckExternals()
{
ConfigManager::Get()->Write("/environment/check_modified_files", chkmod_status); // restore original state
}
cbProject* GetCBProject()
{
wxTreeCtrl* tree = Manager::Get()->GetProjectManager()->GetTree();
FileTreeData* ftd = (FileTreeData*) tree->GetItemData(tree->GetSelection());
if(!ftd) // please don't crash us if nothing is selected
return 0;
return ftd->GetProject();
}
wxString DirName(wxString& d)
{
d.Replace("\\", "/");
if(d[d.Length()-1] == '/')
d = d.Mid(0, d.Length()-1);
return d.AfterLast('/') ;
}
void Kill()
{
if((svn.Valid() && svn->Running()) || (cvs.Valid() && cvs->Running()))
{
if(never_ask || (wxMessageDialog(Manager::Get()->GetAppWindow(), "Are you sure you know what you are doing?\nDo you really want to kill the running transaction?\n\nIt is quite possible that you will render your working copy or your repository unusable, or both.", "Woah, Matey!", wxYES_NO).ShowModal() == wxID_YES))
{
Log::Instance()->Add("sending SIGTERM...");
if(svn.Valid() && svn->Running())
svn->Kill(wxSIGTERM);
if(cvs.Valid() && cvs->Running())
cvs->Kill(wxSIGTERM);
killTimer.Start(5000, true);
}
}
}
void ForceKill(wxTimerEvent& event)
{
Log::Instance()->Add("sending SIGKILL...");
if(svn.Valid())
svn->Kill(wxSIGKILL);
if(cvs.Valid())
cvs->Kill(wxSIGKILL);
}
void Ping(wxMouseEvent & event)
{
wxBell();
} ;
void Verbose(bool v)
{
verbose = v;
wxConfigBase* c = ConfigManager::Get();
c->Write("/svn/verbose", verbose);
};
bool DirUnderVersionControl(const wxString& arg)
{
wxString s = wxFileName(arg).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + ".svn";
return wxFileName::DirExists(s);
}
/*
* As it is possible that both .svn and CVS exist (migrated project with leftover folders), DirUnderCVS first checks for subversion's
* presence, and returns false if subversion is found. Nobody should migrate backwards from subversion to CVS (at least I think so),
* thus it is assumed that if both revision control systems are present, the better one should be used.
* Also, of course, this is a subversion plugin. CVS is only supported as a fallback for the quaint
*/
bool DirUnderCVS(const wxString& arg)
{
wxString s = wxFileName(arg).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + ".svn";
if(wxFileName::DirExists(s))
return false;
s = wxFileName(arg).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + "CVS";
return wxFileName::DirExists(s);
}
bool TamperWithCVS(wxString& repo, wxString& module)
{
/*
* Let's all hope that the CVS developers never change the incorrect naming
* of these files, or my code will break...
*/
wxString cvsdir(GetSelectionsProject() + "/CVS/");
wxFile repoFile(cvsdir + "Root");
wxFile moduleFile(cvsdir + "Repository");
if(repoFile.IsOpened() && moduleFile.IsOpened())
{
wxFileInputStream repoFS(repoFile);
wxFileInputStream moduleFS(moduleFile);
repo = wxTextInputStream(repoFS).ReadLine();
module = wxTextInputStream(moduleFS).ReadLine();
return true;
}
return false;
}
wxString defaultCheckoutDir;
wxString svnbinary;
wxString cvsbinary;
wxString tortoiseproc;
wxString tortoiseact;
wxString extdiff;
wxString tarbin;
wxString bzip2bin;
wxString zipbin;
wxString plink;
bool cascade_menu;
bool auto_add;
bool auto_add_only_project;
bool auto_delete;
bool force_clean;
bool require_comments;
bool prefill_comments;
bool avoid_out_of_date;
bool no_ask_revertable;
bool never_ask;
bool warn_revert;
bool full_status_on_startup;
bool no_props;
bool show_resolved;
bool prompt_reload;
bool up_after_co;
bool svn_ssh;
bool cvs_rsh;
bool verbose;
bool chkmod_status;
MRUList repoHistory;
MRUList repoHistoryCVS;
bool request_autoopen;
cbProject *importedProject;
wxTimer clearTimer;
wxTimer killTimer;
wxString patchFileName;
wxString meow;
bool has_tar_or_zip;
void Bing(wxKeyEvent& event)
{
wxBell();
}
protected:
private:
DECLARE_EVENT_TABLE()
};
CB_DECLARE_PLUGIN();
#endif
| [
"thomasdenk@96b225bb-4cfa-0310-88f5-88b948d20ad7"
] | thomasdenk@96b225bb-4cfa-0310-88f5-88b948d20ad7 |
c648db38e6e4877e0a42f35dd0914c0bac603642 | 507068049610a3f47d86e9ded324129dabda94ab | /include/lima/Scene.h | 7aa1c92240089e59c1560c149909ce4fc94339a3 | [] | no_license | marioprats/lima | d12e5e0c4c15bc13457173b16e9d3ec0d595fa80 | 46eae970f37bd522790df721c6b28296ed180d28 | refs/heads/master | 2021-01-11T11:06:24.643297 | 2013-08-28T17:45:10 | 2013-08-28T17:45:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,769 | h | /*
* Copyright (c) 2007 University of Jaume-I, 2013 Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Mario Prats
*/
#ifndef SCENE_H
#define SCENE_H
#include <lima/limaconfig.h>
#include <lima/Object.h>
#include <visp/vpHomogeneousMatrix.h>
#include <vector>
using namespace std;
/**
A virtual world where objects can be created and dynamics can be simulated (if using the child class ODEGLScene). The robot can use this virtual world as an internal representation of the real world. It can even try actions on the virtual world and observing the results, before performing the tasks in the real world.
@author Mario Prats <mprats@icc.uji.es>
*/
class Scene
{
public:
vector<Object*> objects; ///< A vector of pointers to the objects in the scene
Scene();
/** Adds an object to the scene, at a position given by the homogeneous
matrix wMo. TODO: check that 'o' is a root object */
virtual void addObject(vpHomogeneousMatrix wMo, Object *o);
/** Abstract virtual method for configuring the scene (lights, scenario, etc) */
virtual void configure()=0;
/** Abstract virtual method for updating the scene from one iteration to another */
virtual void simulationStep()=0;
~Scene();
};
#endif
| [
"mprats@willowgarage.com"
] | mprats@willowgarage.com |
020a95e81374653a8fb0a1aa30fcd4ad6d8e7c7f | 26798f56aaa3664b8ff363e51bc047bc32b35966 | /wxcapoc_main.h | d5fa2ac04ca6977fe1712e2d53c67deb3f2b20c5 | [
"Apache-2.0"
] | permissive | mteg/capoc | 39e07e901a7ea24e04d48947bda0c71e79e3f8f7 | 35d33e1fb9b5354e96bcf771492d861592f75eb6 | refs/heads/master | 2020-05-22T15:01:49.954414 | 2019-05-17T22:15:49 | 2019-05-17T22:15:49 | 186,399,500 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,584 | h |
#ifndef WXCAPOC_MAIN_H
#define WXCAPOC_MAIN_H
#include <unordered_map>
#include "wxcapoc_console.h"
typedef std::unordered_map<int, const char *> keyMap;
class wxCapoc_Main : public wxFrame {
public:
wxCapoc_Main(const wxString& title, const wxPoint& pos, const wxSize& size);
wxCapoc_Canvas *canvas;
wxMenu *fileMenu;
bool displayInitialized = false;
capEngine *engine;
capRenderer *renderer;
void keyPress(int c, bool shift);
void keyRelease(int c, bool shift);
void keyHold(int c, bool shift);
void leftDrag(int x, int y, int cx, int cy, int dx, int dy, bool shift);
void rightDrag(int x, int y, int cx, int cy, int dx, int dy, bool shift);
void middleDrag(int x, int y, int cx, int cy, int dx, int dy, bool shift);
void updateStatus();
wxCapoc_Tree *tree;
wxCapoc_Console *consoleDialog = NULL;
#define WXCMAP_ROOT 0
#define WXCMAP_COUNT 1
#define WXCA_PRESS 0
#define WXCA_HOLD 1
#define WXCA_BARE 0
#define WXCA_SHIFT 1
keyMap maps[WXCMAP_COUNT][2][2];
private:
void initializeDisplay();
void OnHello(wxCommandEvent& event);
void OnExit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnShow(wxShowEvent& event);
void OnFocus(wxFocusEvent& event);
void OnClose(wxCloseEvent& event);
void OnTimer(wxTimerEvent &event);
void OnSimpleMenuCommand(wxCommandEvent &event);
void OnOpenModel(wxCommandEvent &event);
void OnOpenNVM(wxCommandEvent &event);
void OnOpenScript(wxCommandEvent &event);
void OnLog0(wxCommandEvent &event);
void OnLog1(wxCommandEvent &event);
void OnLog2(wxCommandEvent &event);
void initKeymaps();
void doMap(int c, int action, bool shift);
wxTimer netTimer;
wxDECLARE_EVENT_TABLE();
void OnSavePNG(wxCommandEvent &event);
void OnSaveProject(wxCommandEvent &event);
};
enum {
ID_Open_Model = 1,
ID_Open_NVM, ID_Save_PNG, ID_Save_Project, ID_Log0, ID_Log1, ID_Log2,
ID_Open_Script,
ID_View_Plan,
ID_View_Profile,
ID_View_Xsect,
ID_View_Fourview,
ID_View_Caver,
ID_View_NVMImage,
ID_View_Zoom_In, ID_View_Zoom_Out, ID_View_Clip_In, ID_View_Clip_Out,
ID_NVM_Prev,
ID_NVM_Next,
ID_NVM_Reproject,
ID_NVM_Search,
ID_NVM_Hide_Image, ID_NVM_Hide_Planar, ID_NVM_Hide_Spatial, ID_NVM_Hide_Matching, ID_NVM_Hide_All,
ID_NVM_Show_Image, ID_NVM_Show_Planar, ID_NVM_Show_Spatial, ID_NVM_Show_Matching, ID_NVM_Show_Next, ID_NVM_Show_Prev,
ID_View_Xsect_In, ID_View_Xsect_Out, ID_View_Log, ID_Reinit_Renderer, ID_Console
};
#endif | [
"mateusz.golicz@sileman.pl"
] | mateusz.golicz@sileman.pl |
bec6ad5fee257609b809c2d22f0b4882f73a9d1a | 7d76df901302422587557bcf42500a51b5d7867c | /FKSimpleServer/Utils/CharSet.cpp | 80dc34eaf66ec99552705fa163b8b29f7a901065 | [
"MIT"
] | permissive | radtek/FKSimpleServer | 569bafe55517580f74a11cd320a016943315c4bb | 6184a1bbf7d5ad6af0ebc1c0bcbe0f4321d532ea | refs/heads/master | 2021-02-07T22:29:34.587466 | 2017-03-16T05:41:27 | 2017-03-16T05:41:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,880 | cpp | #include "CharSet.h"
//-------------------------------------------------------------
CCharSet::CCharSet()
{
clear();
}
//-------------------------------------------------------------
CCharSet::CCharSet(const char * pszTable)
{
clear();
for (int i = 0; i < (int)strlen(pszTable); i++)
addChar(pszTable[i]);
}
//-------------------------------------------------------------
CCharSet::CCharSet(DWORD dwFlags[])
{
for (int i = 0; i < 8; i++)
{
m_dwFlags[i] = dwFlags[i];
}
}
//-------------------------------------------------------------
CCharSet::~CCharSet()
{
}
//-------------------------------------------------------------
bool CCharSet::charIn(char c)
{
BYTE bc = (BYTE)c;
int index = bc >> 5;
int ptr = bc & 31;
if (m_dwFlags[index] & (1 << ptr))
return true;
return false;
}
//-------------------------------------------------------------
void CCharSet::addChar(char c)
{
BYTE bc = (BYTE)c;
int index = bc >> 5;
int ptr = bc & 31;
m_dwFlags[index] |= 1 << ptr;
}
//-------------------------------------------------------------
void CCharSet::clear()
{
memset(m_dwFlags, 0, sizeof(m_dwFlags));
}
//-------------------------------------------------------------
CCharSet& CCharSet::operator +(CCharSet & charset)
{
DWORD dwFlags[8];
for (int i = 0; i < 8; i++)
{
dwFlags[i] = m_dwFlags[i] | charset.m_dwFlags[i];
}
CCharSet tmp = CCharSet(dwFlags);
return tmp;
}
//-------------------------------------------------------------
CCharSet& CCharSet::operator +=(CCharSet & charset)
{
for (int i = 0; i < 8; i++)
{
m_dwFlags[i] |= charset.m_dwFlags[i];
}
return (*this);
}
//-------------------------------------------------------------
CCharSet& CCharSet::operator =(CCharSet & charset)
{
for (int i = 0; i < 8; i++)
{
m_dwFlags[i] = charset.m_dwFlags[i];
}
return (*this);
}
//------------------------------------------------------------- | [
"duzhi5368@163.com"
] | duzhi5368@163.com |
8c0faa90a782cd574a743dc917f6cbbdbe334a57 | 8424d627b1e9367fe1c2bc6e6796791f8c4b7783 | /154/154.cpp | 0ae9e0fdb1ae67f6fb1d13648940989e13be8130 | [] | no_license | lld2006/my-c---practice-project | 72d309f378dea1aaf16ffedf161962684ef25aef | c7e133c79528340f40f1a7192a89956bcc11dd00 | refs/heads/master | 2020-12-25T17:37:28.171658 | 2018-01-21T08:15:49 | 2018-01-21T08:15:49 | 2,707,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cpp | #include <cstdio>
#include <vector>
#include <numeric>
#include <cassert>
#include "../lib/typedef.h"
using namespace std;
int get(int num, int base)
{
int cnt = 0;
while(num % base ==0){
num/=base;
++cnt;
}
return cnt;
}
int main()
{
int target = 200000;
vector<int> v2;
vector<int> v5;
v2.resize(target+1,0);
v5.resize(target+1,0);
for( int i = 2; i<=target; ++i){
v2[i] = v2[i-1] + get(i, 2);
v5[i] = v5[i-1] + get(i, 5);
}
int vala = 200000/3+1;
i64 cnt = 0;
for(int ia = vala; ia <= target;++ia ){
//if(!(ia & 16383))printf("%d\n", ia);
int t5 = v5[target]-v5[ia];
int t2 = v2[target]-v2[ia];
if(t5 < 12 || t2 < 12) continue;
int bstart = target-ia < ia? target-ia:ia;
int ta = target -ia;
int ib, ic;
int b1 = bstart==ia?bstart+1:bstart;
for(ib = b1; true; --ib){
ic = ta - ib;
if(ic >= ib) break;
int nx5 = t5-v5[ib]-v5[ic] ;
if(nx5 < 12) continue;
int nx2 = t2-v2[ib]-v2[ic];
if(nx2 < 12) continue;
//assert(ia+ib+ic==target);
//assert(nx2 >=0 && nx5 >=0);
cnt += 6;
}
int nx5 = t5-v5[ib]-v5[ic] ;
int nx2 = t2-v2[ib]-v2[ic];
if(ic == ib && nx5 >= 12 && nx2 >= 12){
cnt+= 3;
}
nx5 = t5-v5[bstart]-v5[target-ia-bstart] ;
nx2 = t2-v2[bstart]-v2[target-ia-bstart];
if(nx5>=12 && nx2>=12){
if(bstart==ia)
cnt += 3;
}
}
printf("%lld\n", cnt);
}
| [
"euler@ubuntu.(none)"
] | euler@ubuntu.(none) |
e93a2f67842f46e861fba4b049b360defcb95dc7 | 1a8179a25434d62b26f1ed3d95eff03e8b17d08f | /cpp/ProjectManager.cpp | a7d5c4dd709da0cca01f4935e9609a06164eb5c0 | [
"Apache-2.0"
] | permissive | RobertoMalatesta/qmlcreator | 46b1a529853ffd48f26ecf9d3b159509fd10567d | b71c064725bd6d549e062affcb352bc2416963fa | refs/heads/master | 2020-05-23T18:55:58.085715 | 2015-06-08T03:09:28 | 2015-06-08T03:09:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,906 | cpp | /****************************************************************************
**
** Copyright (C) 2013-2015 Oleg Yadrov
**
** 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 "ProjectManager.h"
ProjectManager::ProjectManager(QObject *parent) :
QObject(parent)
{
QDir().mkpath(baseFolderPath(Projects));
QDir().mkpath(baseFolderPath(Examples));
}
ProjectManager::BaseFolder ProjectManager::baseFolder()
{
return m_baseFolder;
}
void ProjectManager::setBaseFolder(BaseFolder baseFolder)
{
if (m_baseFolder != baseFolder)
{
m_baseFolder = baseFolder;
emit baseFolderChanged();
}
}
QStringList ProjectManager::projects()
{
QDir dir(baseFolderPath(m_baseFolder));
QStringList projects;
QFileInfoList folders = dir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot);
foreach(QFileInfo folder, folders) {
QString folderName = folder.fileName();
projects.push_back(folderName);
}
return projects;
}
void ProjectManager::createProject(QString projectName)
{
QDir dir(baseFolderPath(Projects));
if (dir.mkdir(projectName))
{
QFile file(baseFolderPath(Projects) + QDir::separator() + projectName + QDir::separator() + "main.qml");
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QString fileContent = "// Project \"" + projectName + "\"\n" + newFileContent("main");
QTextStream textStream(&file);
textStream<<fileContent;
}
else
{
emit error(QString("Unable to create file \"main.qml\""));
}
}
else
{
emit error(QString("Unable to create folder \"%1\".").arg(projectName));
}
}
void ProjectManager::removeProject(QString projectName)
{
QDir dir(baseFolderPath(m_baseFolder) + QDir::separator() + projectName);
dir.removeRecursively();
}
bool ProjectManager::isProjectExists(QString projectName)
{
QFileInfo checkFile(baseFolderPath(Projects) + QDir::separator() + projectName);
return checkFile.exists();
}
void ProjectManager::restoreExamples()
{
QDir deviceExamplesDir(baseFolderPath(Examples));
deviceExamplesDir.removeRecursively();
deviceExamplesDir.mkpath(baseFolderPath(Examples));
QDir qrcExamplesDir(":/qml/examples");
QFileInfoList folders = qrcExamplesDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot);
foreach(QFileInfo folder, folders) {
QString folderName = folder.fileName();
deviceExamplesDir.mkdir(folderName);
QDir qrcExampleDir(":/qml/examples/" + folderName);
QFileInfoList files = qrcExampleDir.entryInfoList(QDir::Files);
foreach(QFileInfo file, files) {
QString fileName = file.fileName();
QFile::copy(file.absoluteFilePath(), baseFolderPath(Examples) + QDir::separator() + folderName + QDir::separator() + fileName);
QFile::setPermissions(baseFolderPath(Examples) + QDir::separator() + folderName + QDir::separator() + fileName,
QFileDevice::ReadOwner | QFileDevice::WriteOwner |
QFileDevice::ReadUser | QFileDevice::WriteUser |
QFileDevice::ReadGroup | QFileDevice::WriteGroup |
QFileDevice::ReadOther | QFileDevice::WriteOther
);
}
}
}
QString ProjectManager::projectName()
{
return m_projectName;
}
void ProjectManager::setProjectName(QString projectName)
{
if (m_projectName != projectName)
{
m_projectName = projectName;
emit projectNameChanged();
}
}
QStringList ProjectManager::files()
{
QDir dir(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName);
QStringList projectFiles;
QFileInfoList files = dir.entryInfoList(QDir::Files);
foreach(QFileInfo file, files) {
QString fileName = file.fileName();
projectFiles.push_back(fileName);
}
return projectFiles;
}
QString ProjectManager::projectMainPath()
{
return "file:///" + baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + "main.qml";
}
void ProjectManager::createFile(QString fileName, QString fileExtension)
{
QFile file(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + fileName + "." + fileExtension);
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream textStream(&file);
textStream<<newFileContent(fileExtension);
}
else
{
emit error(QString("Unable to create file \"%1.%2\"").arg(fileName, fileExtension));
}
}
void ProjectManager::removeFile(QString fileName)
{
QDir().remove(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + fileName);
}
bool ProjectManager::isFileExists(QString fileName)
{
QFileInfo checkFile(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + fileName);
return checkFile.exists();
}
QString ProjectManager::fileName()
{
return m_fileName;
}
void ProjectManager::setFileName(QString fileName)
{
if (m_fileName != fileName)
{
m_fileName = fileName;
emit fileNameChanged();
}
}
QString ProjectManager::getFileContent()
{
QFile file(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + m_fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream textStream(&file);
QString fileContent = textStream.readAll().trimmed();
return fileContent;
}
void ProjectManager::saveFileContent(QString content)
{
QFile file(baseFolderPath(m_baseFolder) + QDir::separator() + m_projectName + QDir::separator() + m_fileName);
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream textStream(&file);
textStream<<content;
}
QQmlApplicationEngine *ProjectManager::m_qmlEngine;
void ProjectManager::setQmlEngine(QQmlApplicationEngine *engine)
{
ProjectManager::m_qmlEngine = engine;
}
void ProjectManager::clearComponentCache()
{
ProjectManager::m_qmlEngine->clearComponentCache();
}
QString ProjectManager::baseFolderPath(BaseFolder folder)
{
QString folderName;
switch (folder)
{
case Projects:
folderName = "Projects";
break;
case Examples:
folderName = "Examples";
break;
}
QString folderPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) +
QDir::separator() +
"QML Projects";
if (!folderName.isEmpty())
{
folderPath += QDir::separator() + folderName;
}
return folderPath;
}
QString ProjectManager::newFileContent(QString fileType)
{
QString fileName;
if (fileType == "main")
fileName = "MainFile.qml";
else if (fileType == "qml")
fileName = "QmlFile.qml";
else if (fileType == "js")
fileName = "JsFile.js";
QString fileContent;
if (!fileName.isEmpty())
{
QFile file(":/resources/templates/" + fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream textStream(&file);
fileContent = textStream.readAll().trimmed();
}
return fileContent;
}
| [
"wearyinside@gmail.com"
] | wearyinside@gmail.com |
52e95d47adfa515acaf65a237c5a3747ef641ead | c1fb96ec8e1608ab13ad219c04dbf63fcf6cf377 | /BUS_UVMSYSTEMC_2/vip_components/subscriber.h | 9cb9a8cfe53af1556e16f5e7a457dcd4b570b2ea | [] | no_license | NawrasAltaleb/SimulationBasedVerification_UVM | 346ccbb36621f8a9881335f1a36417dfb3681816 | aafc8f92c672160eb60137dcb20d3af4f824ce95 | refs/heads/master | 2020-05-03T09:38:51.967569 | 2019-04-03T19:28:35 | 2019-04-03T19:28:35 | 178,559,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | h | //
// Created by Nawras Altaleb (nawras.altaleb89@gmail.com) on 10/24/18.
//
#ifndef UVMSYSTEMC_SUBSCRIBERS_H
#define UVMSYSTEMC_SUBSCRIBERS_H
#include <uvm>
#include "vip_trans.h"
///////////////////////////////////////////////////////////
/// *************************************************** ///
///////////////////////////////////////////////////////////
class subscriber_REQ: public uvm::uvm_subscriber<vip_trans_bus_req_t> {
public:
subscriber_REQ(uvm::uvm_component_name name);
UVM_COMPONENT_UTILS(subscriber_REQ)
virtual void write(const vip_trans_bus_req_t &t);
};
///////////////////////////////////////////////////////////
/// *************************************************** ///
///////////////////////////////////////////////////////////
class subscriber_RSP: public uvm::uvm_subscriber<vip_trans_bus_resp_t> {
public:
subscriber_RSP(uvm::uvm_component_name name);
UVM_COMPONENT_UTILS(subscriber_RSP)
virtual void write(const vip_trans_bus_resp_t &t);
};
#endif //UVMSYSTEMC_SUBSCRIBERS_H
| [
"nawras.altaleb89@gmail.com"
] | nawras.altaleb89@gmail.com |
9e06bdf33815f2f7a4bad5648f382e2381cbfbaf | e48a4f59c65cb0557d238758f85ad3a5a2e58122 | /nginx/misc/ngx_c_memory.cxx | 42f0993f79f9235322e67be1bac411c639a9db69 | [] | no_license | peterzhenghao/nginx | 032f0a31a59158cec8cdafb16ff25a1364fd2aa8 | 2adf928cd051bd1ffb15d0cbd869dab46d3bbedf | refs/heads/main | 2023-05-09T00:26:34.259532 | 2021-05-27T03:01:02 | 2021-05-27T03:01:02 | 371,208,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | cxx |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ngx_c_memory.h"
CMemory *CMemory::m_instance = NULL;
void *CMemory::AllocMemory(int memCount,bool ifmemset)
{
void *tmpData = (void *)new char[memCount];
if(ifmemset)
{
memset(tmpData,0,memCount);
}
return tmpData;
}
void CMemory::FreeMemory(void *point)
{
delete [] ((char *)point);
}
| [
"noreply@github.com"
] | peterzhenghao.noreply@github.com |
6126e438a7d25280a12416527808451749b8314f | 514996e39fe2129abe231503ce7f5f9688c837f7 | /src/fury/system_vars.cpp | f2fa84000e118ab2de307e168def829fa46b9e49 | [] | no_license | Necrys/Fury | d39182c1e7f9bde799b0d8baec5bc8cb4f62d6c0 | 84b20613299418efb672b6ec37e41ea69aaf72b5 | refs/heads/master | 2023-04-01T18:01:13.696634 | 2021-04-07T14:25:04 | 2021-04-07T14:25:04 | 354,311,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | cpp | #include "types.h"
#include <hgevector.h>
#include <string>
#include "data_level.h"
#include "data_staticobject.h"
#include "data_tileset.h"
using namespace std;
// screen mode
unsigned int screenWidth = 800;
unsigned int screenHeight = 600;
unsigned char screenBPP = 32;
bool windowed = true;
float globalScale = 1.0f;
string appDirectory = "";
string levelFile = "default.flf";
vector2f globalPosition = vector2f(0.0f, 0.0f);
vector2f cameraPosition;
GameLevel* level = 0;
Tileset* g_tileset = 0;
float physicsNorma = 1.0f;
bool game_pause = false; | [
"necrysgd@gmail.com"
] | necrysgd@gmail.com |
3eb2dee855c0c0cf22b843f3efb5d62402a4e555 | fdb404bc4b1f3fc5d1ec9e56faa179f2334a09f2 | /test1_1/test1.h | 3dfaff21c1e08142891ffce7ba9f412557b448fe | [] | no_license | st087823/test1_1 | 0eb108a872ae2e223c7d6ccc6333e7c8303b706c | ce268a7b84ad819a6dd33c8c88b717b53f40699f | refs/heads/master | 2023-01-21T13:27:16.224753 | 2020-12-03T13:04:43 | 2020-12-03T13:04:43 | 318,126,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31 | h | #pragma once
class test1
{
};
| [
"st087823@student.spbu.ru"
] | st087823@student.spbu.ru |
f48a6dfa5b953a5e7c17f2fc0a5917afd97875f9 | 7df60cff2293ef347835be310ff94bb4339c8507 | /Rush 2/PapaXmasElf.hpp | db7e26b16c791c0a95864d27da3bea3f0d9f3f63 | [] | no_license | halil28450/PoolCPP | e9ca42e2adf8a3e2333e2519a33b4cce1a5d92fc | b74387e9cf7bdf853dca86be984bb196f2e0558a | refs/heads/main | 2023-03-18T19:04:33.014416 | 2021-02-15T12:14:57 | 2021-02-15T12:14:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | hpp | //
// Created by nicolass on 15/01/2021.
//
#ifndef B_CPP_300_STG_3_1_CPPRUSH2_NICOLAS_SCHNEIDER_PAPAXMASELF_HPP
#define B_CPP_300_STG_3_1_CPPRUSH2_NICOLAS_SCHNEIDER_PAPAXMASELF_HPP
#include "IElf.hpp"
#include "PapaXmasTable.hpp"
#include "ConveyorBelt.hpp"
class PapaXmasElf : public IElf
{
public :
PapaXmasElf(ITable*);
~PapaXmasElf();
std::vector<std::string> lookAtTable();
Object *pressIn();
void wrap(Wrap*, Object*);
void pressOut();
bool put_on_table(Object*);
private :
class ITable *_table;
class ConveyorBelt *_conveyor_belt;
class Object *_in_hand;
};
#endif // B_CPP_300_STG_3_1_CPPRUSH2_NICOLAS_SCHNEIDER_PAPAXMASELF_HPP | [
"arthur.robine@epitech.eu"
] | arthur.robine@epitech.eu |
1954475dc809605f6007876e7ff809924466d166 | 2bf09444ba4ef5b846454bfff661150745ae2d54 | /.ipd/lib/ge211/src/ge211_error.h | 3cbd7e42b708f4ce5d6e9412abda04d96445e24f | [] | no_license | siddhartha-s/295-fp-frogger | 052ee4f07bb1b4a77e4a019b8e3e6a7c49ba3361 | 0826c0f6a10cd7f3b4c54fbbf8ecd9f9a92b6ee6 | refs/heads/master | 2020-04-09T10:59:08.118940 | 2018-12-12T21:49:30 | 2018-12-12T21:49:30 | 160,290,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,667 | h | #pragma once
#include "ge211_forward.h"
#include <exception>
#include <memory>
#include <sstream>
#include <string>
namespace ge211 {
/// An exception hierarchy for %ge211 to report errors.
namespace exceptions {
/// The root of the %ge211 exception hierarchy. Exceptions thrown by
/// %ge211 are derived from Exception_base.
///
/// The constructor of Exception_base is private, which means that
/// you cannot construct it directly, nor can you derive from it.
/// However, its derived class Client_logic_error has a public
/// constructor, so you can use it as you wish.
class Exception_base : public std::exception
{
public:
/// The error message associated with the exception. This
/// pointer is guaranteed to be good as long as the exception
/// exists and hasn't been mutated. If you need it for longer,
/// copy it to a std::string.
const char* what() const noexcept override;
private:
Exception_base(const std::string& message);
/// Derived classes
friend class Client_logic_error;
friend class Environment_error;
std::shared_ptr<const std::string> message_;
};
/// An exception that indicates that a logic error was performed
/// by the client. For example, a Client_logic_error is thrown by
/// Abstract_game::get_window() const if that function is called
/// before the Window has been created. Client code may throw or
/// derive from Client_logic_error as well.
class Client_logic_error : public Exception_base
{
public:
/// Constructs the error, given the provided error message.
Client_logic_error(const std::string& message);
};
/// Indicates that an error was encountered by the game engine or
/// in the client's environment.
/// This could indicate a problem with your video driver,
/// a missing file, or even a bug in %ge211 itself. The derived
/// classes indicate more precisely the nature of the condition.
class Environment_error : public Exception_base
{
Environment_error(const std::string& message);
/// Throwers
friend class ge211::Window;
/// Derived classes
friend class Ge211_logic_error;
friend class Host_error;
};
/// Indicates a condition unexpected by %ge211, that appears
/// to break its invariants. This may very well indicate a bug
/// in %ge211. Please report it if you see one of these.
class Ge211_logic_error : public Environment_error
{
Ge211_logic_error(const std::string& message);
/// Throwers
friend class detail::Render_sprite;
friend class sprites::Text_sprite;
};
/// Indicates an exception from the host environment being
/// passed along by %ge211. The host environment is usually
/// SDL2, so these exceptions may include a reason provided
/// by SDL2.
class Host_error : public Environment_error
{
Host_error(const std::string& extra_message = "");
/// Derived classes
friend class File_error;
friend class Font_error;
friend class Image_error;
/// Throwers
friend class ge211::Window;
friend class detail::Renderer;
friend class detail::Render_sprite;
friend class ge211::Text_sprite;
friend class detail::Texture;
};
/// Indicates an error opening a file.
class File_error final : public Host_error
{
File_error(const std::string& message);
static File_error could_not_open(const std::string& filename);
/// Thrower
friend class detail::File_resource;
};
/// Indicates an error loading a font front an already-open file.
class Font_error final : public Host_error
{
Font_error(const std::string& message);
static Font_error could_not_load(const std::string& filename);
/// Thrower
friend class ge211::Font;
};
/// Indicates an error loading an image from an already-open file.
class Image_error final : public Host_error
{
Image_error(const std::string& message);
static Image_error could_not_load(const std::string& filename);
/// Thrower
friend class sprites::Image_sprite;
};
} // end namespace exception
namespace detail {
enum class Log_level
{
debug,
info,
warn,
fatal,
};
// Right now a Logger just keeps track of the current log
// level, and there's only one Logger (Singleton Pattern).
class Logger
{
public:
using Level = Log_level;
Level level() const noexcept { return level_; }
void level(Level level) noexcept { level_ = level; }
static Logger& instance() noexcept;
private:
Logger() noexcept = default;
Level level_ = Level::warn;
};
// A Log_message accumulate information and then prints it all at
// once when it's going to be destroyed.
class Log_message
{
public:
using Level = Log_level;
explicit Log_message(Level level = Level::debug);
explicit Log_message(std::string reason,
Level level = Level::debug) noexcept;
template <class T>
Log_message& operator<<(const T& value)
{
if (active_) message_ << value;
return *this;
}
// A Log_message has important work to do when it's destroyed.
virtual ~Log_message();
// A Log_message should not be copied.
Log_message(const Log_message&) = delete;
Log_message& operator=(const Log_message&) = delete;
// But it can be moved.
Log_message(Log_message&&) = default;
Log_message& operator=(Log_message&&) = default;
private:
std::string reason_;
std::ostringstream message_;
bool active_;
};
Log_message debug(std::string reason = "");
Log_message info(std::string reason = "");
Log_message warn(std::string reason = "");
Log_message fatal(std::string reason = "");
Log_message info_sdl();
Log_message warn_sdl();
Log_message fatal_sdl();
} // end namespace detail
}
| [
"sid@Sids-MBP.attlocal.net"
] | sid@Sids-MBP.attlocal.net |
c62fd5be42eaa3561a2151e0b7500843c0610632 | 2c6c7ba5399b5a4d87061bf4206a853cd33f351c | /lib/Dialect/SystemC/SystemCTypes.cpp | 9e3da974c0eca80abdd6603eee8b2a9fcbbe7e24 | [
"LLVM-exception",
"Apache-2.0"
] | permissive | llvm/circt | fbd479f869f296be2e1db95fa6a2808538f24703 | e6057090973eb8a428dce9d3e9ddb63ec4088b55 | refs/heads/main | 2023-09-02T06:34:28.649450 | 2023-09-01T22:25:38 | 2023-09-01T22:25:38 | 245,072,514 | 1,242 | 275 | NOASSERTION | 2023-09-14T20:25:58 | 2020-03-05T04:57:42 | C++ | UTF-8 | C++ | false | false | 10,605 | cpp | //===- SystemCTypes.cpp - Implement the SystemC types ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the SystemC dialect type system.
//
//===----------------------------------------------------------------------===//
#include "circt/Dialect/SystemC/SystemCTypes.h"
#include "circt/Dialect/SystemC/SystemCDialect.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/DialectImplementation.h"
#include "llvm/ADT/TypeSwitch.h"
using namespace circt;
using namespace circt::systemc;
Type systemc::getSignalBaseType(Type type) {
return TypeSwitch<Type, Type>(type)
.Case<InputType, OutputType, InOutType, SignalType>(
[](auto ty) { return ty.getBaseType(); })
.Default([](auto ty) { return Type(); });
}
std::optional<size_t> systemc::getBitWidth(Type type) {
return llvm::TypeSwitch<Type, std::optional<size_t>>(type)
.Case<IntegerType, IntType, UIntType, BigIntType, BigUIntType,
BitVectorType, LogicVectorType>(
[](auto ty) { return ty.getWidth(); })
.Case<LogicType>([](auto ty) { return 1; })
.Default([](auto ty) { return std::nullopt; });
}
namespace circt {
namespace systemc {
namespace detail {
bool operator==(const PortInfo &a, const PortInfo &b) {
return a.name == b.name && a.type == b.type;
}
// NOLINTNEXTLINE(readability-identifier-naming)
llvm::hash_code hash_value(const PortInfo &pi) {
return llvm::hash_combine(pi.name, pi.type);
}
} // namespace detail
} // namespace systemc
} // namespace circt
//===----------------------------------------------------------------------===//
// ModuleType
//===----------------------------------------------------------------------===//
/// Parses a systemc::ModuleType of the format:
/// !systemc.module<moduleName(portName1: type1, portName2: type2)>
Type ModuleType::parse(AsmParser &odsParser) {
if (odsParser.parseLess())
return Type();
StringRef moduleName;
if (odsParser.parseKeyword(&moduleName))
return Type();
SmallVector<ModuleType::PortInfo> ports;
if (odsParser.parseCommaSeparatedList(
AsmParser::Delimiter::Paren, [&]() -> ParseResult {
StringRef name;
PortInfo port;
if (odsParser.parseKeyword(&name) || odsParser.parseColon() ||
odsParser.parseType(port.type))
return failure();
port.name = StringAttr::get(odsParser.getContext(), name);
ports.push_back(port);
return success();
}))
return Type();
if (odsParser.parseGreater())
return Type();
return ModuleType::getChecked(
UnknownLoc::get(odsParser.getContext()), odsParser.getContext(),
StringAttr::get(odsParser.getContext(), moduleName), ports);
}
/// Prints a systemc::ModuleType in the format:
/// !systemc.module<moduleName(portName1: type1, portName2: type2)>
void ModuleType::print(AsmPrinter &odsPrinter) const {
odsPrinter << '<' << getModuleName().getValue() << '(';
llvm::interleaveComma(getPorts(), odsPrinter, [&](auto port) {
odsPrinter << port.name.getValue() << ": " << port.type;
});
odsPrinter << ")>";
}
//===----------------------------------------------------------------------===//
// Type storages
//===----------------------------------------------------------------------===//
namespace circt {
namespace systemc {
namespace detail {
/// Integer Type Storage and Uniquing.
struct IntegerWidthStorage : public TypeStorage {
IntegerWidthStorage(unsigned width) : width(width) {}
/// The hash key used for uniquing.
using KeyTy = unsigned;
static llvm::hash_code hashKey(const KeyTy &key) {
return llvm::hash_value(key);
}
bool operator==(const KeyTy &key) const { return KeyTy(width) == key; }
static IntegerWidthStorage *construct(mlir::TypeStorageAllocator &allocator,
KeyTy key) {
return new (allocator.allocate<IntegerWidthStorage>())
IntegerWidthStorage(key);
}
unsigned width : 32;
};
} // namespace detail
} // namespace systemc
} // namespace circt
//===----------------------------------------------------------------------===//
// Integer types
//===----------------------------------------------------------------------===//
IntBaseType IntBaseType::get(MLIRContext *context) {
return Base::get(context);
}
IntType IntType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned IntType::getWidth() { return getImpl()->width; }
UIntBaseType UIntBaseType::get(MLIRContext *context) {
return Base::get(context);
}
UIntType UIntType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned UIntType::getWidth() { return getImpl()->width; }
SignedType SignedType::get(MLIRContext *context) { return Base::get(context); }
BigIntType BigIntType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned BigIntType::getWidth() { return getImpl()->width; }
UnsignedType UnsignedType::get(MLIRContext *context) {
return Base::get(context);
}
BigUIntType BigUIntType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned BigUIntType::getWidth() { return getImpl()->width; }
//===----------------------------------------------------------------------===//
// Bit-vector types
//===----------------------------------------------------------------------===//
BitVectorBaseType BitVectorBaseType::get(MLIRContext *context) {
return Base::get(context);
}
BitVectorType BitVectorType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned BitVectorType::getWidth() { return getImpl()->width; }
LogicVectorBaseType LogicVectorBaseType::get(MLIRContext *context) {
return Base::get(context);
}
LogicVectorType LogicVectorType::get(MLIRContext *context, unsigned width) {
return Base::get(context, width);
}
unsigned LogicVectorType::getWidth() { return getImpl()->width; }
//===----------------------------------------------------------------------===//
// Generated logic
//===----------------------------------------------------------------------===//
#define GET_TYPEDEF_CLASSES
#include "circt/Dialect/SystemC/SystemCTypes.cpp.inc"
void SystemCDialect::registerTypes() {
addTypes<
#define GET_TYPEDEF_LIST
#include "circt/Dialect/SystemC/SystemCTypes.cpp.inc"
>();
addTypes<UIntType, IntType, BigIntType, BigUIntType, UIntBaseType,
IntBaseType, SignedType, UnsignedType, BitVectorBaseType,
BitVectorType, LogicVectorBaseType, LogicVectorType>();
}
//===----------------------------------------------------------------------===//
// Custom type parsers and printers
//===----------------------------------------------------------------------===//
template <typename Ty>
static LogicalResult parseIntegerOrBitVector(DialectAsmParser &parser,
Type &type) {
unsigned width;
auto *ctxt = parser.getContext();
if (parser.parseLess() || parser.parseInteger(width) || parser.parseGreater())
return failure();
type = Ty::get(ctxt, width);
return success();
}
static mlir::OptionalParseResult customTypeParser(DialectAsmParser &parser,
StringRef mnemonic,
llvm::SMLoc loc, Type &type) {
auto *ctxt = parser.getContext();
if (mnemonic == IntBaseType::getMnemonic()) {
type = IntBaseType::get(ctxt);
return success();
}
if (mnemonic == UIntBaseType::getMnemonic()) {
type = UIntBaseType::get(ctxt);
return success();
}
if (mnemonic == SignedType::getMnemonic()) {
type = SignedType::get(ctxt);
return success();
}
if (mnemonic == UnsignedType::getMnemonic()) {
type = UnsignedType::get(ctxt);
return success();
}
if (mnemonic == BitVectorBaseType::getMnemonic()) {
type = BitVectorBaseType::get(ctxt);
return success();
}
if (mnemonic == LogicVectorBaseType::getMnemonic()) {
type = LogicVectorBaseType::get(ctxt);
return success();
}
if (mnemonic == IntType::getMnemonic())
return parseIntegerOrBitVector<IntType>(parser, type);
if (mnemonic == UIntType::getMnemonic())
return parseIntegerOrBitVector<UIntType>(parser, type);
if (mnemonic == BigIntType::getMnemonic())
return parseIntegerOrBitVector<BigIntType>(parser, type);
if (mnemonic == BigUIntType::getMnemonic())
return parseIntegerOrBitVector<BigUIntType>(parser, type);
if (mnemonic == BitVectorType::getMnemonic())
return parseIntegerOrBitVector<BitVectorType>(parser, type);
if (mnemonic == LogicVectorType::getMnemonic())
return parseIntegerOrBitVector<LogicVectorType>(parser, type);
return failure();
}
static LogicalResult customTypePrinter(Type type, DialectAsmPrinter &printer) {
return TypeSwitch<Type, LogicalResult>(type)
.Case<IntType, UIntType, BigIntType, BigUIntType, BitVectorType,
LogicVectorType>([&](auto ty) {
printer << ty.getMnemonic() << "<" << ty.getWidth() << ">";
return success();
})
.Case<IntBaseType, UIntBaseType, SignedType, UnsignedType,
BitVectorBaseType, LogicVectorBaseType>([&](auto ty) {
printer << ty.getMnemonic();
return success();
})
.Default([](auto ty) { return failure(); });
}
/// Parse a type registered with this dialect.
Type SystemCDialect::parseType(DialectAsmParser &parser) const {
Type type;
llvm::SMLoc loc = parser.getCurrentLocation();
StringRef mnemonic;
mlir::OptionalParseResult result =
generatedTypeParser(parser, &mnemonic, type);
if (result.has_value() && !result.value())
return type;
result = customTypeParser(parser, mnemonic, loc, type);
if (result.has_value() && !result.value())
return type;
parser.emitError(loc) << "unknown type `" << mnemonic
<< "` in dialect `systemc`";
return {};
}
/// Print a type registered with this dialect.
void SystemCDialect::printType(Type type, DialectAsmPrinter &printer) const {
if (succeeded(generatedTypePrinter(type, printer)) ||
succeeded(customTypePrinter(type, printer)))
return;
assert(false && "no printer for unknown `systemc` dialect type");
printer << "<<UnknownType>>";
}
| [
"noreply@github.com"
] | llvm.noreply@github.com |
aa34921ac559af83f434ba4ba5c55637e654db10 | 5f303aef09db373d24db95e797c69631461af5ef | /The Smallest Pair(codechef).cpp | 28613e4776592684b20aefd343354a05a6d4eed3 | [] | no_license | pratik2266/21-DAYS-PROGRAMMING-CHALLENGE-ACES | b646f6f810a4d105037b9614f4b9ba09ef965ba6 | 1e71355682bde18d5e0c1cc55ca8ce0e52931342 | refs/heads/main | 2022-12-30T21:54:32.865214 | 2020-10-25T12:11:08 | 2020-10-25T12:11:08 | 301,333,782 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
cout<<a[0]+a[1]<<endl;
}
return 0;
} | [
"noreply@github.com"
] | pratik2266.noreply@github.com |
066289f13ec67b50d3ed1bfd97f25a16f3482017 | 826c2762805e39ac1c080091e7f4f642fb41e19a | /ouniverse_2020_2_ue4_source/ouniverse/Protocol/System/Ui/SymMenuU.cpp | ffceeaf65043be68a73b7d6895105b7f6e9b91ce | [] | no_license | legendofceo/ouniverse_ue_cpp_source_deprecated_pre2022 | fe625f69210c9c038202b8305495bdf373657ea8 | 729f12569f805ce74e602f8b13bab0ac318358a5 | refs/heads/main | 2023-08-12T19:14:39.216646 | 2021-10-17T16:19:29 | 2021-10-17T16:19:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | cpp | //Copyright 2015-2019, All Rights Reserved.
#include "Protocol/System/Ui/SymMenuU.h"
#include "Protocol/System/SymMenuP.h"
#include "Ui/UiButtonNew.h"
#include "Ui/UiEventCodes.h"
void USymMenu::NativeConstruct()
{
Super::NativeConstruct();
V_NewGame->SetupButton(REG::NewGame, this);
V_Continue->SetupButton(REG::Continue, this);
V_User->SetupButton(REG::User, this);
V_Loadout->SetupButton(REG::Loadout, this);
V_Trophey->SetupButton(REG::Trophey, this);
V_Settings->SetupButton(REG::Settings, this);
V_Update->SetupButton(REG::Update, this);
V_Credits->SetupButton(REG::Credits, this);
V_News->SetupButton(REG::News, this);
V_Scribe->SetupButton(REG::Scribe, this);
}
void USymMenu::UiConstruct(SymMenuP* InPro)
{
Pro_ = InPro;
}
void USymMenu::EventUi(int WidgetID, int InEventID, UUserWidget* InWidget)
{
if (InEventID == UiEventsC::ButtonAccept)
{
switch (WidgetID) {
case REG::User:
Pro_->AcceptUser();
break;
case REG::Scribe:
Pro_->AcceptWriter();
break;
}
}
} | [
"work.by.ceo@gmail.com"
] | work.by.ceo@gmail.com |
6a170804e7c8d4f9c5b6e89f63739374360cd989 | 7c1dc9907f6b009a87abb5a8a50e771a56b86bf4 | /DataStructure/Atcoder/150_4.cpp | e49a275c9f4c33e061e16b74e446ce46e2769c31 | [] | no_license | TarunSaini063/Coding | 4b6a022a23488bbf5a4a1a746d865388095707ab | cd0abd63b469ab7f3be52eca0b5305a49c3f25b6 | refs/heads/master | 2021-08-22T17:41:58.152521 | 2021-05-22T08:58:28 | 2021-05-22T08:58:28 | 252,940,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 951 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ld double
#define ll long long
#define pb emplace_back
#define mk make_pair
#define mod 1000000007
#define ff first
#define ss second
#define sz(x) (int)x.size()
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define all(x) x.begin(),x.end()
ll power(ll a, ll b) {ll res = 1; a = a % mod; while (b) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b /= 2;} return res;}
ll invmod(ll a) {return power(a, mod - 2);}
ll n, m, cd = 1, c = 1;
int lcm(int a, int b)
{
return a / __gcd(a, b) * b;
}
int main()
{
cin >> n >> m;
int x;
for (int i = 1; i <= n; i++)
{
ll a;
cin >> a;
cd = lcm(cd, a);
c = lcm(c, a / 2);
int tmp = 0;
while (a % 2 == 0)
{
tmp++;
a /= 2;
}
if (i == 1)
x = tmp;
else if (x != tmp || c > m)
{
cout << 0 << endl;
exit(0);
}
}
if (m < c)
cout << 0;
else
cout << ((m - c) / cd) + 1;
return 0;
}
| [
"tsaini063@outlook.com"
] | tsaini063@outlook.com |
bd3b7ddcb15e4bc1fe1647953f4c20a66fce2c9d | 01b79a7a0eefc62174ffb9edd2a0f35353a451c5 | /garageDoorGA.ino | 474e65ba73632863f9aa9d412e1f019d9676d07d | [
"MIT"
] | permissive | dmacattack/garageDoorGA | 8dbac73243faf1f55b31cdb3d6ce8966a39b0755 | 57ea4d95e9c3c57c1ec63dd341a235b916d32af3 | refs/heads/master | 2020-04-11T05:42:00.940577 | 2018-12-21T20:00:53 | 2018-12-21T20:00:53 | 161,557,574 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,746 | ino | //---------------------------------------------------------------
// includes
//---------------------------------------------------------------
#include <ESP8266WiFi.h>
#include "WifiCredentials.h"
// refs : https://randomnerdtutorials.com/esp8266-web-server/
//---------------------------------------------------------------
// macros
//---------------------------------------------------------------
// Comment this out to disable prints and save space
#define DBG_ENABLED 1
#if DBG_ENABLED
#define DBG_PRINT(fn, msg) debug_print(fn, msg)
#else
#define DBG_PRINT(fn, msg) 0; // do nothing
#endif
//---------------------------------------------------------------
// Types
//---------------------------------------------------------------
typedef unsigned int UInt32;
typedef unsigned short UInt16;
typedef unsigned char UInt8;
typedef int Int32;
typedef short Int16;
typedef char Int8;
//---------------------------------------------------------------
// constants
//---------------------------------------------------------------
String mVersionNumber = "-------VERSION 0.1-------";
const Int32 LED_PIN = LED_BUILTIN; // ESP8266 onboard, green LED
const Int32 TOGGLE_DURATION = 1000; // full second
const Int32 BUTTON_PIN = 13; // button pin
//---------------------------------------------------------------
// member variables
//---------------------------------------------------------------
WiFiServer server(80); // Set web server port number to 80
String header = ""; // Variable to store the HTTP request
//---------------------------------------------------------------
// setup
//
// setup the wifi, pins, and assign interupts
//---------------------------------------------------------------
void setup()
{
#if DBG_ENABLED
Serial.begin(115200);
#endif
// print the version number
DBG_PRINT("", ""); // intentional blank line
DBG_PRINT("", "--------------------------");
DBG_PRINT("", mVersionNumber );
DBG_PRINT("", "--------------------------");
// setup the hardware pins
pinMode(BUTTON_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(BUTTON_PIN, LOW);
digitalWrite(LED_PIN, LOW);
// connect to wifi
DBG_PRINT("setup", " connecting to wifi ");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED)
{
digitalWrite(LED_PIN, HIGH); // blink the LED button to indicate connection status
delay(250);
digitalWrite(LED_PIN, LOW); // blink the LED button to indicate connection status
delay(250);
DBG_PRINT("setup", "." );
}
Serial.print("Wifi connected. ip address = ");
Serial.println(WiFi.localIP() );
// set the LED to solid to indicate connected
digitalWrite(LED_PIN, HIGH); // blink the LED button to indicate connection status
// start the webserver
server.begin();
}
//---------------------------------------------------------------
// loop
// serve any web requests
//---------------------------------------------------------------
void loop()
{
WiFiClient client = server.available(); // Listen for incoming clients
if (client)
{ // If a new client connects,
DBG_PRINT("loop", "New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) // loop while the client's connected
{
if (client.available()) // if there's bytes to read from the client,
{
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n')
{
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0)
{
// parse any specific requests
parseHTTPRequest();
setHTTPHeader(client);
// Web Page Heading
client.println("<body><h1>Garage Door Web Server</h1>");
// Display info for the open/close button of the garage door
client.println("<p>Click to open/close the Garage Door </p>");
client.println("<p><a href=\"/garage/toggle\"><button class=\"button\">OPEN / CLOSE</button></a></p>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
DBG_PRINT("loop", "Client disconnected.");
DBG_PRINT("loop", "");
}
}
//---------------------------------------------------------------
// parseHTTPRequest
// parse the http request
//---------------------------------------------------------------
void parseHTTPRequest()
{
// turns the GPIOs on and off
if (header.indexOf("GET /garage/open") >= 0)
{
DBG_PRINT("parseHTTPRequest", "open garage door");
toggleGarageDoorButton();
}
else if (header.indexOf("GET /garage/close") >= 0)
{
DBG_PRINT("parseHTTPRequest", "close garage door");
toggleGarageDoorButton();
}
else if (header.indexOf("GET /garage/toggle") >= 0)
{
DBG_PRINT("parseHTTPRequest", "open/close garage door");
toggleGarageDoorButton();
}
}
//---------------------------------------------------------------
// toggleGarageDoorButton
// press and release the button for the garage door
//---------------------------------------------------------------
void toggleGarageDoorButton()
{
digitalWrite(BUTTON_PIN, HIGH);
delay(TOGGLE_DURATION);
digitalWrite(BUTTON_PIN, LOW);
}
//---------------------------------------------------------------
// setHTTPHeader
// set the http client header
//---------------------------------------------------------------
void setHTTPHeader(WiFiClient &client)
{
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #77878A;}</style></head>");
}
//---------------------------------------------------------------
// debug_print
//
// easy way to enable/disable debug prints.
// change the macro at the top of the file
//---------------------------------------------------------------
void debug_print(String fn, String msg)
{
Serial.println(fn + ": " + msg);
}
| [
"dan.b.macdonald@gmail.com"
] | dan.b.macdonald@gmail.com |
852b81f219225cf64dd2608dc2eb1c16f5aa8075 | 70813fd982be0db84fe24b5ebcc9925270d585fd | /StripeTastic.Firmware/lib/StripeBridge/Enums/EffectDirections.h | d75a4e61b97c41aa4ce881cef35c53bac0c40494 | [
"MIT"
] | permissive | Ruffo324/StripeTastic | 36973ef229f0f86e3158a5af74f217e418bfb2a3 | f4490470e042a13ee52884ff20dc623dd07cf7cb | refs/heads/master | 2023-01-21T21:07:37.481242 | 2020-10-28T19:34:11 | 2020-10-28T19:34:11 | 282,495,575 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 335 | h | #pragma once
namespace StripeBridge
{
namespace Enums
{
/**
* Set's the direction for the active Enums::Effects.
* TODO: Not implemented currently.
*/
enum EffectDirections
{
Left,
Right
};
} // namespace Enums
} // namespace StripeBridge | [
"ruffo324@gmail.com"
] | ruffo324@gmail.com |
d0b351d0410e46ebe951fcede3d756437176725f | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/enduser/netmeeting/h/cpnmctl1.h | 4721c5b1d925075f4827818e16b2a9ca5dc8ab2b | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 636 | h |
//////////////////////////////////////////////////////////////////////////////
// CProxyINmAppletNotify
template <class T>
class CProxyINmAppletNotify : public IConnectionPointImpl<T, &IID_INmAppletNotify, CComDynamicUnkArray>
{
public:
//INmAppletNotify
public:
HRESULT Fire_OnStateChanged(
int State)
{
T* pT = (T*)this;
pT->Lock();
HRESULT ret;
IUnknown** pp = m_vec.begin();
while (pp < m_vec.end())
{
if (*pp != NULL)
{
INmAppletNotify* pINmAppletNotify = reinterpret_cast<INmAppletNotify*>(*pp);
ret = pINmAppletNotify->OnStateChanged(State);
}
pp++;
}
pT->Unlock();
return ret;
}
};
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
7766307f17284e9013a97e74933f77b0251fd8dc | e0482a657a37ea9035695d5b7f023edab2d600b5 | /src/src/core/belief.cpp | b1a11daa2d2bbb16a4c0328a73c35ebb95434ddc | [] | no_license | boettiger-lab/despot | 9f28f69970a0058f42d611634b86d8c205f76d76 | c8e1c3bb9fb4867cd5ee905180fac5e2125b1200 | refs/heads/master | 2021-06-19T16:23:03.808822 | 2017-08-02T19:35:28 | 2017-08-02T19:35:28 | 86,734,632 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,356 | cpp | #include <despot/core/belief.h>
#include <despot/core/pomdp.h>
using namespace std;
namespace despot {
/* =============================================================================
* ParticleBelief class
* =============================================================================*/
Belief::Belief(const DSPOMDP* model) :
model_(model) {
}
Belief::~Belief() {
}
string Belief::text() const {
return "AbstractBelief";
}
ostream& operator<<(ostream& os, const Belief& belief) {
os << (&belief)->text();
return os;
}
vector<State*> Belief::Sample(int num, vector<State*> particles,
const DSPOMDP* model) {
double unit = 1.0 / num;
double mass = Random::RANDOM.NextDouble(0, unit);
int pos = 0;
double cur = particles[0]->weight;
vector<State*> sample;
for (int i = 0; i < num; i++) {
while (mass > cur) {
pos++;
if (pos == particles.size())
pos = 0;
cur += particles[pos]->weight;
}
mass += unit;
State* particle = model->Copy(particles[pos]);
particle->weight = unit;
sample.push_back(particle);
}
random_shuffle(sample.begin(), sample.end());
logd << "[Belief::Sample] Sampled " << sample.size() << " particles"
;
for (int i = 0; i < sample.size(); i++) {
logv << " " << i << " = " << *sample[i] ;
}
return sample;
}
vector<State*> Belief::Resample(int num, const vector<State*>& belief,
const DSPOMDP* model, History history, int hstart) {
double unit = 1.0 / num;
double mass = Random::RANDOM.NextDouble(0, unit);
int pos = 0;
double cur = belief[0]->weight;
double reward;
OBS_TYPE obs;
vector<State*> sample;
int count = 0;
double max_wgt = Globals::NEG_INFTY;
int trial = 0;
while (count < num && trial < 200 * num) {
// Pick next particle
while (mass > cur) {
pos++;
if (pos == belief.size())
pos = 0;
cur += belief[pos]->weight;
}
trial++;
mass += unit;
State* particle = model->Copy(belief[pos]);
// Step through history
double log_wgt = 0;
for (int i = hstart; i < history.Size(); i++) {
model->Step(*particle, Random::RANDOM.NextDouble(),
history.Action(i), reward, obs);
double prob = model->ObsProb(history.Observation(i), *particle,
history.Action(i));
if (prob > 0) {
log_wgt += log(prob);
} else {
model->Free(particle);
break;
}
}
// Add to sample if survived
if (particle->IsAllocated()) {
count++;
particle->weight = log_wgt;
sample.push_back(particle);
max_wgt = max(log_wgt, max_wgt);
}
// Remove particles with very small weights
if (count == num) {
for (int i = sample.size() - 1; i >= 0; i--)
if (sample[i]->weight - max_wgt < log(1.0 / num)) {
model->Free(sample[i]);
sample.erase(sample.begin() + i);
count--;
}
}
}
double total_weight = 0;
for (int i = 0; i < sample.size(); i++) {
sample[i]->weight = exp(sample[i]->weight - max_wgt);
total_weight += sample[i]->weight;
}
for (int i = 0; i < sample.size(); i++) {
sample[i]->weight = sample[i]->weight / total_weight;
}
logd << "[Belief::Resample] Resampled " << sample.size() << " particles"
;
for (int i = 0; i < sample.size(); i++) {
logv << " " << i << " = " << *sample[i] ;
}
return sample;
}
vector<State*> Belief::Resample(int num, const DSPOMDP* model,
const StateIndexer* indexer, int action, OBS_TYPE obs) {
if (indexer == NULL) {
loge << "[Belief::Resample] indexer cannot be null" ;
exit(1);
}
vector<State*> sample;
for (int s = 0; s < indexer->NumStates(); s++) {
const State* state = indexer->GetState(s);
double prob = model->ObsProb(obs, *state, action);
if (prob > 0) {
State* particle = model->Copy(state);
particle->weight = prob;
sample.push_back(particle);
}
}
return sample;
}
vector<State*> Belief::Resample(int num, const Belief& belief, History history,
int hstart) {
double reward;
OBS_TYPE obs;
vector<State*> sample;
int count = 0;
int pos = 0;
double max_wgt = Globals::NEG_INFTY;
vector<State*> particles;
int trial = 0;
while (count < num || trial < 200 * num) {
// Pick next particle
if (pos == particles.size()) {
particles = belief.Sample(num);
pos = 0;
}
State* particle = particles[pos];
trial++;
// Step through history
double log_wgt = 0;
for (int i = hstart; i < history.Size(); i++) {
belief.model_->Step(*particle, Random::RANDOM.NextDouble(),
history.Action(i), reward, obs);
double prob = belief.model_->ObsProb(history.Observation(i),
*particle, history.Action(i));
if (prob > 0) {
log_wgt += log(prob);
} else {
belief.model_->Free(particle);
break;
}
}
// Add to sample if survived
if (particle->IsAllocated()) {
particle->weight = log_wgt;
sample.push_back(particle);
max_wgt = max(log_wgt, max_wgt);
count++;
}
// Remove particles with very small weights
if (count == num) {
for (int i = sample.size() - 1; i >= 0; i--) {
if (sample[i]->weight - max_wgt < log(1.0 / num)) {
belief.model_->Free(sample[i]);
sample.erase(sample.begin() + i);
count--;
}
}
}
pos++;
}
// Free unused particles
for (int i = pos; i < particles.size(); i++)
belief.model_->Free(particles[i]);
double total_weight = 0;
for (int i = 0; i < sample.size(); i++) {
sample[i]->weight = exp(sample[i]->weight - max_wgt);
total_weight += sample[i]->weight;
}
for (int i = 0; i < sample.size(); i++) {
sample[i]->weight = sample[i]->weight / total_weight;
}
logd << "[Belief::Resample] Resampled " << sample.size() << " particles"
;
for (int i = 0; i < sample.size(); i++) {
logv << " " << i << " = " << *sample[i] ;
}
return sample;
}
/* =============================================================================
* ParticleBelief class
* =============================================================================*/
ParticleBelief::ParticleBelief(vector<State*> particles, const DSPOMDP* model,
Belief* prior, bool split) :
Belief(model),
particles_(particles),
num_particles_(particles.size()),
prior_(prior),
split_(split),
state_indexer_(NULL) {
if (fabs(State::Weight(particles) - 1.0) > 1e-6) {
loge << "[ParticleBelief::ParticleBelief] Particle weights sum to " << State::Weight(particles) << " instead of 1" ;
exit(1);
}
if (split) {
// Maintain more particles to avoid degeneracy
while (2 * num_particles_ < 5000)
num_particles_ *= 2;
if (particles_.size() < num_particles_) {
logi << "[ParticleBelief::ParticleBelief] Splitting " << particles_.size()
<< " particles into " << num_particles_ << " particles." ;
vector<State*> new_particles;
int n = num_particles_ / particles_.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < particles_.size(); j++) {
State* particle = particles_[j];
State* copy = model_->Copy(particle);
copy->weight /= n;
new_particles.push_back(copy);
}
}
for (int i = 0; i < particles_.size(); i++)
model_->Free(particles_[i]);
particles_ = new_particles;
}
}
if (fabs(State::Weight(particles) - 1.0) > 1e-6) {
loge << "[ParticleBelief::ParticleBelief] Particle weights sum to " << State::Weight(particles) << " instead of 1" ;
exit(1);
}
random_shuffle(particles_.begin(), particles_.end());
// cerr << "Number of particles in initial belief: " << particles_.size() ;
if (prior_ == NULL) {
for (int i = 0; i < particles.size(); i++)
initial_particles_.push_back(model_->Copy(particles[i]));
}
}
ParticleBelief::~ParticleBelief() {
for (int i = 0; i < particles_.size(); i++) {
model_->Free(particles_[i]);
}
for (int i = 0; i < initial_particles_.size(); i++) {
model_->Free(initial_particles_[i]);
}
}
void ParticleBelief::state_indexer(const StateIndexer* indexer) {
state_indexer_ = indexer;
}
const vector<State*>& ParticleBelief::particles() const {
return particles_;
}
vector<State*> ParticleBelief::Sample(int num) const {
return Belief::Sample(num, particles_, model_);
}
void ParticleBelief::Update(int action, OBS_TYPE obs) {
history_.Add(action, obs);
vector<State*> updated;
double total_weight = 0;
double reward;
OBS_TYPE o;
// Update particles
for (int i = 0; i <particles_.size(); i++) {
State* particle = particles_[i];
bool terminal = model_->Step(*particle, Random::RANDOM.NextDouble(),
action, reward, o);
double prob = model_->ObsProb(obs, *particle, action);
if (!terminal && prob) { // Terminal state is not required to be explicitly represented and may not have any observation
particle->weight *= prob;
total_weight += particle->weight;
updated.push_back(particle);
} else {
model_->Free(particle);
}
}
logd << "[ParticleBelief::Update] " << updated.size()
<< " particles survived among " << particles_.size() ;
particles_ = updated;
// Resample if the particle set is empty
if (particles_.size() == 0) {
logw << "Particle set is empty!" ;
if (prior_ != NULL) {
logw
<< "Resampling by drawing random particles from prior which are consistent with history"
;
particles_ = Resample(num_particles_, *prior_, history_);
} else {
logw
<< "Resampling by searching initial particles which are consistent with history"
;
particles_ = Resample(num_particles_, initial_particles_, model_,
history_);
}
if (particles_.size() == 0 && state_indexer_ != NULL) {
logw
<< "Resampling by searching states consistent with last (action, observation) pair"
;
particles_ = Resample(num_particles_, model_, state_indexer_,
action, obs);
}
if (particles_.size() == 0) {
logw << "Resampling failed - Using initial particles" ;
for (int i = 0; i < initial_particles_.size(); i ++)
particles_.push_back(model_->Copy(initial_particles_[i]));
}
//Update total weight so that effective number of particles are computed correctly
total_weight = 0;
for (int i = 0; i < particles_.size(); i++) {
State* particle = particles_[i];
total_weight = total_weight + particle->weight;
}
}
double weight_square_sum = 0;
for (int i = 0; i < particles_.size(); i++) {
State* particle = particles_[i];
particle->weight /= total_weight;
weight_square_sum += particle->weight * particle->weight;
}
// Resample if the effective number of particles is "small"
double num_effective_particles = 1.0 / weight_square_sum;
if (num_effective_particles < num_particles_ / 2.0) {
vector<State*> new_belief = Belief::Sample(num_particles_, particles_,
model_);
for (int i = 0; i < particles_.size(); i++)
model_->Free(particles_[i]);
particles_ = new_belief;
}
}
Belief* ParticleBelief::MakeCopy() const {
vector<State*> copy;
for (int i = 0; i < particles_.size(); i++) {
copy.push_back(model_->Copy(particles_[i]));
}
return new ParticleBelief(copy, model_, prior_, split_);
}
string ParticleBelief::text() const {
ostringstream oss;
map<string, double> pdf;
for (int i = 0; i < particles_.size(); i++) {
pdf[particles_[i]->text()] += particles_[i]->weight;
}
oss << "pdf for " << particles_.size() << " particles:" ;
vector<pair<string, double> > pairs = SortByValue(pdf);
for (int i = 0; i < pairs.size(); i++) {
pair<string, double> pair = pairs[i];
oss << " " << pair.first << " = " << pair.second ;
}
return oss.str();
}
} // namespace despot
| [
"tristan.kalos@ensta.fr"
] | tristan.kalos@ensta.fr |
02e4ae79395f11cd861ecd268fdc6e18e6df9d39 | fb5fd35c3acecb7bb4e45aa8cd39b83dfcfc30c6 | /图论/二分匹配/POJ1469 COURSES.cpp | 7ae6748f427fb64015867343d17d7618b14a56c3 | [] | no_license | chunchou/ACM | 6306f6577a6912d020d5a4fa3f8808beadd283e0 | d5ac8b9511689fed08c15d5f111d53146152a75e | refs/heads/master | 2021-01-14T09:23:58.072885 | 2013-12-24T00:58:43 | 2013-12-24T00:58:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 960 | cpp | /*
学生和课程构成一个二部图,可选课程作为X部,学生选为Y部,构造一个二分图。
然后判断能否为完美匹配
*/
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define X 302
int ym[X],p,n;
bool g[X][X],use[X];
bool dfs(int u)
{
for(int v=1;v<=n;v++)
if(g[u][v]&&!use[v])
{
use[v] = true;
if(ym[v]==-1||dfs(ym[v]))
{
ym[v] = u;
return true;
}
}
return false;
}
int hungry()
{
int ret = 0;
memset(ym,-1,sizeof(ym));
for(int u=1;u<=p;u++)
{
memset(use,false,sizeof(use));
if(dfs(u))
ret++;
}
return ret;
}
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
int t,m,q;
scanf("%d",&t);
while(t--)
{
memset(g,false,sizeof(g));
scanf("%d%d",&p,&n);
for(int i=1;i<=p;i++)
{
scanf("%d",&m);
while(m--)
{
scanf("%d",&q);
g[i][q] = true;
}
}
hungry()==p?printf("YES\n"):printf("NO\n");
}
return 0;
} | [
"545883134@qq.com"
] | 545883134@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.