hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cbf6021119212bfdd13e888bdb0aaa72b88bc33f | 5,191 | cpp | C++ | indra/integration_tests/llui_libtest/llwidgetreg.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/integration_tests/llui_libtest/llwidgetreg.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | null | null | null | indra/integration_tests/llui_libtest/llwidgetreg.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file llwidgetreg.cpp
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llwidgetreg.h"
#include "llbutton.h"
#include "llcheckboxctrl.h"
#include "llcombobox.h"
#include "llcontainerview.h"
#include "lliconctrl.h"
#include "llloadingindicator.h"
#include "llmenubutton.h"
#include "llmenugl.h"
#include "llmultislider.h"
#include "llmultisliderctrl.h"
#include "llprogressbar.h"
#include "llradiogroup.h"
#include "llsearcheditor.h"
#include "llscrollcontainer.h"
#include "llscrollingpanellist.h"
#include "llscrolllistctrl.h"
#include "llslider.h"
#include "llsliderctrl.h"
#include "llspinctrl.h"
#include "llstatview.h"
#include "lltabcontainer.h"
#include "lltextbox.h"
#include "lltexteditor.h"
#include "lltimectrl.h"
#include "llflyoutbutton.h"
#include "llfiltereditor.h"
#include "lllayoutstack.h"
void LLWidgetReg::initClass(bool register_widgets)
{
// Only need to register if the Windows linker has optimized away the
// references to the object files.
if (register_widgets)
{
LLDefaultChildRegistry::Register<LLButton> button("button");
LLDefaultChildRegistry::Register<LLMenuButton> menu_button("menu_button");
LLDefaultChildRegistry::Register<LLCheckBoxCtrl> check_box("check_box");
LLDefaultChildRegistry::Register<LLComboBox> combo_box("combo_box");
LLDefaultChildRegistry::Register<LLFilterEditor> filter_editor("filter_editor");
LLDefaultChildRegistry::Register<LLFlyoutButton> flyout_button("flyout_button");
LLDefaultChildRegistry::Register<LLContainerView> container_view("container_view");
LLDefaultChildRegistry::Register<LLIconCtrl> icon("icon");
LLDefaultChildRegistry::Register<LLLoadingIndicator> loading_indicator("loading_indicator");
LLDefaultChildRegistry::Register<LLLineEditor> line_editor("line_editor");
LLDefaultChildRegistry::Register<LLMenuItemSeparatorGL> menu_item_separator("menu_item_separator");
LLDefaultChildRegistry::Register<LLMenuItemCallGL> menu_item_call_gl("menu_item_call");
LLDefaultChildRegistry::Register<LLMenuItemCheckGL> menu_item_check_gl("menu_item_check");
LLDefaultChildRegistry::Register<LLMenuGL> menu("menu");
LLDefaultChildRegistry::Register<LLMenuBarGL> menu_bar("menu_bar");
LLDefaultChildRegistry::Register<LLContextMenu> context_menu("context_menu");
LLDefaultChildRegistry::Register<LLMultiSlider> multi_slider_bar("multi_slider_bar");
LLDefaultChildRegistry::Register<LLMultiSliderCtrl> multi_slider("multi_slider");
LLDefaultChildRegistry::Register<LLPanel> panel("panel", &LLPanel::fromXML);
LLDefaultChildRegistry::Register<LLLayoutStack> layout_stack("layout_stack");
LLDefaultChildRegistry::Register<LLProgressBar> progress_bar("progress_bar");
LLDefaultChildRegistry::Register<LLRadioGroup> radio_group("radio_group");
LLDefaultChildRegistry::Register<LLSearchEditor> search_editor("search_editor");
LLDefaultChildRegistry::Register<LLScrollContainer> scroll_container("scroll_container");
LLDefaultChildRegistry::Register<LLScrollingPanelList> scrolling_panel_list("scrolling_panel_list");
LLDefaultChildRegistry::Register<LLScrollListCtrl> scroll_list("scroll_list");
LLDefaultChildRegistry::Register<LLSlider> slider_bar("slider_bar");
LLDefaultChildRegistry::Register<LLSliderCtrl> slider("slider");
LLDefaultChildRegistry::Register<LLSpinCtrl> spinner("spinner");
LLDefaultChildRegistry::Register<LLStatBar> stat_bar("stat_bar");
//LLDefaultChildRegistry::Register<LLPlaceHolderPanel> placeholder("placeholder");
LLDefaultChildRegistry::Register<LLTabContainer> tab_container("tab_container");
LLDefaultChildRegistry::Register<LLTextBox> text("text");
LLDefaultChildRegistry::Register<LLTimeCtrl> time("time");
LLDefaultChildRegistry::Register<LLTextEditor> simple_text_editor("simple_text_editor");
LLDefaultChildRegistry::Register<LLUICtrl> ui_ctrl("ui_ctrl");
LLDefaultChildRegistry::Register<LLStatView> stat_view("stat_view");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> locate("locate");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> pad("pad");
LLDefaultChildRegistry::Register<LLViewBorder> view_border("view_border");
}
// *HACK: Usually this is registered as a viewer text editor
LLDefaultChildRegistry::Register<LLTextEditor> text_editor("text_editor");
}
| 48.064815 | 102 | 0.799075 | SaladDais |
02082b5d69c4264e74197730f982e43693fb3c1f | 260 | hpp | C++ | Planets/Graph.hpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | Planets/Graph.hpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | Planets/Graph.hpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | #ifndef GRAPH_H
#define GRAPH_H
#include <vector>
#include <utility>
// Header file for the graphing file
std::pair<double,double> extrema(std::vector<double> v);
std::pair<double,double> getLeastSquares(std::vector<double> x, std::vector<double> y);
#endif | 23.636364 | 87 | 0.746154 | GEslinger |
02098a73feec75805920a6f0064ac723be0d6723 | 2,003 | hh | C++ | src/blas/utils.hh | hmatuschek/linalg | b4b8337ba001b24572f13349cc5804a416bfe5a7 | [
"MIT"
] | 1 | 2016-05-24T15:27:52.000Z | 2016-05-24T15:27:52.000Z | src/blas/utils.hh | hmatuschek/linalg | b4b8337ba001b24572f13349cc5804a416bfe5a7 | [
"MIT"
] | null | null | null | src/blas/utils.hh | hmatuschek/linalg | b4b8337ba001b24572f13349cc5804a416bfe5a7 | [
"MIT"
] | null | null | null | /*
* This file is part of the Linalg project, a C++ interface to BLAS and LAPACK.
*
* The source-code is licensed under the terms of the MIT license, read LICENSE for more details.
*
* (c) 2011, 2012 Hannes Matuschek <hmatuschek at gmail dot com>
*/
#ifndef __LINALG_BLAS_UTILS_HH__
#define __LINALG_BLAS_UTILS_HH__
/*
* Some helper macros to simplify binding to Fortran code.
*/
/**
* Creates an new view to the same array, but ensures that the new view is in column-major
* (Fortran) from.
*
* @ingroup blas
*/
#define BLAS_ENSURE_COLUMN_MAJOR(A, trans) ({ if(A.isRowMajor()) {A = A.t(); trans=BLAS_TRANSPOSE(trans);} else {} A;})
/**
* Is true, (for a @c TriMatrix) if the matrix is stored in the upper-triangular part of the matrix.
*
* It returns how the matrix is stored in the memory, not if the view is a upper-triangular matrix.
*
* @ingroup blas
*/
#define BLAS_IS_UPPER(T) (T.isUpper())
/**
* Is true, (for a @c TriMatrix) if the matrix is stored in the lower-triangular part of the matrix.
*
* It returns how the matrix is stored in the memory, not if the view is a lower-triangular matrix.
*
* @ingroup blas
*/
#define BLAS_IS_LOWER(T) (!T.isUpper())
/**
* Returns true if the @c TriMatrix has a unit diagonal.
*
* @ingroup blas
*/
#define BLAS_HAS_UNIT_DIAG(T) (T.hasUnitDiag())
#define BLAS_UPLO_FLAG(T) BLAS_IS_UPPER(T) ? 'U' : 'L'
#define BLAS_UNIT_DIAG_FLAG(T) BLAS_HAS_UNIT_DIAG(T) ? 'U' : 'N'
#define BLAS_NUM_COLS(A, trans) ('N'==trans ? A.cols() : A.rows())
#define BLAS_NUM_ROWS(A, trans) ('N'==trans ? A.rows() : A.cols())
#define BLAS_LEADING_DIMENSION(A) (A.isRowMajor() ? A.strides(0) : A.strides(1))
#define BLAS_TRANSPOSE(trans) ('N' == trans ? 'T' : 'N')
#define BLAS_TRANSPOSE_UPLO(trans, uplo) ('T' == uplo ? ('U'==uplo ? 'L' : 'U') : uplo)
#define BLAS_DIMENSION(x) (x.dim())
#define BLAS_INCREMENT(x) (x.strides(0))
#endif // __LINALG_BLAS_UTILS_HH__
| 32.306452 | 119 | 0.658013 | hmatuschek |
020a06c3b0386487bf769fdb51b8d0e5db94421b | 3,157 | cpp | C++ | groups/csa/csamisc/csamisc_shortcompare.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | groups/csa/csamisc/csamisc_shortcompare.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | groups/csa/csamisc/csamisc_shortcompare.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | // csamisc_donotuseendl.cpp -*-C++-*-
#include <clang/AST/Expr.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <csabase_analyser.h>
#include <csabase_debug.h>
#include <csabase_registercheck.h>
#include <csabase_report.h>
#include <csabase_util.h>
#include <csabase_visitor.h>
#include <string>
#include <unordered_set>
using namespace clang;
using namespace clang::ast_matchers;
using namespace csabase;
static std::string const check_name("short-compare");
namespace
{
struct data
{
};
struct report : Report<data>
{
INHERIT_REPORT_CTOR(report, Report, data);
void operator()(const BinaryOperator *expr);
};
void report::operator()(const BinaryOperator *expr)
{
if (expr->isComparisonOp()) {
const auto *lhs = llvm::dyn_cast<ImplicitCastExpr>(expr->getLHS());
const auto *rhs = llvm::dyn_cast<ImplicitCastExpr>(expr->getRHS());
if (lhs && rhs) {
const auto *lt = lhs->getType().getTypePtr()->getAs<BuiltinType>();
const auto *rt = rhs->getType().getTypePtr()->getAs<BuiltinType>();
if (lt && lt->getKind() == lt->Int &&
rt && rt->getKind() == rt->Int) {
const auto *ls = lhs->getSubExpr();
const auto *rs = rhs->getSubExpr();
const auto *lst =
ls->getType().getTypePtr()->getAs<BuiltinType>();
const auto *rst =
rs->getType().getTypePtr()->getAs<BuiltinType>();
if (lst && rst &&
((lst->getKind() == lst->Short &&
rst->getKind() == rst->UShort) ||
(lst->getKind() == lst->UShort &&
rst->getKind() == rst->Short))) {
a.report(expr, check_name, "US01",
"Comparison between signed and unsigned short "
"may cause unexpected behavior");
}
}
}
}
}
void subscribe(Analyser& analyser, Visitor& visitor, PPObserver& observer)
// Hook up the callback functions.
{
visitor.onBinaryOperator += report(analyser);
}
} // close anonymous namespace
// -----------------------------------------------------------------------------
static RegisterCheck c1(check_name, &subscribe);
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 34.315217 | 80 | 0.560025 | hyrosen |
020a0fa22c0b7915b733150f7e2839eeba5c0058 | 26,548 | hpp | C++ | libs/fft/FFTRealFixed.hpp | constcut/mtherapp | 20b8e32361ef492d5b7cb4ff150f0956e952fdef | [
"MIT"
] | 2 | 2022-03-04T17:54:48.000Z | 2022-03-28T06:20:31.000Z | libs/fft/FFTRealFixed.hpp | constcut/aurals | bb00fac92a3a919867fe2e482c37fc0abe5e6984 | [
"MIT"
] | null | null | null | libs/fft/FFTRealFixed.hpp | constcut/aurals | bb00fac92a3a919867fe2e482c37fc0abe5e6984 | [
"MIT"
] | null | null | null | #ifndef FFTREALFIXED_H
#define FFTREALFIXED_H
#include <cstdint>
#include <cassert>
#include <cmath>
#include <type_traits>
const double PI = 3.1415926535897932384626433832795;
const double SQRT2 = 1.41421356237309514547462185873883;
template <class T>
class DynArray
{
public:
DynArray ();
explicit DynArray (uint32_t size);
~DynArray ();
inline uint32_t size () const;
inline void resize (uint32_t new_size);
inline const T& operator [] (uint32_t pos) const;
inline T& operator [] (uint32_t pos);
DynArray(const DynArray& other) = delete;
DynArray& operator = (const DynArray& other) = delete;
bool operator == (const DynArray& other) = delete;
bool operator != (const DynArray& other) = delete;
private:
T* _data_ptr;
uint32_t _len;
};
template <class T, long length>
class Array
{
public:
Array () = default;
inline const T& operator [] (long pos) const;
inline T& operator [] (long pos);
static inline long size ();
Array (const Array& other) = delete;
Array& operator = (const Array& other) = delete;
bool operator == (const Array& other) = delete;
bool operator != (const Array& other) = delete;
private:
T _data_arr[length];
}; // class Array
template <class T>
class OscSinCos
{
public:
OscSinCos ();
inline void set_step (double angle_rad);
inline T get_cos () const;
inline T get_sin () const;
inline void step ();
inline void clear_buffers ();
OscSinCos (const OscSinCos& other) = delete;
OscSinCos& operator = (const OscSinCos& other) = delete;
bool operator == (const OscSinCos& other) = delete;
bool operator != (const OscSinCos& other) = delete;
private:
T _pos_cos; // Current phase expressed with sin and cos. [-1 ; 1]
T _pos_sin; // -
T _step_cos; // Phase increment per step, [-1 ; 1]
T _step_sin; // -
}; // class OscSinCos
//Dynamic array implementation
template <class T>
DynArray <T>::DynArray()
: _data_ptr (nullptr), _len (0) {}
template <class T>
DynArray <T>::DynArray(uint32_t size)
: _data_ptr(nullptr), _len (size)
{
//static_assert (_len > 0, "DynArray zero len not expected");
_data_ptr = new T[_len];
}
template <class T>
DynArray <T>::~DynArray()
{
delete [] _data_ptr;
_data_ptr = nullptr;
_len = 0;
}
template <class T>
uint32_t DynArray <T>::size() const {
return (_len);
}
template <class T>
void DynArray <T>::resize(uint32_t new_size)
{
assert (new_size > 0);
_len = new_size;
delete [] _data_ptr;
_data_ptr = new T[_len];
}
template <class T>
const T& DynArray <T>::operator[] (uint32_t pos) const
{
assert (pos >= 0);
assert (pos < _len);
return (_data_ptr [pos]);
}
template <class T>
T& DynArray <T>::operator[] (uint32_t pos)
{
assert (pos >= 0);
assert (pos < _len);
return (_data_ptr [pos]);
}
//Array implementation
template <class T, long length>
const T& Array <T, length>::operator [] (long pos) const
{
assert (pos >= 0);
assert (pos < length);
return (_data_arr [pos]);
}
template <class T, long length>
T& Array <T, length>::operator [] (long pos)
{
assert (pos >= 0);
assert (pos < length);
return (_data_arr [pos]);
}
template <class T, long length>
long Array <T, length>::size () {
return (length);
}
//OscSinCos implementation
template <class T>
OscSinCos <T>::OscSinCos () : _pos_cos(1),
_pos_sin (0), _step_cos(1), _step_sin (0) {}
template <class T>
void OscSinCos <T>::set_step (double angle_rad)
{
_step_cos = std::cos(angle_rad);
_step_sin = std::sin(angle_rad);
}
template <class T>
T OscSinCos <T>::get_cos () const {
return _pos_cos;
}
template <class T>
T OscSinCos <T>::get_sin () const {
return _pos_sin;
}
template <class T>
void OscSinCos <T>::step ()
{
const T old_cos = _pos_cos;
const T old_sin = _pos_sin;
_pos_cos = old_cos * _step_cos - old_sin * _step_sin;
_pos_sin = old_cos * _step_sin + old_sin * _step_cos;
}
template <class T>
void OscSinCos <T>::clear_buffers ()
{
if (std::is_same<float, T>()) {
_pos_cos = 1.f;
_pos_sin = 0.f;
}
if (std::is_same<double, T>()) {
_pos_cos = 1.;
_pos_sin = 0.;
}
}
#define DataType float
//First just fast copy
template <int ALGO>
class FFTRealUseTrigo
{
public:
typedef OscSinCos <DataType> OscType;
inline static void
prepare (OscType &osc);
inline static void
iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s);
private:
FFTRealUseTrigo ();
~FFTRealUseTrigo ();
FFTRealUseTrigo (const FFTRealUseTrigo &other);
FFTRealUseTrigo &
operator = (const FFTRealUseTrigo &other);
bool operator == (const FFTRealUseTrigo &other);
bool operator != (const FFTRealUseTrigo &other);
}; // class FFTRealUseTrigo
template <int ALGO>
void FFTRealUseTrigo <ALGO>::prepare (OscType &osc)
{
osc.clear_buffers ();
}
template <>
inline void FFTRealUseTrigo <0>::prepare ([[maybe_unused]]OscType &osc)
{
// Nothing
}
template <int ALGO>
void FFTRealUseTrigo <ALGO>::iterate (OscType &osc, DataType &c, DataType &s, [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long index_c, [[maybe_unused]] long index_s)
{
osc.step ();
c = osc.get_cos ();
s = osc.get_sin ();
}
template <>
inline void FFTRealUseTrigo <0>::iterate ([[maybe_unused]] OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s)
{
c = cos_ptr [index_c];
s = cos_ptr [index_s];
}
template <int P>
class FFTRealSelect
{
public:
inline static float *
sel_bin (float *e_ptr, float *o_ptr);
private:
FFTRealSelect ();
~FFTRealSelect ();
FFTRealSelect (const FFTRealSelect &other);
FFTRealSelect& operator = (const FFTRealSelect &other);
bool operator == (const FFTRealSelect &other);
bool operator != (const FFTRealSelect &other);
}; // class FFTRealSelect
template <int P>
float * FFTRealSelect <P>::sel_bin ([[maybe_unused]] float *e_ptr, float *o_ptr)
{
return (o_ptr);
}
template <>
inline float * FFTRealSelect <0>::sel_bin (float *e_ptr, [[maybe_unused]] float *o_ptr)
{
return (e_ptr);
}
template <int PASS>
class FFTRealPassInverse
{
public:
typedef OscSinCos <DataType> OscType;
inline static void
process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [],
long cos_len, const uint32_t br_ptr [], OscType osc_list []);
inline static void
process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [],
long cos_len, const uint32_t br_ptr [], OscType osc_list []);
inline static void
process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [],
long cos_len, const uint32_t br_ptr [], OscType osc_list []);
private:
FFTRealPassInverse ();
FFTRealPassInverse (const FFTRealPassInverse &other);
FFTRealPassInverse &
operator = (const FFTRealPassInverse &other);
bool operator == (const FFTRealPassInverse &other);
bool operator != (const FFTRealPassInverse &other);
}; // class FFTRealPassInverse
template <int PASS>
void FFTRealPassInverse <PASS>::process (long len, DataType dest_ptr [], DataType src_ptr [],
const DataType f_ptr [], const DataType cos_ptr [], long cos_len,
const uint32_t br_ptr [], OscType osc_list [])
{
process_internal (
len,
dest_ptr,
f_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
FFTRealPassInverse <PASS - 1>::process_rec (
len,
src_ptr,
dest_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
}
template <int PASS>
void FFTRealPassInverse <PASS>::process_rec (long len, DataType dest_ptr [], DataType src_ptr [],
const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list [])
{
process_internal (
len,
dest_ptr,
src_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
FFTRealPassInverse <PASS - 1>::process_rec (
len,
src_ptr,
dest_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
}
template <>
inline void FFTRealPassInverse <0>::process_rec ([[maybe_unused]] long len, [[maybe_unused]]
DataType dest_ptr [], [[maybe_unused]] DataType src_ptr [], [[maybe_unused]] const DataType cos_ptr [],
[[maybe_unused]] long cos_len, [[maybe_unused]] const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list [])
{
// Stops recursion
}
template <int PASS>
void FFTRealPassInverse <PASS>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [],
const DataType cos_ptr [], long cos_len,
[[maybe_unused]] const uint32_t br_ptr [], OscType osc_list [])
{
const uint32_t dist = 1L << (PASS - 1);
const uint32_t c1_r = 0;
const uint32_t c1_i = dist;
const uint32_t c2_r = dist * 2;
const uint32_t c2_i = dist * 3;
const uint32_t cend = dist * 4;
const uint32_t table_step = cos_len >> (PASS - 1);
enum { TRIGO_OSC = PASS - 12 };
enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 };
uint32_t coef_index = 0;
do
{
const DataType * const sf = src_ptr + coef_index;
DataType * const df = dest_ptr + coef_index;
// Extreme coefficients are always real
df [c1_r] = sf [c1_r] + sf [c2_r];
df [c2_r] = sf [c1_r] - sf [c2_r];
df [c1_i] = sf [c1_i] * 2;
df [c2_i] = sf [c2_i] * 2;
FFTRealUseTrigo <TRIGO_DIRECT>::prepare (osc_list [TRIGO_OSC]);
// Others are conjugate complex numbers
for (uint32_t i = 1; i < dist; ++ i)
{
df [c1_r + i] = sf [c1_r + i] + sf [c2_r - i];
df [c1_i + i] = sf [c2_r + i] - sf [cend - i];
DataType c;
DataType s;
FFTRealUseTrigo <TRIGO_DIRECT>::iterate (
osc_list [TRIGO_OSC],
c,
s,
cos_ptr,
i * table_step,
(dist - i) * table_step
);
const DataType vr = sf [c1_r + i] - sf [c2_r - i];
const DataType vi = sf [c2_r + i] + sf [cend - i];
df [c2_r + i] = vr * c + vi * s;
df [c2_i + i] = vi * c - vr * s;
}
coef_index += cend;
}
while (coef_index < len);
}
template <>
inline void FFTRealPassInverse <2>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [],
[[maybe_unused]] const DataType cos_ptr [],
[[maybe_unused]] long cos_len, [[maybe_unused]] const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list [])
{
// Antepenultimate pass
const DataType sqrt2_2 = DataType (SQRT2 * 0.5);
uint32_t coef_index = 0;
do
{
dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4];
dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4];
dest_ptr [coef_index + 2] = src_ptr [coef_index + 2] * 2;
dest_ptr [coef_index + 6] = src_ptr [coef_index + 6] * 2;
dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + src_ptr [coef_index + 3];
dest_ptr [coef_index + 3] = src_ptr [coef_index + 5] - src_ptr [coef_index + 7];
const DataType vr = src_ptr [coef_index + 1] - src_ptr [coef_index + 3];
const DataType vi = src_ptr [coef_index + 5] + src_ptr [coef_index + 7];
dest_ptr [coef_index + 5] = (vr + vi) * sqrt2_2;
dest_ptr [coef_index + 7] = (vi - vr) * sqrt2_2;
coef_index += 8;
}
while (coef_index < len);
}
template <>
inline void FFTRealPassInverse <1>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [],
[[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len,
const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list [])
{
// Penultimate and last pass at once
const uint32_t qlen = len >> 2;
uint32_t coef_index = 0;
do
{
const uint32_t ri_0 = br_ptr [coef_index >> 2];
const DataType b_0 = src_ptr [coef_index ] + src_ptr [coef_index + 2];
const DataType b_2 = src_ptr [coef_index ] - src_ptr [coef_index + 2];
const DataType b_1 = src_ptr [coef_index + 1] * 2;
const DataType b_3 = src_ptr [coef_index + 3] * 2;
dest_ptr [ri_0 ] = b_0 + b_1;
dest_ptr [ri_0 + 2 * qlen] = b_0 - b_1;
dest_ptr [ri_0 + 1 * qlen] = b_2 + b_3;
dest_ptr [ri_0 + 3 * qlen] = b_2 - b_3;
coef_index += 4;
}
while (coef_index < len);
}
template <int PASS>
class FFTRealPassDirect
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
typedef OscSinCos <DataType> OscType;
inline static void
process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [],
const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []);
private:
FFTRealPassDirect ();
FFTRealPassDirect (const FFTRealPassDirect &other);
FFTRealPassDirect &
operator = (const FFTRealPassDirect &other);
bool operator == (const FFTRealPassDirect &other);
bool operator != (const FFTRealPassDirect &other);
}; // class FFTRealPassDirect
template <>
inline void FFTRealPassDirect <1>::process (long len, DataType dest_ptr [], [[maybe_unused]] DataType src_ptr [],
const DataType x_ptr [], [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len, const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list [])
{
// First and second pass at once
const uint32_t qlen = len >> 2;
uint32_t coef_index = 0;
do
{
// To do: unroll the loop (2x).
const uint32_t ri_0 = br_ptr [coef_index >> 2];
const uint32_t ri_1 = ri_0 + 2 * qlen; // bit_rev_lut_ptr [coef_index + 1];
const uint32_t ri_2 = ri_0 + 1 * qlen; // bit_rev_lut_ptr [coef_index + 2];
const uint32_t ri_3 = ri_0 + 3 * qlen; // bit_rev_lut_ptr [coef_index + 3];
DataType * const df2 = dest_ptr + coef_index;
df2 [1] = x_ptr [ri_0] - x_ptr [ri_1];
df2 [3] = x_ptr [ri_2] - x_ptr [ri_3];
const DataType sf_0 = x_ptr [ri_0] + x_ptr [ri_1];
const DataType sf_2 = x_ptr [ri_2] + x_ptr [ri_3];
df2 [0] = sf_0 + sf_2;
df2 [2] = sf_0 - sf_2;
coef_index += 4;
}
while (coef_index < len);
}
template <>
inline void FFTRealPassDirect <2>::process (long len, DataType dest_ptr [], DataType src_ptr [],
const DataType x_ptr [], const DataType cos_ptr [],
long cos_len, const uint32_t br_ptr [], OscType osc_list [])
{
// Executes "previous" passes first. Inverts source and destination buffers
FFTRealPassDirect <1>::process (
len,
src_ptr,
dest_ptr,
x_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
// Third pass
const DataType sqrt2_2 = SQRT2 * 0.5;
DataType v;
uint32_t coef_index = 0;
do
{
dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4];
dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4];
dest_ptr [coef_index + 2] = src_ptr [coef_index + 2];
dest_ptr [coef_index + 6] = src_ptr [coef_index + 6];
v = (src_ptr [coef_index + 5] - src_ptr [coef_index + 7]) * sqrt2_2;
dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + v;
dest_ptr [coef_index + 3] = src_ptr [coef_index + 1] - v;
v = (src_ptr [coef_index + 5] + src_ptr [coef_index + 7]) * sqrt2_2;
dest_ptr [coef_index + 5] = v + src_ptr [coef_index + 3];
dest_ptr [coef_index + 7] = v - src_ptr [coef_index + 3];
coef_index += 8;
}
while (coef_index < len);
}
template <int PASS>
void FFTRealPassDirect <PASS>::process (long len, DataType dest_ptr [], DataType src_ptr [],
const DataType x_ptr [], const DataType cos_ptr [],
long cos_len, const uint32_t br_ptr [], OscType osc_list [])
{
// Executes "previous" passes first. Inverts source and destination buffers
FFTRealPassDirect <PASS - 1>::process (
len,
src_ptr,
dest_ptr,
x_ptr,
cos_ptr,
cos_len,
br_ptr,
osc_list
);
const uint32_t dist = 1L << (PASS - 1);
const uint32_t c1_r = 0;
const uint32_t c1_i = dist;
const uint32_t c2_r = dist * 2;
const uint32_t c2_i = dist * 3;
const uint32_t cend = dist * 4;
const uint32_t table_step = cos_len >> (PASS - 1);
enum { TRIGO_OSC = PASS - 12 };
enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 };
uint32_t coef_index = 0;
do
{
const DataType * const sf = src_ptr + coef_index;
DataType * const df = dest_ptr + coef_index;
// Extreme coefficients are always real
df [c1_r] = sf [c1_r] + sf [c2_r];
df [c2_r] = sf [c1_r] - sf [c2_r];
df [c1_i] = sf [c1_i];
df [c2_i] = sf [c2_i];
FFTRealUseTrigo <TRIGO_DIRECT>::prepare (osc_list [TRIGO_OSC]);
// Others are conjugate complex numbers
for (uint32_t i = 1; i < dist; ++ i)
{
DataType c;
DataType s;
FFTRealUseTrigo <TRIGO_DIRECT>::iterate (
osc_list [TRIGO_OSC],
c,
s,
cos_ptr,
i * table_step,
(dist - i) * table_step
);
const DataType sf_r_i = sf [c1_r + i];
const DataType sf_i_i = sf [c1_i + i];
const DataType v1 = sf [c2_r + i] * c - sf [c2_i + i] * s;
df [c1_r + i] = sf_r_i + v1;
df [c2_r - i] = sf_r_i - v1;
const DataType v2 = sf [c2_r + i] * s + sf [c2_i + i] * c;
df [c2_r + i] = v2 + sf_i_i;
df [cend - i] = v2 - sf_i_i;
}
coef_index += cend;
}
while (coef_index < len);
}
template <int LL2>
class FFTRealFixLen
{
typedef int CompileTimeCheck1 [(LL2 >= 0) ? 1 : -1];
typedef int CompileTimeCheck2 [(LL2 <= 30) ? 1 : -1];
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
typedef OscSinCos <DataType> OscType;
enum { FFT_LEN_L2 = LL2 };
enum { FFT_LEN = 1 << FFT_LEN_L2 };
FFTRealFixLen ();
inline uint32_t get_length () const;
void do_fft (DataType f [], const DataType x []);
void do_ifft (const DataType f [], DataType x []);
void rescale (DataType x []) const;
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
enum { TRIGO_BD_LIMIT = 12 };
enum { BR_ARR_SIZE_L2 = ((FFT_LEN_L2 - 3) < 0) ? 0 : (FFT_LEN_L2 - 2) };
enum { BR_ARR_SIZE = 1 << BR_ARR_SIZE_L2 };
enum { TRIGO_BD = ((FFT_LEN_L2 - TRIGO_BD_LIMIT) < 0)
? (int)FFT_LEN_L2
: (int)TRIGO_BD_LIMIT };
enum { TRIGO_TABLE_ARR_SIZE_L2 = (LL2 < 4) ? 0 : (TRIGO_BD - 2) };
enum { TRIGO_TABLE_ARR_SIZE = 1 << TRIGO_TABLE_ARR_SIZE_L2 };
enum { NBR_TRIGO_OSC = FFT_LEN_L2 - TRIGO_BD };
enum { TRIGO_OSC_ARR_SIZE = (NBR_TRIGO_OSC > 0) ? NBR_TRIGO_OSC : 1 };
void build_br_lut ();
void build_trigo_lut ();
void build_trigo_osc ();
DynArray <DataType>
_buffer;
DynArray <uint32_t>
_br_data;
DynArray <DataType>
_trigo_data;
Array <OscType, TRIGO_OSC_ARR_SIZE>
_trigo_osc;
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
FFTRealFixLen (const FFTRealFixLen &other);
FFTRealFixLen& operator = (const FFTRealFixLen &other);
bool operator == (const FFTRealFixLen &other);
bool operator != (const FFTRealFixLen &other);
}; // class FFTRealFixLen
template <int LL2>
FFTRealFixLen <LL2>::FFTRealFixLen ()
: _buffer (FFT_LEN)
, _br_data (BR_ARR_SIZE)
, _trigo_data (TRIGO_TABLE_ARR_SIZE)
, _trigo_osc ()
{
build_br_lut ();
build_trigo_lut ();
build_trigo_osc ();
}
template <int LL2>
uint32_t FFTRealFixLen<LL2>::get_length() const
{
return (FFT_LEN);
}
// General case
template <int LL2>
void FFTRealFixLen <LL2>::do_fft (DataType f [], const DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
assert (FFT_LEN_L2 >= 3);
// Do the transform in several passes
const DataType * cos_ptr = &_trigo_data [0];
const uint32_t * br_ptr = &_br_data [0];
FFTRealPassDirect <FFT_LEN_L2 - 1>::process (
FFT_LEN,
f,
&_buffer [0],
x,
cos_ptr,
TRIGO_TABLE_ARR_SIZE,
br_ptr,
&_trigo_osc [0]
);
}
// 4-point FFT
template <>
inline void FFTRealFixLen <2>::do_fft (DataType f [], const DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
f [1] = x [0] - x [2];
f [3] = x [1] - x [3];
const DataType b_0 = x [0] + x [2];
const DataType b_2 = x [1] + x [3];
f [0] = b_0 + b_2;
f [2] = b_0 - b_2;
}
// 2-point FFT
template <>
inline void FFTRealFixLen <1>::do_fft (DataType f [], const DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
f [0] = x [0] + x [1];
f [1] = x [0] - x [1];
}
// 1-point FFT
template <>
inline void FFTRealFixLen <0>::do_fft (DataType f [], const DataType x [])
{
assert (f != 0);
assert (x != 0);
f [0] = x [0];
}
// General case
template <int LL2>
void FFTRealFixLen <LL2>::do_ifft (const DataType f [], DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
assert (FFT_LEN_L2 >= 3);
// Do the transform in several passes
DataType * s_ptr =
FFTRealSelect <FFT_LEN_L2 & 1>::sel_bin (&_buffer [0], x);
DataType * d_ptr =
FFTRealSelect <FFT_LEN_L2 & 1>::sel_bin (x, &_buffer [0]);
const DataType * cos_ptr = &_trigo_data [0];
const uint32_t * br_ptr = &_br_data [0];
FFTRealPassInverse <FFT_LEN_L2 - 1>::process (
FFT_LEN,
d_ptr,
s_ptr,
f,
cos_ptr,
TRIGO_TABLE_ARR_SIZE,
br_ptr,
&_trigo_osc [0]
);
}
// 4-point IFFT
template <>
inline void FFTRealFixLen <2>::do_ifft (const DataType f [], DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
const DataType b_0 = f [0] + f [2];
const DataType b_2 = f [0] - f [2];
x [0] = b_0 + f [1] * 2;
x [2] = b_0 - f [1] * 2;
x [1] = b_2 + f [3] * 2;
x [3] = b_2 - f [3] * 2;
}
// 2-point IFFT
template <>
inline void FFTRealFixLen <1>::do_ifft (const DataType f [], DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
x [0] = f [0] + f [1];
x [1] = f [0] - f [1];
}
// 1-point IFFT
template <>
inline void FFTRealFixLen <0>::do_ifft (const DataType f [], DataType x [])
{
assert (f != 0);
assert (x != 0);
assert (x != f);
x [0] = f [0];
}
template <int LL2>
void FFTRealFixLen <LL2>::rescale (DataType x []) const
{
assert (x != 0);
const DataType mul = 1.0 / FFT_LEN;
if (FFT_LEN < 4)
{
long i = FFT_LEN - 1;
do
{
x [i] *= mul;
--i;
}
while (i >= 0);
}
else
{
assert ((FFT_LEN & 3) == 0);
// Could be optimized with SIMD instruction sets (needs alignment check)
long i = FFT_LEN - 4;
do
{
x [i + 0] *= mul;
x [i + 1] *= mul;
x [i + 2] *= mul;
x [i + 3] *= mul;
i -= 4;
}
while (i >= 0);
}
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
template <int LL2>
void FFTRealFixLen <LL2>::build_br_lut ()
{
_br_data [0] = 0;
for (uint32_t cnt = 1; cnt < BR_ARR_SIZE; ++cnt)
{
uint32_t index = cnt << 2;
uint32_t br_index = 0;
int bit_cnt = FFT_LEN_L2;
do
{
br_index <<= 1;
br_index += (index & 1);
index >>= 1;
-- bit_cnt;
}
while (bit_cnt > 0);
_br_data [cnt] = br_index;
}
}
template <int LL2>
void FFTRealFixLen <LL2>::build_trigo_lut ()
{
const double mul = (0.5 * PI) / TRIGO_TABLE_ARR_SIZE;
for (uint32_t i = 0; i < TRIGO_TABLE_ARR_SIZE; ++ i)
{
using namespace std;
_trigo_data [i] = DataType (cos (i * mul));
}
}
template <int LL2>
void FFTRealFixLen <LL2>::build_trigo_osc ()
{
for (int i = 0; i < NBR_TRIGO_OSC; ++i)
{
OscType & osc = _trigo_osc [i];
const uint32_t len = (TRIGO_TABLE_ARR_SIZE) << (i + 1);
const double mul = (0.5 * PI) / len;
osc.set_step (mul);
}
}
#endif // FFTREALFIXED_H
| 24.672862 | 183 | 0.548403 | constcut |
020b078552ed651f6af89c77f968a8981ff13b1d | 796 | cpp | C++ | LeetCode/_0167_TwoSumII_InputArrayIsSorted.cpp | Restart20200301/Algorithm-Practice | 2b5f42492a1ae574d7ddc7efeebdef55a82a30a5 | [
"MIT"
] | 2 | 2020-05-26T08:25:25.000Z | 2020-05-27T03:53:00.000Z | LeetCode/_0167_TwoSumII_InputArrayIsSorted.cpp | Restart20200301/Algorithm-Practice | 2b5f42492a1ae574d7ddc7efeebdef55a82a30a5 | [
"MIT"
] | null | null | null | LeetCode/_0167_TwoSumII_InputArrayIsSorted.cpp | Restart20200301/Algorithm-Practice | 2b5f42492a1ae574d7ddc7efeebdef55a82a30a5 | [
"MIT"
] | null | null | null | /*
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int first = 0, last = numbers.size() - 1;
while (first < last) {
if (numbers[first] == target - numbers[last])
return { first + 1, last + 1 };
if (numbers[first] + numbers[last] > target) --last;
else ++first;
}
return {};
}
}; | 24.121212 | 68 | 0.611809 | Restart20200301 |
020f2fae5a1cf348fe57133d0d7af0a969664af5 | 14,537 | cpp | C++ | RDT.cpp | fmckenna/RDT | e06273495c4dbe02d7eca55396970d6f749cccaf | [
"BSD-3-Clause"
] | null | null | null | RDT.cpp | fmckenna/RDT | e06273495c4dbe02d7eca55396970d6f749cccaf | [
"BSD-3-Clause"
] | null | null | null | RDT.cpp | fmckenna/RDT | e06273495c4dbe02d7eca55396970d6f749cccaf | [
"BSD-3-Clause"
] | 1 | 2020-09-16T21:02:16.000Z | 2020-09-16T21:02:16.000Z |
// Copyright 2019 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the Sample code usage restrictions document for further information.
//
#include "RDT.h"
#include "Basemap.h"
#include "Map.h"
#include "MapQuickView.h"
#include "FeatureCollectionLayer.h"
#include "FeatureCollection.h"
#include "FeatureCollectionTable.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleRenderer.h"
#include "ClassBreaksRenderer.h"
#include "QJsonDocument"
#include "QDir"
#include <QUrl>
#include <QThread>
#include <QSettings>
#include <PolylineBuilder.h>
#include <Polyline.h>
using namespace Esri::ArcGISRuntime;
RDT::RDT(QObject* parent /* = nullptr */):
QObject(parent),
m_map(new Map(Basemap::topographic(this), this)),
m_loggedIn(false)
{
QString tenant("https://agave.designsafe-ci.org");
QString storage("designsafe.storage.default");
client = new AgaveCurl(tenant, storage);
QThread* agaveThread = new QThread();
agaveThread->setObjectName("AgaveThread");
client->moveToThread(agaveThread);
connect(agaveThread, &QThread::finished, client, &QObject::deleteLater);
connect(agaveThread, &QThread::finished, agaveThread, &QObject::deleteLater);
agaveThread->start();
m_jobsList = new JobsListModel();
m_jobDetails = new JobDetailsModel();
m_inputs << "agave://designsafe.storage.community/SimCenter/Datasets/AnchorageM7/AnchorageBuildings.zip";
m_inputs << "agave://designsafe.storage.community/SimCenter/Datasets/AnchorageM7/AnchorageM7GMs.zip";
m_rendererModel = new RendererModel();
setupConnections();
}
RDT::~RDT()
{
}
void RDT::addCSVLayer(QString filePath)
{
if (filePath.startsWith("file:///"))
filePath = filePath.remove("file:///");
if(filePath.endsWith("values.txt"))
{
addNetwork(filePath);
return;
}
QFile csvFile(filePath);
csvFile.open(QIODevice::ReadOnly);
auto header = csvFile.readLine();
QList<Field> fields;
auto featureCollection = new FeatureCollection();
for (auto columnName:header.split(','))
{
if(columnName == "LossRatio")
fields.append(Field::createDouble(columnName, "Loss Ratio"));
else
fields.append(Field::createText(columnName, columnName, 16));
}
auto featureCollectionTable = new FeatureCollectionTable(fields, GeometryType::Point, SpatialReference::wgs84());
QList<Feature*> features;
while(!csvFile.atEnd())
{
auto line = csvFile.readLine();
auto columns = line.trimmed().split(',');
auto feature = featureCollectionTable->createFeature();
if(columns.count()<9)
continue;
if(columns[7].isEmpty() || columns[8].isEmpty())
continue;
if(!columns[6].isEmpty())
feature->attributes()->replaceAttribute("LossRatio", columns[6].toDouble());
feature->setGeometry(Point(columns[8].toDouble(), columns[7].toDouble()));
features.append(feature);
}
featureCollectionTable->addFeatures(features);
// Define the renderer
QList<ClassBreak*> classBreaks;
auto greenCircle = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, QColor("Light Green"), 5.0, this);
auto greenClassBreak = new ClassBreak("Low Loss Ratio", "Loss Ratio less than 10%", 0.0, 0.1, greenCircle);
classBreaks.append(greenClassBreak);
auto yellowCircle = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, QColor("Yellow"), 5.0, this);
auto yellowClassBreak = new ClassBreak("Medium Loss Ratio", "Loss Ratio Between 10% and 50%", 0.1, 0.5, yellowCircle);
classBreaks.append(yellowClassBreak);
auto redCircle = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, QColor("Red"), 5.0, this);
auto classBreak = new ClassBreak("High Loss Ratio", "Loss Ratio more than 50%", 0.5, 1.0,redCircle);
classBreaks.append(classBreak);
auto renderer = new ClassBreaksRenderer("LossRatio", classBreaks);
featureCollectionTable->setRenderer(renderer);
featureCollection->tables()->append(featureCollectionTable);
auto csvLayer = new FeatureCollectionLayer(featureCollection);
QFileInfo fileInfo(filePath);
csvLayer->setName(fileInfo.fileName());
csvLayer->setDescription("Imported layer");
m_map->operationalLayers()->append(csvLayer);
}
void RDT::refresh()
{
m_map->load();
}
bool RDT::isLoggedIn()
{
return client->isLoggedIn();
}
void RDT::login(QString username, QString password)
{
emit startLogin(username, password);
}
void RDT::refreshJobs()
{
if(client->isLoggedIn())
emit startJobListUpdate("", "rWHALE-1*");
}
void RDT::getJobDetails(int index)
{
auto jobId = m_jobsList->getJobId(index);
emit startJobDetailsUpdate(jobId);
return;
}
void RDT::loadResultFile(QString outputFile)
{
//client->remoteLSCall(outputFile);
for (auto file: m_jobDetails->getOutputs())
{
auto fileName = file.toObject()["name"].toString();
if(0 == fileName.compare(outputFile))
{
auto path = file.toObject()["path"].toString();
QStringList remoteFiles;
//TODO: we may need to handle files from different storage systems, for now using default
remoteFiles << "system/designsafe.storage.default" + path;
QStringList localFiles;
m_resultsPath = QDir::tempPath() + path;
localFiles << m_resultsPath;
QDir(m_resultsPath.left(m_resultsPath.lastIndexOf('/'))).mkpath(".");
client->downloadFilesCall(remoteFiles, localFiles, this);
}
}
}
void RDT::submitJob(QString job)
{
auto jobDoc = QJsonDocument::fromJson(job.toUtf8());
client->startJobCall(jobDoc.object());
}
void RDT::downloadOutputFile(QString outputFileName, QString filePath)
{
if (filePath.startsWith("file:///"))
filePath = filePath.remove("file:///");
for (auto file: m_jobDetails->getOutputs())
{
auto fileName = file.toObject()["name"].toString();
if(0 == fileName.compare(outputFileName))
{
auto path = file.toObject()["path"].toString();
QStringList remoteFiles;
//TODO: we may need to handle files from different storage systems, for now using default
remoteFiles << "system/designsafe.storage.default" + path;
QStringList localFiles;
localFiles << filePath;
client->downloadFilesCall(remoteFiles, localFiles, nullptr);
}
}
}
void RDT::deleteLayer(int index)
{
m_map->operationalLayers()->removeAt(index);
}
void RDT::moveLayerUp(int index)
{
if (index > 0)
m_map->operationalLayers()->move(index, index - 1);
}
void RDT::moveLayerDown(int index)
{
if (index < m_map->operationalLayers()->size() - 1)
m_map->operationalLayers()->move(index, index + 1);
}
void RDT::setRenderer(int index)
{
auto layer = reinterpret_cast<FeatureCollectionLayer*>(m_map->operationalLayers()->at(index));
auto table = reinterpret_cast<FeatureCollectionTable*>(layer->featureCollection()->tables()->at(0));
m_rendererModel->setRenderer(reinterpret_cast<ClassBreaksRenderer*>(table->renderer()));
emit rendererChanged();
}
QString RDT::username()
{
QSettings settings("SimCenter", "Common");
return settings.value("loginAgave", "").toString();
}
QString RDT::password()
{
QSettings settings("SimCenter", "Common");
return settings.value("passwordAgave", "").toString();
}
void RDT::addNetwork(QString filePath)
{
QFile valuesFile(filePath);
valuesFile.open(QIODevice::ReadOnly);
auto allValues = valuesFile.readAll();
valuesFile.close();
auto values = allValues.split(' ');
qDebug() << values.count();
filePath = filePath.replace("values.txt", "seg_start.txt");
QFile startFile(filePath);
startFile.open(QIODevice::ReadOnly);
QList<QPair<double, double>> startPoints;
while(!startFile.atEnd())
{
auto startLine = startFile.readLine();
startPoints.push_back(qMakePair(startLine.split(' ')[0].toDouble(), startLine.split(' ')[1].toDouble()));
}
qDebug() << startPoints.count();
filePath = filePath.replace("seg_start.txt", "seg_end.txt");
QFile endFile(filePath);
endFile.open(QIODevice::ReadOnly);
QList<QPair<double, double>> endPoints;
while(!endFile.atEnd())
{
auto endLine = endFile.readLine();
endPoints.push_back(qMakePair(endLine.split(' ')[0].toDouble(), endLine.split(' ')[1].toDouble()));
}
qDebug() << endPoints.count();
QList<Field> fields;
auto featureCollection = new FeatureCollection();
fields.append(Field::createDouble("RepairRate", "Repair Rate"));
auto featureCollectionTable = new FeatureCollectionTable(fields, GeometryType::Polyline, SpatialReference::wgs84());
QList<Feature*> features;
for(int i = 0; i < startPoints.count(); i++ )
{
auto feature = featureCollectionTable->createFeature();
feature->attributes()->replaceAttribute("RepairRate", values[i].toDouble());
PolylineBuilder* builder = new PolylineBuilder(SpatialReference::wgs84(), this);
builder->addPoint(startPoints[i].first, startPoints[i].second);
builder->addPoint(endPoints[i].first, endPoints[i].second);
Esri::ArcGISRuntime::Polyline singleLine = builder->toPolyline();
feature->setGeometry(singleLine);
features.append(feature);
}
featureCollectionTable->addFeatures(features);
QList<ClassBreak*> classBreaks;
auto line1 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(254, 229, 217), 4.0, this);
auto classbreak1 = new ClassBreak("Very Low Repair Rate", "Repair Rate less than 1e-3", 0.0, 1e-3, line1);
classBreaks.append(classbreak1);
auto line2 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(252, 187, 161), 4.0, this);
auto classbreak2 = new ClassBreak("Low Repair Rate", "Repair Rate less than 0.01", 1e-3, 1e-2, line2);
classBreaks.append(classbreak2);
auto line3 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(252, 146, 114), 4.0, this);
auto classbreak3 = new ClassBreak("Very Moderate Repair Rate", "Repair Rate less than 0.1", 1e-2, 1e-1, line3);
classBreaks.append(classbreak3);
auto line4 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(251, 106, 74), 4.0, this);
auto classbreak4 = new ClassBreak("Moderate Repair Rate", "Repair Rate less than 1", 1e-1, 1e0, line4);
classBreaks.append(classbreak4);
auto line5 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(222, 45, 38), 4.0, this);
auto classbreak5 = new ClassBreak("High Repair Rate", "Repair Rate less than 10", 1e0, 1e1, line5);
classBreaks.append(classbreak5);
auto line6 = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(165, 15, 21), 4.0, this);
auto classbreak6 = new ClassBreak("Very High Repair Rate", "Repair Rate less than 1e10", 1e0, 1e10, line6);
classBreaks.append(classbreak6);
auto renderer = new ClassBreaksRenderer("RepairRate", classBreaks);
featureCollectionTable->setRenderer(renderer);
featureCollection->tables()->append(featureCollectionTable);
auto csvLayer = new FeatureCollectionLayer(featureCollection);
m_map->operationalLayers()->append(csvLayer);
Viewpoint bayArea(37.8272, -122.2913, 500000.0);
m_mapView->setViewpoint(bayArea);
}
MapQuickView* RDT::mapView() const
{
return m_mapView;
}
// Set the view (created in QML)
void RDT::setMapView(MapQuickView* mapView)
{
if (!mapView || mapView == m_mapView)
{
return;
}
m_mapView = mapView;
Viewpoint anchorage(61.2181, -149.9003, 500000.0);
m_map->setInitialViewpoint(anchorage);
m_mapView->setMap(m_map);
connect(m_mapView, &MapQuickView::drawStatusChanged, this, [this](DrawStatus drawStatus)
{
drawStatus == DrawStatus::InProgress ? m_mapDrawing = true : m_mapDrawing = false;
emit mapDrawStatusChanged();
});
emit mapViewChanged();
}
void RDT::setupConnections()
{
// connect(m_mapView, &MapQuickView::dr, this, [this](QDropEvent* dropEvent){
// qDebug() << dropEvent->mimeData();
// });
connect(client, &AgaveCurl::remoteLSReturn, this, [this](QJsonArray remoteFiles){
m_jobDetails->setOutputs(remoteFiles);
});
connect(client, &AgaveCurl::downloadFilesReturn, this, [this](bool result, QObject* sender){
Q_UNUSED(result)
if(sender == this)
{
if(m_resultsPath.endsWith(".csv"))
this->addCSVLayer(m_resultsPath);
else
{
QFile file(m_resultsPath);
file.open(QFile::ReadOnly);
m_textFileContents = file.readAll();
file.close();
emit textFileContentsChanged();
}
}
});
connect(client, &AgaveCurl::getJobListReturn, this, [this](QJsonObject jobs){
m_jobsList->setJobs(jobs);
});
connect(client, &AgaveCurl::getJobDetailsReturn, this, [this](QJsonObject jobDetails){
m_jobDetails->setJob(jobDetails);
client->remoteLSCall(jobDetails["archivePath"].toString());
});
connect(client, &AgaveCurl::startJobReturn, this, [](QString jobreturn){
qDebug() << jobreturn;//TODO: handle job submisstion result
});
connect(client, &AgaveCurl::loginReturn, this, [this](bool loggedIn){
m_loggedIn = loggedIn;
emit loggedInChanged();
});
connect(client, &AgaveCurl::logoutReturn, this, [this](bool loggedOut){
m_loggedIn = !loggedOut;
emit loggedInChanged();
});
connect(this, &RDT::startLogin, client, &AgaveCurl::loginCall);
connect(this, &RDT::startJobListUpdate, client, &AgaveCurl::getJobListCall);
connect(this, &RDT::startJobDetailsUpdate, client, &AgaveCurl::getJobDetailsCall);
}
bool RDT::mapDrawing() const
{
return m_mapDrawing;
}
JobsListModel *RDT::jobsList()
{
return m_jobsList;
}
JobDetailsModel *RDT::jobDetails()
{
return m_jobDetails;
}
LayerListModel *RDT::getLayers()
{
return m_map->operationalLayers();
}
| 31.262366 | 122 | 0.672972 | fmckenna |
020f47b3f07d69f7d0a2a783b77c149ad42bfed4 | 10,169 | cc | C++ | chrome/browser/ui/webui/options/bitpop_options_ui.cc | leiferikb/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-15T15:17:43.000Z | 2021-11-15T15:17:43.000Z | chrome/browser/ui/webui/options/bitpop_options_ui.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/options/bitpop_options_ui.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:24:02.000Z | 2020-11-04T07:24:02.000Z | // Copyright (c) 2013 House of Life Property Ltd. All rights reserved.
// Copyright (c) 2013 Crystalnix <vgachkaylo@crystalnix.com>
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options/bitpop_options_ui.h"
#include <algorithm>
#include <vector>
#include "base/callback.h"
#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/singleton.h"
#include "base/message_loop.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/options/bitpop_core_options_handler.h"
#include "chrome/browser/ui/webui/options/bitpop_options_handler.h"
#include "chrome/browser/ui/webui/options/bitpop_proxy_domain_settings_handler.h"
#include "chrome/browser/ui/webui/options/bitpop_uncensor_filter_handler.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/options_resources.h"
#include "grit/theme_resources.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
using content::RenderViewHost;
namespace {
const char kLocalizedStringsFile[] = "strings.js";
const char kOptionsBundleJsFile[] = "options_bundle.js";
} // namespace
namespace options {
////////////////////////////////////////////////////////////////////////////////
//
// BitpopOptionsUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////
class BitpopOptionsUIHTMLSource : public ChromeURLDataManager::DataSource {
public:
// The constructor takes over ownership of |localized_strings|.
explicit BitpopOptionsUIHTMLSource(DictionaryValue* localized_strings);
// Called when the network layer has requested a resource underneath
// the path we registered.
virtual void StartDataRequest(const std::string& path,
bool is_incognito,
int request_id);
virtual std::string GetMimeType(const std::string&) const;
private:
virtual ~BitpopOptionsUIHTMLSource();
// Localized strings collection.
scoped_ptr<DictionaryValue> localized_strings_;
DISALLOW_COPY_AND_ASSIGN(BitpopOptionsUIHTMLSource);
};
BitpopOptionsUIHTMLSource::BitpopOptionsUIHTMLSource(DictionaryValue* localized_strings)
: DataSource(chrome::kChromeUIBitpopSettingsFrameHost, MessageLoop::current()) {
DCHECK(localized_strings);
localized_strings_.reset(localized_strings);
}
void BitpopOptionsUIHTMLSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
scoped_refptr<base::RefCountedMemory> response_bytes;
SetFontAndTextDirection(localized_strings_.get());
if (path == kLocalizedStringsFile) {
// Return dynamically-generated strings from memory.
jstemplate_builder::UseVersion2 version;
std::string strings_js;
jstemplate_builder::AppendJsonJS(localized_strings_.get(), &strings_js);
response_bytes = base::RefCountedString::TakeString(&strings_js);
} else if (path == kOptionsBundleJsFile) {
// Return (and cache) the options javascript code.
response_bytes = ui::ResourceBundle::GetSharedInstance().
LoadDataResourceBytes(IDR_OPTIONS_BITPOP_BUNDLE_JS);
} else {
// Return (and cache) the main options html page as the default.
response_bytes = ui::ResourceBundle::GetSharedInstance().
LoadDataResourceBytes(IDR_OPTIONS_BITPOP_HTML);
}
SendResponse(request_id, response_bytes);
}
std::string BitpopOptionsUIHTMLSource::GetMimeType(const std::string& path) const {
if (path == kLocalizedStringsFile || path == kOptionsBundleJsFile)
return "application/javascript";
return "text/html";
}
BitpopOptionsUIHTMLSource::~BitpopOptionsUIHTMLSource() {}
////////////////////////////////////////////////////////////////////////////////
//
// BitpopOptionsPageUIHandler
//
////////////////////////////////////////////////////////////////////////////////
const char BitpopOptionsPageUIHandler::kSettingsAppKey[] = "settingsApp";
BitpopOptionsPageUIHandler::BitpopOptionsPageUIHandler() {
}
BitpopOptionsPageUIHandler::~BitpopOptionsPageUIHandler() {
}
bool BitpopOptionsPageUIHandler::IsEnabled() {
return true;
}
// static
void BitpopOptionsPageUIHandler::RegisterStrings(
DictionaryValue* localized_strings,
const OptionsStringResource* resources,
size_t length) {
for (size_t i = 0; i < length; ++i) {
string16 value;
if (resources[i].substitution_id == 0) {
value = l10n_util::GetStringUTF16(resources[i].id);
} else {
value = l10n_util::GetStringFUTF16(
resources[i].id,
l10n_util::GetStringUTF16(resources[i].substitution_id));
}
localized_strings->SetString(resources[i].name, value);
}
}
void BitpopOptionsPageUIHandler::RegisterTitle(DictionaryValue* localized_strings,
const std::string& variable_name,
int title_id) {
localized_strings->SetString(variable_name,
l10n_util::GetStringUTF16(title_id));
localized_strings->SetString(variable_name + "TabTitle",
l10n_util::GetStringFUTF16(IDS_OPTIONS_TAB_TITLE,
l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE),
l10n_util::GetStringUTF16(title_id)));
}
////////////////////////////////////////////////////////////////////////////////
//
// BitpopOptionsUI
//
////////////////////////////////////////////////////////////////////////////////
BitpopOptionsUI::BitpopOptionsUI(content::WebUI* web_ui)
: WebUIController(web_ui),
initialized_handlers_(false) {
DictionaryValue* localized_strings = new DictionaryValue();
localized_strings->Set(BitpopOptionsPageUIHandler::kSettingsAppKey,
new DictionaryValue());
BitpopCoreOptionsHandler* core_handler;
core_handler = new BitpopCoreOptionsHandler();
core_handler->set_handlers_host(this);
AddOptionsPageUIHandler(localized_strings, core_handler);
BitpopOptionsHandler* bitpop_options_handler = new BitpopOptionsHandler();
AddOptionsPageUIHandler(localized_strings, bitpop_options_handler);
AddOptionsPageUIHandler(localized_strings,
new BitpopProxyDomainSettingsHandler());
AddOptionsPageUIHandler(localized_strings,
new BitpopUncensorFilterHandler());
// |localized_strings| ownership is taken over by this constructor.
BitpopOptionsUIHTMLSource* html_source =
new BitpopOptionsUIHTMLSource(localized_strings);
// Set up the chrome://bitpop-settings-frame/ source.
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, html_source);
// Set up the chrome://theme/ source.
ThemeSource* theme = new ThemeSource(profile);
ChromeURLDataManager::AddDataSource(profile, theme);
}
BitpopOptionsUI::~BitpopOptionsUI() {
// Uninitialize all registered handlers. Deleted by WebUIImpl.
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->Uninitialize();
}
// static
base::RefCountedMemory* BitpopOptionsUI::GetFaviconResourceBytes(
ui::ScaleFactor scale_factor) {
return ui::ResourceBundle::GetSharedInstance().
LoadDataResourceBytesForScale(IDR_SETTINGS_FAVICON, scale_factor);
}
void BitpopOptionsUI::InitializeHandlers() {
Profile* profile = Profile::FromWebUI(web_ui());
DCHECK(!profile->IsOffTheRecord() || profile->IsGuestSession());
// A new web page DOM has been brought up in an existing renderer, causing
// this method to be called twice. If that happens, ignore the second call.
if (!initialized_handlers_) {
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->InitializeHandler();
initialized_handlers_ = true;
}
// Always initialize the page as when handlers are left over we still need to
// do various things like show/hide sections and send data to the Javascript.
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->InitializePage();
web_ui()->CallJavascriptFunction(
"BrowserOptions.notifyInitializationComplete");
}
void BitpopOptionsUI::RenderViewCreated(content::RenderViewHost* render_view_host) {
content::WebUIController::RenderViewCreated(render_view_host);
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->PageLoadStarted();
}
void BitpopOptionsUI::RenderViewReused(content::RenderViewHost* render_view_host) {
content::WebUIController::RenderViewReused(render_view_host);
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->PageLoadStarted();
}
void BitpopOptionsUI::AddOptionsPageUIHandler(DictionaryValue* localized_strings,
BitpopOptionsPageUIHandler* handler_raw) {
scoped_ptr<BitpopOptionsPageUIHandler> handler(handler_raw);
DCHECK(handler.get());
// Add only if handler's service is enabled.
if (handler->IsEnabled()) {
// Add handler to the list and also pass the ownership.
web_ui()->AddMessageHandler(handler.release());
handler_raw->GetLocalizedValues(localized_strings);
handlers_.push_back(handler_raw);
}
}
} // namespace options
| 36.579137 | 88 | 0.708821 | leiferikb |
021519459a4abdc8e68defbff44fd977dca0b7d2 | 21,457 | cpp | C++ | classes/ArgumentHelper.cpp | bmampaey/SPoCA | 902f3f713c1f86263a8c27d8a3cf429b508ed596 | [
"MIT"
] | null | null | null | classes/ArgumentHelper.cpp | bmampaey/SPoCA | 902f3f713c1f86263a8c27d8a3cf429b508ed596 | [
"MIT"
] | null | null | null | classes/ArgumentHelper.cpp | bmampaey/SPoCA | 902f3f713c1f86263a8c27d8a3cf429b508ed596 | [
"MIT"
] | null | null | null | /*
*
* Argument Helper
*
* Daniel Russel drussel@alumni.princeton.edu
* Stanford University
*
*
* This software is not subject to copyright protection and is in the
* public domain. Neither Stanford nor the author assume any
* responsibility whatsoever for its use by other parties, and makes no
* guarantees, expressed or implied, about its quality, reliability, or
* any other characteristic.
*
*/
#include "ArgumentHelper.h"
namespace dsr {
// This is a base class for representing one argument value.
/*
This is inherited by many classes and which represent the different types.
*/
class ArgumentHelper::Argument_target {
public:
char key;
std::string long_name;
std::string description;
std::string arg_description;
Argument_target(char k, const std::string lname,
const std::string descr,
const std::string arg_descr) {
key=k;
long_name=lname;
description=descr;
arg_description=arg_descr;
}
Argument_target(const std::string descr,
const std::string arg_descr) {
key=0;
long_name="";
description=descr;
arg_description=arg_descr;
}
virtual bool process(int &, const char **&)=0;
virtual void write_name(std::ostream &out) const;
virtual void write_value(std::ostream &out) const=0;
virtual void write_usage(std::ostream &out) const;
virtual ~Argument_target(){}
};
void ArgumentHelper::Argument_target::write_name(std::ostream &out) const {
if (key != 0) out << '-' << key;
else if (!long_name.empty()) out << "--" << long_name;
else out << arg_description;
}
void ArgumentHelper::Argument_target::write_usage(std::ostream &out) const {
if (key != 0) {
out << '-' << key;
out << "/--" << long_name;
}
out << ' ' << arg_description;
out << "\t" << description;
out << " Value: ";
write_value(out);
out << std::endl;
}
class ArgumentHelper::FlagTarget: public ArgumentHelper::Argument_target{
public:
bool &val;
FlagTarget(char k, const char *lname,
const char *descr,
bool &b): Argument_target(k, std::string(lname), std::string(descr),
std::string()), val(b){}
virtual bool process(int &, const char **&){
val= !val;
return true;
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual void write_usage(std::ostream &out) const {
if (key != 0) {
out << '-' << key;
out << "/--" << long_name;
}
out << "\t" << description;
out << " Value: ";
write_value(out);
out << std::endl;
}
virtual ~FlagTarget(){}
};
class ArgumentHelper::DoubleTarget: public Argument_target{
public:
double &val;
DoubleTarget(char k, const char *lname,
const char *arg_descr,
const char *descr, double &b): Argument_target(k, std::string(lname),
std::string(descr),
std::string(arg_descr)), val(b){}
DoubleTarget(const char *arg_descr,
const char *descr, double &b): Argument_target(std::string(descr),
std::string(arg_descr)), val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing value for argument." << std::endl;
return false;
}
if (sscanf(argv[0], "%le", &val) ==1){
--argc;
++argv;
return true;
} else {
std::cerr << "Double not found at " << argv[0] << std::endl;
return false;
}
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~DoubleTarget(){}
};
class ArgumentHelper::IntTarget: public Argument_target{
public:
int &val;
IntTarget(const char *arg_descr,
const char *descr, int &b): Argument_target(0, std::string(),
std::string(descr),
std::string(arg_descr)),
val(b){}
IntTarget(char k, const char *lname,
const char *arg_descr,
const char *descr, int &b): Argument_target(k, std::string(lname),
std::string(descr),
std::string(arg_descr)),
val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing value for argument." << std::endl;
return false;
}
if (sscanf(argv[0], "%d", &val) ==1){
--argc;
++argv;
return true;
} else {
std::cerr << "Integer not found at " << argv[0] << std::endl;
return false;
}
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~IntTarget(){}
};
class ArgumentHelper::UIntTarget: public Argument_target{
public:
unsigned int &val;
UIntTarget(const char *arg_descr,
const char *descr, unsigned int &b): Argument_target(0, std::string(),
std::string(descr),
std::string(arg_descr)),
val(b){}
UIntTarget(char k, const char *lname,
const char *arg_descr,
const char *descr, unsigned int &b): Argument_target(k, std::string(lname),
std::string(descr),
std::string(arg_descr)),
val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing value for argument." << std::endl;
return false;
}
if (sscanf(argv[0], "%ud", &val) ==1){
--argc;
++argv;
return true;
} else {
std::cerr << "Unsigned integer not found at " << argv[0] << std::endl;
return false;
}
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~UIntTarget(){}
};
class ArgumentHelper::ULongTarget: public Argument_target{
public:
unsigned long &val;
ULongTarget(const char *arg_descr,
const char *descr, unsigned long &b): Argument_target(0, std::string(),
std::string(descr),
std::string(arg_descr)),
val(b){}
ULongTarget(char k, const char *lname,
const char *arg_descr,
const char *descr, unsigned long &b): Argument_target(k, std::string(lname),
std::string(descr),
std::string(arg_descr)),
val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing value for argument." << std::endl;
return false;
}
if (sscanf(argv[0], "%lu", &val) ==1){
--argc;
++argv;
return true;
} else {
std::cerr << "Unsigned long not found at " << argv[0] << std::endl;
return false;
}
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~ULongTarget(){}
};
class ArgumentHelper::CharTarget: public Argument_target{
public:
char &val;
CharTarget(char k, const char *lname,
const char *arg_descr,
const char *descr, char &b): Argument_target(k, std::string(lname),
std::string(descr),
std::string(arg_descr)), val(b){}
CharTarget(const char *arg_descr,
const char *descr, char &b): Argument_target(std::string(descr),
std::string(arg_descr)), val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing value for argument." << std::endl;
return false;
}
if (sscanf(argv[0], "%c", &val) ==1){
--argc;
++argv;
return true;
} else {
std::cerr << "Character not found at " << argv[0] << std::endl;
return false;
}
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~CharTarget(){}
};
class ArgumentHelper::StringTarget: public Argument_target{
public:
std::string &val;
StringTarget(const char *arg_descr,
const char *descr, std::string &b): Argument_target(0, std::string(),
descr,
arg_descr),
val(b){}
StringTarget(char k, const char *lname, const char *arg_descr,
const char *descr, std::string &b): Argument_target(k, lname, descr,
arg_descr),
val(b){}
virtual bool process(int &argc, const char **&argv){
if (argc==0){
std::cerr << "Missing string argument." << std::endl;
return false;
}
val= argv[0];
--argc;
++argv;
return true;
}
virtual void write_value(std::ostream &out) const {
out << val;
}
virtual ~StringTarget(){}
};
class ArgumentHelper::StringVectorTarget: public Argument_target{
public:
std::vector<std::string> &val;
StringVectorTarget(char k, const char *lname, const char *arg_descr,
const char *descr, std::vector<std::string> &b): Argument_target(k, lname, descr,
arg_descr),
val(b){}
virtual bool process(int &argc, const char **&argv){
while (argc >0 && argv[0][0] != '-'){
val.push_back(argv[0]);
--argc;
++argv;
}
return true;
}
virtual void write_value(std::ostream &out) const {
for (unsigned int i=0; i< val.size(); ++i){
out << val[i] << " ";
}
}
virtual ~StringVectorTarget(){}
};
ArgumentHelper::ArgumentHelper(){
author_="Someone";
description_= "This program does something.";
date_= "A long long time ago.";
version_=-1;
extra_arguments_=NULL;
seen_end_named_=false;
}
void ArgumentHelper::set_string_vector(const char *arg_description,
const char *description,
std::vector<std::string> &dest){
assert(extra_arguments_==NULL);
extra_arguments_descr_= description;
extra_arguments_arg_descr_= arg_description;
extra_arguments_= &dest;
}
void ArgumentHelper::set_author(const char *author){
author_=author;
}
void ArgumentHelper::set_description(const char *descr){
description_= descr;
}
void ArgumentHelper::set_name(const char *descr){
name_= descr;
}
void ArgumentHelper::set_version(float v){
version_=v;
}
void ArgumentHelper::set_version(const char *s){
version_=atof(s);
}
void ArgumentHelper::set_build_date(const char *date){
date_=date;
}
void ArgumentHelper::new_argument_target(Argument_target *t) {
assert(t!= NULL);
if (t->key != 0){
if (short_names_.find(t->key) != short_names_.end()){
std::cerr << "Two arguments are defined with the same character key, namely" << std::endl;
short_names_[t->key]->write_usage(std::cerr);
std::cerr << "\n and \n";
t->write_usage(std::cerr);
std::cerr << std::endl;
}
short_names_[t->key]= t;
}
if (!t->long_name.empty()){
if (long_names_.find(t->long_name) != long_names_.end()){
std::cerr << "Two arguments are defined with the same long key, namely" << std::endl;
long_names_[t->long_name]->write_usage(std::cerr);
std::cerr << "\n and \n";
t->write_usage(std::cerr);
std::cerr << std::endl;
}
long_names_[t->long_name]= t;
}
all_arguments_.push_back(t);
}
void ArgumentHelper::new_flag(char key, const char *long_name, const char *description,bool &dest){
Argument_target *t= new FlagTarget(key, long_name, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_string(const char *arg_description, const char *description,
std::string &dest){
Argument_target *t= new StringTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_string(const char *arg_description, const char *description,
std::string &dest){
Argument_target *t= new StringTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_string(char key, const char *long_name,
const char *arg_description, const char *description,
std::string &dest){
Argument_target *t= new StringTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_named_string_vector(char key, const char *long_name,
const char *arg_description, const char *description,
std::vector<std::string> &dest){
Argument_target *t= new StringVectorTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_int(const char *arg_description, const char *description,
int &dest){
Argument_target *t= new IntTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_int(const char *arg_description, const char *description,
int &dest){
Argument_target *t= new IntTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_int(char key, const char *long_name,
const char *arg_description, const char *description,
int &dest){
Argument_target *t= new IntTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_unsigned_int(const char *arg_description, const char *description,
unsigned int &dest){
Argument_target *t= new UIntTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_unsigned_int(const char *arg_description, const char *description,
unsigned int &dest){
Argument_target *t= new UIntTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_unsigned_int(char key, const char *long_name,
const char *arg_description, const char *description,
unsigned int &dest){
Argument_target *t= new UIntTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_unsigned_long(const char *arg_description, const char *description,
unsigned long &dest){
Argument_target *t= new ULongTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_unsigned_long(const char *arg_description, const char *description,
unsigned long &dest){
Argument_target *t= new ULongTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_unsigned_long(char key, const char *long_name,
const char *arg_description, const char *description,
unsigned long &dest){
Argument_target *t= new ULongTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_double(const char *arg_description, const char *description,
double &dest){
Argument_target *t= new DoubleTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_double(const char *arg_description, const char *description,
double &dest){
Argument_target *t= new DoubleTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_double(char key, const char *long_name,
const char *arg_description, const char *description,
double &dest){
Argument_target *t= new DoubleTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::new_char(const char *arg_description, const char *description,
char &dest){
Argument_target *t= new CharTarget(arg_description, description, dest);
unnamed_arguments_.push_back(t);
all_arguments_.push_back(t);
};
void ArgumentHelper::new_optional_char(const char *arg_description, const char *description,
char &dest){
Argument_target *t= new CharTarget(arg_description, description, dest);
optional_unnamed_arguments_.push_back(t);
};
void ArgumentHelper::new_named_char(char key, const char *long_name,
const char *arg_description, const char *description,
char &dest){
Argument_target *t= new CharTarget(key, long_name, arg_description, description, dest);
new_argument_target(t);
};
void ArgumentHelper::write_usage(std::ostream &out) const {
out << name_ << " version " << version_ << ", by " << author_ << std::endl;
out << description_ << std::endl;
out << "Compiled on " << date_ << std::endl << std::endl;
out << "Usage: " << name_ << " ";
for (UVect::const_iterator it= unnamed_arguments_.begin(); it != unnamed_arguments_.end(); ++it){
(*it)->write_name(out);
out << " ";
}
for (UVect::const_iterator it= optional_unnamed_arguments_.begin();
it != optional_unnamed_arguments_.end(); ++it){
out << "[";
(*it)->write_name(out);
out << "] ";
}
if (extra_arguments_ != NULL) {
out << "[" << extra_arguments_arg_descr_ << "]";
}
out << std::endl << std::endl;
out << "All arguments:\n";
for (UVect::const_iterator it= unnamed_arguments_.begin(); it != unnamed_arguments_.end(); ++it){
(*it)->write_usage(out);
}
for (UVect::const_iterator it= optional_unnamed_arguments_.begin();
it != optional_unnamed_arguments_.end(); ++it){
(*it)->write_usage(out);
}
out << extra_arguments_arg_descr_ << ": " << extra_arguments_descr_ << std::endl;
for (SMap::const_iterator it= short_names_.begin(); it != short_names_.end(); ++it){
(it->second)->write_usage(out);
}
}
void ArgumentHelper::write_values(std::ostream &out) const {
for (UVect::const_iterator it= unnamed_arguments_.begin(); it != unnamed_arguments_.end(); ++it){
out << (*it)->description;
out << ": ";
(*it)->write_value(out);
out << std::endl;
}
for (UVect::const_iterator it= optional_unnamed_arguments_.begin();
it != optional_unnamed_arguments_.end(); ++it){
out << (*it)->description;
out << ": ";
(*it)->write_value(out);
out << std::endl;
}
if (extra_arguments_!=NULL){
for (std::vector<std::string>::const_iterator it= extra_arguments_->begin();
it != extra_arguments_->end(); ++it){
out << *it << " ";
}
}
for (SMap::const_iterator it= short_names_.begin(); it != short_names_.end(); ++it){
out << it->second->description;
out << ": ";
it->second->write_value(out);
out << std::endl;
}
}
ArgumentHelper::~ArgumentHelper(){
for (std::vector<Argument_target*>::iterator it= all_arguments_.begin();
it != all_arguments_.end(); ++it){
delete *it;
}
}
void ArgumentHelper::process(int argc, const char **argv){
name_= argv[0];
++argv;
--argc;
current_unnamed_= unnamed_arguments_.begin();
current_optional_unnamed_= optional_unnamed_arguments_.begin();
for ( int i=0; i< argc; ++i){
if (strcmp(argv[i], "--help") == 0){
write_usage(std::cout);
exit(0);
}
}
while (argc != 0){
const char* cur_arg= argv[0];
if (cur_arg[0]=='-' && !seen_end_named_){
--argc; ++argv;
if (cur_arg[1]=='-'){
if (cur_arg[2] == '\0') {
//std::cout << "Ending flags " << std::endl;
seen_end_named_=true;
} else {
// long argument
LMap::iterator f= long_names_.find(cur_arg+2);
if ( f != long_names_.end()){
if (!f->second->process(argc, argv)) {
handle_error();
}
} else {
std::cerr<< "Invalid long argument "<< cur_arg << ".\n";
handle_error();
}
}
} else {
if (cur_arg[1]=='\0') {
std::cerr << "Invalid argument " << cur_arg << ".\n";
handle_error();
}
SMap::iterator f= short_names_.find(cur_arg[1]);
if ( f != short_names_.end()){
if (!f->second->process(argc, argv)) {
handle_error();
}
} else {
std::cerr<< "Invalid short argument "<< cur_arg << ".\n";
handle_error();
}
}
} else {
if (current_unnamed_ != unnamed_arguments_.end()){
Argument_target *t= *current_unnamed_;
t->process(argc, argv);
++current_unnamed_;
} else if (current_optional_unnamed_ != optional_unnamed_arguments_.end()){
Argument_target *t= *current_optional_unnamed_;
t->process(argc, argv);
++current_optional_unnamed_;
} else if (extra_arguments_!= NULL){
extra_arguments_->push_back(cur_arg);
--argc;
++argv;
} else {
std::cerr << "Invalid extra argument " << argv[0] << std::endl;
handle_error();
}
}
}
if (current_unnamed_ != unnamed_arguments_.end()){
std::cerr << "Missing required arguments:" << std::endl;
for (; current_unnamed_ != unnamed_arguments_.end(); ++current_unnamed_){
(*current_unnamed_)->write_name(std::cerr);
std::cerr << std::endl;
}
std::cerr << std::endl;
handle_error();
}
}
void ArgumentHelper::handle_error() const {
write_usage(std::cerr);
exit(1);
}
}
| 31.052098 | 102 | 0.615277 | bmampaey |
0215dc982e9b92fb0d9f4cc0303459c635969a42 | 3,885 | cpp | C++ | src/data_science/logistic_regression.cpp | arotem3/numerics | ba208d9fc0ccb9471cfec9927a21622eb3535f54 | [
"Apache-2.0"
] | 18 | 2019-04-18T17:34:49.000Z | 2021-11-15T07:57:29.000Z | src/data_science/logistic_regression.cpp | arotem3/numerics | ba208d9fc0ccb9471cfec9927a21622eb3535f54 | [
"Apache-2.0"
] | null | null | null | src/data_science/logistic_regression.cpp | arotem3/numerics | ba208d9fc0ccb9471cfec9927a21622eb3535f54 | [
"Apache-2.0"
] | 4 | 2019-12-02T04:04:21.000Z | 2022-02-17T08:23:09.000Z | #include <numerics.hpp>
void mult_coefs_serial(arma::mat& yh, const arma::vec& coefs, const arma::rowvec& b, const arma::mat& w, const arma::mat& x) {
yh = arma::repmat(coefs.subvec(0,b.n_elem-1).as_row(), x.n_rows, 1);
arma::uword start = b.n_elem;
for (u_long i=0; i < w.n_rows; ++i) {
for (u_long j=0; j < w.n_cols; ++j) {
arma::uword ij = start + arma::sub2ind(arma::size(w), i, j);
yh.col(j) += x.col(i) * coefs(ij);
}
}
numerics::softmax_inplace(yh);
}
arma::vec grad_serial(const arma::mat& yh, const arma::vec& coefs, const arma::rowvec& b, const arma::mat& w, const arma::mat& x, const arma::mat& y, double L) {
u_long size = x.n_cols + 1;
size *= y.n_cols;
arma::vec out(size);
arma::mat res = y - yh;
for (u_long i=0; i < b.n_elem; ++i) {
out(i) = -arma::sum(res.col(i));
}
arma::uword start = b.n_elem;
for (u_long i=0; i < w.n_rows; ++i) {
for (u_long j=0; j < w.n_cols; ++j) {
arma::uword ij = start + arma::sub2ind(arma::size(w), i, j);
out(ij) = -arma::dot(x.col(i), res.col(j));
out(ij) += L * coefs(ij);
}
}
return out;
}
void fit_logreg(arma::mat& w, const arma::sp_mat& I, const arma::mat& P, const arma::mat& y, double L) {
u_long n = P.n_cols-1;
auto f = [&](const arma::vec& coefs) -> double {
arma::mat W = arma::reshape(coefs, n+1, y.n_cols);
arma::mat yh = P * W;
numerics::softmax_inplace(yh);
return 0.5*L*arma::trace(W.t()*I*W) - arma::accu(yh % y);
};
auto grad_f = [&](const arma::vec& coefs) -> arma::vec {
arma::mat W = arma::reshape(coefs, n+1, y.n_cols);
arma::mat yh = P * W;
numerics::softmax_inplace(yh);
arma::mat df = L*I*W - P.t()*(y - yh);
return df.as_col();
};
arma::vec coefs = w.as_col();
numerics::optimization::TrustMin fmin;
fmin.minimize(coefs, f, grad_f);
w = arma::reshape(coefs, n+1, y.n_cols);
}
arma::mat pred_logreg(const arma::mat& w, const arma::mat& P) {
arma::mat yh = P*w;
numerics::softmax_inplace(yh);
return yh;
}
void numerics::LogisticRegression::fit(const arma::mat& x, const arma::uvec& y) {
_check_xy(x, y);
_dim = x.n_cols;
u_long nobs = x.n_rows;
_encoder.fit(y);
arma::mat onehot = _encoder.encode(y);
u_long n = x.n_cols;
arma::mat P(nobs, n+1);
arma::sp_mat I = arma::speye(n+1,n+1); I(0,0) = 0;
P.col(0).ones();
P.cols(1,n) = x;
arma::mat W = arma::zeros(n+1, onehot.n_cols);
if (_lambda < 0) {
u_short nfolds = 5;
if (nobs / nfolds < 50) nfolds = 3;
KFolds2Arr<double,double> split(nfolds);
split.fit(P, onehot);
auto cv = [&](double L) -> double {
L = std::pow(10.0, L);
double score = 0;
for (u_short i=0; i < nfolds; ++i) {
fit_logreg(W, I, split.trainX(i), split.trainY(i), L);
arma::mat p = pred_logreg(W, split.testX(i));
score -= accuracy_score(_encoder.decode(split.testY(i)), _encoder.decode(p));
}
return score;
};
_lambda = optimization::fminbnd(cv, -5, 4, 0.1);
_lambda = std::pow(10.0, _lambda);
}
fit_logreg(W, I, P, onehot, _lambda);
_b = W.row(0);
_w = W.rows(1,n);
}
arma::mat numerics::LogisticRegression::predict_proba(const arma::mat& x) const {
_check_x(x);
arma::mat yh = x * _w;
yh.each_row() += _b;
softmax_inplace(yh);
return yh;
}
arma::uvec numerics::LogisticRegression::predict(const arma::mat& x) const {
return _encoder.decode(predict_proba(x));
}
double numerics::LogisticRegression::score(const arma::mat& x, const arma::uvec& y) const {
_check_xy(x,y);
return accuracy_score(y, predict(x));
} | 29.656489 | 161 | 0.551094 | arotem3 |
0217515b32bbeec62e4d1faf4e81d57b3d7b1c5f | 2,409 | cpp | C++ | Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp | yokeshrana/Fast_Algorithms_in_Data_Structures | 2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2 | [
"MIT"
] | 4 | 2021-01-15T16:30:48.000Z | 2021-08-12T03:17:00.000Z | Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp | andy489/Fast_Algorithms_in_Data_Structures | 0f28a75030df3367902f0aa859a34096ea2b2582 | [
"MIT"
] | null | null | null | Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp | andy489/Fast_Algorithms_in_Data_Structures | 0f28a75030df3367902f0aa859a34096ea2b2582 | [
"MIT"
] | 2 | 2021-02-24T14:50:08.000Z | 2021-02-28T17:39:41.000Z | /*
github.com/andy489
Complexity: <O(n.log(n), log(n))>
Link: http://www.spoj.com/problems/DISQUERY/
*/
#include <stdio.h>
#include <vector>
using namespace std;
#define pii pair<int,int>
#define pb push_back
#define f first
#define s second
const int mxN = 1e5 + 5;
const int mxLog = 17;
vector<pair<int, int>> adj[mxN];
// anc = ancestor, anc[v][k] stores 2^k-th ancestor of vertex v
int anc[mxN][mxLog], dep[mxN], mini[mxN][mxLog], maxi[mxN][mxLog];
void dfs(int u = 1, int p = -1, int w = 0) {
int i;
anc[u][0] = p;
if (p != -1) {
dep[u] = dep[p] + 1;
mini[u][0] = maxi[u][0] = w;
}
for (i = 1; i < mxLog; ++i) {
if (anc[u][i - 1] != -1) {
anc[u][i] = anc[anc[u][i - 1]][i - 1];
maxi[u][i] = max(maxi[u][i - 1], maxi[anc[u][i - 1]][i - 1]);
mini[u][i] = min(mini[u][i - 1], mini[anc[u][i - 1]][i - 1]);
} else
break;
}
for (const auto &child : adj[u])
if (child.f ^ p)
dfs(child.f, u, child.s);
}
pii lca(int u, int v) {
int i;
int ansMini = 1e9, ansMaxi = -1;
if (dep[u] > dep[v])
swap(u, v);
for (i = mxLog - 1; i >= 0; --i) {
if (anc[v][i] != -1 and dep[anc[v][i]] >= dep[u]) {
ansMini = min(ansMini, mini[v][i]);
ansMaxi = max(ansMaxi, maxi[v][i]);
v = anc[v][i];
}
}
if (v == u)
return {ansMini, ansMaxi};
for (i = mxLog - 1; i >= 0; --i) {
if (anc[v][i] != anc[u][i]) {
ansMini = min(ansMini, min(mini[v][i],mini[u][i]));
ansMaxi = max(ansMaxi, max(maxi[v][i],maxi[u][i]));
v = anc[v][i];
u = anc[u][i];
}
}
ansMini = min(ansMini, min(mini[v][0], mini[u][0]));
ansMaxi = max(ansMaxi, max(maxi[v][0],maxi[u][0]));
return {ansMini, ansMaxi};
}
int main() {
int n, i, j, u, v, w;
scanf("%d", &n);
for (i = 1; i < n; ++i) {
scanf("%d%d%d", &u, &v, &w);
adj[u].pb({v, w});
adj[v].pb({u, w});
}
for (i = 1; i <= n; ++i) {
for (j = 0; j < mxLog; ++j) {
anc[i][j] = -1;
maxi[i][j] = -1;
mini[i][j] = 1e9;
}
}
dfs();
int q;
scanf("%d", &q);
while (q--) {
scanf("%d%d", &u, &v);
pii ans = lca(u, v);
printf("%d %d\n", ans.f, ans.s);
}
return 0;
}
| 24.581633 | 73 | 0.429639 | yokeshrana |
021cfde3788cdde45bee5f039475f69d25bb37e8 | 1,023 | cpp | C++ | FangameReader/DetectorMouseController.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 3 | 2019-04-02T19:23:35.000Z | 2021-04-30T03:57:15.000Z | FangameReader/DetectorMouseController.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 1 | 2018-07-10T22:34:41.000Z | 2018-07-10T22:52:43.000Z | FangameReader/DetectorMouseController.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 3 | 2020-12-28T19:06:07.000Z | 2021-01-30T10:09:56.000Z | #include <common.h>
#pragma hdrstop
#include <DetectorMouseController.h>
#include <FangameDetectorState.h>
#include <MouseTarget.h>
#include <DetectorActionController.h>
namespace Fangame {
//////////////////////////////////////////////////////////////////////////
void CDetectorMouseController::OnMouseMove()
{
const auto pos = MousePixelPos();
detector.OnMouseAction( pos );
}
void CDetectorMouseController::OnMouseLeave()
{
detector.ClearIconHighlight();
}
void CDetectorMouseController::OnMouseClick()
{
const auto pos = MousePixelPos();
const auto target = detector.OnMouseAction( pos );
if( target != nullptr ) {
target->OnMouseClick( detector.GetActionController() );
}
}
void CDetectorMouseController::OnMouseDClick()
{
const auto pos = MousePixelPos();
const auto target = detector.OnMouseAction( pos );
if( target != nullptr ) {
target->OnMouseDClick( detector.GetActionController() );
}
}
//////////////////////////////////////////////////////////////////////////
} // namespace Fangame.
| 22.733333 | 74 | 0.638319 | TheBiob |
021d90eda0e13562cdffcd38536f0c49f8fc403f | 38,617 | hpp | C++ | thirdparty/nark/gold_hash_map.hpp | ktprime/emhash | 3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37 | [
"MIT"
] | 92 | 2019-09-11T05:17:20.000Z | 2022-03-31T09:54:06.000Z | thirdparty/nark/gold_hash_map.hpp | ktprime/emhash | 3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37 | [
"MIT"
] | 7 | 2019-11-23T16:24:03.000Z | 2020-09-15T13:07:06.000Z | thirdparty/nark/gold_hash_map.hpp | ktprime/emhash | 3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37 | [
"MIT"
] | 5 | 2020-06-10T07:20:04.000Z | 2022-03-01T08:43:18.000Z | #ifndef __nark_gold_hash_tab__
#define __nark_gold_hash_tab__
#ifdef _MSC_VER
#if _MSC_VER < 1600
#include <hash_map>
#define DEFAULT_HASH_FUNC stdext::hash
#else
#include <unordered_map>
#define DEFAULT_HASH_FUNC std::hash
#endif
#elif defined(__GNUC__) && __GNUC__ * 1000 + __GNUC_MINOR__ < 4001
#include <ext/hash_map>
#define DEFAULT_HASH_FUNC __gnu_cxx::hash
#elif defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103 || defined(_LIBCPP_VERSION)
#include <unordered_map>
#define DEFAULT_HASH_FUNC std::hash
#else
#include <tr1/unordered_map>
#define DEFAULT_HASH_FUNC std::tr1::hash
#endif
//#include <nark/parallel_lib.hpp>
#include "hash_common.hpp"
#include <utility> // for std::identity
#if 0
#include <boost/ref.hpp>
#include <boost/current_function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/type_traits/has_trivial_constructor.hpp>
#include <boost/type_traits/has_trivial_destructor.hpp>
#endif
namespace nark {
#if 1
template<class T>
struct nark_identity {
typedef T value_type;
const T& operator()(const T& x) const { return x; }
};
#else
#define nark_identity std::identity
#endif
template<class Key, class Object, size_t Offset>
struct ExtractKeyByOffset {
const Key& operator()(const Object& x) const {
return *reinterpret_cast<const Key *>(
reinterpret_cast<const char*>(&x) + Offset);
}
BOOST_STATIC_ASSERT(Offset >= 0);
BOOST_STATIC_ASSERT(Offset <= sizeof(Object)-sizeof(Key));
};
template< class Key
, class Elem = Key
, class HashEqual = hash_and_equal<Key, DEFAULT_HASH_FUNC<Key>, std::equal_to<Key> >
, class KeyExtractor = nark_identity<Elem>
, class NodeLayout = node_layout<Elem, unsigned/*LinkTp*/ >
, class HashTp = size_t
>
class gold_hash_tab : dummy_bucket<typename NodeLayout::link_t>
{
protected:
typedef typename NodeLayout::link_t LinkTp;
typedef typename NodeLayout::copy_strategy CopyStrategy;
// BOOST_STATIC_ASSERT(sizeof(LinkTp) <= sizeof(Elem));
using dummy_bucket<LinkTp>::tail;
using dummy_bucket<LinkTp>::delmark;
static const intptr_t hash_cache_disabled = 8; // good if compiler aggressive optimize
struct IsNotFree {
bool operator()(LinkTp link_val) const { return delmark != link_val; }
};
public:
typedef typename NodeLayout:: iterator fast_iterator;
typedef typename NodeLayout::const_iterator const_fast_iterator;
typedef std::reverse_iterator< fast_iterator> fast_reverse_iterator;
typedef std::reverse_iterator<const_fast_iterator> const_fast_reverse_iterator;
#ifdef NARK_GOLD_HASH_MAP_ITERATOR_USE_FAST
typedef fast_iterator iterator;
typedef const_fast_iterator const_iterator;
iterator get_iter(size_t idx) { return m_nl.begin() + idx; }
const_iterator get_iter(size_t idx) const { return m_nl.begin() + idx; }
#else
class iterator; friend class iterator;
class iterator {
public:
typedef Elem value_type;
typedef gold_hash_tab* OwnerPtr;
#define ClassIterator iterator
#include "gold_hash_map_iterator.hpp"
};
class const_iterator; friend class const_iterator;
class const_iterator {
public:
typedef const Elem value_type;
const_iterator(const iterator& y)
: owner(y.get_owner()), index(y.get_index()) {}
typedef const gold_hash_tab* OwnerPtr;
#define ClassIterator const_iterator
#include "gold_hash_map_iterator.hpp"
};
iterator get_iter(size_t idx) { return iterator(this, idx); }
const_iterator get_iter(size_t idx) const { return const_iterator(this, idx); }
#endif
typedef std::reverse_iterator< iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef Elem value_type;
typedef Elem& reference;
typedef const Key key_type;
protected:
NodeLayout m_nl;
LinkTp* bucket; // index to m_nl
HashTp* pHash;
double load_factor;
size_t nBucket; // may larger than LinkTp.max if LinkTp is small than size_t
LinkTp nElem;
LinkTp maxElem;
LinkTp maxload; // cached guard for calling rehash
LinkTp freelist_head;
LinkTp freelist_size;
LinkTp freelist_freq;
bool is_sorted;
HashEqual he;
KeyExtractor keyExtract;
private:
void init() {
new(&m_nl)NodeLayout();
nElem = 0;
maxElem = 0;
maxload = 0;
if (!std::is_trivial_destructor<Elem>::value || sizeof(Elem) > sizeof(intptr_t))
pHash = NULL;
else
pHash = (HashTp*)(hash_cache_disabled);
bucket = const_cast<LinkTp*>(&tail); // false start
nBucket = 1;
freelist_head = delmark; // don't use freelist
freelist_size = 0;
freelist_freq = 0;
load_factor = 0.8;
is_sorted = true;
}
void relink_impl(bool bFillHash) {
LinkTp* pb = bucket;
size_t nb = nBucket;
NodeLayout nl = m_nl;
// (LinkTp)tail is just used for coerce tail be passed by value
// otherwise, tail is passed by reference, this cause g++ link error
if (nb > 1) {
assert(&tail != pb);
std::fill_n(pb, nb, (LinkTp)tail);
} else {
assert(&tail == pb);
return;
}
{ // set delmark
LinkTp i = freelist_head;
while (i < delmark) {
nl.link(i) = delmark;
i = reinterpret_cast<LinkTp&>(nl.data(i));
}
}
if (intptr_t(pHash) == hash_cache_disabled) {
if (0 == freelist_size)
for (size_t j = 0, n = nElem; j < n; ++j) {
size_t i = he.hash(keyExtract(nl.data(j))) % nb;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
else
for (size_t j = 0, n = nElem; j < n; ++j) {
if (delmark != nl.link(j)) {
size_t i = he.hash(keyExtract(nl.data(j))) % nb;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
}
}
else if (bFillHash) {
HashTp* ph = pHash;
if (0 == freelist_size)
for (size_t j = 0, n = nElem; j < n; ++j) {
HashTp h = HashTp(he.hash(keyExtract(nl.data(j))));
size_t i = h % nb;
ph[j] = h;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
else
for (size_t j = 0, n = nElem; j < n; ++j) {
if (delmark != nl.link(j)) {
HashTp h = HashTp(he.hash(keyExtract(nl.data(j))));
size_t i = h % nb;
ph[j] = h;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
}
}
else {
const HashTp* ph = pHash;
if (0 == freelist_size)
for (size_t j = 0, n = nElem; j < n; ++j) {
size_t i = ph[j] % nb;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
else
for (size_t j = 0, n = nElem; j < n; ++j) {
if (delmark != nl.link(j)) {
size_t i = ph[j] % nb;
nl.link(j) = pb[i];
pb[i] = LinkTp(j);
}
}
}
}
void relink() { relink_impl(false); }
void relink_fill() { relink_impl(true); }
void destroy() {
NodeLayout nl = m_nl;
if (!nl.is_null()) {
if (!std::is_trivial_destructor<Elem>::value) {
if (freelist_is_empty()) {
for (size_t i = nElem; i > 0; --i)
nl.data(i-1).~Elem();
} else {
for (size_t i = nElem; i > 0; --i)
if (delmark != nl.link(i-1))
nl.data(i-1).~Elem();
}
}
m_nl.free();
}
if (intptr_t(pHash) != hash_cache_disabled && NULL != pHash)
free(pHash);
if (bucket && &tail != bucket)
free(bucket);
}
public:
explicit gold_hash_tab(HashEqual he = HashEqual()
, KeyExtractor keyExtr = KeyExtractor())
: he(he), keyExtract(keyExtr) {
init();
}
explicit gold_hash_tab(size_t cap
, HashEqual he = HashEqual()
, KeyExtractor keyExtr = KeyExtractor())
: he(he), keyExtract(keyExtr) {
init();
rehash(cap);
}
/// ensured not calling HashEqual and KeyExtractor
gold_hash_tab(const gold_hash_tab& y)
: he(y.he), keyExtract(y.keyExtract) {
nElem = y.nElem;
maxElem = y.nElem;
maxload = y.maxload;
nBucket = y.nBucket;
pHash = NULL;
freelist_head = y.freelist_head;
freelist_size = y.freelist_size;
freelist_freq = y.freelist_freq;
load_factor = y.load_factor;
is_sorted = y.is_sorted;
if (0 == nElem) { // empty
nBucket = 1;
maxload = 0;
bucket = const_cast<LinkTp*>(&tail);
return; // not need to do deep copy
}
assert(y.bucket != &tail);
m_nl.reserve(0, nElem);
bucket = (LinkTp*)malloc(sizeof(LinkTp) * y.nBucket);
if (NULL == bucket) {
m_nl.free();
init();
throw std::bad_alloc();
}
if (intptr_t(y.pHash) == hash_cache_disabled) {
pHash = (HashTp*)(hash_cache_disabled);
}
else {
pHash = (HashTp*)malloc(sizeof(HashTp) * nElem);
if (NULL == pHash) {
free(bucket);
m_nl.free();
throw std::bad_alloc();
}
memcpy(pHash, y.pHash, sizeof(HashTp) * nElem);
}
memcpy(bucket, y.bucket, sizeof(LinkTp) * nBucket);
if (!std::is_trivial_copy<Elem>::value
&& freelist_size) {
node_layout_copy_cons(m_nl, y.m_nl, nElem, IsNotFree());
} else // freelist is empty, copy all
node_layout_copy_cons(m_nl, y.m_nl, nElem);
}
gold_hash_tab& operator=(const gold_hash_tab& y) {
if (this != &y) {
#if 1 // prefer performance, std::map is in this manner
// this is exception-safe but not transactional
// non-transactional: lose old content of *this on exception
this->destroy();
new(this)gold_hash_tab(y);
#else // exception-safe, but take more peak memory
gold_hash_tab(y).swap(*this);
#endif
}
return *this;
}
~gold_hash_tab() { destroy(); }
void swap(gold_hash_tab& y) {
std::swap(pHash , y.pHash);
std::swap(m_nl , y.m_nl);
std::swap(nElem , y.nElem);
std::swap(maxElem, y.maxElem);
std::swap(maxload, y.maxload);
std::swap(nBucket, y.nBucket);
std::swap(bucket , y.bucket);
std::swap(freelist_head, y.freelist_head);
std::swap(freelist_size, y.freelist_size);
std::swap(freelist_freq, y.freelist_freq);
std::swap(load_factor, y.load_factor);
std::swap(is_sorted , y.is_sorted);
std::swap(he , y.he);
std::swap(keyExtract , y.keyExtract);
}
// void setHashEqual(const HashEqual& he) { this->he = he; }
// void setKeyExtractor(const KeyExtractor& kEx) { this->keyExtract = kEx; }
const HashEqual& getHashEqual() const { return this->he; }
const KeyExtractor& getKeyExtractor() const { return this->keyExtract; }
void clear() {
destroy();
init();
}
void shrink_to_fit() { if (nElem < maxElem) reserve(nElem); }
bool is_hash_cached() const {
return intptr_t(pHash) != hash_cache_disabled;
}
void enable_hash_cache() {
if (intptr_t(pHash) == hash_cache_disabled) {
if (0 == maxElem) {
pHash = NULL;
}
else {
HashTp* ph = (HashTp*)malloc(sizeof(HashTp) * maxElem);
if (NULL == ph) {
throw std::bad_alloc();
}
if (0 == freelist_size) {
for (size_t i = 0, n = nElem; i < n; ++i)
ph[i] = he.hash(keyExtract(m_nl.data(i)));
}
else {
for (size_t i = 0, n = nElem; i < n; ++i)
if (delmark != m_nl.link(i))
ph[i] = he.hash(keyExtract(m_nl.data(i)));
}
pHash = ph;
}
}
assert(NULL != pHash || 0 == maxElem);
}
void disable_hash_cache() {
if (intptr_t(pHash) == hash_cache_disabled)
return;
if (pHash)
free(pHash);
pHash = (HashTp*)(hash_cache_disabled);
}
void rehash(size_t newBucketSize) {
newBucketSize = __hsm_stl_next_prime(newBucketSize);
if (newBucketSize != nBucket) {
// shrink or enlarge
if (bucket != &tail) {
assert(NULL != bucket);
free(bucket);
}
bucket = (LinkTp*)malloc(sizeof(LinkTp) * newBucketSize);
if (NULL == bucket) { // how to handle?
assert(0); // immediately fail on debug mode
destroy();
throw std::runtime_error("rehash failed, unrecoverable");
}
nBucket = newBucketSize;
relink();
maxload = LinkTp(newBucketSize * load_factor);
}
}
// void resize(size_t n) { rehash(n); }
void reserve(size_t cap) {
reserve_nodes(cap);
rehash(size_t(cap / load_factor + 1));
}
void reserve_nodes(size_t cap) {
// assert(cap >= maxElem); // could be shrink
assert(cap >= nElem);
assert(cap <= delmark);
if (cap != (size_t)maxElem && cap != nElem) {
if (intptr_t(pHash) != hash_cache_disabled) {
HashTp* ph = (HashTp*)realloc(pHash, sizeof(HashTp) * cap);
if (NULL == ph)
throw std::bad_alloc();
pHash = ph;
}
if (freelist_size)
m_nl.reserve(nElem, cap, IsNotFree());
else
m_nl.reserve(nElem, cap);
maxElem = LinkTp(cap);
}
}
void set_load_factor(double fact) {
if (fact >= 0.999) {
throw std::logic_error("load factor must <= 0.999");
}
load_factor = fact;
maxload = &tail == bucket ? 0 : LinkTp(nBucket * fact);
}
double get_load_factor() const { return load_factor; }
inline HashTp hash_i(size_t i) const {
assert(i < nElem);
if (intptr_t(pHash) == hash_cache_disabled)
return HashTp(he.hash(keyExtract(m_nl.data(i))));
else
return pHash[i];
}
inline HashTp hash_v(const Elem& e) const {
return HashTp(he.hash(keyExtract(e)));
}
bool empty() const { return nElem == freelist_size; }
size_t size() const { return nElem - freelist_size; }
size_t beg_i() const {
size_t i;
if (freelist_size == nElem)
i = nElem;
else if (freelist_size && delmark == m_nl.link(0))
i = next_i(0);
else
i = 0;
return i;
}
size_t end_i() const { return nElem; }
size_t rbeg_i() const { return freelist_size == nElem ? 0 : nElem; }
size_t rend_i() const { return 0; }
size_t next_i(size_t idx) const {
size_t n = nElem;
assert(idx < n);
do ++idx; while (idx < n && delmark == m_nl.link(idx));
return idx;
}
size_t prev_i(size_t idx) const {
assert(idx > 0);
assert(idx <= nElem);
do --idx; while (idx > 0 && delmark == m_nl.link(idx));
return idx;
}
size_t capacity() const { return maxElem; }
size_t delcnt() const { return freelist_size; }
iterator begin() { return get_iter(beg_i()); }
const_iterator begin() const { return get_iter(beg_i()); }
const_iterator cbegin() const { return get_iter(beg_i()); }
iterator end() { return get_iter(nElem); }
const_iterator end() const { return get_iter(nElem); }
const_iterator cend() const { return get_iter(nElem); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
fast_iterator fast_begin() { return m_nl.begin(); }
const_fast_iterator fast_begin() const { return m_nl.begin(); }
const_fast_iterator fast_cbegin() const { return m_nl.begin(); }
fast_iterator fast_end() { return m_nl.begin() + nElem; }
const_fast_iterator fast_end() const { return m_nl.begin() + nElem; }
const_fast_iterator fast_cend() const { return m_nl.begin() + nElem; }
fast_reverse_iterator fast_rbegin() { return fast_reverse_iterator(fast_end()); }
const_fast_reverse_iterator fast_rbegin() const { return const_fast_reverse_iterator(fast_end()); }
const_fast_reverse_iterator fast_crbegin() const { return const_fast_reverse_iterator(fast_end()); }
fast_reverse_iterator fast_rend() { return fast_reverse_iterator(fast_begin()); }
const_fast_reverse_iterator fast_rend() const { return const_fast_reverse_iterator(fast_begin()); }
const_fast_reverse_iterator fast_crend() const { return const_fast_reverse_iterator(fast_begin()); }
template<class CompatibleObject>
std::pair<iterator, bool> insert(const CompatibleObject& obj) {
std::pair<size_t, bool> ib = insert_i(obj);
return std::pair<iterator, bool>(get_iter(ib.first), ib.second);
}
template<class Arg1>
std::pair<iterator, bool> emplace(const Arg1& a1) {
std::pair<size_t, bool> ib = insert_i(value_type(a1));
return std::pair<iterator, bool>(get_iter(ib.first), ib.second);
}
template<class Arg1, class Arg2>
std::pair<iterator, bool> emplace(const Arg1& a1, const Arg2& a2) {
std::pair<size_t, bool> ib = insert_i(value_type(a1, a2));
return std::pair<iterator, bool>(get_iter(ib.first), ib.second);
}
#if defined(HSM_HAS_MOVE)
template<class... _Valty>
std::pair<iterator, bool> emplace(_Valty&&... _Val) {
std::pair<size_t, bool> ib =
insert_i(value_type(std::forward<_Valty>(_Val)...));
return std::pair<iterator, bool>(get_iter(ib.first), ib.second);
}
#endif
iterator find(const Key& key) { return get_iter(find_i(key)); }
const_iterator find(const Key& key) const { return get_iter(find_i(key)); }
// keep memory
void erase_all() {
NodeLayout nl = m_nl;
if (!nl.is_null()) {
if (!std::is_trivial_destructor<Elem>::value) {
if (freelist_is_empty()) {
for (size_t i = nElem; i > 0; --i)
nl.data(i-1).~Elem();
} else {
for (size_t i = nElem; i > 0; --i)
if (delmark != nl.link(i-1))
nl.data(i-1).~Elem();
}
}
}
if (freelist_head < delmark) {
assert(freelist_head < nElem);
freelist_head = tail;
freelist_size = 0;
freelist_freq = 0;
}
if (nElem) {
std::fill_n(bucket, nBucket, (LinkTp)tail);
nElem = 0;
}
}
#ifndef NARK_GOLD_HASH_MAP_ITERATOR_USE_FAST
void erase(iterator iter) {
assert(iter.get_owner() == this);
assert(!m_nl.is_null());
assert(iter.get_index() < nElem);
erase_i(iter.get_index());
}
#endif
void erase(fast_iterator iter) {
assert(!m_nl.is_null());
assert(iter >= m_nl.begin());
assert(iter < m_nl.begin() + nElem);
erase_i(iter - m_nl.begin());
}
private:
// return erased elements count
template<class Predictor>
size_t erase_if_impl(Predictor pred, FastCopy) {
if (freelist_size)
// this extra scan should be eliminated, by some way
revoke_deleted_no_relink();
NodeLayout nl = m_nl;
size_t i = 0, n = nElem;
for (; i < n; ++i)
if (pred(nl.data(i)))
goto DoErase;
return 0;
DoErase:
HashTp* ph = pHash;
nl.data(i).~Elem();
if (intptr_t(ph) == hash_cache_disabled) {
for (size_t j = i + 1; j != n; ++j)
if (pred(nl.data(j)))
nl.data(j).~Elem();
else
memcpy(&nl.data(i), &nl.data(j), sizeof(Elem)), ++i;
} else {
for (size_t j = i + 1; j != n; ++j)
if (pred(nl.data(j)))
nl.data(j).~Elem();
else {
ph[i] = ph[j];
memcpy(&nl.data(i), &nl.data(j), sizeof(Elem)), ++i;
}
}
nElem = i;
if (0 == i) { // all elements are erased
this->destroy();
this->init();
}
return n - i; // erased elements count
}
template<class Predictor>
size_t erase_if_impl(Predictor pred, SafeCopy) {
if (freelist_size)
// this extra scan should be eliminated, by some way
revoke_deleted_no_relink();
NodeLayout nl = m_nl;
size_t i = 0, n = nElem;
for (; i < n; ++i)
if (pred(nl.data(i)))
goto DoErase;
return 0;
DoErase:
HashTp* ph = pHash;
if (intptr_t(ph) == hash_cache_disabled) {
for (size_t j = i + 1; j != n; ++j)
if (!pred(nl.data(j)))
std::swap(nl.data(i), nl.data(j)), ++i;
} else {
for (size_t j = i + 1; j != n; ++j)
if (!pred(nl.data(j))) {
ph[i] = ph[j];
std::swap(nl.data(i), nl.data(j)), ++i;
}
}
if (!std::is_trivial_destructor<Elem>::value) {
for (size_t j = i; j != n; ++j)
nl.data(j).~Elem();
}
nElem = i;
if (0 == i) { // all elements are erased
this->destroy();
this->init();
}
return n - i; // erased elements count
}
public:
//@{
//@brief erase_if
/// will invalidate saved id/index/iterator
/// can be called even if freelist_is_using
template<class Predictor>
size_t erase_if(Predictor pred) {
if (freelist_is_using())
return keepid_erase_if(pred);
else {
size_t nErased = erase_if_impl(pred, CopyStrategy());
if (nElem * 2 <= maxElem)
shrink_to_fit();
else
relink();
return nErased;
}
}
template<class Predictor>
size_t shrink_after_erase_if(Predictor pred) {
size_t nErased = erase_if_impl(pred, CopyStrategy());
shrink_to_fit();
return nErased;
}
template<class Predictor>
size_t no_shrink_after_erase_if(Predictor pred) {
size_t nErased = erase_if_impl(pred, CopyStrategy());
relink();
return nErased;
}
//@}
template<class Predictor>
size_t keepid_erase_if(Predictor pred) {
// should be much slower than erase_if
assert(freelist_is_using());
size_t n = nElem;
size_t erased = 0;
NodeLayout nl = m_nl;
if (freelist_is_empty()) {
assert(0 == freelist_size);
for (size_t i = 0; i != n; ++i)
if (pred(nl.data(i)))
erase_to_freelist(i), ++erased;
}
else {
assert(0 != freelist_size);
for (size_t i = 0; i != n; ++i)
if (delmark != nl.link(i) && pred(nl.data(i)))
erase_to_freelist(i), ++erased;
}
return erased;
}
// if return non-zero, all permanent id/index are invalidated
size_t revoke_deleted() {
assert(freelist_is_using()); // must be using/enabled
if (freelist_size) {
size_t erased = revoke_deleted_no_relink();
relink();
return erased;
} else
return 0;
}
bool is_deleted(size_t idx) const {
assert(idx < nElem);
assert(freelist_is_using());
return delmark == m_nl.link(idx);
}
//@{
/// default is disabled
void enable_freelist() {
if (delmark == freelist_head) {
assert(0 == freelist_size);
freelist_head = tail;
}
}
/// @note this function may take O(n) time
void disable_freelist() {
if (delmark != freelist_head) {
revoke_deleted();
freelist_head = delmark;
}
}
bool freelist_is_empty() const { return freelist_head >= delmark; }
bool freelist_is_using() const { return freelist_head != delmark; }
//@}
template<class CompatibleObject>
std::pair<size_t, bool> insert_i(const CompatibleObject& obj) {
const Key& key = keyExtract(obj);
const HashTp h = HashTp(he.hash(key));
size_t i = h % nBucket;
for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) {
HSM_SANITY(p < nElem);
if (he.equal(key, keyExtract(m_nl.data(p))))
return std::make_pair(p, false);
}
if (nark_unlikely(nElem - freelist_size >= maxload)) {
rehash(nBucket + 1); // will auto find next prime bucket size
i = h % nBucket;
}
size_t slot = risk_slot_alloc(); // here, no risk
new(&m_nl.data(slot))Elem(obj);
m_nl.link(slot) = bucket[i]; // newer at head
bucket[i] = LinkTp(slot); // new head of i'th bucket
if (intptr_t(pHash) != hash_cache_disabled)
pHash[slot] = h;
is_sorted = false;
return std::make_pair(slot, true);
}
///@{ low level operations
/// the caller should pay the risk for gain
///
LinkTp risk_slot_alloc() {
LinkTp slot;
if (freelist_is_empty()) {
assert(0 == freelist_size);
slot = nElem;
if (nark_unlikely(nElem == maxElem))
reserve_nodes(0 == nElem ? 1 : 2*nElem);
assert(nElem < maxElem);
nElem++;
} else {
assert(freelist_head < nElem);
assert(freelist_size > 0);
slot = freelist_head;
assert(delmark == m_nl.link(slot));
freelist_size--;
freelist_head = reinterpret_cast<LinkTp&>(m_nl.data(slot));
}
m_nl.link(slot) = tail; // for debug check&verify
return slot;
}
/// precond: # Elem on slot is constructed
/// # Elem on slot is not in the table:
/// it is not reached through 'bucket'
/// effect: destory the Elem on slot then free the slot
void risk_slot_free(size_t slot) {
assert(slot < nElem);
assert(delmark != m_nl.link(slot));
if (nark_unlikely(nElem-1 == slot)) {
m_nl.data(slot).~Elem();
--nElem;
}
else if (freelist_is_using()) {
fast_slot_free(slot);
is_sorted = false;
}
else {
assert(!"When freelist is disabled, nElem-1==slot must be true");
throw std::logic_error(BOOST_CURRENT_FUNCTION);
}
}
/// @note when calling this function:
// 1. this->begin()[slot] must has been newly constructed by the caller
// 2. this->begin()[slot] must not existed in the hash index
size_t risk_insert_on_slot(size_t slot) {
assert(slot < nElem);
assert(delmark != m_nl.link(slot));
const Key& key = keyExtract(m_nl.data(slot));
const HashTp h = HashTp(he.hash(key));
size_t i = h % nBucket;
for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) {
assert(p != slot); // slot must not be reached
HSM_SANITY(p < nElem);
if (he.equal(key, keyExtract(m_nl.data(p))))
return p;
}
if (intptr_t(pHash) != hash_cache_disabled)
pHash[slot] = h;
if (nark_unlikely(nElem - freelist_size >= maxload)) { // must be >=
// rehash will set the bucket&link for 'slot'
rehash(nBucket + 1); // will auto find next prime bucket size
} else {
m_nl.link(slot) = bucket[i]; // newer at head
bucket[i] = LinkTp(slot); // new head of i'th bucket
}
is_sorted = false;
return slot;
}
void risk_size_inc(LinkTp n) {
if (nark_unlikely(nElem + n > maxElem))
reserve_nodes(nElem + std::max(nElem, n));
assert(nElem + n <= maxElem);
NodeLayout nl = m_nl;
for (size_t i = n, j = nElem; i; --i, ++j)
nl.link(j) = (LinkTp)tail;
nElem += n;
}
void risk_size_dec(LinkTp n) {
assert(nElem >= n);
nElem -= n;
}
// BOOST_CONSTANT(size_t, risk_data_stride = NodeLayout::data_stride);
//@}
size_t find_i(const Key& key) const {
const HashTp h = HashTp(he.hash(key));
const size_t i = h % nBucket;
for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) {
HSM_SANITY(p < nElem);
if (he.equal(key, keyExtract(m_nl.data(p))))
return p;
}
return nElem; // not found
}
template<class CompatibleKey>
size_t find_i(const CompatibleKey& key) const {
const HashTp h = HashTp(he.hash(key));
const size_t i = h % nBucket;
for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) {
HSM_SANITY(p < nElem);
if (he.equal(key, keyExtract(m_nl.data(p))))
return p;
}
return nElem; // not found
}
// return erased element count
size_t erase(const Key& key) {
const HashTp h = HashTp(he.hash(key));
const HashTp i = h % nBucket;
for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) {
HSM_SANITY(p < nElem);
if (he.equal(key, keyExtract(m_nl.data(p)))) {
erase_i_impl(p, i);
return 1;
}
}
return 0;
}
size_t count(const Key& key) const {
return find_i(key) == nElem ? 0 : 1;
}
// return value is same with count(key), but type is different
// this function is not stl standard, but more meaningful for app
bool exists(const Key& key) const {
return find_i(key) != nElem;
}
private:
// if return non-zero, all permanent id/index are invalidated
size_t revoke_deleted_no_relink() {
assert(freelist_is_using()); // must be using/enabled
assert(freelist_size > 0);
NodeLayout nl = m_nl;
size_t i = 0, n = nElem;
for (; i < n; ++i)
if (delmark == nl.link(i))
goto DoErase;
assert(0); // would not go here
DoErase:
HashTp* ph = pHash;
if (intptr_t(ph) == hash_cache_disabled) {
for (size_t j = i + 1; j < n; ++j)
if (delmark != nl.link(j))
CopyStrategy::move_cons(&nl.data(i), nl.data(j)), ++i;
} else {
for (size_t j = i + 1; j < n; ++j)
if (delmark != nl.link(j)) {
ph[i] = ph[j]; // copy cached hash value
CopyStrategy::move_cons(&nl.data(i), nl.data(j)), ++i;
}
}
nElem = i;
freelist_head = tail;
freelist_size = 0;
return n - i; // erased elements count
}
// use erased elem as free list link
HSM_FORCE_INLINE void fast_slot_free(size_t slot) {
m_nl.link(slot) = delmark;
m_nl.data(slot).~Elem();
reinterpret_cast<LinkTp&>(m_nl.data(slot)) = freelist_head;
freelist_size++;
freelist_freq++; // never decrease
freelist_head = slot;
}
HSM_FORCE_INLINE void
erase_to_freelist(const size_t slot) {
HashTp const h = hash_i(slot);
size_t const i = h % nBucket;
HSM_SANITY(tail != bucket[i]);
LinkTp* curp = &bucket[i];
LinkTp curr; // delete from collision list ...
while (slot != (curr = *curp)) {
curp = &m_nl.link(curr);
HSM_SANITY(*curp < nElem);
}
*curp = m_nl.link(slot); // delete the idx'th node from collision list
fast_slot_free(slot);
}
// bucket_idx == hash % nBucket
void erase_i_impl(const size_t idx, const HashTp bucket_idx) {
size_t n = nElem;
HashTp*ph = pHash;
HSM_SANITY(n >= 1);
#if defined(_DEBUG) || !defined(NDEBUG)
assert(idx < n);
#else
if (idx >= n) {
throw std::invalid_argument(BOOST_CURRENT_FUNCTION);
}
#endif
HSM_SANITY(tail != bucket[bucket_idx]);
LinkTp* curp = &bucket[bucket_idx];
LinkTp curr;
while (idx != (curr = *curp)) {
curp = &m_nl.link(curr);
HSM_SANITY(*curp < n);
}
*curp = m_nl.link(idx); // delete the idx'th node from collision list
if (nark_unlikely(n-1 == idx)) {
m_nl.data(idx).~Elem();
--nElem;
}
else if (freelist_is_using()) {
assert(!is_deleted(idx));
fast_slot_free(idx);
is_sorted = false;
}
else {
// Move last Elem to slot idx
//
// delete last Elem from it's collision list
const HashTp lastHash = hash_i(n-1);
const size_t j = lastHash % nBucket;
HSM_SANITY(tail != bucket[j]);
curp = &bucket[j];
while (n-1 != (curr = *curp)) {
curp = &m_nl.link(curr);
HSM_SANITY(*curp < n);
}
*curp = m_nl.link(n-1); // delete the last node from link list
// put last Elem to the slot idx and sync the link
CopyStrategy::move_assign(&m_nl.data(idx), m_nl.data(n-1));
m_nl.link(idx) = bucket[j];
if (intptr_t(ph) != hash_cache_disabled)
ph[idx] = lastHash;
bucket[j] = LinkTp(idx);
is_sorted = false;
--nElem;
}
}
public:
void erase_i(const size_t idx) {
assert(nElem >= 1);
assert(idx < nElem);
assert(delmark != m_nl.link(idx));
erase_i_impl(idx, hash_i(idx) % nBucket);
}
const Key& key(size_t idx) const {
assert(nElem >= 1);
assert(idx < nElem);
assert(delmark != m_nl.link(idx));
return keyExtract(m_nl.data(idx));
}
const Key& end_key(size_t idxEnd) const {
assert(nElem >= 1);
assert(idxEnd >= 1);
assert(idxEnd <= nElem);
assert(delmark != m_nl.link(nElem - idxEnd));
return keyExtract(m_nl.data(nElem - idxEnd));
}
const Elem& elem_at(size_t idx) const {
assert(nElem >= 1);
assert(idx < nElem);
assert(delmark != m_nl.link(idx));
return m_nl.data(idx);
}
Elem& elem_at(size_t idx) {
assert(nElem >= 1);
assert(idx < nElem);
assert(delmark != m_nl.link(idx));
return m_nl.data(idx);
}
const Elem& end_elem(size_t idxEnd) const {
assert(nElem >= 1);
assert(idxEnd >= 1);
assert(idxEnd <= nElem);
assert(delmark != m_nl.link(nElem - idxEnd));
return m_nl.data(nElem - idxEnd);
}
Elem& end_elem(size_t idxEnd) {
assert(nElem >= 1);
assert(idxEnd >= 1);
assert(idxEnd <= nElem);
assert(delmark != m_nl.link(nElem - idxEnd));
return m_nl.data(nElem - idxEnd);
}
template<class OP>
void for_each(OP op) {
size_t n = nElem;
NodeLayout nl = m_nl;
if (freelist_size) {
assert(freelist_is_using());
for (size_t i = 0; i != n; ++i)
if (delmark != nl.link(i))
op(nl.data(i));
} else {
for (size_t i = 0; i != n; ++i)
op(nl.data(i));
}
}
template<class OP>
void for_each(OP op) const {
const size_t n = nElem;
const NodeLayout nl = m_nl;
if (freelist_size) {
assert(freelist_is_using());
for (size_t i = 0; i != n; ++i)
if (delmark != nl.link(i))
op(nl.data(i));
} else {
for (size_t i = 0; i != n; ++i)
op(nl.data(i));
}
}
template<class Compare> void sort(Compare comp) {
if (freelist_size)
revoke_deleted_no_relink();
fast_iterator beg_iter = m_nl.begin();
fast_iterator end_iter = beg_iter + nElem;
nark_parallel_sort(beg_iter, end_iter, Compare(comp));
relink_fill();
is_sorted = true;
}
void sort() { sort(std::less<Elem>()); }
size_t bucket_size() const { return nBucket; }
template<class IntVec>
void bucket_histogram(IntVec& hist) const {
for (size_t i = 0, n = nBucket; i < n; ++i) {
size_t listlen = 0;
for (LinkTp j = bucket[i]; j != tail; j = m_nl.link(j))
++listlen;
if (hist.size() <= listlen)
hist.resize(listlen+1);
hist[listlen]++;
}
}
protected:
// DataIO support
template<class DataIO> void dio_load_fast(DataIO& dio) {
unsigned char cacheHash;
clear();
typename DataIO::my_var_uint64_t size;
dio >> size;
dio >> load_factor;
dio >> cacheHash;
pHash = cacheHash ? NULL : (size_t*)(hash_cache_disabled);
if (0 == size.t)
return;
if (NULL == pHash) {
pHash = (HashTp*)malloc(sizeof(HashTp)*size.t);
if (NULL == pHash)
throw std::bad_alloc();
}
m_nl.reserve(0, size.t);
size_t i = 0, n = size.t;
try {
NodeLayout nl = m_nl;
for (; i < n; ++i) {
new(&nl.data(i))Elem();
dio >> nl.data(i);
}
if ((size_t*)(hash_cache_disabled) != pHash) {
assert(NULL != pHash);
for (size_t j = 0; j < n; ++j)
pHash[j] = he.hash(keyExtract(nl.data(i)));
}
nElem = LinkTp(size.t);
maxElem = nElem;
maxload = nElem; //LinkTp(load_factor * nBucket);
rehash(maxElem / load_factor);
}
catch (...) {
nElem = i; // valid elem count
clear();
throw;
}
}
template<class DataIO> void dio_save_fast(DataIO& dio) const {
dio << typename DataIO::my_var_uint64_t(nElem);
dio << load_factor;
dio << (unsigned char)(intptr_t(pHash) != hash_cache_disabled);
const NodeLayout nl = m_nl;
for (size_t i = 0, n = nElem; i < n; ++i)
dio << nl.data(i);
}
// compatible format
template<class DataIO> void dio_load(DataIO& dio) {
typename DataIO::my_var_uint64_t Size;
dio >> Size;
this->clear();
this->reserve(Size.t);
Elem e;
for (size_t i = 0, n = Size.t; i < n; ++i) {
this->insert_i(e);
}
}
template<class DataIO> void dio_save(DataIO& dio) const {
dio << typename DataIO::my_var_uint64_t(this->size());
if (this->freelist_size) {
for (size_t i = 0, n = this->end_i(); i < n; ++i)
if (this->is_deleted())
dio << m_nl.data(i);
} else {
for (size_t i = 0, n = this->end_i(); i < n; ++i)
dio << m_nl.data(i);
}
}
template<class DataIO>
friend void DataIO_loadObject(DataIO& dio, gold_hash_tab& x) {
x.dio_load(dio);
}
template<class DataIO>
friend void DataIO_saveObject(DataIO& dio, const gold_hash_tab& x) {
x.dio_save(dio);
}
};
template<class First>
struct nark_get_first {
template<class T>
const First& operator()(const T& x) const { return x.first; }
};
template< class Key
, class Value
, class HashFunc = DEFAULT_HASH_FUNC<Key>
, class KeyEqual = std::equal_to<Key>
, class NodeLayout = node_layout<std::pair<Key, Value>, unsigned>
, class HashTp = size_t
>
class gold_hash_map : public
gold_hash_tab<Key, std::pair<Key, Value>
, hash_and_equal<Key, HashFunc, KeyEqual>, nark_get_first<Key>
, NodeLayout
, HashTp
>
{
typedef
gold_hash_tab<Key, std::pair<Key, Value>
, hash_and_equal<Key, HashFunc, KeyEqual>, nark_get_first<Key>
, NodeLayout
, HashTp
>
super;
public:
// typedef std::pair<const Key, Value> value_type;
typedef Value mapped_type;
using super::insert;
using super::insert_i;
std::pair<size_t, bool>
insert_i(const Key& key, const Value& val = Value()) {
return this->insert_i(std::make_pair(key, val));
}
Value& operator[](const Key& key) {
// typedef boost::reference_wrapper<const Key> key_cref;
typedef std::pair<key_cref , Value> key_by_ref;
typedef std::pair<const Key, Value> key_by_val;
std::pair<size_t, bool> ib =
this->insert_i(key_by_val( key , Value()));
return this->m_nl.data(ib.first).second;
}
Value& val(size_t idx) {
assert(idx < this->nElem);
assert(this->delmark != this->m_nl.link(idx));
return this->m_nl.data(idx).second;
}
const Value& val(size_t idx) const {
assert(idx < this->nElem);
assert(this->delmark != this->m_nl.link(idx));
return this->m_nl.data(idx).second;
}
const Value& end_val(size_t idxEnd) const {
assert(this->nElem >= 1);
assert(idxEnd >= 1);
assert(idxEnd <= this->nElem);
assert(this->delmark != this->m_nl.link(this->nElem - idxEnd));
return this->m_nl.data(this->nElem - idxEnd).second;
}
Value& end_val(size_t idxEnd) {
assert(this->nElem >= 1);
assert(idxEnd >= 1);
assert(idxEnd <= this->nElem);
assert(this->delmark != this->m_nl.link(this->nElem - idxEnd));
return this->m_nl.data(this->nElem - idxEnd).second;
}
// DataIO support
template<class DataIO>
friend void DataIO_loadObject(DataIO& dio, gold_hash_map& x) {
x.dio_load(dio);
}
template<class DataIO>
friend void DataIO_saveObject(DataIO& dio, const gold_hash_map& x) {
x.dio_save(dio);
}
};
template< class Key
, class Value
, class HashFunc = DEFAULT_HASH_FUNC<Key>
, class KeyEqual = std::equal_to<Key>
, class Deleter = HSM_DefaultDeleter
>
class gold_hash_map_p : public nark_ptr_hash_map
< gold_hash_map<Key, Value*, HashFunc, KeyEqual>, Value*, Deleter>
{};
///////////////////////////////////////////////////////////////////////////////
template< class Key
, class HashFunc = DEFAULT_HASH_FUNC<Key>
, class KeyEqual = std::equal_to<Key>
, class NodeLayout = node_layout<Key, unsigned>
, class HashTp = size_t
>
class gold_hash_set : public
gold_hash_tab<Key, Key
, hash_and_equal<Key, HashFunc, KeyEqual>, nark_identity<Key>
, NodeLayout, HashTp
>
{
public:
// DataIO support
template<class DataIO>
friend void DataIO_loadObject(DataIO& dio, gold_hash_set& x) {
x.dio_load(dio);
}
template<class DataIO>
friend void DataIO_saveObject(DataIO& dio, const gold_hash_set& x) {
x.dio_save(dio);
}
};
} // namespace nark
namespace std { // for std::swap
template< class Key
, class Elem
, class HashEqual
, class KeyExtractor
, class NodeLayout
, class HashTp
>
void
swap(nark::gold_hash_tab<Key, Elem, HashEqual, KeyExtractor, NodeLayout, HashTp>& x,
nark::gold_hash_tab<Key, Elem, HashEqual, KeyExtractor, NodeLayout, HashTp>& y)
{
x.swap(y);
}
template< class Key
, class Value
, class HashFunc
, class KeyEqual
, class NodeLayout
, class HashTp
>
void
swap(nark::gold_hash_map<Key, Value, HashFunc, KeyEqual, NodeLayout, HashTp>& x,
nark::gold_hash_map<Key, Value, HashFunc, KeyEqual, NodeLayout, HashTp>& y)
{
x.swap(y);
}
template< class Key
, class HashFunc
, class KeyEqual
, class NodeLayout
, class HashTp
>
void
swap(nark::gold_hash_set<Key, HashFunc, KeyEqual, NodeLayout, HashTp>& x,
nark::gold_hash_set<Key, HashFunc, KeyEqual, NodeLayout, HashTp>& y)
{
x.swap(y);
}
} // namespace std
#endif // __nark_gold_hash_tab__
| 27.842105 | 101 | 0.640081 | ktprime |
021f205bbd10b7ed975697de2501f90ec14fee0f | 7,038 | hpp | C++ | src/Luddite/Graphics/ShaderAttributeList.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | 1 | 2021-06-03T05:46:46.000Z | 2021-06-03T05:46:46.000Z | src/Luddite/Graphics/ShaderAttributeList.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | src/Luddite/Graphics/ShaderAttributeList.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Luddite/Core/pch.hpp"
#include "Luddite/Core/Core.hpp"
#include "Luddite/Core/AssetTypes/Texture.hpp"
#include "Luddite/Graphics/Color.hpp"
#include "Luddite/Graphics/DiligentInclude.hpp"
// #include "Luddite/Core/pch.hpp"
// #include "Luddite/Platform/DiligentPlatform.hpp"
// #include "Graphics/GraphicsEngine/interface/RenderDevice.h"
// #include "Graphics/GraphicsEngine/interface/DeviceContext.h"
// #include "Graphics/GraphicsEngine/interface/SwapChain.h"
// #include "Common/interface/RefCntAutoPtr.hpp"
// // #include "Luddite/Core/Core.hpp"
namespace Luddite
{
struct LUDDITE_API ShaderBufferData
{
std::string Name{};
std::vector<Handle<Texture> > TexturesVertexShader;
std::vector<Handle<Texture> > TexturesPixelShader;
// std::unordered_map<std::string, Texture::Handle> texture_map;
// Handle<Texture> GetTexture(const std::string& id) {return texture_map[id];}
// void SetTexture(const std::string& id, const Texture::Handle handle) {texture_map[id] = handle;}
char* Data = nullptr;
std::size_t Size = 0;
~ShaderBufferData()
{
if (Data)
free(Data);
}
ShaderBufferData& operator=(const ShaderBufferData& other)
{
if (this == &other)
return *this;
if (Size != other.Size)
{
if (Data)
free(Data);
Size = other.Size;
Data = (char*)malloc(Size);
}
memcpy(Data, other.Data, Size);
Name = other.Name;
TexturesVertexShader = other.TexturesVertexShader;
TexturesPixelShader = other.TexturesPixelShader;
return *this;
}
};
//enum, name, typename, size
#define VALUE_TYPES_DECLARE \
VALUE_TYPE_DECLARATION(Float, float, 0.f) \
VALUE_TYPE_DECLARATION(Int, int32_t, 0) \
VALUE_TYPE_DECLARATION(UInt, uint32_t, 0) \
VALUE_TYPE_DECLARATION(Vec2, glm::vec2, glm::vec2{0}) \
VALUE_TYPE_DECLARATION(IVec2, glm::ivec2, glm::ivec2{0}) \
VALUE_TYPE_DECLARATION(UVec2, glm::uvec2, glm::uvec2{0}) \
VALUE_TYPE_DECLARATION(Vec3, glm::vec3, glm::vec3{0}) \
VALUE_TYPE_DECLARATION(IVec3, glm::ivec3, glm::ivec3{0}) \
VALUE_TYPE_DECLARATION(UVec3, glm::uvec3, glm::uvec3{0}) \
VALUE_TYPE_DECLARATION(Vec4, glm::vec4, glm::vec4{0}) \
VALUE_TYPE_DECLARATION(Color, glm::vec4, glm::vec4{1}) \
VALUE_TYPE_DECLARATION(IVec4, glm::ivec4, glm::ivec4{0}) \
VALUE_TYPE_DECLARATION(UVec4, glm::uvec4, glm::uvec4{0}) \
VALUE_TYPE_DECLARATION(Mat3, glm::mat3, glm::identity<glm::mat3>()) \
VALUE_TYPE_DECLARATION(Mat4, glm::mat4, glm::identity<glm::mat3>())
struct LUDDITE_API ShaderBufferDescription
{
static const char* ValueTypeNames[];
enum class ValueType : uint32_t
{
#define VALUE_TYPE_DECLARATION(Name, Type, Default) Name,
VALUE_TYPES_DECLARE
#undef VALUE_TYPE_DECLARATION
SIZE,
NONE
};
static constexpr uint32_t ValueTypeSizes[] =
{
#define VALUE_TYPE_DECLARATION(Name, Type, Default) sizeof(Type),
VALUE_TYPES_DECLARE
#undef VALUE_TYPE_DECLARATION
0,
0
};
struct BufferValue
{
ValueType type;
std::size_t offset;
};
std::map<std::string, BufferValue> Attributes;
std::vector<std::string> TexturesVertexShader;
std::vector<std::string> TexturesPixelShader;
inline void AddTextureVertexShader(const std::string& name) {TexturesVertexShader.emplace_back(name);}
inline void AddTexturePixelShader(const std::string& name) {TexturesPixelShader.emplace_back(name);}
void SetTextureVertexShader(ShaderBufferData& data, const std::string& name, Handle<Texture> texture);
void SetTexturePixelShader(ShaderBufferData& data, const std::string& name, Handle<Texture> texture);
Handle<Texture> GetTextureVertexShader(ShaderBufferData& data, const std::string& name) const;
Handle<Texture> GetTexturePixelShader(ShaderBufferData& data, const std::string& name) const;
#define VALUE_TYPE_DECLARATION(Name, Type, Default) inline void Add ## Name(const std::string& name) \
{ \
/*Perform byte alignment*/ \
constexpr int align = 16; \
if (m_Size / align != ((m_Size + sizeof(Type) - 1) / align) && m_Size % align != 0) \
{m_Size = ((m_Size / align) + 1) * align;} \
Attributes.insert({name, {ValueType::Name, m_Size}}); \
m_Size += sizeof(Type); \
}
VALUE_TYPES_DECLARE
#undef VALUE_TYPE_DECLARATION
inline void Add(const std::string& name, const ValueType& type)
{
//Perform byte alignment
constexpr int align = 16;
if (m_Size / align != ((m_Size + ValueTypeSizes[static_cast<uint32_t>(type)] - 1) / align) && m_Size % align != 0)
m_Size = ((m_Size / align) + 1) * align;
Attributes.insert({name, {type, m_Size}});
m_Size += ValueTypeSizes[static_cast<uint32_t>(type)];
}
ValueType GetTypenameFromString(const std::string& type) const;
#define VALUE_TYPE_DECLARATION(Name, Type, Default) inline void Set ## Name(ShaderBufferData & data, const std::string& name, Type value) const \
{ \
std::size_t offset = Attributes.find(name)->second.offset; \
Type value_ = value; \
memcpy(data.Data + offset, &value_, sizeof(Type)); \
}
VALUE_TYPES_DECLARE
#undef VALUE_TYPE_DECLARATION
#define VALUE_TYPE_DECLARATION(Name, Type, Default) inline Type Get ## Name(ShaderBufferData & data, const std::string& name) const \
{ \
std::size_t offset = Attributes.find(name)->second.offset; \
Type ret; \
memcpy(&ret, data.Data + offset, sizeof(Type)); \
return ret; \
}
VALUE_TYPES_DECLARE
#undef VALUE_TYPE_DECLARATION
inline std::size_t GetSize() const
{
return m_Size;
}
void MapBuffer(ShaderBufferData & data, Diligent::RefCntAutoPtr<Diligent::IBuffer> buffer) const;
void MapTextures(ShaderBufferData& data, Diligent::RefCntAutoPtr<Diligent::IShaderResourceBinding> srb) const;
void SetDefaultAttribs(ShaderBufferData& data) const;
void SetAttribsFromYaml(ShaderBufferData& data, const YAML::Node& yaml) const;
ShaderBufferData CreateData(const std::string& name) const;
private:
std::size_t m_Size = 0;
};
}
| 42.143713 | 153 | 0.603296 | Aquaticholic |
0220d2bb3788965160cc9bdbaf6163ae99a03f91 | 2,423 | cc | C++ | engine/runtime/gpu/src/resource.cc | aejsmith/orion | 0e172e1829c0f4522a4af1ddb4afcd2ed046ca49 | [
"ISC"
] | 5 | 2015-08-02T18:20:19.000Z | 2020-03-10T10:39:51.000Z | engine/runtime/gpu/src/resource.cc | aejsmith/orion | 0e172e1829c0f4522a4af1ddb4afcd2ed046ca49 | [
"ISC"
] | 1 | 2018-04-25T15:12:35.000Z | 2018-04-25T15:12:35.000Z | engine/runtime/gpu/src/resource.cc | aejsmith/orion | 0e172e1829c0f4522a4af1ddb4afcd2ed046ca49 | [
"ISC"
] | null | null | null | /*
* Copyright (C) 2016 Alex Smith
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @file
* @brief GPU resource definitions.
*/
#include "gpu/buffer.h"
#include "gpu/resource.h"
#include "gpu/texture.h"
/** Create a GPU resource set.
* @param layout Layout to use for the set. */
GPUResourceSet::GPUResourceSet(GPUResourceSetLayout *layout) :
m_layout (layout)
{
const GPUResourceSetLayoutDesc &desc = m_layout->desc();
m_slots.reserve(desc.slots.size());
for (const GPUResourceSetLayoutDesc::Slot &slotDesc : desc.slots)
m_slots.emplace_back(slotDesc);
}
/** Destroy the resource set. */
GPUResourceSet::~GPUResourceSet() {}
/** Bind a uniform buffer.
* @param index Slot index to bind to (must be a uniform buffer slot).
* @param buffer Buffer to bind. */
void GPUResourceSet::bindUniformBuffer(size_t index, GPUBuffer *buffer) {
check(index < m_slots.size());
Slot &slot = m_slots[index];
check(slot.desc.type == GPUResourceType::kUniformBuffer);
if (slot.object != buffer) {
slot.object = buffer;
slot.sampler = nullptr;
updateSlot(index);
}
}
/** Bind a texture.
* @param index Slot index to bind to (must be a texture slot).
* @param texture Texture to bind.
* @param sampler Sampler state to use. */
void GPUResourceSet::bindTexture(size_t index, GPUTexture *texture, GPUSamplerState *sampler) {
check(index < m_slots.size());
Slot &slot = m_slots[index];
check(slot.desc.type == GPUResourceType::kTexture);
if (slot.object != texture || slot.sampler != sampler) {
slot.object = texture;
slot.sampler = sampler;
updateSlot(index);
}
}
| 33.652778 | 95 | 0.685927 | aejsmith |
0226d207c2cff8ddfb0f5797b924142535f9ce20 | 6,045 | cc | C++ | src/engine/systems/collider_system.cc | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | 1 | 2019-05-28T16:39:19.000Z | 2019-05-28T16:39:19.000Z | src/engine/systems/collider_system.cc | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | null | null | null | src/engine/systems/collider_system.cc | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | 1 | 2019-05-28T16:39:06.000Z | 2019-05-28T16:39:06.000Z | #include "collider_system.h"
#include "rigid_body_system.h"
#include "transform_system.h"
#include "utils/mesh_decimator.h"
#include <platform/scene.h>
namespace lambda
{
namespace components
{
namespace ColliderSystem
{
ColliderComponent addComponent(const entity::Entity& entity, scene::Scene& scene)
{
if (!TransformSystem::hasComponent(entity, scene))
TransformSystem::addComponent(entity, scene);
scene.collider.add(entity);
/** Init start */
auto& data = scene.collider.get(entity);
RigidBodySystem::getPhysicsWorld(scene)->createCollisionBody(entity);
return ColliderComponent(entity, scene);
}
ColliderComponent getComponent(const entity::Entity& entity, scene::Scene& scene)
{
return ColliderComponent(entity, scene);
}
bool hasComponent(const entity::Entity& entity, scene::Scene& scene)
{
return scene.collider.has(entity);
}
void removeComponent(const entity::Entity& entity, scene::Scene& scene)
{
scene.collider.remove(entity);
}
void collectGarbage(scene::Scene& scene)
{
if (!scene.collider.marked_for_delete.empty())
{
for (entity::Entity entity : scene.collider.marked_for_delete)
{
const auto& it = scene.collider.entity_to_data.find(entity);
if (it != scene.collider.entity_to_data.end())
{
auto& data = scene.collider.data.at(it->second);
uint32_t idx = it->second;
scene.collider.unused_data_entries.push(idx);
scene.collider.data_to_entity.erase(idx);
scene.collider.entity_to_data.erase(entity);
scene.collider.data[idx].valid = false;
if (RigidBodySystem::hasComponent(entity, scene))
RigidBodySystem::removeComponent(entity, scene);
RigidBodySystem::getPhysicsWorld(scene)->destroyCollisionBody(entity);
}
}
scene.collider.marked_for_delete.clear();
}
}
void deinitialize(scene::Scene& scene)
{
Vector<entity::Entity> entities;
for (const auto& it : scene.collider.entity_to_data)
entities.push_back(it.first);
for (const auto& entity : entities)
removeComponent(entity, scene);
collectGarbage(scene);
}
void makeBox(const entity::Entity& entity, scene::Scene& scene)
{
scene.rigid_body.physics_world->getCollisionBody(entity).makeBoxCollider();
}
void makeSphere(const entity::Entity& entity, scene::Scene& scene)
{
scene.rigid_body.physics_world->getCollisionBody(entity).makeSphereCollider();
}
void makeCapsule(const entity::Entity& entity, scene::Scene& scene)
{
scene.rigid_body.physics_world->getCollisionBody(entity).makeCapsuleCollider();
}
void makeMeshCollider(const entity::Entity& entity, asset::VioletMeshHandle mesh, const uint32_t& sub_mesh_id, scene::Scene& scene)
{
scene.rigid_body.physics_world->getCollisionBody(entity).makeMeshCollider(mesh, sub_mesh_id);
}
uint16_t getLayers(const entity::Entity& entity, scene::Scene& scene)
{
return scene.rigid_body.physics_world->getCollisionBody(entity).getLayers();
}
void setLayers(const entity::Entity& entity, const uint16_t& layers, scene::Scene& scene)
{
scene.rigid_body.physics_world->getCollisionBody(entity).setLayers(layers);
}
}
// The system data.
namespace ColliderSystem
{
Data& SystemData::add(const entity::Entity& entity)
{
uint32_t idx = 0ul;
if (!unused_data_entries.empty())
{
idx = unused_data_entries.front();
unused_data_entries.pop();
data[idx] = Data(entity);
}
else
{
idx = (uint32_t)data.size();
data.push_back(Data(entity));
data_to_entity[idx] = entity;
}
data_to_entity[idx] = entity;
entity_to_data[entity] = idx;
return data[idx];
}
Data& SystemData::get(const entity::Entity& entity)
{
auto it = entity_to_data.find(entity);
LMB_ASSERT(it != entity_to_data.end(), "COLLIDER: %llu does not have a component", entity);
LMB_ASSERT(data[it->second].valid, "COLLIDER: %llu's data was not valid", entity);
return data[it->second];
}
void SystemData::remove(const entity::Entity& entity)
{
marked_for_delete.insert(entity);
}
bool SystemData::has(const entity::Entity& entity)
{
return entity_to_data.find(entity) != entity_to_data.end();
}
}
namespace ColliderSystem
{
Data::Data(const Data& other)
{
type = other.type;
is_trigger = other.is_trigger;
entity = other.entity;
valid = other.valid;
}
Data& Data::operator=(const Data& other)
{
type = other.type;
is_trigger = other.is_trigger;
entity = other.entity;
valid = other.valid;
return *this;
}
}
ColliderComponent::ColliderComponent(const entity::Entity& entity, scene::Scene& scene) :
IComponent(entity), scene_(&scene)
{
}
ColliderComponent::ColliderComponent(const ColliderComponent& other) :
IComponent(other.entity_), scene_(other.scene_)
{
}
ColliderComponent::ColliderComponent() :
IComponent(entity::Entity()), scene_(nullptr)
{
}
void ColliderComponent::makeBoxCollider()
{
ColliderSystem::makeBox(entity_, *scene_);
}
void ColliderComponent::makeSphereCollider()
{
ColliderSystem::makeSphere(entity_, *scene_);
}
void ColliderComponent::makeCapsuleCollider()
{
ColliderSystem::makeCapsule(entity_, *scene_);
}
void ColliderComponent::makeMeshCollider(asset::VioletMeshHandle mesh, const uint32_t& sub_mesh_id)
{
ColliderSystem::makeMeshCollider(entity_, mesh, sub_mesh_id, *scene_);
}
uint16_t ColliderComponent::getLayers() const
{
return ColliderSystem::getLayers(entity_, *scene_);
}
void ColliderComponent::setLayers(const uint16_t& layers)
{
ColliderSystem::setLayers(entity_, layers, *scene_);
}
}
} | 27.729358 | 135 | 0.66617 | hvonck |
02280e2bdcf0d36c1832ab5c74c6fbdd1c45cd52 | 2,421 | cpp | C++ | Sandbox/src/Player.cpp | Super-Shadow/RiseFlappyRocketGame | 7ed3191823af77cd246940f6766f453c12dab601 | [
"Apache-2.0"
] | null | null | null | Sandbox/src/Player.cpp | Super-Shadow/RiseFlappyRocketGame | 7ed3191823af77cd246940f6766f453c12dab601 | [
"Apache-2.0"
] | null | null | null | Sandbox/src/Player.cpp | Super-Shadow/RiseFlappyRocketGame | 7ed3191823af77cd246940f6766f453c12dab601 | [
"Apache-2.0"
] | null | null | null | #include "Player.h"
#include "imgui/imgui.h"
#include <glm/gtx/transform.hpp>
using namespace Rise;
Player::Player()
{
m_SmokeParticle.Position = {0.f, 0.f};
m_SmokeParticle.Velocity = {-2.f, 0.f};
m_SmokeParticle.VelocityVariation = { 4.f, 2.f};
m_SmokeParticle.SizeBegin = .35f;
m_SmokeParticle.SizeEnd = 0.f;
m_SmokeParticle.SizeVariation = .15f;
m_SmokeParticle.ColourBegin = {.8f, .8f, .8f, 1.f};
m_SmokeParticle.ColourEnd = {.6f, .6f, .6f, 1.f};
m_SmokeParticle.LifeTime = 4.f;
m_EngineParticle.Position = { 0.f, 0.f };
m_EngineParticle.Velocity = { -2.f, 0.f };
m_EngineParticle.VelocityVariation = { 3.f, 1.f };
m_EngineParticle.SizeBegin = .5f;
m_EngineParticle.SizeEnd = 0.f;
m_EngineParticle.SizeVariation = .3f;
m_EngineParticle.ColourBegin = { 254 / 255.f, 109 / 255.f, 41 / 255.f, 1.f };
m_EngineParticle.ColourEnd = { 254 / 255.f, 212 / 255.f, 123 / 255.f, 1.f };
m_EngineParticle.LifeTime = 1.f;
}
void Player::LoadAssets()
{
m_ShipTexture = Texture2D::Create("assets/textures/ship.png");
}
void Player::OnUpdate(const TimeStep timeStep)
{
m_Time += timeStep;
if (Input::IsKeyPressed(RS_KEY_SPACE))
{
m_Velocity.y += m_EnginePower;
if (m_Velocity.y < 0.f)
m_Velocity.y += m_EnginePower * 2.f;
constexpr glm::vec2 emissionPoint = {0.f, -0.6f};
const auto rotation = glm::radians(GetRotation());
const glm::vec4 rotated = glm::rotate(glm::mat4(1.f), rotation, {.0f, .0f, 1.f}) * glm::vec4(emissionPoint, 0.f, 1.f);
m_EngineParticle.Position = m_Position + glm::vec2{rotated.x, rotated.y};
m_EngineParticle.Velocity.y = -m_Velocity.y * .2f - .2f;
m_ParticleSystem.Emit(m_EngineParticle);
}
else
{
m_Velocity.y -= m_Gravity;
}
m_Velocity.y = glm::clamp(m_Velocity.y, -20.f, 20.f);
m_Position += m_Velocity * static_cast<float>(timeStep);
if(m_Time > m_SmokeNextEmitTime)
{
m_SmokeParticle.Position = m_Position;
m_ParticleSystem.Emit(m_SmokeParticle);
m_SmokeNextEmitTime += m_SmokeEmitInterval;
}
m_ParticleSystem.OnUpdate(timeStep);
}
void Player::OnRender()
{
m_ParticleSystem.OnRender();
Renderer2D::DrawQuad({m_Position.x, m_Position.y, .5f}, glm::radians(GetRotation()), { .9f, 1.3f }, m_ShipTexture);
}
void Player::OnImGuiRender()
{
ImGui::DragFloat("Engine Power", &m_EnginePower, 0.1f);
ImGui::DragFloat("Gravity", &m_Gravity, 0.1f);
}
void Player::Reset()
{
m_Position = { -10.f, 0.f };
m_Velocity = { 5.f, 0.f };
}
| 26.604396 | 120 | 0.693928 | Super-Shadow |
022b26afd6d361726223c70e6c3ffbcb736c160d | 349 | cpp | C++ | CF/1611B.cpp | jawahiir98/CP | a32566554949cd12a62151f90ac3b82b67275cac | [
"MIT"
] | null | null | null | CF/1611B.cpp | jawahiir98/CP | a32566554949cd12a62151f90ac3b82b67275cac | [
"MIT"
] | null | null | null | CF/1611B.cpp | jawahiir98/CP | a32566554949cd12a62151f90ac3b82b67275cac | [
"MIT"
] | null | null | null | /*
/\ In The Name Of Allah /\
Author : Jawahiir Nabhan
*/
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
const char nl = '\n';
int main()
{
int T; cin>> T;
while(T--)
{
int a,b; cin>> a >> b;
if(a > b) swap(a, b);
cout<< min(min(a, b), (a + b)/4) << nl;
}
}
| 16.619048 | 47 | 0.495702 | jawahiir98 |
022c8391657a0ed821ec91198f3e3811e7e6e97e | 6,398 | cpp | C++ | DT3Core/System/Globals.cpp | 9heart/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 3 | 2018-10-05T15:03:27.000Z | 2019-03-19T11:01:56.000Z | DT3Core/System/Globals.cpp | pakoito/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Core/System/Globals.cpp | pakoito/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 3 | 2016-01-14T07:51:52.000Z | 2021-08-21T08:02:51.000Z | //==============================================================================
///
/// File: Globals.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/System/Globals.hpp"
#include "DT3Core/System/StaticInitializer.hpp"
#include "DT3Core/Types/Utility/MoreStrings.hpp"
#include "DT3Core/Types/Utility/Error.hpp"
#include "DT3Core/Types/Utility/ConsoleStream.hpp"
#include DT3_HAL_INCLUDE_PATH
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
//==============================================================================
std::mutex Globals::_globals_lock;
std::map<StringCopier, Globals::GlobalsEntry> Globals::_globals;
//==============================================================================
//==============================================================================
GLOBAL_STATIC_INITIALIZATION(0,Globals::initialize())
GLOBAL_STATIC_DESTRUCTION(0,Globals::destroy())
//==============================================================================
//==============================================================================
void Globals::initialize (void)
{
load();
}
void Globals::destroy (void)
{
save();
}
//==============================================================================
//==============================================================================
DTboolean Globals::has_global (const std::string &name_with_case)
{
std::string name = MoreStrings::lowercase(name_with_case);
std::unique_lock<std::mutex> lock(_globals_lock);
if (_globals.find(name) == _globals.end())
return false;
else
return true;
}
//==============================================================================
//==============================================================================
std::string Globals::global (const std::string &name_with_case)
{
// Convert name to lowercase
std::string name = MoreStrings::lowercase(name_with_case);
std::unique_lock<std::mutex> lock(_globals_lock);
auto i = _globals.find(name);
if (i != _globals.end())
return _globals[name].value;
else
return "";
}
DTboolean Globals::global (const std::string &name_with_case, std::string &value)
{
// Convert name to lowercase
std::string name = MoreStrings::lowercase(name_with_case);
std::unique_lock<std::mutex> lock(_globals_lock);
auto i = _globals.find(name);
if (i != _globals.end()) {
value = _globals[name].value;
return true;
} else {
value = "";
return false;
}
}
//==============================================================================
//==============================================================================
void Globals::set_global (const std::string &name_with_case, const std::string &value, const DTint lifetime)
{
// Convert name to lowercase
std::string name = MoreStrings::lowercase(name_with_case);
std::unique_lock<std::mutex> lock(_globals_lock);
auto i = _globals.find(name);
if ((i != _globals.end() && i->second.lifetime != READ_ONLY) || (i == _globals.end())) {
GlobalsEntry entry;
entry.lifetime = lifetime;
entry.name = name;
entry.value = value;
_globals[name] = entry;
}
}
//==============================================================================
//==============================================================================
void Globals::set_global_default (const std::string &name_with_case, const std::string &value, const DTint lifetime)
{
// Convert name to lowercase
std::string name = MoreStrings::lowercase(name_with_case);
std::unique_lock<std::mutex> lock(_globals_lock);
auto i = _globals.find(name);
if (i == _globals.end()) {
GlobalsEntry entry;
entry.lifetime = lifetime;
entry.name = name;
entry.value = value;
_globals[name] = entry;
}
}
//==============================================================================
//==============================================================================
std::string Globals::substitute_global (const std::string &s)
{
std::string value;
DTboolean success = substitute_global (s, value);
if (success) return value;
else return s;
}
DTboolean Globals::substitute_global (const std::string &s, std::string &value)
{
value = s;
for (DTuint i = 0; i < 100; ++i) {
std::string::size_type first = value.find_last_of('{');
std::string::size_type last = value.find_first_of('}',first);
// Check to see if a replacement has to be made
if (first == std::string::npos || last == std::string::npos || last <= first)
return true;
std::string key = MoreStrings::lowercase(value.substr(first + 1, last - first - 1));
std::string replacement;
// if global not found then return fail
if (!global(key,replacement))
return false;
// Do replacement
value.replace(first, last-first+1, replacement);
}
WARNINGMSG("Exceeded maximum iterations. Infinite loop?");
return false;
}
//==============================================================================
//==============================================================================
void Globals::load (void)
{
std::unique_lock<std::mutex> lock(_globals_lock);
auto globals = HAL::load_globals();
// Note: This doesn't overwrite existing elements so we have to manually copy below
//_globals.insert(globals.begin(), globals.end());
for(auto& i : globals)
_globals[i.first] = i.second;
}
void Globals::save (void)
{
std::unique_lock<std::mutex> lock(_globals_lock);
HAL::save_globals(_globals);
}
//==============================================================================
//==============================================================================
} // DT3
| 29.897196 | 116 | 0.455924 | 9heart |
0232334d11e4efc946c3ffad18c64a59c08d2b86 | 14,341 | cpp | C++ | src/asdxSkySphere.cpp | ProjectAsura/asdx11 | 67c3d4129f3e6d32e66c64ee9354d873f99d0eaf | [
"MIT"
] | null | null | null | src/asdxSkySphere.cpp | ProjectAsura/asdx11 | 67c3d4129f3e6d32e66c64ee9354d873f99d0eaf | [
"MIT"
] | null | null | null | src/asdxSkySphere.cpp | ProjectAsura/asdx11 | 67c3d4129f3e6d32e66c64ee9354d873f99d0eaf | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// File : asdxSkySphere.cpp
// Desc : Sky Sphere Module.
// Copyright(c) Project Asura. All right reserved.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <asdxSkySphere.h>
#include <asdxLogger.h>
#include <vector>
namespace {
#include "../res/shaders/Compiled/SkySphereVS.inc"
#include "../res/shaders/Compiled/SkySpherePS.inc"
#include "../res/shaders/Compiled/SkySphereFlowPS.inc"
///////////////////////////////////////////////////////////////////////////////
// CbSkySphere structure
///////////////////////////////////////////////////////////////////////////////
struct alignas(16) CbSkySphere
{
asdx::Matrix World; //!< ワールド行列.
asdx::Matrix View; //!< ビュー行列.
asdx::Matrix Proj; //!< 射影行列.
float SphereSize; //!< スカイスフィアサイズ.
float Padding[3];
};
///////////////////////////////////////////////////////////////////////////////
// CbSkySphereFlow structure
///////////////////////////////////////////////////////////////////////////////
struct alignas(16) CbSkySphereFlow
{
asdx::Vector3 WindDirection; //!< 風の方向.
float Padding0;
asdx::Vector2 Offset; //!< オフセット.
};
///////////////////////////////////////////////////////////////////////////////
// Vertex structure
///////////////////////////////////////////////////////////////////////////////
struct Vertex
{
asdx::Vector3 Position; //!< 位置座標です.
asdx::Vector2 Texcoord; //!< テクスチャ座標です.
asdx::Vector3 Normal; //!< 法線ベクトルです.
asdx::Vector3 Tangent; //!< 接線ベクトルです.
};
} // namespace
namespace asdx {
///////////////////////////////////////////////////////////////////////////////
// SkySphere class
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// コンストラクタです.
//-----------------------------------------------------------------------------
SkySphere::SkySphere()
{
ResetFlow();
}
//-----------------------------------------------------------------------------
// デストラクタです.
//-----------------------------------------------------------------------------
SkySphere::~SkySphere()
{ Term(); }
//-----------------------------------------------------------------------------
// 初期化処理を行います.
//-----------------------------------------------------------------------------
bool SkySphere::Init(ID3D11Device* pDevice, int tessellation)
{
HRESULT hr = S_OK;
// 頂点シェーダ・入力レイアウトの生成.
{
hr = pDevice->CreateVertexShader(SkySphereVS, sizeof(SkySphereVS), nullptr, m_pVS.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateVertexShader() Failed.");
return false;
}
D3D11_INPUT_ELEMENT_DESC elements[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA },
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA }
};
hr = pDevice->CreateInputLayout(elements, 4, SkySphereVS, sizeof(SkySphereVS), m_pIL.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateInputLayout() Failed.");
return false;
}
}
// ピクセルシェーダの生成.
{
hr = pDevice->CreatePixelShader(SkySpherePS, sizeof(SkySpherePS), nullptr, m_pPS.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreatePixelShader() Failed.");
return false;
}
}
// フロー用ピクセルシェーダの生成.
{
hr = pDevice->CreatePixelShader(SkySphereFlowPS, sizeof(SkySphereFlowPS), nullptr, m_pPSFlow.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreatePixelShader() Failed.");
return false;
}
}
// 定数バッファの生成.
{
D3D11_BUFFER_DESC desc = {};
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.ByteWidth = sizeof(CbSkySphere);
desc.Usage = D3D11_USAGE_DEFAULT;
hr = pDevice->CreateBuffer(&desc, nullptr, m_pCB.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateBuffer() Failed.");
return false;
}
}
// 定数バッファの生成.
{
D3D11_BUFFER_DESC desc = {};
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.ByteWidth = sizeof(CbSkySphereFlow);
desc.Usage = D3D11_USAGE_DEFAULT;
hr = pDevice->CreateBuffer(&desc, nullptr, m_pCBFlow.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateBuffer() Failed.");
return false;
}
}
// 頂点バッファとインデックスバッファの生成.
{
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
uint32_t verticalSegments = tessellation;
uint32_t horizontalSegments = tessellation * 2;
float radius = 1.0f;
// Create rings of vertices at progressively higher latitudes.
for (size_t i = 0; i <= verticalSegments; i++)
{
float v = 1 - (float)i / verticalSegments;
float theta = (i * F_PI / verticalSegments) - F_PIDIV2;
auto st = sin(theta);
auto ct = cos(theta);
// Create a single ring of vertices at this latitude.
for (size_t j = 0; j <= horizontalSegments; j++)
{
float u = (float)j / horizontalSegments;
float phi = j * F_2PI / horizontalSegments;
auto sp = sin(phi);
auto cp = cos(phi);
auto normal = Vector3(sp * ct, st, cp * ct);
auto uv = Vector2(u, v);
auto l = normal.x * normal.x + normal.z * normal.z;
Vector3 tangent;
tangent.x = st * cp;
tangent.y = st * sp;
tangent.z = ct;
Vertex vert;
vert.Position = normal * radius;
vert.Texcoord = uv;
vert.Normal = normal;
vert.Tangent = tangent;
vertices.push_back(vert);
}
}
// Fill the index buffer with triangles joining each pair of latitude rings.
uint32_t stride = horizontalSegments + 1;
for (auto i = 0u; i < verticalSegments; i++)
{
for (auto j = 0u; j <= horizontalSegments; j++)
{
auto nextI = i + 1;
auto nextJ = (j + 1) % stride;
indices.push_back(i * stride + j);
indices.push_back(nextI * stride + j);
indices.push_back(i * stride + nextJ);
indices.push_back(i * stride + nextJ);
indices.push_back(nextI * stride + j);
indices.push_back(nextI * stride + nextJ);
}
}
// 頂点バッファの生成.
{
auto vertexCount = uint32_t(vertices.size());
D3D11_BUFFER_DESC desc = {};
desc.Usage = D3D11_USAGE_DEFAULT;
desc.ByteWidth = sizeof(Vertex) * vertexCount;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA res = {};
res.pSysMem = &vertices[0];
hr = pDevice->CreateBuffer(&desc, &res, m_pVB.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateBuffer() Failed.");
return false;
}
}
// インデックスバッファの生成.
{
m_IndexCount = uint32_t(indices.size());
D3D11_BUFFER_DESC desc = {};
desc.Usage = D3D11_USAGE_DEFAULT;
desc.ByteWidth = sizeof(uint32_t) * m_IndexCount;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
D3D11_SUBRESOURCE_DATA res = {};
res.pSysMem = &indices[0];
hr = pDevice->CreateBuffer(&desc, &res, m_pIB.GetAddress());
if (FAILED(hr))
{
ELOG("Error : ID3D11Device::CreateBuffer() Failed.");
return false;
}
}
}
return true;
}
//-----------------------------------------------------------------------------
// 終了処理を行います.
//-----------------------------------------------------------------------------
void SkySphere::Term()
{
m_pVB.Reset();
m_pIB.Reset();
m_pCB.Reset();
m_pIL.Reset();
m_pVS.Reset();
m_pPS.Reset();
m_pPSFlow.Reset();
m_pCBFlow.Reset();
}
//-----------------------------------------------------------------------------
// 描画処理を行います.
//-----------------------------------------------------------------------------
void SkySphere::Draw
(
ID3D11DeviceContext* pContext,
ID3D11ShaderResourceView* pSRV,
ID3D11SamplerState* pSmp,
float sphereSize,
const Vector3& cameraPos,
const Matrix& view,
const Matrix& proj
)
{
auto stride = uint32_t(sizeof(Vertex));
auto offset = 0u;
pContext->VSSetShader(m_pVS.GetPtr(), nullptr, 0);
pContext->PSSetShader(m_pPS.GetPtr(), nullptr, 0);
pContext->GSSetShader(nullptr, nullptr, 0);
pContext->HSSetShader(nullptr, nullptr, 0);
pContext->DSSetShader(nullptr, nullptr, 0);
auto pCB = m_pCB.GetPtr();
{
CbSkySphere buf = {};
buf.World = Matrix::CreateTranslation(cameraPos);
buf.View = view;
buf.Proj = proj;
buf.SphereSize = sphereSize;
pContext->UpdateSubresource(pCB, 0, nullptr, &buf, 0, 0);
}
pContext->VSSetConstantBuffers(0, 1, &pCB);
pContext->PSSetShaderResources(0, 1, &pSRV);
pContext->PSSetSamplers(0, 1, &pSmp);
pContext->IASetInputLayout(m_pIL.GetPtr());
pContext->IASetIndexBuffer(m_pIB.GetPtr(), DXGI_FORMAT_R32_UINT, 0);
pContext->IASetVertexBuffers(0, 1, m_pVB.GetAddress(), &stride, &offset);
pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
pContext->DrawIndexed(m_IndexCount, 0, 0);
ID3D11ShaderResourceView* pNullSRV[1] = { nullptr };
ID3D11SamplerState* pNullSmp[1] = { nullptr };
pContext->PSSetShaderResources(0, 1, pNullSRV);
pContext->PSSetSamplers(0, 1, pNullSmp);
pContext->VSSetShader(nullptr, nullptr, 0);
pContext->PSSetShader(nullptr, nullptr, 0);
}
//-----------------------------------------------------------------------------
// 描画処理を行います.
//-----------------------------------------------------------------------------
void SkySphere::DrawFlow
(
ID3D11DeviceContext* pContext,
ID3D11ShaderResourceView* pSRV,
ID3D11SamplerState* pSmp,
float sphereSize,
const Vector3& cameraPos,
const Matrix& view,
const Matrix& proj,
const Vector3& flowDir,
float flowStep
)
{
auto stride = uint32_t(sizeof(Vertex));
auto offset = 0u;
pContext->VSSetShader(m_pVS.GetPtr(), nullptr, 0);
pContext->PSSetShader(m_pPSFlow.GetPtr(), nullptr, 0);
pContext->GSSetShader(nullptr, nullptr, 0);
pContext->HSSetShader(nullptr, nullptr, 0);
pContext->DSSetShader(nullptr, nullptr, 0);
auto pCB = m_pCB.GetPtr();
{
CbSkySphere buf = {};
buf.World = Matrix::CreateRotationX(F_PIDIV2) * Matrix::CreateTranslation(cameraPos);
buf.View = view;
buf.Proj = proj;
buf.SphereSize = sphereSize;
pContext->UpdateSubresource(pCB, 0, nullptr, &buf, 0, 0);
}
auto pCBFlow = m_pCBFlow.GetPtr();
{
CbSkySphereFlow buf = {};
buf.WindDirection = flowDir;
buf.Offset.x = m_FlowOffset[0];
buf.Offset.y = m_FlowOffset[1];
m_FlowOffset[0] += flowStep;
m_FlowOffset[1] += flowStep;
if (m_FlowOffset[0] > 1.0f)
{ m_FlowOffset[0] -= 1.0f; }
if (m_FlowOffset[1] > 1.0f)
{ m_FlowOffset[1] -= 1.0f; }
pContext->UpdateSubresource(pCBFlow, 0, nullptr, &buf, 0, 0);
}
pContext->VSSetConstantBuffers(0, 1, &pCB);
pContext->PSSetConstantBuffers(1, 1, &pCBFlow);
pContext->PSSetShaderResources(0, 1, &pSRV);
pContext->PSSetSamplers(0, 1, &pSmp);
pContext->IASetInputLayout(m_pIL.GetPtr());
pContext->IASetIndexBuffer(m_pIB.GetPtr(), DXGI_FORMAT_R32_UINT, 0);
pContext->IASetVertexBuffers(0, 1, m_pVB.GetAddress(), &stride, &offset);
pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
pContext->DrawIndexed(m_IndexCount, 0, 0);
ID3D11ShaderResourceView* pNullSRV[1] = { nullptr };
ID3D11SamplerState* pNullSmp[1] = { nullptr };
pContext->PSSetShaderResources(0, 1, pNullSRV);
pContext->PSSetSamplers(0, 1, pNullSmp);
pContext->VSSetShader(nullptr, nullptr, 0);
pContext->PSSetShader(nullptr, nullptr, 0);
}
//-----------------------------------------------------------------------------
// フローオフセットをリセットします.
//-----------------------------------------------------------------------------
void SkySphere::ResetFlow()
{
m_FlowOffset[0] = 0.0f;
m_FlowOffset[1] = 0.5f;
}
} // namespace asdx
| 33.664319 | 122 | 0.473816 | ProjectAsura |
0237b7eb818f95115f65a80370fb734d44937069 | 363 | hpp | C++ | include/bbbgpio/core.hpp | uilianries/BeagleBoneBlackGPIO | bbd4137ca2b5b2e506321bf440ba87370764646b | [
"MIT"
] | 6 | 2016-03-11T16:48:16.000Z | 2021-06-05T11:38:48.000Z | include/bbbgpio/core.hpp | uilianries/BeagleBoneBlackGPIO | bbd4137ca2b5b2e506321bf440ba87370764646b | [
"MIT"
] | 9 | 2016-03-03T17:31:57.000Z | 2018-01-11T23:00:55.000Z | include/bbbgpio/core.hpp | uilianries/BeagleBoneBlackGPIO | bbd4137ca2b5b2e506321bf440ba87370764646b | [
"MIT"
] | null | null | null | /**
* \file
* \brief Load basic pin core
*
* \author Uilian Ries <uilianries@gmail.com>
*/
#ifndef BBBGPIO_CORE_HPP
#define BBBGPIO_CORE_HPP
namespace bbb {
namespace gpio {
/**
* \brief Basic core declaration
*/
class core {
public:
virtual ~core() = default;
};
} // namespace gpio
} // namespace bbb
#endif //BBBGPIO_CORE_HPP
| 13.961538 | 45 | 0.639118 | uilianries |
0238d577559be1aeeded0fdfb1e11de41c886a7b | 718 | hpp | C++ | src/layout/composer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | src/layout/composer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | src/layout/composer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "layout/cell_util.hpp"
namespace hisui::layout {
class Region;
struct ComposerParameters {
const std::vector<std::shared_ptr<Region>>& regions;
const Resolution& resolution;
};
class Composer {
public:
explicit Composer(const ComposerParameters&);
~Composer();
void compose(std::vector<unsigned char>*, const std::uint64_t);
private:
std::vector<std::shared_ptr<Region>> m_regions;
Resolution m_resolution;
std::array<unsigned char*, 3> m_planes;
std::array<std::size_t, 3> m_plane_sizes;
std::array<unsigned char, 3> m_plane_default_values;
};
} // namespace hisui::layout
| 20.514286 | 65 | 0.729805 | kounoike |
023ee49c6e0a51231affc25ec765f9383fce1f2a | 3,662 | hpp | C++ | be/src/util/lru_cache.hpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 3,562 | 2018-08-30T05:26:10.000Z | 2022-03-31T10:01:56.000Z | be/src/util/lru_cache.hpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 5,199 | 2018-09-11T07:57:21.000Z | 2022-03-31T16:17:50.000Z | be/src/util/lru_cache.hpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 1,234 | 2018-08-31T09:34:54.000Z | 2022-03-31T06:01:02.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#ifndef DORIS_BE_UTIL_LRU_CACHE_HPP
#define DORIS_BE_UTIL_LRU_CACHE_HPP
#include <list>
#include <unordered_map>
#include <iterator>
namespace doris {
template <typename Key, typename Value>
class LruCache {
public:
typedef typename std::pair<Key, Value> KeyValuePair;
typedef typename std::list<KeyValuePair>::iterator ListIterator;
class Iterator : public std::iterator<std::input_iterator_tag, KeyValuePair> {
public:
Iterator(typename std::unordered_map<Key, ListIterator>::iterator it) : _it(it) { }
Iterator& operator++() {
++_it;
return *this;
}
bool operator==(const Iterator& rhs) const {
return _it == rhs._it;
}
bool operator!=(const Iterator& rhs) const {
return _it != rhs._it;
}
KeyValuePair* operator->() {
return _it->second.operator->();
}
KeyValuePair& operator*() {
return *_it->second;
}
private:
typename std::unordered_map<Key, ListIterator>::iterator _it;
};
LruCache(size_t max_size) : _max_size(max_size) { }
void put(const Key& key, const Value& value) {
auto it = _cache_items_map.find(key);
if (it != _cache_items_map.end()) {
_cache_items_list.erase(it->second);
_cache_items_map.erase(it);
}
_cache_items_list.push_front(KeyValuePair(key, value));
_cache_items_map[key] = _cache_items_list.begin();
if (_cache_items_map.size() > _max_size) {
auto last = _cache_items_list.end();
last--;
_cache_items_map.erase(last->first);
_cache_items_list.pop_back();
}
}
void erase(const Key& key) {
auto it = _cache_items_map.find(key);
if (it != _cache_items_map.end()) {
_cache_items_list.erase(it->second);
_cache_items_map.erase(it);
}
}
// Must copy value, because value maybe relased when caller used
bool get(const Key& key, Value* value) {
auto it = _cache_items_map.find(key);
if (it == _cache_items_map.end()) {
return false;
}
_cache_items_list.splice(_cache_items_list.begin(), _cache_items_list, it->second);
*value = it->second->second;
return true;
}
bool exists(const Key& key) const {
return _cache_items_map.find(key) != _cache_items_map.end();
}
size_t size() const {
return _cache_items_map.size();
}
Iterator begin() {
return Iterator(_cache_items_map.begin());
}
Iterator end() {
return Iterator(_cache_items_map.end());
}
private:
std::list<KeyValuePair> _cache_items_list;
std::unordered_map<Key, ListIterator> _cache_items_map;
size_t _max_size;
};
}
#endif
| 29.063492 | 91 | 0.638176 | kaiker19 |
0241e131febd400c95b44450a12d4a135b6f0489 | 1,007 | cc | C++ | Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | 1 | 2020-02-07T12:25:56.000Z | 2020-02-07T12:25:56.000Z | Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | #include <vector>
using std::vector;
class Solution {
public:
// 除去直接使用通项公式的方法,还有一种方法时间复杂度更低,
// 1 1 ^n f(1) = f(n+1)
// 1 0 f(0) f(n)
using matrix_type = vector<vector<int>>;
int fib(int n) {
if (n < 2) return n;
matrix_type a{{1, 1}, {1, 0}};
matrix_type r = matrix_pow(a, n - 1);
return r[0][0];
}
matrix_type matrix_pow(matrix_type& matrix, int n) {
matrix_type result{{1, 0}, {0, 1}};
while (n) {
if (n & 1) {
result = matrix_multiply(result, matrix);
}
matrix = matrix_multiply(matrix, matrix);
n >>= 1;
}
return result;
}
matrix_type matrix_multiply(matrix_type& a, matrix_type& b) {
matrix_type c(2, vector<int>(2));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
return c;
}
}; | 23.97619 | 65 | 0.454816 | sheriby |
02464d969d1ea5a1796198d466f27a0e71d79a41 | 7,317 | hxx | C++ | data3d/suncg_utils/cmake-3.13.2/Bootstrap.cmk/cmsys/Configure.hxx | picwoon/As_built_BIM | 9e6b81e2fd8904f5afd013e21d2db45456c138d5 | [
"MIT"
] | 2 | 2020-03-05T06:39:03.000Z | 2020-03-31T12:08:04.000Z | data3d/suncg_utils/cmake-3.13.2/Bootstrap.cmk/cmsys/Configure.hxx | picwoon/As_built_BIM | 9e6b81e2fd8904f5afd013e21d2db45456c138d5 | [
"MIT"
] | null | null | null | data3d/suncg_utils/cmake-3.13.2/Bootstrap.cmk/cmsys/Configure.hxx | picwoon/As_built_BIM | 9e6b81e2fd8904f5afd013e21d2db45456c138d5 | [
"MIT"
] | null | null | null | /*
* Generated by /home/wenjing/DATA/Detection_3D-data_multi_stories/data3d/suncg_utils/cmake-3.13.2/bootstrap
* Version: $Revision$
*
* Source directory: /home/wenjing/DATA/Detection_3D-data_multi_stories/data3d/suncg_utils/cmake-3.13.2
* Binary directory: /home/wenjing/DATA/Detection_3D-data_multi_stories/data3d/suncg_utils/cmake-3.13.2/Bootstrap.cmk
*
* C compiler: gcc
* C flags:
*
* C++ compiler: g++
* C++ flags: -std=gnu++17
*
* Make: make
*
* Sources:
* cmAddCustomCommandCommand cmAddCustomTargetCommand cmAddDefinitionsCommand cmAddDependenciesCommand cmAddExecutableCommand cmAddLibraryCommand cmAddSubDirectoryCommand cmAddTestCommand cmBreakCommand cmBuildCommand cmCMakeMinimumRequired cmCMakePolicyCommand cmCPackPropertiesGenerator cmCacheManager cmCommand cmCommandArgumentParserHelper cmCommandArgumentsHelper cmCommands cmCommonTargetGenerator cmComputeComponentGraph cmComputeLinkDepends cmComputeLinkInformation cmComputeTargetDepends cmConditionEvaluator cmConfigureFileCommand cmContinueCommand cmCoreTryCompile cmCreateTestSourceList cmCustomCommand cmCustomCommandGenerator cmDefinePropertyCommand cmDefinitions cmDepends cmDependsC cmDisallowedCommand cmDocumentationFormatter cmEnableLanguageCommand cmEnableTestingCommand cmExecProgramCommand cmExecuteProcessCommand cmExpandedCommandArgument cmExportBuildFileGenerator cmExportFileGenerator cmExportInstallFileGenerator cmExportSet cmExportSetMap cmExportTryCompileFileGenerator cmExprParserHelper cmExternalMakefileProjectGenerator cmFileCommand cmFileTimeComparison cmFindBase cmFindCommon cmFindFileCommand cmFindLibraryCommand cmFindPackageCommand cmFindPathCommand cmFindProgramCommand cmForEachCommand cmFunctionCommand cmFSPermissions cmGeneratedFileStream cmGeneratorExpression cmGeneratorExpressionContext cmGeneratorExpressionDAGChecker cmGeneratorExpressionEvaluationFile cmGeneratorExpressionEvaluator cmGeneratorExpressionLexer cmGeneratorExpressionNode cmGeneratorExpressionParser cmGeneratorTarget cmGetCMakePropertyCommand cmGetDirectoryPropertyCommand cmGetFilenameComponentCommand cmGetPropertyCommand cmGetSourceFilePropertyCommand cmGetTargetPropertyCommand cmGetTestPropertyCommand cmGlobalCommonGenerator cmGlobalGenerator cmGlobalUnixMakefileGenerator3 cmGlobVerificationManager cmHexFileConverter cmIfCommand cmIncludeCommand cmIncludeGuardCommand cmIncludeDirectoryCommand cmIncludeRegularExpressionCommand cmInstallCommand cmInstallCommandArguments cmInstallDirectoryGenerator cmInstallExportGenerator cmInstallFilesCommand cmInstallFilesGenerator cmInstallGenerator cmInstallScriptGenerator cmInstallTargetGenerator cmInstallTargetsCommand cmInstalledFile cmLinkDirectoriesCommand cmLinkItem cmLinkLineComputer cmListCommand cmListFileCache cmLocalCommonGenerator cmLocalGenerator cmLocalUnixMakefileGenerator3 cmMSVC60LinkLineComputer cmMacroCommand cmMakeDirectoryCommand cmMakefile cmMakefileExecutableTargetGenerator cmMakefileLibraryTargetGenerator cmMakefileTargetGenerator cmMakefileUtilityTargetGenerator cmMarkAsAdvancedCommand cmMathCommand cmMessageCommand cmMessenger cmNewLineStyle cmOSXBundleGenerator cmOptionCommand cmOrderDirectories cmOutputConverter cmParseArgumentsCommand cmPathLabel cmPolicies cmProcessOutput cmProjectCommand cmProperty cmPropertyDefinition cmPropertyDefinitionMap cmPropertyMap cmReturnCommand cmRulePlaceholderExpander cmScriptGenerator cmSearchPath cmSeparateArgumentsCommand cmSetCommand cmSetDirectoryPropertiesCommand cmSetPropertyCommand cmSetSourceFilesPropertiesCommand cmSetTargetPropertiesCommand cmSetTestsPropertiesCommand cmSiteNameCommand cmSourceFile cmSourceFileLocation cmState cmStateDirectory cmStateSnapshot cmStringReplaceHelper cmStringCommand cmSubdirCommand cmSystemTools cmTarget cmTargetCompileDefinitionsCommand cmTargetCompileFeaturesCommand cmTargetCompileOptionsCommand cmTargetIncludeDirectoriesCommand cmTargetLinkLibrariesCommand cmTargetPropCommandBase cmTargetPropertyComputer cmTargetSourcesCommand cmTest cmTestGenerator cmTimestamp cmTryCompileCommand cmTryRunCommand cmUnexpectedCommand cmUnsetCommand cmUVHandlePtr cmVersion cmWhileCommand cmWorkingDirectory cmake cmakemain cmcmd
* LexerParser Sources:
* cmCommandArgumentLexer cmCommandArgumentParser cmExprLexer cmExprParser cmListFileLexer
* kwSys Sources:
* Directory EncodingCXX FStream Glob RegularExpression SystemTools EncodingC ProcessUNIX String System Terminal
* libuv Sources:
* src/uv-common.c src/unix/cmake-bootstrap.c src/unix/core.c src/unix/fs.c src/unix/loop.c src/unix/loop-watcher.c src/unix/no-fsevents.c src/unix/pipe.c src/unix/poll.c src/unix/posix-hrtime.c src/unix/posix-poll.c src/unix/process.c src/unix/signal.c src/unix/stream.c src/unix/timer.c
*/
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef cmsys_Configure_hxx
#define cmsys_Configure_hxx
/* Include C configuration. */
#include <cmsys/Configure.h>
/* Whether wstring is available. */
#define cmsys_STL_HAS_WSTRING 1
/* Whether <ext/stdio_filebuf.h> is available. */
#define cmsys_CXX_HAS_EXT_STDIO_FILEBUF_H \
1
#if defined(__SUNPRO_CC) && __SUNPRO_CC > 0x5130 && defined(__has_attribute)
# define cmsys__has_cpp_attribute(x) __has_attribute(x)
#elif defined(__has_cpp_attribute)
# define cmsys__has_cpp_attribute(x) __has_cpp_attribute(x)
#else
# define cmsys__has_cpp_attribute(x) 0
#endif
#if __cplusplus >= 201103L
# define cmsys_NULLPTR nullptr
#else
# define cmsys_NULLPTR 0
#endif
#ifndef cmsys_FALLTHROUGH
# if __cplusplus >= 201703L && \
cmsys__has_cpp_attribute(fallthrough)
# define cmsys_FALLTHROUGH [[fallthrough]]
# elif __cplusplus >= 201103L && \
cmsys__has_cpp_attribute(gnu::fallthrough)
# define cmsys_FALLTHROUGH [[gnu::fallthrough]]
# elif __cplusplus >= 201103L && \
cmsys__has_cpp_attribute(clang::fallthrough)
# define cmsys_FALLTHROUGH [[clang::fallthrough]]
# endif
#endif
#ifndef cmsys_FALLTHROUGH
# define cmsys_FALLTHROUGH static_cast<void>(0)
#endif
#undef cmsys__has_cpp_attribute
/* If building a C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
# if !cmsys_NAME_IS_KWSYS
# define kwsys cmsys
# endif
# define KWSYS_NAME_IS_KWSYS cmsys_NAME_IS_KWSYS
# define KWSYS_STL_HAS_WSTRING cmsys_STL_HAS_WSTRING
# define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H \
cmsys_CXX_HAS_EXT_STDIO_FILEBUF_H
# define KWSYS_FALLTHROUGH cmsys_FALLTHROUGH
# define KWSYS_NULLPTR cmsys_NULLPTR
#endif
#endif
| 84.103448 | 4,066 | 0.789941 | picwoon |
0249b78204328624e2fdccb88e9a72f5398166e4 | 5,933 | cpp | C++ | platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 2 | 2020-01-13T07:32:50.000Z | 2020-03-03T14:32:25.000Z | platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 16 | 2019-06-16T05:51:02.000Z | 2020-02-03T01:59:23.000Z | platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 1 | 2020-03-03T14:32:27.000Z | 2020-03-03T14:32:27.000Z | //
// Created by Ivan Kishchenko on 01.09.2021.
//
#ifdef ARDUINO_ARCH_ESP8266
#include "ZeroMQConnection.h"
#include "../ZeroMQReader.h"
#include <HardwareSerial.h>
size_t ZeroMQDataMessage::ack(size_t len) {
// If the whole message is now acked...
if (_acked + len > _buf->size()) {
// Return the number of extra bytes acked (they will be carried on to the next message)
const size_t extra = _acked + len - _buf->size();
_acked = _buf->size();
return extra;
}
// Return that no extra bytes left.
_acked += len;
return 0;
}
size_t ZeroMQDataMessage::send(AsyncClient *client) {
const size_t len = _buf->size() - _sent;
if (client->space() < len) {
return 0;
}
size_t sent = client->add((const char *) _buf->data(), len);
if (client->canSend()) {
client->send();
}
_sent += sent;
return sent;
}
ZeroMQDataMessage::ZeroMQDataMessage(std::shared_ptr<ZeroMQCharBuf> &buf)
: _buf(std::move(buf)) {
}
ZeroMQConnection::ZeroMQConnection(AsyncClient *client)
: _serverMode{true}, _client(client), _state{ZeroMQStatus::ZMQ_Idle} {
_dec.onCommand([this](const ZeroMQCommand &cmd) {
onCommand(cmd);
});
_dec.onMessage([this](const ZeroMQMessage &msg) {
onMessage(msg);
});
_topics.insert("joystick");
}
void ZeroMQConnection::onConnect() {
_state = ZeroMQStatus::ZMQ_Idle;
std::shared_ptr<ZeroMQCharBuf> buf(new ZeroMQBufFix<64>());
std::ostream out(buf.get());
ZeroMQGreeting reply(true);
out << reply;
send(buf);
}
void ZeroMQConnection::onError(int8_t error) {
Serial.printf("%s: conn error: %s \n", _client->remoteIP().toString().c_str(), _client->errorToString(error));
}
void ZeroMQConnection::onData(void *data, size_t len) {
// Serial.printf("%s: recv: %d\n", _client->remoteIP().toString().c_str(), len);
// Serial.println(ZeroMQUtils::netDump((uint8_t *) data, len).c_str());
_inc.sputn((const char *) data, (std::streamsize) len);
onData(_inc);
}
void ZeroMQConnection::onData(ZeroMQCharBuf &incBuf) {
while (incBuf.in_avail()) {
switch (_state) {
case ZeroMQStatus::ZMQ_Idle:
case ZeroMQStatus::ZMQ_S_Wait_Greeting: {
if (_inc.in_avail() < 64) {
return;
}
ZeroMQReader inc(incBuf);
std::array<uint8_t, 64> greeting{};
inc.readBinary<uint8_t, 64>(greeting);
_inc.consume(64);
_version.major = greeting[10];
_version.minor = greeting[11];
if (_version.major != 0x03) {
Serial.printf("%s: unsupported version: %d:%d\n", getRemoteAddress().c_str(), _version.major, _version.minor);
_client->close();
return;
}
Serial.printf("%s: version: %d:%d\n", getRemoteAddress().c_str(), _version.major, _version.minor);
ZeroMQCommand reply(ZERO_MQ_CMD_READY);
reply.props.emplace(ZERO_MQ_PROP_SOCKET_TYPE, "SUB");
std::shared_ptr<ZeroMQCharBuf> out(new ZeroMQBufFix<64>());
_enc.write(*out, reply);
send(out);
_state = ZeroMQStatus::ZMQ_Stream;
break;
}
case ZeroMQStatus::ZMQ_Stream: {
if (_dec.read(incBuf)) {
return;
}
}
break;
default:
break;
}
}
}
void ZeroMQConnection::onDisconnect() {
}
void ZeroMQConnection::onTimeOut(uint32_t time) {
}
void ZeroMQConnection::onPool() {
runQueue();
}
void ZeroMQConnection::onAck(size_t len) {
if (!_out.empty()) {
_out.front()->ack(len);
}
onPool();
}
void ZeroMQConnection::send(std::shared_ptr<ZeroMQCharBuf> &msg) {
// Serial.printf("send: %d\n", msg->size());
// Serial.println(msg->dump().c_str());
_out.emplace_back(new ZeroMQDataMessage(msg));
if (_client->canSend()) {
runQueue();
}
}
void ZeroMQConnection::runQueue() {
while (!_out.empty() && _out.front()->finished()) {
_out.remove(_out.front());
}
for (auto &buf: _out) {
if (!buf->sent()) {
buf->send(_client);
}
}
}
void ZeroMQConnection::onCommand(const ZeroMQCommand &cmd) {
if (cmd.getName() == ZERO_MQ_CMD_READY) {
Serial.printf("%s: %s\n", getRemoteAddress().c_str(), cmd.getName().c_str());
for (auto &prop: cmd.props) {
Serial.printf("%s: %s %s\n", getRemoteAddress().c_str(), prop.first.c_str(), prop.second.c_str());
}
// subscribe = %x00 short-size %d1 subscription
for (auto &topic: _topics) {
std::shared_ptr<ZeroMQCharBuf> out(new ZeroMQBufFix<64>());
if (_version.minor == 0x00) {
std::ostream str(out.get());
str << (uint8_t) 0x00 << (uint8_t) (1 + 8) << (uint8_t) 0x01 << topic;
} else if (_version.minor == 0x01) {
ZeroMQCommand sub(ZERO_MQ_CMD_SUBSCRIBE);
sub.props.emplace(ZERO_MQ_PROP_SUBSCRIPTION, topic);
_enc.write(*out, sub);
}
send(out);
}
} else {
Serial.printf("%s: %s unsupported\n", getRemoteAddress().c_str(), cmd.name.c_str());
}
}
void ZeroMQConnection::onMessage(const ZeroMQMessage &msg) {
if (msg.data.size() == 2 && _topicEventHandler) {
Serial.printf("%s: sub: %s:%s\n", getRemoteAddress().c_str(), msg.data.front().c_str(), msg.data.back().c_str());
_topicEventHandler(ZeroMQTopicEvent{msg.data.front(), msg.data.back()});
return;
}
for (const auto &item: msg.data) {
Serial.printf("%s: msg %s\n", getRemoteAddress().c_str(), item.c_str());
}
}
#endif | 30.116751 | 130 | 0.568178 | darvik80 |
024bea0e9b3bff5f63c5cd9a4a76ca5587a89ab7 | 6,790 | cpp | C++ | task3_stack_queue_list.cpp | 5x/AlgorithmsAndDataStructures | e383c509c09ea0b9eccad761b9fa53227d05e6d5 | [
"MIT"
] | null | null | null | task3_stack_queue_list.cpp | 5x/AlgorithmsAndDataStructures | e383c509c09ea0b9eccad761b9fa53227d05e6d5 | [
"MIT"
] | null | null | null | task3_stack_queue_list.cpp | 5x/AlgorithmsAndDataStructures | e383c509c09ea0b9eccad761b9fa53227d05e6d5 | [
"MIT"
] | null | null | null | #include <iostream>
template<class T>
struct Node {
T value;
Node* next;
Node(T _value, Node* _next) : value(_value), next(_next) {
}
};
template<class T>
class Stack {
public:
Stack() {
last = NULL;
}
~Stack() {
clear();
}
void push(T const& value) {
last = new Node<T>(value, last);
}
T peek() const {
return (isEmpty()) ? NULL : last->value;
}
T pop() {
if (isEmpty()) {
return NULL;
}
T value = last->value;
Node<T>* tmp = last->next;
delete last;
last = tmp;
return value;
}
bool isEmpty() const {
return (last == NULL);
}
void clear() {
while (!isEmpty()) {
pop();
}
}
void print() const {
std::cout << '[';
if (isEmpty()) {
std::cout << "<empty>";
} else {
Node<T>* curr = last;
while (curr) {
std::cout << curr->value << ", ";
curr = curr->next;
}
}
std::cout << ']' << std::endl;
}
private:
Node<T>* last;
};
template<class T>
class Queue {
public:
Queue() {
head = tail = NULL;
}
~Queue() {
clear();
}
void enqueue(T const& value) {
if (tail) {
tail->next = new Node<T>(value, NULL);
tail = tail->next;
} else {
head = tail = new Node<T>(value, head);
}
}
T dequeue() {
if (isEmpty()) {
return NULL;
}
T value = head->value;
Node<T>* tmp = head->next;
delete head;
head = tmp;
return value;
}
bool isEmpty() const {
return (head == NULL);
}
void clear() {
while (!isEmpty()) {
dequeue();
}
}
void print() const {
std::cout << '[';
if (isEmpty()) {
std::cout << "<empty>";
} else {
Node<T>* curr = head;
while (curr) {
std::cout << curr->value << ", ";
curr = curr->next;
}
}
std::cout << ']' << std::endl;
}
private:
Node<T>* head;
Node<T>* tail;
};
template<class T>
class List {
public:
List() {
head = tail = NULL;
}
~List() {
clear();
}
/* Insert value to end of list */
void add(const T& value) {
if (isEmpty()) {
head = tail = new Node<T>(value, NULL);
} else {
tail->next = new Node<T>(value, NULL);
tail = tail->next;
}
}
void remove(Node<T>* node) {
if (isEmpty()) {
return;
}
if (node->next == NULL) {
removeLast();
} else {
*node = *node->next;
}
}
void removeLast() {
if (head->next == NULL) {
delete tail;
head = tail = NULL;
} else {
Node<T>* prev = head;
while (prev->next->next) {
prev = prev->next;
}
tail = prev;
tail->next = NULL;
delete prev->next;
}
}
/* Insert value to start of list */
void insert(const T& value) {
head = new Node<T>(value, head);
}
/* Insert value after @prev node */
void insert(const T& value, Node<T>* prev) {
prev->next = new Node<T>(value, prev->next);
}
void clear() {
Node<T>* tmp = NULL;
while (!isEmpty()) {
tmp = head;
head = head->next;
delete (tmp);
}
}
bool isEmpty() const {
return (head == NULL);
}
void print() const {
std::cout << '[';
if (isEmpty()) {
std::cout << "<empty>";
} else {
Node<T>* curr = head;
while (curr) {
std::cout << curr->value << ", ";
curr = curr->next;
}
}
std::cout << ']' << std::endl;
}
Node<T>* first() const {
return head;
}
Node<T>* last() const {
return tail;
}
protected:
Node<T>* head;
Node<T>* tail;
};
void testList() {
std::cout << "\n-----------\nList:\n-----------\n";
List<int>* list = new List<int>();
std::cout << "Print(First->Last) stack: ";
list->print();
std::cout << "Add to end (60): ";
list->add(60);
list->print();
std::cout << "Add to start (25, 5): ";
list->insert(25);
list->insert(5);
list->print();
std::cout << "Add after first (10): ";
list->insert(10, list->first());
list->print();
std::cout << "Remove first: ";
list->remove(list->first());
list->print();
std::cout << "Remove last: ";
list->remove(list->last());
list->print();
std::cout << "Empty list: ";
list->clear();
list->print();
list->~List();
}
void testStack() {
std::cout << "\n-----------\nStack:\n-----------\n";
Stack<int>* stack = new Stack<int>();
std::cout << "Print(Last->First) stack: ";
stack->print();
std::cout << "Push (5): ";
stack->push(5);
stack->print();
std::cout << "Push (10, 25, 60): ";
stack->push(10);
stack->push(25);
stack->push(60);
stack->print();
std::cout << "Pop(" << stack->pop() << "): ";
stack->print();
std::cout << "Pop(" << stack->pop() << "): ";
stack->print();
std::cout << "Peak(" << stack->peek() << "): ";
stack->print();
std::cout << "Empty Stack: ";
stack->clear();
stack->print();
stack->~Stack();
}
void testQueue() {
std::cout << "\n-----------\nQueue:\n-----------\n";
Queue<int>* queue = new Queue<int>();
std::cout << "Print(First->Last) queue: ";
queue->print();
std::cout << "Enqueue (5): ";
queue->enqueue(5);
queue->print();
std::cout << "Enqueue (10, 25, 60): ";
queue->enqueue(10);
queue->enqueue(25);
queue->enqueue(60);
queue->print();
std::cout << "Dequeue(" << queue->dequeue() << "): ";
queue->print();
std::cout << "Dequeue(" << queue->dequeue() << "): ";
queue->print();
std::cout << "Empty Queue: ";
queue->clear();
queue->print();
queue->~Queue();
}
int main() {
testList();
testStack();
testQueue();
system("pause");
return 0;
}
| 20.268657 | 63 | 0.405007 | 5x |
024fb820d76ab863416a6f3ad7ef02dae89eea3a | 4,329 | cpp | C++ | VAlloc.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | VAlloc.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | VAlloc.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | /* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net
* Project: Vulture(c)
* Author : Andrea Nardinocchi
* eMail : andrea@nardinan.it
*
* 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "VAlloc.h"
unsigned int memory = 0;
unsigned int pointers = 0;
allocationslist *allocationsroot = NULL;
void *vmalloc(size_t size, const char *file, int line) {
vcoords *coords = NULL;
allocationslist *list = allocationsroot;
int index;
void *result = NULL;
unsigned char *check = NULL;
if ((result = malloc(size + sizeof (vcoords) + 20))) {
pointers++;
memory += size + sizeof (vcoords) + 20;
check = (unsigned char *) ((char *) result + size);
coords = (vcoords *) (check + 20);
coords->file = file;
coords->line = line;
for (index = 0; index < size; index++) ((char *) result)[index] = '\0';
*((unsigned int *) check) = 0xdeadbeef;
if (allocationsroot) {
while (list->next) list = list->next;
if ((list->next = (allocationslist *) malloc(sizeof (allocationslist)))) {
list->next->pointer = result;
list->next->buffersize = size;
list->next->next = NULL;
list->next->back = list;
} else LOG_ERROR("unable to allocate node of the list");
} else {
if ((allocationsroot = (allocationslist *) malloc(sizeof (allocationslist)))) {
allocationsroot->pointer = result;
allocationsroot->buffersize = size;
allocationsroot->next = NULL;
allocationsroot->back = NULL;
} else LOG_ERROR("unable to allocate root of the list");
}
}
return result;
}
void *vrealloc(void *pointer, size_t size) {
allocationslist *list = allocationsroot;
void *result = NULL;
while ((list) && (list->pointer != pointer)) list = list->next;
if (list->pointer == pointer) {
if ((result = pvmalloc(size))) {
memcpy(result, pointer, list->buffersize);
pvfree(pointer);
}
}
return result;
}
void vfree(void *pointer) {
allocationslist *list = allocationsroot;
while ((list) && (list->pointer != pointer)) list = list->next;
if ((list) && (list->pointer == pointer)) {
pointers--;
memory -= list->buffersize + sizeof (vcoords) + 20;
if (list->next) list->next->back = list->back;
if (list->back) list->back->next = list->next;
else allocationsroot = list->next;
free(list);
free(pointer);
} else LOG_ERROR("unable to find reference on pointers' list (double free!)");
}
void vdeallocate(void) {
vshow();
while (allocationsroot)
pvfree(allocationsroot->pointer);
}
int vshow(void) {
vcoords *coords = NULL;
allocationslist *list = allocationsroot;
unsigned char *check = NULL;
unsigned int correct = 0, errors = 0;
while (list) {
check = (unsigned char *) (((char *) list->pointer) + (size_t) list->buffersize);
coords = (vcoords *) (check + 20);
if (*((unsigned int *) check) == 0xdeadbeef) correct++;
else errors++;
printf("\n[POINTER] %p at %s (row %d) 0xDEADBEEF (contain: %s) { %s }!",
list->pointer,
coords->file,
coords->line,
list->pointer,
(*((unsigned int *) check) == 0xdeadbeef) ? "OK" : "ERROR");
list = list->next;
}
printf("\n[FINISH] I've found: %d correct pointers AND %d damaged pointers (%s)\n",
correct,
errors,
((errors == 0) ? "that's good for you!" : "uh-oh!"));
return errors;
}
| 37.318966 | 91 | 0.585355 | nardinan |
02513cf2f95e0a8bacaeefde50dcfdc8e25c6acc | 18,224 | cpp | C++ | third_party/skia_m63/third_party/externals/angle2/src/libANGLE/renderer/d3d/d3d11/dxgi_format_map_autogen.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 4 | 2019-10-18T05:53:30.000Z | 2021-08-21T07:36:37.000Z | third_party/skia_m63/third_party/externals/angle2/src/libANGLE/renderer/d3d/d3d11/dxgi_format_map_autogen.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | third_party/skia_m63/third_party/externals/angle2/src/libANGLE/renderer/d3d/d3d11/dxgi_format_map_autogen.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 4 | 2018-10-14T00:17:11.000Z | 2020-07-01T04:01:25.000Z | // GENERATED FILE - DO NOT EDIT.
// Generated by gen_dxgi_format_table.py using data from dxgi_format_data.json.
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DXGI format info:
// Determining metadata about a DXGI format.
#include "libANGLE/renderer/Format.h"
using namespace angle;
namespace rx
{
namespace d3d11
{
GLenum GetComponentType(DXGI_FORMAT dxgiFormat)
{
switch (dxgiFormat)
{
case DXGI_FORMAT_420_OPAQUE:
break;
case DXGI_FORMAT_A8P8:
break;
case DXGI_FORMAT_A8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_AI44:
break;
case DXGI_FORMAT_AYUV:
break;
case DXGI_FORMAT_B4G4R4A4_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B5G5R5A1_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B5G6R5_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
break;
case DXGI_FORMAT_B8G8R8A8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
break;
case DXGI_FORMAT_B8G8R8X8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC1_TYPELESS:
break;
case DXGI_FORMAT_BC1_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC1_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC2_TYPELESS:
break;
case DXGI_FORMAT_BC2_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC2_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC3_TYPELESS:
break;
case DXGI_FORMAT_BC3_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC3_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC4_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_BC4_TYPELESS:
break;
case DXGI_FORMAT_BC4_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC5_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_BC5_TYPELESS:
break;
case DXGI_FORMAT_BC5_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC6H_SF16:
break;
case DXGI_FORMAT_BC6H_TYPELESS:
break;
case DXGI_FORMAT_BC6H_UF16:
break;
case DXGI_FORMAT_BC7_TYPELESS:
break;
case DXGI_FORMAT_BC7_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_BC7_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_D16_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_D24_UNORM_S8_UINT:
break;
case DXGI_FORMAT_D32_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
break;
case DXGI_FORMAT_G8R8_G8B8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_IA44:
break;
case DXGI_FORMAT_NV11:
break;
case DXGI_FORMAT_NV12:
break;
case DXGI_FORMAT_P010:
break;
case DXGI_FORMAT_P016:
break;
case DXGI_FORMAT_P8:
break;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
break;
case DXGI_FORMAT_R10G10B10A2_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R10G10B10A2_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R11G11B10_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R16G16B16A16_SINT:
return GL_INT;
case DXGI_FORMAT_R16G16B16A16_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
break;
case DXGI_FORMAT_R16G16B16A16_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R16G16B16A16_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R16G16_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R16G16_SINT:
return GL_INT;
case DXGI_FORMAT_R16G16_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R16G16_TYPELESS:
break;
case DXGI_FORMAT_R16G16_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R16G16_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R16_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R16_SINT:
return GL_INT;
case DXGI_FORMAT_R16_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R16_TYPELESS:
break;
case DXGI_FORMAT_R16_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R16_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R1_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R24G8_TYPELESS:
break;
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R32G32B32A32_SINT:
return GL_INT;
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
break;
case DXGI_FORMAT_R32G32B32A32_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R32G32B32_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R32G32B32_SINT:
return GL_INT;
case DXGI_FORMAT_R32G32B32_TYPELESS:
break;
case DXGI_FORMAT_R32G32B32_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R32G32_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R32G32_SINT:
return GL_INT;
case DXGI_FORMAT_R32G32_TYPELESS:
break;
case DXGI_FORMAT_R32G32_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R32G8X24_TYPELESS:
break;
case DXGI_FORMAT_R32_FLOAT:
return GL_FLOAT;
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
return GL_FLOAT;
case DXGI_FORMAT_R32_SINT:
return GL_INT;
case DXGI_FORMAT_R32_TYPELESS:
break;
case DXGI_FORMAT_R32_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R8G8B8A8_SINT:
return GL_INT;
case DXGI_FORMAT_R8G8B8A8_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
break;
case DXGI_FORMAT_R8G8B8A8_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R8G8B8A8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R8G8_B8G8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R8G8_SINT:
return GL_INT;
case DXGI_FORMAT_R8G8_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R8G8_TYPELESS:
break;
case DXGI_FORMAT_R8G8_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R8G8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R8_SINT:
return GL_INT;
case DXGI_FORMAT_R8_SNORM:
return GL_SIGNED_NORMALIZED;
case DXGI_FORMAT_R8_TYPELESS:
break;
case DXGI_FORMAT_R8_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_R8_UNORM:
return GL_UNSIGNED_NORMALIZED;
case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
return GL_FLOAT;
case DXGI_FORMAT_UNKNOWN:
break;
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
return GL_UNSIGNED_INT;
case DXGI_FORMAT_Y210:
break;
case DXGI_FORMAT_Y216:
break;
case DXGI_FORMAT_Y410:
break;
case DXGI_FORMAT_Y416:
break;
case DXGI_FORMAT_YUY2:
break;
default:
break;
}
UNREACHABLE();
return GL_NONE;
}
} // namespace d3d11
namespace d3d11_angle
{
const Format &GetFormat(DXGI_FORMAT dxgiFormat)
{
switch (dxgiFormat)
{
case DXGI_FORMAT_420_OPAQUE:
break;
case DXGI_FORMAT_A8P8:
break;
case DXGI_FORMAT_A8_UNORM:
return Format::Get(Format::ID::A8_UNORM);
case DXGI_FORMAT_AI44:
break;
case DXGI_FORMAT_AYUV:
break;
case DXGI_FORMAT_B4G4R4A4_UNORM:
return Format::Get(Format::ID::B4G4R4A4_UNORM);
case DXGI_FORMAT_B5G5R5A1_UNORM:
return Format::Get(Format::ID::B5G5R5A1_UNORM);
case DXGI_FORMAT_B5G6R5_UNORM:
return Format::Get(Format::ID::B5G6R5_UNORM);
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
break;
case DXGI_FORMAT_B8G8R8A8_UNORM:
return Format::Get(Format::ID::B8G8R8A8_UNORM);
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
break;
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
break;
case DXGI_FORMAT_B8G8R8X8_UNORM:
return Format::Get(Format::ID::B8G8R8X8_UNORM);
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
break;
case DXGI_FORMAT_BC1_TYPELESS:
break;
case DXGI_FORMAT_BC1_UNORM:
return Format::Get(Format::ID::BC1_RGBA_UNORM_BLOCK);
case DXGI_FORMAT_BC1_UNORM_SRGB:
return Format::Get(Format::ID::BC1_RGBA_UNORM_SRGB_BLOCK);
case DXGI_FORMAT_BC2_TYPELESS:
break;
case DXGI_FORMAT_BC2_UNORM:
return Format::Get(Format::ID::BC2_RGBA_UNORM_BLOCK);
case DXGI_FORMAT_BC2_UNORM_SRGB:
return Format::Get(Format::ID::BC2_RGBA_UNORM_SRGB_BLOCK);
case DXGI_FORMAT_BC3_TYPELESS:
break;
case DXGI_FORMAT_BC3_UNORM:
return Format::Get(Format::ID::BC3_RGBA_UNORM_BLOCK);
case DXGI_FORMAT_BC3_UNORM_SRGB:
return Format::Get(Format::ID::BC3_RGBA_UNORM_SRGB_BLOCK);
case DXGI_FORMAT_BC4_SNORM:
break;
case DXGI_FORMAT_BC4_TYPELESS:
break;
case DXGI_FORMAT_BC4_UNORM:
break;
case DXGI_FORMAT_BC5_SNORM:
break;
case DXGI_FORMAT_BC5_TYPELESS:
break;
case DXGI_FORMAT_BC5_UNORM:
break;
case DXGI_FORMAT_BC6H_SF16:
break;
case DXGI_FORMAT_BC6H_TYPELESS:
break;
case DXGI_FORMAT_BC6H_UF16:
break;
case DXGI_FORMAT_BC7_TYPELESS:
break;
case DXGI_FORMAT_BC7_UNORM:
break;
case DXGI_FORMAT_BC7_UNORM_SRGB:
break;
case DXGI_FORMAT_D16_UNORM:
return Format::Get(Format::ID::D16_UNORM);
case DXGI_FORMAT_D24_UNORM_S8_UINT:
return Format::Get(Format::ID::D24_UNORM_S8_UINT);
case DXGI_FORMAT_D32_FLOAT:
return Format::Get(Format::ID::D32_FLOAT);
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
return Format::Get(Format::ID::D32_FLOAT_S8X24_UINT);
case DXGI_FORMAT_G8R8_G8B8_UNORM:
break;
case DXGI_FORMAT_IA44:
break;
case DXGI_FORMAT_NV11:
break;
case DXGI_FORMAT_NV12:
break;
case DXGI_FORMAT_P010:
break;
case DXGI_FORMAT_P016:
break;
case DXGI_FORMAT_P8:
break;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
break;
case DXGI_FORMAT_R10G10B10A2_UINT:
return Format::Get(Format::ID::R10G10B10A2_UINT);
case DXGI_FORMAT_R10G10B10A2_UNORM:
return Format::Get(Format::ID::R10G10B10A2_UNORM);
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
break;
case DXGI_FORMAT_R11G11B10_FLOAT:
return Format::Get(Format::ID::R11G11B10_FLOAT);
case DXGI_FORMAT_R16G16B16A16_FLOAT:
return Format::Get(Format::ID::R16G16B16A16_FLOAT);
case DXGI_FORMAT_R16G16B16A16_SINT:
return Format::Get(Format::ID::R16G16B16A16_SINT);
case DXGI_FORMAT_R16G16B16A16_SNORM:
return Format::Get(Format::ID::R16G16B16A16_SNORM);
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
break;
case DXGI_FORMAT_R16G16B16A16_UINT:
return Format::Get(Format::ID::R16G16B16A16_UINT);
case DXGI_FORMAT_R16G16B16A16_UNORM:
return Format::Get(Format::ID::R16G16B16A16_UNORM);
case DXGI_FORMAT_R16G16_FLOAT:
return Format::Get(Format::ID::R16G16_FLOAT);
case DXGI_FORMAT_R16G16_SINT:
return Format::Get(Format::ID::R16G16_SINT);
case DXGI_FORMAT_R16G16_SNORM:
return Format::Get(Format::ID::R16G16_SNORM);
case DXGI_FORMAT_R16G16_TYPELESS:
break;
case DXGI_FORMAT_R16G16_UINT:
return Format::Get(Format::ID::R16G16_UINT);
case DXGI_FORMAT_R16G16_UNORM:
return Format::Get(Format::ID::R16G16_UNORM);
case DXGI_FORMAT_R16_FLOAT:
return Format::Get(Format::ID::R16_FLOAT);
case DXGI_FORMAT_R16_SINT:
return Format::Get(Format::ID::R16_SINT);
case DXGI_FORMAT_R16_SNORM:
return Format::Get(Format::ID::R16_SNORM);
case DXGI_FORMAT_R16_TYPELESS:
break;
case DXGI_FORMAT_R16_UINT:
return Format::Get(Format::ID::R16_UINT);
case DXGI_FORMAT_R16_UNORM:
return Format::Get(Format::ID::R16_UNORM);
case DXGI_FORMAT_R1_UNORM:
break;
case DXGI_FORMAT_R24G8_TYPELESS:
break;
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
return Format::Get(Format::ID::R32G32B32A32_FLOAT);
case DXGI_FORMAT_R32G32B32A32_SINT:
return Format::Get(Format::ID::R32G32B32A32_SINT);
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
break;
case DXGI_FORMAT_R32G32B32A32_UINT:
return Format::Get(Format::ID::R32G32B32A32_UINT);
case DXGI_FORMAT_R32G32B32_FLOAT:
return Format::Get(Format::ID::R32G32B32_FLOAT);
case DXGI_FORMAT_R32G32B32_SINT:
return Format::Get(Format::ID::R32G32B32_SINT);
case DXGI_FORMAT_R32G32B32_TYPELESS:
break;
case DXGI_FORMAT_R32G32B32_UINT:
return Format::Get(Format::ID::R32G32B32_UINT);
case DXGI_FORMAT_R32G32_FLOAT:
return Format::Get(Format::ID::R32G32_FLOAT);
case DXGI_FORMAT_R32G32_SINT:
return Format::Get(Format::ID::R32G32_SINT);
case DXGI_FORMAT_R32G32_TYPELESS:
break;
case DXGI_FORMAT_R32G32_UINT:
return Format::Get(Format::ID::R32G32_UINT);
case DXGI_FORMAT_R32G8X24_TYPELESS:
break;
case DXGI_FORMAT_R32_FLOAT:
return Format::Get(Format::ID::R32_FLOAT);
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
break;
case DXGI_FORMAT_R32_SINT:
return Format::Get(Format::ID::R32_SINT);
case DXGI_FORMAT_R32_TYPELESS:
break;
case DXGI_FORMAT_R32_UINT:
return Format::Get(Format::ID::R32_UINT);
case DXGI_FORMAT_R8G8B8A8_SINT:
return Format::Get(Format::ID::R8G8B8A8_SINT);
case DXGI_FORMAT_R8G8B8A8_SNORM:
return Format::Get(Format::ID::R8G8B8A8_SNORM);
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
break;
case DXGI_FORMAT_R8G8B8A8_UINT:
return Format::Get(Format::ID::R8G8B8A8_UINT);
case DXGI_FORMAT_R8G8B8A8_UNORM:
return Format::Get(Format::ID::R8G8B8A8_UNORM);
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
return Format::Get(Format::ID::R8G8B8A8_UNORM_SRGB);
case DXGI_FORMAT_R8G8_B8G8_UNORM:
break;
case DXGI_FORMAT_R8G8_SINT:
return Format::Get(Format::ID::R8G8_SINT);
case DXGI_FORMAT_R8G8_SNORM:
return Format::Get(Format::ID::R8G8_SNORM);
case DXGI_FORMAT_R8G8_TYPELESS:
break;
case DXGI_FORMAT_R8G8_UINT:
return Format::Get(Format::ID::R8G8_UINT);
case DXGI_FORMAT_R8G8_UNORM:
return Format::Get(Format::ID::R8G8_UNORM);
case DXGI_FORMAT_R8_SINT:
return Format::Get(Format::ID::R8_SINT);
case DXGI_FORMAT_R8_SNORM:
return Format::Get(Format::ID::R8_SNORM);
case DXGI_FORMAT_R8_TYPELESS:
break;
case DXGI_FORMAT_R8_UINT:
return Format::Get(Format::ID::R8_UINT);
case DXGI_FORMAT_R8_UNORM:
return Format::Get(Format::ID::R8_UNORM);
case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
return Format::Get(Format::ID::R9G9B9E5_SHAREDEXP);
case DXGI_FORMAT_UNKNOWN:
return Format::Get(Format::ID::NONE);
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
break;
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
break;
case DXGI_FORMAT_Y210:
break;
case DXGI_FORMAT_Y216:
break;
case DXGI_FORMAT_Y410:
break;
case DXGI_FORMAT_Y416:
break;
case DXGI_FORMAT_YUY2:
break;
default:
break;
}
UNREACHABLE();
return Format::Get(Format::ID::NONE);
}
} // namespace d3d11_angle
} // namespace rx
| 35.249516 | 79 | 0.63131 | kniefliu |
025a22a31abed79d345bca7e660f644db80de58c | 571 | cpp | C++ | Stack.cpp | nyugoh/STL | 3cd09e0be525e8951d7e28bc935fc0aa1971777c | [
"Apache-2.0"
] | null | null | null | Stack.cpp | nyugoh/STL | 3cd09e0be525e8951d7e28bc935fc0aa1971777c | [
"Apache-2.0"
] | null | null | null | Stack.cpp | nyugoh/STL | 3cd09e0be525e8951d7e28bc935fc0aa1971777c | [
"Apache-2.0"
] | null | null | null | #include <stack>
#include <iostream>
using namespace std;
int main(){
stack<string> applications;
//Adding elements to the stack
applications.push("ASPOF-3435");
applications.push("AAKJDH2399");
applications.push("ADXKJQ2332");
applications.push("ASDWWE232");
applications.push("ASKLD923");
std::cout << "Use applications.pop() to remove the top element." << '\n';
std::cout << "Use applications.top() to return the top element." << '\n';
std::cout << "The first element :: "<< applications.top() << '\n';
return 0;
}
| 25.954545 | 77 | 0.635727 | nyugoh |
025c838c9c4d9c10d39fba29bcf3d162ddd6a3e5 | 9,957 | cpp | C++ | gtsam_unstable/dynamics/tests/testPoseRTV.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 1,402 | 2017-03-28T00:18:11.000Z | 2022-03-30T10:28:32.000Z | gtsam_unstable/dynamics/tests/testPoseRTV.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 851 | 2017-11-27T15:09:56.000Z | 2022-03-31T22:26:38.000Z | gtsam_unstable/dynamics/tests/testPoseRTV.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 565 | 2017-11-30T16:15:59.000Z | 2022-03-31T02:53:04.000Z | /**
* @file testPoseRTV
* @author Alex Cunningham
*/
#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/Testable.h>
#include <gtsam/base/TestableAssertions.h>
#include <gtsam/base/numericalDerivative.h>
#include <gtsam_unstable/dynamics/PoseRTV.h>
using namespace gtsam;
GTSAM_CONCEPT_TESTABLE_INST(PoseRTV)
GTSAM_CONCEPT_LIE_INST(PoseRTV)
static const Rot3 rot = Rot3::RzRyRx(0.1, 0.2, 0.3);
static const Point3 pt(1.0, 2.0, 3.0);
static const Velocity3 vel(0.4, 0.5, 0.6);
static const Vector3 kZero3 = Vector3::Zero();
/* ************************************************************************* */
TEST( testPoseRTV, constructors ) {
PoseRTV state1(pt, rot, vel);
EXPECT(assert_equal(pt, state1.t()));
EXPECT(assert_equal(rot, state1.R()));
EXPECT(assert_equal(vel, state1.v()));
EXPECT(assert_equal(Pose3(rot, pt), state1.pose()));
PoseRTV state2;
EXPECT(assert_equal(Point3(0,0,0), state2.t()));
EXPECT(assert_equal(Rot3(), state2.R()));
EXPECT(assert_equal(kZero3, state2.v()));
EXPECT(assert_equal(Pose3(), state2.pose()));
PoseRTV state3(Pose3(rot, pt), vel);
EXPECT(assert_equal(pt, state3.t()));
EXPECT(assert_equal(rot, state3.R()));
EXPECT(assert_equal(vel, state3.v()));
EXPECT(assert_equal(Pose3(rot, pt), state3.pose()));
PoseRTV state4(Pose3(rot, pt));
EXPECT(assert_equal(pt, state4.t()));
EXPECT(assert_equal(rot, state4.R()));
EXPECT(assert_equal(kZero3, state4.v()));
EXPECT(assert_equal(Pose3(rot, pt), state4.pose()));
Vector vec_init = (Vector(9) << 0.1, 0.2, 0.3, 1.0, 2.0, 3.0, 0.4, 0.5, 0.6).finished();
PoseRTV state5(vec_init);
EXPECT(assert_equal(pt, state5.t()));
EXPECT(assert_equal(rot, state5.R()));
EXPECT(assert_equal(vel, state5.v()));
EXPECT(assert_equal(vec_init, state5.vector()));
}
/* ************************************************************************* */
TEST( testPoseRTV, dim ) {
PoseRTV state1(pt, rot, vel);
EXPECT_LONGS_EQUAL(9, state1.dim());
EXPECT_LONGS_EQUAL(9, PoseRTV::Dim());
}
/* ************************************************************************* */
TEST( testPoseRTV, equals ) {
PoseRTV state1, state2(pt, rot, vel), state3(state2), state4(Pose3(rot, pt));
EXPECT(assert_equal(state1, state1));
EXPECT(assert_equal(state2, state3));
EXPECT(assert_equal(state3, state2));
EXPECT(assert_inequal(state1, state2));
EXPECT(assert_inequal(state2, state1));
EXPECT(assert_inequal(state2, state4));
}
/* ************************************************************************* */
TEST( testPoseRTV, Lie ) {
// origin and zero deltas
PoseRTV identity;
EXPECT(assert_equal(identity, (PoseRTV)identity.retract(Z_9x1)));
EXPECT(assert_equal((Vector) Z_9x1, identity.localCoordinates(identity)));
PoseRTV state1(pt, rot, vel);
EXPECT(assert_equal(state1, (PoseRTV)state1.retract(Z_9x1)));
EXPECT(assert_equal((Vector) Z_9x1, state1.localCoordinates(state1)));
Vector delta(9);
delta << 0.1, 0.1, 0.1, 0.2, 0.3, 0.4,-0.1,-0.2,-0.3;
Pose3 pose2 = Pose3(rot, pt).retract(delta.head<6>());
Velocity3 vel2 = vel + Velocity3(-0.1, -0.2, -0.3);
PoseRTV state2(pose2.translation(), pose2.rotation(), vel2);
EXPECT(assert_equal(state2, (PoseRTV)state1.retract(delta)));
EXPECT(assert_equal(delta, state1.localCoordinates(state2)));
// roundtrip from state2 to state3 and back
PoseRTV state3 = state2.retract(delta);
EXPECT(assert_equal(delta, state2.localCoordinates(state3)));
// roundtrip from state3 to state4 and back, with expmap.
PoseRTV state4 = state3.expmap(delta);
EXPECT(assert_equal(delta, state3.logmap(state4)));
// For the expmap/logmap (not necessarily retract/local) -delta goes other way
EXPECT(assert_equal(state3, (PoseRTV)state4.expmap(-delta)));
EXPECT(assert_equal(delta, -state4.logmap(state3)));
}
/* ************************************************************************* */
TEST( testPoseRTV, dynamics_identities ) {
// general dynamics should produce the same measurements as the imuPrediction function
PoseRTV x0, x1, x2, x3, x4;
const double dt = 0.1;
Vector accel = Vector3(0.2, 0.0, 0.0), gyro = Vector3(0.0, 0.0, 0.2);
Vector imu01 = Z_6x1, imu12 = Z_6x1, imu23 = Z_6x1, imu34 = Z_6x1;
x1 = x0.generalDynamics(accel, gyro, dt);
x2 = x1.generalDynamics(accel, gyro, dt);
x3 = x2.generalDynamics(accel, gyro, dt);
x4 = x3.generalDynamics(accel, gyro, dt);
// EXPECT(assert_equal(imu01, x0.imuPrediction(x1, dt).first));
// EXPECT(assert_equal(imu12, x1.imuPrediction(x2, dt).first));
// EXPECT(assert_equal(imu23, x2.imuPrediction(x3, dt).first));
// EXPECT(assert_equal(imu34, x3.imuPrediction(x4, dt).first));
//
// EXPECT(assert_equal(x1.translation(), x0.imuPrediction(x1, dt).second));
// EXPECT(assert_equal(x2.translation(), x1.imuPrediction(x2, dt).second));
// EXPECT(assert_equal(x3.translation(), x2.imuPrediction(x3, dt).second));
// EXPECT(assert_equal(x4.translation(), x3.imuPrediction(x4, dt).second));
}
/* ************************************************************************* */
PoseRTV compose_proxy(const PoseRTV& A, const PoseRTV& B) { return A.compose(B); }
TEST( testPoseRTV, compose ) {
PoseRTV state1(pt, rot, vel), state2 = state1;
Matrix actH1, actH2;
state1.compose(state2, actH1, actH2);
Matrix numericH1 = numericalDerivative21(compose_proxy, state1, state2);
Matrix numericH2 = numericalDerivative22(compose_proxy, state1, state2);
EXPECT(assert_equal(numericH1, actH1));
EXPECT(assert_equal(numericH2, actH2));
}
/* ************************************************************************* */
PoseRTV between_proxy(const PoseRTV& A, const PoseRTV& B) { return A.between(B); }
TEST( testPoseRTV, between ) {
PoseRTV state1(pt, rot, vel), state2 = state1;
Matrix actH1, actH2;
state1.between(state2, actH1, actH2);
Matrix numericH1 = numericalDerivative21(between_proxy, state1, state2);
Matrix numericH2 = numericalDerivative22(between_proxy, state1, state2);
EXPECT(assert_equal(numericH1, actH1));
EXPECT(assert_equal(numericH2, actH2));
}
/* ************************************************************************* */
PoseRTV inverse_proxy(const PoseRTV& A) { return A.inverse(); }
TEST( testPoseRTV, inverse ) {
PoseRTV state1(pt, rot, vel);
Matrix actH1;
state1.inverse(actH1);
Matrix numericH1 = numericalDerivative11(inverse_proxy, state1);
EXPECT(assert_equal(numericH1, actH1));
}
/* ************************************************************************* */
double range_proxy(const PoseRTV& A, const PoseRTV& B) { return A.range(B); }
TEST( testPoseRTV, range ) {
Point3 tA(1.0, 2.0, 3.0), tB(3.0, 2.0, 3.0);
PoseRTV rtvA(tA), rtvB(tB);
EXPECT_DOUBLES_EQUAL(0.0, rtvA.range(rtvA), 1e-9);
EXPECT_DOUBLES_EQUAL(2.0, rtvA.range(rtvB), 1e-9);
EXPECT_DOUBLES_EQUAL(2.0, rtvB.range(rtvA), 1e-9);
Matrix actH1, actH2;
rtvA.range(rtvB, actH1, actH2);
Matrix numericH1 = numericalDerivative21(range_proxy, rtvA, rtvB);
Matrix numericH2 = numericalDerivative22(range_proxy, rtvA, rtvB);
EXPECT(assert_equal(numericH1, actH1));
EXPECT(assert_equal(numericH2, actH2));
}
/* ************************************************************************* */
PoseRTV transformed_from_proxy(const PoseRTV& a, const Pose3& trans) {
return a.transformed_from(trans);
}
TEST( testPoseRTV, transformed_from_1 ) {
Rot3 R = Rot3::Rodrigues(0.1, 0.2, 0.3);
Point3 T(1.0, 2.0, 3.0);
Velocity3 V(2.0, 3.0, 4.0);
PoseRTV start(R, T, V);
Pose3 transform(Rot3::Yaw(M_PI_2), Point3(1.0, 2.0, 3.0));
Matrix actDTrans, actDGlobal;
PoseRTV actual = start.transformed_from(transform, actDGlobal, actDTrans);
PoseRTV expected(transform.compose(start.pose()), transform.rotation().matrix() * V);
EXPECT(assert_equal(expected, actual));
Matrix numDGlobal = numericalDerivative21(transformed_from_proxy, start, transform, 1e-5); // At 1e-8, fails
Matrix numDTrans = numericalDerivative22(transformed_from_proxy, start, transform, 1e-8); // Sensitive to step size
EXPECT(assert_equal(numDGlobal, actDGlobal));
EXPECT(assert_equal(numDTrans, actDTrans, 1e-5)); // FIXME: still needs analytic derivative
}
/* ************************************************************************* */
TEST( testPoseRTV, transformed_from_2 ) {
Rot3 R;
Point3 T(1.0, 2.0, 3.0);
Velocity3 V(2.0, 3.0, 4.0);
PoseRTV start(R, T, V);
Pose3 transform(Rot3::Yaw(M_PI_2), Point3(1.0, 2.0, 3.0));
Matrix actDTrans, actDGlobal;
PoseRTV actual = start.transformed_from(transform, actDGlobal, actDTrans);
PoseRTV expected(transform.compose(start.pose()), transform.rotation().matrix() * V);
EXPECT(assert_equal(expected, actual));
Matrix numDGlobal = numericalDerivative21(transformed_from_proxy, start, transform, 1e-5); // At 1e-8, fails
Matrix numDTrans = numericalDerivative22(transformed_from_proxy, start, transform, 1e-8); // Sensitive to step size
EXPECT(assert_equal(numDGlobal, actDGlobal));
EXPECT(assert_equal(numDTrans, actDTrans, 1e-5)); // FIXME: still needs analytic derivative
}
/* ************************************************************************* */
TEST(testPoseRTV, RRTMbn) {
EXPECT(assert_equal(I_3x3, PoseRTV::RRTMbn(kZero3)));
EXPECT(assert_equal(I_3x3, PoseRTV::RRTMbn(Rot3())));
EXPECT(assert_equal(PoseRTV::RRTMbn(Vector3(0.3, 0.2, 0.1)), PoseRTV::RRTMbn(Rot3::Ypr(0.1, 0.2, 0.3))));
}
/* ************************************************************************* */
TEST(testPoseRTV, RRTMnb) {
EXPECT(assert_equal(I_3x3, PoseRTV::RRTMnb(kZero3)));
EXPECT(assert_equal(I_3x3, PoseRTV::RRTMnb(Rot3())));
EXPECT(assert_equal(PoseRTV::RRTMnb(Vector3(0.3, 0.2, 0.1)), PoseRTV::RRTMnb(Rot3::Ypr(0.1, 0.2, 0.3))));
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
/* ************************************************************************* */
| 40.47561 | 117 | 0.629306 | kvmanohar22 |
025db52336b789ba6b08c8a68415287dcddffdec | 2,699 | hpp | C++ | septem/include/communication.hpp | CalielOfSeptem/septem | fe7a615eb6c279d3746ee78de8864b5e07bf7e3e | [
"MIT"
] | 1 | 2017-03-30T14:31:33.000Z | 2017-03-30T14:31:33.000Z | septem/include/communication.hpp | HoraceWeebler/septem | fe7a615eb6c279d3746ee78de8864b5e07bf7e3e | [
"MIT"
] | null | null | null | septem/include/communication.hpp | HoraceWeebler/septem | fe7a615eb6c279d3746ee78de8864b5e07bf7e3e | [
"MIT"
] | null | null | null |
// ==========================================================================
#ifndef SE7EN_COMMUNICATION_HPP_
#define SE7EN_COMMUNICATION_HPP_
#include <string>
#include <boost/shared_ptr.hpp>
namespace terminalpp {
class string;
}
class client;
class world_context;
//* =========================================================================
/// \brief Send a text message to all connected players.
//* =========================================================================
void send_to_all(
boost::shared_ptr<world_context> &ctx
, std::string const &text);
//* =========================================================================
/// \brief Send a text message to all connected players.
//* =========================================================================
void send_to_all(
std::shared_ptr<world_context> &ctx
, terminalpp::string const &text);
//* =========================================================================
/// \brief Send a text message to a single player.
//* =========================================================================
void send_to_player(
std::shared_ptr<world_context> &ctx
, char const *text
, std::shared_ptr< client >& player);
//* =========================================================================
/// \brief Send a text message to a single player.
//* =========================================================================
void send_to_player(
std::shared_ptr<world_context> &ctx
, std::string const &text
, std::shared_ptr<client> &player);
//* =========================================================================
/// \brief Send a text message to a single player.
//* ========================================================================
void send_to_player(
std::shared_ptr<world_context> &ctx
, terminalpp::string const &text
, std::shared_ptr<client> &player);
//* =========================================================================
/// \brief Send a text message to all players in the same room as player,
/// but not to player.
//* =========================================================================
void send_to_room(
std::shared_ptr<world_context> &ctx
, std::string const &text
, std::shared_ptr<client> &player);
//* =========================================================================
/// \brief Send a text message to all players in the same room as player,
/// but not to player.
//* =========================================================================
void send_to_room(
std::shared_ptr<world_context> &ctx
, terminalpp::string const &text
, std::shared_ptr<client> &player);
#endif
| 34.164557 | 77 | 0.399407 | CalielOfSeptem |
025ffbb15475ed2d03edf32bfe3b9fbf87e589d8 | 2,708 | hpp | C++ | src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp | LittleQili/nnfusion | 6c1a25db5be459a1053798f1c75bfbd26863ed08 | [
"MIT"
] | 1 | 2021-05-14T08:10:30.000Z | 2021-05-14T08:10:30.000Z | src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp | LittleQili/nnfusion | 6c1a25db5be459a1053798f1c75bfbd26863ed08 | [
"MIT"
] | null | null | null | src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp | LittleQili/nnfusion | 6c1a25db5be459a1053798f1c75bfbd26863ed08 | [
"MIT"
] | 1 | 2021-08-11T09:09:53.000Z | 2021-08-11T09:09:53.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "nnfusion/common/common.hpp"
#include "nnfusion/common/languageunit.hpp"
#include "nnfusion/core/kernels/antares_ke_imp.hpp"
#include "nnfusion/core/kernels/kernel_emitter.hpp"
#include "nnfusion/core/operators/generic_op/generic_op.hpp"
DECLARE_string(fantares_codegen_server);
namespace nnfusion
{
namespace kernels
{
namespace hlsl
{
class HLSLKernelEmitter : public KernelEmitter
{
public:
HLSLKernelEmitter(shared_ptr<KernelContext> ctx)
: KernelEmitter(ctx, "hlsl")
{
}
virtual LanguageUnit_p emit_dependency() override;
};
class AntaresHLSLKernelEmitter : public HLSLKernelEmitter
{
public:
AntaresHLSLKernelEmitter(shared_ptr<KernelContext> ctx)
: HLSLKernelEmitter(ctx)
, m_antares_ke_imp(new AntaresKEImp)
{
if (!FLAGS_fantares_codegen_server.empty())
{
ir = nnfusion::op::get_translation_v2(ctx->gnode);
if (ir.empty())
ir = nnfusion::op::get_translation(ctx->gnode);
if (!ir.empty())
{
const char annotation[] = "## @annotation: ";
int pos = ir.find(annotation);
if (pos >= 0)
{
pos += sizeof(annotation) - 1;
options = ir.substr(pos);
}
if (options.size() > 0)
{
if (options[0] != '|')
options = "|" + options;
if (options.back() != '|')
options += "|";
}
auto info = m_antares_ke_imp->autogen(ir);
antares_code = info.first;
m_is_tuned = info.second;
}
}
}
virtual LanguageUnit_p emit_function_body() override;
virtual LanguageUnit_p emit_function_call() override;
AntaresKEImp::Pointer m_antares_ke_imp;
std::string antares_code;
protected:
std::string ir, options;
};
}
}
}
| 34.717949 | 75 | 0.441654 | LittleQili |
02627f9072997ed6493369ed68e83e6b5db55726 | 25 | hh | C++ | include/trick/compat/trick_utils/units/include/UCFn.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 647 | 2015-05-07T16:08:16.000Z | 2022-03-30T02:33:21.000Z | include/trick/compat/trick_utils/units/include/UCFn.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 995 | 2015-04-30T19:44:31.000Z | 2022-03-31T20:14:44.000Z | include/trick/compat/trick_utils/units/include/UCFn.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 251 | 2015-05-15T09:24:34.000Z | 2022-03-22T20:39:05.000Z | #include "trick/UCFn.hh"
| 12.5 | 24 | 0.72 | gilbertguoze |
026740d230641181e886680a0a7b6c846e76d76e | 1,286 | cpp | C++ | first_round/easy/test/test_add_two_nums_smartptr.cpp | forwardkth/leetcode | af1ecf96ca0630b2124f06b0527088f91ee2dafe | [
"MIT"
] | 1 | 2019-01-29T16:23:33.000Z | 2019-01-29T16:23:33.000Z | first_round/easy/test/test_add_two_nums_smartptr.cpp | forwardkth/leetcode | af1ecf96ca0630b2124f06b0527088f91ee2dafe | [
"MIT"
] | null | null | null | first_round/easy/test/test_add_two_nums_smartptr.cpp | forwardkth/leetcode | af1ecf96ca0630b2124f06b0527088f91ee2dafe | [
"MIT"
] | null | null | null | #include "../include/add_two_nums_smartptr.h"
#include <gtest/gtest.h>
//Google Test cases
TEST(AddTwoNums_sharedPtr_Test, testPos)
{
ListNodeShared* ls1 = new ListNodeShared(2);
ls1->next = make_shared<ListNodeShared>(4);
ls1->next->next = make_shared<ListNodeShared>(3);
ListNodeShared* ls2 = new ListNodeShared(5);
ls2->next = make_shared<ListNodeShared>(6);
ls2->next->next = make_shared<ListNodeShared>(4);
AddTwoNumsSolution2 ats2;
ListNodeShared* result2 = ats2.AddTwoNums(ls1, ls2);
EXPECT_EQ(7, result2->val);
EXPECT_EQ(0, result2->next->val);
EXPECT_EQ(8, result2->next->next->val);
EXPECT_NO_THROW(ats2.AddTwoNums(ls1, ls2));
}
TEST(AddTwoNums_fullySharedPtr_Test, testPos)
{
std::shared_ptr<ListNodeShared> ls1 = make_shared<ListNodeShared>(2);
ls1->next = make_shared<ListNodeShared>(4);
ls1->next->next = make_shared<ListNodeShared>(3);
std::shared_ptr<ListNodeShared> ls2 = make_shared<ListNodeShared>(5);
ls2->next = make_shared<ListNodeShared>(6);
ls2->next->next = make_shared<ListNodeShared>(4);
AddTwoNumsSolution3 ats3;
auto result3 = ats3.AddTwoNums(ls1, ls2);
EXPECT_EQ(7, result3->val);
EXPECT_EQ(0, result3->next->val);
EXPECT_EQ(8, result3->next->next->val);
EXPECT_NO_THROW(ats3.AddTwoNums(ls1, ls2));
}
| 31.365854 | 71 | 0.730949 | forwardkth |
026825fff62a84aa690ffc8b2b542b878f8483de | 3,545 | cpp | C++ | qink/CQInkscapeColorBar.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 5 | 2015-04-11T14:56:03.000Z | 2021-12-14T10:12:36.000Z | qink/CQInkscapeColorBar.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-04-20T19:23:15.000Z | 2021-09-03T20:03:30.000Z | qink/CQInkscapeColorBar.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-05-21T08:33:12.000Z | 2020-05-13T15:45:11.000Z | #include <CQInkscapeColorBar.h>
#include <CQInkscapeWindow.h>
#include <CSVGObject.h>
#include <CQUtil.h>
#include <QPainter>
#include <QMenu>
#include <QContextMenuEvent>
namespace CQInkscape {
ColorBar::
ColorBar(Window *window) :
QFrame(window), window_(window)
{
setObjectName("colorBar");
setContextMenuPolicy(Qt::DefaultContextMenu);
addPalettes();
}
void
ColorBar::
addPalettes()
{
ColorPalette lightPalette("Light Icon");
lightPalette.addColor(QColor( 84, 63, 124));
lightPalette.addColor(QColor(149, 116, 174));
lightPalette.addColor(QColor(244, 129, 50));
lightPalette.addColor(QColor(101, 153, 65));
lightPalette.addColor(QColor(126, 126, 141));
lightPalette.addColor(QColor(205, 191, 218));
lightPalette.addColor(QColor(207, 89, 89));
lightPalette.addColor(QColor( 2, 105, 165));
lightPalette.addColor(QColor(247, 234, 110));
lightPalette.addColor(QColor(255, 255, 255));
lightPalette.addColor(QColor( 0, 0, 0));
palettes_.push_back(lightPalette);
}
void
ColorBar::
mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
auto pos = e->pos();
int ind = (swatchWidth_ > 0.0 ? pos.x()/swatchWidth_ : 0.0);
//std::cerr << ind << "\n";
setFill(ind);
}
}
void
ColorBar::
setFill(int ind)
{
auto *obj = window_->currentObject();
if (obj) {
auto fill = obj->getFill();
auto c = (ind > 0 ? paletteColor(ind - 1) : Qt::transparent);
fill.setColor(CSVGFill::Color(CSVGColor(CQUtil::colorToRGBA(c))));
fill.setOpacity(CSVGFill::Opacity(c.alphaF()));
obj->setFill(fill);
window_->redraw(/*update*/true);
}
}
void
ColorBar::
setStroke(int ind)
{
auto *obj = window_->currentObject();
if (obj) {
auto stroke = obj->getStroke();
auto c = (ind > 0 ? paletteColor(ind - 1) : Qt::transparent);
stroke.setColor(CSVGStroke::Color(CSVGColor(CQUtil::colorToRGBA(c))));
stroke.setOpacity(CSVGFill::Opacity(c.alphaF()));
obj->setStroke(stroke);
window_->redraw(/*update*/true);
}
}
void
ColorBar::
contextMenuEvent(QContextMenuEvent *e)
{
auto *menu = new QMenu;
auto pos = e->pos();
menuInd_ = (swatchWidth_ > 0.0 ? pos.x()/swatchWidth_ : 0.0);
//---
auto *fillAction = menu->addAction("Set fill");
auto *strokeAction = menu->addAction("Set stroke");
connect(fillAction, SIGNAL(triggered()), this, SLOT(fillSlot()));
connect(strokeAction, SIGNAL(triggered()), this, SLOT(strokeSlot()));
//---
(void) menu->exec(e->globalPos());
delete menu;
}
void
ColorBar::
fillSlot()
{
setFill(menuInd_);
}
void
ColorBar::
strokeSlot()
{
setStroke(menuInd_);
}
void
ColorBar::
paintEvent(QPaintEvent *)
{
QPainter painter(this);
const auto &palette = palettes_[paletteNum_];
int n = palette.numColors() + 1;
swatchWidth_ = width()/n;
double x = 0.0;
for (int i = 0; i < n; ++i) {
auto rect = QRectF(x, 0, swatchWidth_, height());
if (i == 0) {
// transparent
painter.setBrush(Qt::white);
}
else {
const auto &c = paletteColor(i - 1);
painter.setBrush(c);
}
painter.fillRect(rect, painter.brush());
if (i == 0) {
QPen pen;
pen.setColor(Qt::red);
pen.setWidth(4);
painter.setPen(pen);
painter.drawLine(rect.topLeft(), rect.bottomRight());
painter.drawLine(rect.bottomLeft(), rect.topRight());
}
x += swatchWidth_;
}
}
QColor
ColorBar::
paletteColor(int i) const
{
const auto &palette = palettes_[paletteNum_];
return palette.color(i);
}
}
| 18.367876 | 74 | 0.643159 | colinw7 |
026d5be2cb1f5ab3247a0e0f36b008c1a18e59a0 | 4,124 | cpp | C++ | darwin/unix_adapter.cpp | mikecovlee/darwin | 000bcfd31994be860a422fe2fb11dbced408da72 | [
"Apache-2.0"
] | 20 | 2016-12-12T12:07:44.000Z | 2021-07-29T01:23:35.000Z | darwin/unix_adapter.cpp | mikecovlee/darwin | 000bcfd31994be860a422fe2fb11dbced408da72 | [
"Apache-2.0"
] | null | null | null | darwin/unix_adapter.cpp | mikecovlee/darwin | 000bcfd31994be860a422fe2fb11dbced408da72 | [
"Apache-2.0"
] | 7 | 2016-12-17T12:52:19.000Z | 2020-04-04T03:35:47.000Z | /*
* Covariant Darwin Universal Character Graphics Library
*
* 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.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*/
#include "./module.hpp"
#include "./graphics.hpp"
#include "./unix_conio.hpp"
#include <cstdio>
#include <string>
namespace darwin {
class unix_adapter : public platform_adapter {
bool mReady = false;
picture mDrawable;
public:
unix_adapter() = default;
virtual ~unix_adapter() = default;
virtual status get_state() const override
{
if (mReady)
return status::ready;
else
return status::leisure;
}
virtual results init() override
{
conio::reset();
//conio::clrscr();
conio::echo(false);
mReady = true;
return results::success;
}
virtual results stop() override
{
conio::reset();
//conio::clrscr();
conio::echo(true);
mReady = false;
return results::success;
}
virtual results exec_commands(commands c) override
{
switch (c) {
case commands::echo_on:
conio::echo(true);
break;
case commands::echo_off:
conio::echo(false);
break;
case commands::reset_cursor:
conio::gotoxy(0, 0);
break;
case commands::reset_attri:
conio::reset();
break;
case commands::clrscr:
conio::clrscr();
break;
}
return results::success;
}
virtual bool is_kb_hit() override
{
return conio::kbhit();
}
virtual int get_kb_hit() override
{
return conio::getch();
}
virtual results fit_drawable() override
{
mDrawable.resize(conio::terminal_width(), conio::terminal_height());
return results::success;
}
virtual drawable *get_drawable() override
{
return &mDrawable;
}
virtual results update_drawable() override
{
conio::gotoxy(0, 0);
std::size_t sw(std::min<std::size_t>(mDrawable.get_width(), conio::terminal_width())), sh(
std::min<std::size_t>(mDrawable.get_height(), conio::terminal_height()));
for (std::size_t y = 0; y < sh; ++y) {
for (std::size_t x = 0; x < sw; ++x) {
const pixel &pix = mDrawable.get_pixel(x, y);
std::string cmd = "\e[0m\e[";
switch (pix.get_front_color()) {
case colors::white:
cmd += "37;";
break;
case colors::black:
cmd += "30;";
break;
case colors::red:
cmd += "31;";
break;
case colors::green:
cmd += "32;";
break;
case colors::blue:
cmd += "34;";
break;
case colors::pink:
cmd += "35;";
break;
case colors::yellow:
cmd += "33;";
break;
case colors::cyan:
cmd += "36;";
break;
default:
return results::failure;
break;
}
switch (pix.get_back_color()) {
case colors::white:
cmd += "47";
break;
case colors::black:
cmd += "40";
break;
case colors::red:
cmd += "41";
break;
case colors::green:
cmd += "42";
break;
case colors::blue:
cmd += "44";
break;
case colors::pink:
cmd += "45";
break;
case colors::yellow:
cmd += "43";
break;
case colors::cyan:
cmd += "46";
break;
default:
return results::failure;
break;
}
if (pix.is_bright())
cmd += ";1";
if (pix.is_underline())
cmd += ";4";
cmd += "m";
printf("%s%c", cmd.c_str(), pix.get_char());
}
conio::reset();
printf("\n");
}
fflush(stdout);
return results::success;
}
} dunixadapter;
platform_adapter *module_resource()
{
return &dunixadapter;
}
}
| 21.591623 | 93 | 0.598206 | mikecovlee |
027276e2cd5dceec1f48b9c4a0df221cc6f05831 | 881 | cpp | C++ | dependency_graph_generator.cpp | YJDoc2/Makefile-Generator | 94780cee107ecc7286e80777f1a3beea615b00e5 | [
"MIT"
] | null | null | null | dependency_graph_generator.cpp | YJDoc2/Makefile-Generator | 94780cee107ecc7286e80777f1a3beea615b00e5 | [
"MIT"
] | null | null | null | dependency_graph_generator.cpp | YJDoc2/Makefile-Generator | 94780cee107ecc7286e80777f1a3beea615b00e5 | [
"MIT"
] | null | null | null | #include <set>
#include <list>
#include <fstream>
#include <iostream>
#include "./dependency_graph_generator.hpp"
using dgg = dependency_graph_generator;
dependency_graph dgg::get_dependency_graph(const std::string& f){
enqued.push_back(f);
while(!enqued.empty()){
std::string f = enqued.front();
enqued.pop_front();
visited.insert(f);
generate_dependencies(f);
}
return dg;
}
void dgg::generate_dependencies(const std::string& f){
reader r_code(f);
while(!r_code.is_done()){
std::string tmp = r_code.get_next_custom_dependency();
if(tmp.compare("")==0){
continue;
}
dg.add_dependency(f,tmp);
if(!is_visited(tmp)){
enqued.push_back(tmp);
}
}
}
bool dgg::is_visited(const std::string& f){
return (visited.find(f) != visited.end());
}
| 21.487805 | 65 | 0.61067 | YJDoc2 |
02727ceffbb8735c91c04cf170c1dd1741da86f4 | 528 | cc | C++ | ports/www/chromium-legacy/newport/files/patch-base_process_launch.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 31 | 2015-02-06T17:06:37.000Z | 2022-03-08T19:53:28.000Z | ports/www/chromium-legacy/newport/files/patch-base_process_launch.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 236 | 2015-06-29T19:51:17.000Z | 2021-12-16T22:46:38.000Z | ports/www/chromium-legacy/newport/files/patch-base_process_launch.cc | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 52 | 2015-02-06T17:05:36.000Z | 2021-10-21T12:13:06.000Z | --- base/process/launch.cc.orig 2020-11-13 06:36:34 UTC
+++ base/process/launch.cc
@@ -15,7 +15,7 @@ LaunchOptions::~LaunchOptions() = default;
LaunchOptions LaunchOptionsForTest() {
LaunchOptions options;
-#if defined(OS_LINUX) || defined(OS_CHROMEOS)
+#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
// To prevent accidental privilege sharing to an untrusted child, processes
// are started with PR_SET_NO_NEW_PRIVS. Do not set that here, since this
// new child will be used for testing only.
| 44 | 78 | 0.731061 | liweitianux |
02765f6ce6846b83230b64cf3eac7489f99e2786 | 4,972 | cpp | C++ | Samples/shell/src/Shell.cpp | inniyah/RmlUi | 35b1132d7d018cfca4f9f1836f0d059a8e795ecf | [
"MIT"
] | null | null | null | Samples/shell/src/Shell.cpp | inniyah/RmlUi | 35b1132d7d018cfca4f9f1836f0d059a8e795ecf | [
"MIT"
] | null | null | null | Samples/shell/src/Shell.cpp | inniyah/RmlUi | 35b1132d7d018cfca4f9f1836f0d059a8e795ecf | [
"MIT"
] | null | null | null | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "../include/Shell.h"
#include "../include/PlatformExtensions.h"
#include "../include/ShellFileInterface.h"
#include <RmlUi/Core/Context.h>
#include <RmlUi/Core/Core.h>
#include <RmlUi/Core/ElementDocument.h>
#include <RmlUi/Core/Input.h>
#include <RmlUi/Debugger.h>
static Rml::UniquePtr<ShellFileInterface> file_interface;
bool Shell::Initialize()
{
// Find the path to the 'Samples' directory.
Rml::String root = PlatformExtensions::FindSamplesRoot();
if (root.empty())
return false;
// The shell overrides the default file interface so that absolute paths in RML/RCSS-documents are relative to the 'Samples' directory.
file_interface = Rml::MakeUnique<ShellFileInterface>(root);
Rml::SetFileInterface(file_interface.get());
return true;
}
void Shell::Shutdown()
{
file_interface.reset();
}
void Shell::LoadFonts()
{
const Rml::String directory = "assets/";
struct FontFace {
const char* filename;
bool fallback_face;
};
FontFace font_faces[] = {
{"LatoLatin-Regular.ttf", false},
{"LatoLatin-Italic.ttf", false},
{"LatoLatin-Bold.ttf", false},
{"LatoLatin-BoldItalic.ttf", false},
{"NotoEmoji-Regular.ttf", true},
};
for (const FontFace& face : font_faces)
Rml::LoadFontFace(directory + face.filename, face.fallback_face);
}
bool Shell::ProcessKeyDownShortcuts(Rml::Context* context, Rml::Input::KeyIdentifier key, int key_modifier, float native_dp_ratio, bool priority)
{
if (!context)
return true;
// Result should return true to allow the event to propagate to the next handler.
bool result = false;
// This function is intended to be called twice by the backend, before and after submitting the key event to the context. This way we can
// intercept shortcuts that should take priority over the context, and then handle any shortcuts of lower priority if the context did not
// intercept it.
if (priority)
{
// Priority shortcuts are handled before submitting the key to the context.
// Toggle debugger and set dp-ratio using Ctrl +/-/0 keys.
if (key == Rml::Input::KI_F8)
{
Rml::Debugger::SetVisible(!Rml::Debugger::IsVisible());
}
else if (key == Rml::Input::KI_0 && key_modifier & Rml::Input::KM_CTRL)
{
context->SetDensityIndependentPixelRatio(native_dp_ratio);
}
else if (key == Rml::Input::KI_1 && key_modifier & Rml::Input::KM_CTRL)
{
context->SetDensityIndependentPixelRatio(1.f);
}
else if ((key == Rml::Input::KI_OEM_MINUS || key == Rml::Input::KI_SUBTRACT) && key_modifier & Rml::Input::KM_CTRL)
{
const float new_dp_ratio = Rml::Math::Max(context->GetDensityIndependentPixelRatio() / 1.2f, 0.5f);
context->SetDensityIndependentPixelRatio(new_dp_ratio);
}
else if ((key == Rml::Input::KI_OEM_PLUS || key == Rml::Input::KI_ADD) && key_modifier & Rml::Input::KM_CTRL)
{
const float new_dp_ratio = Rml::Math::Min(context->GetDensityIndependentPixelRatio() * 1.2f, 2.5f);
context->SetDensityIndependentPixelRatio(new_dp_ratio);
}
else
{
// Propagate the key down event to the context.
result = true;
}
}
else
{
// We arrive here when no priority keys are detected and the key was not consumed by the context. Check for shortcuts of lower priority.
if (key == Rml::Input::KI_R && key_modifier & Rml::Input::KM_CTRL)
{
for (int i = 0; i < context->GetNumDocuments(); i++)
{
Rml::ElementDocument* document = context->GetDocument(i);
const Rml::String& src = document->GetSourceURL();
if (src.size() > 4 && src.substr(src.size() - 4) == ".rml")
{
document->ReloadStyleSheet();
}
}
}
else
{
result = true;
}
}
return result;
}
| 34.054795 | 145 | 0.716412 | inniyah |
0276aff95eb79ef76baddcf8dac2319d4bf66be9 | 1,986 | cpp | C++ | parts/Drive.cpp | fdekruijff/Group-Project-TICT-V1GP-15 | ec1de58bf3e5f22066f563e0014760e54d779159 | [
"MIT"
] | null | null | null | parts/Drive.cpp | fdekruijff/Group-Project-TICT-V1GP-15 | ec1de58bf3e5f22066f563e0014760e54d779159 | [
"MIT"
] | null | null | null | parts/Drive.cpp | fdekruijff/Group-Project-TICT-V1GP-15 | ec1de58bf3e5f22066f563e0014760e54d779159 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <unistd.h>
#include "./piprograms/BrickPi3.cpp"
#include <thread>
#include <signal.h>
#include <vector>
using namespace std;
BrickPi3 BP;
uint8_t s_contrast = PORT_2; // Light sensor
uint8_t m_head = PORT_A; // Head motor
uint8_t m_left = PORT_B; // Left motor
uint8_t m_right = PORT_C; // Right motor
void exit_signal_handler(int signo);
//Stop
void stop(void){
BP.set_motor_power(m_right, 0);
BP.set_motor_power(m_left, 0);
}
//Drive
void dodge(int turn_drive, int degrees, int distance){
//Makes Wall-E turn and drive straight
int power =40;
if(turn_drive== 0){
BP.set_motor_limits(m_left,35,1200);
BP.set_motor_limits(m_right,35,1200);
BP.set_motor_position_relative(m_left,degrees*5.95);
BP.set_motor_position_relative(m_right,degrees*5.85*-1);
}else if(turn_drive==1){
if(distance < 0){
distance *= -1;
power *= -1;
}
BP.set_motor_power(m_left, power);
BP.set_motor_power(m_right, power);
usleep(76927*distance);
stop();
}
}
int main(){
signal(SIGINT, exit_signal_handler); // register the exit function for Ctrl+C
BP.detect(); // Make sure that the BrickPi3 is communicating and that the firmware is compatible with the drivers.
BP.set_motor_limits(PORT_B, 60, 0);
BP.set_motor_limits(PORT_C, 60, 0);
char inp;
while(true){
cout << "Press s (stop), d (drive): " << endl;
cin >> inp; //Take input from the terminal
if (inp=='d'){
//drive or steer, degrees, (rigth positive, left negative), distance
int turn_drive = 0;
int degrees = 90;
int distance =-10;
dodge(turn_drive, degrees, distance);
}else if (inp=='s'){
stop();
}
}
return 0;
}
// Signal handler that will be called when Ctrl+C is pressed to stop the program
void exit_signal_handler(int signo){
if(signo == SIGINT){
BP.reset_all(); // Reset everything so there are no run-away motors
exit(-2);
}
} | 24.219512 | 117 | 0.666163 | fdekruijff |
02773adfef90ebe52be74848f2315ef64a8c0346 | 1,822 | cpp | C++ | algorithms/recursion/twisted_tower_of_hanoi.cpp | adisakshya/dsa | 5b40eb339b19cdec95dcfc645516d725f0cb6c74 | [
"MIT"
] | null | null | null | algorithms/recursion/twisted_tower_of_hanoi.cpp | adisakshya/dsa | 5b40eb339b19cdec95dcfc645516d725f0cb6c74 | [
"MIT"
] | null | null | null | algorithms/recursion/twisted_tower_of_hanoi.cpp | adisakshya/dsa | 5b40eb339b19cdec95dcfc645516d725f0cb6c74 | [
"MIT"
] | null | null | null | /**
* Twisted Tower of Hanoi (Recursive)
*
* Twisted Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
* The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
* 1) Only one disk can be moved at a time.
* 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack
* i.e. a disk can only be moved if it is the uppermost disk on a stack.
* 3) No disk may be placed on top of a smaller disk.
* 4) No disk can be moved directly from first rod to last rod
*
* Complexity
* Time:
* Worst Case: 3^N
* Space: O(N)
*
*/
#include <bits/stdc++.h>
using namespace std;
// Function to solve Tower of Hanoi
void twisted_tower_of_hanoi(int disks, char from_rod, char to_rod, char aux_rod) {
// Base condition
if(disks == 1) {
cout << "Disk 1 moved from " << from_rod << " to " << aux_rod << endl;
cout << "Disk 1 moved from " << aux_rod << " to " << to_rod << endl;
return;
}
// shift n-1 disks from from_rod to to_rod
twisted_tower_of_hanoi(disks - 1, from_rod, to_rod, aux_rod);
cout << "Disk " << disks << " moved from " << from_rod << " to " << aux_rod << endl;
// shift n-1 disks from to_rod to from_rod
twisted_tower_of_hanoi(disks - 1, to_rod, from_rod, aux_rod);
cout << "Disk " << disks << " moved from " << aux_rod << " to " << to_rod << endl;
// shift n-1 from from_rod to to_rod
twisted_tower_of_hanoi(disks - 1, from_rod, to_rod, aux_rod);
}
int main() {
int number_of_disks = 2;
// A, B and C are name of rods
twisted_tower_of_hanoi(number_of_disks, 'A', 'C', 'B');
return 0;
} | 35.72549 | 117 | 0.608672 | adisakshya |
02776f948c5fa197561eef3d5f575f85a41e012e | 4,281 | cpp | C++ | ModuleProgram.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | ModuleProgram.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | ModuleProgram.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | #include "ModuleProgram.h"
#include "Application.h"
#include "ModuleImgui.h"
#include "Globals.h"
#include "MathGeoLib/include/Math/float4x4.h"
#include "SDL.h"
ModuleProgram::ModuleProgram()
{
}
ModuleProgram::~ModuleProgram()
{
}
bool ModuleProgram::Init()
{
App->imgui->AddLog("\nSHADERS.\n\n");
//init vertex shader
vs = createVertexShader(VERTEX_SHADER_PATH);
fs = createFragmentShader(FRAGMENT_SHADER_PATH);
defaultProgram = CreateProgram(vs, fs);
sceneProgram = CreateProgram(vs, fs);
//init skybox shader
skyboxVertexShader = App->program->createVertexShader("Game/Skybox.vs");
skyboxFragmentShader = App->program->createFragmentShader("Game/Skybox.fs");
skyboxProgram = CreateProgram(skyboxVertexShader, skyboxFragmentShader);
//set up the uniforms
setUniformsBuffer();
return true;
}
update_status ModuleProgram::PreUpdate()
{
return UPDATE_CONTINUE;
}
update_status ModuleProgram::Update()
{
return UPDATE_CONTINUE;
}
update_status ModuleProgram::PostUpdate()
{
return UPDATE_CONTINUE;
}
bool ModuleProgram::CleanUp()
{
App->imgui->AddLog("Deleting vertex shader\n");
glDeleteShader(vertex_shader);
App->imgui->AddLog("Deleting fragment shader\n");
glDeleteShader(fragment_shader);
return true;
}
GLuint ModuleProgram::CreateProgram(unsigned int vs, unsigned int fs)
{
//Creating shader program
shader_program = glCreateProgram();
//Attaching vertex shader to shader program
glAttachShader(shader_program, vertex_shader);
//Attaching fragment shader to shader program
glAttachShader(shader_program, fragment_shader);
//Linking shader program
glLinkProgram(shader_program);
GLint statusP = NULL;
char charP[512];
glGetProgramiv(shader_program, GL_LINK_STATUS, &statusP);
if (!statusP)
{
glGetProgramInfoLog(shader_program, 512, NULL, charP);
App->imgui->AddLog("Program created wrong, code: %s\n", charP);
}
return shader_program;
}
const char* ModuleProgram::loadFile(const char* file_name)
{
char* data = nullptr;
FILE* file = nullptr;
fopen_s(&file, file_name, "rb");
if (file)
{
fseek(file, 0, SEEK_END);
int size = ftell(file);
rewind(file);
data = (char*)malloc(size + 1);
fread(data, 1, size, file);
data[size] = 0;
fclose(file);
}
return data;
}
unsigned int ModuleProgram::createVertexShader(const char * filename)
{
assert(filename != NULL);
const char *vertex_shader_file = loadFile(VERTEX_SHADER_PATH);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_file, NULL);
delete vertex_shader_file;
glCompileShader(vertex_shader);
GLint statusV = NULL;
char charV[512];
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &statusV);
if(!statusV)
{
glGetShaderInfoLog(vertex_shader, 512, NULL, charV);
App->imgui->AddLog("Vertex shader created wrong, code: %s\n", charV);
}
else {
App->imgui->AddLog("Vertex shader created correctly.\n");
}
return vertex_shader;
}
unsigned int ModuleProgram::createFragmentShader(const char * filename)
{
assert(filename != NULL);
const char *fragment_shader_file = loadFile(FRAGMENT_SHADER_PATH);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_file, NULL);
delete fragment_shader_file;
glCompileShader(fragment_shader);
GLint statusF = NULL;
char charF[512];
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &statusF);
if (!statusF)
{
glGetShaderInfoLog(fragment_shader, 512, NULL, charF);
App->imgui->AddLog("Fragment shader created wrong, code: %s\n", charF);
}
else {
App->imgui->AddLog("Fragment shader created correctly.\n");
}
return fragment_shader;
}
void ModuleProgram::setUniformsBuffer()
{
unsigned int uniformBlockIndexDefault = glGetUniformBlockIndex(defaultProgram, "Matrices");
glUniformBlockBinding(defaultProgram, uniformBlockIndexDefault, 0);
unsigned int uniformSkybox = glGetUniformBlockIndex(skyboxProgram, "Skybox");
glUniformBlockBinding(skyboxProgram, uniformSkybox, 0);
glGenBuffers(1, &uniformsBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, uniformsBuffer);
glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(float4x4), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformsBuffer, 0, 2 * sizeof(float4x4));
} | 24.186441 | 92 | 0.759402 | raulgonzalezupc |
027819e961512efc5a5ec99005c2753ebcd04467 | 1,669 | cpp | C++ | velox/connectors/hive/tests/FileHandleTest.cpp | winningsix/velox-1 | 45c25f5ad58491ede2491b9406256535ce438b2d | [
"Apache-2.0"
] | null | null | null | velox/connectors/hive/tests/FileHandleTest.cpp | winningsix/velox-1 | 45c25f5ad58491ede2491b9406256535ce438b2d | [
"Apache-2.0"
] | null | null | null | velox/connectors/hive/tests/FileHandleTest.cpp | winningsix/velox-1 | 45c25f5ad58491ede2491b9406256535ce438b2d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "velox/connectors/hive/FileHandle.h"
#include <string>
#include "gtest/gtest.h"
#include "velox/common/caching/SimpleLRUCache.h"
#include "velox/common/file/File.h"
#include "velox/common/memory/Arena.h"
using namespace facebook::velox;
TEST(FileHandleTest, localFile) {
// TODO: use the appropriate test directory.
// Use unique name for each process/thread execution to prevent cross
// process/thread race condition
auto pid = getpid();
auto tid = pthread_self();
const std::string filename =
"/tmp/test" + std::to_string(pid) + "_" + std::to_string(tid);
remove(filename.data());
{
LocalWriteFile writeFile(filename);
writeFile.append("foo");
}
FileHandleFactory factory(
std::make_unique<SimpleLRUCache<std::string, FileHandle>>(1000),
std::make_unique<FileHandleGenerator>());
auto fileHandle = factory.generate(filename);
ASSERT_EQ(fileHandle->file->size(), 3);
Arena arena;
ASSERT_EQ(fileHandle->file->pread(0, 3, &arena), "foo");
// Clean up
remove(filename.data());
}
| 31.490566 | 75 | 0.714799 | winningsix |
02785cc1636955ff187ba94b3c6a64069cb80935 | 11,312 | cxx | C++ | main/autodoc/source/display/idl/hfi_linklist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/autodoc/source/display/idl/hfi_linklist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/autodoc/source/display/idl/hfi_linklist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <precomp.h>
#include "hfi_linklist.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary/idl/ip_type.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_doc.hxx"
#include "hfi_tag.hxx"
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
//******************* HF_CommentedLink_Table **********************************//
HF_CommentedLink_Table::HF_CommentedLink_Table( Environment & io_rEnv,
Xml::Element & o_rOut,
const String & i_sTitle,
const String & i_sLabel,
bool i_bBorder )
: HtmlFactory_Idl(io_rEnv,&o_rOut),
pTable( new Html::Table( (i_bBorder ? "1" : "0"), "100%", "5", "0") ),
pCurLinkColumn(0),
pCurCommentColumn(0)
{
*pTable
<< new Html::ClassAttr("commentedlinks");
CurOut()
>> *new Html::Label(i_sLabel)
<< new Html::LineBreak;
CurOut()
<< pTable;
// HF_SubTitle aTitle(*pTable);
// aTitle.Produce_it(i_sTitle);
}
HF_CommentedLink_Table::~HF_CommentedLink_Table()
{
}
void
HF_CommentedLink_Table::Add_Line()
{
Html::TableRow &
rRow = pTable->AddRow();
pCurLinkColumn = & (rRow.AddCell()
<< new Html::WidthAttr("30%")
<< new Xml::AnAttribute("valign","top") );
pCurCommentColumn = & rRow.AddCell();
}
Xml::Element &
HF_CommentedLink_Table::Cur_LinkColumn()
{
csv_assert(pCurLinkColumn != 0);
return *pCurLinkColumn;
}
Xml::Element &
HF_CommentedLink_Table::Cur_CommentColumn()
{
csv_assert(pCurCommentColumn != 0);
return *pCurCommentColumn;
}
//******************* HF_MemberTable **********************************//
HF_MemberTable::HF_MemberTable( Environment & io_rEnv,
Xml::Element & o_rOut,
const String & i_sTitle,
const String & i_sLabel,
bool i_bInline )
: HtmlFactory_Idl(io_rEnv,&o_rOut),
pTable( new Html::Table("1", "100%", "5", "0") ),
pCurDeclaration(0),
pCurDescription(0),
bInline(i_bInline)
{
*pTable
<< new Html::ClassAttr("memberlist");
CurOut()
>> *new Html::Label(i_sLabel)
<< new Html::LineBreak;
CurOut()
<< pTable;
// HF_SubTitle aTitle(*pTable);
// aTitle.Produce_it(i_sTitle);
}
HF_MemberTable::~HF_MemberTable()
{
}
void
HF_MemberTable::Add_Line()
{
if (bInline)
{
Html::TableRow & rRow = pTable->AddRow();
pCurDeclaration = &( rRow.AddCell()
<< new Xml::AnAttribute("valign","top")
<< new Html::WidthAttr("30%") );
pCurDescription = & rRow.AddCell();
}
else
{
Html::DefList *
pMemberSpace = new Html::DefList;
*pMemberSpace
<< new Html::ClassAttr("member");
pTable->AddRow().AddCell() << pMemberSpace;
pCurDeclaration =
& ( *pMemberSpace
>> *new Html::DefListTerm
<< new Html::ClassAttr("member") );
pCurDescription =
& ( *pMemberSpace
>> *new Html::DefListDefinition()
<< new Html::ClassAttr("member") );
}
}
Xml::Element &
HF_MemberTable::Cur_Declaration()
{
csv_assert(pCurDeclaration != 0);
return *pCurDeclaration;
}
Xml::Element &
HF_MemberTable::Cur_Description()
{
csv_assert(pCurDescription != 0);
return *pCurDescription;
}
//******************* HF_IdlLinkList **********************************//
HF_IdlLinkList::HF_IdlLinkList( Environment & io_rEnv,
Xml::Element * o_pOut )
: HtmlFactory_Idl(io_rEnv,o_pOut)
{
}
HF_IdlLinkList::~HF_IdlLinkList()
{
}
void
HF_IdlLinkList::Produce_NamespaceMembers( const String & i_sTitle,
const String & i_sLabel,
const std::vector<ary::idl::Ce_id> & i_rList,
bool i_bNestedNamespaces ) const
{
HF_CommentedLink_Table
aTableMaker( Env(), CurOut(),
i_sTitle, i_sLabel,
true );
std::vector<ary::idl::Ce_id>::const_iterator itEnd = i_rList.end();
for ( std::vector<ary::idl::Ce_id>::const_iterator it = i_rList.begin();
it != itEnd;
++it )
{
static String sEntryName;
static String sEntryLink;
const ce_info *
pDocu = 0;
Get_EntryData_NamespaceMembers( sEntryName, sEntryLink, pDocu, *it, i_bNestedNamespaces );
aTableMaker.Add_Line();
aTableMaker.Cur_LinkColumn()
>> *new Html::Link(sEntryLink)
<< sEntryName;
if ( pDocu != 0 )
{
HF_IdlShortDocu
aTextDisplay(Env(), aTableMaker.Cur_CommentColumn() );
aTextDisplay.Produce_byData( pDocu );
}
} // end for
}
void
HF_IdlLinkList::Produce_GlobalLinks( const String & i_sTitle,
const String & i_sLabel,
ce_list & i_rList ) const
{
HF_CommentedLink_Table
aTableMaker( Env(), CurOut(),
i_sTitle, i_sLabel,
true );
for ( ; i_rList; ++i_rList )
{
aTableMaker.Add_Line();
HF_IdlTypeText
aLinkText( Env(), aTableMaker.Cur_LinkColumn(), true );
aLinkText.Produce_byData(*i_rList);
const ce_info *
pDocu = Get_EntryDocu(*i_rList);
if ( pDocu != 0 )
{
HF_IdlShortDocu
aTextDisplay(Env(), aTableMaker.Cur_CommentColumn() );
aTextDisplay.Produce_byData( pDocu, *i_rList );
}
}
}
void
HF_IdlLinkList::Produce_GlobalCommentedLinks( const String & i_sTitle,
const String & i_sLabel,
comref_list & i_rList ) const
{
HF_CommentedLink_Table
aTableMaker( Env(), CurOut(),
i_sTitle, i_sLabel,
true );
/*
for ( ; i_rList; ++i_rList )
{
aTableMaker.Add_Line();
HF_IdlTypeText
aLinkText( Env(), aTableMaker.Cur_LinkColumn(), true );
aLinkText.Produce_byData( (*i_rList).first );
HF_DocEntryList
aDocList( aTableMaker.Cur_CommentColumn() );
if ( (*i_rList).second != 0 )
{
HF_IdlDocu
aDocuDisplay( Env(), aDocList );
aDocuDisplay.Produce_byData( (*i_rList).second );
}
else
{
const ce_info *
pShort = Get_EntryDocu(
Env().Gate().Types().Search_CeRelatedTo(
(*i_rList).first) );
if ( pShort != 0 )
{
if (pShort->IsDeprecated())
{
aDocList.Produce_Term()
<< "[ DEPRECATED ]";
}
if (pShort->IsOptional())
{
aDocList.Produce_Term()
<< "[ OPTIONAL ]";
}
aDocList.Produce_Term()
<< "Description";
HF_IdlDocuTextDisplay
aShortDisplay( Env(), &aDocList.Produce_Definition() );
aShortDisplay.Set_CurScopeTo(
Env().Gate().Types().Search_CeRelatedTo((*i_rList).first) );
pShort->Short().DisplayAt(aShortDisplay);
}
}
}
*/
}
void
HF_IdlLinkList::Produce_MemberLinks( const String & i_sTitle,
const String & i_sLabel,
ce_list & i_rList ) const
{
HF_CommentedLink_Table
aTableMaker( Env(), CurOut(),
i_sTitle, i_sLabel,
true );
/*
for ( ; i_rList; ++i_rList )
{
const ary::idl::CodeEntity &
rCe = Env().Gate().Ces().Find_Ce(*i_rList);
aTableMaker.Add_Line();
aTableMaker.Cur_LinkColumn()
>> *new Html::Link(
StreamLock(200)() << "#" << rCe.LocalName() << c_str)
<< rCe.LocalName();
const ce_info *
pDocu = rCe.Docu();
if ( pDocu != 0 )
{
HF_IdlShortDocu
aTextDisplay(Env(), aTableMaker.Cur_CommentColumn() );
aTextDisplay.Produce_byData( *pDocu );
}
} // end for
*/
}
void
HF_IdlLinkList::Get_EntryData_NamespaceMembers(
String & o_sEntryName,
String & o_sEntryLink,
const ce_info * & o_pDocu,
ce_id i_nMemberId,
bool i_bIsNestedNamespace ) const
{
const ary::idl::CodeEntity &
rCe = Env().Data().Find_Ce(i_nMemberId);
o_sEntryName = rCe.LocalName();
o_sEntryLink = StreamLock(200)() << rCe.LocalName()
<< ( i_bIsNestedNamespace
? "/module-ix"
: "" )
<< ".html"
<< c_str;
o_pDocu = rCe.Docu();
}
const ary::doc::OldIdlDocu *
HF_IdlLinkList::Get_EntryDocu(ce_id i_nMemberId) const
{
if (i_nMemberId.IsValid())
return Env().Data().Find_Ce(i_nMemberId).Docu();
else
return 0;
}
| 30.327078 | 107 | 0.487447 | Grosskopf |
027aef0ad172b889318d28bb09dbad2e6c8b0ee6 | 4,823 | cc | C++ | remoting/host/win/session_event_executor.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 2 | 2020-06-10T07:15:26.000Z | 2020-12-13T19:44:12.000Z | remoting/host/win/session_event_executor.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | remoting/host/win/session_event_executor.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/win/session_event_executor.h"
#include <string>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/win/windows_version.h"
#include "remoting/host/sas_injector.h"
#include "remoting/host/win/desktop.h"
#include "remoting/proto/event.pb.h"
namespace {
const uint32 kUsbLeftControl = 0x0700e0;
const uint32 kUsbRightControl = 0x0700e4;
const uint32 kUsbLeftAlt = 0x0700e2;
const uint32 kUsbRightAlt = 0x0700e6;
const uint32 kUsbDelete = 0x07004c;
bool CheckCtrlAndAltArePressed(const std::set<uint32>& pressed_keys) {
size_t ctrl_keys = pressed_keys.count(kUsbLeftControl) +
pressed_keys.count(kUsbRightControl);
size_t alt_keys = pressed_keys.count(kUsbLeftAlt) +
pressed_keys.count(kUsbRightAlt);
return ctrl_keys != 0 && alt_keys != 0 &&
(ctrl_keys + alt_keys == pressed_keys.size());
}
} // namespace
namespace remoting {
using protocol::ClipboardEvent;
using protocol::MouseEvent;
using protocol::KeyEvent;
SessionEventExecutorWin::SessionEventExecutorWin(
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
scoped_ptr<EventExecutor> nested_executor)
: nested_executor_(nested_executor.Pass()),
task_runner_(main_task_runner),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
weak_ptr_(weak_ptr_factory_.GetWeakPtr()) {
// Let |weak_ptr_| be used on the |task_runner_| thread.
// |weak_ptr_| and |weak_ptr_factory_| share a ThreadChecker, so the
// following line affects both of them.
weak_ptr_factory_.DetachFromThread();
}
SessionEventExecutorWin::~SessionEventExecutorWin() {
}
void SessionEventExecutorWin::Start(
scoped_ptr<protocol::ClipboardStub> client_clipboard) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&SessionEventExecutorWin::Start,
weak_ptr_, base::Passed(&client_clipboard)));
return;
}
nested_executor_->Start(client_clipboard.Pass());
}
void SessionEventExecutorWin::StopAndDelete() {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&SessionEventExecutorWin::StopAndDelete,
weak_ptr_));
return;
}
nested_executor_.release()->StopAndDelete();
delete this;
}
void SessionEventExecutorWin::InjectClipboardEvent(
const ClipboardEvent& event) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&SessionEventExecutorWin::InjectClipboardEvent,
weak_ptr_, event));
return;
}
nested_executor_->InjectClipboardEvent(event);
}
void SessionEventExecutorWin::InjectKeyEvent(const KeyEvent& event) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&SessionEventExecutorWin::InjectKeyEvent,
weak_ptr_, event));
return;
}
// HostEventDispatcher should drop events lacking the pressed field.
DCHECK(event.has_pressed());
if (event.has_usb_keycode()) {
if (event.pressed()) {
// Simulate secure attention sequence if Ctrl-Alt-Del was just pressed.
if (event.usb_keycode() == kUsbDelete &&
CheckCtrlAndAltArePressed(pressed_keys_)) {
VLOG(3) << "Sending Secure Attention Sequence to console";
if (sas_injector_.get() == NULL)
sas_injector_ = SasInjector::Create();
sas_injector_->InjectSas();
}
pressed_keys_.insert(event.usb_keycode());
} else {
pressed_keys_.erase(event.usb_keycode());
}
}
SwitchToInputDesktop();
nested_executor_->InjectKeyEvent(event);
}
void SessionEventExecutorWin::InjectMouseEvent(const MouseEvent& event) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&SessionEventExecutorWin::InjectMouseEvent,
weak_ptr_, event));
return;
}
SwitchToInputDesktop();
nested_executor_->InjectMouseEvent(event);
}
void SessionEventExecutorWin::SwitchToInputDesktop() {
// Switch to the desktop receiving user input if different from the current
// one.
scoped_ptr<Desktop> input_desktop = Desktop::GetInputDesktop();
if (input_desktop.get() != NULL && !desktop_.IsSame(*input_desktop)) {
// If SetThreadDesktop() fails, the thread is still assigned a desktop.
// So we can continue capture screen bits, just from a diffected desktop.
desktop_.SetThreadDesktop(input_desktop.Pass());
}
}
} // namespace remoting
| 30.719745 | 77 | 0.716774 | quisquous |
027bb391c109eb9866ead92e51ab438cc9d42def | 3,066 | cc | C++ | ecs/src/model/DescribeDiskMonitorDataRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | ecs/src/model/DescribeDiskMonitorDataRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | ecs/src/model/DescribeDiskMonitorDataRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ecs/model/DescribeDiskMonitorDataRequest.h>
using AlibabaCloud::Ecs::Model::DescribeDiskMonitorDataRequest;
DescribeDiskMonitorDataRequest::DescribeDiskMonitorDataRequest() :
RpcServiceRequest("ecs", "2014-05-26", "DescribeDiskMonitorData")
{
setMethod(HttpRequest::Method::Post);
}
DescribeDiskMonitorDataRequest::~DescribeDiskMonitorDataRequest()
{}
long DescribeDiskMonitorDataRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeDiskMonitorDataRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string DescribeDiskMonitorDataRequest::getStartTime()const
{
return startTime_;
}
void DescribeDiskMonitorDataRequest::setStartTime(const std::string& startTime)
{
startTime_ = startTime;
setParameter("StartTime", startTime);
}
std::string DescribeDiskMonitorDataRequest::getDiskId()const
{
return diskId_;
}
void DescribeDiskMonitorDataRequest::setDiskId(const std::string& diskId)
{
diskId_ = diskId;
setParameter("DiskId", diskId);
}
int DescribeDiskMonitorDataRequest::getPeriod()const
{
return period_;
}
void DescribeDiskMonitorDataRequest::setPeriod(int period)
{
period_ = period;
setParameter("Period", std::to_string(period));
}
std::string DescribeDiskMonitorDataRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DescribeDiskMonitorDataRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DescribeDiskMonitorDataRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DescribeDiskMonitorDataRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
std::string DescribeDiskMonitorDataRequest::getEndTime()const
{
return endTime_;
}
void DescribeDiskMonitorDataRequest::setEndTime(const std::string& endTime)
{
endTime_ = endTime;
setParameter("EndTime", endTime);
}
long DescribeDiskMonitorDataRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeDiskMonitorDataRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
| 25.983051 | 102 | 0.771363 | iamzken |
0280219b9443179587297e57704c87cc4b7aa7f2 | 1,644 | cpp | C++ | src/algorithm/Algorithm.cpp | oldas1/Riner | 492804079eb223e6d4ffd5f5f44283162eaf421b | [
"MIT"
] | null | null | null | src/algorithm/Algorithm.cpp | oldas1/Riner | 492804079eb223e6d4ffd5f5f44283162eaf421b | [
"MIT"
] | null | null | null | src/algorithm/Algorithm.cpp | oldas1/Riner | 492804079eb223e6d4ffd5f5f44283162eaf421b | [
"MIT"
] | null | null | null | //
//
#include "Algorithm.h"
#include "grin/AlgoCuckatoo31Cl.h"
#include "dummy/AlgoDummy.h"
#include "ethash/AlgoEthashCL.h"
#include <src/compute/DeviceId.h>
#include <src/pool/WorkEthash.h>
#include <src/pool/WorkCuckoo.h>
namespace miner {
/**
* Register all Algorithm implementations here.
* This is necessary so that the compiler includes the necessary code into a library
* because only Algorithm is referenced by another compilation unit.
*/
static const Algorithm::Registry<AlgoCuckatoo31Cl> registryAlgoCuckatoo31Cl {"AlgoCuckatoo31Cl", HasPowTypeCuckatoo<31>::getPowType()};
static const Algorithm::Registry<AlgoDummy> regustryAlgoDummy {"AlgoDummy" , HasPowTypeEthash::getPowType()};
static const Algorithm::Registry<AlgoEthashCL> registryAlgoEthashCL {"AlgoEthashCL", HasPowTypeEthash::getPowType()};
unique_ptr<Algorithm> Algorithm::makeAlgo(AlgoConstructionArgs args, const std::string &implName) {
if (auto entry = entryWithName(implName)) {
return entry->makeFunc(std::move(args));
}
return nullptr;
}
std::string Algorithm::powTypeForAlgoImplName(const std::string &algoImplName) {
if (auto entry = entryWithName(algoImplName)) {
return entry->powType;
}
return ""; //no matching algo type found
}
optional_ref<Algorithm::Entry> Algorithm::entryWithName(const std::string &algoImplName) {
for (auto &entry : getEntries()) {
if (entry.algoImplName == algoImplName) {
return entry;
}
}
return {};
}
} | 34.978723 | 139 | 0.667275 | oldas1 |
0283b0332e6a4eb780ca44439332565d75e5dd1d | 601 | cpp | C++ | two-sum.cpp | casper001207/leetcode | 7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30 | [
"MIT"
] | null | null | null | two-sum.cpp | casper001207/leetcode | 7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30 | [
"MIT"
] | null | null | null | two-sum.cpp | casper001207/leetcode | 7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
for ( vector<int>::iterator it = nums.begin(); it != nums.end(); ++it ) {
for ( vector<int>::iterator it2 = nums.begin() + distance(nums.begin(), it) + 1; it2 != nums.end(); ++it2 ) {
if (*it + *it2 == target) {
v.push_back(distance(nums.begin(), it));
v.push_back(distance(nums.begin(), it2));
return v;
}
}
}
return v;
}
}; | 37.5625 | 121 | 0.430948 | casper001207 |
02886a263f1ca7908acf62c14d5f2532f559567e | 3,278 | hpp | C++ | src/libraries/core/interpolation/surfaceInterpolation/schemes/pointLinear/pointLinear.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/surfaceInterpolation/schemes/pointLinear/pointLinear.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/surfaceInterpolation/schemes/pointLinear/pointLinear.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
pointLinear
Description
Face-point interpolation scheme class derived from linear and
returns linear weighting factors but also applies an explicit correction.
Uses volPointInterpolation to obtain the field values at the face-points.
SourceFiles
pointLinear.cpp
\*---------------------------------------------------------------------------*/
#ifndef pointLinear_H
#define pointLinear_H
#include "linear.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class pointLinear Declaration
\*---------------------------------------------------------------------------*/
template<class Type>
class pointLinear
:
public linear<Type>
{
// Private Member Functions
//- Disallow default bitwise copy construct
pointLinear(const pointLinear&);
//- Disallow default bitwise assignment
void operator=(const pointLinear&);
public:
//- Runtime type information
TypeName("pointLinear");
// Constructors
//- Construct from mesh
pointLinear(const fvMesh& mesh)
:
linear<Type>(mesh)
{}
//- Construct from mesh and Istream
pointLinear
(
const fvMesh& mesh,
Istream&
)
:
linear<Type>(mesh)
{}
//- Construct from mesh, faceFlux and Istream
pointLinear
(
const fvMesh& mesh,
const surfaceScalarField&,
Istream&
)
:
linear<Type>(mesh)
{}
// Member Functions
//- Return true if this scheme uses an explicit correction
virtual bool corrected() const
{
return true;
}
//- Return the explicit correction to the face-interpolate
virtual tmp<GeometricField<Type, fvsPatchField, surfaceMesh> >
correction
(
const GeometricField<Type, fvPatchField, volMesh>& vf
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 26.015873 | 79 | 0.493289 | MrAwesomeRocks |
02886c0d5b3d2ef911ea028d4e50894471323041 | 6,248 | cpp | C++ | platform-abstractions/tizen/resource-loader/resource-thread-image.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | platform-abstractions/tizen/resource-loader/resource-thread-image.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | platform-abstractions/tizen/resource-loader/resource-thread-image.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "resource-thread-image.h"
// EXTERNAL INCLUDES
#include <dali/devel-api/common/ref-counted-dali-vector.h>
#include <dali/integration-api/bitmap.h>
#include <dali/integration-api/debug.h>
#include <dali/integration-api/resource-cache.h>
#include <dali/integration-api/resource-types.h>
// INTERNAL INCLUDES
#include "portable/file-closer.h"
#include "image-loaders/image-loader.h"
#include "network/file-download.h"
using namespace Dali::Integration;
namespace Dali
{
namespace TizenPlatform
{
namespace
{
// limit maximum image down load size to 50 MB
const size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024 ;
}
ResourceThreadImage::ResourceThreadImage(ResourceLoader& resourceLoader)
: ResourceThreadBase(resourceLoader)
{
}
ResourceThreadImage::~ResourceThreadImage()
{
}
void ResourceThreadImage::Load(const ResourceRequest& request)
{
DALI_LOG_TRACE_METHOD( mLogFilter );
DALI_LOG_INFO( mLogFilter, Debug::Verbose, "%s(%s)\n", __FUNCTION__, request.GetPath().c_str() );
LoadImageFromLocalFile(request);
}
void ResourceThreadImage::Download(const ResourceRequest& request)
{
bool succeeded;
DALI_LOG_TRACE_METHOD( mLogFilter );
DALI_LOG_INFO( mLogFilter, Debug::Verbose, "%s(%s)\n", __FUNCTION__, request.GetPath().c_str() );
Dali::Vector<uint8_t> dataBuffer;
size_t dataSize;
succeeded = DownloadRemoteImageIntoMemory( request, dataBuffer, dataSize );
if( succeeded )
{
DecodeImageFromMemory(static_cast<void*>(&dataBuffer[0]), dataBuffer.Size(), request);
}
}
void ResourceThreadImage::Decode(const ResourceRequest& request)
{
DALI_LOG_TRACE_METHOD( mLogFilter );
DALI_LOG_INFO(mLogFilter, Debug::Verbose, "%s(%s)\n", __FUNCTION__, request.GetPath().c_str());
// Get the blob of binary data that we need to decode:
DALI_ASSERT_DEBUG( request.GetResource() );
DALI_ASSERT_DEBUG( 0 != dynamic_cast<Dali::RefCountedVector<uint8_t>*>( request.GetResource().Get() ) && "Only blobs of binary data can be decoded." );
Dali::RefCountedVector<uint8_t>* const encodedBlob = reinterpret_cast<Dali::RefCountedVector<uint8_t>*>( request.GetResource().Get() );
if( 0 != encodedBlob )
{
const size_t blobSize = encodedBlob->GetVector().Size();
uint8_t * const blobBytes = &(encodedBlob->GetVector()[0]);
DecodeImageFromMemory(blobBytes, blobSize, request);
}
else
{
FailedResource resource(request.GetId(), FailureUnknown);
mResourceLoader.AddFailedLoad(resource);
}
}
bool ResourceThreadImage::DownloadRemoteImageIntoMemory(const Integration::ResourceRequest& request, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize)
{
bool ok = Network::DownloadRemoteFileIntoMemory( request.GetPath(), dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE );
if( !ok )
{
FailedResource resource(request.GetId(), FailureUnknown);
mResourceLoader.AddFailedLoad(resource);
}
return ok;
}
void ResourceThreadImage::LoadImageFromLocalFile(const Integration::ResourceRequest& request)
{
bool fileNotFound = false;
BitmapPtr bitmap = 0;
bool result = false;
Dali::Internal::Platform::FileCloser fileCloser( request.GetPath().c_str(), "rb" );
FILE * const fp = fileCloser.GetFile();
if( NULL != fp )
{
result = ImageLoader::ConvertStreamToBitmap( *request.GetType(), request.GetPath(), fp, *this, bitmap );
// Last chance to interrupt a cancelled load before it is reported back to clients
// which have already stopped tracking it:
InterruptionPoint(); // Note: This can throw an exception.
if( result && bitmap )
{
// Construct LoadedResource and ResourcePointer for image data
LoadedResource resource( request.GetId(), request.GetType()->id, ResourcePointer( bitmap.Get() ) );
// Queue the loaded resource
mResourceLoader.AddLoadedResource( resource );
}
else
{
DALI_LOG_WARNING( "Unable to decode %s\n", request.GetPath().c_str() );
}
}
else
{
DALI_LOG_WARNING( "Failed to open file to load \"%s\"\n", request.GetPath().c_str() );
fileNotFound = true;
}
if ( !bitmap )
{
if( fileNotFound )
{
FailedResource resource(request.GetId(), FailureFileNotFound );
mResourceLoader.AddFailedLoad(resource);
}
else
{
FailedResource resource(request.GetId(), FailureUnknown);
mResourceLoader.AddFailedLoad(resource);
}
}
}
void ResourceThreadImage::DecodeImageFromMemory(void* blobBytes, size_t blobSize, const Integration::ResourceRequest& request)
{
BitmapPtr bitmap = 0;
DALI_ASSERT_DEBUG( blobSize > 0U );
DALI_ASSERT_DEBUG( blobBytes != 0U );
if( blobBytes != 0 && blobSize > 0U )
{
// Open a file handle on the memory buffer:
Dali::Internal::Platform::FileCloser fileCloser( blobBytes, blobSize, "rb" );
FILE * const fp = fileCloser.GetFile();
if ( NULL != fp )
{
bool result = ImageLoader::ConvertStreamToBitmap( *request.GetType(), request.GetPath(), fp, StubbedResourceLoadingClient(), bitmap );
if ( result && bitmap )
{
// Construct LoadedResource and ResourcePointer for image data
LoadedResource resource( request.GetId(), request.GetType()->id, ResourcePointer( bitmap.Get() ) );
// Queue the loaded resource
mResourceLoader.AddLoadedResource( resource );
}
else
{
DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" );
}
}
}
if (!bitmap)
{
FailedResource resource(request.GetId(), FailureUnknown);
mResourceLoader.AddFailedLoad(resource);
}
}
} // namespace TizenPlatform
} // namespace Dali
| 30.778325 | 153 | 0.711908 | pwisbey |
028a2c507cef9b32cac89ce2f3e7c543e476d5c4 | 3,738 | cxx | C++ | Testing/Code/BasicFilters/itkMinimumMaximumImageCalculatorTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Testing/Code/BasicFilters/itkMinimumMaximumImageCalculatorTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/BasicFilters/itkMinimumMaximumImageCalculatorTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMinimumMaximumImageCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkSize.h"
int
itkMinimumMaximumImageCalculatorTest(int ,char *[] )
{
typedef itk::Size<3> SizeType;
typedef itk::Image<short, 3> ImageType;
typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxCalculatorType;
/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};
int flag = 0; /* Did this test program work? */
std::cout << "Testing Minimum and Maximum Image Calulator:\n";
// Allocate a simple test image
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
region.SetSize(size);
image->SetLargestPossibleRegion(region);
image->SetRequestedRegion(region);
image->SetBufferedRegion(region);
image->Allocate();
// Set origin and spacing of physical coordinates
image->SetOrigin(origin);
image->SetSpacing(spacing);
short minimum = -52;
short maximum = 103;
// Initialize the image contents with the minimum value
itk::Index<3> index;
for (int slice = 0; slice < 20; slice++) {
index[2] = slice;
for (int row = 0; row <20; row++) {
index[1] = row;
for (int col = 0; col < 20; col++) {
index[0] = col;
image->SetPixel(index, minimum);
}
}
}
// Set voxel (10,10,10) to maximum value
index[0] = 10;
index[1] = 10;
index[2] = 10;
image->SetPixel(index, maximum);
// Create and initialize the calculator
MinMaxCalculatorType::Pointer calculator = MinMaxCalculatorType::New();
calculator->SetImage( image );
calculator->Compute();
// Return minimum of intensity
short minimumResult = calculator->GetMinimum();
std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;
std::cout << "Its index position is : " << calculator->GetIndexOfMinimum() << std::endl;
if(minimumResult != minimum)
{
std::cout << "Minimum Value is wrong : " << minimumResult ;
std::cout << " != " << minimum << std::endl;
flag = 1;
}
// Return maximum of intensity
short maximumResult = calculator->GetMaximum();
std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;
std::cout << "Its index position is : " << calculator->GetIndexOfMaximum() << std::endl;
if(maximumResult != maximum)
{
std::cout << "Maximum Value is wrong : " << maximumResult ;
std::cout << " != " << maximum << std::endl;
flag = 2;
}
// Return results of test
if (flag != 0) {
std::cout << "*** Some tests failed" << std::endl;
return flag; }
else {
std::cout << "All tests successfully passed" << std::endl;
return EXIT_SUCCESS; }
}
| 31.677966 | 92 | 0.587747 | kiranhs |
028c018ae593b3cb084a8b013613887b039fd020 | 15,309 | cpp | C++ | moon-src/luabind/lua_json.cpp | Mu-L/moon | 53a32422a39788850ec16dd84ca4276a66f5f1da | [
"MIT"
] | null | null | null | moon-src/luabind/lua_json.cpp | Mu-L/moon | 53a32422a39788850ec16dd84ca4276a66f5f1da | [
"MIT"
] | null | null | null | moon-src/luabind/lua_json.cpp | Mu-L/moon | 53a32422a39788850ec16dd84ca4276a66f5f1da | [
"MIT"
] | null | null | null | #include "lua.hpp"
#include <vector>
#include <charconv>
#include <string_view>
// __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler.
// We use -march=native with gmake to enable -msse2 and -msse4.2, if supported.
#if defined(__SSE4_2__)
# define RAPIDJSON_SSE42
#elif defined(__SSE2__)
# define RAPIDJSON_SSE2
#endif
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/reader.h"
#include "rapidjson/error/en.h"
#include "common/buffer.hpp"
#ifdef MOON_ENABLE_MIMALLOC
#include "mimalloc.h"
class MimallocAllocator {
public:
static const bool kNeedFree = true;
void* Malloc(size_t size) {
if (size) // behavior of malloc(0) is implementation defined.
return mi_malloc(size);
else
return nullptr; // standardize to returning NULL.
}
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
(void)originalSize;
if (newSize == 0) {
mi_free(originalPtr);
return nullptr;
}
return mi_realloc(originalPtr, newSize);
}
static void Free(void* ptr) { mi_free(ptr); }
};
using JsonAllocator = MimallocAllocator;
#else
using JsonAllocator = rapidjson::CrtAllocator;
#endif
using StreamBuf = rapidjson::GenericStringBuffer<rapidjson::UTF8<>, JsonAllocator>;
using JsonWriter = rapidjson::Writer<StreamBuf>;
using JsonPrettyWriter = rapidjson::PrettyWriter<StreamBuf>;
using JsonReader = rapidjson::GenericReader<rapidjson::UTF8<>, rapidjson::UTF8<>, JsonAllocator>;
static constexpr int max_depth = 32;
namespace rapidjson
{
// StringNStream
//! Read-only string stream.
/*! \note implements Stream concept
*/
template <typename Encoding>
struct GenericStringNStream {
typedef typename Encoding::Ch Ch;
GenericStringNStream(const Ch* src, const size_t len) : src_(src), head_(src), len_(len) {}
Ch Peek() const { return Tell() < len_ ? *src_ : '\0'; }
Ch Take() { return *src_++; }
size_t Tell() const { return static_cast<size_t>(src_ - head_); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
const Ch* src_; //!< Current read position.
const Ch* head_; //!< Original head of the string.
size_t len_; //!< Original head of the string.
};
//! String stream with UTF8 encoding.
typedef GenericStringNStream<UTF8<> > StringNStream;
template <typename Encoding>
struct StreamTraits<GenericStringNStream<Encoding> > {
enum { copyOptimization = 1 };
};
}
using StringNStream = rapidjson::StringNStream;
template<typename Writer>
static void encode_table(lua_State* L, Writer* writer, int idx, int depth, bool empty_as_array);
template<typename Writer>
static void encode_one(lua_State* L, Writer* writer, int idx, int depth = 0, bool empty_as_array = true)
{
int t = lua_type(L, idx);
switch (t)
{
case LUA_TBOOLEAN:
{
writer->Bool(lua_toboolean(L, idx) != 0);
return;
}
case LUA_TNUMBER:
{
if (lua_isinteger(L, idx))
{
writer->Int64(lua_tointeger(L, idx));
}
else
{
if (!writer->Double(lua_tonumber(L, idx)))
luaL_error(L, "error while encode double value.");
}
return;
}
case LUA_TSTRING:
{
size_t len = 0;
const char* str = lua_tolstring(L, idx, &len);
writer->String(str, static_cast<rapidjson::SizeType>(len));
return;
}
case LUA_TTABLE:
{
encode_table(L, writer, idx, depth + 1, empty_as_array);
return;
}
case LUA_TNIL:
{
writer->Null();
return;
}
default:
luaL_error(L, "json encode: unsupport value type : %s", lua_typename(L, t));
}
}
static inline size_t array_size(lua_State* L, int index)
{
size_t len = lua_rawlen(L, index);
if (len == 0)
return 0;
// test first key
lua_pushnil(L);
lua_next(L, index);
lua_Integer firstkey = lua_isinteger(L, -2) ? lua_tointeger(L, -2) : 0;
lua_pop(L, 2);
if (firstkey != 1)
return 0;
lua_pushinteger(L, len);
if (lua_next(L, index) == 0) {
return len;
}
else {
lua_pop(L, 2);
return 0;
}
}
template<typename Writer>
static void encode_table(lua_State* L, Writer* writer, int idx, int depth, bool empty_as_array)
{
if (depth > max_depth)
luaL_error(L, "nested too depth");
if (idx < 0) {
idx = lua_gettop(L) + idx + 1;
}
luaL_checkstack(L, LUA_MINSTACK, NULL);
if (size_t size = array_size(L, idx); size >0)
{
writer->StartArray();
for (size_t i = 1; i <= size; i++)
{
lua_rawgeti(L, idx, i);
encode_one(L, writer, -1, depth, empty_as_array);
lua_pop(L, 1);
}
writer->EndArray();
}
else
{
bool empty = true;
lua_pushnil(L);
while (lua_next(L, idx))
{
if (empty)
{
writer->StartObject();
empty = false;
}
int key_type = lua_type(L, -2);
switch (key_type)
{
case LUA_TSTRING:
{
size_t len = 0;
const char* key = lua_tolstring(L, -2, &len);
writer->Key(key, static_cast<rapidjson::SizeType>(len));
encode_one(L, writer, -1, depth, empty_as_array);
break;
}
case LUA_TNUMBER:
{
lua_Integer key = luaL_checkinteger(L, -2);
char tmp[256];
auto res = std::to_chars(tmp, tmp + 255, key);
if (res.ec != std::errc())
{
luaL_error(L, "json encode: int key to_chars failed.");
}
writer->Key(tmp, static_cast<rapidjson::SizeType>(res.ptr - tmp), true);
encode_one(L, writer, -1, depth, empty_as_array);
break;
}
default:
luaL_error(L, "json encode: object only support string and integer key");
break;
}
lua_pop(L, 1);
}
if (!empty)
{
writer->EndObject();
}
else
{
if (empty_as_array)
{
writer->StartArray();
writer->EndArray();
}
else
{
writer->StartObject();
writer->EndObject();
}
}
}
}
static int do_encode(lua_State* L, int index, bool empty_as_array, moon::buffer* buf)
{
if (index < 0) {
index = lua_gettop(L) + index + 1;
}
StreamBuf stream;
JsonWriter writer(stream);
encode_one(L, &writer, index, 0, empty_as_array);
if (nullptr != buf)
{
buf->write_back(stream.GetString(), stream.GetSize());
return 0;
}
else
{
lua_pushlstring(L, stream.GetString(), stream.GetSize());
return 1;
}
}
static int encode(lua_State* L)
{
luaL_checktype(L, 1, LUA_TTABLE);
bool empty_as_array = (bool)luaL_opt(L, lua_toboolean, 2, true);
lua_settop(L, 1);
return do_encode(L, 1, empty_as_array, nullptr);
}
static int pretty_encode(lua_State* L)
{
luaL_checktype(L, 1, LUA_TTABLE);
bool empty_as_array = (bool)luaL_opt(L, lua_toboolean, 2, true);
lua_settop(L, 1);
StreamBuf stream;
JsonPrettyWriter writer(stream);
encode_one(L, &writer, 1, 0, empty_as_array);
lua_pushlstring(L, stream.GetString(), stream.GetSize());
return 1;
}
static int concat(lua_State* L)
{
if (lua_type(L, 1) == LUA_TSTRING)
{
size_t size;
const char* sz = lua_tolstring(L, -1, &size);
auto buf = new moon::buffer(256, 16);
buf->write_back(sz, size);
lua_pushlightuserdata(L, buf);
return 1;
}
luaL_checktype(L, 1, LUA_TTABLE);
auto buf = new moon::buffer(256, 16);
int array_size = (int)lua_rawlen(L, 1);
for (int i = 1; i <= array_size; i++) {
lua_rawgeti(L, 1, i);
switch (lua_type(L, -1))
{
case LUA_TNUMBER:
{
if (lua_isinteger(L, -1))
{
buf->write_chars(lua_tointeger(L, -1));
}
else
{
std::string s = std::to_string(lua_tonumber(L, -1));
buf->write_back(s.data(), s.size());
}
break;
}
case LUA_TBOOLEAN:
{
const char* v = lua_toboolean(L, -1) ? "true" : "false";
buf->write_back(v, strlen(v));
break;
}
case LUA_TSTRING:
{
size_t size;
const char* sz = lua_tolstring(L, -1, &size);
buf->write_back(sz, size);
break;
}
case LUA_TTABLE:
{
do_encode(L, -1, true, buf);
break;
}
default:
break;
}
lua_pop(L, 1);
}
lua_pushlightuserdata(L, buf);
return 1;
}
static void write_resp(moon::buffer* buf, const char* cmd, size_t size)
{
buf->write_back("\r\n$", 3);
buf->write_chars(size);
buf->write_back("\r\n", 2);
buf->write_back(cmd, size);
}
static int concat_resp(lua_State* L) {
int n = lua_gettop(L);
if (0 == n)
{
return 0;
}
auto buf = new moon::buffer(256, 16);
buf->write_back("*", 1);
buf->write_chars(n);
for (int i = 1; i <= n; i++) {
switch (lua_type(L, i))
{
case LUA_TNIL:
{
std::string_view sv = "\r\n$-1";
buf->write_back(sv.data(), sv.size());
break;
}
case LUA_TNUMBER:
{
if (lua_isinteger(L, i))
{
std::string s = std::to_string(lua_tointeger(L, i));
write_resp(buf, s.data(), s.size());
}
else
{
std::string s = std::to_string(lua_tonumber(L, i));
write_resp(buf, s.data(), s.size());
}
break;
}
case LUA_TBOOLEAN:
{
std::string_view sv = lua_toboolean(L, i) ? "true" : "false";
write_resp(buf, sv.data(), sv.size());
break;
}
case LUA_TSTRING:
{
size_t msize;
const char* sz = lua_tolstring(L, i, &msize);
write_resp(buf, sz, msize);
break;
}
case LUA_TTABLE:
{
StreamBuf stream;
JsonWriter writer(stream);
encode_one(L, &writer, i, 0, true);
write_resp(buf, stream.GetString(), stream.GetSize());
break;
}
default:
break;
}
}
buf->write_back("\r\n", 2);
lua_pushlightuserdata(L, buf);
return 1;
}
struct LuaPushHandler {
explicit LuaPushHandler(lua_State* aL) : L(aL) {}
bool Null() {
static int json_null = LUA_NOREF;
lua_rawgeti(L, LUA_REGISTRYINDEX, json_null);
Commit();
return true;
}
bool Bool(bool b) {
lua_pushboolean(L, b);
Commit();
return true;
}
bool Int(int i) {
lua_pushinteger(L, i);
Commit();
return true;
}
bool Uint(unsigned u) {
lua_pushinteger(L, u);
Commit();
return true;
}
bool Int64(int64_t i) {
lua_pushinteger(L, i);
Commit();
return true;
}
bool Uint64(uint64_t u) {
lua_pushinteger(L, u);
Commit();
return true;
}
bool Double(double d) {
lua_pushnumber(L, static_cast<lua_Number>(d));
Commit();
return true;
}
bool RawNumber(const char* str, rapidjson::SizeType length, bool /*copy*/) {
lua_getglobal(L, "tonumber");
lua_pushlstring(L, str, length);
lua_call(L, 1, 1);
Commit();
return true;
}
bool String(const char* str, rapidjson::SizeType length, bool /*copy*/) {
lua_pushlstring(L, str, length);
Commit();
return true;
}
bool StartObject() {
luaL_checkstack(L, LUA_MINSTACK, NULL);
lua_createtable(L, 0, 8);
stack_.push_back(0);// 0 means hash, >0 means array
return true;
}
bool Key(const char* str, rapidjson::SizeType length, bool /*copy*/) const {
if (length == 0)
{
return false;
}
char c = str[0];
if (c == '-' || (c >= '0' && c <= '9'))
{
const char* last = str + length;
int64_t v = 0;
auto [p, ec] = std::from_chars(str, last, v);
if (ec == std::errc() && p == last)
{
lua_pushinteger(L, v);
return true;
}
}
lua_pushlstring(L, str, length);
return true;
}
bool EndObject(rapidjson::SizeType /*memberCount*/) {
stack_.pop_back();
Commit();
return true;
}
bool StartArray() {
luaL_checkstack(L, LUA_MINSTACK, NULL);
lua_createtable(L, 8, 0);
stack_.push_back(1);
return true;
}
bool EndArray(rapidjson::SizeType /*elementCount*/) {
stack_.pop_back();
Commit();
return true;
}
private:
void Commit()
{
if (!stack_.empty())
{
//obj
if (stack_.back() == 0)
{
lua_rawset(L, -3);
}
else
{
lua_rawseti(L, -2, stack_.back()++);
}
}
}
lua_State* L;
std::vector<int> stack_;
};
static int lua_json_decode(lua_State* L, const char* s, size_t len)
{
JsonReader reader;
StringNStream stream{ s, len };
LuaPushHandler handler{ L };
auto res = reader.Parse(stream, handler);
if (!res) {
lua_pushnil(L);
lua_pushfstring(L, "%s (%d)", rapidjson::GetParseError_En(res.Code()), (int)res.Offset());
return 2;
}
return 1;
}
static int decode(lua_State* L)
{
size_t len = 0;
const char* str = nullptr;
if (lua_type(L, 1) == LUA_TSTRING) {
str = luaL_checklstring(L, 1, &len);
}
else {
str = reinterpret_cast<const char*>(lua_touserdata(L, 1));
len = luaL_checkinteger(L, 2);
}
if (nullptr == str)
{
return 0;
}
lua_settop(L, 1);
return lua_json_decode(L, str, len);
}
extern "C"
{
int LUAMOD_API luaopen_json(lua_State* L)
{
luaL_Reg l[] = {
{"encode", encode},
{"pretty_encode", pretty_encode},
{"concat", concat},
{"concat_resp", concat_resp},
{"decode", decode},
{NULL,NULL}
};
luaL_newlib(L, l);
return 1;
}
}
| 25.515 | 104 | 0.525639 | Mu-L |
028e5ec97bbaec3a476e32481d2a4f6b93c99e52 | 5,701 | cpp | C++ | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 12 | 2020-09-07T11:19:10.000Z | 2022-02-17T17:40:19.000Z | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 110 | 2020-09-02T15:29:24.000Z | 2022-03-09T09:50:01.000Z | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 3 | 2021-05-21T13:24:31.000Z | 2022-02-11T14:43:12.000Z | /**
* Initialization of runaway source terms.
*/
#include "DREAM/Equations/Fluid/TritiumRateTerm.hpp"
#include "DREAM/Equations/Fluid/HottailRateTermHighZ.hpp"
#include "DREAM/Equations/Fluid/ExternalAvalancheTerm.hpp"
#include "DREAM/Equations/RunawaySourceTerm.hpp"
#include "DREAM/IO.hpp"
#include "DREAM/Settings/SimulationGenerator.hpp"
using namespace DREAM;
RunawaySourceTermHandler *SimulationGenerator::ConstructRunawaySourceTermHandler(
FVM::Grid *grid, FVM::Grid *hottailGrid, FVM::Grid *runawayGrid, FVM::Grid *fluidGrid,
FVM::UnknownQuantityHandler *unknowns, RunawayFluid *REFluid,
IonHandler *ions, AnalyticDistributionHottail *distHT,
struct OtherQuantityHandler::eqn_terms *oqty_terms, Settings *s, bool signPositive
) {
const std::string &mod = "eqsys/n_re";
std::string eqnSign = signPositive ? " + " : " - ";
RunawaySourceTermHandler *rsth = new RunawaySourceTermHandler();
// Add avalanche growth rate:
// - fluid mode, use analytical growth rate formula,
// - kinetic mode, add those knockons which are created for p>pMax
OptionConstants::eqterm_avalanche_mode ava_mode = (enum OptionConstants::eqterm_avalanche_mode)s->GetInteger(mod + "/avalanche");
// Add avalanche growth rate
if (ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_FLUID || ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_FLUID_HESSLOW)
rsth->AddSourceTerm(eqnSign + "n_re*Gamma_ava", new AvalancheGrowthTerm(grid, unknowns, REFluid, fluidGrid, -1.0) );
else if (ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_KINETIC) {
if (hottailGrid || runawayGrid != nullptr) {
// XXX: assume same momentum grid at all radii
real_t pCut;
if (hottailGrid != nullptr)
pCut = hottailGrid->GetMomentumGrid(0)->GetP1_f(hottailGrid->GetNp1(0));
else if (runawayGrid != nullptr)
pCut = runawayGrid->GetMomentumGrid(0)->GetP1_f(0);
if (grid == runawayGrid) {
rsth->AddSourceTerm(eqnSign + "external avalanche", new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_POSITIVE) );
rsth->AddAvalancheNreNeg(new AvalancheSourceRP(grid, unknowns, pCut, +1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_POSITIVE));
rsth->AddAvalancheNreNegPos(new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_NEGATIVE));
} else if (grid == fluidGrid){
if(runawayGrid == nullptr) // match external growth to fluid formula in E~<Eceff limit
rsth->AddSourceTerm(eqnSign + "external avalanche", new ExternalAvalancheTerm(grid, pCut, -2.0, REFluid, unknowns, -1.0) );
else // use regular external RE growth (RP integrated over p>pCut)
rsth->AddSourceTerm(eqnSign + "external avalanche", new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_FLUID) );
}
} else
DREAM::IO::PrintWarning(DREAM::IO::WARNING_KINETIC_AVALANCHE_NO_HOT_GRID, "A kinetic avalanche term is used, but the hot-tail grid is disabled. Ignoring avalanche source...");
}
// Add Dreicer runaway rate
enum OptionConstants::eqterm_dreicer_mode dm =
(enum OptionConstants::eqterm_dreicer_mode)s->GetInteger(mod + "/dreicer");
switch (dm) {
case OptionConstants::EQTERM_DREICER_MODE_CONNOR_HASTIE_NOCORR:
rsth->AddSourceTerm(eqnSign + "dreicer (CH)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::CONNOR_HASTIE_NOCORR, -1.0
));
break;
case OptionConstants::EQTERM_DREICER_MODE_CONNOR_HASTIE:
rsth->AddSourceTerm(eqnSign + "dreicer (CH)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::CONNOR_HASTIE, -1.0
));
break;
case OptionConstants::EQTERM_DREICER_MODE_NEURAL_NETWORK:
rsth->AddSourceTerm(eqnSign + "dreicer (NN)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::NEURAL_NETWORK, -1.0
));
break;
default: break; // Don't add Dreicer runaways
}
// Add compton source
OptionConstants::eqterm_compton_mode compton_mode = (enum OptionConstants::eqterm_compton_mode)s->GetInteger(mod + "/compton/mode");
if (compton_mode == OptionConstants::EQTERM_COMPTON_MODE_FLUID)
rsth->AddSourceTerm(eqnSign + "compton", new ComptonRateTerm(grid, unknowns, REFluid, fluidGrid, -1.0) );
// Add tritium source
bool tritium_enabled = s->GetBool(mod + "/tritium");
if (tritium_enabled) {
const len_t *ti = ions->GetTritiumIndices();
for (len_t i = 0; i < ions->GetNTritiumIndices(); i++)
rsth->AddSourceTerm(eqnSign + "tritium", new TritiumRateTerm(grid, ions, unknowns, ti[i], REFluid, -1.0));
}
// Add hottail source
OptionConstants::eqterm_hottail_mode hottail_mode = (enum OptionConstants::eqterm_hottail_mode)s->GetInteger(mod + "/hottail");
if(distHT!=nullptr && hottail_mode == OptionConstants::EQTERM_HOTTAIL_MODE_ANALYTIC_ALT_PC){
oqty_terms->n_re_hottail_rate = new HottailRateTermHighZ(
grid, distHT, unknowns, ions,
REFluid->GetLnLambda(), -1.0
);
rsth->AddSourceTerm(eqnSign + "hottail", oqty_terms->n_re_hottail_rate);
}
return rsth;
}
| 50.008772 | 208 | 0.6776 | chalmersplasmatheory |
028e7cbdf1e43feb8ada7ee6eef1eac47839e56c | 13,358 | cpp | C++ | source/Bit/System/Bencode/BencodeValue.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | source/Bit/System/Bencode/BencodeValue.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | source/Bit/System/Bencode/BencodeValue.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | // Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// This software is provided 'as-is', without any express or
// implied warranty. In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute
// it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but
// is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any
// source distribution.
// ///////////////////////////////////////////////////////////////////////////
#include <Bit/System/Bencode/Value.hpp>
#include <sstream>
#include <Bit/System/MemoryLeak.hpp>
namespace Bit
{
namespace Bencode
{
// Global varaibles
static std::string g_EmptyString = "";
static std::string g_TemporaryString = "";
static std::string g_NilString = "[Nil]";
static std::string g_DictionaryString = "[Dictionary]";
static std::string g_ListString = "[List]";
// Static variable members
const Value Value::NilValue( Nil );
Value Value::s_DefaultValue( Nil );
// Value definitions
Value::Value( ) :
m_Type( Nil )
{
}
Value::Value( eType p_Type ) :
m_Type( p_Type )
{
}
Value::Value( const Value & p_Value )
{
// Always clear the old data
Clear( );
// Get this value's pointer
Value * pValue = const_cast<Value *>( this );
// Copy the value
CopyValue( p_Value, *pValue );
}
Value::~Value( )
{
Clear( );
}
void Value::Clear( )
{
switch( m_Type )
{
case Integer:
{
m_Value.Integer = 0;
}
break;
case String:
{
if( m_Value.String )
{
delete m_Value.String;
}
}
break;
case List:
{
if( m_Value.List )
{
// Delete all the values in the list
for( ValueVector::iterator it = m_Value.List->begin( ); it != m_Value.List->end( ); it++ )
{
delete *it;
}
delete m_Value.List;
}
}
break;
case Dictionary:
{
if( m_Value.Dictionary )
{
// Go through the dictionary and delete all the values
for( ValueMap::iterator it = m_Value.Dictionary->begin( ); it != m_Value.Dictionary->end( ); it++ )
{
delete it->second;
}
// Delete the dictionary pointer.
delete m_Value.Dictionary;
}
}
break;
default:
break;
}
// Set the type to Nil.
m_Type = Nil;
}
void Value::Append( const Value & p_Value )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a new value
Value * pValue = new Value;
// Copy the value
CopyValue( p_Value, *pValue );
// Push the new value value to the vector.
m_Value.List->push_back( pValue );
}
void Value::Append( const Int32 & p_Integer )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a value and push it to the vector
Value * pValue = new Value( Integer );
pValue->m_Value.Integer = p_Integer;
m_Value.List->push_back( pValue );
}
void Value::Append( const std::string & p_String )
{
// The value is not a list, turn it into a list
if( m_Type != List || !m_Value.List )
{
// Clear the old data first
Clear( );
m_Type = List;
m_Value.List = new ValueVector;
}
// Create a new value
Value * pValue = new Value( String );
pValue->m_Value.String = new std::string( );
// Set the string data for the new value.
pValue->m_Value.String->reserve( p_String.size( ) );
pValue->m_Value.String->append( p_String );
// Push the new value value to the vector.
m_Value.List->push_back( pValue );
}
void Value::Erase( const SizeType & p_Index )
{
// Make sure that this is a list.
if( m_Type != List || !m_Value.List )
{
return;
}
// Error check the size
if( p_Index >= m_Value.List->size( ) )
{
return;
}
// Delete the value
Value * pValue = *(m_Value.List->begin( ) + p_Index);
delete pValue;
// Erase the item
m_Value.List->erase( m_Value.List->begin( ) + p_Index );
}
void Value::Erase( const std::string & p_Key )
{
// Make sure that this is a dictionary.
if( m_Type != Dictionary || !m_Value.Dictionary )
{
return;
}
// Find the value
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could we find the value?
if( it == m_Value.Dictionary->end( ) )
{
return;
}
// Delete the value
delete it->second;
// Erase the value from the dictionary
m_Value.Dictionary->erase( it );
}
Value::eType Value::GetType( ) const
{
return m_Type;
}
Bool Value::IsNil( ) const
{
return m_Type == Nil;
}
Value & Value::Get( const std::string & p_Key, const Value & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::Get( const std::string & p_Key, const Int32 & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::Get( const std::string & p_Key, const std::string & p_DefaultValue ) const
{
// This function only works for dictionaries
if( m_Type != Dictionary )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key
if( it == m_Value.Dictionary->end( ) )
{
s_DefaultValue = p_DefaultValue;
return s_DefaultValue;
}
// Return the found value.
return *(it->second);
}
SizeType Value::GetSize( ) const
{
if( m_Type == Dictionary && m_Value.Dictionary )
{
return static_cast<SizeType>( m_Value.Dictionary->size( ) );
}
else if( m_Type == List && m_Value.List )
{
return static_cast<SizeType>( m_Value.List->size( ) );
}
return 0;
}
const std::string & Value::AsString( ) const
{
// Switch the type in order to know which method you
// are going to use to convert the value into a string.
switch( m_Type )
{
case Nil:
{
return g_NilString;
}
break;
case String:
{
// Return the string if it's allocated.
return m_Value.String ? *m_Value.String : g_EmptyString;
}
break;
case Integer:
{
std::stringstream ss;
ss << m_Value.Integer;
g_TemporaryString = ss.str( );
return g_TemporaryString;
}
break;
case List:
{
return g_ListString;
}
break;
case Dictionary:
{
return g_DictionaryString;
}
break;
}
return g_EmptyString;
}
Int32 Value::AsInt( ) const
{
// Switch the type in order to know which method you
// are going to use to convert the value into a string.
switch( m_Type )
{
case Nil:
{
return 0;
}
break;
case String:
{
if( !m_Value.String )
{
return 0;
}
// Get the string as an int
return atoi( m_Value.String->c_str( ) );
}
break;
case Integer:
{
return m_Value.Integer;
}
break;
case List:
{
return 0;
}
break;
case Dictionary:
{
return 0;
}
break;
}
return 0;
}
Value & Value::operator [ ] ( const std::string & p_Key )
{
// This function only works for dictionaries.
// Turn this value into a dictionary.
if( m_Type != Dictionary )
{
// Clear all the old data
Clear( );
m_Type = Dictionary;
m_Value.Dictionary = new ValueMap;
}
// Find the key
ValueMap::iterator it = m_Value.Dictionary->find( p_Key );
// Could not find the key, add a Nil value to the dictionary.
if( it == m_Value.Dictionary->end( ) )
{
// Create a value
Value * pValue = new Value( Nil );
(*m_Value.Dictionary)[ p_Key ] = pValue;
// Return the nil value you just created.
return *pValue;
}
// Return the found value.
return *(it->second);
}
Value & Value::operator [ ] ( const SizeType & p_Index )
{
// Make sure that the value is a list.
if( m_Type != List )
{
s_DefaultValue.Clear( );
return s_DefaultValue;
}
// Error check the index.
if( p_Index > m_Value.List->size( ) )
{
s_DefaultValue.Clear( );
return s_DefaultValue;
}
return *(*m_Value.List)[ p_Index ];
}
Value & Value::operator = ( const Value & p_Value )
{
// Always clear the old data
Clear( );
// Get this value's pointer
Value * pValue = const_cast<Value *>( this );
// Copy the value
CopyValue( p_Value, *pValue );
// Return this value.
return *pValue;
}
Value & Value::operator = ( const Int32 & p_Integer )
{
// The value is not an integer, turn it into an integer value.
if( m_Type != Integer )
{
Clear( );
m_Type = Integer;
}
// Set the string data.
m_Value.Integer = p_Integer;
// Return this value.
return *const_cast<Value *>( this );
}
Value & Value::operator = ( const char * p_Characters )
{
return Value::operator=( std::string( p_Characters ) );
}
Value & Value::operator = ( const std::string & p_String )
{
// The value is not a string, turn it into a string value.
if( m_Type != String )
{
Clear( );
m_Type = String;
m_Value.String = new std::string( );
}
// Set the string data.
m_Value.String->reserve( p_String.size( ) );
m_Value.String->append( p_String );
// Return this value.
return *const_cast<Value *>( this );
}
bool Value::operator == ( const Value & p_Value ) const
{
return m_Type == p_Value.m_Type;
}
bool Value::operator != ( const Value & p_Value ) const
{
return m_Type != p_Value.m_Type;
}
// Private functions
void Value::CopyValue( const Value & p_From, Value & p_To ) const
{
// Set the type
p_To.m_Type = p_From.m_Type;
// Set the data
switch( p_From.m_Type )
{
case Integer:
{
p_To.m_Type = Integer;
p_To.m_Value.Integer = p_From.m_Value.Integer;
}
break;
case String:
{
// Make sure that the string is valid.
if( !p_From.m_Value.String )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = String;
p_To.m_Value.String = new std::string;
p_To.m_Value.String->reserve( p_From.m_Value.String->size( ) );
p_To.m_Value.String->append( *p_From.m_Value.String );
}
break;
case List:
{
// Make sure that the list is valid.
if( !p_From.m_Value.List )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = List;
p_To.m_Value.List = new ValueVector;
// Go throguh all the values in the list, and make copies of them.
for( ValueVector::iterator it = p_From.m_Value.List->begin( ); it != p_From.m_Value.List->end( ); it++ )
{
// Create a new value
Value * pValue = new Value( );
// Copy the value
CopyValue( *(*(it)), * pValue );
// Add the new value to the target list
p_To.m_Value.List->push_back( pValue );
}
}
break;
case Dictionary:
{
// Make sure that the dictionary is valid.
if( !p_From.m_Value.Dictionary )
{
p_To.m_Type = Nil;
break;
}
p_To.m_Type = Dictionary;
p_To.m_Value.Dictionary = new ValueMap;
// Go throguh all the values in the dictionary, and make copies of them.
for( ValueMap::iterator it = p_From.m_Value.Dictionary->begin( ); it != p_From.m_Value.Dictionary->end( ); it++ )
{
// Create a new value
Value * pValue = new Value( );
// Copy the value
CopyValue( *(it->second), * pValue );
// Add the new value to the target dictionary
(*p_To.m_Value.Dictionary)[ it->first ] = pValue;
}
}
break;
default: // Nil value
{
p_To.m_Type = Nil;
}
break;
}
}
}
} | 21.579968 | 118 | 0.59485 | jimmiebergmann |
028fb24e8a5f1bcc6c8e9582ef71e19ff0523bfe | 3,223 | cpp | C++ | Linux/src/myTrackpadHelper.cpp | teamclouday/AndroidTrackpad | c4a8b954592dac3e1020b0e5df55c46260437c75 | [
"MIT"
] | 1 | 2022-03-03T19:46:03.000Z | 2022-03-03T19:46:03.000Z | Linux/src/myTrackpadHelper.cpp | teamclouday/AndroidTrackpad | c4a8b954592dac3e1020b0e5df55c46260437c75 | [
"MIT"
] | null | null | null | Linux/src/myTrackpadHelper.cpp | teamclouday/AndroidTrackpad | c4a8b954592dac3e1020b0e5df55c46260437c75 | [
"MIT"
] | null | null | null | #include "myTrackpadHelper.hpp"
#include "myUI.hpp"
#include <X11/Xutil.h>
#include <X11/extensions/XTest.h>
#include <thread>
#include <iostream>
TrackpadManager::TrackpadManager() : buffer()
{
root_display = XOpenDisplay(NULL);
if(!root_display)
{
UIManager::showLinuxMessageError("Failed to get X11 root display");
return;
}
initialized = true;
}
TrackpadManager::~TrackpadManager()
{
buffer.clear();
if(root_display)
XCloseDisplay(root_display);
}
void TrackpadManager::process()
{
std::this_thread::sleep_for(std::chrono::nanoseconds(100));
if( buffer.size() > 0 )
{
DATA_PACK data;
lock.lock();
data = buffer.front();
buffer.pop_front();
lock.unlock();
switch ((DATA_TYPE)data.type)
{
case DATA_TYPE::DATA_TYPE_CLICK_LEFT:
mouseLeftClick(data.velX);
break;
case DATA_TYPE::DATA_TYPE_CLICK_RIGHT:
mouseRightClick();
break;
case DATA_TYPE::DATA_TYPE_DRAG:
if (!dragging)
{
dragStart();
}
move(data.velX, data.velY);
break;
case DATA_TYPE::DATA_TYPE_MOVE:
move(data.velX, data.velY);
break;
case DATA_TYPE::DATA_TYPE_SCROLL_HORI:
scrollHorizontal(data.velX);
break;
case DATA_TYPE::DATA_TYPE_SCROLL_VERT:
scrollVertical(data.velY);
break;
}
}
}
void TrackpadManager::addData(DATA_PACK newData)
{
lock.lock();
buffer.push_back(newData);
while (buffer.size() > DATA_PACK_MAX)
buffer.pop_front();
lock.unlock();
}
void TrackpadManager::mouseLeftClick(float flag)
{
if (flag)
{
// if not 0, perform dragStop
dragStop();
}
else
{
// if 0, perform normal left click
XTestFakeButtonEvent(root_display, Button1, True, 0);
XFlush(root_display);
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
XTestFakeButtonEvent(root_display, Button1, False, 0);
XFlush(root_display);
}
}
void TrackpadManager::mouseRightClick()
{
XTestFakeButtonEvent(root_display, Button3, True, 0);
XFlush(root_display);
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
XTestFakeButtonEvent(root_display, Button3, False, 0);
XFlush(root_display);
}
void TrackpadManager::scrollHorizontal(float delta)
{
int button = (delta > 0) ? Button6 : Button7;
XTestFakeButtonEvent(root_display, button, True, 0);
XFlush(root_display);
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
XTestFakeButtonEvent(root_display, button, False, 0);
XFlush(root_display);
}
void TrackpadManager::scrollVertical(float delta)
{
int button = (delta > 0) ? Button4 : Button5;
XTestFakeButtonEvent(root_display, button, True, 0);
XFlush(root_display);
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
XTestFakeButtonEvent(root_display, button, False, 0);
XFlush(root_display);
}
void TrackpadManager::dragStart()
{
XTestFakeButtonEvent(root_display, Button1, True, 0);
XFlush(root_display);
}
void TrackpadManager::dragStop()
{
XTestFakeButtonEvent(root_display, Button1, False, 0);
XFlush(root_display);
}
void TrackpadManager::move(float deltaX, float deltaY)
{
deltaX *= sensitivity;
deltaY *= sensitivity;
Window root = DefaultRootWindow(root_display);
XWarpPointer(root_display, root, None, 0, 0, 0, 0, static_cast<int>(deltaX), static_cast<int>(deltaY));
XFlush(root_display);
} | 22.858156 | 104 | 0.730065 | teamclouday |
028fd3cc4dd03dc2e8913fb16a2ee72aa527f652 | 2,720 | cxx | C++ | src/Math/Interpolate.cxx | ICRAR/NBodylib | 10de78dde32d724b7a5ce323ce8ab093b15c61a8 | [
"MIT"
] | null | null | null | src/Math/Interpolate.cxx | ICRAR/NBodylib | 10de78dde32d724b7a5ce323ce8ab093b15c61a8 | [
"MIT"
] | 5 | 2020-05-21T16:49:12.000Z | 2021-07-27T06:31:03.000Z | src/Math/Interpolate.cxx | ICRAR/NBodylib | 10de78dde32d724b7a5ce323ce8ab093b15c61a8 | [
"MIT"
] | 3 | 2019-04-23T02:58:07.000Z | 2020-10-23T00:21:57.000Z | /*! \file Interpolate.cxx
* \brief interpolation subroutines
*/
#include <Interpolate.h>
using namespace std;
namespace Math
{
//polynomial interpolation
/*void PolyInt(Double_t *xa, Double_t *ya, int n, Double_t x, Double_t &y, Double_t &dy)
{
const int nmax=10;
int i,m,ns;
Double_t den,dif,dift,ho,hp,w;
Double_t *c=new Double_t[nmax],*d=new Double_t[nmax];
ns=0;
dif=fabs(x-xa[0]);
for(int i=1;i<n;i++)
{
dift=fabs(x-xa[i]);
if (dift<dif)
{
ns=i;
dif=dift;
}
c[i]=ya[i];
d[i]=ya[i];
}
y=ya[ns];
cout<<"first estimate"<<y<<" "<<dy<<endl;
for (int m=0;m<n-1;m++)
{
for (int i=1;i<=n-m;i++)
for (int i=0;i<n-m;i++)
{
ho=xa[i]-x;
hp=xa[i+m]-x;
w=c[i+1]-d[i];
den=ho-hp;
if(den==0.){cerr<<"failure in polint\n";exit(8);}
den=w/den;
//d[i-1]=hp*den;
//c[i-1]=ho*den;
d[i]=hp*den;
c[i]=ho*den;
}
if (2*ns<n-m) dy=c[ns+1];
else
{
dy=d[ns--];
}
y=y+dy;
//y+=(dy=(2*ns<(n-m)?c[ns+1]:d[ns--]));
}
cout<<"latestest estimate"<<y<<" "<<dy<<endl;
delete []c;
delete []d;
return;
}*/
void PolyInt(Double_t *xa, Double_t *ya, int n, Double_t x, Double_t &y, Double_t &dy)
{
int ns;
Double_t den,dif,dift,ho,hp,w;
Double_t *c=new Double_t[n],*d=new Double_t[n];
//interpolate uses index one arrays
xa--;ya--;c--;d--;
ns=1;
dif=fabs(x-xa[1]);
for(int i=1;i<=n;i++)
{
dift=fabs(x-xa[i]);
if (dift<dif)
{
ns=i;
dif=dift;
}
c[i]=ya[i];
d[i]=ya[i];
}
y=ya[ns--];
for (int m=1;m<n;m++)
{
for (int i=1;i<=n-m;i++)
{
ho=xa[i]-x;
hp=xa[i+m]-x;
w=c[i+1]-d[i];
den=ho-hp;
if(den==0.){cerr<<"failure in polint\n";exit(8);}
den=w/den;
d[i]=hp*den;
c[i]=ho*den;
}
if (2*ns<n-m) dy=c[ns+1];
else
{
dy=d[ns--];
}
y=y+dy;
}
//reset pointers
c++;d++;
delete []c;
delete []d;
xa++;ya++;
return;
}
}
| 23.652174 | 92 | 0.359191 | ICRAR |
029026b90ad7da546a8f342a6ffe4ea383f85c98 | 7,600 | hpp | C++ | Lab11/barista.hpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab11/barista.hpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab11/barista.hpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | #ifndef BARISTA_HPP
#define BARISTA_HPP
#include "drink.hpp"
#include <string>
#include <iostream>
#include <unordered_set>
#include <deque>
#include <ctime>
#include <algorithm>
using std::cin; using std::cout;
using std::string; using std::endl;
//----------------------------
// File: barista.hpp
// By: Nolan LaDuke
// Date: 3/30/2021
//------------------------------------------------------------------------------
// Function: Observer Design Paradigm used for Coffee serving
//------------------------------------------------------------------------------
// Forward class declaration of Customer
class Customer;
// Barista Class
class Barista{
public:
// Constructors:
Barista(){srand(time(NULL));}
virtual ~Barista();
// Function that takes in a new Customer-Drink pair and registers them
void registerOrder(Customer*, Drink*);
// Function that takes the first non-ready order and makes it ready
virtual bool makeOrder(){
// Iterate through until an unprepared order is found
auto completableOrder = std::find_if(orderQueue_.begin(), orderQueue_.end(),
[](Drink* order){
return !order->getStatus();
});
// if one is found mark it as ready
if(completableOrder != orderQueue_.end()){
(*completableOrder)->setReady();
cout << "Barista finished making order number " << (*completableOrder)->getID() << endl;
return true;
}
return false;
}
// Function that takes the first ready order and announces to all registered Customers its ID
bool serveOrder();
// Function that Customer initiates, deregisters + deletes Customer and matching Drink
void pickupOrder(Customer*);
// 50/50 Prepare or Serve order function
void work(){
if(rand()%2){
if(makeOrder()) cout << endl;
}
else{
if(serveOrder()) cout << endl;
}
}
// 50/50 Prepare + Serve or Take order function
void workAlternate();
// Returns whether or not there are any more orders
bool doneWorking(){
return (customers_.empty() && orderQueue_.empty());
}
// Takes in a new order and returns it as a Drink*
Drink* takeOrder(){
// Set up variables:
char userInput;
string custName;
// Prompt user
cout << "Welcome to Not_Starbucks, can I get a name for this order? ";
cin >> custName;
cout << "Hello " << custName << "!" << endl
<< "would you like a [l]arge, [m]edium, or [s]mall coffee? ";
cin >> userInput;
// Case for invalid inputs:
while(userInput != 'l' && userInput != 'm' && userInput != 's'){
cout << "Sorry, the value you input is not valid, please try again:" << endl
<< "Can I get you a [l]arge, [m]edium, or [s]mall coffee? ";
cin >> userInput;
}
// Set Drink type + cost based on input
DrinkType size = userInput == 'l' ? DrinkType::large : (userInput == 'm' ? DrinkType::medium : DrinkType::small);
int cost = userInput == 'l' ? 3 : (userInput == 'm' ? 2 : 1);
// Set up base drink
Drink* custDrink = new Drink(size, custName, cost);
// Repeatedly prompt user for toppings until they give the 'n' input:
cout << "Would you like to add [s]prinkles, [c]aramel, milk [f]oam, [i]ce or [n]othing? ";
cin >> userInput;
while(userInput != 'n'){
switch(userInput){
case('s'):
custDrink = new sprinkles(custDrink);
break;
case('c'):
custDrink = new caramel(custDrink);
break;
case('f'):
custDrink = new milkFoam(custDrink);
break;
case('i'):
custDrink = new ice(custDrink);
break;
default: // Default for invalid input:
cout << "Sorry, the input you gave was not valid - please try again:" << endl;
}
cout << "Would you like to add [s]prinkles, [c]aramel, milk [f]oam, [i]ce or [n]othing? ";
cin >> userInput;
}
cout << "Thank you, your order will be ready momentarily!" << endl << endl;
return custDrink;
}
protected:
std::deque<Customer*> customers_;
std::deque<Drink*> orderQueue_;
};
// Customer Class:
class Customer{
public:
// Constructors:
Customer(Drink* order = nullptr, Barista* barista = nullptr, string name = "")
: order_(order), barista_(barista), name_(name), orderNum_(-1){};
~Customer(){} // order_ erased manually elsewhere
// Setters:
void setNumber(int orderNum){orderNum_ = orderNum;};
// Getters:
string getName(){return name_;};
int getOrderNum(){return orderNum_;};
// Functions:
void notifyOrder(Drink*);
private:
string name_;
Drink* order_;
Barista* barista_;
int orderNum_;
};
//=================== Implementation for Barista Class =========================
// Destructor implementation
Barista::~Barista(){
std::for_each(customers_.begin(), customers_.end(), [](Customer* cust){delete cust;});
}
// Register Order Implementation
void Barista::registerOrder(Customer* cust, Drink* drnk){
static int orderNumber = 0;
cust->setNumber(orderNumber);
drnk->setID(orderNumber++);
customers_.push_back(cust);
orderQueue_.push_back(drnk);
}
// Serve Order implementaiton
bool Barista::serveOrder(){
// Iterate through until a prepared order is found
auto completedOrder = std::find_if(orderQueue_.begin(), orderQueue_.end(),
[](Drink* order){
return order->getStatus();
});
// If an order was not found, return; otherwise, alert everyone
if(completedOrder == orderQueue_.end()) return false;
// Announce that the order is ready
cout << "Order number " << (*completedOrder)->getID()
<< " is now ready for pickup!" << endl;
for(auto cust : customers_){
cust->notifyOrder(*completedOrder);
}
// Erase and delete picked up order:
Drink* delPtr = *completedOrder;
orderQueue_.erase(completedOrder);
delete delPtr;
return true;
}
// Pickup Order implementation
void Barista::pickupOrder(Customer* cust){
// Find Customer's Order
auto custOrder = std::find_if(orderQueue_.begin(), orderQueue_.end(),
[&cust](Drink* currentDrink){
return (cust->getOrderNum() == currentDrink->getID()) && currentDrink->getStatus();
});
// Error Case
if(custOrder == orderQueue_.end()){
std::cerr << "ERROR: Customer attempted to pick up an invalid order [ID did not exist / order not ready]\n";
return;
}
// Print statement:
cout << "Here you go " << cust->getName() << "!" << endl
<< "Your " << (*custOrder)->getSizeName()
<< " with " << (*custOrder)->getToppings() << " is ready." << endl
<< "Your total is $" << (*custOrder)->getPrice() << endl;
// Erase and delete customer
auto custRemoval = std::find_if(customers_.begin(), customers_.end(),
[&cust](Customer* currentCust){
return (currentCust->getOrderNum() == cust->getOrderNum());
});
// Error Case
if(custRemoval == customers_.end()){
std::cerr << "ERROR: Customer not found yet had drink in queue\n";
return;
}
Customer* forDeletion = *custRemoval;
customers_.erase(custRemoval);
delete forDeletion;
}
// Alternative Work implementation
void Barista::workAlternate(){
if(rand()%2){
if(makeOrder() && serveOrder()) cout << endl;
}
else{
Drink* order = takeOrder();
Customer* cust = new Customer(order, this, order->getName());
registerOrder(cust, order);
}
}
//==================== Implementation for Customer Class =======================
void Customer::notifyOrder(Drink* finishedOrder){
if(finishedOrder->getID() == orderNum_){
barista_->pickupOrder(this);
}
}
#endif
| 28.04428 | 118 | 0.615263 | NLaDuke |
0296044c22ef9d508056b8ffc59078c21a1dd264 | 5,352 | cc | C++ | store/weakstore/shardclient.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 437 | 2016-01-13T23:06:06.000Z | 2022-03-07T07:41:55.000Z | store/weakstore/shardclient.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 13 | 2016-01-14T06:12:21.000Z | 2021-09-15T07:45:17.000Z | store/weakstore/shardclient.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 58 | 2016-01-14T05:54:13.000Z | 2022-03-08T02:56:33.000Z | // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
/***********************************************************************
*
* store/weakstore/shardclient.cc
* Client for one weak consistency store shard.
*
* Copyright 2015 Irene Zhang <iyzhang@cs.washington.edu>
* Naveen Kr. Sharma <naveenks@cs.washington.edu>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************/
#include "store/weakstore/shardclient.h"
namespace weakstore {
using namespace std;
using namespace proto;
ShardClient::ShardClient(string configPath, Transport *transport,
uint64_t client_id, int shard, int closestReplica) :
transport(transport), client_id(client_id), shard(shard)
{
ifstream configStream(configPath);
if (configStream.fail()) {
fprintf(stderr, "unable to read configuration file: %s\n",
configPath.c_str());
}
config = new transport::Configuration(configStream);
transport->Register(this, *config, -1);
timeout = new Timeout(transport, 250, [this]() {
RequestTimedOut();
});
if (closestReplica == -1) {
replica = client_id % config->n;
} else {
replica = closestReplica;
}
waiting = NULL;
}
ShardClient::~ShardClient()
{
delete config;
delete timeout;
}
void
ShardClient::Get(uint64_t id, const string &key, Promise *promise)
{
// Create get request
GetMessage msg;
msg.set_clientid(client_id);
msg.set_key(key);
ASSERT(waiting == NULL);
waiting = promise;
// Send message
transport->Timer(0, [=]() {
if (transport->SendMessageToReplica(this, replica, msg)) {
if (waiting != NULL) {
timeout->SetTimeout(promise->GetTimeout());
timeout->Start();
}
} else if (waiting != NULL) {
Promise *w = waiting;
waiting = NULL;
w->Reply(REPLY_NETWORK_FAILURE);
}
});
}
void
ShardClient::Put(uint64_t id,
const string &key,
const string &value,
Promise *promise)
{
Debug("[shard %d] Sending PUT [%s %s]", shard, key.c_str(), value.c_str());
// Creating put request
PutMessage msg;
msg.set_clientid(client_id);
msg.set_key(key);
msg.set_value(value);
ASSERT(waiting == NULL);
waiting = promise;
// clear the reply counter
totalReplies = 0;
// Send messages
transport->Timer(0, [=]() {
// always send to leader for now
if (transport->SendMessageToAll(this, msg)) {
// set the timeout
if (waiting != NULL) {
timeout->SetTimeout(waiting->GetTimeout());
timeout->Start();
}
} else if (waiting != NULL) {
Promise *w = waiting;
waiting = NULL;
w->Reply(REPLY_NETWORK_FAILURE);
}
});
}
// Callbacks that happen in the transport thread
void
ShardClient::RequestTimedOut()
{
Debug("[shard %d] Timeout", shard);
timeout->Stop();
if (waiting != NULL) {
Promise *w = waiting;
waiting = NULL;
w->Reply(REPLY_TIMEOUT);
}
}
void
ShardClient::ReceiveMessage(const TransportAddress &remote,
const string &type,
const string &data)
{
GetReplyMessage getReply;
PutReplyMessage putReply;
Debug("Received reply type: %s", type.c_str());
if (type == getReply.GetTypeName()) {
getReply.ParseFromString(data);
if (waiting != NULL) {
timeout->Stop();
Promise *w = waiting;
waiting = NULL;
w->Reply(getReply.status(),getReply.value());
}
} else if (type == putReply.GetTypeName()) {
totalReplies++;
if (totalReplies >= config->n) {
if (waiting != NULL) {
timeout->Stop();
Promise *w = waiting;
waiting = NULL;
w->Reply(REPLY_OK);
}
}
} else {
NOT_REACHABLE();
}
}
} // namespace weakstore
| 29.086957 | 86 | 0.56988 | yc1111 |
02975f410346e6c65299d093623b36bcdb28b09c | 1,531 | cpp | C++ | BOJ_solve/5804.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | BOJ_solve/5804.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | null | null | null | BOJ_solve/5804.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 2e18;
const long long mod = 1e9+7;
const long long hashmod = 100003;
const int MAXN = 100000;
const int MAXM = 1000000;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
ll a,b,c,d;
pl add_gcd(ll x,ll y) {
if(!y) return make_pair(1,0);
ll g,nx,ny;
pl N = add_gcd(y,x%y);
nx = N.x, ny = N.y;
return {ny,nx-(x/y)*ny};
}
pl inverse(ll ax,ll by) {
ll g,x,y;
g = __gcd(ax,by);
pl N = add_gcd(ax,by);
return N;
}
int main() {
int T; cin >> T;
while(T--) {
scanf("%lld/%lld",&c,&d);
ll rc = c,rd = d;
a = inverse(d,c).x, b = inverse(d,c).y;
if(__gcd(c,d) != 1) {
cout << c/__gcd(c,d) << '/' << d/__gcd(c,d) << '\n';
continue;
}
ll a2 = -a, b2 = -b;
ll na = c/__gcd(d,c), nb = d/__gcd(d,c);
ll op = (d-b-1)/nb,op2 = (d-b2-1)/nb;
a -= op*na, b += op*nb, a2 -= op2*na, b2 += op2*nb;
if(b < d&&b2 < d) {
if(b == b2) cout << min(-a,-a2) << '/' << b << '\n';
else if(b > b2) cout << -a << '/' << b << '\n';
else cout << -a2 << '/' << b2 << '\n';
}
else if(b < d) cout << -a << '/' << b << '\n';
else if(b2 < d) cout << -a2 << '/' << b2 << '\n';
else return -1;
}
} | 23.553846 | 55 | 0.544089 | python-programmer1512 |
029ab28c0d8d12a4cebdeb14483fe8731bda23ad | 17,991 | cxx | C++ | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 3 | 2016-05-30T15:12:16.000Z | 2022-03-22T08:11:13.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 21 | 2016-06-13T11:33:45.000Z | 2017-05-23T09:46:52.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | null | null | null | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimSpaceBoundary.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimSpaceBoundary
//
const SimSpaceBoundary::RelatingSpace_optional& SimSpaceBoundary::
RelatingSpace () const
{
return this->RelatingSpace_;
}
SimSpaceBoundary::RelatingSpace_optional& SimSpaceBoundary::
RelatingSpace ()
{
return this->RelatingSpace_;
}
void SimSpaceBoundary::
RelatingSpace (const RelatingSpace_type& x)
{
this->RelatingSpace_.set (x);
}
void SimSpaceBoundary::
RelatingSpace (const RelatingSpace_optional& x)
{
this->RelatingSpace_ = x;
}
void SimSpaceBoundary::
RelatingSpace (::std::auto_ptr< RelatingSpace_type > x)
{
this->RelatingSpace_.set (x);
}
const SimSpaceBoundary::RelatedBuildingElement_optional& SimSpaceBoundary::
RelatedBuildingElement () const
{
return this->RelatedBuildingElement_;
}
SimSpaceBoundary::RelatedBuildingElement_optional& SimSpaceBoundary::
RelatedBuildingElement ()
{
return this->RelatedBuildingElement_;
}
void SimSpaceBoundary::
RelatedBuildingElement (const RelatedBuildingElement_type& x)
{
this->RelatedBuildingElement_.set (x);
}
void SimSpaceBoundary::
RelatedBuildingElement (const RelatedBuildingElement_optional& x)
{
this->RelatedBuildingElement_ = x;
}
void SimSpaceBoundary::
RelatedBuildingElement (::std::auto_ptr< RelatedBuildingElement_type > x)
{
this->RelatedBuildingElement_.set (x);
}
const SimSpaceBoundary::ConnectionGeometry_optional& SimSpaceBoundary::
ConnectionGeometry () const
{
return this->ConnectionGeometry_;
}
SimSpaceBoundary::ConnectionGeometry_optional& SimSpaceBoundary::
ConnectionGeometry ()
{
return this->ConnectionGeometry_;
}
void SimSpaceBoundary::
ConnectionGeometry (const ConnectionGeometry_type& x)
{
this->ConnectionGeometry_.set (x);
}
void SimSpaceBoundary::
ConnectionGeometry (const ConnectionGeometry_optional& x)
{
this->ConnectionGeometry_ = x;
}
void SimSpaceBoundary::
ConnectionGeometry (::std::auto_ptr< ConnectionGeometry_type > x)
{
this->ConnectionGeometry_.set (x);
}
const SimSpaceBoundary::PhysicalOrVirtualBoundary_optional& SimSpaceBoundary::
PhysicalOrVirtualBoundary () const
{
return this->PhysicalOrVirtualBoundary_;
}
SimSpaceBoundary::PhysicalOrVirtualBoundary_optional& SimSpaceBoundary::
PhysicalOrVirtualBoundary ()
{
return this->PhysicalOrVirtualBoundary_;
}
void SimSpaceBoundary::
PhysicalOrVirtualBoundary (const PhysicalOrVirtualBoundary_type& x)
{
this->PhysicalOrVirtualBoundary_.set (x);
}
void SimSpaceBoundary::
PhysicalOrVirtualBoundary (const PhysicalOrVirtualBoundary_optional& x)
{
this->PhysicalOrVirtualBoundary_ = x;
}
void SimSpaceBoundary::
PhysicalOrVirtualBoundary (::std::auto_ptr< PhysicalOrVirtualBoundary_type > x)
{
this->PhysicalOrVirtualBoundary_.set (x);
}
const SimSpaceBoundary::InternalOrExternalBoundary_optional& SimSpaceBoundary::
InternalOrExternalBoundary () const
{
return this->InternalOrExternalBoundary_;
}
SimSpaceBoundary::InternalOrExternalBoundary_optional& SimSpaceBoundary::
InternalOrExternalBoundary ()
{
return this->InternalOrExternalBoundary_;
}
void SimSpaceBoundary::
InternalOrExternalBoundary (const InternalOrExternalBoundary_type& x)
{
this->InternalOrExternalBoundary_.set (x);
}
void SimSpaceBoundary::
InternalOrExternalBoundary (const InternalOrExternalBoundary_optional& x)
{
this->InternalOrExternalBoundary_ = x;
}
void SimSpaceBoundary::
InternalOrExternalBoundary (::std::auto_ptr< InternalOrExternalBoundary_type > x)
{
this->InternalOrExternalBoundary_.set (x);
}
const SimSpaceBoundary::OthersideSpaceBoundary_optional& SimSpaceBoundary::
OthersideSpaceBoundary () const
{
return this->OthersideSpaceBoundary_;
}
SimSpaceBoundary::OthersideSpaceBoundary_optional& SimSpaceBoundary::
OthersideSpaceBoundary ()
{
return this->OthersideSpaceBoundary_;
}
void SimSpaceBoundary::
OthersideSpaceBoundary (const OthersideSpaceBoundary_type& x)
{
this->OthersideSpaceBoundary_.set (x);
}
void SimSpaceBoundary::
OthersideSpaceBoundary (const OthersideSpaceBoundary_optional& x)
{
this->OthersideSpaceBoundary_ = x;
}
void SimSpaceBoundary::
OthersideSpaceBoundary (::std::auto_ptr< OthersideSpaceBoundary_type > x)
{
this->OthersideSpaceBoundary_.set (x);
}
const SimSpaceBoundary::ChildSpaceBoundaries_optional& SimSpaceBoundary::
ChildSpaceBoundaries () const
{
return this->ChildSpaceBoundaries_;
}
SimSpaceBoundary::ChildSpaceBoundaries_optional& SimSpaceBoundary::
ChildSpaceBoundaries ()
{
return this->ChildSpaceBoundaries_;
}
void SimSpaceBoundary::
ChildSpaceBoundaries (const ChildSpaceBoundaries_type& x)
{
this->ChildSpaceBoundaries_.set (x);
}
void SimSpaceBoundary::
ChildSpaceBoundaries (const ChildSpaceBoundaries_optional& x)
{
this->ChildSpaceBoundaries_ = x;
}
void SimSpaceBoundary::
ChildSpaceBoundaries (::std::auto_ptr< ChildSpaceBoundaries_type > x)
{
this->ChildSpaceBoundaries_.set (x);
}
const SimSpaceBoundary::GrossSurfaceArea_optional& SimSpaceBoundary::
GrossSurfaceArea () const
{
return this->GrossSurfaceArea_;
}
SimSpaceBoundary::GrossSurfaceArea_optional& SimSpaceBoundary::
GrossSurfaceArea ()
{
return this->GrossSurfaceArea_;
}
void SimSpaceBoundary::
GrossSurfaceArea (const GrossSurfaceArea_type& x)
{
this->GrossSurfaceArea_.set (x);
}
void SimSpaceBoundary::
GrossSurfaceArea (const GrossSurfaceArea_optional& x)
{
this->GrossSurfaceArea_ = x;
}
const SimSpaceBoundary::SurfaceNormal_optional& SimSpaceBoundary::
SurfaceNormal () const
{
return this->SurfaceNormal_;
}
SimSpaceBoundary::SurfaceNormal_optional& SimSpaceBoundary::
SurfaceNormal ()
{
return this->SurfaceNormal_;
}
void SimSpaceBoundary::
SurfaceNormal (const SurfaceNormal_type& x)
{
this->SurfaceNormal_.set (x);
}
void SimSpaceBoundary::
SurfaceNormal (const SurfaceNormal_optional& x)
{
this->SurfaceNormal_ = x;
}
void SimSpaceBoundary::
SurfaceNormal (::std::auto_ptr< SurfaceNormal_type > x)
{
this->SurfaceNormal_.set (x);
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimSpaceBoundary
//
SimSpaceBoundary::
SimSpaceBoundary ()
: ::schema::simxml::SimModelCore::SimResourceObject (),
RelatingSpace_ (this),
RelatedBuildingElement_ (this),
ConnectionGeometry_ (this),
PhysicalOrVirtualBoundary_ (this),
InternalOrExternalBoundary_ (this),
OthersideSpaceBoundary_ (this),
ChildSpaceBoundaries_ (this),
GrossSurfaceArea_ (this),
SurfaceNormal_ (this)
{
}
SimSpaceBoundary::
SimSpaceBoundary (const RefId_type& RefId)
: ::schema::simxml::SimModelCore::SimResourceObject (RefId),
RelatingSpace_ (this),
RelatedBuildingElement_ (this),
ConnectionGeometry_ (this),
PhysicalOrVirtualBoundary_ (this),
InternalOrExternalBoundary_ (this),
OthersideSpaceBoundary_ (this),
ChildSpaceBoundaries_ (this),
GrossSurfaceArea_ (this),
SurfaceNormal_ (this)
{
}
SimSpaceBoundary::
SimSpaceBoundary (const SimSpaceBoundary& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimResourceObject (x, f, c),
RelatingSpace_ (x.RelatingSpace_, f, this),
RelatedBuildingElement_ (x.RelatedBuildingElement_, f, this),
ConnectionGeometry_ (x.ConnectionGeometry_, f, this),
PhysicalOrVirtualBoundary_ (x.PhysicalOrVirtualBoundary_, f, this),
InternalOrExternalBoundary_ (x.InternalOrExternalBoundary_, f, this),
OthersideSpaceBoundary_ (x.OthersideSpaceBoundary_, f, this),
ChildSpaceBoundaries_ (x.ChildSpaceBoundaries_, f, this),
GrossSurfaceArea_ (x.GrossSurfaceArea_, f, this),
SurfaceNormal_ (x.SurfaceNormal_, f, this)
{
}
SimSpaceBoundary::
SimSpaceBoundary (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimResourceObject (e, f | ::xml_schema::flags::base, c),
RelatingSpace_ (this),
RelatedBuildingElement_ (this),
ConnectionGeometry_ (this),
PhysicalOrVirtualBoundary_ (this),
InternalOrExternalBoundary_ (this),
OthersideSpaceBoundary_ (this),
ChildSpaceBoundaries_ (this),
GrossSurfaceArea_ (this),
SurfaceNormal_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimSpaceBoundary::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::SimModelCore::SimResourceObject::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// RelatingSpace
//
if (n.name () == "RelatingSpace" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< RelatingSpace_type > r (
RelatingSpace_traits::create (i, f, this));
if (!this->RelatingSpace_)
{
this->RelatingSpace_.set (r);
continue;
}
}
// RelatedBuildingElement
//
if (n.name () == "RelatedBuildingElement" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< RelatedBuildingElement_type > r (
RelatedBuildingElement_traits::create (i, f, this));
if (!this->RelatedBuildingElement_)
{
this->RelatedBuildingElement_.set (r);
continue;
}
}
// ConnectionGeometry
//
if (n.name () == "ConnectionGeometry" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< ConnectionGeometry_type > r (
ConnectionGeometry_traits::create (i, f, this));
if (!this->ConnectionGeometry_)
{
this->ConnectionGeometry_.set (r);
continue;
}
}
// PhysicalOrVirtualBoundary
//
if (n.name () == "PhysicalOrVirtualBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< PhysicalOrVirtualBoundary_type > r (
PhysicalOrVirtualBoundary_traits::create (i, f, this));
if (!this->PhysicalOrVirtualBoundary_)
{
this->PhysicalOrVirtualBoundary_.set (r);
continue;
}
}
// InternalOrExternalBoundary
//
if (n.name () == "InternalOrExternalBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< InternalOrExternalBoundary_type > r (
InternalOrExternalBoundary_traits::create (i, f, this));
if (!this->InternalOrExternalBoundary_)
{
this->InternalOrExternalBoundary_.set (r);
continue;
}
}
// OthersideSpaceBoundary
//
if (n.name () == "OthersideSpaceBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< OthersideSpaceBoundary_type > r (
OthersideSpaceBoundary_traits::create (i, f, this));
if (!this->OthersideSpaceBoundary_)
{
this->OthersideSpaceBoundary_.set (r);
continue;
}
}
// ChildSpaceBoundaries
//
if (n.name () == "ChildSpaceBoundaries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< ChildSpaceBoundaries_type > r (
ChildSpaceBoundaries_traits::create (i, f, this));
if (!this->ChildSpaceBoundaries_)
{
this->ChildSpaceBoundaries_.set (r);
continue;
}
}
// GrossSurfaceArea
//
if (n.name () == "GrossSurfaceArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->GrossSurfaceArea_)
{
this->GrossSurfaceArea_.set (GrossSurfaceArea_traits::create (i, f, this));
continue;
}
}
// SurfaceNormal
//
if (n.name () == "SurfaceNormal" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< SurfaceNormal_type > r (
SurfaceNormal_traits::create (i, f, this));
if (!this->SurfaceNormal_)
{
this->SurfaceNormal_.set (r);
continue;
}
}
break;
}
}
SimSpaceBoundary* SimSpaceBoundary::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimSpaceBoundary (*this, f, c);
}
SimSpaceBoundary& SimSpaceBoundary::
operator= (const SimSpaceBoundary& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::SimModelCore::SimResourceObject& > (*this) = x;
this->RelatingSpace_ = x.RelatingSpace_;
this->RelatedBuildingElement_ = x.RelatedBuildingElement_;
this->ConnectionGeometry_ = x.ConnectionGeometry_;
this->PhysicalOrVirtualBoundary_ = x.PhysicalOrVirtualBoundary_;
this->InternalOrExternalBoundary_ = x.InternalOrExternalBoundary_;
this->OthersideSpaceBoundary_ = x.OthersideSpaceBoundary_;
this->ChildSpaceBoundaries_ = x.ChildSpaceBoundaries_;
this->GrossSurfaceArea_ = x.GrossSurfaceArea_;
this->SurfaceNormal_ = x.SurfaceNormal_;
}
return *this;
}
SimSpaceBoundary::
~SimSpaceBoundary ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 29.835821 | 132 | 0.617642 | EnEff-BIM |
029b4ad5e413faf728cfca0f64f0bf38fa38e055 | 1,003 | cpp | C++ | Codeforces/CF1618F.cpp | Nickel-Angel/Coding-Practice | 6fb70e9c9542323f82a9a8714727cc668ff58567 | [
"MIT"
] | null | null | null | Codeforces/CF1618F.cpp | Nickel-Angel/Coding-Practice | 6fb70e9c9542323f82a9a8714727cc668ff58567 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | Codeforces/CF1618F.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2021
*/
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <string>
using std::set;
using std::string;
long long x, y;
string tar, ori;
set<string> cur;
void dfs(string s)
{
if (cur.count(s) || s.length() > 100)
return;
if (s == tar)
{
puts("YES");
exit(0);
}
cur.insert(s);
auto it = s.rbegin();
while (it != s.rend() && *it == '0')
++it;
string t;
while (it != s.rend())
{
t += *it;
++it;
}
dfs(t);
std::reverse(s.begin(), s.end());
dfs("1" + s);
}
int main()
{
scanf("%lld%lld", &x, &y);
while (y)
{
tar += '0' + (y & 1);
y >>= 1;
}
std::reverse(tar.begin(), tar.end());
while (x)
{
ori += '0' + (x & 1);
x >>= 1;
}
std::reverse(ori.begin(), ori.end());
dfs(ori);
puts("NO");
return 0;
} | 16.177419 | 42 | 0.461615 | Nickel-Angel |
029f7862c89879897231d107e993919270bfa276 | 1,241 | hpp | C++ | src/Event/KeyboardEvent.hpp | billy4479/BillyEngine | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | 1 | 2021-09-05T20:50:59.000Z | 2021-09-05T20:50:59.000Z | src/Event/KeyboardEvent.hpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | src/Event/KeyboardEvent.hpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | #pragma once
#include "Event.hpp"
#include "KeyCodes.hpp"
namespace BillyEngine {
class KeyboardEvent : public Event {
public:
KeyboardEvent(Key::KeyCode keyCode, Key::Mods::Mods mods)
: m_Key(keyCode), m_Mods(mods) {}
EVENT_CLASS_CATEGORY(EventCategory::Input | EventCategory::Keyboard)
Key::KeyCode GetKeyCode() { return m_Key; }
Key::Mods::Mods GetKeyMods() { return m_Mods; }
protected:
Key::KeyCode m_Key;
Key::Mods::Mods m_Mods;
};
class KeyPressedEvent : public KeyboardEvent {
public:
KeyPressedEvent(const Key::KeyCode keycode, const Key::Mods::Mods mods)
: KeyboardEvent(keycode, mods) {}
std::string ToString() const override {
std::stringstream ss;
ss << "KeyPressedEvent: " << m_Key;
return ss.str();
}
EVENT_CLASS_TYPE(KeyPressed)
};
class KeyReleasedEvent : public KeyboardEvent {
public:
KeyReleasedEvent(const Key::KeyCode keycode, const Key::Mods::Mods mods)
: KeyboardEvent(keycode, mods) {}
std::string ToString() const override {
std::stringstream ss;
ss << "KeyReleasedEvent: " << m_Key;
return ss.str();
}
EVENT_CLASS_TYPE(KeyReleased)
};
} // namespace BillyEngine | 24.82 | 76 | 0.65834 | billy4479 |
02a216c58d84cc56bb99ecf6f493fb6d0a725f2a | 1,780 | cpp | C++ | Volume105/10582 - ASCII Labyrinth/10582.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | 1 | 2017-01-25T18:07:49.000Z | 2017-01-25T18:07:49.000Z | Volume105/10582 - ASCII Labyrinth/10582.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | Volume105/10582 - ASCII Labyrinth/10582.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define N 64
#define M 3
#define DIR 4
using namespace std;
int t;
int n,m;
char tab[N][N][M][M];
int mat[N][N];
int vis[N][N];
int x[DIR]={0,0,-1,1};
int y[DIR]={-1,1,0,0};
int sol;
void compute(int i,int j,int dir)
{
if(i==n-1 && j==m-1)
{
if(mat[i][j]!=0)
sol++;
return;
}
if(mat[i][j]==0)
return;
if(mat[i][j]==1)
{
int t1 = i+x[dir];
int t2 = j+y[dir];
if(t1>=0 && t1<n && t2>=0 && t2<m && !vis[t1][t2])
{
vis[t1][t2]=1;
compute(t1,t2,dir);
vis[t1][t2]=0;
}
}
else
{
int p1=0,p2=1;
if(dir==0 || dir==1)
{
p1=2;
p2=3;
}
int t1=i+x[p1];
int t2=j+y[p1];
int t3=i+x[p2];
int t4=j+y[p2];
if(t1>=0 && t1<n && t2>=0 && t2<m && !vis[t1][t2])
{
vis[t1][t2]=1;
compute(t1,t2,p1);
vis[t1][t2]=0;
}
if(t3>=0 && t3<n && t4>=0 && t4<m && !vis[t3][t4])
{
vis[t3][t4]=1;
compute(t3,t4,p2);
vis[t3][t4]=0;
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
getline(cin,s);
istringstream iss(s);
iss>>t;
while(t--)
{
getline(cin,s);
istringstream iss(s);
iss>>n>>m;
for(int i=0;i<n*4;++i)
{
getline(cin,s);
if(i%4!=0)
{
for(int j=0;j<4*m;++j)
{
if(j%4!=0)
{
tab[i/4][j/4][i%4-1][j%4-1]=s[j];
}
}
}
}
getline(cin,s);
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
if(tab[i][j][1][0]=='*' && tab[i][j][1][1]=='*' && tab[i][j][1][2]=='*')
mat[i][j]=1;
else if(tab[i][j][1][0]=='*' && tab[i][j][1][1]=='*' && tab[i][j][2][1]=='*')
mat[i][j]=2;
else
mat[i][j]=0;
}
}
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
vis[i][j]=0;
sol=0;
vis[0][0]=1;
compute(0,0,1);
compute(0,0,3);
cout<<"Number of solutions: "<<sol<<"\n";
}
return 0;
} | 15.344828 | 81 | 0.451124 | rstancioiu |
02a53a62b1405396c37f4ef32977b172e8bb6076 | 1,573 | cpp | C++ | adopt_lock/adopt_lock.cpp | giorgiozoppi/cppconcurrency | 7c19f780f5649cd048467a013e42948e5ba2efd5 | [
"MIT"
] | null | null | null | adopt_lock/adopt_lock.cpp | giorgiozoppi/cppconcurrency | 7c19f780f5649cd048467a013e42948e5ba2efd5 | [
"MIT"
] | null | null | null | adopt_lock/adopt_lock.cpp | giorgiozoppi/cppconcurrency | 7c19f780f5649cd048467a013e42948e5ba2efd5 | [
"MIT"
] | null | null | null | #include <mutex>
#include <thread>
#include <iostream>
class BankAccount {
public:
explicit BankAccount(int balance): balance(balance) {}
int getBalance() { return balance; }
friend void transfer(BankAccount* fromAcc, BankAccount* toAcc, int amount);
private:
int balance;
std::mutex m;
};
void transfer(BankAccount* fromAcc, BankAccount* toAcc, int amount) {
// first two mutexes are locked
std::lock(fromAcc->m, toAcc->m);
// two lock_guard instances are constructed, one for each mutex
// std::adopt_lock parameter specifies that mutexes are already
// locked, and they should just adopt the ownership of the existing
// lock on the mutex rather than attempt to lock the mutex in the
// constructor.
std::lock_guard<std::mutex> lock1(fromAcc->m, std::adopt_lock);
std::lock_guard<std::mutex> lock2(toAcc->m, std::adopt_lock);
fromAcc->balance -= amount;
toAcc->balance += amount;
}
int main() {
BankAccount person1(100);
BankAccount person2(200);
std::cout << "Balance person1: " << person1.getBalance() << std::endl;
std::cout << "Balance person2: " << person2.getBalance() << std::endl;
std::thread t1(transfer, &person1, &person2, 50);
std::thread t2(transfer, &person2, &person1, 20);
if (t1.joinable()) t1.join();
if (t2.joinable()) t2.join();
std::cout << "Balance person1 after transfer: " <<
person1.getBalance() << std::endl;
std::cout << "Balance person2 after transfer: " <<
person2.getBalance() << std::endl;
return 0;
} | 30.843137 | 79 | 0.656707 | giorgiozoppi |
02a7a66dfb63a9527f9cb4ae8e89f1d70cb2a936 | 4,331 | cpp | C++ | lib/Parser/FunctionBuilder.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 80 | 2015-02-19T21:38:57.000Z | 2016-05-25T06:53:12.000Z | lib/Parser/FunctionBuilder.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 8 | 2015-02-20T09:47:20.000Z | 2015-11-13T07:49:17.000Z | lib/Parser/FunctionBuilder.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 6 | 2015-02-20T11:26:19.000Z | 2016-04-13T14:30:39.000Z | #include <locic/AST.hpp>
#include <locic/Debug/SourcePosition.hpp>
#include <locic/Parser/FunctionBuilder.hpp>
#include <locic/Parser/TokenReader.hpp>
namespace locic {
namespace Parser {
FunctionBuilder::FunctionBuilder(const TokenReader& reader)
: reader_(reader) { }
FunctionBuilder::~FunctionBuilder() { }
AST::Node<AST::Function>
FunctionBuilder::makeFunctionDecl(bool isVarArg, bool isStatic,
AST::Node<AST::TypeDecl> returnType, AST::Node<Name> name,
AST::Node<AST::VarList> parameters,
AST::Node<AST::ConstSpecifier> constSpecifier,
AST::Node<AST::RequireSpecifier> noexceptSpecifier,
AST::Node<AST::RequireSpecifier> requireSpecifier,
const Debug::SourcePosition& start) {
const auto location = reader_.locationWithRangeFrom(start);
std::unique_ptr<AST::Function> function(new AST::Function());
function->setIsVarArg(isVarArg);
function->setIsStatic(isStatic);
function->setNameDecl(std::move(name));
function->setReturnType(std::move(returnType));
function->setParameterDecls(std::move(parameters));
function->setConstSpecifier(std::move(constSpecifier));
function->setNoexceptSpecifier(std::move(noexceptSpecifier));
function->setRequireSpecifier(std::move(requireSpecifier));
return AST::makeNode(location, function.release());
}
AST::Node<AST::Function>
FunctionBuilder::makeFunctionDef(bool isVarArg, bool isStatic,
AST::Node<AST::TypeDecl> returnType, AST::Node<Name> name,
AST::Node<AST::VarList> parameters,
AST::Node<AST::ConstSpecifier> constSpecifier,
AST::Node<AST::RequireSpecifier> noexceptSpecifier,
AST::Node<AST::RequireSpecifier> requireSpecifier,
AST::Node<AST::Scope> scope,
const Debug::SourcePosition& start) {
const auto location = reader_.locationWithRangeFrom(start);
std::unique_ptr<AST::Function> function(new AST::Function());
function->setIsVarArg(isVarArg);
function->setIsStatic(isStatic);
function->setNameDecl(std::move(name));
function->setReturnType(std::move(returnType));
function->setParameterDecls(std::move(parameters));
function->setConstSpecifier(std::move(constSpecifier));
function->setNoexceptSpecifier(std::move(noexceptSpecifier));
function->setRequireSpecifier(std::move(requireSpecifier));
function->setScope(std::move(scope));
return AST::makeNode(location, function.release());
}
AST::Node<AST::Function>
FunctionBuilder::makeDefaultMethod(bool isStatic, AST::Node<Name> name,
AST::Node<AST::RequireSpecifier> requireSpecifier,
const Debug::SourcePosition& start) {
const auto location = reader_.locationWithRangeFrom(start);
std::unique_ptr<AST::Function> function(new AST::Function());
function->setIsStatic(isStatic);
function->setAutoGenerated(true);
function->setNameDecl(std::move(name));
function->setRequireSpecifier(std::move(requireSpecifier));
return AST::makeNode(location, function.release());
}
AST::Node<AST::Function>
FunctionBuilder::makeDestructor(AST::Node<Name> name, AST::Node<AST::Scope> scope,
const Debug::SourcePosition& start) {
const auto location = reader_.locationWithRangeFrom(start);
std::unique_ptr<AST::Function> function(new AST::Function());
function->setNameDecl(std::move(name));
function->setReturnType(AST::makeNode(scope.location(),
AST::TypeDecl::Void()));
function->setParameterDecls(AST::makeDefaultNode<AST::VarList>());
function->setScope(std::move(scope));
return AST::makeNode(location, function.release());
}
AST::Node<Name>
FunctionBuilder::makeName(Name name, const Debug::SourcePosition& start) {
const auto location = reader_.locationWithRangeFrom(start);
return AST::makeNode(location, new Name(std::move(name)));
}
}
}
| 45.589474 | 94 | 0.641422 | scross99 |
02a810f45d6bc4b465de8be7ebd0c44ade2b405c | 5,526 | cpp | C++ | murdoch_rta/src/murdoch_rta/resource/IntegerRange.cpp | caueguidotti/MRTA | a933fde4046444c9aa5750cf7b42f19a88e5bb3d | [
"BSD-3-Clause"
] | 1 | 2018-07-17T00:51:11.000Z | 2018-07-17T00:51:11.000Z | murdoch_rta/src/murdoch_rta/resource/IntegerRange.cpp | caueguidotti/MRTA | a933fde4046444c9aa5750cf7b42f19a88e5bb3d | [
"BSD-3-Clause"
] | 1 | 2018-08-01T03:01:46.000Z | 2020-10-24T22:33:36.000Z | murdoch_rta/src/murdoch_rta/resource/IntegerRange.cpp | caueguidotti/MRTA | a933fde4046444c9aa5750cf7b42f19a88e5bb3d | [
"BSD-3-Clause"
] | null | null | null | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Caue Franco Guidotti
* 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 copyright holder 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.
*/
#include "murdoch_rta/resource/IntegerRange.h"
namespace murdoch_rta
{
namespace resource
{
IntegerRange::IntegerRange(int lowerBoundValue, int upperBoundValue, std::string resourceIdentifier, bool isIddle)
: Resource(IntegerRangeResource, resourceIdentifier, isIddle)
, _resourceLowerBound(lowerBoundValue)
, _resourceUpperBound(upperBoundValue)
{
}
IntegerRange::IntegerRange(const murdoch_rta_msgs::Resource &resourceMsgRos) : Resource(resourceMsgRos)
{
_resourceLowerBound = resourceMsgRos.integerResourceValue1;
_resourceUpperBound = resourceMsgRos.integerResourceValue2;
}
IntegerRange::IntegerRange(const IntegerRange &resource)
: Resource(resource.getResourceType(), resource.getResourceIdentifier(), resource.getIsIddle())
, _resourceLowerBound(resource.getResourceLowerBound())
, _resourceUpperBound(resource.getResourceUpperBound())
{
}
IntegerRange::~IntegerRange()
{
}
int IntegerRange::getResourceUpperBound() const
{
return _resourceUpperBound;
}
void IntegerRange::setResourceUpperBound(int value)
{
_resourceUpperBound = value;
}
int IntegerRange::getResourceLowerBound() const
{
return _resourceLowerBound;
}
void IntegerRange::setResourceLowerBound(int value)
{
_resourceLowerBound = value;
}
murdoch_rta_msgs::Resource IntegerRange::toRosMessage() const
{
murdoch_rta_msgs::Resource res;
res.baseMsg.messageTime = ros::Time::now();
res.type = _resourceType;
res.resourceID = _resourceIdentifier;
res.integerResourceValue1 = _resourceLowerBound;
res.integerResourceValue2 = _resourceUpperBound;
return res;
}
int IntegerRange::resCompareUpperBound(ResourcePtr res1, ResourcePtr res2)
{
boost::shared_ptr<resource::IntegerRange> res1Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res1);
boost::shared_ptr<resource::IntegerRange> res2Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res2);
return IntegerRange::resCompareUpperBound(res1Typed, res2Typed);
}
int IntegerRange::resCompareUpperBound(boost::shared_ptr<IntegerRange> res1, boost::shared_ptr<IntegerRange> res2)
{
return res1->getResourceUpperBound() - res2->getResourceUpperBound();
}
int IntegerRange::resCompareLowerBound(ResourcePtr res1, ResourcePtr res2)
{
boost::shared_ptr<resource::IntegerRange> res1Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res1);
boost::shared_ptr<resource::IntegerRange> res2Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res2);
return IntegerRange::resCompareLowerBound(res1Typed, res2Typed);
}
int IntegerRange::resCompareLowerBound(boost::shared_ptr<IntegerRange> res1, boost::shared_ptr<IntegerRange> res2)
{
return res1->getResourceLowerBound() - res2->getResourceLowerBound();
}
int IntegerRange::resCompare(ResourcePtr res1, ResourcePtr res2)
{
boost::shared_ptr<resource::IntegerRange> res1Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res1);
boost::shared_ptr<resource::IntegerRange> res2Typed = boost::dynamic_pointer_cast<resource::IntegerRange>(res2);
return IntegerRange::resCompare(res1Typed, res2Typed);
}
int IntegerRange::resCompare(boost::shared_ptr<IntegerRange> res1, boost::shared_ptr<IntegerRange> res2)
{
float lowerCompare = IntegerRange::resCompareLowerBound(res1, res2);
float upperCompare = IntegerRange::resCompareUpperBound(res1, res2);
if (lowerCompare < 0 && upperCompare > 0)
return 1;
if (lowerCompare == 0 && upperCompare == 0)
return 0;
return -1;
}
void IntegerRange::printResource(std::ostream &out) const
{
out << "\n\tID:\t" << getResourceIdentifier() << "\n\tValue:\t(" << getResourceLowerBound() << ", "
<< getResourceUpperBound() << ")"
<< "\n\tType:\tFloatRange";
}
}
}
| 36.117647 | 115 | 0.74991 | caueguidotti |
02a8b5e456ab04346a8605f66c1ebbd3ae9c3fef | 4,411 | cpp | C++ | ContourTiler/CloseContourRanker.cpp | GuMiner/agow | b8665d5879f43a6bcb6e878827b3b25af9cc1b1d | [
"MIT"
] | null | null | null | ContourTiler/CloseContourRanker.cpp | GuMiner/agow | b8665d5879f43a6bcb6e878827b3b25af9cc1b1d | [
"MIT"
] | null | null | null | ContourTiler/CloseContourRanker.cpp | GuMiner/agow | b8665d5879f43a6bcb6e878827b3b25af9cc1b1d | [
"MIT"
] | null | null | null | #include "CloseContourRanker.h"
CloseContourRanker::CloseContourRanker()
: closestLine(CloseContourLine()), secondClosestLine(CloseContourLine()), thirdClosestLine(CloseContourLine())
{
}
bool CloseContourRanker::ResortIfIdentical(CloseContourLine contourLine)
{
if (closestLine.elevationId == contourLine.elevationId)
{
// Identical, resorting done.
if (contourLine.distanceSqd < closestLine.distanceSqd)
{
closestLine.distanceSqd = contourLine.distanceSqd;
}
return true;
}
else if (secondClosestLine.elevationId == contourLine.elevationId)
{
if (contourLine.distanceSqd < secondClosestLine.distanceSqd)
{
secondClosestLine.distanceSqd = contourLine.distanceSqd;
if (secondClosestLine.distanceSqd < closestLine.distanceSqd)
{
// Swap
CloseContourLine other;
other.CopyFrom(closestLine);
closestLine.CopyFrom(secondClosestLine);
secondClosestLine.CopyFrom(other);
}
}
return true;
}
else if (thirdClosestLine.elevationId == contourLine.elevationId)
{
if (contourLine.distanceSqd < thirdClosestLine.distanceSqd)
{
thirdClosestLine.distanceSqd = contourLine.distanceSqd;
if (thirdClosestLine.distanceSqd < closestLine.distanceSqd)
{
// Swap and move down #2
CloseContourLine other;
other.CopyFrom(closestLine);
closestLine.CopyFrom(thirdClosestLine);
thirdClosestLine.CopyFrom(secondClosestLine);
secondClosestLine.CopyFrom(other);
}
else if (thirdClosestLine.distanceSqd < secondClosestLine.distanceSqd)
{
CloseContourLine other;
other.CopyFrom(secondClosestLine);
secondClosestLine.CopyFrom(thirdClosestLine);
thirdClosestLine.CopyFrom(other);
}
}
return true;
}
return false;
}
void CloseContourRanker::AddElevationToRank(const CloseContourLine& contourLine)
{
if (ResortIfIdentical(contourLine))
{
return;
}
// Not identical, figure out if it we need to insert this contour line anywhere.
// Handle each contour sequentially, filling it in automatically if empty.
if (closestLine.elevationId == -1)
{
closestLine.CopyFrom(contourLine);
return;
}
else if (contourLine.distanceSqd < closestLine.distanceSqd)
{
// Move all down.
thirdClosestLine.CopyFrom(secondClosestLine);
secondClosestLine.CopyFrom(closestLine);
closestLine.CopyFrom(contourLine);
return;
}
if (secondClosestLine.elevationId == -1)
{
secondClosestLine.CopyFrom(contourLine);
return;
}
else if (contourLine.distanceSqd < secondClosestLine.distanceSqd)
{
// Move second and third down.
thirdClosestLine.CopyFrom(secondClosestLine);
secondClosestLine.CopyFrom(contourLine);
return;
}
if (thirdClosestLine.elevationId == -1 || contourLine.distanceSqd < thirdClosestLine.distanceSqd)
{
thirdClosestLine.CopyFrom(contourLine);
return;
}
}
bool CloseContourRanker::FilledSufficientLines() const
{
return closestLine.elevationId != -1 && secondClosestLine.elevationId != -1; // && thirdClosestLine.elevationId != -1;
}
decimal CloseContourRanker::GetWeightedElevation() const
{
// We're guaranteed to have something in the closest line, but nothing in the other two.
decimal elevation = 0;
decimal inverseWeights = 0;
// Double the sqrt for a less drastic flow.
decimal distCL = closestLine.distanceSqd;
elevation += closestLine.elevation / distCL;
inverseWeights += (decimal)1.0 / distCL;
if (secondClosestLine.elevationId != -1)
{
distCL = secondClosestLine.distanceSqd;
elevation += secondClosestLine.elevation / distCL;
inverseWeights += (decimal)1.0 / distCL;
}
if (thirdClosestLine.elevationId != -1)
{
distCL = thirdClosestLine.distanceSqd;
elevation += thirdClosestLine.elevation / distCL;
inverseWeights += (decimal)1.0 / distCL;
}
return elevation / inverseWeights;
} | 30.631944 | 122 | 0.642938 | GuMiner |
02aa9fbddd18b0f443fd9499e88de2f5ab907888 | 198 | hh | C++ | Include/Zion/Main.hh | zionmultiplayer/Client | 291c027c4011cb1ab207c9b394fb5f4b1da8652c | [
"MIT"
] | 4 | 2022-02-08T07:04:49.000Z | 2022-02-09T23:43:49.000Z | Include/Zion/Main.hh | zionmultiplayer/Client | 291c027c4011cb1ab207c9b394fb5f4b1da8652c | [
"MIT"
] | null | null | null | Include/Zion/Main.hh | zionmultiplayer/Client | 291c027c4011cb1ab207c9b394fb5f4b1da8652c | [
"MIT"
] | null | null | null | #pragma once
#include "Game/CPad.h"
#include "Game/CPlayerPed.h"
namespace Zion
{
class Main
{
public:
static CPlayerPed *player;
static CPad *pad;
};
}; | 15.230769 | 38 | 0.560606 | zionmultiplayer |
02abbb2801446ddd72cdac1c1ee8d8876f2d97eb | 1,018 | hpp | C++ | src/metal-driver/pseudo_operators.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 12 | 2020-04-21T05:21:32.000Z | 2022-02-19T11:27:18.000Z | src/metal-driver/pseudo_operators.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 10 | 2019-02-10T17:10:16.000Z | 2020-02-01T20:05:42.000Z | src/metal-driver/pseudo_operators.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 4 | 2020-07-15T04:42:20.000Z | 2022-02-19T11:27:19.000Z | #pragma once
#include <stdint.h>
#include <cxxopts.hpp>
namespace metal {
class OperatorAgent;
class DatagenOperator {
public:
static std::string id() { return "datagen"; }
static bool isDatagenAgent(const OperatorAgent &agent);
static void validate(OperatorAgent &agent);
static bool isProfilingEnabled(OperatorAgent &agent);
static uint64_t datagenLength(OperatorAgent &agent);
static void setInputFile(OperatorAgent &agent);
protected:
static cxxopts::ParseResult parseOptions(OperatorAgent &agent);
};
class MetalCatOperator {
public:
static std::string id() { return "metal-cat"; }
static bool isMetalCatAgent(const OperatorAgent &agent);
static void validate(OperatorAgent &agent);
static bool isProfilingEnabled(OperatorAgent &agent);
static void setInputFile(OperatorAgent &agent);
protected:
static cxxopts::ParseResult parseOptions(OperatorAgent &agent);
};
class DevNullFile {
public:
static bool isNullOutput(const OperatorAgent &agent);
};
} // namespace metal
| 24.238095 | 65 | 0.764244 | metalfs |
02abf685440a7045f4f1884222d8248747a38684 | 1,424 | cpp | C++ | util/Bip39.cpp | velezladonna/mwc-qt-wallet | bd241b91d28350e17e52a10208e663fcb992d7cc | [
"Apache-2.0"
] | 1 | 2020-03-19T10:02:16.000Z | 2020-03-19T10:02:16.000Z | util/Bip39.cpp | velezladonna/mwc-qt-wallet | bd241b91d28350e17e52a10208e663fcb992d7cc | [
"Apache-2.0"
] | null | null | null | util/Bip39.cpp | velezladonna/mwc-qt-wallet | bd241b91d28350e17e52a10208e663fcb992d7cc | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The MWC Developers
//
// 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 "Bip39.h"
#include <QApplication>
#include "../control/messagebox.h"
#include <QFile>
#include <QTextStream>
namespace util {
static QSet<QString> bip39words;
const QSet<QString> & getBip39words() {
if (bip39words.empty()) {
// load the words
QFile file(":/txt/bip39_words.txt");
if (!file.open(QFile::ReadOnly)) {
control::MessageBox::messageText(nullptr, "Fatal Error", "Unable to read bip39 dictionary from the resources");
QApplication::quit();
return bip39words;
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine().trimmed();
if (line.isEmpty())
continue;
bip39words += line;
}
file.close();
}
return bip39words;
}
}
| 27.384615 | 123 | 0.643258 | velezladonna |
02ad6389b3ff30b8ad3461909f013803a088a115 | 1,575 | hpp | C++ | include/humanity/io/file.hpp | crimsonwoods/humanity | 5c2cc601eb8823ca7c06a0bef5cde0122b4d067a | [
"MIT"
] | 1 | 2019-04-16T16:06:05.000Z | 2019-04-16T16:06:05.000Z | include/humanity/io/file.hpp | crimsonwoods/humanity | 5c2cc601eb8823ca7c06a0bef5cde0122b4d067a | [
"MIT"
] | null | null | null | include/humanity/io/file.hpp | crimsonwoods/humanity | 5c2cc601eb8823ca7c06a0bef5cde0122b4d067a | [
"MIT"
] | null | null | null | /**
* ファイルを扱うためのクラス定義ファイル
* @file file.hpp
*/
#ifndef HUMANITY_IO_FILE_H
#define HUMANITY_IO_FILE_H
#include <humanity/io/io.hpp>
HUMANITY_IO_NS_BEGIN
class path;
/**
* ファイルを扱うためのクラス
*/
class file {
public:
/**
* ファイルのモードを表す定数値群
*/
enum {
FMODE_USER_READ = 0400,
FMODE_USER_WRITE = 0200,
FMODE_USER_EXEC = 0100,
FMODE_USER_RW = FMODE_USER_READ | FMODE_USER_WRITE,
FMODE_USER_RX = FMODE_USER_READ | FMODE_USER_EXEC,
FMODE_USER_WX = FMODE_USER_WRITE | FMODE_USER_EXEC,
FMODE_USER_RWX = FMODE_USER_READ | FMODE_USER_WRITE | FMODE_USER_EXEC,
FMODE_GROUP_READ = 0040,
FMODE_GROUP_WRITE = 0020,
FMODE_GROUP_EXEC = 0010,
FMODE_GROUP_RW = FMODE_GROUP_READ | FMODE_GROUP_WRITE,
FMODE_GROUP_RX = FMODE_GROUP_READ | FMODE_GROUP_EXEC,
FMODE_GROUP_WX = FMODE_GROUP_WRITE | FMODE_GROUP_EXEC,
FMODE_GROUP_RWX = FMODE_GROUP_READ | FMODE_GROUP_WRITE | FMODE_GROUP_EXEC,
FMODE_OTHER_READ = 0004,
FMODE_OTHER_WRITE = 0002,
FMODE_OTHER_EXEC = 0001,
FMODE_OTHER_RW = FMODE_OTHER_READ | FMODE_OTHER_WRITE,
FMODE_OTHER_RX = FMODE_OTHER_READ | FMODE_OTHER_EXEC,
FMODE_OTHER_WX = FMODE_OTHER_WRITE | FMODE_OTHER_EXEC,
FMODE_OTHER_RWX = FMODE_OTHER_READ | FMODE_OTHER_WRITE | FMODE_OTHER_EXEC,
};
static bool is_link(path const &path);
static bool is_exist(path const &path);
static bool chmod(path const &path, uint16_t mode);
static bool remove(path const &path);
static bool rename(path const &src, path const &dst);
};
HUMANITY_IO_NS_END
#endif // end of HUMANITY_IO_FILE_H
| 27.155172 | 79 | 0.743492 | crimsonwoods |
02aea3a9f2104d5b36ad58263d19937bd6aea589 | 3,234 | cc | C++ | vos/MotifApp/YesNoDialog.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/MotifApp/YesNoDialog.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/MotifApp/YesNoDialog.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | ///////////////////////////////////////////////////////////////
// YesNoDialog.h: Motif Question dialog that also contains No
// button. Note that this dialog is not cached, it is created
// at every request and destroys itself when user presses any of
// the buttons.
////////////////////////////////////////////////////////////////
#include "YesNoDialog.h"
#include "Cmd.h"
#include "Application.h"
#include <Xm/MessageB.h>
#include <Xm/PushB.h>
#include <stdio.h>
String YesNoDialog::_defaults[] = {
(char *)"*okLabelString: Yes",
(char *)"*no.labelString: No",
NULL,
};
#define DEFAULTQUESTION "Do you want to save changes?"
YesNoDialog::YesNoDialog (const char *name, void *clientData,
const char *question,
DialogCallback yes,
DialogCallback no,
DialogCallback cancel,
DialogCallback help)
: UIComponent (name)
{
_clientData = clientData;
_yes = yes;
_no = no;
_cancel = cancel;
_help = help;
if (question && strlen(question))
_question = strdup(question);
else
_question = strdup(DEFAULTQUESTION);
XmString msgStr = XmStringCreateLocalized (_question);
Arg args[5];
int n = 0;
XtSetArg (args[n], XmNautoUnmanage, False); n++;
XtSetArg (args[n], XmNmessageString, msgStr); n++;
setDefaultResources ( theApplication->baseWidget(), _defaults );
Widget dialog = XmCreateQuestionDialog (theApplication->baseWidget(),
_name, args, n);
XtVaSetValues (dialog,
XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL,
NULL);
if (help == NULL)
XtUnmanageChild (XmMessageBoxGetChild (dialog, XmDIALOG_HELP_BUTTON));
_w = XtParent (dialog);
installDestroyHandler();
XtAddCallback (dialog, XmNokCallback,
YesNoDialog::yesCallback,
(XtPointer) this);
XtAddCallback (dialog, XmNcancelCallback,
YesNoDialog::cancelCallback,
(XtPointer) this);
XmStringFree (msgStr);
Widget noButton = XtVaCreateManagedWidget ("no",
xmPushButtonWidgetClass, dialog,
NULL);
XtAddCallback (noButton, XmNactivateCallback,
YesNoDialog::noCallback,
(XtPointer) this);
XtManageChild(dialog);
manage();
}
YesNoDialog::~YesNoDialog()
{
XtPopdown (_w);
}
void YesNoDialog::manage()
{
UIComponent::manage();
XtPopup (_w, XtGrabNone);
}
void YesNoDialog::yesCallback (Widget, XtPointer clientData,
XtPointer)
{
YesNoDialog *obj = (YesNoDialog *) clientData;
// Call the base class execute() member function
// to do all the usual processing of the command
obj->yes();
delete obj;
}
void YesNoDialog::yes()
{
(*_yes)(_clientData);
}
void YesNoDialog::noCallback (Widget, XtPointer clientData,
XtPointer)
{
YesNoDialog *obj = (YesNoDialog *) clientData;
obj->no();
delete obj;
}
void YesNoDialog::no()
{
(*_no)(_clientData);
}
void YesNoDialog::cancelCallback (Widget, XtPointer clientData,
XtPointer)
{
YesNoDialog *obj = (YesNoDialog *) clientData;
delete obj;
}
void YesNoDialog::helpCallback (Widget, XtPointer clientData,
XtPointer)
{
YesNoDialog *obj = (YesNoDialog *) clientData;
obj->help();
}
void YesNoDialog::help()
{
(*_help)(_clientData);
}
| 22.774648 | 74 | 0.648423 | NASA-AMMOS |
02aeb57f89aacc9e872341e5208681726dcb708b | 1,737 | hpp | C++ | src/include/duckdb/common/re2_regex.hpp | lokax/duckdb | c2581dfebccaebae9468c924c2c722fcf0306944 | [
"MIT"
] | 1 | 2022-01-06T17:44:07.000Z | 2022-01-06T17:44:07.000Z | src/include/duckdb/common/re2_regex.hpp | lokax/duckdb | c2581dfebccaebae9468c924c2c722fcf0306944 | [
"MIT"
] | 32 | 2021-09-24T23:50:09.000Z | 2022-03-29T09:37:26.000Z | src/include/duckdb/common/re2_regex.hpp | lokax/duckdb | c2581dfebccaebae9468c924c2c722fcf0306944 | [
"MIT"
] | null | null | null | // RE2 compatibility layer with std::regex
#pragma once
#include "duckdb/common/winapi.hpp"
#include <vector>
#include <string>
#include <stdexcept>
namespace duckdb_re2 {
class RE2;
enum class RegexOptions : uint8_t { NONE, CASE_INSENSITIVE };
class Regex {
public:
DUCKDB_API Regex(const std::string &pattern, RegexOptions options = RegexOptions::NONE);
DUCKDB_API Regex(const char *pattern, RegexOptions options = RegexOptions::NONE) : Regex(std::string(pattern)) {
}
const duckdb_re2::RE2 &GetRegex() const {
return *regex;
}
private:
std::shared_ptr<duckdb_re2::RE2> regex;
};
struct GroupMatch {
std::string text;
uint32_t position;
const std::string &str() const {
return text;
}
operator std::string() const {
return text;
}
};
struct Match {
std::vector<GroupMatch> groups;
GroupMatch &GetGroup(uint64_t index) {
if (index >= groups.size()) {
throw std::runtime_error("RE2: Match index is out of range");
}
return groups[index];
}
std::string str(uint64_t index) {
return GetGroup(index).text;
}
uint64_t position(uint64_t index) {
return GetGroup(index).position;
}
uint64_t length(uint64_t index) {
return GetGroup(index).text.size();
}
GroupMatch &operator[](uint64_t i) {
return GetGroup(i);
}
};
DUCKDB_API bool RegexSearch(const std::string &input, Match &match, const Regex ®ex);
DUCKDB_API bool RegexMatch(const std::string &input, Match &match, const Regex ®ex);
DUCKDB_API bool RegexMatch(const char *start, const char *end, Match &match, const Regex ®ex);
DUCKDB_API bool RegexMatch(const std::string &input, const Regex ®ex);
DUCKDB_API std::vector<Match> RegexFindAll(const std::string &input, const Regex ®ex);
} // namespace duckdb_re2
| 23.472973 | 113 | 0.723661 | lokax |
02b389941a8f99833ac436c39a06ca1cd9194c53 | 72 | cpp | C++ | MailClient/sources/gui/Tasks.cpp | SRIIIXI/XDesk | 4324763a7d981bb3c335d153ebf27a6ddf1cfc13 | [
"BSD-2-Clause"
] | null | null | null | MailClient/sources/gui/Tasks.cpp | SRIIIXI/XDesk | 4324763a7d981bb3c335d153ebf27a6ddf1cfc13 | [
"BSD-2-Clause"
] | null | null | null | MailClient/sources/gui/Tasks.cpp | SRIIIXI/XDesk | 4324763a7d981bb3c335d153ebf27a6ddf1cfc13 | [
"BSD-2-Clause"
] | null | null | null | #include "Tasks.h"
Tasks::Tasks(QWidget *parent) : QWidget(parent)
{
}
| 12 | 47 | 0.680556 | SRIIIXI |
02b6fd676b8055976f0aff9d4ac0daf6de01459b | 16,979 | cpp | C++ | DocCluster/src/DCController.cpp | McGill-DMaS/FIHC | 6928f6fdf62f0e0de004623a8f956e4ca3b3afa1 | [
"Apache-2.0"
] | null | null | null | DocCluster/src/DCController.cpp | McGill-DMaS/FIHC | 6928f6fdf62f0e0de004623a8f956e4ca3b3afa1 | [
"Apache-2.0"
] | null | null | null | DocCluster/src/DCController.cpp | McGill-DMaS/FIHC | 6928f6fdf62f0e0de004623a8f956e4ca3b3afa1 | [
"Apache-2.0"
] | null | null | null | // DCController.cpp: implementation of the CDCController class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#if !defined(DCCONTROLLER_H)
#include "DCController.h"
#endif
#if !defined(DCKMEANSMGR_H)
#include "DCKMeansMgr.h"
#endif
#if !defined(DCCLUTOMGR_H)
#include "DCClutoMgr.h"
#endif
#if !defined(BFFILEHELPER_H)
#include "BFFileHelper.h"
#endif
char runningChars [] = {'-', '\\', '|', '/'};
CDCDebug* debugObject = new CDCDebug();
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDCController::CDCController()
{
}
CDCController::~CDCController()
{
cleanup();
}
BOOL CDCController::initialize(TDCAlgoMode algoMode)
{
if (!m_treeBuilder.initialize(&m_clusterMgr))
return FALSE;
if (!m_evalMgr.initialize(algoMode, &m_docMgr, &m_clusterMgr))
return FALSE;
if (!m_outputMgr.initialize(algoMode, &m_docMgr, &m_clusterMgr, &m_clusterMgr2))
return FALSE;
return TRUE;
}
void CDCController::cleanup()
{
delete debugObject;
debugObject = NULL;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
BOOL CDCController::runFreqItems(FLOAT globalSupport, FLOAT clusterSupport, int kClusters, LPCTSTR inputDir)
{
// Document Manager reads all the files
CString docSetDirPath = inputDir;
docSetDirPath += DC_DOCUMENTS_DIRECTORY;
CString stopWordFilePath = inputDir;
stopWordFilePath += DC_STOPWORDS_FILENAME;
m_docMgr.setDocDirectory((LPCTSTR) docSetDirPath);
m_docMgr.setStopWordFile(DC_STOPWORDS_FILENAME);
m_docMgr.setMinSupport(globalSupport);
m_docMgr.preProcess();
CDCDocuments* pAllDocs = NULL;
m_docMgr.getAllDocs(pAllDocs);
ASSERT(pAllDocs);
CDCFreqItemsets * pF1 = NULL;
m_docMgr.getF1Sets(pF1);
ASSERT(pF1);
DEBUGPrint(_T("********\n"));
DEBUGPrint(_T("* FIHC *\n"));
DEBUGPrint(_T("********\n"));
CDCDebug::printTime();
// Frequent Item Manager mines the frequent itemset (Apriori)
m_freqItemMgr.setMinGlobalSupport(globalSupport);
if (!m_freqItemMgr.mineGlobalFreqItemsets(pAllDocs, pF1)) {
ASSERT(FALSE);
return FALSE;
}
CDCFreqItemsets* pGlobalFreqItemsets = NULL;
m_freqItemMgr.getGlobalFreqItemsets(pGlobalFreqItemsets);
ASSERT(pGlobalFreqItemsets);
#ifdef _DEBUG_PRT_INFO
DEBUGPrint("Global frequent itemsets\n");
debugObject->printFreqItemsets(*pGlobalFreqItemsets);
#endif
// Cluster Manager builds the clusters of documents
CDCDebug::printTime();
if (TRUE) {
// tree based clustering
if (!m_clusterMgr.makeClusters(pAllDocs, pGlobalFreqItemsets, clusterSupport)) {
ASSERT(FALSE);
return FALSE;
}
}
else {
// linear clustering
m_clusterMgr2.setAllDocs(pAllDocs);
m_clusterMgr2.setClusterSupport(clusterSupport);
TDCClusterOrderType orderType = ORDER_TYPE_GLOBAL_SUP;
BOOL descOrAsc = TRUE;
if(!m_clusterMgr2.produceClusters(pGlobalFreqItemsets, orderType, descOrAsc)) {
ASSERT(FALSE);
return FALSE;
}
}
// Tree Builder constructs the topical tree
CDCDebug::printTime();
if (!m_treeBuilder.buildTree()) {
ASSERT(FALSE);
return FALSE;
}
// Remove empty clusters
CDCDebug::printTime();
if (!m_treeBuilder.removeEmptyClusters(FALSE)) {
ASSERT(FALSE);
return FALSE;
}
/*
// Pruning clusters from tree
if (!m_treeBuilder.pruneTree()) {
ASSERT(FALSE);
return FALSE;
}
*/
if (TRUE) {
// prune children based on inter-cluster similarity with parent
if (!m_treeBuilder.pruneChildren()) {
ASSERT(FALSE);
return FALSE;
}
/*
// Remove empty clusters
if (!m_treeBuilder.removeEmptyClusters(TRUE)) {
ASSERT(FALSE);
return FALSE;
}
*/
// inter-cluster similarity based pruning
if (!m_treeBuilder.interSimPrune(kClusters)) {
ASSERT(FALSE);
return FALSE;
}
/*
// similarity based pruning
if (!m_treeBuilder.simBasedPrune(kClusters)) {
ASSERT(FALSE);
return FALSE;
}
*/
// score based pruning
if (!m_treeBuilder.interSimOverPrune(kClusters)) {
ASSERT(FALSE);
return FALSE;
}
}
else {
// score based pruning
if (!m_treeBuilder.interSimOverPrune(kClusters)) {
ASSERT(FALSE);
return FALSE;
}
}
// Evaluate clusters using overall similairty
CDCDebug::printTime();
CDCClusterWH* pClusterWH = NULL;
m_clusterMgr.getClusterWH(pClusterWH);
CDCCluster* pRoot = NULL;
if (!pClusterWH->getTreeRoot(pRoot)) {
ASSERT(FALSE);
return FALSE;
}
// Evaluate clusters using FMeasure
FLOAT fMeasure = 0.0f;
if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) {
ASSERT(FALSE);
return FALSE;
}
DEBUGPrint(_T("F-Measure = %f\n"), fMeasure);
// Evaluate overall similarity
FLOAT overallSim = 0.0f;
if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) {
ASSERT(FALSE);
return FALSE;
}
//DEBUGPrint(_T("Overall similarity = %f\n"), overallSim);
// Evaluate clusters using entropy
FLOAT entropyH = 0.0f;
if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) {
ASSERT(FALSE);
return FALSE;
}
//DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH);
FLOAT entropyF = 0.0f;
if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) {
ASSERT(FALSE);
return FALSE;
}
DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF);
// Output Manager organizes and displays the results to user
CString inputDirStr = inputDir;
CString prefixStr;
int slashPos = inputDirStr.ReverseFind(TCHAR('\\'));
if (slashPos == -1)
prefixStr = DC_XML_FREQITEM_FILENAME;
else
prefixStr = inputDirStr.Mid(slashPos + 1);
CString outFilePath = makeOutFilePath(_T(".."), (LPCTSTR) prefixStr, globalSupport, clusterSupport, kClusters, fMeasure, entropyF);
if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, fMeasure, overallSim, entropyH, entropyF)) {
ASSERT(FALSE);
return FALSE;
}
DEBUGPrint(_T("Output file: %s\n"), outFilePath);
CDCDebug::printTime();
return TRUE;
}
//---------------------------------------------------------------------------
// Run the K-Means algorithm
//---------------------------------------------------------------------------
BOOL CDCController::runKMeans(int kClusters, LPCTSTR inputDir)
{
// Document Manager reads all the files
CString docSetDirPath = inputDir;
docSetDirPath += DC_DOCUMENTS_DIRECTORY;
CString stopWordFilePath = inputDir;
stopWordFilePath += DC_STOPWORDS_FILENAME;
m_docMgr.setDocDirectory((LPCTSTR) docSetDirPath);
m_docMgr.setStopWordFile(DC_STOPWORDS_FILENAME);
m_docMgr.setMinSupport(0.0f);
m_docMgr.preProcess();
CDCDocuments* pAllDocs = NULL;
m_docMgr.getAllDocs(pAllDocs);
ASSERT(pAllDocs);
#ifdef DC_DOCVECTOR_CONVERTOR
if (!writeVectorsFile(pAllDocs)) {
ASSERT(FALSE);
return FALSE;
}
return TRUE;
#endif
// Run the K-Means algorithm
DEBUGPrint("***********\n");
DEBUGPrint("* K-Means *\n");
DEBUGPrint("***********\n");
CDCDebug::printTime();
CDCKMeansMgr kMeansMgr;
if (!kMeansMgr.makeClusters(kClusters, pAllDocs)) {
ASSERT(FALSE);
return FALSE;
}
CDCDebug::printTime();
CDCCluster* pRoot = NULL;
kMeansMgr.getRoot(pRoot);
CDCClusters* pChildren = NULL;
pRoot->getTreeChildren(pChildren);
// Evaluate clusters using FMeasure
FLOAT fMeasure = 0.0f;
if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("F-Measure = %f\n"), fMeasure);
// Evaluate clusters using overall similairty
FLOAT overallSim = 0.0f;
if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
//DEBUGPrint(_T("Overall similarity = %f\n"), overallSim);
// Evaluate clusters using entropy
FLOAT entropyH = 0.0f;
if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH);
FLOAT entropyF = 0.0f;
if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF);
// Output Manager organizes and displays the results to user
CString inputDirStr = inputDir;
CString prefixStr = DC_XML_KMEANS_FILENAME;
int slashPos = inputDirStr.ReverseFind(TCHAR('\\'));
if (slashPos != -1)
prefixStr += inputDirStr.Mid(slashPos + 1);
CString outFilePath = makeOutFilePath(_T(".."), (LPCTSTR) prefixStr, 0.0f, 0.0f, kClusters, fMeasure, entropyF);
if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, pRoot, fMeasure, overallSim, entropyH, entropyF)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Output file: %s\n"), outFilePath);
CDCDebug::printTime();
pChildren->cleanup();
return TRUE;
}
//---------------------------------------------------------------------------
// Run the Cluto evaluator
//---------------------------------------------------------------------------
BOOL CDCController::runCluto(LPCTSTR solFile, LPCTSTR classFile)
{
DEBUGPrint("*******************\n");
DEBUGPrint("* Cluto Evaluator *\n");
DEBUGPrint("*******************\n");
CDCClutoMgr clutoMgr;
if (!clutoMgr.makeClusters(solFile, classFile)) {
ASSERT(FALSE);
return FALSE;
}
CDCCluster* pRoot = NULL;
clutoMgr.getRoot(pRoot);
CDCClusters* pChildren = NULL;
pRoot->getTreeChildren(pChildren);
// Evaluate clusters using FMeasure
FLOAT fMeasure = 0.0f;
if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("F-Measure = %f\n"), fMeasure);
// Evaluate clusters using overall similairty
FLOAT overallSim = 0.0f;
if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
//DEBUGPrint(_T("Overall similarity = %f\n"), overallSim);
// Evaluate clusters using entropy
FLOAT entropyH = 0.0f;
if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH);
FLOAT entropyF = 0.0f;
if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF);
// get number of clusters
CString drive, dir, fname, ext;
CBFFileHelper::splitPath(solFile, drive, dir, fname, ext);
ext = ext.Mid(1);
int kClusters = StrToInt((LPCTSTR) ext);
// Output Manager organizes and displays the results to user
CString outFilePath = makeOutFilePath(drive + dir, DC_XML_CLUTO_FILENAME, 0.0f, 0.0f, kClusters, fMeasure, entropyF);
if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, pRoot, fMeasure, overallSim, entropyH, entropyF)) {
ASSERT(FALSE);
pChildren->cleanup();
return FALSE;
}
DEBUGPrint(_T("Output file: %s\n"), outFilePath);
pChildren->cleanup();
return TRUE;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
CString CDCController::makeOutFilePath(LPCTSTR dir, LPCTSTR fileNamePrefix, FLOAT globalSupport, FLOAT clusterSupport, int kClusters, FLOAT fm, FLOAT entropyF)
{
time_t ltime;
time(<ime);
CString outFilePath = dir;
if (outFilePath.Right(1) != _T("\\") && outFilePath.Right(1) != _T("/"))
outFilePath += _T("\\");
outFilePath += fileNamePrefix;
CString gsStr;
int gsSupport = (int) (globalSupport * 100.5f);
if (gsSupport >= 100)
gsStr.Format(_T("%d"), gsSupport);
else if (gsSupport >= 10)
gsStr.Format(_T("0%d"), gsSupport);
else
gsStr.Format(_T("00%d"), gsSupport);
gsStr = gsStr.Left(3);
CString csStr;
int csSupport = (int) (clusterSupport * 100.5f);
if (csSupport >= 100)
csStr.Format(_T("%d"), csSupport);
else if (csSupport >= 10)
csStr.Format(_T("0%d"), csSupport);
else
csStr.Format(_T("00%d"), csSupport);
csStr = csStr.Left(3);
CString kcStr;
if (kClusters >= 100)
kcStr.Format(_T("%d"), kClusters);
else if (kClusters >= 10)
kcStr.Format(_T("0%d"), kClusters);
else
kcStr.Format(_T("00%d"), kClusters);
kcStr = kcStr.Left(3);
CString fmStr;
fmStr.Format(_T("_%f"), fm);
CString entropyFStr;
entropyFStr.Format(_T("_%f"), entropyF);
CString timeStr;
timeStr.Format(_T("_%ld"), ltime);
outFilePath += gsStr + csStr + kcStr + fmStr + entropyFStr + DC_XML_EXT;
return outFilePath;
}
//---------------------------------------------------------------------------
// Write vectors to the file
//---------------------------------------------------------------------------
BOOL CDCController::writeVectorsFile(CDCDocuments* pAllDocs)
{
int nDocs = pAllDocs->GetSize();
if (nDocs == 0)
return TRUE;
CString vectorFileName = _T("vectors.mat");
CString classFileName = _T("vectors.mat.rclass");
CString labelFileName = _T("vectors.mat.clabel");
CStdioFile vectorFile, classFile, labelFile;
if (!vectorFile.Open(vectorFileName, CFile::modeCreate | CFile::modeWrite)) {
ASSERT(FALSE);
return FALSE;
}
if (!classFile.Open(classFileName, CFile::modeCreate | CFile::modeWrite)) {
ASSERT(FALSE);
vectorFile.Close();
return FALSE;
}
// get number of nonzero entries
int nonZeroEntry = 0;
CDCDocument* pDoc = NULL;
CDCDocVector* pDocVector = NULL;
for (int i = 0; i < nDocs; ++i) {
DEBUGPrint(_T("%d\r"), i);
pDoc = pAllDocs->GetAt(i);
pDoc->getDocVector(pDocVector);
int vectorSize = pDocVector->GetSize();
for (int v = 0; v < vectorSize; ++v) {
if ((*pDocVector)[v] > 0) {
++nonZeroEntry;
}
}
}
// # of docs, # of distinct words, # of nonzero entries
CString outStr;
((CDCDocument*) pAllDocs->GetAt(0))->getDocVector(pDocVector);
int vectorSize = pDocVector->GetSize();
outStr.Format(_T("%d %d %d\n"), nDocs, vectorSize, nonZeroEntry);
vectorFile.WriteString(outStr);
for (i = 0; i < nDocs; ++i) {
DEBUGPrint(_T("%d\r"), i);
pDoc = pAllDocs->GetAt(i);
pDoc->getDocVector(pDocVector);
vectorSize = pDocVector->GetSize();
outStr.Empty();
for (int v = 0; v < vectorSize; ++v) {
if ((*pDocVector)[v] > 0) {
CString temp;
temp.Format(_T(" %d %d"), v + 1, (*pDocVector)[v]);
outStr += temp;
}
}
vectorFile.WriteString(outStr + _T("\n"));
classFile.WriteString(pDoc->getClassName() + _T("\n"));
}
classFile.Close();
vectorFile.Close();
// write label file
if (!labelFile.Open(labelFileName, CFile::modeCreate | CFile::modeWrite)) {
ASSERT(FALSE);
return FALSE;
}
CString labelStr;
for (int v = 0; v < vectorSize; ++v) {
if (!m_docMgr.getFreqTermFromID(v, labelStr)) {
ASSERT(FALSE);
return FALSE;
}
labelFile.WriteString(labelStr + _T("\n"));
}
labelFile.Close();
return TRUE;
}
| 30.428315 | 160 | 0.566464 | McGill-DMaS |
02ba104c1168ba8820fcfeb2afa53da656a9db43 | 2,194 | cpp | C++ | Code/GUI/ProgressBar.cpp | BomjSoft/BCL | f6863035d987b3fad184db8533d395d73beaf601 | [
"MIT"
] | null | null | null | Code/GUI/ProgressBar.cpp | BomjSoft/BCL | f6863035d987b3fad184db8533d395d73beaf601 | [
"MIT"
] | null | null | null | Code/GUI/ProgressBar.cpp | BomjSoft/BCL | f6863035d987b3fad184db8533d395d73beaf601 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#include "ProgressBar.h"
//---------------------------------------------------------------------------
namespace bcl {
//---------------------------------------------------------------------------
CProgressBar::CProgressBar() : CComponent()
{
minValue = 0;
maxValue = 100;
}
//---------------------------------------------------------------------------
CProgressBar::~CProgressBar()
{
}
//---------------------------------------------------------------------------
void CProgressBar::CreateObject(HWND Parent, DWORD Id)
{
InitExtComponent(ICC_PROGRESS_CLASS);
hwnd = CreateWindowEx(0, PROGRESS_CLASS, caption, WS_CHILD | (visible?WS_VISIBLE:0) | PBS_SMOOTH, left, top, width, height, Parent, HMENU(Id), GetModuleHandle(nullptr), nullptr);
created = true;
SendMessage(hwnd, PBM_SETRANGE, TRUE, MAKELPARAM(minValue, maxValue));
if (!enable)
{
SetEnable(false);
}
}
//---------------------------------------------------------------------------
LRESULT CProgressBar::Message(UINT Type)
{
return 0;
}
//---------------------------------------------------------------------------
void CProgressBar::SetRange(int Min, int Max)
{
minValue = Min;
maxValue = Max;
if (created)
{
SendMessage(hwnd, PBM_SETRANGE, TRUE, MAKELPARAM(minValue, maxValue));
}
}
//---------------------------------------------------------------------------
void CProgressBar::SetPosition(int Value)
{
SendMessage(hwnd, PBM_SETPOS, Value, 0);
}
//---------------------------------------------------------------------------
void CProgressBar::SetStep(int Value)
{
SendMessage(hwnd, PBM_SETSTEP, Value, 0);
}
//---------------------------------------------------------------------------
void CProgressBar::Update(int StepCount)
{
SendMessage(hwnd, PBM_DELTAPOS, StepCount, 0);
}
//---------------------------------------------------------------------------
void CProgressBar::Update()
{
SendMessage(hwnd, PBM_STEPIT, 0, 0);
}
//---------------------------------------------------------------------------
}
| 30.472222 | 182 | 0.377393 | BomjSoft |
02babea15d1ecfd6da55df55bc1e7c4062d5c06d | 1,124 | cpp | C++ | codeforces/659/c.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | codeforces/659/c.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | codeforces/659/c.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | #include <iostream>
#include <cassert>
#include <cstring>
#include <vector>
#include <string>
#include <set>
#include <map>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
string a,b;
cin >> a >> b;
bool flag = true;
map<char,set<int>> m;
for(int i=0 ; i<n ; i++){
if(a[i] > b[i]){
flag = false;
}
if(a[i]==b[i]) continue;
m[a[i]].insert(i);
}
if(!flag){
cout << -1 << "\n";
continue;
}
int output = 0;
for(char c='a' ; c<='t' ; c++){
if(m[c].size()==0) continue;
char temp = 'z';
for(auto ind : m[c]){
if(b[ind]<temp) temp=b[ind];
}
for(auto ind : m[c]){
if(b[ind]==temp) continue;
m[temp].insert(ind);
}
m[c].clear();
output++;
}
cout << output << "\n";
}
return 0;
}
| 21.615385 | 44 | 0.387011 | udayan14 |
02bcd3a4e6afc4dd03196b29ddf3d91bf9e1ff1b | 3,866 | cc | C++ | extern/glow-extras/material/glow-extras/material/IBL.cc | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/glow-extras/material/glow-extras/material/IBL.cc | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/glow-extras/material/glow-extras/material/IBL.cc | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #include "IBL.hh"
#include <glow/common/str_utils.hh>
#include <glow/data/TextureData.hh>
#include <glow/objects/Program.hh>
#include <glow/objects/Texture2D.hh>
#include <glow/objects/TextureCubeMap.hh>
#include <glow/util/DefaultShaderParser.hh>
#ifdef GLOW_EXTRAS_EMBED_SHADERS
#include <glow-extras/generated/material_embed_shaders.hh>
#endif
#include <typed-geometry/tg.hh>
#include "data/DefaultEnvmapData.hh"
glow::SharedTexture2D glow::material::IBL::sEnvLutGGX = nullptr;
glow::SharedTextureCubeMap glow::material::IBL::sDefaultEnvMap = nullptr;
glow::SharedTexture2D glow::material::IBL::createEnvLutGGX(int width, int height)
{
// only one mip-map level
auto tex = Texture2D::createStorageImmutable(width, height, GL_RG16F, 1);
// setup
{
auto t = tex->bind();
t.setMinFilter(GL_LINEAR);
t.setMagFilter(GL_LINEAR);
t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
}
// compute
const int localSize = 4;
auto shader = Program::createFromFile("glow-material/precalc-env-brdf-lut.csh");
{
auto s = shader->use();
s.setImage(0, tex, GL_WRITE_ONLY);
s.compute((width - 1) / localSize + 1, (height - 1) / localSize + 1);
}
return tex;
}
const glow::SharedTextureCubeMap& glow::material::IBL::getDefaultCubeMap()
{
if (!sDefaultEnvMap)
{
using namespace internal_embedded_files;
sDefaultEnvMap = glow::TextureCubeMap::createFromData(glow::TextureData::createFromRawPngCube(
defaultEnvPX, defaultEnvPXS, defaultEnvNX, defaultEnvNXS, defaultEnvPY, defaultEnvPYS, defaultEnvNY, defaultEnvNYS, defaultEnvPZ,
defaultEnvPZS, defaultEnvNZ, defaultEnvNZS, glow::ColorSpace::Linear));
}
return sDefaultEnvMap;
}
glow::SharedTextureCubeMap glow::material::IBL::createEnvMapGGX(const glow::SharedTextureCubeMap& envMap, int size)
{
// GL_RGB8 and GL_RGB16F are not supported! see https://www.opengl.org/sdk/docs/man/html/glBindImageTexture.xhtml
auto tex = TextureCubeMap::createStorageImmutable(size, size, GL_RGBA16F);
// setup
{
auto t = tex->bind();
t.setMinFilter(GL_LINEAR_MIPMAP_LINEAR);
t.setMagFilter(GL_LINEAR);
}
// compute
int const localSize = 4;
auto shader = Program::createFromFile("glow-material/precalc-env-map.csh");
auto const maxLevel = (int)tg::floor(tg::log2((float)size));
{
auto s = shader->use();
s.setTexture("uEnvMap", envMap);
auto miplevel = 0;
for (auto tsize = size; tsize > 0; tsize /= 2)
{
auto roughness = miplevel / (float)maxLevel;
s.setUniform("uRoughness", roughness);
s.setImage(0, tex, GL_WRITE_ONLY, miplevel);
s.compute((tsize - 1) / localSize + 1, (tsize - 1) / localSize + 1, 6);
++miplevel;
}
}
// we manually calculated all mipmaps
tex->setMipmapsGenerated(true);
{
auto boundTex = tex->bind();
boundTex.setBaseLevel(0);
boundTex.setMaxLevel(maxLevel);
}
return tex;
}
void glow::material::IBL::initShaderGGX(UsedProgram& shader, SharedTexture2D const& customLUT)
{
if (!customLUT && !sEnvLutGGX)
sEnvLutGGX = createEnvLutGGX();
shader.setTexture("uGlowMaterialEnvLutGGX", customLUT ? customLUT : sEnvLutGGX);
}
void glow::material::IBL::prepareShaderGGX(UsedProgram& shader, SharedTextureCubeMap const& envMapGGX)
{
shader.setTexture("uGlowMaterialEnvMapGGX", envMapGGX);
}
void glow::material::IBL::GlobalInit()
{
#ifdef GLOW_EXTRAS_EMBED_SHADERS
for (auto& virtualPair : internal_embedded_files::material_embed_shaders)
DefaultShaderParser::addVirtualFile(virtualPair.first, virtualPair.second);
#else
DefaultShaderParser::addIncludePath(util::pathOf(__FILE__) + "/../../shader");
#endif
}
| 30.68254 | 141 | 0.681324 | rovedit |
02be76086ccef99a5f863463431c62b50b535cad | 1,209 | hh | C++ | examples/ScatteringExample/include/SEDetectorConstruction.hh | QTNM/Electron-Tracking | b9dff0232af5a99fd795fd504dbddde71f4dd31c | [
"MIT"
] | 2 | 2022-03-16T22:30:19.000Z | 2022-03-16T22:30:26.000Z | examples/ScatteringExample/include/SEDetectorConstruction.hh | QTNM/Electron-Tracking | b9dff0232af5a99fd795fd504dbddde71f4dd31c | [
"MIT"
] | 18 | 2021-03-02T15:14:11.000Z | 2022-02-14T08:12:20.000Z | examples/ScatteringExample/include/SEDetectorConstruction.hh | QTNM/Electron-Tracking | b9dff0232af5a99fd795fd504dbddde71f4dd31c | [
"MIT"
] | null | null | null | #ifndef SEDetectorConstruction_h
#define SEDetectorConstruction_h 1
#include "G4Cache.hh"
#include "G4GenericMessenger.hh"
#include "G4VUserDetectorConstruction.hh"
#include "globals.hh"
class G4VPhysicalVolume;
class G4GlobalMagFieldMessenger;
class SEGasSD;
class SEWatchSD;
class SEDetectorConstruction : public G4VUserDetectorConstruction
{
public:
SEDetectorConstruction();
~SEDetectorConstruction();
public:
virtual G4VPhysicalVolume* Construct();
virtual void ConstructSDandField();
void SetGeometry(const G4String& name);
void SetDensity(G4double d);
private:
void DefineCommands();
void DefineMaterials();
G4VPhysicalVolume* SetupBaseline();
G4VPhysicalVolume* SetupBunches();
G4VPhysicalVolume* SetupShort();
G4GenericMessenger* fDetectorMessenger = nullptr;
G4String fGeometryName = "baseline";
G4double fdensity;
G4Cache<G4GlobalMagFieldMessenger*> fFieldMessenger = nullptr;
G4Cache<SEGasSD*> fSD1 = nullptr;
G4Cache<SEWatchSD*> fSD2 = nullptr;
};
#endif
| 27.477273 | 76 | 0.659222 | QTNM |
02c6b4dbed15e710d6e9dbd33aee3f9119917f39 | 3,165 | cpp | C++ | GameDownloader/src/GameDownloader/Behavior/PostHookBehavior.cpp | ProtocolONE/cord.game-downloader | 90950019937cd2974801ca2f53ed3b4ecd1d219b | [
"Apache-2.0"
] | 1 | 2019-08-07T06:13:15.000Z | 2019-08-07T06:13:15.000Z | GameDownloader/src/GameDownloader/Behavior/PostHookBehavior.cpp | ProtocolONE/cord.game-downloader | 90950019937cd2974801ca2f53ed3b4ecd1d219b | [
"Apache-2.0"
] | null | null | null | GameDownloader/src/GameDownloader/Behavior/PostHookBehavior.cpp | ProtocolONE/cord.game-downloader | 90950019937cd2974801ca2f53ed3b4ecd1d219b | [
"Apache-2.0"
] | null | null | null | #include <GameDownloader/Behavior/PostHookBehavior.h>
#include <GameDownloader/ServiceState.h>
#include <GameDownloader/GameDownloadService.h>
#include <Core/Service.h>
#include <QtConcurrent/QtConcurrentRun>
namespace P1 {
namespace GameDownloader {
namespace Behavior {
PostHookBehavior::PostHookBehavior(QObject *parent)
: BaseBehavior(parent)
{
QObject::connect(this, SIGNAL(postHooksCompleted(P1::GameDownloader::ServiceState *, P1::GameDownloader::HookBase::HookResult)),
SLOT(postHooksCompletedSlot(P1::GameDownloader::ServiceState *, P1::GameDownloader::HookBase::HookResult )));
}
PostHookBehavior::~PostHookBehavior(void)
{
}
void PostHookBehavior::start(P1::GameDownloader::ServiceState *state)
{
QtConcurrent::run(this, &PostHookBehavior::postHookLoop, state);
}
void PostHookBehavior::stop(P1::GameDownloader::ServiceState *state)
{
emit this->stopping(state);
}
void PostHookBehavior::postHookLoop(P1::GameDownloader::ServiceState *state)
{
Q_CHECK_PTR(state);
Q_CHECK_PTR(state->service());
if (state->state() != ServiceState::Started) {
emit this->postHooksCompleted(state, HookBase::Continue); // Походу надо будет урезать результаты хуков
}
const P1::Core::Service *service = state->service();
emit this->statusMessageChanged(state, QObject::tr("PRE_HOOK_DEFAULT_MESSAGE"));
HookBase::HookResult result = HookBase::Continue;
if(this->_afterDownloadHookMap.contains(service->id())) {
Q_FOREACH(HookBase *hook, this->_afterDownloadHookMap[service->id()]) {
if (state->state() != ServiceState::Started) {
emit this->postHooksCompleted(state, HookBase::Continue); // Походу надо будет урезать результаты хуков
return;
}
result = hook->afterDownload(this->_gameDownloadService, state);
emit this->statusMessageChanged(state, QObject::tr("PRE_HOOK_DEFAULT_MESSAGE"));
if (result != HookBase::Continue)
break;
}
}
emit this->postHooksCompleted(state, result);
}
void PostHookBehavior::postHooksCompletedSlot(ServiceState *state, HookBase::HookResult result)
{
// UNDONE Можно тут кстати обработать разные выходы с хуков и вызвать либо фейли либо разные выходы
if (result == HookBase::Continue)
emit this->next(Finished, state);
else if (result == HookBase::CheckUpdate)
emit this->next(ReturnToStart, state);
else
emit failed(state);
}
void PostHookBehavior::setGameDownloaderService(GameDownloadService *gameDownloadService)
{
this->_gameDownloadService = gameDownloadService;
}
void PostHookBehavior::registerHook(const QString& serviceId, int preHookPriority, HookBase *hook)
{
this->_afterDownloadHookMap[serviceId].insert(-preHookPriority, hook);
}
}
}
} | 35.965909 | 137 | 0.64139 | ProtocolONE |
02c917b230168e05d5c19fecf4033164e612a287 | 1,149 | hpp | C++ | src/utils/DisplayConfiguration.hpp | bonnefoa/flowstats | 64f3e2d4466596788174b508bc62838379162224 | [
"MIT"
] | 4 | 2020-07-21T12:34:26.000Z | 2020-12-09T16:51:33.000Z | src/utils/DisplayConfiguration.hpp | bonnefoa/flowstats | 64f3e2d4466596788174b508bc62838379162224 | [
"MIT"
] | null | null | null | src/utils/DisplayConfiguration.hpp | bonnefoa/flowstats | 64f3e2d4466596788174b508bc62838379162224 | [
"MIT"
] | 1 | 2020-07-21T12:34:31.000Z | 2020-07-21T12:34:31.000Z | #pragma once
#include "Field.hpp"
#include "enum.h"
#include <string>
#include <vector>
namespace flowstats {
class DisplayConfiguration {
public:
DisplayConfiguration();
auto updateFieldSize(Field field, int delta) -> void;
auto emptyFilter() { filter = ""; };
auto addFilterChar(int c) { filter.push_back(c); };
auto removeFilterChar() { filter.pop_back(); };
auto toggleMergedDirection() { mergeDirection = !mergeDirection; };
auto setMaxResults(int newMaxResults) { maxResults = newMaxResults; };
auto nextRateMode() -> void;
auto previousRateMode() -> void;
[[nodiscard]] auto getFieldToSize() const& { return fieldToSize; };
[[nodiscard]] auto getFilter() const& { return filter; };
[[nodiscard]] auto getMaxResults() const { return maxResults; };
[[nodiscard]] auto getMergeDirection() const { return mergeDirection; };
[[nodiscard]] auto getRateMode() const { return rateMode; };
private:
std::vector<int> fieldToSize;
std::string filter;
bool mergeDirection = true;
int maxResults = 1000;
RateMode rateMode = +RateMode::AVG;
};
} // namespace flowstats
| 27.357143 | 76 | 0.678851 | bonnefoa |
02caa5f3c7d730e77ef9a47742232d53e52cf02f | 1,041 | cpp | C++ | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | 3 | 2020-05-15T17:15:10.000Z | 2021-04-24T17:54:26.000Z | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | null | null | null | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | 1 | 2019-06-24T18:41:49.000Z | 2019-06-24T18:41:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define ll long long
#define pq priority_queue
#define mii map<int,int>
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef set<int> si;
typedef vector<vi> vii;
typedef vector<ii> vpi;
typedef vector<ll> vll;
int oo = (1e9) + 7;
int tb[10205][105];
int m, n;
int tmp;
vi p, f;
int dp(int money, int i) {
if(money > tmp and money <= 2000 and i == n) return -oo;
if(i == n or money == m) return 0;
if(tb[money][i] != -1) return tb[money][i];
int ans = dp(money, i+1);
if(money + p[i] <= m) ans = max(ans, dp(money + p[i], i+1) + f[i]);
tb[money][i] = ans;
return ans;
}
int main() {
while(scanf("%d %d", &m, &n) != EOF) {
p.assign(n+5, 0);
f.assign(n+5, 0);
for(int i = 0; i < n; i++)
{
scanf("%d %d", &p[i], &f[i]);
}
memset(tb, -1, sizeof tb);
tmp = m;
if(m + 200 > 2000) m += 200;
printf("%d\n", dp(0, 0));
}
}
| 20.82 | 71 | 0.513929 | raphasramos |
c49f007a9c1ae8d5d42f9db5932d934641f1561b | 369 | cpp | C++ | cppLearn/fib.cpp | adammorley/cpp | ff8682843f64f808b51f45b6e9530b0755455f27 | [
"Apache-2.0"
] | null | null | null | cppLearn/fib.cpp | adammorley/cpp | ff8682843f64f808b51f45b6e9530b0755455f27 | [
"Apache-2.0"
] | null | null | null | cppLearn/fib.cpp | adammorley/cpp | ff8682843f64f808b51f45b6e9530b0755455f27 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
int main() {
std::vector<long long> fib;
fib.push_back(0);
fib.push_back(1);
long long a;
std::cin >> a;
long long cnt = 2;
while (cnt <= a) {
long long num = fib[cnt-1] + fib[cnt-2];
fib.push_back(num);
cnt++;
}
std::cout << fib[a] << std::endl;
//std::cout << lcm_naive(a, b) << std::endl;
return 0;
}
| 17.571429 | 46 | 0.571816 | adammorley |
c4a0ab9be5956d15f660c0b48a9d16b7f14613cb | 2,530 | cpp | C++ | TestsParallel/test_contact_model_3d.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | null | null | null | TestsParallel/test_contact_model_3d.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 2 | 2020-10-19T02:03:11.000Z | 2021-03-19T16:34:39.000Z | TestsParallel/test_contact_model_3d.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 1 | 2020-04-28T00:33:14.000Z | 2020-04-28T00:33:14.000Z | #include "TestsParallel_pcp.h"
#include "ParticleGenerator3D.hpp"
#include "LinearElasticity.h"
#include "Model_T3D_ME_mt.h"
#include "Step_T3D_ME_mt.h"
#include "ModelData_T3D_ME_mt.h"
#include "TimeHistory_T3D_ME_mt_complete.h"
#include "TimeHistory_ConsoleProgressBar.h"
#include "QtApp_Prep_T3D_ME_mt.h"
#include "test_parallel_utils.h"
#include "test_simulations_omp.h"
void test_contact_model_3d(int argc, char** argv)
{
TetrahedronMesh teh_mesh;
teh_mesh.load_mesh_from_hdf5("../../Asset/brick_mesh_0.10_5x5x1.h5");
teh_mesh.init_search_grid(0.05, 0.05, 0.05);
Model_T3D_ME_mt model;
model.init_mesh(teh_mesh);
model.init_search_grid(teh_mesh);
ParticleGenerator3D<TetrahedronMesh> pcl_generator;
pcl_generator.generate_pcls_grid(Cube(0.0, 0.5, 0.0, 0.5, 0.0, 0.1), 0.025, 0.025, 0.025);
model.init_pcls(pcl_generator, 10.0);
size_t pcl_num = model.get_pcl_num();
MatModel::MaterialModel** mms = model.get_mat_models();
MatModel::LinearElasticity* les = model.add_LinearElasticity(pcl_num);
for (size_t pcl_id = 0; pcl_id < pcl_num; ++pcl_id)
{
MatModel::LinearElasticity& le = les[pcl_id];
le.set_param(1000.0, 0.0);
mms[pcl_id] = ≤
}
// penetrate 0.05
model.init_rigid_cylinder(0.25, 0.25, 0.12, 0.05, 0.2);
model.set_rigid_cylinder_velocity(0.02, 0.0, 0.0);
model.set_contact_param(20000.0, 200000.0, 0.01, 0.1);
IndexArray all_n_ids(model.get_node_num());
for (size_t n_id = 0; n_id < model.get_node_num(); ++n_id)
all_n_ids.add(n_id);
model.init_fixed_vx_bc(all_n_ids.get_num(), all_n_ids.get_mem());
model.init_fixed_vy_bc(all_n_ids.get_num(), all_n_ids.get_mem());
model.init_fixed_vz_bc(all_n_ids.get_num(), all_n_ids.get_mem());
QtApp_Prep_T3D_ME_mt md_disp(argc, argv);
md_disp.set_win_size(1200, 950);
md_disp.set_view_dir(30.0f, 30.0f);
md_disp.set_light_dir(90.0f, 30.0f);
md_disp.set_model(model);
//md_disp.set_pts_from_node_id(all_n_ids.get_mem(), all_n_ids.get_num(), 0.01);
md_disp.start();
return;
ResultFile_hdf5 res_file_hdf5;
res_file_hdf5.create("t3d_me_mt_cylinder_sliding.h5");
ModelData_T3D_ME_mt md;
md.output_model(model, res_file_hdf5);
TimeHistory_T3D_ME_mt_complete out1("slide");
out1.set_res_file(res_file_hdf5);
out1.set_output_init_state();
out1.set_interval_num(50);
TimeHistory_ConsoleProgressBar out_cpb;
Step_T3D_ME_mt step("step1");
step.set_model(model);
//step.set_step_time(1.0);
step.set_step_time(1.0e-3);
step.set_dtime(1.0e-5);
step.add_time_history(out1);
step.add_time_history(out_cpb);
step.solve();
}
| 32.025316 | 91 | 0.762846 | COFS-UWA |
c4a82c434e58b321c715c96ac6bd83d5400cd1fe | 5,802 | cpp | C++ | sdl2/sdlbird/Sprite.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/sdlbird/Sprite.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/sdlbird/Sprite.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2014, Wei Mingzhi <whistler_wmz@users.sf.net>.
* All rights reserved.
*
* 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. The name of the author and contributors may not be used to endorse
* or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 WASABI SYSTEMS, INC
* 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.
*/
#include "Sprite.h"
CSprite::CSprite(SDL_Renderer *pRenderer, const char *szImageFileName, const char *szTxtFileName)
{
Load(pRenderer, szImageFileName, szTxtFileName);
}
CSprite::~CSprite()
{
if (m_pTexture != NULL)
{
SDL_DestroyTexture(m_pTexture);
}
}
/**
* This hash function has been taken from an Article in Dr Dobbs Journal.
* This is normally a collision-free function, distributing keys evenly.
* Collision can be avoided by comparing the key itself in last resort.
*/
inline unsigned int CalcTag(const char *sz)
{
unsigned int hash = 0;
while (*sz)
{
hash += (unsigned short)*sz;
hash += (hash << 10);
hash ^= (hash >> 6);
sz++;
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
void CSprite::Draw(SDL_Renderer *pRenderer, const char *szTag, int x, int y)
{
unsigned int uiTag = CalcTag(szTag);
std::map<unsigned int, SpritePart_t>::iterator it = m_mapSpriteParts.find(uiTag);
if (it != m_mapSpriteParts.end())
{
SDL_Rect srcrect, dstrect;
srcrect.x = it->second.X;
srcrect.y = it->second.Y;
srcrect.w = it->second.usWidth;
srcrect.h = it->second.usHeight;
dstrect.x = x;
dstrect.y = y;
dstrect.w = it->second.usWidth;
dstrect.h = it->second.usHeight;
SDL_RenderCopy(pRenderer, m_pTexture, &srcrect, &dstrect);
}
}
void CSprite::DrawEx(SDL_Renderer *pRenderer, const char *szTag, int x, int y, double angle, SDL_RendererFlip flip)
{
unsigned int uiTag = CalcTag(szTag);
std::map<unsigned int, SpritePart_t>::iterator it = m_mapSpriteParts.find(uiTag);
if (it != m_mapSpriteParts.end())
{
SDL_Rect srcrect, dstrect;
srcrect.x = it->second.X;
srcrect.y = it->second.Y;
srcrect.w = it->second.usWidth;
srcrect.h = it->second.usHeight;
dstrect.x = x;
dstrect.y = y;
dstrect.w = it->second.usWidth;
dstrect.h = it->second.usHeight;
SDL_RenderCopyEx(pRenderer, m_pTexture, &srcrect, &dstrect, angle, NULL, flip);
}
}
void CSprite::Load(SDL_Renderer *pRenderer, const char *szImageFileName, const char *szTxtFileName)
{
SDL_Surface *pSurface = SDL_LoadBMP(szImageFileName);
if (pSurface == NULL)
{
fprintf(stderr, "CSprite::Load(): IMG_Load failed: %s\n", SDL_GetError());
return;
}
m_iTextureWidth = pSurface->w;
m_iTextureHeight = pSurface->h;
m_pTexture = SDL_CreateTextureFromSurface(pRenderer, pSurface);
SDL_FreeSurface(pSurface);
if (m_pTexture == NULL)
{
fprintf(stderr, "CSprite::Load(): SDL_CreateTextureFromSurface failed: %s\n", SDL_GetError());
return;
}
// Load txt file
if (!LoadTxt(szTxtFileName))
{
SDL_DestroyTexture(m_pTexture);
m_pTexture = NULL;
fprintf(stderr, "CSprite::Load(): LoadTxte failed\n");
return;
}
}
bool CSprite::LoadTxt(const char *szTxtFileName)
{
SDL_RWops *rwops = SDL_RWFromFile(szTxtFileName, "r");
if (rwops == NULL)
{
return false;
}
char *pBuf = (char *)malloc(SDL_RWsize(rwops) + 1);
if (pBuf == NULL)
{
SDL_RWclose(rwops);
return false;
}
SDL_RWread(rwops, pBuf, 1, SDL_RWsize(rwops));
pBuf[SDL_RWsize(rwops)] = '\0';
SDL_RWclose(rwops);
char *p = pBuf;
while (p != NULL && *p != '\0')
{
char name[256];
int w, h;
float x1, y1, x2, y2;
if (sscanf(p, "%s %d %d %f %f %f %f", name, &w, &h, &x1, &y1, &x2, &y2) != 7)
{
p = strstr(p, "\n");
if (p != NULL)
{
while (*p == '\n')
{
p++;
}
}
continue;
}
p = strstr(p, "\n");
if (p != NULL)
{
while (*p == '\n')
{
p++;
}
}
SpritePart_t spritePart;
spritePart.usWidth = w;
spritePart.usHeight = h;
spritePart.X = (unsigned short)(m_iTextureWidth * x1);
spritePart.Y = (unsigned short)(m_iTextureHeight * y1);
unsigned int uiTag = CalcTag(name);
if (m_mapSpriteParts.find(uiTag) == m_mapSpriteParts.end())
{
m_mapSpriteParts[uiTag] = spritePart;
}
else
{
fprintf(stderr, "CSprite::LoadTxt(): WARNING, duplicate tag: %s %u\n", name, uiTag);
}
}
free(pBuf);
return true;
}
| 25.901786 | 115 | 0.647363 | pdpdds |
c4aafeaa4d72886d265d9ecdad97d91aaa482665 | 5,898 | hpp | C++ | src/util/rpc/client.hpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 652 | 2022-02-03T19:31:04.000Z | 2022-03-31T17:45:29.000Z | src/util/rpc/client.hpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 50 | 2022-02-03T23:16:36.000Z | 2022-03-31T19:50:19.000Z | src/util/rpc/client.hpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 116 | 2022-02-03T19:57:26.000Z | 2022-03-20T17:23:47.000Z | // Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OPENCBDC_TX_SRC_RPC_CLIENT_H_
#define OPENCBDC_TX_SRC_RPC_CLIENT_H_
#include "format.hpp"
#include "messages.hpp"
#include "util/serialization/util.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <functional>
#include <optional>
namespace cbdc::rpc {
/// Generic RPC client. Handles serialization of requests and responses
/// combined with a message header. Subclass to define actual remote
/// communication logic.
/// \tparam Request type for requests.
/// \tparam Response type for responses.
template<typename Request, typename Response>
class client {
public:
client() = default;
client(client&&) noexcept = default;
auto operator=(client&&) noexcept -> client& = default;
client(const client&) = delete;
auto operator=(const client&) -> client& = delete;
virtual ~client() = default;
using request_type = request<Request>;
using response_type = response<Response>;
/// User-provided response callback function type for asynchronous
/// requests.
using response_callback_type
= std::function<void(std::optional<Response>)>;
/// Issues the given request with an optional timeout, then waits for
/// and returns the response. Serializes the request data, calls
/// call_raw() to transmit the data and get a response, and returns the
/// deserialized response. Thread safe.
/// \param request_payload payload for the RPC.
/// \param timeout optional timeout in milliseconds. Zero indicates the
/// call should not timeout.
/// \return response from the RPC, or std::nullopt if the call timed out
/// or produced an error.
[[nodiscard]] auto call(Request request_payload,
std::chrono::milliseconds timeout
= std::chrono::milliseconds::zero())
-> std::optional<Response> {
auto [request_buf, request_id]
= make_request(std::move(request_payload));
auto resp = call_raw(std::move(request_buf), request_id, timeout);
if(!resp.has_value()) {
return std::nullopt;
}
assert(resp.value().m_header.m_request_id == request_id);
return resp.value().m_payload;
}
/// Issues an asynchronous request and registers the given callback to
/// handle the response. Serializes the request data, then transmits it
/// with call_raw(). Thread safe.
/// \param request_payload payload for the RPC.
/// \param response_callback function for the request handler to call
/// when the response is available.
/// \return true if the request was sent successfully.
auto call(Request request_payload,
response_callback_type response_callback) -> bool {
auto [request_buf, request_id]
= make_request(std::move(request_payload));
auto ret = call_raw(
std::move(request_buf),
request_id,
[req_id = request_id, resp_cb = std::move(response_callback)](
std::optional<response_type> resp) {
if(!resp.has_value()) {
return;
}
assert(resp.value().m_header.m_request_id == req_id);
resp_cb(std::move(resp.value().m_payload));
});
return ret;
}
protected:
/// Deserializes a response object from the given buffer.
/// \param response_buf buffer containing an RPC response.
/// \return response object or std::nullopt if deserialization failed.
auto deserialize_response(cbdc::buffer& response_buf)
-> std::optional<response_type> {
return from_buffer<response_type>(response_buf);
}
/// Response callback function type for handling an RPC response.
using raw_callback_type
= std::function<void(std::optional<response_type>)>;
private:
std::atomic<uint64_t> m_current_request_id{};
/// Subclasses must override this function to define the logic for
/// call() to transmit a serialized RPC request and wait for a
/// serialized response with an optional timeout.
/// \param request_buf serialized request object.
/// \param request_id identifier to match requests with responses.
/// \param timeout timeout in milliseconds. Zero indicates the
/// call should not timeout.
/// \return response object, or std::nullopt if sending the request
/// failed or the timeout expired while waiting for a response.
virtual auto call_raw(cbdc::buffer request_buf,
request_id_type request_id,
std::chrono::milliseconds timeout)
-> std::optional<response_type> = 0;
virtual auto call_raw(cbdc::buffer request_buf,
request_id_type request_id,
raw_callback_type response_callback) -> bool
= 0;
auto make_request(Request request_payload)
-> std::pair<cbdc::buffer, request_id_type> {
auto request_id = m_current_request_id++;
auto req = request_type{{request_id}, std::move(request_payload)};
return {make_buffer(req), request_id};
}
};
}
#endif
| 43.051095 | 80 | 0.604103 | EnrikoChavez |
c4abbc992515476b03b4d213d4352259d198df90 | 3,213 | cc | C++ | third_party/eRPC/src/util/numautils.cc | agnesnatasya/Be-Tree | 516c97c1a4ee68346e301277cfc318bb07a0c1b7 | [
"BSD-2-Clause"
] | 579 | 2019-02-24T20:58:06.000Z | 2022-03-31T08:56:48.000Z | third_party/eRPC/src/util/numautils.cc | agnesnatasya/Be-Tree | 516c97c1a4ee68346e301277cfc318bb07a0c1b7 | [
"BSD-2-Clause"
] | 64 | 2019-02-25T02:48:31.000Z | 2022-03-30T03:38:40.000Z | third_party/eRPC/src/util/numautils.cc | agnesnatasya/Be-Tree | 516c97c1a4ee68346e301277cfc318bb07a0c1b7 | [
"BSD-2-Clause"
] | 86 | 2019-02-28T01:40:50.000Z | 2022-02-23T08:02:26.000Z | #include <stdio.h>
#include <thread>
#include <vector>
#include "common.h"
#include "util/logger.h"
#ifdef __linux__
#include <numa.h>
#else
#include <windows.h>
#endif
namespace erpc {
#ifdef __linux__
size_t num_lcores_per_numa_node() {
return static_cast<size_t>(numa_num_configured_cpus() /
numa_num_configured_nodes());
}
std::vector<size_t> get_lcores_for_numa_node(size_t numa_node) {
rt_assert(numa_node <= static_cast<size_t>(numa_max_node()));
std::vector<size_t> ret;
size_t num_lcores = static_cast<size_t>(numa_num_configured_cpus());
for (size_t i = 0; i < num_lcores; i++) {
if (numa_node == static_cast<size_t>(numa_node_of_cpu(i))) {
ret.push_back(i);
}
}
return ret;
}
void bind_to_core(std::thread &thread, size_t numa_node,
size_t numa_local_index) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
rt_assert(numa_node <= kMaxNumaNodes, "Invalid NUMA node");
const std::vector<size_t> lcore_vec = get_lcores_for_numa_node(numa_node);
if (numa_local_index >= lcore_vec.size()) {
ERPC_ERROR(
"eRPC: Requested binding to core %zu (zero-indexed) on NUMA node %zu, "
"which has only %zu cores. Ignoring, but this can cause very low "
"performance.\n",
numa_local_index, numa_node, lcore_vec.size());
return;
}
const size_t global_index = lcore_vec.at(numa_local_index);
CPU_SET(global_index, &cpuset);
int rc = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t),
&cpuset);
rt_assert(rc == 0, "Error setting thread affinity");
}
void clear_affinity_for_process() {
cpu_set_t mask;
CPU_ZERO(&mask);
const size_t num_cpus = std::thread::hardware_concurrency();
for (size_t i = 0; i < num_cpus; i++) CPU_SET(i, &mask);
int ret = sched_setaffinity(0 /* whole-process */, sizeof(cpu_set_t), &mask);
rt_assert(ret == 0, "Failed to clear CPU affinity for this process");
}
#else // Windows
size_t num_lcores_per_numa_node() {
return std::thread::hardware_concurrency();
}
std::vector<size_t> get_lcores_for_numa_node(size_t numa_node) {
rt_assert(numa_node == 0,
"eRPC/Windows currently supports only one NUMA node");
std::vector<size_t> ret;
for (size_t i = 0; i < num_lcores_per_numa_node(); i++) ret.push_back(i);
return ret;
}
void bind_to_core(std::thread &thread, size_t numa_node,
size_t numa_local_index) {
rt_assert(numa_node == 0,
"eRPC/Windows currently supports only one NUMA node");
rt_assert(numa_local_index < num_lcores_per_numa_node() and
numa_local_index < 8 * sizeof(DWORD_PTR),
"Requested core index is too high");
ERPC_INFO("eRPC: Binding thread to core %zu\n", numa_local_index);
const DWORD_PTR dw = SetThreadAffinityMask(thread.native_handle(),
DWORD_PTR(1) << numa_local_index);
if (dw == 0) {
ERPC_ERROR(
"eRPC: SetThreadAffinityMask failed with error %lu. Ignoring, but this "
"can cause very low performance.\n",
GetLastError());
}
}
void clear_affinity_for_process() { return; }
#endif
} // namespace erpc
| 30.028037 | 80 | 0.668845 | agnesnatasya |
c4ad43f15955cded255e777e45a2fb436ddd38ed | 3,017 | cpp | C++ | example/frame/concept/alpha/src/alphawriter.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | example/frame/concept/alpha/src/alphawriter.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | example/frame/concept/alpha/src/alphawriter.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | // alphawriter.cpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#include "alphawriter.hpp"
#include "alphaprotocolfilters.hpp"
#include "alphaconnection.hpp"
using namespace solid;
namespace concept{
namespace alpha{
Writer::Writer(
protocol::text::Logger *_plog
):protocol::text::Writer(_plog){
}
Writer::~Writer(){
}
void Writer::clear(){
tags.clear();
msgs.clear();
cassert(wpos == rpos);
}
bool isLiteralString(const char *_pb, unsigned _bl){
while(_bl--){
//if it's not quoted means its literal
if(!QuotedFilter::check(*_pb)) return true;
++_pb;
}
return false;
}
/*static*/ int Writer::putAString(protocol::text::Writer &_rw, protocol::text::Parameter &_rp){
Writer &rw = static_cast<Writer&>(_rw);
const char *ps = (const char*)_rp.a.p;
if(_rp.b.u32 > 128 || isLiteralString(ps, _rp.b.u32)){
//right here i know for sure I can write safely (buflen - FlushLength) chars
rw<<'{'<<_rp.b.u32;
rw.putChar('}','\r','\n');
rw.fs.top().first = &Writer::putAtom;
}else{//send quoted
rw<<'\"';
protocol::text::Parameter ppp(_rp);
rw.replace(&Writer::putChar, protocol::text::Parameter('\"'));
rw.push(&Writer::putAtom, ppp);
rw.push(&Writer::flush);//only try to do a flush
}
return Continue;
}
//NOTE: to be used by the above method
/*static*/ /*int Writer::putQString(protocol::text::Writer &_rw, protocol::text::Parameter &_rp){
return Bad;
}*/
/*static*/ int Writer::putStatus(protocol::text::Writer &_rw, protocol::text::Parameter &_rp){
Writer &rw = static_cast<Writer&>(_rw);
protocol::text::Parameter rp = _rp;
rw.replace(&Writer::clear);
rw.push(&Writer::flushAll);
rw.push(&Writer::putCrlf);
if(rp.a.p){
rw.push(&Writer::putAtom, rp);
}else{//send the msg
rw.push(&Writer::putAtom, protocol::text::Parameter((void*)rw.msgs.data(), rw.msgs.size()));
}
//rw.push(&Writer::putChar, protocol::text::Parameter(' '));
if(rw.tags.size()){
rw.push(&Writer::putAtom, protocol::text::Parameter((void*)rw.tags.data(), rw.tags.size()));
}else{
rw.push(&Writer::putChar, protocol::text::Parameter('*'));
}
return Continue;
}
/*static*/ int Writer::clear(protocol::text::Writer &_rw, protocol::text::Parameter &_rp){
Writer &rw = static_cast<Writer&>(_rw);
rw.clear();
return Success;
}
/*static*/ int Writer::putCrlf(protocol::text::Writer &_rw, protocol::text::Parameter &_rp){
_rw.replace(&Writer::putChar, protocol::text::Parameter('\n'));
_rw.push(&Writer::putChar, protocol::text::Parameter('\r'));
return Continue;
}
int Writer::write(char *_pb, uint32 _bl){
// switch(rch.send(_pb, _bl)){
// case BAD: return Bad;
// case OK: return Ok;
// case NOK: return No;
// }
// cassert(false);
// return Bad;
return Connection::the().socketSend(_pb, _bl);
}
}//namespace alpha
}//namespace concept
| 27.18018 | 97 | 0.672854 | joydit |
c4ae11028445ad1e97267d0264850775b57a6778 | 2,610 | cpp | C++ | Client/client/World/World.cpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 14 | 2019-03-05T10:03:59.000Z | 2021-12-21T03:00:18.000Z | Client/client/World/World.cpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 1 | 2019-10-24T21:37:59.000Z | 2019-10-24T21:37:59.000Z | Client/client/World/World.cpp | pinkmouse/SlayersWorld | 53cdde28f3464ee9ada9b655f8c4df63f0e9389e | [
"MIT"
] | 1 | 2020-12-06T21:07:52.000Z | 2020-12-06T21:07:52.000Z | #include "World.hpp"
#include "../Global.hpp"
#include "WorldPacket.hpp"
#include <vector>
World::World()
{
g_Socket = new Socket();
m_Events = new Events();
g_Config = new ConfigHandler();
m_MapManager = new MapManager(m_Events);
m_InterfaceManager = new InterfaceManager(m_Events);
m_Graphics = new Graphics(m_MapManager, m_InterfaceManager, m_Events);
m_PacketHandler = new PacketHandler(m_MapManager, m_InterfaceManager);
m_Run = true;
}
World::~World()
{
}
void World::SetIp(const std::string & p_Ip)
{
m_Ip = p_Ip;
}
bool World::InitializeConnection()
{
if (!g_Socket->Connection(m_Ip))
{
m_InterfaceManager->SetSystemMsg("Connection failed");
return false;
}
g_Socket->setBlocking(false);
g_Socket->SendAuth(m_Credentials.first, m_Credentials.second);
return true;
}
bool World::InitializeWindow()
{
m_InterfaceManager->Initialize();
if (!m_Graphics->CreateWindow(X_WINDOW, Y_WINDOW, ZOOM_FACTOR))
return false;
if (!m_Graphics->LoadFont())
return false;
return true;
}
bool World::Initialize()
{
if (!g_Config->Initialize())
{
printf("Config error\n");
return false;
}
m_Ip = g_Config->GetValue("IPserver");
if (!InitializeWindow())
return false;
m_MapManager->InitializeMaps();
m_PacketHandler->LoadPacketHandlerMap();
return true;
}
void World::Login(const std::string& login, const std::string& password)
{
m_Credentials.first = login;
m_Credentials.second = password;
m_InterfaceManager->SetSystemMsg("Connection...");
//m_InterfaceManager->SetSystemMsg("Connection...");
}
void World::Run()
{
while (m_Run)
{
if (!g_Socket->IsConnected())
InitializeConnection();
else if (!UpdateSocket())
{
m_InterfaceManager->SetSystemMsg("Disconnected");
delete g_Player;
g_Player = nullptr;
}
sf::Time l_Diff = m_Clock.restart();
if (m_PacketHandler->HasMinimalRequiered())
m_MapManager->Update(l_Diff);
m_Graphics->UpdateWindow(l_Diff);
m_Graphics->CheckEvent();
if (!m_Graphics->WindowIsOpen())
End();
}
}
bool World::UpdateSocket()
{
WorldPacket l_Packet;
sf::Socket::Status l_SocketStatus;
l_SocketStatus = g_Socket->Receive(l_Packet);
if (l_SocketStatus == sf::Socket::Status::Done) ///< Reception OK
m_PacketHandler->OperatePacket(l_Packet);
if (l_SocketStatus == sf::Socket::Status::Disconnected) ///< Disconnecetd
return false;
return true;
}
void World::End()
{
m_Run = false;
g_Socket->disconnect();
} | 22.894737 | 74 | 0.6659 | pinkmouse |
c4aedb60a6b584cb8efb91d7df4431cd47cb86e0 | 483 | hpp | C++ | include/brimstone/Size.hpp | theJ8910/Brimstone | e28da7a995ab5533b78bf5e1664a59753d139fff | [
"MIT"
] | 1 | 2015-12-31T05:49:39.000Z | 2015-12-31T05:49:39.000Z | include/brimstone/Size.hpp | theJ8910/Brimstone | e28da7a995ab5533b78bf5e1664a59753d139fff | [
"MIT"
] | null | null | null | include/brimstone/Size.hpp | theJ8910/Brimstone | e28da7a995ab5533b78bf5e1664a59753d139fff | [
"MIT"
] | null | null | null | /*
Size.hpp
-----------------------
Copyright (c) 2014, theJ89
Description:
Include this file for access to Size and its variations.
Note: Since this file merely includes other files, there are no include guards necessary here.
*/
//Includes
#include <brimstone/size/SizeN.hpp>
#include <brimstone/size/Size2.hpp>
#include <brimstone/size/Size3.hpp>
#include <brimstone/size/Size4.hpp>
//This macro isn't needed outside of the above files
#undef BS_SIZE_DECLARE_METHODS | 23 | 98 | 0.724638 | theJ8910 |
c4b010e42abdd2e35f215d93afc09ed2119a37f3 | 22 | cpp | C++ | TetrisConsole/source/Konsole/Vector2i.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | TetrisConsole/source/Konsole/Vector2i.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | TetrisConsole/source/Konsole/Vector2i.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | #include "Vector2i.h"
| 11 | 21 | 0.727273 | mooviies |
c4b088cdd2eba4b2c63c98fff03c2b0e99b3275c | 1,305 | cpp | C++ | codechef/SWAPPALI/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codechef/SWAPPALI/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codechef/SWAPPALI/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 29-02-2020 19:55:44
* solution_verdict: Wrong Answer language: C++14
* run_time: 0.00 sec memory_used: 0M
* problem: https://www.codechef.com/LTIME81A/problems/SWAPPALI
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int n,dp[N+2];string s;
int dfs(int i)
{
int j=n-1-i;if(j<=i)return 0;
if(dp[i]!=-1)return dp[i];
int now=inf;
if(s[i]==s[j])now=min(now,dfs(i+1));
if(i+1<j-1)
{
if(s[i+1]==s[j]&&s[i]==s[j-1])
now=min(now,1+dfs(i+2));
}
if(i+1==j-1)
{
if(s[i]==s[i+1]||s[j]==s[j-1])
now=min(now,1+dfs(i+2));
}
return dp[i]=now;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
cin>>n>>s;
for(int i=0;i<=n;i++)dp[i]=-1;
int ans=dfs(0);if(ans==inf)ans=-1;
if(ans!=-1)cout<<"YES\n"<<ans<<"\n";
else cout<<"NO\n";
//cout<<endl;
}
return 0;
} | 29.659091 | 111 | 0.4 | kzvd4729 |
c4b0cb7be0da45a9827665348569fe4bd3544efa | 3,005 | cpp | C++ | unittests/timer/ExecutionDeferrerTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | 24 | 2015-03-04T16:30:03.000Z | 2022-02-04T15:03:42.000Z | unittests/timer/ExecutionDeferrerTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | null | null | null | unittests/timer/ExecutionDeferrerTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | 7 | 2015-04-08T12:22:58.000Z | 2018-06-14T09:58:45.000Z | #include <stingraykit/function/bind.h>
#include <stingraykit/timer/Timer.h>
#include <stingraykit/unique_ptr.h>
#include <gtest/gtest.h>
using namespace stingray;
class ExecutionDeferrerTest : public testing::Test
{
protected:
class DeferrerHolder
{
private:
ExecutionDeferrer _deferrer;
public:
DeferrerHolder(Timer& timer, size_t timeout, const function<void ()>& func)
: _deferrer(timer, TimeDuration(timeout))
{ _deferrer.Defer(func); }
~DeferrerHolder()
{ _deferrer.Cancel(); }
};
struct Counter
{
private:
size_t _value;
public:
Counter() : _value(0) { }
size_t GetValue() const { return _value; }
void Increment() { ++_value; }
};
struct ExecutionDeferrerTestDummy
{ };
STINGRAYKIT_DECLARE_PTR(ExecutionDeferrerTestDummy);
protected:
bool _finished;
protected:
ExecutionDeferrerTest() : _finished(false)
{ }
static void DoNothing() { }
void DoCancel(const ExecutionDeferrerWithTimerPtr& deferrer)
{ deferrer->Cancel(); }
public:
void DoTest(size_t testCount, size_t timeout, size_t sleepTimeout)
{
ExecutionDeferrerWithTimerPtr deferrer(new ExecutionDeferrerWithTimer("deferrerTestTimer"));
ExecutionDeferrerWithTimerPtr cancelDeferrer(new ExecutionDeferrerWithTimer("deferrerCancelTestTimer"));
for (size_t i = 0; i < testCount; ++i)
{
deferrer->Defer(Bind(&ExecutionDeferrerTest::DoCancel, this, deferrer), TimeDuration(timeout));
cancelDeferrer->Defer(Bind(&ExecutionDeferrerTest::DoCancel, this, deferrer), TimeDuration(timeout));
Thread::Sleep(sleepTimeout);
}
deferrer.reset();
cancelDeferrer.reset();
_finished = true;
}
};
TEST_F(ExecutionDeferrerTest, Cancel)
{
const size_t Timeout = 500;
const size_t ObjectsCount = 1000;
Timer timer("deferrerTestTimer");
Counter counter;
for (size_t i = 0; i < ObjectsCount; ++i)
{
unique_ptr<DeferrerHolder> tmp(new DeferrerHolder(timer, Timeout, Bind(&Counter::Increment, wrap_ref(counter))));
tmp.reset();
}
Thread::Sleep(2 * Timeout);
ASSERT_EQ(counter.GetValue(), 0u);
}
TEST_F(ExecutionDeferrerTest, Defer)
{
const size_t EvenTimeout = 0;
const size_t OddTimeout = 200;
const size_t TestCount = 10000;
ExecutionDeferrerWithTimer deferrer("deferrerTestTimer");
for (size_t i = 0; i < TestCount; ++i)
{
const size_t timeout = i % 2? OddTimeout : EvenTimeout;
deferrer.Defer(&ExecutionDeferrerTest::DoNothing, TimeDuration(timeout));
}
}
TEST_F(ExecutionDeferrerTest, CancelDeadlock)
{
const size_t TestCount = 100;
const size_t Timeout = 3;
const size_t SleepTimeout = 50;
static ExecutionDeferrerWithTimer deferrer("deadlockTestDeferrerTimer");
deferrer.Defer(Bind(&ExecutionDeferrerTest::DoTest, this, TestCount, Timeout, SleepTimeout), TimeDuration(0));
size_t elapsed = 0;
while(elapsed < (TestCount * SleepTimeout * 2) && !_finished)
{
elapsed += SleepTimeout;
Thread::Sleep(SleepTimeout);
}
if (!_finished)
STINGRAYKIT_THROW("Cannot finish ExecutionDeferrerTest, possible there is a deadlock");
}
| 23.294574 | 115 | 0.738769 | zavadovsky |
c4b10ee02bb5e600696d5bd152526c61ae663e94 | 215 | cpp | C++ | Source/Common/MPIWrapper.cpp | sunkwei/CNTK | 08691e97707538b110ca71bce4ad06c46d840517 | [
"Intel"
] | 6 | 2019-08-18T05:29:09.000Z | 2021-01-19T09:58:45.000Z | Source/Common/MPIWrapper.cpp | Omar-Belghaouti/CNTK | 422f710242c602b2660a634f2234abf5aaf5b337 | [
"RSA-MD"
] | null | null | null | Source/Common/MPIWrapper.cpp | Omar-Belghaouti/CNTK | 422f710242c602b2660a634f2234abf5aaf5b337 | [
"RSA-MD"
] | 1 | 2019-10-24T00:35:07.000Z | 2019-10-24T00:35:07.000Z | #include "Include/Basics.h"
#include "Include/MPIWrapper.h"
int Microsoft::MSR::CNTK::MPIWrapper::s_myRank = -1;
std::shared_ptr<Microsoft::MSR::CNTK::MPIWrapper> Microsoft::MSR::CNTK::MPIWrapper::s_mpi = nullptr;
| 35.833333 | 100 | 0.748837 | sunkwei |
c4b3615457b213dec9d96b0c8eaaf5b4af20be21 | 299 | cpp | C++ | Codeforces Online Judge Solve/dice.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/dice.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/dice.cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
int main ()
{
ll m,n,k;
cin>>n;
while(n--)
{
cin>>m;
if(m==2||m==3||m==4||m==5||m==6||m==7) cout<<"1"<<endl;
else
{
k=m/2; cout<<k<<endl;
}
}
}
| 16.611111 | 64 | 0.381271 | Remonhasan |
c4b3834a3ced9015f6db46be6e6f5fc176787725 | 1,234 | cc | C++ | src/platform/udp_server_test.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | null | null | null | src/platform/udp_server_test.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | null | null | null | src/platform/udp_server_test.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | 2 | 2019-11-12T23:15:18.000Z | 2020-01-15T17:49:27.000Z | #include "platform.cc"
#include <cstdio>
volatile bool running = true;
s32
main(s32 argc, char** argv)
{
const char* ip = "127.0.0.1";
const char* port = "9845";
while (1) {
s32 opt = platform_getopt(argc, argv, "i:p:");
if (opt == -1) break;
switch (opt) {
case 'i':
ip = platform_optarg;
break;
case 'p':
port = platform_optarg;
break;
};
}
#define MAX_BUFFER 4 * 1024
u8 buffer[MAX_BUFFER];
udp::Init();
Udp4 location;
if (!udp::GetAddr4(ip, port, &location)) {
puts("fail GetAddr4");
exit(1);
}
printf("Server binding %s:%s\n", ip, port);
if (!udp::Bind(location)) {
puts("fail Bind");
exit(1);
}
while (running) {
u16 received_bytes;
Udp4 peer;
if (!udp::ReceiveAny(location, MAX_BUFFER, buffer, &received_bytes,
&peer)) {
if (udp_errno) running = false;
if (udp_errno) printf("udp_errno %d\n", udp_errno);
continue;
}
// Echo bytes to peer
printf("socket %d echo %d bytes\n", location.socket, received_bytes);
if (!udp::SendTo(location, peer, buffer, received_bytes)) {
puts("send failed");
} else {
puts("send ok");
}
}
}
| 19.903226 | 73 | 0.559157 | AnthonyBrunasso |
c4b421f980c2a384fcb3a9806084e3725979098a | 442 | cc | C++ | caffe2/opt/distributed_converter.cc | brooks-anderson/pytorch | dd928097938b6368fc7e2dc67721550d50ab08ea | [
"Intel"
] | 7 | 2021-05-29T16:31:51.000Z | 2022-02-21T18:52:25.000Z | caffe2/opt/distributed_converter.cc | stas00/pytorch | 6a085648d81ce88ff59d6d1438fdb3707a0d6fb7 | [
"Intel"
] | 1 | 2021-05-10T01:18:33.000Z | 2021-05-10T01:18:33.000Z | caffe2/opt/distributed_converter.cc | stas00/pytorch | 6a085648d81ce88ff59d6d1438fdb3707a0d6fb7 | [
"Intel"
] | 1 | 2021-12-26T23:20:06.000Z | 2021-12-26T23:20:06.000Z | #include "caffe2/opt/converter.h"
namespace caffe2 {
namespace {
using namespace nom;
using namespace nom::repr;
TRIVIAL_CONVERTER(Declare);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CONVERTER(Declare, DeclareConverter);
TRIVIAL_CONVERTER(Export);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CONVERTER(Export, ExportConverter);
} // namespace
} // namespace caffe2
| 23.263158 | 69 | 0.807692 | brooks-anderson |
c4b457a7d61ab62179e13416dda2f179f7be4a5e | 1,663 | hh | C++ | modules/Tsp/TspParticle.hh | ElonKou/genetic | 507f739b44399b8dbae1bde4523fbb718704e223 | [
"MIT"
] | null | null | null | modules/Tsp/TspParticle.hh | ElonKou/genetic | 507f739b44399b8dbae1bde4523fbb718704e223 | [
"MIT"
] | null | null | null | modules/Tsp/TspParticle.hh | ElonKou/genetic | 507f739b44399b8dbae1bde4523fbb718704e223 | [
"MIT"
] | null | null | null | #pragma once
#include "TspAlgorithmBase.hh"
typedef struct SpeedItem {
int x;
int y;
} SpeedItem;
class TspParticle : public TspAlgorithmBase {
public:
std::vector<SpeedItem> m_personal; // cur:A -> his:B (current vs personal history)
std::vector<SpeedItem> m_global; // cur:A -> bst:B (current and global history)
std::vector<std::vector<int>> p_best_genes; // record all best genes for all personal gene history.
std::vector<std::vector<SpeedItem>> m_speeds; // record particle's old speeds.
float w; // keep current rate.
float alpha; // move personal best rate.
float beta; // move hsitory best rate.
float gama; // move random.
TspParticle();
TspParticle(int node_cnt, int agent_cnt, float w_, float alpha_, float beta_, float gama = 0.1);
~TspParticle();
void Init();
void SomeInit();
void RandomRemoveWorstParticles();
/**
* Calculate velocity of all particles between two positions.
*/
void CalculateVelocity(std::vector<int>& cur_ori, const std::vector<int>& per, const std::vector<int>& glo, std::vector<SpeedItem>& cur_speed, std::vector<SpeedItem>& speed);
/**
* Calculate new position of all velocity and current position.
*/
void CalculatePosition(std::vector<int>& cur, std::vector<SpeedItem>& cur_speed);
virtual void Step();
virtual void Predict();
virtual void GetCurrentBest(std::vector<int>& best, float& score);
};
| 33.938776 | 178 | 0.595911 | ElonKou |
c4b4aaa187fd4398015417a985e637dd01253ad7 | 10,528 | cpp | C++ | src/IndexBar.cpp | Keyaku/ff8-garden | 76754fb067ccf07add4feb2c5e5dafe97e758380 | [
"MIT"
] | 1 | 2019-09-03T20:33:19.000Z | 2019-09-03T20:33:19.000Z | src/IndexBar.cpp | Keyaku/ff8-garden | 76754fb067ccf07add4feb2c5e5dafe97e758380 | [
"MIT"
] | null | null | null | src/IndexBar.cpp | Keyaku/ff8-garden | 76754fb067ccf07add4feb2c5e5dafe97e758380 | [
"MIT"
] | null | null | null | // IndexBar.cpp : implementation file
//
#include "ui_win32/StdAfx.h"
//#include "Gast.h"
#include "Garden.h"
#include "IndexBar.h"
#include "resource.h"
#include <afxpriv.h>
#include "project.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CProject theProject;
/////////////////////////////////////////////////////////////////////////////
// CIndexBar
IMPLEMENT_DYNCREATE(CIndexBar, CWnd)
CIndexBar::CIndexBar()
{
fntTitle.CreateFont(-12,0,0,0,0,0,0,0,0,0,0,0,0,"Tahoma");
if (!(HFONT)fntTitle)
fntTitle.CreateFont(-12,0,0,0,0,0,0,0,0,0,0,0,0,"Arial");
if (!(HFONT)fntTitle)
fntTitle.FromHandle((HFONT)GetStockObject(ANSI_VAR_FONT));
width = 205;
sortby = 0;
bRevOrder = 0;
}
CIndexBar::~CIndexBar()
{
fntTitle.DeleteObject();
}
BEGIN_MESSAGE_MAP(CIndexBar, CWnd)
//{{AFX_MSG_MAP(CIndexBar)
ON_MESSAGE(WM_SIZEPARENT, OnSizeParent)
ON_WM_PAINT()
ON_NOTIFY(TVN_SELCHANGED, ID_INDEX_DIR, OnClickDir)
ON_NOTIFY(NM_DBLCLK, ID_INDEX_CTRL, OnClickIndex)
ON_NOTIFY(HDN_ITEMCLICK, 0, OnClickHeader)
ON_NOTIFY(NM_RCLICK, ID_INDEX_CTRL, OnRClickIndex)
ON_WM_SIZE()
ON_MESSAGE(WM_DRAWITEM, OnDrawItem)
ON_NOTIFY(NM_RETURN, ID_INDEX_CTRL, OnClickIndex)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CIndexBar message handlers
afx_msg LRESULT CIndexBar::OnSizeParent(WPARAM wParam, LPARAM lParam)
{
AFX_SIZEPARENTPARAMS *params = (AFX_SIZEPARENTPARAMS*)lParam;
SetWindowPos(NULL,params->rect.left,params->rect.top,width,params->rect.bottom - params->rect.top,SWP_NOZORDER);
params->rect.left += width;
//params->rect.right -= 202;
params->sizeTotal.cx -= width;
return 0;
}
void CIndexBar::OnPaint()
{
CPaintDC dc(this); // device context for painting
CDC *wdc = GetWindowDC();
// TODO: Add your message handler code here
COLORREF dark, light, face;
CRect rc;
GetClientRect((LPRECT)rc);
dark = GetSysColor(COLOR_BTNSHADOW);
light = GetSysColor(COLOR_BTNHILIGHT);
face = GetSysColor(COLOR_BTNFACE);
dc.SelectObject(&fntTitle);
dc.SetBkMode(TRANSPARENT);
dc.Draw3dRect(5,6,3,19,light,dark);
dc.Draw3dRect(9,6,3,19,light,dark);
dc.TextOut(17,8,"Project files");
// wdc->FillSolidRect(0,2,5,rc.Height()-4,face);
// wdc->FillSolidRect(rc.Width()-10,2,6,rc.Height()-4,face);
wdc->Draw3dRect(0,0,width-5,2,dark,light);
wdc->Draw3dRect(0,rc.Height()-2,width-5,2,dark,light);
wdc->Draw3dRect(width-6,0,2,rc.Height(),dark,light);
// Do not call CDialogBar::OnPaint() for painting messages
}
void CIndexBar::OnClickIndex(NMHDR* pNMHDR, LRESULT* pResult)
{
// If an item has been double-clicked, open it
if (list.GetSelectedCount() != 0) {
extern CGardenApp theApp;
theApp.OnOpenfile();
// ::SendMessage((HWND)AfxGetMainWnd(),WM_COMMAND,ID_OPENFILE,0);
}
*pResult = 0;
}
void CIndexBar::OnClickHeader(NMHDR* pNMHDR, LRESULT* pResult)
{
HD_NOTIFY *hd = (HD_NOTIFY*)pNMHDR;
switch (hd->iItem) {
case 0: if (sortby == 1) bRevOrder = !bRevOrder;
else bRevOrder = false;
sortby = 1; break;
case 1: if (sortby == 3) bRevOrder = !bRevOrder;
else bRevOrder = false;
sortby = 3; break;
default: break;
}
Sort();
*pResult = 0;
}
void CIndexBar::OnRClickIndex(NMHDR* pNMHDR, LRESULT* pResult)
{
CMenu menu, *mnu;
menu.LoadMenu(IDR_INDEX);
// If an item has been right-clicked, show item context menu
if (list.GetSelectedCount() != 0) {
mnu = menu.GetSubMenu(0);
mnu->SetDefaultItem(0,true);
POINT pnt;
list.GetItemPosition(list.GetSelectionMark(),&pnt);
list.ClientToScreen(&pnt);
mnu->TrackPopupMenu(TPM_RIGHTBUTTON,pnt.x+14,pnt.y+14,GetParent());
}
// If not, show list context menu
else {
mnu = menu.GetSubMenu(1);
mnu->GetSubMenu(0)->CheckMenuRadioItem(0,3,sortby,MF_BYPOSITION);
mnu->GetSubMenu(0)->CheckMenuItem(ID_ARCHIVE_SORTREV, MF_BYCOMMAND | ( bRevOrder ? MF_CHECKED : MF_UNCHECKED ));
POINT pnt;
GetCursorPos(&pnt);
mnu->TrackPopupMenu(TPM_RIGHTBUTTON,pnt.x,pnt.y,GetParent());
}
menu.DestroyMenu();
*pResult = 0;
}
void CIndexBar::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
if (!m_hWnd) return;
if (!list.m_hWnd) return;
CRect rc;
GetClientRect((LPRECT)rc);
/* LOGFONT logfnt;
::GetObject(GetStockObject(ANSI_VAR_FONT),sizeof(LOGFONT),&logfnt);
titleheight = logfnt.lfHeight < 0 ? -logfnt.lfHeight : logfnt.lfHeight;
*/
dirbox.SetWindowPos(NULL,5,17+12,rc.Width()-18,103,SWP_NOZORDER);
list.SetWindowPos(NULL,5,17+122,rc.Width()-18,rc.Height()-27-122,SWP_NOZORDER);
// TODO: Add your message handler code here
}
BOOL CIndexBar::Create(CWnd* pParentWnd)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_VREDRAW | CS_DBLCLKS;
wcex.lpfnWndProc = AfxGetAfxWndProc();
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = AfxGetInstanceHandle();
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL,IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "GastIndexBar32";
wcex.hIconSm = NULL;
RegisterClassEx(&wcex);
BOOL r = CWnd::Create("GastIndexBar32","GastIndexBar",WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN,CRect(0,0,100,100),pParentWnd,ID_INDEX_BAR);
if (!r) return false;
CBitmap bmp;
bmp.LoadBitmap(IDB_TYPES);
il.Create(14,14,ILC_COLOR | ILC_MASK,0,32);
il.Add(&bmp,RGB(255,0,255));
bmp.DeleteObject();
dirbox.Create(WS_CHILDWINDOW | WS_VISIBLE | TVS_FULLROWSELECT | TVS_SINGLEEXPAND | TVS_SHOWSELALWAYS, CRect(0,0,100,100),this,ID_INDEX_DIR);
dirbox.ModifyStyleEx(0,WS_EX_CLIENTEDGE);
//dirbox.Create(WS_CHILDWINDOW | WS_VISIBLE | CBS_DROPDOWNLIST,CRect(0,0,100,100),this,ID_INDEX_DIR);
dirbox.SetImageList(&il,TVSIL_NORMAL);
dirbox.SetIndent(0);
list.Create(WS_VISIBLE | WS_DISABLED | WS_CHILDWINDOW | LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS, CRect(0,0,100,100), this, ID_INDEX_CTRL);
list.ModifyStyleEx(0,WS_EX_CLIENTEDGE);
// list.SetExtendedStyle(LVS_EX_FULLROWSELECT);
list.SetImageList(&il,LVSIL_SMALL);
list.InsertColumn(0,"Name",LVCFMT_LEFT,106,0);
// list.InsertColumn(1,"Type",LVCFMT_CENTER,40,1);
list.InsertColumn(1,"Size",LVCFMT_RIGHT,width-128-GetSystemMetrics(SM_CXHSCROLL),1);
return r;
}
BOOL CIndexBar::DestroyWindow()
{
// TODO: Add your specialized code here and/or call the base class
BOOL r = CWnd::DestroyWindow();
UnregisterClass("GastIndexBar32",AfxGetInstanceHandle());
return r;
}
CListCtrl * CIndexBar::GetList()
{
if (!list.m_hWnd) return NULL;
return &list;
}
/*
// Sort function
int CALLBACK sort_none (LPARAM a, LPARAM b, LPARAM p) {
return a-b; }
int CALLBACK sort_none_r (LPARAM a, LPARAM b, LPARAM p) {
return b-a; }
int CALLBACK sort_name (LPARAM a, LPARAM b, LPARAM p) {
return strcmpi(((CLGP*)p)->GetSlotName((USHORT)a),((CLGP*)p)->GetSlotName((USHORT)b)); }
int CALLBACK sort_name_r (LPARAM a, LPARAM b, LPARAM p) {
return strcmpi(((CLGP*)p)->GetSlotName((USHORT)b),((CLGP*)p)->GetSlotName((USHORT)a)); }
int CALLBACK sort_type (LPARAM a, LPARAM b, LPARAM p) {
return strcmpi(((CLGP*)p)->GetSlotSuffix((USHORT)a),((CLGP*)p)->GetSlotSuffix((USHORT)b)); }
int CALLBACK sort_type_r (LPARAM a, LPARAM b, LPARAM p) {
return strcmpi(((CLGP*)p)->GetSlotSuffix((USHORT)b),((CLGP*)p)->GetSlotSuffix((USHORT)a)); }
int CALLBACK sort_size (LPARAM a, LPARAM b, LPARAM p) {
return ((CLGP*)p)->GetSlotSize((USHORT)a)-((CLGP*)p)->GetSlotSize((USHORT)b); }
int CALLBACK sort_size_r (LPARAM a, LPARAM b, LPARAM p) {
return ((CLGP*)p)->GetSlotSize((USHORT)b)-((CLGP*)p)->GetSlotSize((USHORT)a); }
*/
void CIndexBar::Sort()
{
BOOL rev = bRevOrder;
/* extern CLGP theLGP;
switch (sortby) {
case 0: if (rev) list.SortItems(sort_none_r, (LONG)&theLGP);
else list.SortItems(sort_none, (LONG)&theLGP);
break;
case 1: if (rev) list.SortItems(sort_name_r, (LONG)&theLGP);
else list.SortItems(sort_name, (LONG)&theLGP);
break;
case 2: if (rev) list.SortItems(sort_type_r, (LONG)&theLGP);
else list.SortItems(sort_type, (LONG)&theLGP);
break;
case 3: if (rev) list.SortItems(sort_size_r, (LONG)&theLGP);
else list.SortItems(sort_size, (LONG)&theLGP);
break;
default: break;
}
*/
}
void CIndexBar::OnDrawItem(UINT nIDCtrl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
}
CTreeCtrl * CIndexBar::GetDirBox()
{
if (!dirbox.m_hWnd) return NULL;
return &dirbox;
}
//DEL void CIndexBar::OnDecompile()
//DEL {
//DEL
//DEL
//DEL }
void CIndexBar::Update()
{
dirbox.DeleteAllItems();
HTREEITEM hroot[2049];
hroot[0] = dirbox.InsertItem(theProject.GetName(),0,0);
dirbox.SetItemData(hroot[0],(DWORD)-1);
for (int i=0;(UINT)i<theProject.nDirs;i++) {
hroot[i+1] = dirbox.InsertItem(theProject.GetDirName(i),1,2,hroot[(USHORT)(theProject.GetDirParent(i)+1)]);
dirbox.SetItemData(hroot[i+1],i);
}
list.EnableWindow(TRUE);
}
void CIndexBar::OnClickDir(NMHDR* pNMHDR, LRESULT* pResult)
{
NMTREEVIEWA *pNM = (NMTREEVIEW*)pNMHDR;
if (!dirbox.GetSelectedItem()) return;
if (!pNM->itemNew.hItem) return;
list.DeleteAllItems();
if (pNM->itemNew.lParam == (DWORD)-1) return;
CString dir1 = "";
HTREEITEM hroot[32];
int n=1;
dir1.Insert(0,dirbox.GetItemText(pNM->itemNew.hItem));
hroot[0] = pNM->itemNew.hItem;
while (1) {
hroot[n] = dirbox.GetParentItem(hroot[n-1]);
if (dirbox.GetItemData(hroot[n]) == (DWORD)-1) break;
dir1.Insert(0,"\\");
dir1.Insert(0,dirbox.GetItemText(hroot[n]));
n++;
}
CString dir2 = "";
char buf[100];
int q;
int tmp;
for (int i=0;(UINT)i<theProject.nFiles;i++) {
dir2 = theProject.GetFileName(i);
q = dir2.ReverseFind('\\');
if (q < 0) continue;
memset(buf,0,100);
strncpy(buf,dir2,q);
if (!stricmp(dir1,buf)) {
int o, img;
o = dir2.ReverseFind('.');
if (!strnicmp(".msd",(LPCTSTR)dir2+o,4)) img = 9;
else if (!strnicmp(".tex",(LPCTSTR)dir2+o,4)) img = 4;
else if (!strnicmp(".lzs",(LPCTSTR)dir2+o,4)) img = 4;
else if (!strnicmp(".tim",(LPCTSTR)dir2+o,4)) img = 4;
else img = 3;
tmp = list.InsertItem(i,(LPCTSTR)dir2+q+1,img);
list.SetItemText(tmp,1,"-");
list.SetItemData(tmp,i);
}
}
*pResult = 0;
}
| 26.385965 | 153 | 0.666413 | Keyaku |