blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8aa3824ad5577d1850826da7b3717d5d566b9d13 | 9d85f046c748424fca7991552334cae9c3d01330 | /VBsheet/main.cpp | 775da625af87db29780db77109a0e5751a609a1e | [] | no_license | r2d236po/VBSheet | 1fcdc591ca0666e736989fd61448c64aac0c0303 | 6023809ee12f3b73174ded32bd81a1d83211aa87 | refs/heads/master | 2020-04-17T19:42:16.833370 | 2016-08-21T15:26:33 | 2016-08-21T15:26:33 | 66,205,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | #include "prematch.h"
#include "match.h"
#include "teamlistv2.h"
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QFileDialog>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Match::initmatchSystem();
#if 0
Match test;
TeamlistV2 saveWindows(0,&test);
saveWindows.show();
a.exec();
#endif
MainWindow test2;
test2.show();
a.exec();
return 1;
}
| [
"noreply@github.com"
] | r2d236po.noreply@github.com |
c0a8fe821bb82028b677887db65198de8463df84 | 8947812c9c0be1f0bb6c30d1bb225d4d6aafb488 | /01_Develop/libXMGraphics/Source/FTGLES/FTGL/FTGlyph.h | 5aa679289192765112c148cd7c3fa01110547639 | [
"MIT"
] | permissive | alissastanderwick/OpenKODE-Framework | cbb298974e7464d736a21b760c22721281b9c7ec | d4382d781da7f488a0e7667362a89e8e389468dd | refs/heads/master | 2021-10-25T01:33:37.821493 | 2016-07-12T01:29:35 | 2016-07-12T01:29:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,122 | h | /*
* FTGL - OpenGL font library
*
* Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>
* Copyright (c) 2008 Sam Hocevar <sam@zoy.org>
* Copyright (c) 2008 Sean Morrison <learner@brlcad.org>
*
* 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.
*/
#ifndef __FTGlyph__
#define __FTGlyph__
#ifdef __cplusplus
class FTGlyphImpl;
/**
* FTGlyph is the base class for FTGL glyphs.
*
* It provides the interface between Freetype glyphs and their openGL
* renderable counterparts. This is an abstract class and derived classes
* must implement the <code>Render</code> function.
*
* @see FTBBox
* @see FTPoint
*/
class FTGL_EXPORT FTGlyph
{
protected:
/**
* Create a glyph.
*
* @param glyph The Freetype glyph to be processed
*/
FTGlyph(FT_GlyphSlot glyph);
private:
/**
* Internal FTGL FTGlyph constructor. For private use only.
*
* @param pImpl Internal implementation object. Will be destroyed
* upon FTGlyph deletion.
*/
FTGlyph(FTGlyphImpl *pImpl);
/* Allow our internal subclasses to access the private constructor */
friend class FTBitmapGlyph;
friend class FTBufferGlyph;
//friend class FTExtrudeGlyph;
friend class FTOutlineGlyph;
//friend class FTPixmapGlyph;
//friend class FTPolygonGlyph;
friend class FTTextureGlyph;
public:
/**
* Destructor
*/
virtual ~FTGlyph();
/**
* Renders this glyph at the current pen position.
*
* @param pen The current pen position.
* @param renderMode Render mode to display
* @return The advance distance for this glyph.
*/
virtual const FTPoint& Render(const FTPoint& pen, int renderMode) = 0;
/**
* Return the advance width for this glyph.
*
* @return advance width.
*/
virtual float Advance() const;
/**
* Return the bounding box for this glyph.
*
* @return bounding box.
*/
virtual const FTBBox& BBox() const;
/**
* Queries for errors.
*
* @return The current error code.
*/
virtual FT_Error Error() const;
private:
/**
* Internal FTGL FTGlyph implementation object. For private use only.
*/
FTGlyphImpl *impl;
};
#endif //__cplusplus
FTGL_BEGIN_C_DECLS
/**
* FTGLglyph is the base class for FTGL glyphs.
*
* It provides the interface between Freetype glyphs and their openGL
* renderable counterparts. This is an abstract class and derived classes
* must implement the ftglRenderGlyph() function.
*/
struct _FTGLGlyph;
typedef struct _FTGLglyph FTGLglyph;
/**
* Create a custom FTGL glyph object.
* FIXME: maybe get rid of "base" and have advanceCallback etc. functions
*
* @param base The base FTGLglyph* to subclass.
* @param data A pointer to private data that will be passed to callbacks.
* @param renderCallback A rendering callback function.
* @param destroyCallback A callback function to be called upon destruction.
* @return An FTGLglyph* object.
*/
FTGL_EXPORT FTGLglyph *ftglCreateCustomGlyph(FTGLglyph *base, void *data,
void (*renderCallback) (FTGLglyph *, void *, FTGL_DOUBLE, FTGL_DOUBLE,
int, FTGL_DOUBLE *, FTGL_DOUBLE *),
void (*destroyCallback) (FTGLglyph *, void *));
/**
* Destroy an FTGL glyph object.
*
* @param glyph An FTGLglyph* object.
*/
FTGL_EXPORT void ftglDestroyGlyph(FTGLglyph *glyph);
/**
* Render a glyph at the current pen position and compute the corresponding
* advance.
*
* @param glyph An FTGLglyph* object.
* @param penx The current pen's X position.
* @param peny The current pen's Y position.
* @param renderMode Render mode to display
* @param advancex A pointer to an FTGL_DOUBLE where to write the advance's X
* component.
* @param advancey A pointer to an FTGL_DOUBLE where to write the advance's Y
* component.
*/
FTGL_EXPORT void ftglRenderGlyph(FTGLglyph *glyph, FTGL_DOUBLE penx,
FTGL_DOUBLE peny, int renderMode,
FTGL_DOUBLE *advancex, FTGL_DOUBLE *advancey);
/**
* Return the advance for a glyph.
*
* @param glyph An FTGLglyph* object.
* @return The advance's X component.
*/
FTGL_EXPORT float ftglGetGlyphAdvance(FTGLglyph *glyph);
/**
* Return the bounding box for a glyph.
*
* @param glyph An FTGLglyph* object.
* @param bounds An array of 6 float values where the bounding box's lower
* left near and upper right far 3D coordinates will be stored.
*/
FTGL_EXPORT void ftglGetGlyphBBox(FTGLglyph *glyph, float bounds[6]);
/**
* Query a glyph for errors.
*
* @param glyph An FTGLglyph* object.
* @return The current error code.
*/
FTGL_EXPORT FT_Error ftglGetGlyphError(FTGLglyph* glyph);
FTGL_END_C_DECLS
#endif // __FTGlyph__
| [
"mcodegeeks@gmail.com"
] | mcodegeeks@gmail.com |
1b50bbd08c61feef41bffbd86f20efb1c13263d3 | 0fc6eadc8811a6990e0bd41e9a23bf698e738c88 | /比赛/icpc/南京/j.cpp | ded65dc8971450d775327416da3d04f4a8548da0 | [] | no_license | bossxu/acm | f88ee672736709f75739522d7e0f000ac86a31de | 871f8096086e53aadaf48cd098267dfbe6b51e19 | refs/heads/master | 2018-12-27T22:20:27.307185 | 2018-12-20T04:41:51 | 2018-12-20T04:41:51 | 108,379,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | cpp | #include<bits/stdc++.h>
using namespace std;
#define clr(shu,x) memset(shu,x,sizeof(shu))
#define INF 0x3f3f3f3f
#define pi acos(-1)
#define loge exp(1)
#define ll long long
#define pb push_back
#define ios_close ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
const int mod = 1e9+7;
const double eps = 1e-6;
const int maxn = 20000001;
const int N=2e7+5;
bool mark[N];
ll prim[N],d[N],num[N];
int cnt;
void initial()
{
cnt=0;
d[1]=1;
for (int i=2 ; i<N ; ++i)
{
if (!mark[i])
{
prim[cnt++]=i;
num[i]=1;
d[i]=2;
}
for (int j=0 ; j<cnt && i*prim[j]<N ; ++j)
{
mark[i*prim[j]]=1;
if (!(i%prim[j]))
{
num[i*prim[j]]=num[i]+1;
if(num[i*prim[j]] > 2)
d[i*prim[j]] = 0;
if(num[i*prim[j]] == 2)
d[i*prim[j]]=d[i]/2;
break;
}
d[i*prim[j]]=d[i]*d[prim[j]];
num[i*prim[j]]=1;
}
}
for(int i = 1;i<=maxn;i++)
{
d[i] += d[i-1];
}
}
int main()
{
int t;
initial();
scanf("%d",&t);
while(t--)
{
ll n;
scanf("%lld",&n);
printf("%lld\n",d[n]);
}
return 0;
}
| [
"756753676@qq.com"
] | 756753676@qq.com |
af3741167a98532b733de0976441bedd51231bb3 | 6a55fc908497a0d4ada6eae74d64a057b609c261 | /inference-engine/src/transformations/src/ngraph_ops/normalize_ie.cpp | 65275853552654b90de1bd46d3857b4311b04a50 | [
"Apache-2.0"
] | permissive | anton-potapov/openvino | 9f24be70026a27ea55dafa6e7e2b6b18c6c18e88 | 84119afe9a8c965e0a0cd920fff53aee67b05108 | refs/heads/master | 2023-04-27T16:34:50.724901 | 2020-06-10T11:13:08 | 2020-06-10T11:13:08 | 271,256,329 | 1 | 0 | Apache-2.0 | 2021-04-23T08:22:48 | 2020-06-10T11:16:29 | null | UTF-8 | C++ | false | false | 1,424 | cpp | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph_ops/normalize_ie.hpp"
#include <memory>
#include <string>
#include "ngraph/op/constant.hpp"
using namespace std;
using namespace ngraph;
constexpr NodeTypeInfo op::NormalizeIE::type_info;
op::NormalizeIE::NormalizeIE(const Output<Node>& data, const Output<Node>& weights, float eps, bool across_spatial,
bool channel_shared)
: Op({data, weights}), m_eps(eps), m_across_spatial(across_spatial), m_channel_shared(channel_shared) {
constructor_validate_and_infer_types();
}
void op::NormalizeIE::validate_and_infer_types() {
element::Type arg_type = get_input_element_type(0);
PartialShape arg_shape = get_input_partial_shape(0);
set_output_type(0, arg_type, arg_shape);
const PartialShape& input_shape = get_input_partial_shape(0);
NODE_VALIDATION_CHECK(this,
input_shape.rank().is_dynamic() || input_shape.rank().get_length() >= 2 && input_shape.rank().get_length() <= 4,
"Argument must have rank >= 2 and <= 4 (argument shape: ", input_shape, ").");
}
shared_ptr<Node> op::NormalizeIE::copy_with_new_args(const NodeVector& new_args) const {
check_new_args_count(this, new_args);
return make_shared<op::NormalizeIE>(new_args.at(0), new_args.at(1), m_eps, m_across_spatial, m_channel_shared);
}
| [
"alexey.suhov@intel.com"
] | alexey.suhov@intel.com |
1296c6462d13468db8e29629b2305869aab41fe0 | d89a102718ba60ee88b730d7a8c9412971e40fd9 | /External/eigen-3.3.7/unsupported/test/cxx11_tensor_thread_pool.cpp | 62f1bab5a38b9d9376e72197b06056f995f5052f | [
"MIT",
"GPL-3.0-only",
"LGPL-2.1-only",
"Minpack",
"MPL-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later"
] | permissive | RokKos/eol-cloth | bd228eef04400d3199864d5d7cf60de641c88479 | b9c6f55f25ba17f33532ea5eefa41fedd29c5206 | refs/heads/master | 2021-02-18T23:08:30.700135 | 2020-03-28T10:46:48 | 2020-03-28T10:46:48 | 245,248,707 | 0 | 0 | MIT | 2020-03-05T19:20:33 | 2020-03-05T19:20:32 | null | UTF-8 | C++ | false | false | 12,672 | cpp | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPool tp(4);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabsf(t_result(i) - m_result(i)) < 1e-4f) {
continue;
}
if (Eigen::internal::isApprox(t_result(i), m_result(i), 1e-4f)) {
continue;
}
std::cout << "mismatch detected at index " << i << ": " << t_result(i)
<< " vs " << m_result(i) << std::endl;
assert(false);
}
}
template<int DataLayout>
void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPool tp(12);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!(numext::isnan)(t_result.data()[i]));
if (fabsf(t_result.data()[i] - m_result.data()[i]) >= 1e-4f) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!(numext::isnan)(t_result.data()[i]));
if (fabsf(t_result.data()[i] - m_result.data()[i]) >= 1e-4f) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!(numext::isnan)(t_result.data()[i]));
if (fabsf(t_result.data()[i] - m_result.data()[i]) >= 1e-4f) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!(numext::isnan)(t_result.data()[i]));
if (fabsf(t_result.data()[i] - m_result.data()[i]) >= 1e-4f) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPool tp(internal::random<int>(2, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (numext::abs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4f) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
template<int DataLayout>
void test_full_contraction() {
int contract_size1 = internal::random<int>(1, 500);
int contract_size2 = internal::random<int>(1, 500);
Tensor<float, 2, DataLayout> left(contract_size1,
contract_size2);
Tensor<float, 2, DataLayout> right(contract_size1,
contract_size2);
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 2>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(0, 0), DimPair(1, 1)}});
Eigen::ThreadPool tp(internal::random<int>(2, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(2, 11));
Tensor<float, 0, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 0, DataLayout> tp_result;
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (numext::abs(st_result() - tp_result()) >= 1e-4f) {
VERIFY_IS_APPROX(st_result(), tp_result());
}
}
template<int DataLayout>
void test_multithreaded_reductions() {
const int num_threads = internal::random<int>(3, 11);
ThreadPool thread_pool(num_threads);
Eigen::ThreadPoolDevice thread_pool_device(&thread_pool, num_threads);
const int num_rows = internal::random<int>(13, 732);
const int num_cols = internal::random<int>(13, 732);
Tensor<float, 2, DataLayout> t1(num_rows, num_cols);
t1.setRandom();
Tensor<float, 0, DataLayout> full_redux;
full_redux = t1.sum();
Tensor<float, 0, DataLayout> full_redux_tp;
full_redux_tp.device(thread_pool_device) = t1.sum();
// Check that the single threaded and the multi threaded reductions return
// the same result.
VERIFY_IS_APPROX(full_redux(), full_redux_tp());
}
void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPool tp(num_threads);
Eigen::ThreadPoolDevice thread_pool_device(&tp, num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int j = 0; j < size; j++) {
VERIFY_IS_EQUAL(t1(j), result[j]);
}
}
}
void test_multithread_random()
{
Eigen::ThreadPool tp(2);
Eigen::ThreadPoolDevice device(&tp, 2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
template<int DataLayout>
void test_multithread_shuffle()
{
Tensor<float, 4, DataLayout> tensor(17,5,7,11);
tensor.setRandom();
const int num_threads = internal::random<int>(2, 11);
ThreadPool threads(num_threads);
Eigen::ThreadPoolDevice device(&threads, num_threads);
Tensor<float, 4, DataLayout> shuffle(7,5,11,17);
array<ptrdiff_t, 4> shuffles = {{2,1,3,0}};
shuffle.device(device) = tensor.shuffle(shuffles);
for (int i = 0; i < 17; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
for (int l = 0; l < 11; ++l) {
VERIFY_IS_EQUAL(tensor(i,j,k,l), shuffle(k,j,l,i));
}
}
}
}
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST_1(test_multithread_elementwise());
CALL_SUBTEST_1(test_multithread_compound_assignment());
CALL_SUBTEST_2(test_multithread_contraction<ColMajor>());
CALL_SUBTEST_2(test_multithread_contraction<RowMajor>());
CALL_SUBTEST_3(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST_3(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST_4(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST_4(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST_4(test_full_contraction<ColMajor>());
CALL_SUBTEST_4(test_full_contraction<RowMajor>());
CALL_SUBTEST_5(test_multithreaded_reductions<ColMajor>());
CALL_SUBTEST_5(test_multithreaded_reductions<RowMajor>());
CALL_SUBTEST_6(test_memcpy());
CALL_SUBTEST_6(test_multithread_random());
CALL_SUBTEST_6(test_multithread_shuffle<ColMajor>());
CALL_SUBTEST_6(test_multithread_shuffle<RowMajor>());
}
| [
"rok.kos@outfit7.com"
] | rok.kos@outfit7.com |
4efc3da5f06d9c80d4d8e718ab5bc54100120df9 | 76a85bf82e51e8c09305af4d962bb0d2169fe42d | /Source/Trolled/Items/GearItem.h | 4dfc988fd167084fbb146f1898b654b78e672637 | [] | no_license | nik3122/Trolled | 29a1bc88ba8710e6871bc44a01fa357781a8e69f | b5d21bf9f9daafc9f9afd14accccad8a42d7125b | refs/heads/master | 2022-11-28T21:13:27.183880 | 2020-08-14T21:58:00 | 2020-08-14T21:58:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Trolled/Items/EquippableItem.h"
#include "GearItem.generated.h"
/**
*
*/
// can create in bp
UCLASS(Blueprintable)
class TROLLED_API UGearItem : public UEquippableItem
{
GENERATED_BODY()
public:
UGearItem();
// override Equip/UnEquip to define how the gear items work
virtual bool Equip(class AMainCharacter* Character) override;
virtual bool UnEquip(class AMainCharacter* Character) override;
// skeletal mesh for the gear
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Gear")
class USkeletalMesh* Mesh;
// material instance to apply to the gear
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Gear")
class UMaterialInstance* MaterialInstance;
// Damage reduction this item provides, 0.2 = 20% less damage taken. Clamped at 0% and 100%
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Gear", meta = (ClampMin = 0.0, ClampMax = 1.0))
float DamageReductionMultiplier;
};
| [
"eric.born85@gmail.com"
] | eric.born85@gmail.com |
f67eeba4eb46326c1f4a44b3b531ed9dea68e005 | 3f3400cd20ba816e787192973e8fdaf9d538e73d | /content/browser/accessibility/accessibility_tree_formatter_base_unittest.cc | f66f5c91384ee6b3dfabb2cd9285314c20fdf09b | [
"BSD-3-Clause"
] | permissive | kshpin/stripped-chromium | 9269998b47d4b01d08c0e288a93d66698cb2efaf | 6f845e8804232c3547e85507574a65d88c166402 | refs/heads/master | 2022-12-05T21:25:05.654148 | 2020-08-21T01:21:13 | 2020-08-21T01:21:13 | 288,032,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,567 | cc | // Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/accessibility/accessibility_tree_formatter_base.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/test_browser_accessibility_delegate.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
namespace content {
class AccessibilityTreeFormatterBaseTest : public testing::Test {
public:
AccessibilityTreeFormatterBaseTest() = default;
~AccessibilityTreeFormatterBaseTest() override = default;
protected:
std::unique_ptr<TestBrowserAccessibilityDelegate>
test_browser_accessibility_delegate_;
private:
void SetUp() override {
test_browser_accessibility_delegate_ =
std::make_unique<TestBrowserAccessibilityDelegate>();
}
DISALLOW_COPY_AND_ASSIGN(AccessibilityTreeFormatterBaseTest);
};
PropertyNode Parse(const char* input) {
AccessibilityTreeFormatter::PropertyFilter filter(
base::UTF8ToUTF16(input),
AccessibilityTreeFormatter::PropertyFilter::ALLOW);
return PropertyNode::FromPropertyFilter(filter);
}
PropertyNode GetArgumentNode(const char* input) {
auto got = Parse(input);
if (got.parameters.size() == 0) {
return PropertyNode();
}
return std::move(got.parameters[0]);
}
void ParseAndCheck(const char* input, const char* expected) {
auto got = Parse(input).ToString();
EXPECT_EQ(got, expected);
}
TEST_F(AccessibilityTreeFormatterBaseTest, ParseProperty) {
// Properties and methods.
ParseAndCheck("Role", "Role");
ParseAndCheck("ChildAt(3)", "ChildAt(3)");
ParseAndCheck("Cell(3, 4)", "Cell(3, 4)");
ParseAndCheck("Volume(3, 4, 5)", "Volume(3, 4, 5)");
ParseAndCheck("TableFor(CellBy(id))", "TableFor(CellBy(id))");
ParseAndCheck("A(B(1), 2)", "A(B(1), 2)");
ParseAndCheck("A(B(1), 2, C(3, 4))", "A(B(1), 2, C(3, 4))");
ParseAndCheck("[3, 4]", "[](3, 4)");
ParseAndCheck("Cell([3, 4])", "Cell([](3, 4))");
// Arguments
ParseAndCheck("Text({val: 1})", "Text({}(val: 1))");
ParseAndCheck("Text({lat: 1, len: 1})", "Text({}(lat: 1, len: 1))");
ParseAndCheck("Text({dict: {val: 1}})", "Text({}(dict: {}(val: 1)))");
ParseAndCheck("Text({dict: {val: 1}, 3})", "Text({}(dict: {}(val: 1), 3))");
ParseAndCheck("Text({dict: [1, 2]})", "Text({}(dict: [](1, 2)))");
ParseAndCheck("Text({dict: ValueFor(1)})", "Text({}(dict: ValueFor(1)))");
// Nested arguments
ParseAndCheck("AXIndexForTextMarker(AXTextMarkerForIndex(0))",
"AXIndexForTextMarker(AXTextMarkerForIndex(0))");
// Line indexes filter.
ParseAndCheck(":3,:5;AXDOMClassList", ":3,:5;AXDOMClassList");
// Wrong format.
ParseAndCheck("Role(3", "Role(3)");
ParseAndCheck("TableFor(CellBy(id", "TableFor(CellBy(id))");
ParseAndCheck("[3, 4", "[](3, 4)");
// Arguments conversion
EXPECT_EQ(GetArgumentNode("ChildAt([3])").IsArray(), true);
EXPECT_EQ(GetArgumentNode("Text({loc: 3, len: 2})").IsDict(), true);
EXPECT_EQ(GetArgumentNode("ChildAt(3)").IsDict(), false);
EXPECT_EQ(GetArgumentNode("ChildAt(3)").IsArray(), false);
EXPECT_EQ(GetArgumentNode("ChildAt(3)").AsInt(), 3);
// Dict: FindStringKey
EXPECT_EQ(
GetArgumentNode("Text({start: :1, dir: forward})").FindStringKey("start"),
":1");
EXPECT_EQ(
GetArgumentNode("Text({start: :1, dir: forward})").FindStringKey("dir"),
"forward");
EXPECT_EQ(GetArgumentNode("Text({start: :1, dir: forward})")
.FindStringKey("notexists"),
base::nullopt);
// Dict: FindIntKey
EXPECT_EQ(GetArgumentNode("Text({loc: 3, len: 2})").FindIntKey("loc"), 3);
EXPECT_EQ(GetArgumentNode("Text({loc: 3, len: 2})").FindIntKey("len"), 2);
EXPECT_EQ(GetArgumentNode("Text({loc: 3, len: 2})").FindIntKey("notexists"),
base::nullopt);
// Dict: FindKey
EXPECT_EQ(GetArgumentNode("Text({anchor: {:1, 0, up}})")
.FindKey("anchor")
->ToString(),
"anchor: {}(:1, 0, up)");
EXPECT_EQ(GetArgumentNode("Text({anchor: {:1, 0, up}})").FindKey("focus"),
nullptr);
EXPECT_EQ(GetArgumentNode("AXStringForTextMarkerRange({anchor: {:2, 1, "
"down}, focus: {:2, 2, down}})")
.FindKey("anchor")
->ToString(),
"anchor: {}(:2, 1, down)");
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
fd4a779efdecf8953aa1c9e8efb859486539017e | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Freescale/MK20D5/include/arch/reg/cmp1.hpp | 1e88dab715db94370a21d97dccbd7cdccae03e70 | [] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,370 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory).
*
* 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.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Freescale/MK20D5.svd"
//
// vendor: Freescale Semiconductor, Inc.
// vendorID: Freescale
// name: MK20D5
// series: Kinetis_K
// version: 1.6
// description: MK20D5 Freescale Microcontroller
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_CMP1_HPP_INCLUDED
#define ARCH_REG_CMP1_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* High-Speed Comparator (CMP), Voltage Reference (VREF) Digital-to-Analog Converter (DAC), and Analog Mux (ANMUX)
*/
struct CMP1
{
static constexpr reg_addr_t base_addr = 0x40073008;
/**
* CMP Control Register 0
*/
struct CR0
: public reg< uint8_t, base_addr + 0, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0, rw, 0 >;
using HYSTCTR = regbits< type, 0, 2 >; /**< Comparator hard block hysteresis control */
using FILTER_CNT = regbits< type, 4, 3 >; /**< Filter Sample Count */
};
/**
* CMP Control Register 1
*/
struct CR1
: public reg< uint8_t, base_addr + 0x1, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x1, rw, 0 >;
using EN = regbits< type, 0, 1 >; /**< Comparator Module Enable */
using OPE = regbits< type, 1, 1 >; /**< Comparator Output Pin Enable */
using COS = regbits< type, 2, 1 >; /**< Comparator Output Select */
using INV = regbits< type, 3, 1 >; /**< Comparator INVERT */
using PMODE = regbits< type, 4, 1 >; /**< Power Mode Select */
using WE = regbits< type, 6, 1 >; /**< Windowing Enable */
using SE = regbits< type, 7, 1 >; /**< Sample Enable */
};
/**
* CMP Filter Period Register
*/
struct FPR
: public reg< uint8_t, base_addr + 0x2, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x2, rw, 0 >;
using FILT_PER = regbits< type, 0, 8 >; /**< Filter Sample Period */
};
/**
* CMP Status and Control Register
*/
struct SCR
: public reg< uint8_t, base_addr + 0x3, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x3, rw, 0 >;
using COUT = regbits< type, 0, 1 >; /**< Analog Comparator Output */
using CFF = regbits< type, 1, 1 >; /**< Analog Comparator Flag Falling */
using CFR = regbits< type, 2, 1 >; /**< Analog Comparator Flag Rising */
using IEF = regbits< type, 3, 1 >; /**< Comparator Interrupt Enable Falling */
using IER = regbits< type, 4, 1 >; /**< Comparator Interrupt Enable Rising */
using DMAEN = regbits< type, 6, 1 >; /**< DMA Enable Control */
};
/**
* DAC Control Register
*/
struct DACCR
: public reg< uint8_t, base_addr + 0x4, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x4, rw, 0 >;
using VOSEL = regbits< type, 0, 6 >; /**< DAC Output Voltage Select */
using VRSEL = regbits< type, 6, 1 >; /**< Supply Voltage Reference Source Select */
using DACEN = regbits< type, 7, 1 >; /**< DAC Enable */
};
/**
* MUX Control Register
*/
struct MUXCR
: public reg< uint8_t, base_addr + 0x5, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x5, rw, 0 >;
using MSEL = regbits< type, 0, 3 >; /**< Minus Input MUX Control */
using PSEL = regbits< type, 3, 3 >; /**< Plus Input MUX Control */
};
};
} // namespace mptl
#endif // ARCH_REG_CMP1_HPP_INCLUDED
| [
"axel@tty0.ch"
] | axel@tty0.ch |
183e033cdd8e330594aea24cf1d5655c89f489f2 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/iis/svcs/nntp/server/server/sortlist.h | 9fe0fe04e873d4990c5db6b6e3c54ee18464a0f2 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,909 | h | //
// sortlist.h
//
// This file contains stuff for building sorted lists. The classes defined
// here are templated in which the user can specify his own key and
// data element. It is assumed by the templates that an element can
// be copied using CopyMemory() or MoveMemory().
//
// Implementation Schedule for all classed defined by this file :
//
// 0.5 week
//
//
// Unit Test Schedule for all classes defined by this file :
//
// 0.5 week
//
// Unit Testing will consist of the following :
//
// Build a standalone executable that uses these templates to build
// a sorted list. This executable should do the following :
// Create a list and insert elements in sorted order
// Create a list and insert elements in reverse sorted order
// Create a list and insert elements in random order
// Search for every element inserted in each list.
// Search for elements not in the list.
//
//
#ifndef _SORTLIST_H_
#define _SORTLIST_H_
#include "smartptr.h"
/*
The following defines the interface the classes used
with the template must support :
class Data {
public :
Data() ;
Key& GetKey( ) ;
} ;
class Key {
public :
BOOL operator < ( Key& ) ;
BOOL operator== ( Key& ) ;
BOOL operator > ( Key& ) ;
} ;
*/
//----------------------------------------------------------------------
template< class Data, class Key >
class CList : public CRefCount {
//
// Template class CList -
// This template will maintain a sorted array of elements.
// This will be an array of type Data (not Data*).
// We will keep track of three things :
// a pointer to the array.
// The Number of elements in use in the array.
// The total number of elements in the array.
//
// This class is derived from CRefCount and can be used with Smart Pointers.
//
// This Insert function of this class is not Multi-thread safe. All other
// functions are.
//
private :
friend class CListIterator< Data, Key > ;
Data* m_pData ; // Array of Data objects
int m_cData ; // Number of Data objects we are using in the array
int m_cLimit ; // Total Number of Data objects in the array. The
// last m_cLimit-m_cData objects are initialized with the
// default constructor and do not take place in any
// searches.
//
// Private functions used to manage the size of the array.
//
BOOL Grow( int cGrowth ) ;
BOOL Shrink( int cGap ) ;
int Search( Key&, BOOL& ) ;
public :
//
// Because we want to be smart pointer enabled we have very
// simple constructors.
//
CList( ) ;
~CList( ) ;
//
// Initialization functions
//
BOOL Init( int limit ) ; // Specify initial size,
// no elements in the list
BOOL Init( Data *p, int cData ) ; // Specify an initial array
// of elements which we will copy.
BOOL IsValid() ; // Test validity of this class
BOOL Insert( Data& entry ) ;
BOOL Search( Key&, Data& ) ;
BOOL Remove( Key&, Data& ) ;
} ;
#include "sortlist.inl"
//-----------------------------------------------------------------------
template< class Data, class Key >
//
// Template class CListIterator -
//
// This class is used by people who wish to enumerate a sorted list.
//
// We will either enumerate everything in the list, or upon
// Initialization the user will specify a key, and we will enumerate
// everything following that key.
//
// This class is not intended to be multithread safe. If two threads
// wish to enumerate the same list they should create different CListIterator
// objects.
//
//
class CListIterator {
public :
typedef CList< Data, Key > TARGETLIST ;
private :
CRefPtr< TARGETLIST > m_pList ; // Smart pointer to original list
int m_index ; // current position
int m_begin ; // begin of the range we are enuming
int m_end ; // end of the range we are enuming
public :
//
// Simple Constructor and Destructor.
//
CListIterator( ) ;
~CListIterator( ) ;
//
// Initialization functions. User may specify an initial key
// if they wish to enumerate only things larger than the key.
//
BOOL Init( TARGETLIST *p ) ;
BOOL Init( TARGETLIST *p, Key k ) ;
//
// Worker functions.
// These functions use m_index, m_begin and m_end to move through the list.
//
Data Next( ) ;
Data Prev( ) ;
BOOL IsEnd( ) ;
BOOL IsBegin( ) ;
} ;
#include "iterator.inl"
#endif // _SORTLIST_H_ | [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
e6b6cf561e66a695a5d25779a4230901e088a510 | a81c07a5663d967c432a61d0b4a09de5187be87b | /chrome/browser/page_load_metrics/observers/loading_predictor_page_load_metrics_observer.h | 26c0b218ff5a1e9479a78ca314bdbac06173e114 | [
"BSD-3-Clause"
] | permissive | junxuezheng/chromium | c401dec07f19878501801c9e9205a703e8643031 | 381ce9d478b684e0df5d149f59350e3bc634dad3 | refs/heads/master | 2023-02-28T17:07:31.342118 | 2019-09-03T01:42:42 | 2019-09-03T01:42:42 | 205,967,014 | 2 | 0 | BSD-3-Clause | 2019-09-03T01:48:23 | 2019-09-03T01:48:23 | null | UTF-8 | C++ | false | false | 2,456 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_LOADING_PREDICTOR_PAGE_LOAD_METRICS_OBSERVER_H_
#define CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_LOADING_PREDICTOR_PAGE_LOAD_METRICS_OBSERVER_H_
#include <memory>
#include "chrome/browser/page_load_metrics/page_load_metrics_observer.h"
namespace content {
class WebContents;
}
namespace predictors {
class ResourcePrefetchPredictor;
class LoadingDataCollector;
}
namespace internal {
extern const char
kHistogramLoadingPredictorFirstContentfulPaintPreconnectable[];
extern const char
kHistogramLoadingPredictorFirstMeaningfulPaintPreconnectable[];
} // namespace internal
// Observer responsible for recording page load metrics relevant to
// ResourcePrefetchPredictor.
class LoadingPredictorPageLoadMetricsObserver
: public page_load_metrics::PageLoadMetricsObserver {
public:
// Returns a LoadingPredictorPageLoadMetricsObserver, or nullptr if it is not
// needed.
static std::unique_ptr<LoadingPredictorPageLoadMetricsObserver>
CreateIfNeeded(content::WebContents* web_contents);
// Public for testing. Normally one should use CreateIfNeeded. Predictor must
// outlive this observer.
explicit LoadingPredictorPageLoadMetricsObserver(
predictors::ResourcePrefetchPredictor* predictor,
predictors::LoadingDataCollector* collector);
~LoadingPredictorPageLoadMetricsObserver() override;
// page_load_metrics::PageLoadMetricsObserver:
ObservePolicy OnStart(content::NavigationHandle* navigation_handle,
const GURL& currently_commited_url,
bool started_in_foreground) override;
ObservePolicy OnHidden(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
void OnFirstContentfulPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
void OnFirstMeaningfulPaintInMainFrameDocument(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
private:
predictors::ResourcePrefetchPredictor* predictor_;
predictors::LoadingDataCollector* collector_;
bool record_histogram_preconnectable_;
DISALLOW_COPY_AND_ASSIGN(LoadingPredictorPageLoadMetricsObserver);
};
#endif // CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_LOADING_PREDICTOR_PAGE_LOAD_METRICS_OBSERVER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8a914abc3494acac91df3f90b0fbafa9271d0479 | 2cad35f19ba36f23ce1b80d55b85c20bdd357bca | /Qt Topics/QSettings/settings/widget.h | 9a451677e06dfee7458cba727cdf6a593c01c7a7 | [] | no_license | emrahsariboz/QTCreatorProjects | 26bb3aa25f0c378d021c3e783868a89be9104fb6 | 9dcb9f30686de599db1a38495d9ab088e51e202c | refs/heads/master | 2020-11-25T08:00:18.717870 | 2020-08-06T05:45:31 | 2020-08-06T05:45:31 | 228,566,566 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_1_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
void on_pushButton_5_clicked();
void on_pushButton_6_clicked();
void on_pushButton_7_clicked();
void on_pushButton_8_clicked();
void on_pushButton_9_clicked();
void on_saveButton_clicked();
void on_loadButton_clicked();
private:
Ui::Widget *ui;
QList<QColor> colorList;
void saveColor(QString key, QColor color);
QColor loadColor(QString key);
void setLoadedColor(QString key, int index, QPushButton *button);
};
#endif // WIDGET_H
| [
"emrahsarboz@gmail.com"
] | emrahsarboz@gmail.com |
50b04728ae22b75c5218f38773969dbaae84381f | 262fcd1fa1864ffecb64748680b3cd9ef5ddbd00 | /abc/abc182/a.cpp | eb257f47140b40d2fb24ddcfa9b6ff468141dfb3 | [] | no_license | jpskgc/AtCoder | 3e183afc5cbc3241a2fb4df2baa5226be2d624ad | c3121127105fe433b25bb52c7ce08028a7aba6cf | refs/heads/main | 2023-07-15T21:57:29.775193 | 2021-08-08T18:20:14 | 2021-08-08T18:20:14 | 319,402,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int A, B;
cin >> A >> B;
cout << (2 * A + 100) - B << endl;
} | [
"jpskgc.v3@gmail.com"
] | jpskgc.v3@gmail.com |
16d63578c02824443e39c389b47601ef25ef0ad0 | 8544dd472224f976886f4cfe9219d61d9a4819fc | /ShieldedFighterEnemy.h | e9bd13567daebf4a5fc68a2c415f31ed81864334 | [] | no_license | KareemOsamaSobeih/DS-KOMK | f43b284addbbba2f6d671aadba098e8b63b90dc2 | 712a7639078edd5a0ad68f475b771c7cead14546 | refs/heads/master | 2021-04-18T19:55:29.077400 | 2018-04-09T12:32:41 | 2018-04-09T12:32:41 | 126,900,660 | 0 | 0 | null | 2018-03-26T23:12:54 | 2018-03-26T23:12:54 | null | UTF-8 | C++ | false | false | 460 | h | #pragma once
#include "Enemy.h"
class ShieldedFighterEnemy : public Enemy
{
public:
ShieldedFighterEnemy();
~ShieldedFighterEnemy();
virtual void SetColor();
static void SetC1(double c1);
static void SetC2(double c2);
static void SetC3(double c3);
static double GetC1();
static double GetC2();
static double GetC3();
double GetPriority(int t)const;
private:
static double C1, C2, C3;
virtual void DecrementHealth(double f);
}; | [
"noreply@github.com"
] | KareemOsamaSobeih.noreply@github.com |
ba6fcb93980a20455da3954e47213362fdcfff61 | 0112f46215be863139b81b2a05144d42d1fa293d | /4_semestre/programacao_de_computadores_III/WorkspacePG3/ProjetoMatrizTemplate/Erro.cpp | 3c91310cf0960fa735a433e280e69d0d0a2b9c78 | [] | no_license | adyjunior/adyjrpucgo | 0f07b5bd7678bda19724655d69dc4ffccfec0b6f | 4a631e36ea7214a8d887f4a762771c234b4873a8 | refs/heads/master | 2021-01-25T07:19:53.188133 | 2014-11-25T23:50:36 | 2014-11-25T23:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | cpp | #include "Erro.h"
namespace PG3 {
Erro::Erro(int opcao) {
int tam;
std::string nomeDoArquivo,lixo;
if(opcao == 2)
nomeDoArquivo="DiretorioErro/arquivoDeErro.txt";
else
nomeDoArquivo="DiretorioErro/arquivoDeErroEUA.txt";
std::ifstream arquivo(nomeDoArquivo.c_str());
try{
if(!arquivo.is_open()) throw (std::logic_error) ("Arquivo de Erro nao pode ser aberto");
arquivo >> tam;
strErro = new std::string[tam];
std::getline(arquivo,lixo);
for(int i=0;i < tam;i++)
std::getline(arquivo,strErro[i]);
arquivo.close();
}catch(std::logic_error a){
arquivo.close();
throw a;
}catch(std::bad_alloc&){
arquivo.close();
throw (std::logic_error) ("Memoria insuficiente para criacao do arquivo de ERROS");
}
}
Erro *Erro::instancia=0;
}
| [
"adycmp@gmail.com"
] | adycmp@gmail.com |
29325c49f5f3f6bb8ba8778ae1c76ae993b9aa6f | e91e4e2d375796b905bc18dc8138e408e66f2b60 | /road fighter/UIButtonInputController.h | b55a31a6e8071e27922b833ca6f0919a5452b04d | [] | no_license | drei096/GDADPRG-MP | 0588fd8ad9e088791e51777e7fa8c5546daa6646 | 0932dda942dbb4102a9e6a3084594b0b6345826d | refs/heads/master | 2023-05-08T03:45:04.280026 | 2021-05-19T17:30:37 | 2021-05-19T17:30:37 | 368,188,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #pragma once
#include "InputController.h"
#include "ButtonListener.h"
#include "UIButton.h"
class UIButtonInputController : public InputController
{
public:
UIButtonInputController(string name, ButtonListener* buttonListener);
~UIButtonInputController();
void perform();
private:
ButtonListener* buttonListener;
bool pressed = false;
};
| [
"gauranadrei@yahoo.com"
] | gauranadrei@yahoo.com |
1ecaa0bae25c53e790c273038c5d30a3ca5f6afe | eed7b94f96fcff5e706c4ab726f12ee60647d272 | /steering_lacalite_withRF/steering_lacalite_withRF.ino | 92ea7b7bb35ad7b6747e192dc309b0f7fb7f7272 | [] | no_license | jessamarie21/AER201-v2 | d7713d11106b912eebbf3428c1ff2494dec2c48c | bf2f06d0f6b4ff00769c9893299f49259188e1ee | refs/heads/master | 2021-04-30T06:43:50.178574 | 2018-02-14T00:13:40 | 2018-02-14T00:13:40 | 121,451,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,743 | ino | /*Using Photo Sensors to Control Differential Steering
white left range: 420-430
white right range: 420-430
left black range: 330-350
right black range: 340-360
red left range: 390-400
red right range: 370-390
*/
//motor pins
int left_pins[] = {7,4};
int right_pins[] = {3,2};
const int enable_2 = 6;
const int enable_1 = 5;
//analog pins
const int left_pin = A0;
const int right_pin = A1;
const int mid_pin = A3;
const int side_pin = A2;
const int rec_pin = A4;
//line following calibration
int loc = 1;
int j = 0;
int max_black_left;
int max_black_mid;
int max_black_side;
int max_black_right = 360;
int max_red_left = 400;
int max_red_right = 390;
int min_white = 420;
//rf calibration
unsigned int rec_data = 0;
const unsigned int upper_limit = 370;
const unsigned int lower_limit = 370;
void setup()
{
Serial.begin(9600);
delay(1000);
for(int i = 0; i < 2; i++)
{
pinMode(left_pins[i],OUTPUT);
pinMode(right_pins[i],OUTPUT);
}
analogWrite(enable_2,255);
analogWrite(enable_1,255);
}
void loop()
{
//rf_receiving
/*rec_data = analogRead(rec_pin);
Serial.println(rec_data);
Serial.println('\n');*/
//line_following readings
int left_val = analogRead(left_pin);
int right_val = analogRead(right_pin);
int mid_val = analogRead(mid_pin);
int side_val = analogRead(side_pin);
Serial.println("left value: ");
Serial.println(left_val);
Serial.println(' ');
delay(1000);
Serial.println("right value: ");
Serial.println(right_val);
Serial.println(' ');
delay(1000);
Serial.println("middle value: ");
Serial.println(mid_val);
Serial.println(' ');
delay(1000);
Serial.println("side value: ");
Serial.println(side_val);
Serial.println(' ');
delay(2000);
/*if(left_val < max_black_left && right_val > max_black_right)
{
Turn_left_off();
}
else if(right_val < max_black_right && left_val > max_black_left)
{
Turn_right_off();
}
else if(right_val < max_black_right && left_val < max_black_left)
{
j++;
Serial.print("You have now passed ");
Serial.print(j);
Serial.println(" lines");
Drive_fwd();
}
else if(j == 4)
{
if(loc == 1)
{
while(mid_val > max_black_mid && side_val > max_black_side)
{
Turn_right_off();
mid_val = analogRead(mid_pin);
side_val = analogRead(side_pin);
}
j = 0;
}
else
{
Turn_left_off();
while(mid_val > max_black_mid && side_val > max_black_side)
{
Turn_left_off();
mid_val = analogRead(mid_pin);
side_val = analogRead(side_pin);
}
j = 0;
}
}
else
{
Drive_fwd();
}*/
}
void Drive_fwd()
{
Serial.println("Driving Forward");
digitalWrite(left_pins[0],LOW);
digitalWrite(left_pins[1],HIGH);
digitalWrite(right_pins[0],LOW);
digitalWrite(right_pins[1],HIGH);
}
void Drive_bwd()
{
digitalWrite(left_pins[0],HIGH);
digitalWrite(left_pins[1],LOW);
digitalWrite(right_pins[0],HIGH);
digitalWrite(right_pins[1],LOW);
Serial.println("Driving Backward");
}
void Turn_left_off()
{
digitalWrite(left_pins[0],LOW);
digitalWrite(left_pins[1],LOW);
//analogWrite(enable_1,30);
Serial.println("Turning Left off");
//change pwm instead of turning off motor completely
}
void Turn_right_off()
{
digitalWrite(right_pins[0],LOW);
digitalWrite(right_pins[1],LOW);
Serial.println("Turning Right off");
//analogWrite(enable_2,30);
}
void STOP()
{
digitalWrite(left_pins[0],LOW);
digitalWrite(left_pins[1],LOW);
digitalWrite(right_pins[0],LOW);
digitalWrite(right_pins[1],LOW);
Serial.println("STOPPING!");
}
| [
"jessa.zabala@mail.utoronto.ca"
] | jessa.zabala@mail.utoronto.ca |
1476bcf38e696918a6fde27139a56b437be0519b | 58d3e7dbcf5c33fbc6a8e681e1b0cdf2140e2925 | /SLIC_version/SLIC_version/Api.cpp | 53b8779083e602d3721df52f4794b78c8ff46659 | [] | no_license | janestar/SLIC_version | 7e9accaef318fb7bf998660836349d7f688e7e3f | d2cae7df12322466fe56425f394f5b7e3cbb39e8 | refs/heads/master | 2021-01-20T01:56:28.628551 | 2014-09-19T07:07:06 | 2014-09-19T07:07:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,214 | cpp | #include"Api.h"
//the interface of out algorithm
void Api:: Do_Depthimage_Repairing(cv::Mat& depth,cv::Mat& color,int sigma,int m_spcount,double m_compactness){
Mat depth2;
depth.copyTo(depth2);
Holefilling hole;
hole.setMat(depth);
hole.BFS();
cv::imwrite("C:/pic/d_holefilling.png",depth);
Mat cimg;
cimg.create(color.rows,color.cols,color.type());
cv::bilateralFilter(color,cimg,5,40,10);
cv::imwrite("C:/pic/c_bilateral.png",cimg);
int width=cimg.size().width;
int height=cimg.size().height;
int sz=width*height;
int* labels = new int[sz];
int numlabels(0);
//to ensure the size you set is meaningful
if(m_spcount < 10 || m_spcount > sz/4) m_spcount = sz/200;//i.e the default size of the superpixel is 200 pixels
if(m_compactness < 1.0 || m_compactness > 80.0) m_compactness = 20.0;
SLIC slic;
slic.DoSuperpixelSegmentation_ForGivenNumberOfSuperpixels(cimg, width, height, labels, numlabels, m_spcount, m_compactness);
slic.DrawContoursAroundSegments(depth, labels, width, height, 0,numlabels);
cv::imwrite("C:/pic/d_SLIC.png",depth);
vector<vector<Node>> vec=slic.getVector2();
vector<vector<Node>> vec_after_ransac=slic.getVector3();
vector<vector<Node>>::size_type size=vec.size();
vec_after_ransac.resize(size);
vector<vector<Node>>::iterator it;
vector<vector<Node>>::iterator it_;
vector<Node>::iterator it_contour;
// cout<<vec.size()<<endl;
//for each segment,we use the RANSAC algorithm to eliminate the outliers
for(it=vec.begin(),it_=vec_after_ransac.begin();it!=vec.end()&&it_!=vec_after_ransac.end();it++,it_++){
vector<Node>::iterator it2;
std::vector<double> planeParameters;
PlaneParamEstimator lpEstimator(0.5);
int numForEstimate = 3;
double usedData = Ransac<Node,double>::compute(planeParameters, &lpEstimator, *it, numForEstimate,*it_);
double resultA = planeParameters[0];
double resultB = planeParameters[1];
double resultC = planeParameters[2];
double resultX = planeParameters[3];
double resultY = planeParameters[4];
double resultZ = planeParameters[5];
std::cout<<"RANSAC plane parameters [A, B, C, X0, Y0, Z0]\n\t [ "<<planeParameters[0]<<", "<<planeParameters[1]<<", "
<<planeParameters[2]<<", "<<planeParameters[3]<<", "
<<planeParameters[4]<<", "<<planeParameters[5]<<", ";
std::cout<<"\tPercentage of points which were used for final estimate: "<<usedData<<std::endl;
}
//apply plane fitting algorithm to estimate a plane that represents the depth within this segment best
vector<vector<Node>>::iterator it_2;
vector<vector<Node>>::iterator it_3;
int num=0;
for(it_2=vec_after_ransac.begin(),it_3=vec.begin();it_2!=vec_after_ransac.end()&&it_3!=vec.end();it_2++,it_3++){
vector<Node>::iterator ite;
float A[3][3]={
{0.0,0.0,0.0},
{0.0,0.0,0.0},
{0.0,0.0,0.0}
};
float tx=0.0;
float ty=0.0;
float tz=0.0;
int cnt=0;
char numName[50];
sprintf_s(numName,"abc%.2d.txt",num);
ofstream os(numName);
for(ite=it_2->begin();ite!=it_2->end();ite++){
float xx=ite->getX();
float yy=ite->getY();
float zz=ite->getZ();
os<<xx<<" "<<yy<<" "<<zz<<" "<<endl;
tx+=xx;
ty+=yy;
tz+=zz;
cnt++;
}
os.close();
num++;
float tx2=tx/cnt;
float ty2=ty/cnt;
float tz2=tz/cnt;
float tx3=0.0;
float ty3=0.0;
float tz3=0.0;
for(ite=it_2->begin();ite!=it_2->end();ite++){
float xx=ite->getX();
float yy=ite->getY();
float zz=ite->getZ();
tx3=xx-tx2;
ty3=yy-ty2;
tz3=zz-tz2;
A[0][0]+=tx3*tx3;
A[0][1]+=tx3*ty3;
A[0][2]+=tx3*tz3;
A[1][0]+=tx3*ty3;
A[1][1]+=ty3*ty3;
A[1][2]+=ty3*tz3;
A[2][0]+=tx3*tz3;
A[2][1]+=ty3*tz3;
A[2][2]+=tz3*tz3;
}
Mat ma=Mat(3,3,CV_32FC1,A);
float B[3][3]={{0.0,0.0,0.0},
{0.0,0.0,0.0},
{0.0,0.0,0.0}};
Mat mb=Mat(3,3,CV_32FC1,B);
float C[3]={0.0,0.0,0.0};
Mat mc=Mat(3,1,CV_32FC1,C);
bool f=cv::eigen(ma,mc,mb);
cout<<mb.row(0)<<endl;
cout<<mb.row(1)<<endl;
cout<<mb.row(2)<<endl;
cout<<mc.at<float>(0,0)<<endl;
cout<<mc.at<float>(1,0)<<endl;
cout<<mc.at<float>(2,0)<<endl;
float a=0.0;
float b=0.0;
float c=0.0;
float dd=0.0;
float norm=0.0;
if(f){
a=mb.row(2).at<float>(0,0);
b=mb.row(2).at<float>(0,1);
c=mb.row(2).at<float>(0,2);
norm=sqrt(a*a+b*b+c*c);
a=a/norm;
b=b/norm;
c=c/norm;
dd=tx2*a+ty2*b+tz2*c;
for(ite=it_3->begin();ite!=it_3->end();ite++){
// for(ite=it_2->begin();ite!=it_2->end();ite++){
int x=ite->getX();
int y=ite->getY();
int z=depth.at<uchar>(y,x);
int temp_z=z;
if(c){
temp_z=saturate_cast<uchar>((dd-(a*x+b*y))/c);
//depth.at<uchar>(y,x)=temp_z;
}
if(abs(z-temp_z)>sigma){
depth2.at<uchar>(y,x)=temp_z;
}
}
}
}
cv::imwrite("C:/pic/final.png",depth2);
}
| [
"janestar92@163.com"
] | janestar92@163.com |
3ea163c358a0c8926ef0d71ce5c2e5730dc267ed | 1c444bdf16632d78a3801a7fe6b35c054c4cddde | /include/bds/bedrock/item/HatchetItem.h | c6add071d11cd1c6b5288f0a42bc55c346ae3f96 | [] | no_license | maksym-pasichnyk/symbols | 962a082bf6a692563402c87eb25e268e7e712c25 | 7673aa52391ce93540f0e65081f16cd11c2aa606 | refs/heads/master | 2022-04-11T03:17:18.078103 | 2020-03-15T11:30:36 | 2020-03-15T11:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | #pragma once
#include "DiggerItem.h"
#include <string>
#include "Item.h"
#include "../util/BlockPos.h"
class HatchetItem : public DiggerItem {
public:
~HatchetItem(); // _ZN11HatchetItemD2Ev
virtual void getEnchantSlot()const; // _ZNK11HatchetItem14getEnchantSlotEv
virtual void getDestroySpeed(ItemInstance const&, Block const&)const; // _ZNK11HatchetItem15getDestroySpeedERK12ItemInstanceRK5Block
virtual void _useOn(ItemStack &, Actor &, BlockPos, unsigned char, float, float, float)const; // _ZNK11HatchetItem6_useOnER9ItemStackR5Actor8BlockPoshfff
HatchetItem(std::string const&, int, Item::Tier const&); // _ZN11HatchetItemC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiRKN4Item4TierE
};
| [
"honzaxp01@gmail.com"
] | honzaxp01@gmail.com |
0079b811f95f97145931d1c824c07bc3c7abab11 | ac227cc22d5f5364e5d029a2cef83816a6954590 | /applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OptiX/Rendering_Materials/OPTIX_MATERIAL_FAST_SMOKE.h | 6e36b8dae217708e4dbf9669801973fc6ed948fb | [
"BSD-3-Clause"
] | permissive | schinmayee/nimbus | 597185bc8bac91a2480466cebc8b337f5d96bd2e | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | refs/heads/master | 2020-03-11T11:42:39.262834 | 2018-04-18T01:28:23 | 2018-04-18T01:28:23 | 129,976,755 | 0 | 0 | BSD-3-Clause | 2018-04-17T23:33:23 | 2018-04-17T23:33:23 | null | UTF-8 | C++ | false | false | 2,602 | h | //#####################################################################
// Copyright 2012, Bo Zhu
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class OPTIX_MATERIAL_FAST_SMOKE
//#####################################################################
#ifdef USE_OPTIX
#ifndef __OPTIX_MATERIAL_FAST_SMOKE__
#define __OPTIX_MATERIAL_FAST_SMOKE__
#include <PhysBAM_Tools/Vectors/VECTOR_3D.h>
#include <PhysBAM_Rendering/PhysBAM_OptiX/Rendering/OPTIX_RENDER_WORLD.h>
#include <PhysBAM_Rendering/PhysBAM_OptiX/Rendering_Materials/OPTIX_MATERIAL.h>
#include <PhysBAM_Rendering/PhysBAM_Optix/Rendering_Materials/OPTIX_TEXTURE.h>
#include <optix_world.h>
#include <optixu/optixpp_namespace.h>
namespace PhysBAM{
using namespace optix;
template<class T>
class OPTIX_MATERIAL_FAST_SMOKE:public OPTIX_MATERIAL<T>
{
typedef VECTOR<T,3> TV;typedef VECTOR<int,3> TV_INT;
public:
TV_INT size;
OPTIX_TEXTURE<T,1,3>* soot_texture;
OPTIX_MATERIAL_FAST_SMOKE(const TV_INT& size_input)
:OPTIX_MATERIAL<T>(false)/*smoke is not opaque*/,size(size_input),soot_texture(0),world(NULL){}
virtual Material getRTMaterial(){return rt_material;}
virtual void ensureInitialized(OPTIX_RENDER_WORLD<T> *world_input)
{
if (world&&world_input==world)return;
PHYSBAM_ASSERT(world==NULL);world=world_input;
Context rt_context=world->RTContext();
Program closest_hit_program;
Program closest_hit_program_shadow;
std::string path_to_ptx;
path_to_ptx=world_input->shader_prefix+"_generated_OPTIX_PARTICIPATING_MEDIA.cu.ptx";
closest_hit_program=rt_context->createProgramFromPTXFile(path_to_ptx,"closest_hit_radiance_smoke");
closest_hit_program_shadow=rt_context->createProgramFromPTXFile(path_to_ptx,"closest_hit_shadow_smoke");
rt_material=rt_context->createMaterial();
rt_material->setClosestHitProgram(world->RAY_TYPE_RADIANCE,closest_hit_program);
rt_material->setClosestHitProgram(world->RAY_TYPE_SHADOW,closest_hit_program_shadow);
soot_texture=new OPTIX_TEXTURE<T,1,3>("soot_texture",rt_context,size);
}
void Update_Texture_From_File(const std::string& soot_file)
{
soot_texture->Read_From_File(soot_file.c_str());
}
void Update_Texture_From_Data(const T* data)
{
soot_texture->Copy_From(data);
}
private:
OPTIX_RENDER_WORLD<T>* world;
Material rt_material;
};
}
#endif
#endif | [
"quhang@stanford.edu"
] | quhang@stanford.edu |
c9f7d672afcbc801c45b3a529c158b852e0220ef | 675dde2b1ece857cc5bc0e3cca9f1346bdc6c7ea | /tsf/include/tencentcloud/tsf/v20180326/model/DescribeGroupsRequest.h | 8b884910436b89de33ce3f0193ec60f2861d9509 | [
"Apache-2.0"
] | permissive | jackrambor/tencentcloud-sdk-cpp | 7ec86b31df6a9d37c3966b136a14691c2088bf55 | 71ce9e62893f8d3110c20e051897f55137ea4699 | refs/heads/master | 2020-06-25T18:44:19.397792 | 2019-07-29T03:34:29 | 2019-07-29T03:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,918 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_TSF_V20180326_MODEL_DESCRIBEGROUPSREQUEST_H_
#define TENCENTCLOUD_TSF_V20180326_MODEL_DESCRIBEGROUPSREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tsf
{
namespace V20180326
{
namespace Model
{
/**
* DescribeGroups请求参数结构体
*/
class DescribeGroupsRequest : public AbstractModel
{
public:
DescribeGroupsRequest();
~DescribeGroupsRequest() = default;
std::string ToJsonString() const;
/**
* 获取搜索字段
* @return SearchWord 搜索字段
*/
std::string GetSearchWord() const;
/**
* 设置搜索字段
* @param SearchWord 搜索字段
*/
void SetSearchWord(const std::string& _searchWord);
/**
* 判断参数 SearchWord 是否已赋值
* @return SearchWord 是否已赋值
*/
bool SearchWordHasBeenSet() const;
/**
* 获取应用ID
* @return ApplicationId 应用ID
*/
std::string GetApplicationId() const;
/**
* 设置应用ID
* @param ApplicationId 应用ID
*/
void SetApplicationId(const std::string& _applicationId);
/**
* 判断参数 ApplicationId 是否已赋值
* @return ApplicationId 是否已赋值
*/
bool ApplicationIdHasBeenSet() const;
/**
* 获取排序字段
* @return OrderBy 排序字段
*/
std::string GetOrderBy() const;
/**
* 设置排序字段
* @param OrderBy 排序字段
*/
void SetOrderBy(const std::string& _orderBy);
/**
* 判断参数 OrderBy 是否已赋值
* @return OrderBy 是否已赋值
*/
bool OrderByHasBeenSet() const;
/**
* 获取排序方式
* @return OrderType 排序方式
*/
int64_t GetOrderType() const;
/**
* 设置排序方式
* @param OrderType 排序方式
*/
void SetOrderType(const int64_t& _orderType);
/**
* 判断参数 OrderType 是否已赋值
* @return OrderType 是否已赋值
*/
bool OrderTypeHasBeenSet() const;
/**
* 获取偏移量
* @return Offset 偏移量
*/
int64_t GetOffset() const;
/**
* 设置偏移量
* @param Offset 偏移量
*/
void SetOffset(const int64_t& _offset);
/**
* 判断参数 Offset 是否已赋值
* @return Offset 是否已赋值
*/
bool OffsetHasBeenSet() const;
/**
* 获取分页个数
* @return Limit 分页个数
*/
int64_t GetLimit() const;
/**
* 设置分页个数
* @param Limit 分页个数
*/
void SetLimit(const int64_t& _limit);
/**
* 判断参数 Limit 是否已赋值
* @return Limit 是否已赋值
*/
bool LimitHasBeenSet() const;
/**
* 获取命名空间ID
* @return NamespaceId 命名空间ID
*/
std::string GetNamespaceId() const;
/**
* 设置命名空间ID
* @param NamespaceId 命名空间ID
*/
void SetNamespaceId(const std::string& _namespaceId);
/**
* 判断参数 NamespaceId 是否已赋值
* @return NamespaceId 是否已赋值
*/
bool NamespaceIdHasBeenSet() const;
/**
* 获取集群ID
* @return ClusterId 集群ID
*/
std::string GetClusterId() const;
/**
* 设置集群ID
* @param ClusterId 集群ID
*/
void SetClusterId(const std::string& _clusterId);
/**
* 判断参数 ClusterId 是否已赋值
* @return ClusterId 是否已赋值
*/
bool ClusterIdHasBeenSet() const;
private:
/**
* 搜索字段
*/
std::string m_searchWord;
bool m_searchWordHasBeenSet;
/**
* 应用ID
*/
std::string m_applicationId;
bool m_applicationIdHasBeenSet;
/**
* 排序字段
*/
std::string m_orderBy;
bool m_orderByHasBeenSet;
/**
* 排序方式
*/
int64_t m_orderType;
bool m_orderTypeHasBeenSet;
/**
* 偏移量
*/
int64_t m_offset;
bool m_offsetHasBeenSet;
/**
* 分页个数
*/
int64_t m_limit;
bool m_limitHasBeenSet;
/**
* 命名空间ID
*/
std::string m_namespaceId;
bool m_namespaceIdHasBeenSet;
/**
* 集群ID
*/
std::string m_clusterId;
bool m_clusterIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TSF_V20180326_MODEL_DESCRIBEGROUPSREQUEST_H_
| [
"zhiqiangfan@tencent.com"
] | zhiqiangfan@tencent.com |
af92060d77e8cf84e1b5945e9d3b1f33cab439ef | db3033246bb9edc514d19e0c604e5cc7c41ff6e3 | /week3/杨帆/搜索回溯/4-3.cpp | f7346df99ff167744270fd55e17c7216ba9b2430 | [] | no_license | 1525125249/NEUQ-ACM-Solution | 2945a96659ccc5b5294a358564291c758feffce9 | f651574880b6974b12e5dbc28f78d9bf4c1694b3 | refs/heads/main | 2023-08-27T17:56:56.052183 | 2021-11-07T05:14:30 | 2021-11-07T05:14:30 | 425,413,832 | 0 | 0 | null | 2021-11-07T04:40:57 | 2021-11-07T04:40:57 | null | UTF-8 | C++ | false | false | 2,029 | cpp | #include<bits/stdc++.h>
using namespace std;
int n,m,k,l,site[50][50],boom[50][50],book[50][50];
bool check(){
int sum=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
if(site[i][j]==-1)
sum++;
}
if(sum==k) return true;
return false;
}
void bfs(int x,int y){
queue<pair<int,int> >que;
que.push({x,y});
book[x][y]=1;
int kx[8]={1,1,1,0,0,-1,-1,-1};
int ky[8]={-1,0,1,-1,1,-1,0,1};
while(!que.empty()){
int dx=que.front().first;
int dy=que.front().second;
que.pop();
int num=0;
for(int i=0;i<8;i++){
int dxx=dx+kx[i];
int dyy=dy+ky[i];
if(dxx>=0&&dyy>=0&&dxx<n&&dyy<m){
if(boom[dxx][dyy]==1) num++;
}
}
if(num!=0) site[dx][dy]=num;
else{
site[dx][dy]=0;
for(int i=0;i<8;i++){
int dxx=dx+kx[i];
int dyy=dy+ky[i];
if(dxx>=0&&dyy>=0&&dxx<n&&dyy<m&&book[dxx][dyy]==0){
book[dxx][dyy]=1;
site[dxx][dyy]=0;
que.push({dxx,dyy});
}
}
}
}
}
int main(){
cin>>n>>m>>k>>l;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
site[i][j]=-1;
}
for(int i=1;i<=k;i++){
int a,b;
cin>>a>>b;
boom[a][b]=1;
}
while(l--){
int a,b;
cin>>a>>b;
if(boom[a][b]==1){
cout<<"You lose";
return 0;
}
else if(book[a][b]==1) continue;
else{
bfs(a,b);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<site[i][j]<<" ";
}
cout<<"\n";
}
if(check()){
cout<<"You win";
return 0;
}
else cout<<"\n";
}
}
return 0;
}
| [
"yf040513@126.com"
] | yf040513@126.com |
00ab5be5054c7b5f369f1e4d3c356dece8994c17 | 974749492500560d2d29fb89b305a7c2966011a5 | /build-NFC_monitoring-Desktop_Qt_5_10_1_MinGW_32bit-Debug/ui_mainwindow.h | 19ca7f2925c7b16d914936100cdb5beb31585fd6 | [] | no_license | holmes-asava/NFC | 78d226603ed900301c7df62706ffcdc89d191dc0 | 54f12107dbef29ec1f18932c8891e28367bfa3d4 | refs/heads/master | 2021-09-16T13:50:59.706405 | 2018-06-21T09:57:49 | 2018-06-21T09:57:49 | 135,673,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,414 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.10.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QWidget>
#include "qcustomplot.h"
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QCustomPlot *widget;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(611, 551);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
widget = new QCustomPlot(centralWidget);
widget->setObjectName(QStringLiteral("widget"));
widget->setGeometry(QRect(170, 250, 211, 171));
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 611, 26));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"homer.asava@gmail.com"
] | homer.asava@gmail.com |
a1b146dcac56dead1134a7bb8bc0202d1b4daef7 | e24a981d22dc9f08eaead51792f5933d359f003d | /contrib/sdk/sources/Mesa/mesa-10.6.0/src/glsl/tests/uniform_initializer_utils.cpp | b90bdcaed3b3e31a67ed9c1972f2a7a25aa68ddd | [] | no_license | Harmon758/kolibrios | d6001876fefb006ea65e5fe3810b26606e33284e | 0d615a7c442e8974f58b7260b094c1212c618bcf | refs/heads/master | 2023-08-20T11:47:59.999028 | 2023-08-20T10:40:03 | 2023-08-20T10:40:03 | 66,638,292 | 32 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,625 | cpp | /*
* Copyright © 2012 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <gtest/gtest.h>
#include "main/mtypes.h"
#include "main/macros.h"
#include "util/ralloc.h"
#include "uniform_initializer_utils.h"
#include <stdio.h>
void
fill_storage_array_with_sentinels(gl_constant_value *storage,
unsigned data_size,
unsigned red_zone_size)
{
for (unsigned i = 0; i < data_size; i++)
storage[i].u = 0xDEADBEEF;
for (unsigned i = 0; i < red_zone_size; i++)
storage[data_size + i].u = 0xBADDC0DE;
}
/**
* Verfiy that markers past the end of the real uniform are unmodified
*/
static ::testing::AssertionResult
red_zone_is_intact(gl_constant_value *storage,
unsigned data_size,
unsigned red_zone_size)
{
for (unsigned i = 0; i < red_zone_size; i++) {
const unsigned idx = data_size + i;
if (storage[idx].u != 0xBADDC0DE)
return ::testing::AssertionFailure()
<< "storage[" << idx << "].u = " << storage[idx].u
<< ", exepected data values = " << data_size
<< ", red-zone size = " << red_zone_size;
}
return ::testing::AssertionSuccess();
}
static const int values[] = {
2, 0, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
};
/**
* Generate a single data element.
*
* This is by both \c generate_data and \c generate_array_data to create the
* data.
*/
static void
generate_data_element(void *mem_ctx, const glsl_type *type,
ir_constant *&val, unsigned data_index_base)
{
/* Set the initial data values for the generated constant.
*/
ir_constant_data data;
memset(&data, 0, sizeof(data));
for (unsigned i = 0; i < type->components(); i++) {
const unsigned idx = (i + data_index_base) % ARRAY_SIZE(values);
switch (type->base_type) {
case GLSL_TYPE_UINT:
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
case GLSL_TYPE_IMAGE:
data.i[i] = values[idx];
break;
case GLSL_TYPE_FLOAT:
data.f[i] = float(values[idx]);
break;
case GLSL_TYPE_BOOL:
data.b[i] = bool(values[idx]);
break;
case GLSL_TYPE_DOUBLE:
data.d[i] = double(values[idx]);
break;
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_VOID:
case GLSL_TYPE_ERROR:
case GLSL_TYPE_INTERFACE:
ASSERT_TRUE(false);
break;
}
}
/* Generate and verify the constant.
*/
val = new(mem_ctx) ir_constant(type, &data);
for (unsigned i = 0; i < type->components(); i++) {
switch (type->base_type) {
case GLSL_TYPE_UINT:
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
case GLSL_TYPE_IMAGE:
ASSERT_EQ(data.i[i], val->value.i[i]);
break;
case GLSL_TYPE_FLOAT:
ASSERT_EQ(data.f[i], val->value.f[i]);
break;
case GLSL_TYPE_BOOL:
ASSERT_EQ(data.b[i], val->value.b[i]);
break;
case GLSL_TYPE_DOUBLE:
ASSERT_EQ(data.d[i], val->value.d[i]);
break;
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_VOID:
case GLSL_TYPE_ERROR:
case GLSL_TYPE_INTERFACE:
ASSERT_TRUE(false);
break;
}
}
}
void
generate_data(void *mem_ctx, enum glsl_base_type base_type,
unsigned columns, unsigned rows,
ir_constant *&val)
{
/* Determine what the type of the generated constant should be.
*/
const glsl_type *const type =
glsl_type::get_instance(base_type, rows, columns);
ASSERT_FALSE(type->is_error());
generate_data_element(mem_ctx, type, val, 0);
}
void
generate_array_data(void *mem_ctx, enum glsl_base_type base_type,
unsigned columns, unsigned rows, unsigned array_size,
ir_constant *&val)
{
/* Determine what the type of the generated constant should be.
*/
const glsl_type *const element_type =
glsl_type::get_instance(base_type, rows, columns);
ASSERT_FALSE(element_type->is_error());
const glsl_type *const array_type =
glsl_type::get_array_instance(element_type, array_size);
ASSERT_FALSE(array_type->is_error());
/* Set the initial data values for the generated constant.
*/
exec_list values_for_array;
for (unsigned i = 0; i < array_size; i++) {
ir_constant *element;
generate_data_element(mem_ctx, element_type, element, i);
values_for_array.push_tail(element);
}
val = new(mem_ctx) ir_constant(array_type, &values_for_array);
}
/**
* Verify that the data stored for the uniform matches the initializer
*
* \param storage Backing storage for the uniform
* \param storage_array_size Array size of the backing storage. This must be
* less than or equal to the array size of the type
* of \c val. If \c val is not an array, this must
* be zero.
* \param val Value of the initializer for the unifrom.
* \param red_zone
*/
void
verify_data(gl_constant_value *storage, unsigned storage_array_size,
ir_constant *val, unsigned red_zone_size,
unsigned int boolean_true)
{
if (val->type->base_type == GLSL_TYPE_ARRAY) {
const glsl_type *const element_type = val->array_elements[0]->type;
for (unsigned i = 0; i < storage_array_size; i++) {
verify_data(storage + (i * element_type->components()), 0,
val->array_elements[i], 0, boolean_true);
}
const unsigned components = element_type->components();
if (red_zone_size > 0) {
EXPECT_TRUE(red_zone_is_intact(storage,
storage_array_size * components,
red_zone_size));
}
} else {
ASSERT_EQ(0u, storage_array_size);
for (unsigned i = 0; i < val->type->components(); i++) {
switch (val->type->base_type) {
case GLSL_TYPE_UINT:
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
case GLSL_TYPE_IMAGE:
EXPECT_EQ(val->value.i[i], storage[i].i);
break;
case GLSL_TYPE_FLOAT:
EXPECT_EQ(val->value.f[i], storage[i].f);
break;
case GLSL_TYPE_BOOL:
EXPECT_EQ(val->value.b[i] ? boolean_true : 0, storage[i].i);
break;
case GLSL_TYPE_DOUBLE:
EXPECT_EQ(val->value.d[i], *(double *)&storage[i*2].i);
break;
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_VOID:
case GLSL_TYPE_ERROR:
case GLSL_TYPE_INTERFACE:
ASSERT_TRUE(false);
break;
}
}
if (red_zone_size > 0) {
EXPECT_TRUE(red_zone_is_intact(storage,
val->type->components(),
red_zone_size));
}
}
}
| [
"serge@a494cfbc-eb01-0410-851d-a64ba20cac60"
] | serge@a494cfbc-eb01-0410-851d-a64ba20cac60 |
323fb5f8a3054630c72fad20bbcb03311a3a09e9 | 70204b7306a4dd6603966eadb618a202b3ad698b | /sources/Leetcodes/src/20_valid_parentheses.cpp | 85649ec758112bd123290d6c371f0e6ca1a8387a | [
"MIT"
] | permissive | mcoder2014/myNotes | 3a9f0ff1aec9594547efee51ee8058a9c1feae75 | 443cf16b1873bb473b7cb6bc1a6ec9c6423333e7 | refs/heads/master | 2023-02-05T17:07:05.991032 | 2020-12-24T07:27:44 | 2020-12-24T07:27:44 | 209,985,750 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include <iostream>
#include <string>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> chs;
unordered_map<char,char> map{{'}','{'}, {']','['},{')','('}};
for(char ch:s)
{
if(ch == ')' || ch ==']' || ch=='}')
{
if(chs.size() == 0)
return false;
char pair = chs.top();
chs.pop();
if(map[ch] != pair)
return false;
}
else
{
chs.push(ch);
}
}
if(chs.size()==0)
return true;
else
return false;
}
};
int main()
{
return 0;
}
| [
"mcoder2014@sina.com"
] | mcoder2014@sina.com |
12ffb7d3508d4fec17d8ef8a3679df0823433149 | 1890b475dc4e7b856f973252080814b14bb52d57 | /aws/v7.1/Samples/netds/adsi/general/adqi/ADQIDlg.cpp | e93abd6a66b4cee0564f86f9d0a5cc9430ce067e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | nfouka/InnoSetup5 | 065629007b00af7c14ae9b202011e12b46eea257 | df39fc74995a6955d2d8ee12feed9cff9e5c37db | refs/heads/master | 2020-04-20T02:51:58.072759 | 2019-01-31T21:53:45 | 2019-01-31T21:53:45 | 168,582,148 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,986 | cpp | //----------------------------------------------------------------------------
//
// Microsoft Active Directory 2.5 Sample Code
//
// Copyright (C) Microsoft Corporation, 1996 - 2000
//
// File: ADQIDlg.cpp
//
// Contents: Main ADQI User Interface Implementation
//
//
//----------------------------------------------------------------------------
#include "stdafx.h"
#include "ADQI.h"
#include "ADQIDlg.h"
#include "lmcons.h"
#include "ads.h"
#include "adscontainer.h"
#include "directorysearch.h"
#include "directoryobject.h"
#include "adspropertylist.h"
#include "adsopendsobject.h"
#include "adslargeinteger.h"
#include "security.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
DECLAREADSPROC(IADs)
DECLAREADSPROC(IADsContainer)
DECLAREADSPROC(IDirectorySearch)
DECLAREADSPROC(IDirectoryObject)
DECLAREADSPROC(IADsPropertyList)
DECLAREADSPROC(IADsSecurityDescriptor)
DECLAREADSPROC(IADsLargeInteger)
ADSIIF adsiIfs[] = {
MAKEADSENTRY(IADs), DlgProcIADs,
MAKEADSENTRY(IADsContainer), DlgProcIADsContainer,
MAKEADSENTRY(IADsCollection), NULL,
MAKEADSENTRY(IADsMembers), NULL,
MAKEADSENTRY(IADsPropertyList), DlgProcIADsPropertyList,
MAKEADSENTRY(IADsPropertyEntry), NULL,
MAKEADSENTRY(IADsPropertyValue), NULL,
MAKEADSENTRY(IADsExtension), NULL,
MAKEADSENTRY(IADsNamespaces), NULL,
MAKEADSENTRY(IADsClass), NULL,
MAKEADSENTRY(IADsProperty), NULL,
MAKEADSENTRY(IADsSyntax), NULL,
MAKEADSENTRY(IADsLocality), NULL,
MAKEADSENTRY(IADsO), NULL,
MAKEADSENTRY(IADsOU), NULL,
MAKEADSENTRY(IADsDomain), NULL,
MAKEADSENTRY(IADsComputer), NULL,
MAKEADSENTRY(IADsComputerOperations), NULL,
MAKEADSENTRY(IADsGroup), NULL,
MAKEADSENTRY(IADsUser), NULL,
MAKEADSENTRY(IADsPrintQueue), NULL,
MAKEADSENTRY(IADsPrintQueueOperations), NULL,
MAKEADSENTRY(IADsPrintJob), NULL,
MAKEADSENTRY(IADsPrintJobOperations), NULL,
MAKEADSENTRY(IADsService), NULL,
MAKEADSENTRY(IADsServiceOperations), NULL,
MAKEADSENTRY(IADsFileService), NULL,
MAKEADSENTRY(IADsFileServiceOperations), NULL,
MAKEADSENTRY(IADsFileShare), NULL,
MAKEADSENTRY(IADsSession), NULL,
MAKEADSENTRY(IADsResource), NULL,
MAKEADSENTRY(IADsOpenDSObject), DlgProcIADsOpenDSObject,
MAKEADSENTRY(IDirectoryObject), DlgProcIDirectoryObject,
MAKEADSENTRY(IDirectorySearch), DlgProcIDirectorySearch,
MAKEADSENTRY(IADsAccessControlEntry), NULL,
MAKEADSENTRY(IADsSecurityDescriptor), DlgProcIADsSecurityDescriptor,
MAKEADSENTRY(IADsLargeInteger), DlgProcIADsLargeInteger,
MAKEADSENTRY(IADsObjectOptions), NULL,
MAKEADSENTRY(IADsPropertyValue2), NULL,
//The following interfaces is CoCreateable, not living off on any object,
//so we comment this out, because QI won't return any of these interfaces
// MAKEADSENTRY(IADsPathname), NULL,
// MAKEADSENTRY(IADsNameTranslate), NULL,
MAKEADSENTRY(NULL), NULL
};
/////////////////////////////////////////////////////////////////////////////
// CADQIDlg dialog
CADQIDlg::CADQIDlg(CWnd* pParent /*=NULL*/)
: CDialog(CADQIDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CADQIDlg)
m_sADsPath = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_pUnk = NULL;
}
void CADQIDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CADQIDlg)
DDX_Control(pDX, IDC_INTERFACES, m_cListIf);
DDX_Control(pDX, IDOK, m_cOK);
DDX_Control(pDX, IDC_ADSPATH, m_cADsPath);
DDX_Text(pDX, IDC_ADSPATH, m_sADsPath);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CADQIDlg, CDialog)
//{{AFX_MSG_MAP(CADQIDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_EN_CHANGE(IDC_ADSPATH, OnChangeADsPath)
ON_LBN_DBLCLK(IDC_INTERFACES, OnDblClkInterfaces)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CADQIDlg message handlers
BOOL CADQIDlg::OnInitDialog()
{
CDialog::OnInitDialog();
OnChangeADsPath();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CADQIDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CADQIDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CADQIDlg::OnOK()
{
HRESULT hr;
CWaitCursor wait;
IUnknown *pSave = NULL;
UpdateData( TRUE );
if ( m_pUnk )
{
pSave = m_pUnk; // save it first
}
USES_CONVERSION;
hr = App->ADsOpenObject(T2OLE(m_sADsPath), IID_IUnknown, (void**) &m_pUnk );
if ( !SUCCEEDED(hr) )
{
AfxMessageBox(GetErrorMessage(hr));
m_pUnk = NULL;
return;
}
if ( pSave ) // release the previous pointer
{
pSave->Release();
}
EnumerateInterface();
}
void CADQIDlg::OnChangeADsPath()
{
BOOL bEnabled;
bEnabled = m_cADsPath.GetWindowTextLength() > 0 ? TRUE : FALSE;
m_cOK.EnableWindow( bEnabled );
}
void CADQIDlg::OnCancel()
{
CDialog::OnCancel();
}
void CADQIDlg::EnumerateInterface()
{
int xx=0;
HRESULT hr;
LPUNKNOWN pQI;
m_cListIf.ResetContent();
///////////////////////////////////////////////////////////////
// Query Interface all known ADSI Interfaces
////////////////////////////////////////////////////////////////
while( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) )
{
hr = m_pUnk->QueryInterface( *adsiIfs[xx].pIID, (void**) &pQI );
if ( SUCCEEDED(hr) )
{
m_cListIf.AddString( adsiIfs[xx].szIf );
pQI->Release();
}
xx++;
}
}
void CADQIDlg::OnDblClkInterfaces()
{
CString s;
int xx=0;
int idx;
IUnknown *pNewUnk = NULL;
idx = m_cListIf.GetCurSel();
if ( idx == LB_ERR )
{
MessageBeep(0);
return;
}
CWaitCursor wait;
m_cListIf.GetText( idx, s );
//////////////////////////////////////////////////////////////
//
// Find the appropriate dialog box to display
//
/////////////////////////////////////////////////////////////////
while( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) && s != adsiIfs[xx].szIf )
{
xx++;
}
ASSERT( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) );
if ( adsiIfs[xx].pFn )
{
m_pUnk->AddRef();
(*adsiIfs[xx].pFn)( m_pUnk, &pNewUnk );
}
else
{
wait.Restore();
AfxMessageBox(_T("No UI implemented yet"));
}
////////////////////////////////////////////////////
// if IADsOpenObject is selected, special care
///////////////////////////////////////////////////
if ( pNewUnk )
{
HRESULT hr;
BSTR bstr;
IADs *pADs;
hr = pNewUnk->QueryInterface( IID_IADs, (void**) &pADs );
if ( SUCCEEDED(hr) )
{
pADs->get_ADsPath( &bstr );
}
pADs->Release();
m_sADsPath = bstr;
SysFreeString( bstr );
m_pUnk->Release(); // old ads iunknown path;
m_pUnk = pNewUnk;
UpdateData(FALSE);
EnumerateInterface();
}
}
| [
"nadir.foukagmail.com"
] | nadir.foukagmail.com |
2d4eb62c1ba634f280482a68cd8b9500ca431470 | db286309dfc5aa629af1ffdb7ad21b3b8b78c888 | /CPP/56.cpp | ee2b03f25b3160eb07c2d1633fb0c97114892040 | [] | no_license | Prachi-2001/450-Important-Interview-Question-all-languages- | a147dfa8eef7043f77dce498b79e04f60ee9a157 | ff8cf1a5ba6cc301a740cc6b4494ecb98b6f759f | refs/heads/main | 2023-08-28T11:18:19.877106 | 2021-10-21T10:57:50 | 2021-10-21T10:57:50 | 417,231,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | // Question name- Reverse a string
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define f(i,a,b) for(ll i=a;i<b;i++)
void reverse_string(string &s){
ll n=s.length();
f(i,0,n/2){
char t=s[i];
s[i]=s[n-i-1];
s[n-i-1]=t;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
string s;
cin>>s;
reverse_string(s);
cout<<s;
}
| [
"noreply@github.com"
] | Prachi-2001.noreply@github.com |
2d777a9c9cd9b8b96c916af83ffa45773feb568c | 70fe255d0a301952a023be5e1c1fefd062d1e804 | /LeetCode/231.cpp | be80f148c321688c22ab9c02fb5908ca8157df9f | [
"MIT"
] | permissive | LauZyHou/Algorithm-To-Practice | 524d4318032467a975cf548d0c824098d63cca59 | 66c047fe68409c73a077eae561cf82b081cf8e45 | refs/heads/master | 2021-06-18T01:48:43.378355 | 2021-01-27T14:44:14 | 2021-01-27T14:44:14 | 147,997,740 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 183 | cpp | class Solution {
public:
bool isPowerOfTwo(int n) {
bool find=false;
if(!n)
return false;
while(n && !find){
if(n&1)
find=true;
n>>=1;
}
return !n;
}
}; | [
"java233@foxmail.com"
] | java233@foxmail.com |
fd053b21cc0e4a18c92721f7f4af4e5b36f46785 | 33f1f83a838b7f0f0fc85d858e888bce3d238e50 | /desk.cpp | b2d3d58c15acb1ba862e4fcca5f7d62bfc58fb34 | [] | no_license | Slezkin/tasktree | b8c043cb0820f460d2b9df2c70445aa10bfb4a44 | 7da671e71f3ed3b452a54116e9116d898cf2c2f5 | refs/heads/master | 2021-05-15T09:36:03.511131 | 2017-11-14T06:28:03 | 2017-11-14T06:28:03 | 108,161,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include "desk.h"
#include "ui_desk.h"
desk::desk(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::desk)
{
ui->setupUi(this);
}
desk::~desk()
{
delete ui;
}
| [
"slezkin@live.ru"
] | slezkin@live.ru |
ba8655748236d39422d495df113dc769a9dd59ab | 15cb8f2568ad75d32f83bcea0336e76921a940f9 | /src/patrol/src/warehouse_action.cpp | 2eed569f4784cc90ebafdbef9f2bfae3b31a1d91 | [] | no_license | alvis1029/patrol | 798642b33f319f100b5d4f39d56ca824c34d395b | 9d306d0df84d2eabd28f8831e1be540b1cf9d703 | refs/heads/master | 2023-07-15T12:48:46.565442 | 2021-08-26T08:33:43 | 2021-08-26T08:33:43 | 358,222,396 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 53,262 | cpp | #include <iostream>
#include <time.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
//ROS
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Int8.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Pose.h>
#include <moveit/move_group_interface/move_group_interface.h>
#include <tf/tf.h>
#include <tf/LinearMath/Matrix3x3.h>
#include <tf/LinearMath/Vector3.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
// Custom msg & srv
#include <detection_msgs/Detection2DTrig.h>
#include <detection_msgs/Det3D.h>
#include <detection_msgs/Det3DArray.h>
#include <detection_msgs/StringArray.h>
using namespace std;
class warehouse_action
{
private:
std_msgs::Bool grip;
const string PLANNING_GROUP = "tm_arm";
char command;
const vector<double> home_p = {-M_PI_2, -M_PI_4, M_PI*2/3, -1.309, M_PI, 0.000};
const vector<double> home_p_2 = {-M_PI_2, -M_PI_4, M_PI*2/3, -1.309, M_PI_2, 0.000};
const vector<double> home_r = {M_PI, M_PI/3, -M_PI_4*3, 1.309, -M_PI_2, 0.0};
const vector<double> middle1_a = {-M_PI, -M_PI_4, M_PI*2/3, -1.309, M_PI, 0.000};
const vector<double> middle1_b = {-2.552, -0.527, 2.218, -1.679, 1.009, 0.000};
const vector<double> middle2_a = {0, -M_PI_4, M_PI*2/3, -1.309, M_PI, 0.000};
const vector<double> middle2_b = {3.344, -1.023, 2.259, -1.218, 1.285, 0.000};
const vector<double> middler_p = {M_PI_2, -M_PI/3, M_PI_4*3, -1.309, -M_PI_2, 0.0};
const vector<double> middlep_r = {0.000, 0.000, 0.000, 0.000, -M_PI_2, 0.0};
const vector<double> position_s = {0, M_PI/3, -M_PI_4*3, 1.309, 0.000, 0.000}; //M_PI_4*3
const vector<double> joint_sh_scan = {-M_PI_2, -M_PI_4, M_PI*2/3, -1.309, 2.800, 0.000};
// const vector<double> joint_wh_scan3 = {-0.305, 0.485, 1.635, -1.953, 0.293, 0.160};
// const vector<double> joint_wh_scan2 = {-0.772, -0.048, 2.320, -2.200, 0.758, 0.056};
// const vector<double> joint_wh_scan1 = {-1.564, 0.014, 2.261, -2.227, 1.549, 0.003};
const vector<double> joint_wh_scan2 = {-0.362, 0.002, 2.369, -2.270, 0.350, 0.133};
const vector<double> joint_wh_scan1 = {-1.564, -0.518, 2.621, -2.082, M_PI_2, 0.000};
const vector<double> joint_place1 = {-3.133, 0.180, 2.279, -2.450, 1.545, 0.000};
const vector<double> joint_place1_mid = {-3.133, -0.282, 2.255, -2.234, 1.547, 0.002};
const vector<double> joint_place2 = {-2.583, 0.183, 2.462, -2.644, 1.019, 0.000};
const vector<double> joint_place2_mid = {-2.822, -0.355, 2.231, -2.045, 1.473, 0.016};
const vector<double> joint_place3 = {-0.020, 0.269, -1.979, -1.416, 1.551, 3.130};
const vector<double> joint_place3_mid = {-0.028, 0.410, -1.616, -1.813, 1.544, 3.041};
const vector<double> joint_place4 = {3.181, -0.120,2.709, -2.586, 1.454, 0.034};
const vector<double> joint_place4_mid = {3.344, -1.023, 2.259, -1.218, 1.285, 0.028};
const vector<double> joint_place5 = {0.012, 0.647, -2.194, -1.579, 1.552, 3.040};
const vector<double> joint_place5_mid = {0.002, 0.755, -1.787, -2.089, 1.533, 3.035};
const vector<double> joint_place_tag = {-1.558, -0.568, 2.070, -1.501, 1.555, 0.000};
float *x_tmp, *y_tmp, *z_tmp;
int count = 0, target_amount = 0, target_number = 0;
bool find = false, grab = false, collect = false, reach = false;
std_msgs::Int8 replacement_finished;
detection_msgs::Det3DArray target_bias;
detection_msgs::Det3D bias;
public:
warehouse_action(ros::NodeHandle nh);
void det_callback(detection_msgs::Det3DArray msg);
void mis_callback(detection_msgs::StringArray msg);
void loc_callback(std_msgs::Int8 msg);
void Position_Manager();
ros::Publisher gripper_pub;
ros::Publisher mis_pub;
ros::Publisher prod_pub;
ros::Publisher replace_finish_pub;
ros::Subscriber det_sub;
ros::Subscriber mis_sub;
ros::Subscriber loc_sub;
geometry_msgs::Pose current_pose, tag_pose;
detection_msgs::StringArray mis_list, sa, prod_list;
};
warehouse_action::warehouse_action(ros::NodeHandle nh)
{
ros::AsyncSpinner spinner(1);
spinner.start();
x_tmp = new float[10] ();
y_tmp = new float[10] ();
z_tmp = new float[10] ();
gripper_pub = nh.advertise<std_msgs::Bool>("/gripper/cmd_gripper", 1);
prod_pub = nh.advertise<detection_msgs::StringArray>("/product/information", 1);
replace_finish_pub = nh.advertise<std_msgs::Int8>("/replacement_finished", 1);
mis_sub = nh.subscribe("/missing_bottle", 1, &warehouse_action::mis_callback, this);
mis_pub = nh.advertise<detection_msgs::StringArray>("/missing_bottle", 1);
string s;
s = "Soda";
sa.strings.push_back(s);
s = "MineralWater";
sa.strings.push_back(s);
s = "PinkSoda";
sa.strings.push_back(s);
mis_pub.publish(sa);
replacement_finished.data = 0;
replace_finish_pub.publish(replacement_finished);
loc_sub = nh.subscribe("/mob_plat/location", 1, &warehouse_action::loc_callback, this);
det_sub = nh.subscribe("/scan_clustering_node/det3d_result", 1, &warehouse_action::det_callback, this);
Position_Manager();
}
void warehouse_action::det_callback(detection_msgs::Det3DArray msg)
{
if(msg.dets_list.size() != 0 && reach)
find = true;
else
find = false;
if(find && !collect)
{
target_bias.dets_list.clear();
while(count < 10)
{
for(int i=0; i<msg.dets_list.size(); i++)
{
x_tmp[i] += msg.dets_list[i].x;
y_tmp[i] += msg.dets_list[i].y;
z_tmp[i] += msg.dets_list[i].z;
}
count++;
}
count = 0;
for(int i=0; i<msg.dets_list.size(); i++)
{
for(int j=0; j<mis_list.strings.size(); j++)
{
if(mis_list.strings[j] == msg.dets_list[i].class_name)
{
bias.class_name = msg.dets_list[i].class_name;
cout<<bias.class_name<<endl;
bias.class_id = msg.dets_list[i].class_id;
bias.x = x_tmp[i]/10;
bias.y = y_tmp[i]/10;
bias.z = z_tmp[i]/10;
x_tmp[i] = 0;
y_tmp[i] = 0;
z_tmp[i] = 0;
target_bias.dets_list.push_back(bias);
}
}
}
collect = true;
}
if(collect)
{
target_amount = target_bias.dets_list.size();
for(int i=0; i<target_bias.dets_list.size(); i++)
{
static tf::TransformBroadcaster br;
tf::Transform tf1;
string tf_name1 = "tm_target_pose";
tf1.setOrigin(tf::Vector3(target_bias.dets_list[i].x, target_bias.dets_list[i].y, target_bias.dets_list[i].z));
tf1.setRotation(tf::Quaternion(current_pose.orientation.x, current_pose.orientation.y, current_pose.orientation.z, current_pose.orientation.w));
br.sendTransform(tf::StampedTransform(tf1, ros::Time::now(), "camera1_link", tf_name1 + to_string(i)));
string b;
b = target_bias.dets_list[i].class_name;
prod_list.strings.push_back(b);
}
}
}
void warehouse_action::mis_callback(detection_msgs::StringArray msg)
{
mis_list.strings = msg.strings;
for(int i=0; i<msg.strings.size(); i++)
{
cout<<msg.strings[i]<<endl;
}
}
void warehouse_action::loc_callback(std_msgs::Int8 msg)
{
printf("%d\n", msg.data);
if(msg.data == 1)
cout<<"At Position One"<<endl;
}
void warehouse_action::Position_Manager()
{
moveit::planning_interface::MoveGroupInterface move_group(PLANNING_GROUP);
const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(PLANNING_GROUP);
moveit::core::RobotStatePtr current_state = move_group.getCurrentState();
vector<double> joint_group_positions;
current_state->copyJointGroupPositions(joint_model_group, joint_group_positions);
move_group.setStartState(*move_group.getCurrentState());
moveit::planning_interface::MoveGroupInterface::Plan my_plan;
bool success;
while(1)
{
command = getchar();
if(command == 'h')
{
ROS_INFO("GO HOME");
grip.data = false;
gripper_pub.publish(grip);
joint_group_positions = home_p;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(command == 'w')
{
detection_msgs::StringArray prod_list;
ROS_INFO("GO SCANNING POINT 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
current_pose = move_group.getCurrentPose().pose;
sleep(1);
reach = true;
sleep(1);
ROS_INFO("DONE");
cout<<target_amount<<" target(s)"<<endl;
if(target_amount > 0)
{
for(int i=0; i<target_amount; i++)
{
current_pose = move_group.getCurrentPose().pose;
tf::TransformListener listener;
tf::StampedTransform tf2;
string tf_name2 = "/tm_target_pose";
listener.waitForTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), ros::Duration(4.0));
listener.lookupTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), tf2);
current_pose.position.x += tf2.getOrigin().getX();
current_pose.position.y -= tf2.getOrigin().getZ()-0.095;
current_pose.position.z += tf2.getOrigin().getY()-0.09;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
current_pose.position.y -= 0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
sleep(0.5);
current_pose.position.y -= -0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
target_number++;
if(target_number == 1)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 2)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 2");
joint_group_positions = joint_place2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 3)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 3");
joint_group_positions = joint_place3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 4)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place4;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 5)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place5;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
}
target_amount = 0;
}
collect = false;
reach = false;
ROS_INFO("GO SCANNING POINT 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
current_pose = move_group.getCurrentPose().pose;
sleep(1);
reach = true;
sleep(1);
ROS_INFO("DONE");
cout<<target_amount<<" target(s)"<<endl;
if(target_amount > 0)
{
for(int i=0; i<target_amount; i++)
{
current_pose = move_group.getCurrentPose().pose;
tf::TransformListener listener;
tf::StampedTransform tf2;
string tf_name2 = "/tm_target_pose";
listener.waitForTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), ros::Duration(4.0));
listener.lookupTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), tf2);
current_pose.position.x += tf2.getOrigin().getX();
current_pose.position.y -= tf2.getOrigin().getZ()-0.095;
current_pose.position.z += tf2.getOrigin().getY()-0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
current_pose.position.y -= 0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
sleep(0.5);
current_pose.position.y -= -0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
target_number++;
if(target_number == 1)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 2)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 2");
joint_group_positions = joint_place2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 3)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 3");
joint_group_positions = joint_place3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 4)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place4;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 5)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place5;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
}
target_amount = 0;
}
collect = false;
reach = false;
/*
ROS_INFO("GO SCANNING POINT 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
current_pose = move_group.getCurrentPose().pose;
sleep(1);
reach = true;
sleep(1);
ROS_INFO("DONE");
cout<<target_amount<<" target(s)"<<endl;
if(target_amount > 0)
{
for(int i=0; i<target_amount; i++)
{
current_pose = move_group.getCurrentPose().pose;
tf::TransformListener listener;
tf::StampedTransform tf2;
string tf_name2 = "/tm_target_pose";
listener.waitForTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), ros::Duration(4.0));
listener.lookupTransform("/tm_end_eff", tf_name2 + to_string(i), ros::Time(0), tf2);
current_pose.position.x += tf2.getOrigin().getX();
current_pose.position.y -= tf2.getOrigin().getZ()-0.095;
current_pose.position.z += tf2.getOrigin().getY()-0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
current_pose.position.y -= 0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
sleep(0.5);
current_pose.position.y -= -0.1;
move_group.setPoseTarget(current_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
target_number++;
if(target_number == 1)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 2)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 2");
joint_group_positions = joint_place2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 3)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 3");
joint_group_positions = joint_place3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 4)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place4;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place4_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(target_number == 5)
{
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO PLACE 1");
joint_group_positions = joint_place5;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
ROS_INFO("GO MIDDLE POINT");
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place5_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCAN 3");
joint_group_positions = joint_wh_scan3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
}
target_amount = 0;
}
collect = false;
reach = false;
*/
ROS_INFO("GO HOME");
joint_group_positions = home_p;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
target_number = 0;
prod_pub.publish(prod_list);
replacement_finished.data = 1;
replace_finish_pub.publish(replacement_finished);
ROS_INFO("GO SHELF SCAN POINT");
joint_group_positions = joint_sh_scan;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
}
if(command == 's')
{
ROS_INFO("GO SCANNING POINT 1");
joint_group_positions = joint_wh_scan1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO SCANNING POINT 2");
joint_group_positions = joint_wh_scan2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
}
if(command == 'r')
{
ROS_INFO("GO JOINT PLACE TAG");
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
sleep(1);
tf::TransformListener listener;
tf::StampedTransform tf_l, tf_bl2coke, tf_bl2soda, tf_bl2lemonade, tf_bl2pinksoda, tf_bl2mineralwater;
static tf::TransformBroadcaster br;
tf::Transform tf_b;
std::string tf_l_name = "/tag_308";
std::string tf_coke_name = "/target_Coke";
std::string tf_soda_name = "/target_Soda";
std::string tf_lemonade_name = "/target_Lemonade";
std::string tf_pinksoda_name = "/target_PinkSoda";
std::string tf_mineralwater_name = "/target_MineralWater";
listener.waitForTransform("/base_link", tf_l_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_l_name, ros::Time(0), tf_l);
tf_b.setOrigin(tf::Vector3(0.05, -0.11, 0.40));
tf_b.setRotation(tf::Quaternion(-0.500, 0.500, 0.500, 0.500));
br.sendTransform(tf::StampedTransform(tf_b, ros::Time::now(), "/tag_308", tf_coke_name));
listener.waitForTransform("/base_link", tf_coke_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_coke_name, ros::Time(0), tf_bl2coke);
tf_b.setOrigin(tf::Vector3(-0.08, -0.11, 0.40));
tf_b.setRotation(tf::Quaternion(-0.500, 0.500, 0.500, 0.500));
br.sendTransform(tf::StampedTransform(tf_b, ros::Time::now(), "/tag_308", tf_mineralwater_name));
listener.waitForTransform("/base_link", tf_mineralwater_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_mineralwater_name, ros::Time(0), tf_bl2mineralwater);
tf_b.setOrigin(tf::Vector3(0.18, -0.11, 0.40));
tf_b.setRotation(tf::Quaternion(-0.500, 0.500, 0.500, 0.500));
br.sendTransform(tf::StampedTransform(tf_b, ros::Time::now(), "/tag_308", tf_pinksoda_name));
listener.waitForTransform("/base_link", tf_pinksoda_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_pinksoda_name, ros::Time(0), tf_bl2pinksoda);
tf_b.setOrigin(tf::Vector3(-0.21, -0.11, 0.40));
tf_b.setRotation(tf::Quaternion(-0.500, 0.500, 0.500, 0.500));
br.sendTransform(tf::StampedTransform(tf_b, ros::Time::now(), "/tag_308", tf_lemonade_name));
listener.waitForTransform("/base_link", tf_lemonade_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_lemonade_name, ros::Time(0), tf_bl2lemonade);
tf_b.setOrigin(tf::Vector3(-0.34, -0.11, 0.40));
tf_b.setRotation(tf::Quaternion(-0.500, 0.500, 0.500, 0.500));
br.sendTransform(tf::StampedTransform(tf_b, ros::Time::now(), "/tag_308", tf_soda_name));
listener.waitForTransform("/base_link", tf_soda_name, ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/base_link", tf_soda_name, ros::Time(0), tf_bl2soda);
tf::StampedTransform product_at_p1 = tf_bl2pinksoda;
tf::StampedTransform product_at_p2 = tf_bl2mineralwater;
tf::StampedTransform product_at_p3 = tf_bl2soda;
//START REPLACEMENT
ROS_INFO("GO JOINT PLACE 3");
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place3;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
joint_group_positions = joint_place3_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO JOINT PLACE TARGET");
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
tag_pose = move_group.getCurrentPose().pose;
tag_pose.position.x = product_at_p3.getOrigin().getX();
tag_pose.position.y = product_at_p3.getOrigin().getY();
tag_pose.position.z = product_at_p3.getOrigin().getZ();
tag_pose.position.y += 0.10;
tag_pose.position.z += 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
tag_pose.position.y -= 0.10;
tag_pose.position.z -= 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
tag_pose.position.y += 0.15;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO JOINT PLACE 2");
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
joint_group_positions = joint_place2_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO JOINT PLACE TARGET");
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
tag_pose = move_group.getCurrentPose().pose;
tag_pose.position.x = product_at_p2.getOrigin().getX();
tag_pose.position.y = product_at_p2.getOrigin().getY();
tag_pose.position.z = product_at_p2.getOrigin().getZ();
tag_pose.position.y += 0.10;
tag_pose.position.z += 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
tag_pose.position.y -= 0.10;
tag_pose.position.z -= 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
tag_pose.position.y += 0.15;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO JOINT PLACE 1");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
joint_group_positions = joint_place1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
grip.data = true;
gripper_pub.publish(grip);
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("GO JOINT PLACE TARGET");
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
tag_pose = move_group.getCurrentPose().pose;
tag_pose.position.x = product_at_p1.getOrigin().getX();
tag_pose.position.y = product_at_p1.getOrigin().getY();
tag_pose.position.z = product_at_p1.getOrigin().getZ();
tag_pose.position.y += 0.10;
tag_pose.position.z += 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
tag_pose.position.y -= 0.10;
tag_pose.position.z -= 0.10;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
grip.data = false;
gripper_pub.publish(grip);
tag_pose.position.y += 0.15;
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
move_group.setPoseTarget(tag_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
move_group.move();
joint_group_positions = joint_place_tag;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("DONE");
replacement_finished.data = 2;
replace_finish_pub.publish(replacement_finished);
}
if(command == 'm')
{
ROS_INFO("GO JOINT PLACE 1 MID");
joint_group_positions = joint_place1_mid;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
}
if(command == 'p')
{
ROS_INFO("GO JOINT PLACE 1");
joint_group_positions = joint_place1;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
}
if(command == 'q')
{
joint_group_positions = home_p_2;
move_group.setJointValueTarget(joint_group_positions);
move_group.move();
ROS_INFO("QUIT");
break;
}
}
}
warehouse_action *wa;
void sigHandler(int signum)
{
delete wa;
exit(0);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "warehouse_action");
ros::NodeHandle nh;
signal(SIGINT, sigHandler);
wa = new warehouse_action(nh);
ros::spin();
return 0;
} | [
"kyyoung54402@gmail.com"
] | kyyoung54402@gmail.com |
76e61c71272a7cdbe36311892db3bd775e346c6c | 498d79134ee56abd3949edff64cc7900eefe0f09 | /C++/.vscode/算法竞赛入门/demo_dfs.cpp | 34dd8fc8125073ff970659148d4a6973ee8750d2 | [] | no_license | dannyXSC/XSCabBar | 8cfbedaf5e9f9759cc79ef52774fac65b6320c9e | 76e519aeb8f04339bbdd43f87f36d992a3bf3abb | refs/heads/master | 2022-12-31T15:05:22.362555 | 2020-10-26T15:06:48 | 2020-10-26T15:06:48 | 301,393,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | cpp | #include <iostream>
#include <string.h>
using namespace std;
#define barrier '*'
#define target '@'
const int maxn=1000,maxm=1000; //分别为最大行数和列数
int n,m; //n,m为输入的行列数
char ele[maxn][maxm]; //表格中的元素
int val[maxn][maxm];
int dfs(int r,int c,int id)
{
//判断是否出界
if(r<0||r>=n||c<0||c>=m)return 0;
//结束条件 本元素不是目标元素或者已经算过
if(barrier==ele[r][c]||val[r][c]>0)return 0;
//对需要dfs的元素进行操作
//进行id赋值
val[r][c]=id;
//对四周进行dfs
int i,j;
for(i=-1;i<=1;i++)
{
for(j=-1;j<=1;j++)
{
if(0==i*j&&!(i==0&&j==0))
{
dfs(r+i,c+j,id);
}
}
}
//此时已经对四周都进行了dfs,遍历完成
return 1;
}
//下面是测试程序
/*
3 3
@ @ *
@ * @
* @ *
*/
int main()
{
int i,j;
int id=1;
cin>>n>>m;
//初始化数组
memset(ele,0,sizeof(ele));
memset(val,0,sizeof(val));
//读入元素
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>ele[i][j];
}
}
//进行dfs
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(dfs(i,j,id))
{
id++;
}
}
}
//输出
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<val[i][j]<<" ";
}
cout<<endl;
}
return 0;
} | [
"874794016@qq.com"
] | 874794016@qq.com |
bf270dbf81b8d364192d9c5fda36d617255ffe4e | 8bc4f1bc2144c0e5711baf47783541c9a4ac1e5e | /goldIngot_codevita_9.cpp | fa4e8df12ddc79fa006f80a379546d070a300717 | [] | no_license | 1337w0rm/BVEC-Hacktoberfest-2020 | 09df549175471e7c92d7eebc837402822d51af6e | 5759759edf0b86bba2612b5c29594d6f27031645 | refs/heads/master | 2023-01-07T02:23:15.681254 | 2020-10-22T11:34:07 | 2020-10-22T11:34:07 | 300,498,799 | 2 | 20 | null | 2020-10-22T11:34:08 | 2020-10-02T04:20:06 | HTML | UTF-8 | C++ | false | false | 901 | cpp | #include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main(){
int i,g,b,h;
cin>>g;
int l[g];
cin>>b>>h;
for(i=0;i<g;i++){
cin>>l[i];
}
int totVol=0;
for(i=0;i<g;i++){
totVol+=l[i]*b*h;
}
int cal, maxl;
cal=maxl=0;
stack<int> s;
for (int i=0;i<g;i++)
{
while(!s.empty() && l[i]<=l[s.top()])
{
int n = s.top();
s.pop();
if(s.empty()){
cal = l[n] * i;
}
else{
cal = l[n] * (i-s.top()-1);
}
if(cal>maxl){
maxl=cal;
}
}
s.push(i);
}
while (!s.empty()){
int n = s.top();
s.pop();
if(s.empty()){
cal = l[n]*g;
}
else{
cal = l[n]*(g-s.top()-1);
}
if(cal>maxl){
maxl=cal;
}
}
int ingotVol;
ingotVol=maxl*b*h;
int mod = pow(10,9) + 7;
cout << (totVol-ingotVol) % mod ;
return 0;
}
| [
"49098410+rishavjyoti@users.noreply.github.com"
] | 49098410+rishavjyoti@users.noreply.github.com |
4cf95d20e4d777e271d2da99e17783a5fb9f8759 | f64042757a67a081977bcea985f6747793540a06 | /Project-1/studentdb.h | a09794f94615f66035696879020cfb1132e4b66b | [] | no_license | Blaine-Mason/COSC220 | fcf0b1fc3661ba38972bf7747852a3f9171f9831 | 5575308db6156889a7c6731336351a4416e4f868 | refs/heads/master | 2020-08-08T00:53:26.213733 | 2019-12-06T19:29:33 | 2019-12-06T19:29:33 | 213,647,755 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | #ifndef STUDENTDB_H
#define STUDENTDB_H
#include "course.h"
#include "student.h"
#include <iostream>
#include <string>
class StudentDB{
private:
struct StudentNode{
Student s;
StudentNode* next;
};
StudentNode* head;
public:
StudentDB();
~StudentDB();
void createStudent(Student);
void deleteStudent(Student);
void updateStudent(Student);
Student getStudent(std::string);
void displayDB() const;
};
#endif
| [
"bmason3@gulls.salisbury.edu"
] | bmason3@gulls.salisbury.edu |
77c16db4fb485d75a87dc21ce687d52e26ed063b | d8e7a11322f6d1b514c85b0c713bacca8f743ff5 | /7.6.00.32/V76_00_32/MaxDB_ORG/sys/src/SAPDB/Join/Join_IAccessOperator.hpp | 0d63f8057d3a439c2d9d1ac61deeaaa856698fbc | [] | no_license | zhaonaiy/MaxDB_GPL_Releases | a224f86c0edf76e935d8951d1dd32f5376c04153 | 15821507c20bd1cd251cf4e7c60610ac9cabc06d | refs/heads/master | 2022-11-08T21:14:22.774394 | 2020-07-07T00:52:44 | 2020-07-07T00:52:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,040 | hpp | #ifndef JOIN_IACCESSOPERATOR_HPP
#define JOIN_IACCESSOPERATOR_HPP
/*!
* @file Join_IAccessOperator.hpp
* @brief realize one table access operator by means of Join_AccessDesc
*
* @author MartinKi
* @ingroup Join
*
* @sa Join_AccessDesc.hpp
*/
/*
========== licence begin GPL
Copyright (c) 2002-2005 SAP AG
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
========== licence end
*/
#include "SAPDBCommon/SAPDB_Types.hpp"
#include "Join/Join_IOperator.hpp"
#include "Join/Join_AccessDesc.hpp"
#include "ggg00.h"
class SQLMan_Context;
//! operator for base table access via key or index
class Join_IAccessOperator: public IOperator {
public:
//! @name record stream properties
//@{
//! return key length of records in stream
SAPDB_UInt2 GetKeyLength() const { return m_AccessDesc.GetKeyLength(); }
//! return length of records in stream
SAPDB_UInt2 GetRecordLength() const { return m_AccessDesc.GetRecordLength(); }
//@}
/*!
*
*/
virtual tgg00_BasisError Next( tgg00_Rec*& recptr ) =0;
/*!
* @brief Sets the maxmimum number of rows that will read during a
* single bd-access.
*/
virtual void SetMaximumRowsReadAtATime(const SAPDB_Int4 maxRowRequest);
/*!
* @brief Returns the maxmimum number of rows that will read during a
* single bd-access.
*/
virtual SAPDB_Int4 GetMaximumRowsReadAtATime() const;
/*!
* @brief Returns true if all qualified records of this table are
* buffered in memory.
*/
virtual SAPDB_Bool IsResultFullyBuffered() const { return false; };
/*!
* @brief Returns the number of records that are buffered. If not
* all qualified records could be buffered, 0 is returned.
*/
virtual SAPDB_UInt4 GetBufferedRecordCount() const { return 0; };
virtual tgg00_BasisError GetNullRecord( tgg00_Rec*& recptr );
// member methods
//! @name constructor(is protected) / destructor
//@{
//! destructor
virtual ~Join_IAccessOperator();
//@}
protected:
// member methods
//! @name constructor / destructor
//@{
//! constructor
Join_IAccessOperator(SQLMan_Context& acv, const SAPDB_UInt2 tabno);
void invalidate_keys();
virtual tgg00_BasisError next( tgg00_Rec** records )
{
tgg00_Rec *_recptr = 0;
tgg00_BasisError _b_err = this->Next( _recptr );
*(records + m_TableNo-1) = _recptr;
return _b_err;
}
virtual tgg00_BasisError get_null_record( tgg00_Rec** records )
{
tgg00_Rec *_recptr = 0;
tgg00_BasisError _b_err = this->GetNullRecord( _recptr );
*(records + m_TableNo-TAB_OFFS_GG07) = _recptr;
return _b_err;
}
// protected member variables
Join_AccessDesc m_AccessDesc;
SAPDB_Int4 m_maxRowRequest;
const SAPDB_UInt2 m_TableNo;
private:
// private member variables
SAPDB_AutoPtr<tgg00_Rec> m_NullRec;
};
/*************************************************************************/
inline void Join_IAccessOperator::invalidate_keys()
{
// initialize keys as invalid key: first key compare --> false
m_Startkeys.reckey.keyLen_gg00() = -1;
m_Startkeys.listkey.keyLen_gg00() = -1;
m_Stopkeys.reckey.keyLen_gg00() = -1;
m_Stopkeys.listkey.keyLen_gg00() = -1;
}
#endif
| [
"gunter.mueller@gmail.com"
] | gunter.mueller@gmail.com |
f33d0c2d9c96f695927cb181009ea7a86c794585 | e41e78cc4b8d010ebdc38bc50328e7bba2d5a3fd | /SDK/Mordhau_BP_HoveredSetting_parameters.hpp | e2a0904ff1820fbc848dd6e7a5440ef56d1c0f55 | [] | no_license | Mentos-/Mordhau_SDK | a5e4119d60988dca9063e75e2563d1169a2924b8 | aacf020e6d4823a76787177eac2f8f633f558ec2 | refs/heads/master | 2020-12-13T10:36:47.589320 | 2020-01-03T18:06:38 | 2020-01-03T18:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | hpp | #pragma once
// Mordhau (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BP_HoveredSetting.BP_HoveredSetting_C.SetPerformanceImpact
struct UBP_HoveredSetting_C_SetPerformanceImpact_Params
{
int Amount; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UTextBlock* Widget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FString Prefix; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor)
};
// Function BP_HoveredSetting.BP_HoveredSetting_C.SetHoveredSetting
struct UBP_HoveredSetting_C_SetHoveredSetting_Params
{
struct FText Title; // (BlueprintVisible, BlueprintReadOnly, Parm)
struct FText Description; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool bShowPerformanceImpact; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
int CPU_Impact; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
int GPU_Impact; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
int VRAM_Impact; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UTexture2D* Image; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_HoveredSetting.BP_HoveredSetting_C.Construct
struct UBP_HoveredSetting_C_Construct_Params
{
};
// Function BP_HoveredSetting.BP_HoveredSetting_C.ExecuteUbergraph_BP_HoveredSetting
struct UBP_HoveredSetting_C_ExecuteUbergraph_BP_HoveredSetting_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
206daa69c42205c1a4f9e321b8c28dfa31048b31 | e77bb7afc612666f1b8d65a0039a32f737b4f209 | /components/viz/service/display_embedder/skia_output_device.h | c8bcc7b26acb2167b12367d9086d8e0905fab60b | [
"BSD-3-Clause"
] | permissive | lvyeshufang/chromium | 76f6b227ac100f0c75305252a9ffc45820da70de | 49f84636734485b99303ed44a18bc09a39efabe2 | refs/heads/master | 2022-08-22T02:35:00.231811 | 2019-07-09T11:24:00 | 2019-07-09T11:24:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,244 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_
#define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_
#include "base/callback.h"
#include "base/macros.h"
#include "base/optional.h"
#include "components/viz/service/display/output_surface.h"
#include "gpu/command_buffer/common/swap_buffers_complete_params.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/src/gpu/GrSemaphore.h"
#include "ui/gfx/swap_result.h"
class SkSurface;
namespace gfx {
class ColorSpace;
class Rect;
class Size;
struct PresentationFeedback;
} // namespace gfx
namespace viz {
class SkiaOutputDevice {
public:
// A helper class for defining a BeginPaint() and EndPaint() scope.
class ScopedPaint {
public:
explicit ScopedPaint(SkiaOutputDevice* device)
: device_(device), sk_surface_(device->BeginPaint()) {
DCHECK(sk_surface_);
}
~ScopedPaint() { device_->EndPaint(semaphore_); }
SkSurface* sk_surface() const { return sk_surface_; }
void set_semaphore(const GrBackendSemaphore& semaphore) {
DCHECK(!semaphore_.isInitialized());
semaphore_ = semaphore;
}
private:
SkiaOutputDevice* const device_;
SkSurface* const sk_surface_;
GrBackendSemaphore semaphore_;
DISALLOW_COPY_AND_ASSIGN(ScopedPaint);
};
using BufferPresentedCallback =
base::OnceCallback<void(const gfx::PresentationFeedback& feedback)>;
using DidSwapBufferCompleteCallback =
base::RepeatingCallback<void(gpu::SwapBuffersCompleteParams,
const gfx::Size& pixel_size)>;
SkiaOutputDevice(
bool need_swap_semaphore,
DidSwapBufferCompleteCallback did_swap_buffer_complete_callback);
virtual ~SkiaOutputDevice();
// Changes the size of draw surface and invalidates it's contents.
virtual void Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
gfx::OverlayTransform transform) = 0;
// Presents the back buffer.
virtual gfx::SwapResponse SwapBuffers(BufferPresentedCallback feedback) = 0;
virtual gfx::SwapResponse PostSubBuffer(const gfx::Rect& rect,
BufferPresentedCallback feedback);
// Set the rectangle that will be drawn into on the surface.
virtual void SetDrawRectangle(const gfx::Rect& draw_rectangle);
const OutputSurface::Capabilities& capabilities() const {
return capabilities_;
}
// EnsureBackbuffer called when output surface is visible and may be drawn to.
// DiscardBackbuffer called when output surface is hidden and will not be
// drawn to. Default no-op.
virtual void EnsureBackbuffer();
virtual void DiscardBackbuffer();
bool need_swap_semaphore() const { return need_swap_semaphore_; }
protected:
// Begin paint the back buffer.
virtual SkSurface* BeginPaint() = 0;
// End paint the back buffer.
virtual void EndPaint(const GrBackendSemaphore& semaphore) = 0;
// Helper method for SwapBuffers() and PostSubBuffer(). It should be called
// at the beginning of SwapBuffers() and PostSubBuffer() implementations
void StartSwapBuffers(base::Optional<BufferPresentedCallback> feedback);
// Helper method for SwapBuffers() and PostSubBuffer(). It should be called
// at the end of SwapBuffers() and PostSubBuffer() implementations
gfx::SwapResponse FinishSwapBuffers(gfx::SwapResult result,
const gfx::Size& size);
OutputSurface::Capabilities capabilities_;
const bool need_swap_semaphore_;
uint64_t swap_id_ = 0;
DidSwapBufferCompleteCallback did_swap_buffer_complete_callback_;
// Only valid between StartSwapBuffers and FinishSwapBuffers.
base::Optional<BufferPresentedCallback> feedback_;
base::Optional<gpu::SwapBuffersCompleteParams> params_;
DISALLOW_COPY_AND_ASSIGN(SkiaOutputDevice);
};
} // namespace viz
#endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e06dfa638b6e99332694437f7a0c021710c431da | a5de1de8ba3e4d0825bdbbb8428e0ee4471227c5 | /trunk/activemq-cpp-2.2.6/src/test/activemq/connector/openwire/marshal/v1/ConnectionIdMarshallerTest.cpp | 0a746e5b53c563caa77344d1599962616fa6591b | [
"Apache-2.0"
] | permissive | ypdxcn/ActiveMQClient | 91de74526f2d63ab31e4911298376db07917d92d | 311068b73d6a84e4f4fe25b67a520f93af5f83b0 | refs/heads/master | 2020-03-23T09:45:07.281201 | 2018-07-18T08:43:53 | 2018-07-18T08:43:53 | 141,406,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,639 | cpp | /*
* 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 <activemq/connector/openwire/marshal/v1/ConnectionIdMarshallerTest.h>
#include <activemq/connector/openwire/marshal/v1/ConnectionIdMarshaller.h>
#include <activemq/connector/openwire/commands/ConnectionId.h>
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::connector::openwire::marshal::v1::ConnectionIdMarshallerTest );
#include <activemq/connector/openwire/OpenWireFormat.h>
#include <activemq/connector/openwire/commands/DataStructure.h>
#include <activemq/connector/openwire/utils/BooleanStream.h>
#include <decaf/io/DataInputStream.h>
#include <decaf/io/DataOutputStream.h>
#include <decaf/io/IOException.h>
#include <decaf/io/ByteArrayOutputStream.h>
#include <decaf/io/ByteArrayInputStream.h>
#include <decaf/util/Properties.h>
//
// NOTE!: This file is autogenerated - do not modify!
// if you need to make a change, please see the Java Classes in the
// activemq-core module
//
using namespace std;
using namespace activemq;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace activemq::connector;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::commands;
using namespace activemq::connector::openwire::marshal;
using namespace activemq::connector::openwire::utils;
using namespace activemq::connector::openwire::marshal::v1;
using namespace decaf::io;
using namespace decaf::lang;
using namespace decaf::util;
///////////////////////////////////////////////////////////////////////////////
void ConnectionIdMarshallerTest::test() {
ConnectionIdMarshaller myMarshaller;
ConnectionId myCommand;
ConnectionId* myCommand2;
CPPUNIT_ASSERT( myMarshaller.getDataStructureType() == myCommand.getDataStructureType() );
myCommand2 = dynamic_cast<ConnectionId*>( myMarshaller.createObject() );
CPPUNIT_ASSERT( myCommand2 != NULL );
delete myCommand2;
}
///////////////////////////////////////////////////////////////////////////////
void ConnectionIdMarshallerTest::testLooseMarshal() {
ConnectionIdMarshaller marshaller;
Properties props;
OpenWireFormat openWireFormat( props );
// Configure for this test.
openWireFormat.setVersion( 1 );
openWireFormat.setTightEncodingEnabled( false );
ConnectionId outCommand;
ConnectionId inCommand;
try {
// Marshal the dataStructure to a byte array.
ByteArrayOutputStream baos;
DataOutputStream dataOut( &baos );
dataOut.writeByte( outCommand.getDataStructureType() );
marshaller.looseMarshal( &openWireFormat, &outCommand, &dataOut );
// Now read it back in and make sure it's all right.
ByteArrayInputStream bais( baos.toByteArray(), baos.size() );
DataInputStream dataIn( &bais );
unsigned char dataType = dataIn.readByte();
CPPUNIT_ASSERT( dataType == outCommand.getDataStructureType() );
marshaller.looseUnmarshal( &openWireFormat, &inCommand, &dataIn );
CPPUNIT_ASSERT( inCommand.equals( &outCommand ) == true );
} catch( ActiveMQException& e ) {
e.printStackTrace();
CPPUNIT_ASSERT( false );
} catch( ... ) {
CPPUNIT_ASSERT( false );
}
}
///////////////////////////////////////////////////////////////////////////////
void ConnectionIdMarshallerTest::testTightMarshal() {
ConnectionIdMarshaller marshaller;
Properties props;
OpenWireFormat openWireFormat( props );
// Configure for this test.
openWireFormat.setVersion( 1 );
openWireFormat.setTightEncodingEnabled( true );
ConnectionId outCommand;
ConnectionId inCommand;
try {
// Marshal the dataStructure to a byte array.
ByteArrayOutputStream baos;
DataOutputStream dataOut( &baos );
// Phase 1 - count the size
int size = 1;
BooleanStream bs;
size += marshaller.tightMarshal1( &openWireFormat, &outCommand, &bs );
size += bs.marshalledSize();
// Phase 2 - marshal
dataOut.writeByte( outCommand.getDataStructureType() );
bs.marshal( &dataOut );
marshaller.tightMarshal2( &openWireFormat, &outCommand, &dataOut, &bs );
// Now read it back in and make sure it's all right.
ByteArrayInputStream bais( baos.toByteArray(), baos.size() );
DataInputStream dataIn( &bais );
unsigned char dataType = dataIn.readByte();
CPPUNIT_ASSERT( dataType == outCommand.getDataStructureType() );
bs.clear();
bs.unmarshal( &dataIn );
marshaller.tightUnmarshal( &openWireFormat, &inCommand, &dataIn, &bs );
CPPUNIT_ASSERT( inCommand.equals( &outCommand ) == true );
} catch( ActiveMQException& e ) {
e.printStackTrace();
CPPUNIT_ASSERT( false );
} catch( ... ) {
CPPUNIT_ASSERT( false );
}
}
| [
"ypdxcn@163.com"
] | ypdxcn@163.com |
af872a4462d3068500a39a5af14279c8ccc3f518 | 4f2174ffe63cbd3b4e8daca465e6c62c6a8fd9b8 | /Problem-22/Problem-22.cpp | 4f1dadb8ad736374e8dba85a07985dbb5c6da1c1 | [] | no_license | DHRUV-EDDI/DailyCodingProblem | 5e680bcd4c00698e91d55955ecf087302214e3dc | 82410cb245f4d4d5a50bc02a939f1286ca6ceb6e | refs/heads/master | 2022-12-10T12:33:52.706714 | 2020-08-23T07:33:38 | 2020-08-23T07:33:38 | 260,503,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,751 | cpp | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
typedef struct Node
{
struct Node *leftChild,*Parent,*rightChild;
bool isLocked;
ll val,lockedDescendants;
}Node;
Node *root=NULL;
map<ll,Node*> mp;
Node* insert(ll val)
{
Node *n = new Node;
n -> leftChild = n -> Parent = n -> rightChild = NULL;
n -> isLocked = false;
n -> val = val;
if(root == NULL)
{
n -> lockedDescendants = 0;
root = n;
mp[val] = root;
return root;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp -> leftChild == NULL)
{
n -> Parent = temp;
temp -> leftChild = n;
n -> lockedDescendants = 0;
mp[val] = n;
break;
}
else
q.push(temp -> leftChild);
if(temp -> rightChild == NULL)
{
n -> Parent = temp;
temp -> rightChild = n;
n -> lockedDescendants = 0;
mp[val] = n;
break;
}
else
q.push(temp -> rightChild);
}
return root;
}
bool isLocked(Node *t)
{
return t -> isLocked;
}
void inorder(Node *t)
{
if(t && !isLocked(t))
{
inorder(t -> leftChild);
cout<<t -> val<<" ";
inorder(t -> rightChild);
}
}
bool canUnlockorLock(Node *n)
{
if(n -> lockedDescendants > 0)
return false;
Node *temp = n -> Parent;
while(temp)
{
if(temp -> isLocked)
return false;
temp = temp -> Parent;
}
return true;
}
bool Lock(Node *n)
{
if(!isLocked(n) && canUnlockorLock(n))
{
Node *cur = n -> Parent;
while(cur)
{
cur -> lockedDescendants ++;
cur = cur -> Parent;
}
n -> isLocked = true;
return true;
}
return false;
}
bool Unlock(Node *n)
{
if(n && isLocked(n) && canUnlockorLock(n))
{
Node *cur = n -> Parent;
while(cur)
{
cur -> lockedDescendants--;
cur = cur -> Parent;
}
n -> isLocked = false;
return true;
}
return false;
}
int main()
{
ll n;
cin>>n;
for(int i=0;i<n;i++)
{
ll val;
cin >> val;
root = insert(val);
}
ll lockQueries,unlockQueries;
cin >> lockQueries >> unlockQueries;
while(lockQueries--)
{
ll lockVal;
cin>> lockVal;
Lock((Node*)mp[lockVal]);
}
inorder(root); cout<<"\n";
while(unlockQueries--)
{
ll unlockVal;
cin >> unlockVal;
Unlock((Node*)mp[unlockVal]);
}
inorder(root);
return 0;
} | [
"dhruv2018570@gmail.com"
] | dhruv2018570@gmail.com |
5423895734dc9286c280b49cad578b00b3cc828e | 7c5d7fb6a64df1a118a64bdf6087ecf395a3a722 | /data/open-Red/sources/004656-open-2015-022-Red.cpp | eb4d59d39cf619e028a2a4288650b38271aaabaa | [] | no_license | alexhein189/code-plagiarism-detector | e66df71c46cc5043b6825ef76a940b658c0e5015 | 68d21639d4b37bb2c801befe6f7ce0007d7eccc5 | refs/heads/master | 2023-03-18T06:02:45.508614 | 2016-05-04T14:29:57 | 2016-05-04T14:54:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 5e5 + 111;
const int INF = 1e9 + 10;
int n, m, d, edges, a, b;
int first[MAX], nextt[MAX], endd[MAX], t[MAX];
bool was[MAX];
int ans;
int cc;
void addEdge(int i, int j, int c)
{
nextt[edges] = first[i];
first[i] = edges;
endd[edges] = j;
t[edges++] = c;
}
void dfs(int v, int dist, int temp = INF)
{
if(dist >= ans)
return;
cc++;
if(v == b)
{
ans = min(ans, dist);
return;
}
if(cc > 1e5)
return;
for(int i = first[v]; i != -1; i = nextt[i])
{
if(!was[i])
{
if(temp == INF || abs(temp - t[i]) <= d)
{
was[i] = true;
dfs(endd[i], dist + 1, t[i]);
was[i] = false;
}
}
}
}
int main()
{
//freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
fill(first, first + MAX, -1);
scanf("%d %d %d", &n, &m, &d);
for(int i = 0; i < m; i++)
{
int a, b, t;
scanf("%d %d %d", &a, &b, &t);
addEdge(--a, --b, t);
addEdge(b, a, t);
}
int q;
cin >> q;
for(int i = 0; i < q; i++)
{
scanf("%d %d", &a, &b);
a--;b--;
cc = 0;
ans = INF;
dfs(a, 0);
if(ans == INF)
printf("%d\n", -1);
else printf("%d\n", ans);
}
return 0;
}
| [
"shk.slava@gmail.com"
] | shk.slava@gmail.com |
47c5300782c1c559545522bc2bf8cb3aa37c88d9 | f5524a0e68536f703871fc1d9bd2b3acfefc8090 | /JumpTrading/Order.h | 5c4c29f722653fc24b891a21d0a5ba7320e431d7 | [] | no_license | mganesh/code | ee014845b38e946fe7aa21853aca100a1d25f4a8 | 5a74b51c2763f3a7d8796bcdcceab1cdd637ca95 | refs/heads/master | 2021-01-17T17:00:06.590324 | 2014-01-23T15:22:11 | 2014-01-23T15:22:11 | 1,059,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | h | //
// Order.h
// ExchangeFeed
//
//
#ifndef ExchangeFeed_Order_h
#define ExchangeFeed_Order_h
#include <stdint.h>
#include <string>
namespace feed {
class Order {
public:
enum Side {
BUY = 1,
SELL = 2
};
Order(uint64_t orderId,
Side side,
uint64_t quantity,
double price);
~Order();
uint64_t getOrderId() { return m_orderId;}
Side getSide() const { return m_side; }
double getPrice() const { return m_price; }
uint64_t getQuantity() const { return m_quantity; }
bool isOpen() { return m_openQuantity > 0; }
void setPrice(double price) { m_price = price; }
void setQuantity(uint64_t quantity);
void setOpenQuantity(uint64_t openQuantity) { m_openQuantity = openQuantity; }
void fill(double price, uint64_t quantity);
double lastExecutedPrice() { return m_lastExecutedPrice; }
uint64_t lastExecutedQuantity() { return m_lastExecutedQuantity; }
uint64_t getOpenQuantity() { return m_openQuantity; }
uint64_t getExecutedQty() { return m_executedQuantity; }
private:
uint64_t m_orderId;
Side m_side;
uint64_t m_quantity;
double m_price;
double m_lastExecutedPrice;
uint64_t m_openQuantity;
uint64_t m_lastExecutedQuantity;
uint64_t m_executedQuantity;
};
}
#endif
| [
"ganesh.muniyandi@gmail.com"
] | ganesh.muniyandi@gmail.com |
b57bea2cccfddfe6b9113b1c05e6a18698e54fba | 5a8fcff9e4ece56a677f5edce16f55b338e5df1f | /HelperTool/libtins/include/network_interface.h | c9ee55fceb55ded8a07ff3ba56863e51f8bb2004 | [] | no_license | martinhering/radiohijack | 6ca61a790ddac3b1b4dc4ee72eaf2abd0991df18 | 233a55b98399755e623771b0ca7d238236709776 | refs/heads/master | 2021-01-19T15:27:39.530689 | 2014-05-01T08:47:10 | 2014-05-01T08:47:10 | 19,338,883 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,441 | h | /*
* Copyright (c) 2012, Matias Fontanini
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef TINS_NETWORK_INTERFACE_H
#define TINS_NETWORK_INTERFACE_H
#include <string>
#include <stdint.h>
#include "hw_address.h"
#include "ip_address.h"
namespace Tins {
/**
* \class NetworkInterface
* \brief Abstraction of a network interface
*/
class NetworkInterface {
public:
/**
* \brief The type used to store the interface's identifier.
*/
typedef uint32_t id_type;
/**
* \brief The type of this interface's address.
*/
typedef HWAddress<6> address_type;
/**
* \brief Struct that holds an interface's addresses.
*/
struct Info {
IPv4Address ip_addr, netmask, bcast_addr;
address_type hw_addr;
};
/**
* Returns a NetworkInterface object associated with the default
* interface.
*/
static NetworkInterface default_interface();
/**
* Default constructor.
*/
NetworkInterface();
/**
* \brief Constructor from std::string.
*
* \param name The name of the interface this object will abstract.
*/
NetworkInterface(const std::string &name);
/**
* \brief Constructor from const char*.
*
* \param name The name of the interface this object will abstract.
*/
NetworkInterface(const char *name);
/**
* \brief Constructs a NetworkInterface from an ip address.
*
* This abstracted interface will be the one that would be the gateway
* when sending a packet to the given ip.
*
* \param ip The ip address being looked up.
*/
NetworkInterface(IPv4Address ip);
/**
* \brief Getter for this interface's identifier.
*
* \return id_type containing the identifier.
*/
id_type id() const {
return iface_id;
}
/**
* \brief Retrieves this interface's name.
*
* \return std::string containing this interface's name.
*/
std::string name() const;
/**
* \brief Retrieve this interface's addresses.
*
* This method iterates through all the interface's until the
* correct one is found. Therefore it's O(N), being N the amount
* of interfaces in the system.
*/
Info addresses() const;
/**
* \brief Tests whether this is a valid interface;
*
* An interface will not be valid iff it was created using the
* default constructor.
*/
operator bool() const {
return iface_id != 0;
}
/**
* \brief Compares this interface for equality.
*
* \param rhs The interface being compared.
*/
bool operator==(const NetworkInterface &rhs) const {
return iface_id == rhs.iface_id;
}
/**
* \brief Compares this interface for inequality.
*
* \param rhs The interface being compared.
*/
bool operator!=(const NetworkInterface &rhs) const {
return !(*this == rhs);
}
private:
id_type resolve_index(const char *name);
id_type iface_id;
};
}
#endif // TINS_NETWORK_INTERFACE_H
| [
"hering@vemedio.com"
] | hering@vemedio.com |
e90b6af8f452a76f16f061043467cf3e37ec3cdd | 1aeb50f6fbbc59c94576c3c40f8b64ca890b2474 | /plugins/MultiContactStabilizerPlugin/ModelPredictiveController.cpp | 75146a33f144b0ecfba3b2a15019440faecb67ea | [] | no_license | kindsenior/jsk_choreonoid | b6a8f39b45a8350404c42f1e029d777cb349615e | 82e3faa0e03595637c30654dba28f90ae3bc9e72 | refs/heads/master | 2021-01-24T09:46:38.756888 | 2020-07-07T06:23:12 | 2020-07-07T06:23:12 | 37,442,336 | 1 | 3 | null | 2020-06-04T08:42:16 | 2015-06-15T03:56:32 | C++ | UTF-8 | C++ | false | false | 10,448 | cpp | /**
@author Kunio Kojima
*/
#include "ModelPredictiveController.h"
using namespace hrp;
using namespace std;
// template <class ControllerClass, class ParamClass>
// ModelPredictiveController<ControllerClass,ParamClass>::ModelPredictiveController()
// {
// isInitial = true;
// parent = NULL;
// }
// template <class ControllerClass, class ParamClass>
// ParamClass* ModelPredictiveController<ControllerClass,ParamClass>::copyMpcParam(ControllerClass* controller, ParamClass* fromMpcParam)
// {
// ParamClass* toMpcParam = new ControllerClass(controller, fromMpcParam);
// return toMpcParam;
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcPhiMatrix()
// {
// phiMat = dmatrix(stateDim*numWindows_,stateDim);
// dmatrix lastMat = dmatrix::Identity(stateDim,stateDim);
// for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){
// int idx = std::distance(mpcParamDeque.begin(), iter);
// lastMat = (*iter)->systemMat * lastMat;
// phiMat.block(stateDim*idx,0, stateDim,stateDim) = lastMat;
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcPsiMatrix()
// {
// psiMat = dmatrix::Zero(stateDim*numWindows_,psiCols);
// int colIdx = 0;
// for(typename std::deque<ParamClass*>::iterator Biter = mpcParamDeque.begin(); Biter != mpcParamDeque.end(); ){// Biterは内側のforループでインクリメント
// dmatrix lastMat = (*Biter)->inputMat;
// int cols = lastMat.cols();
// int Bidx = std::distance(mpcParamDeque.begin(), Biter);// column index
// psiMat.block(stateDim*Bidx,colIdx, stateDim,cols) = lastMat;
// for(typename std::deque<ParamClass*>::iterator Aiter = ++Biter; Aiter != mpcParamDeque.end(); ++Aiter){
// int Aidx = std::distance(mpcParamDeque.begin(), Aiter);// row index
// lastMat = (*Aiter)->systemMat * lastMat;
// psiMat.block(stateDim*Aidx,colIdx, stateDim,cols) = lastMat;
// }
// colIdx += cols;
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcEqualConstraints()
// {
// equalMat = dmatrix::Zero(equalMatRows,URows);
// equalVec = dvector(equalMatRows);
// int rowIdx = 0;
// int colIdx = 0;
// hrp::dumpMatrix(equalMat, &ParamClass::equalMat, mpcParamDeque, rowIdx, colIdx, blockFlagVec);
// hrp::dumpVector(equalVec, &ParamClass::equalVec, mpcParamDeque, rowIdx, blockFlagVec);
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcInequalConstraints()
// {
// inequalMat = dmatrix::Zero(inequalMatRows,URows);
// inequalMinVec = dvector(inequalMatRows);
// inequalMaxVec = dvector(inequalMatRows);
// int rowIdx = 0;
// int colIdx = 0;
// hrp::dumpMatrix(inequalMat, &ParamClass::inequalMat, mpcParamDeque, rowIdx, colIdx, blockFlagVec);
// hrp::dumpVector(inequalMinVec, &ParamClass::inequalMinVec, mpcParamDeque, rowIdx, blockFlagVec);
// hrp::dumpVector(inequalMaxVec, &ParamClass::inequalMaxVec, mpcParamDeque, rowIdx, blockFlagVec);
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcBoundVectors()
// {
// minVec = dvector(URows);
// maxVec = dvector(URows);
// int rowIdx = 0;
// hrp::dumpVector(minVec, &ParamClass::minVec, mpcParamDeque, rowIdx, blockFlagVec);
// hrp::dumpVector(maxVec, &ParamClass::maxVec, mpcParamDeque, rowIdx, blockFlagVec);
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcRefXVector()
// {
// refXVec = dvector(stateDim*numWindows_);
// for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){
// int idx = std::distance(mpcParamDeque.begin(), iter);
// refXVec.block(stateDim*idx,0, stateDim,1) = (*iter)->refStateVec;
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcErrorWeightMatrix()
// {
// errorWeightMat = dmatrix::Zero(stateDim*numWindows_,stateDim*numWindows_);
// for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){
// int idx = std::distance(mpcParamDeque.begin(), iter);
// errorWeightMat.block(stateDim*idx,stateDim*idx, stateDim,stateDim) = (*iter)->errorWeightVec.asDiagonal();
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcInputWeightMatrix()
// {
// inputWeightMat = dmatrix::Zero(psiCols,psiCols);
// int rowIdx = 0;
// for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){
// int rows = (*iter)->inputWeightVec.rows();
// inputWeightMat.block(rowIdx,rowIdx, rows,rows) = (*iter)->inputWeightVec.asDiagonal();
// rowIdx += rows;
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcBlockMatrix()
// {
// blockMat = dmatrix::Zero(psiCols,URows);
// blockMatInv = dmatrix::Zero(URows,psiCols);
// std::vector<bool>::iterator blockFlagIter = blockFlagVec.begin();
// typename std::deque<ParamClass*>::iterator colIter = mpcParamDeque.begin();
// int count = 1, rowIdx = 0, colIdx = 0;
// for(typename std::deque<ParamClass*>::iterator rowIter = mpcParamDeque.begin(); rowIter != mpcParamDeque.end(); ++rowIter, ++colIter){
// int rows,cols;
// rows = (*rowIter)->inputDim;
// if(*blockFlagIter){
// cols = (*colIter)->inputDim;
// blockMatInv.block(colIdx,rowIdx, cols,rows) = dmatrix::Identity(cols,rows);// blockMatInv
// }
// blockMat.block(rowIdx,colIdx, rows,cols) = dmatrix::Identity(rows,cols);// blockMat
// if(*(++blockFlagIter)){
// colIdx += cols;
// }
// rowIdx += rows;
// }
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::updateX0Vector()
// {
// ParamClass* mpcParam = mpcParamDeque[0];
// // U->u0
// // x0 = A0*x0 + B'0*u0
// dmatrix x1 = mpcParam->systemMat*x0 + mpcParam->inputMat*U.block(0,0, mpcParam->inputMat.cols(),1);
// if(parent != NULL){
// ControllerClass* root = rootController();
// int stepNum = parent->dt/root->dt;// root->dtで割り切れる?
// // int nextPushIndex;
// // if(!parent->preMpcParamDeque.empty()) nextPushIndex = parent->preMpcParamDeque.back()->index() + stepNum;
// // else if(!parent->mpcParamDeque.empty()) nextPushIndex = parent->mpcParamDeque.back()->index() + stepNum;
// // else nextPushIndex = 0;
// int x0Index = mpcParamDeque[0]->index();
// int x1Index = mpcParamDeque[1]->index();// 0除算の可能性 最後以降は補間しないから大丈夫?
// cout << x0Index << ": " << x0.transpose() << endl;
// cout << x1Index << ": " << x1.transpose() << endl;
// cout << "root: " << root->dt << " parent:" << parent->dt << endl;
// typename std::deque<ParamClass*>::iterator rootPreDequeIter = root->preMpcParamDeque.begin();
// ParamClass* targetMpcParam;
// while((*rootPreDequeIter)->index() < x0Index) rootPreDequeIter += stepNum;
// while((*rootPreDequeIter)->index() < x1Index){
// if(root == parent){
// targetMpcParam = *rootPreDequeIter;
// }else{
// parent->preMpcParamDeque.push_back(copyMpcParam(parent, *rootPreDequeIter));// pickup mpcParam from root mpc dtが変わるので行列は生成し直す
// targetMpcParam = parent->preMpcParamDeque.back();
// }
// targetMpcParam->setRefStateVector(x0 + (x1-x0)*((*rootPreDequeIter)->index() - x0Index)/(double)(x1Index - x0Index)); // interpolate refX,U
// rootPreDequeIter += stepNum;
// }
// }
// x0 = x1;
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::calcAugmentedMatrix()
// {
// psiCols = 0;
// equalMatRows = 0;
// inequalMatRows = 0;
// URows = 0;
// std::vector<bool>::iterator blockFlagIter = blockFlagVec.begin();
// for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter, ++blockFlagIter){
// psiCols += (*iter)->inputMat.cols();
// if(*blockFlagIter){
// URows += (*iter)->inputDim;
// equalMatRows += (*iter)->equalMat.rows();
// inequalMatRows += (*iter)->inequalMat.rows();
// }
// }
// if(isInitial){
// x0 = dvector(stateDim);
// x0 = mpcParamDeque[0]->refStateVec;
// isInitial = false;
// }
// calcPhiMatrix();
// calcPsiMatrix();
// calcEqualConstraints();
// calcInequalConstraints();
// calcBoundVectors();
// calcRefXVector();
// calcErrorWeightMatrix();
// calcInputWeightMatrix();
// calcBlockMatrix();
// U = dvector::Zero(URows);
// }
// template <class ControllerClass, class ParamClass>
// ControllerClass* ModelPredictiveController<ControllerClass,ParamClass>::rootController()
// {
// if(parent != NULL) return parent->rootController();
// return this;
// }
// template <class ControllerClass, class ParamClass>
// void ModelPredictiveController<ControllerClass,ParamClass>::pushAllPreMPCParamFromRoot()
// {
// ControllerClass* root = rootController();
// int stepNum = dt/root->dt;// root->dtで割り切れる?
// typename std::deque<ParamClass*>::iterator iter = root->preMpcParamDeque.begin();
// while(iter != root->preMpcParamDeque.end()){
// preMpcParamDeque.push_back(copyMpcParam(this ,*iter));
// for(int i=0; i<stepNum && iter !=root->preMpcParamDeque.end(); ++i, ++iter);
// }
// }
| [
"kunio.einstein@gmail.com"
] | kunio.einstein@gmail.com |
4cf80ee9495418a54a96c7f7e98d73f9ef713898 | 60393750e9c3f3b8ab42d6326fe9eca4ee349b47 | /SNAPLib/IntersectingPairedEndAligner.h | 4cd3b68157bae80a8021c1797da5f56035a466aa | [
"Apache-2.0"
] | permissive | andrewmagis/snap-rnaseq | 5ee9f33ef63539d1f225899971247ac5170e1bdc | 458e648f570466e2c702a4c349d11f16e1ee4eac | refs/heads/master | 2021-01-10T19:43:26.311446 | 2013-12-06T03:14:18 | 2013-12-06T03:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,841 | h | /*++
Module Name:
IntersectingPairedEndAligner.h
Abstract:
A paired-end aligner based on set intersections to narrow down possible candidate locations.
Authors:
Bill Bolosky, February, 2013
Environment:
User mode service.
Revision History:
--*/
#pragma once
#include "PairedEndAligner.h"
#include "BaseAligner.h"
#include "BigAlloc.h"
#include "directions.h"
#include "LandauVishkin.h"
#include "FixedSizeMap.h"
const unsigned DEFAULT_INTERSECTING_ALIGNER_MAX_HITS = 16000;
const unsigned DEFAULT_MAX_CANDIDATE_POOL_SIZE = 1000000;
class IntersectingPairedEndAligner : public PairedEndAligner
{
public:
IntersectingPairedEndAligner(
GenomeIndex *index_,
unsigned maxReadSize_,
unsigned maxHits_,
unsigned maxK_,
unsigned maxSeedsFromCommandLine_,
double seedCoverage_,
unsigned minSpacing_, // Minimum distance to allow between the two ends.
unsigned maxSpacing_, // Maximum distance to allow between the two ends.
unsigned maxBigHits_,
unsigned extraSearchDepth_,
unsigned maxCandidatePoolSize,
BigAllocator *allocator);
void setLandauVishkin(
LandauVishkin<1> *landauVishkin_,
LandauVishkin<-1> *reverseLandauVishkin_)
{
landauVishkin = landauVishkin_;
reverseLandauVishkin = reverseLandauVishkin_;
}
virtual ~IntersectingPairedEndAligner();
virtual void align(
Read *read0,
Read *read1,
PairedAlignmentResult *result);
static size_t getBigAllocatorReservation(GenomeIndex * index, unsigned maxBigHitsToConsider, unsigned maxReadSize, unsigned seedLen, unsigned maxSeedsFromCommandLine,
double seedCoverage, unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize);
virtual _int64 getLocationsScored() const {
return nLocationsScored;
}
private:
IntersectingPairedEndAligner() {} // This is for the counting allocator, it doesn't build a useful object
static const int NUM_SET_PAIRS = 2; // A "set pair" is read0 FORWARD + read1 RC, or read0 RC + read1 FORWARD. Again, it doesn't make sense to change this.
void allocateDynamicMemory(BigAllocator *allocator, unsigned maxReadSize, unsigned maxBigHitsToConsider, unsigned maxSeedsToUse,
unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize);
GenomeIndex * index;
const Genome * genome;
unsigned genomeSize;
unsigned maxReadSize;
unsigned maxHits;
unsigned maxBigHits;
unsigned extraSearchDepth;
unsigned maxK;
unsigned numSeedsFromCommandLine;
double seedCoverage;
static const unsigned MAX_MAX_SEEDS = 30;
unsigned minSpacing;
unsigned maxSpacing;
unsigned seedLen;
unsigned maxMergeDistance;
_int64 nLocationsScored;
struct HashTableLookup {
unsigned seedOffset;
unsigned nHits;
const unsigned *hits;
unsigned whichDisjointHitSet;
//
// We keep the hash table lookups that haven't been exhaused in a circular list.
//
HashTableLookup *nextLookupWithRemainingMembers;
HashTableLookup *prevLookupWithRemainingMembers;
//
// State for handling the binary search of a location in this lookup.
// This would ordinarily be stack local state in the binary search
// routine, but because a) we want to interleave the steps of the binary
// search in order to allow cache prefetches to have time to execute;
// and b) we don't want to do dynamic memory allocation (really at all),
// it gets stuck here.
//
int limit[2]; // The upper and lower limits of the current binary search in hits
unsigned maxGenomeOffsetToFindThisSeed;
//
// A linked list of lookups that haven't yet completed this binary search. This is a linked
// list with no header element, so testing for emptiness needs to happen at removal time.
// It's done that way to avoid a comparison for list head that would result in a hard-to-predict
// branch.
//
HashTableLookup *nextLookupForCurrentBinarySearch;
HashTableLookup *prevLookupForCurrentBinarySearch;
unsigned currentHitForIntersection;
};
//
// A set of seed hits, represented by the lookups that came out of the big hash table.
//
class HashTableHitSet {
public:
HashTableHitSet() {}
void firstInit(unsigned maxSeeds_, unsigned maxMergeDistance_);
//
// Reset to empty state.
//
void init();
//
// Record a hash table lookup. All recording must be done before any
// calls to getNextHitLessThanOrEqualTo. A disjoint hit set is a set of hits
// that don't share any bases in the read. This is interesting because the edit
// distance of a read must be at least the number of seeds that didn't hit for
// any disjoint hit set (because there must be a difference in the read within a
// seed for it not to hit, and since the reads are disjoint there can't be a case
// where the same difference caused two seeds to miss).
//
void recordLookup(unsigned seedOffset, unsigned nHits, const unsigned *hits, bool beginsDisjointHitSet);
//
// This efficiently works through the set looking for the next hit at or below this address.
// A HashTableHitSet only allows a single iteration through its address space per call to
// init().
//
bool getNextHitLessThanOrEqualTo(unsigned maxGenomeOffsetToFind, unsigned *actualGenomeOffsetFound, unsigned *seedOffsetFound);
//
// Walk down just one step, don't binary search.
//
bool getNextLowerHit(unsigned *genomeLocation, unsigned *seedOffsetFound);
//
// Find the highest genome address.
//
bool getFirstHit(unsigned *genomeLocation, unsigned *seedOffsetFound);
unsigned computeBestPossibleScoreForCurrentHit();
private:
struct DisjointHitSet {
unsigned countOfExhaustedHits;
unsigned missCount;
};
int currentDisjointHitSet;
DisjointHitSet *disjointHitSets;
HashTableLookup *lookups;
HashTableLookup lookupListHead[1];
unsigned maxSeeds;
unsigned nLookupsUsed;
unsigned mostRecentLocationReturned;
unsigned maxMergeDistance;
};
HashTableHitSet *hashTableHitSets[NUM_READS_PER_PAIR][NUM_DIRECTIONS];
unsigned countOfHashTableLookups[NUM_READS_PER_PAIR];
unsigned totalHashTableHits[NUM_READS_PER_PAIR][NUM_DIRECTIONS];
unsigned largestHashTableHit[NUM_READS_PER_PAIR][NUM_DIRECTIONS];
unsigned readWithMoreHits;
unsigned readWithFewerHits;
//
// A location that's been scored (or waiting to be scored). This is needed in order to do merging
// of close-together hits and to track potential mate pairs.
//
struct HitLocation {
unsigned genomeLocation;
int genomeLocationOffset; // This is needed because we might get an offset back from scoring (because it's really scoring a range).
unsigned seedOffset;
bool isScored; // Mate pairs are sometimes not scored when they're inserted, because they
unsigned score;
unsigned maxK; // The maxK that this was scored with (we may need to rescore if we need a higher maxK and score is -1)
double matchProbability;
unsigned bestPossibleScore;
//
// We have to be careful in the case where lots of offsets in a row match well against the read (think
// about repetitive short sequences, i.e., ATTATTATTATT...). We want to merge the close ones together,
// but if the repetitive sequence extends longer than maxMerge, we don't want to just slide the window
// over the whole range and declare it all to be one. There is really no good definition for the right
// thing to do here, so instead all we do is that when we declare two candidates to be matched we
// pick one of them to be the match primary and then coalesce all matches that are within maxMatchDistance
// of the match primary. No one can match with any of the locations in the set that's beyond maxMatchDistance
// from the set primary. This means that in the case of repetitve sequences that we'll declare locations
// right next to one another not to be matches. There's really no way around this while avoiding
// matching things that are possibly much more than maxMatchDistance apart.
//
unsigned genomeLocationOfNearestMatchedCandidate;
};
class HitLocationRingBuffer {
public:
HitLocationRingBuffer(unsigned bufferSize_) : bufferSize(bufferSize_), head(0), tail(0)
{
buffer = new HitLocation[bufferSize];
}
~HitLocationRingBuffer()
{
delete [] buffer;
}
bool isEmpty() {return head == tail;}
void insertHead(unsigned genomeLocation, unsigned seedOffset, unsigned bestPossibleScore)
{
_ASSERT((head + 1 ) % bufferSize != tail); // Not overflowing
_ASSERT(head == tail || genomeLocation < buffer[(head + bufferSize - 1)%bufferSize].genomeLocation); // Inserting in strictly descending order
buffer[head].genomeLocation = genomeLocation;
buffer[head].seedOffset = seedOffset;
buffer[head].isScored = false;
buffer[head].genomeLocationOfNearestMatchedCandidate = 0xffffffff;
buffer[head].bestPossibleScore = bestPossibleScore;
head = (head + 1) % bufferSize;
}
void insertHead(unsigned genomeLocation, unsigned seedOffset, unsigned score, double matchProbability)
{
insertHead(genomeLocation, seedOffset, score);
HitLocation *insertedLocation = &buffer[(head + bufferSize - 1)%bufferSize];
insertedLocation->isScored = true;
insertedLocation->score = score;
insertedLocation->matchProbability = matchProbability;
}
void clear()
{
head = tail = 0;
}
void trimAboveLocation(unsigned highestGenomeLocatonToKeep)
{
for (; tail != head && buffer[tail].genomeLocation > highestGenomeLocatonToKeep; tail = (tail + 1) % bufferSize) {
// This loop body intentionally left blank.
}
}
HitLocation *getTail(unsigned *index) {
if (head == tail) return NULL;
*index = tail;
return &buffer[tail];
}
HitLocation *getTail() {
if (head == tail) return NULL;
return &buffer[tail];
}
HitLocation *getHead() {
if (head == tail) return NULL;
//
// Recall that head is the next place to write, so it's not filled in yet.
// Use the previous element.
//
return &buffer[(head + bufferSize - 1)% bufferSize];
}
HitLocation *getNext(unsigned *index) // Working from tail to head
{
if ((*index + 1) % bufferSize == head) return NULL;
*index = (*index + 1) % bufferSize;
return &buffer[*index];
}
private:
unsigned bufferSize;
unsigned head;
unsigned tail;
HitLocation *buffer;
};
char *rcReadData[NUM_READS_PER_PAIR]; // the reverse complement of the data for each read
char *rcReadQuality[NUM_READS_PER_PAIR]; // the reversed quality strings for each read
unsigned readLen[NUM_READS_PER_PAIR];
Read *reads[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; // These are the reads that are provided in the align call, together with their reverse complements, which are computed.
Read rcReads[NUM_READS_PER_PAIR][NUM_DIRECTIONS];
char *reversedRead[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; // The reversed data for each read for forward and RC. This is used in the backwards LV
LandauVishkin<> *landauVishkin;
LandauVishkin<-1> *reverseLandauVishkin;
char rcTranslationTable[256];
unsigned nTable[256];
BYTE *seedUsed;
inline bool IsSeedUsed(unsigned indexInRead) const {
return (seedUsed[indexInRead / 8] & (1 << (indexInRead % 8))) != 0;
}
inline void SetSeedUsed(unsigned indexInRead) {
seedUsed[indexInRead / 8] |= (1 << (indexInRead % 8));
}
//
// "Local probability" means the probability that each end is correct given that the pair itself is correct.
// Consider the example where there's exactly one decent match for one read, but the other one has several
// that are all within the correct range for the first one. Then the local probability for the second read
// is lower than the first. The overall probability of an alignment then is
// pairProbability * localProbability/ allPairProbability.
//
double localBestPairProbability[NUM_READS_PER_PAIR];
void scoreLocation(
unsigned whichRead,
Direction direction,
unsigned genomeLocation,
unsigned seedOffset,
unsigned scoreLimit,
unsigned *score,
double *matchProbability,
int *genomeLocationOffset // The computed offset for genomeLocation (which is needed because we scan several different possible starting locations)
);
//
// These are used to keep track of places where we should merge together candidate locations for MAPQ purposes, because they're sufficiently
// close in the genome.
//
struct MergeAnchor {
double matchProbability;
unsigned locationForReadWithMoreHits;
unsigned locationForReadWithFewerHits;
int pairScore;
void init(unsigned locationForReadWithMoreHits_, unsigned locationForReadWithFewerHits_, double matchProbability_, int pairScore_) {
locationForReadWithMoreHits = locationForReadWithMoreHits_;
locationForReadWithFewerHits = locationForReadWithFewerHits_;
matchProbability = matchProbability_;
pairScore = pairScore_;
}
//
// Returns whether this candidate is a match for this merge anchor.
//
bool doesRangeMatch(unsigned newMoreHitLocation, unsigned newFewerHitLocation) {
unsigned deltaMore = DistanceBetweenGenomeLocations(locationForReadWithMoreHits, newMoreHitLocation);
unsigned deltaFewer = DistanceBetweenGenomeLocations(locationForReadWithFewerHits, newFewerHitLocation);
return deltaMore < 50 && deltaFewer < 50;
}
//
// Returns true and sets oldMatchProbability if this should be eliminated due to a match.
//
bool checkMerge(unsigned newMoreHitLocation, unsigned newFewerHitLocation, double newMatchProbability, int newPairScore,
double *oldMatchProbability);
};
//
// We keep track of pairs of locations to score using two structs, one for each end. The ends for the read with fewer hits points into
// a list of structs for the end with more hits, so that we don't need one stuct for each pair, just one for each end, and also so that
// we don't need to score the mates more than once if they could be paired with more than one location from the end with fewer hits.
//
struct ScoringMateCandidate {
//
// These are kept in arrays in decreasing genome order, one for each set pair, so you can find the next largest location by just looking one
// index lower, and vice versa.
//
double matchProbability;
unsigned readWithMoreHitsGenomeLocation;
unsigned bestPossibleScore;
unsigned score;
unsigned scoreLimit; // The scoreLimit with which score was computed
unsigned seedOffset;
int genomeOffset;
void init(unsigned readWithMoreHitsGenomeLocation_, unsigned bestPossibleScore_, unsigned seedOffset_) {
readWithMoreHitsGenomeLocation = readWithMoreHitsGenomeLocation_;
bestPossibleScore = bestPossibleScore_;
seedOffset = seedOffset_;
score = -2;
scoreLimit = -1;
matchProbability = 0;
genomeOffset = 0;
}
};
struct ScoringCandidate {
ScoringCandidate * scoreListNext; // This is a singly-linked list
MergeAnchor * mergeAnchor;
unsigned scoringMateCandidateIndex; // Index into the array of scoring mate candidates where we should look
unsigned readWithFewerHitsGenomeLocation;
unsigned whichSetPair;
unsigned seedOffset;
unsigned bestPossibleScore;
void init(unsigned readWithFewerHitsGenomeLocation_, unsigned whichSetPair_, unsigned scoringMateCandidateIndex_, unsigned seedOffset_,
unsigned bestPossibleScore_, ScoringCandidate *scoreListNext_)
{
readWithFewerHitsGenomeLocation = readWithFewerHitsGenomeLocation_;
whichSetPair = whichSetPair_;
_ASSERT(whichSetPair < NUM_SET_PAIRS); // You wouldn't think this would be necessary, but...
scoringMateCandidateIndex = scoringMateCandidateIndex_;
seedOffset = seedOffset_;
bestPossibleScore = bestPossibleScore_;
scoreListNext = scoreListNext_;
mergeAnchor = NULL;
}
};
//
// A pool of scoring candidates. For each alignment call, we free them all by resetting lowestFreeScoringCandidatePoolEntry to 0,
// and then fill in the content when they're initialized. This means that for alignments with few candidates we'll be using the same
// entries over and over, so they're likely to be in the cache. We have maxK * maxSeeds * 2 of these in the pool, so we can't possibly run
// out. We rely on their being allocated in descending genome order within a set pair.
//
ScoringCandidate *scoringCandidatePool;
unsigned scoringCandidatePoolSize;
unsigned lowestFreeScoringCandidatePoolEntry;
//
// maxK + 1 lists of Scoring Candidates. The lists correspond to bestPossibleScore for the candidate and its best mate.
//
ScoringCandidate **scoringCandidates;
//
// The scoring mates. The each set scoringCandidatePoolSize / 2.
//
ScoringMateCandidate * scoringMateCandidates[NUM_SET_PAIRS];
unsigned lowestFreeScoringMateCandidate[NUM_SET_PAIRS];
//
// Merge anchors. Again, we allocate an upper bound number of them, which is the same as the number of scoring candidates.
//
MergeAnchor *mergeAnchorPool;
unsigned firstFreeMergeAnchor;
unsigned mergeAnchorPoolSize;
};
| [
"andrewmagis@gmail.com"
] | andrewmagis@gmail.com |
5b9814a86f6ec984bed3e937b631e4e1fb547a7e | d4c74a8001451840f3efb87f15856cdb9d5e9eb6 | /rtos/mbed-os/rtos/EventFlags.cpp | 1167d764ac5fdc63e4ab41bf3e94f5569ea61a97 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | danieldennett/gap_sdk | 3e4b4d187f03a28a761b08aed36a5e6a06f48e8d | 5667c899025a3a152dbf91e5c18e5b3e422d4ea6 | refs/heads/master | 2020-12-19T19:17:40.083131 | 2020-02-27T14:51:48 | 2020-02-27T14:51:48 | 235,814,026 | 1 | 0 | Apache-2.0 | 2020-01-23T14:39:59 | 2020-01-23T14:39:58 | null | UTF-8 | C++ | false | false | 2,460 | cpp | /* mbed Microcontroller Library
* Copyright (c) 2006-2017 ARM Limited
*
* 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 "rtos/EventFlags.h"
#include <string.h>
#include "mbed_error.h"
#include "mbed_assert.h"
namespace rtos {
EventFlags::EventFlags()
{
constructor();
}
EventFlags::EventFlags(const char *name)
{
constructor(name);
}
void EventFlags::constructor(const char *name)
{
osEventFlagsAttr_t attr = { 0 };
attr.name = name ? name : "application_unnamed_event_flags";
attr.cb_mem = &_obj_mem;
attr.cb_size = sizeof(_obj_mem);
_id = osEventFlagsNew(&attr);
MBED_ASSERT(_id);
}
uint32_t EventFlags::set(uint32_t flags)
{
return osEventFlagsSet(_id, flags);
}
uint32_t EventFlags::clear(uint32_t flags)
{
return osEventFlagsClear(_id, flags);
}
uint32_t EventFlags::get() const
{
return osEventFlagsGet(_id);
}
uint32_t EventFlags::wait_all(uint32_t flags, uint32_t millisec, bool clear)
{
return wait(flags, osFlagsWaitAll, millisec, clear);
}
uint32_t EventFlags::wait_any(uint32_t flags, uint32_t millisec, bool clear)
{
return wait(flags, osFlagsWaitAny, millisec, clear);
}
EventFlags::~EventFlags()
{
osEventFlagsDelete(_id);
}
uint32_t EventFlags::wait(uint32_t flags, uint32_t opt, uint32_t millisec, bool clear)
{
if (clear == false) {
opt |= osFlagsNoClear;
}
return osEventFlagsWait(_id, flags, opt, millisec);
}
}
| [
"noreply@github.com"
] | danieldennett.noreply@github.com |
7160ff685a62260b9bf78f0139f37f7f8e814383 | 084b38da37754392fae375c43d593be1c8b22bb7 | /bailian/4107.cpp | a70c14d31b630f53c3d0d8c0b05a6903fb524256 | [] | no_license | heliy/oj | 1b0c65f02f94ffb5c1ce44a95bc07144505fc141 | 4c5f97f30997f285e321b0ece53e85595bc641ff | refs/heads/master | 2021-01-25T06:36:37.454934 | 2016-01-14T13:42:21 | 2016-01-14T13:42:21 | 28,627,519 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | #include<iostream>
using namespace std;
bool isinclude(int p){
while(p > 10){
if(p%100 == 19){
return true;
}
p /= 10;
}
return false;
}
int main(){
int n, ni, p;
cin >> n;
for(ni = 0; ni < n; ni++){
cin >> p;
if(p%19 == 0 || isinclude(p)){
cout << "Yes" << endl;
}else{
cout << "No" << endl;
}
}
return 0;
}
| [
"ohhlyhly@gmail.com"
] | ohhlyhly@gmail.com |
5db154d54c27d2abf6e3d3062a4fdbec1a1f79dc | 60a2ce8ae0f155dedea181a76da169947508078b | /dprojectmanager/dmakestep.cpp | ddadfa846661827fbe744fdefaaf349ac3e53d7b | [] | no_license | RomulT/QtCreatorD | cc37724f386c8dff4dcfee1eb52843c2afea6a9f | eb2c8dfa4b31af731fdf848f550d5c3f824b3b41 | refs/heads/master | 2021-01-21T01:11:13.391350 | 2013-11-29T00:44:29 | 2013-11-29T00:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,481 | cpp | #include "dmakestep.h"
#include "dprojectmanagerconstants.h"
#include "dproject.h"
#include "ui_dmakestep.h"
#include "dbuildconfiguration.h"
#include "drunconfiguration.h"
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/gnumakeparser.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtparser.h>
#include <coreplugin/variablemanager.h>
#include <utils/stringutils.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QSettings>
using namespace Core;
using namespace ProjectExplorer;
using namespace DProjectManager;
namespace DProjectManager {
namespace Internal {
DMakeStep::DMakeStep(BuildStepList *parent) :
AbstractProcessStep(parent, Id(Constants::D_MS_ID)),
m_targetType(Executable), m_buildPreset(Debug)
{
ctor();
}
DMakeStep::DMakeStep(BuildStepList *parent, const Id id) :
AbstractProcessStep(parent, id),
m_targetType(Executable), m_buildPreset(Debug)
{
ctor();
}
DMakeStep::DMakeStep(BuildStepList *parent, DMakeStep *bs) :
AbstractProcessStep(parent, bs),
m_targetType(bs->m_targetType),
m_buildPreset(bs->m_buildPreset),
m_makeArguments(bs->m_makeArguments),
m_targetName(bs->m_targetName),
m_targetDirName(bs->m_targetDirName),
m_objDirName(bs->m_objDirName)
{
ctor();
}
void DMakeStep::ctor()
{
setDefaultDisplayName(QCoreApplication::translate("DProjectManager::Internal::DMakeStep",
Constants::D_MS_DISPLAY_NAME));
if(m_targetName.length() == 0)
m_targetName = project()->displayName();
QString bname = this->buildConfiguration()->displayName().toLower();
QString sep(QDir::separator());
if(m_targetDirName.length() == 0)
m_targetDirName = QLatin1String("bin") + sep + bname;
if(m_objDirName.length() == 0)
m_objDirName = QLatin1String("obj") + sep + bname;
if(m_makeArguments.length() == 0)
{
ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi();
if(abi.wordWidth() == 64)
m_makeArguments = QLatin1String("-m64");
}
}
DMakeStep::~DMakeStep() { }
bool DMakeStep::init()
{
BuildConfiguration *bc = buildConfiguration();
if (!bc)
bc = target()->activeBuildConfiguration();
m_tasks.clear();
ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
if (!tc) {
m_tasks.append(Task(Task::Error, tr("Qt Creator needs a compiler set up to build. Configure a compiler in the kit options."),
Utils::FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
return true; // otherwise the tasks will not get reported
}
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
pp->setWorkingDirectory(bc->buildDirectory().toString());
Utils::Environment env = bc->environment();
// Force output to english for the parsers. Do this here and not in the toolchain's
// addToEnvironment() to not screw up the users run environment.
env.set(QLatin1String("LC_ALL"), QLatin1String("C"));
pp->setEnvironment(env);
pp->setCommand(makeCommand(bc->environment()));
pp->setArguments(allArguments());
pp->resolveAll();
setOutputParser(new GnuMakeParser());
IOutputParser *parser = target()->kit()->createOutputParser();
if (parser)
appendOutputParser(parser);
outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
return AbstractProcessStep::init();
}
QVariantMap DMakeStep::toMap() const
{
QVariantMap map = AbstractProcessStep::toMap();
map.insert(QLatin1String(Constants::INI_TARGET_TYPE_KEY), m_targetType);
map.insert(QLatin1String(Constants::INI_BUILD_PRESET_KEY), m_buildPreset);
map.insert(QLatin1String(Constants::INI_TARGET_NAME_KEY), m_targetName);
map.insert(QLatin1String(Constants::INI_TARGET_DIRNAME_KEY), m_targetDirName);
map.insert(QLatin1String(Constants::INI_OBJ_DIRNAME_KEY), m_objDirName);
map.insert(QLatin1String(Constants::INI_MAKE_ARGUMENTS_KEY), m_makeArguments);
return map;
}
bool DMakeStep::fromMap(const QVariantMap &map)
{
m_targetType = (TargetType)map.value(QLatin1String(Constants::INI_TARGET_TYPE_KEY)).toInt();
m_buildPreset = (BuildPreset)map.value(QLatin1String(Constants::INI_BUILD_PRESET_KEY)).toInt();
m_targetName = map.value(QLatin1String(Constants::INI_TARGET_NAME_KEY)).toString();
m_targetDirName = map.value(QLatin1String(Constants::INI_TARGET_DIRNAME_KEY)).toString();
m_objDirName = map.value(QLatin1String(Constants::INI_OBJ_DIRNAME_KEY)).toString();
m_makeArguments = map.value(QLatin1String(Constants::INI_MAKE_ARGUMENTS_KEY)).toString();
return BuildStep::fromMap(map);
}
QString DMakeStep::makeCommand(const Utils::Environment &environment) const
{
ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
if (tc)
return tc->makeCommand(environment);
else
return QLatin1String("dmd");
}
QString DMakeStep::allArguments() const
{
QString bname = this->buildConfiguration()->displayName().toLower();
QString args;
if(m_buildPreset == Debug)
args += QLatin1String("-debug -gc");
else if(m_buildPreset == Unittest)
args += QLatin1String("-debug -gc -unittest");
else if(m_buildPreset == Release)
args += QLatin1String(" -release -O -inline");
if(m_targetType == StaticLibrary)
args += QLatin1String(" -lib");
else if(m_targetType == SharedLibrary)
args += QLatin1String(" -shared -fPIC");
QDir buildDir(this->buildConfiguration()->buildDirectory().toString());
QString projDir = project()->projectDirectory();
QString relTargetDir = m_targetDirName;
if(QDir(m_targetDirName).isRelative())
relTargetDir = buildDir.relativeFilePath(projDir + QDir::separator() + m_targetDirName);
if(relTargetDir.length() == 0)
relTargetDir = QLatin1String(".");
QString outFile = outFileName();
QString makargs = m_makeArguments;
makargs.replace(QLatin1String("%{TargetDir}"),relTargetDir);
Utils::QtcProcess::addArgs(&args, makargs);
Utils::QtcProcess::addArgs(&args, QLatin1String("-of") + relTargetDir + QDir::separator() + outFile);
if(QDir(m_objDirName).isRelative())
{
QString relDir = buildDir.relativeFilePath(projDir + QDir::separator() + m_objDirName);
if(relDir.length() > 0)
Utils::QtcProcess::addArgs(&args, QLatin1String("-od") + relDir);
}
DProject* proj = static_cast<DProject*>(project());
// Libs
QStringList libs = proj->libraries().split(QLatin1Char(' '), QString::SkipEmptyParts);
foreach(QString s, libs)
{
s = s.replace(QLatin1String("%{TargetDir}"),relTargetDir);
if(s.startsWith(QLatin1String("-L")))
Utils::QtcProcess::addArgs(&args, s);
else
Utils::QtcProcess::addArgs(&args, QLatin1String("-L-l") + s);
}
// Includes
QStringList incs = proj->includes().split(QLatin1Char(' '), QString::SkipEmptyParts);
foreach(QString s, incs)
{
s = s.replace(QLatin1String("%{TargetDir}"),relTargetDir);
if(s.startsWith(QLatin1String("-I")))
Utils::QtcProcess::addArgs(&args, s);
else
Utils::QtcProcess::addArgs(&args, QLatin1String("-I") + s);
}
// Extra Args
makargs = proj->extraArgs();
Utils::QtcProcess::addArgs(&args, makargs.replace(QLatin1String("%{TargetDir}"),relTargetDir));
// Files
static QLatin1String dotd(".d");
static QLatin1String dotdi(".di");
static QLatin1String space(" ");
QString srcs = QLatin1String(" ");
const QHash<QString,QString>& files = static_cast<DProject*>(project())->files();
foreach(QString file, files.values())
if(file.endsWith(dotd) || file.endsWith(dotdi))
srcs.append(file).append(space);
Utils::QtcProcess::addArgs(&args, srcs);
return args;
}
QString DMakeStep::outFileName() const
{
QString outName = m_targetName;
if(m_targetType > 0)
{
QString fix = QLatin1String("lib");
if(outName.startsWith(fix) == false)
outName = fix + outName;
if(m_targetType == StaticLibrary)
fix = QLatin1String(".a");
else if(m_targetType == SharedLibrary)
fix = QLatin1String(".so");
if(outName.endsWith(fix) == false)
outName.append(fix);
}
return outName;
}
void DMakeStep::run(QFutureInterface<bool> &fi)
{
bool canContinue = true;
foreach (const Task &t, m_tasks)
{
addTask(t);
canContinue = false;
}
if (!canContinue)
{
emit addOutput(tr("Configuration is faulty. Check the Issues view for details."), BuildStep::MessageOutput);
fi.reportResult(false);
emit finished();
return;
}
//processParameters()->setWorkingDirectory(project()->projectDirectory());
AbstractProcessStep::run(fi);
}
void DMakeStep::stdError(const QString &line)
{
QString res = line;
try
{
QProcess proc;
proc.setProcessChannelMode(QProcess::MergedChannels);
proc.start(QLatin1String("ddemangle"));
if (!proc.waitForStarted(10000))
return;
proc.write(line.toUtf8());
proc.closeWriteChannel();
if(!proc.waitForFinished(2000))
{
proc.close();
return;
}
else if(proc.exitCode() != 0)
{
proc.close();
return;
}
else
{
res = QString::fromUtf8(proc.readAllStandardOutput());
proc.close();
}
}
catch(...){}
AbstractProcessStep::stdError(res);
}
BuildStepConfigWidget *DMakeStep::createConfigWidget()
{
return new DMakeStepConfigWidget(this);
}
bool DMakeStep::immutable() const
{
return false;
}
//-------------------------------------------------------------------------
//-- DMakeStepConfigWidget
//-------------------------------------------------------------------------
DMakeStepConfigWidget::DMakeStepConfigWidget(DMakeStep *makeStep)
: m_makeStep(makeStep)
{
Project *pro = m_makeStep->target()->project();
m_ui = new Ui::DMakeStep;
m_ui->setupUi(this);
m_ui->targetTypeComboBox->addItem(QLatin1String("Executable"));
m_ui->targetTypeComboBox->addItem(QLatin1String("Static Library"));
m_ui->targetTypeComboBox->addItem(QLatin1String("Shared Library"));
m_ui->buildPresetComboBox->addItem(QLatin1String("Debug"));
m_ui->buildPresetComboBox->addItem(QLatin1String("Release"));
m_ui->buildPresetComboBox->addItem(QLatin1String("Unittest"));
m_ui->buildPresetComboBox->addItem(QLatin1String("None"));
m_ui->targetTypeComboBox->setCurrentIndex((int)m_makeStep->m_targetType);
m_ui->buildPresetComboBox->setCurrentIndex((int)m_makeStep->m_buildPreset);
m_ui->makeArgumentsLineEdit->setPlainText(m_makeStep->m_makeArguments);
m_ui->targetNameLineEdit->setText(m_makeStep->m_targetName);
m_ui->targetDirLineEdit->setText(m_makeStep->m_targetDirName);
m_ui->objDirLineEdit->setText(m_makeStep->m_objDirName);
updateDetails();
connect(m_ui->targetTypeComboBox, SIGNAL(currentIndexChanged (int)),
this, SLOT(targetTypeComboBoxSelectItem(int)));
connect(m_ui->buildPresetComboBox, SIGNAL(currentIndexChanged (int)),
this, SLOT(buildPresetComboBoxSelectItem(int)));
connect(m_ui->targetNameLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(targetNameLineEditTextEdited()));
connect(m_ui->targetDirLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(targetDirNameLineEditTextEdited()));
connect(m_ui->objDirLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(objDirLineEditTextEdited()));
connect(m_ui->makeArgumentsLineEdit, SIGNAL(textChanged()),
this, SLOT(makeArgumentsLineEditTextEdited()));
connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
this, SLOT(updateDetails()));
connect(pro, SIGNAL(environmentChanged()),
this, SLOT(updateDetails()));
connect(m_makeStep->buildConfiguration(), SIGNAL(buildDirectoryChanged()),
this, SLOT(updateDetails()));
connect(m_makeStep->buildConfiguration(), SIGNAL(configurationChanged()),
this, SLOT(updateDetails()));
}
DMakeStepConfigWidget::~DMakeStepConfigWidget()
{
delete m_ui;
}
QString DMakeStepConfigWidget::displayName() const
{
return tr("Make", "D Makestep");
}
void DMakeStepConfigWidget::updateDetails()
{
BuildConfiguration *bc = m_makeStep->buildConfiguration();
if (!bc)
bc = m_makeStep->target()->activeBuildConfiguration();
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setWorkingDirectory(bc->buildDirectory().toString());
param.setEnvironment(bc->environment());
param.setCommand(m_makeStep->makeCommand(bc->environment()));
param.setArguments(m_makeStep->allArguments());
m_summaryText = param.summary(displayName());
emit updateSummary();
foreach(RunConfiguration* rc, m_makeStep->target()->runConfigurations())
{
DRunConfiguration * brc = dynamic_cast<DRunConfiguration *>(rc);
if(brc)
brc->updateConfig(m_makeStep);
}
}
QString DMakeStepConfigWidget::summaryText() const
{
return m_summaryText;
}
void DMakeStepConfigWidget::targetTypeComboBoxSelectItem(int index)
{
m_makeStep->m_targetType = (DMakeStep::TargetType)index;
updateDetails();
}
void DMakeStepConfigWidget::buildPresetComboBoxSelectItem(int index)
{
m_makeStep->m_buildPreset = (DMakeStep::BuildPreset)index;
updateDetails();
}
void DMakeStepConfigWidget::makeArgumentsLineEditTextEdited()
{
m_makeStep->m_makeArguments = m_ui->makeArgumentsLineEdit->toPlainText();
updateDetails();
}
void DMakeStepConfigWidget::targetNameLineEditTextEdited()
{
m_makeStep->m_targetName = m_ui->targetNameLineEdit->text();
updateDetails();
}
void DMakeStepConfigWidget::targetDirNameLineEditTextEdited()
{
m_makeStep->m_targetDirName = m_ui->targetDirLineEdit->text();
updateDetails();
}
void DMakeStepConfigWidget::objDirLineEditTextEdited()
{
m_makeStep->m_objDirName = m_ui->objDirLineEdit->text();
updateDetails();
}
//--------------------------------------------------------------------------
//-- DMakeStepFactory
//--------------------------------------------------------------------------
DMakeStepFactory::DMakeStepFactory(QObject *parent) :
IBuildStepFactory(parent)
{
}
bool DMakeStepFactory::canCreate(BuildStepList *parent, const Id id) const
{
if (parent->target()->project()->id() == Constants::DPROJECT_ID)
return id == Constants::D_MS_ID;
return false;
}
BuildStep *DMakeStepFactory::create(BuildStepList *parent, const Id id)
{
if (!canCreate(parent, id))
return 0;
DMakeStep *step = new DMakeStep(parent);
return step;
}
bool DMakeStepFactory::canClone(BuildStepList *parent, BuildStep *source) const
{
return canCreate(parent, source->id());
}
BuildStep *DMakeStepFactory::clone(BuildStepList *parent, BuildStep *source)
{
if (!canClone(parent, source))
return 0;
DMakeStep *old(qobject_cast<DMakeStep *>(source));
Q_ASSERT(old);
return new DMakeStep(parent, old);
}
bool DMakeStepFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
BuildStep *DMakeStepFactory::restore(BuildStepList *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
DMakeStep *bs(new DMakeStep(parent));
if (bs->fromMap(map))
return bs;
delete bs;
return 0;
}
QList<Id> DMakeStepFactory::availableCreationIds(BuildStepList *parent) const
{
if (parent->target()->project()->id() == Constants::DPROJECT_ID)
return QList<Id>() << Id(Constants::D_MS_ID);
return QList<Id>();
}
QString DMakeStepFactory::displayNameForId(const Id id) const
{
if (id == Constants::D_MS_ID)
return QCoreApplication::translate("DProjectManager::Internal::DMakeStep",
Constants::D_MS_DISPLAY_NAME);
return QString();
}
} // namespace Internal
} // namespace DProjectManager
| [
"goldmax3000@gmail.com"
] | goldmax3000@gmail.com |
3111c81f82b06d42ab86f07b34c1be1c980bd8f7 | 1aaeaeaf042529cb0e5b551cde992c91e501e46c | /lab1/src/presenter.cpp | 04c12a4e39469c3072eec53e9a1fe40cd1a8787d | [] | no_license | Kazeshirou/ppo | 17c3371de5a2f9d06a1a6cedd738b98fa52d0576 | b857fb8ba6b6cf712e4b365911ace4d7f814a1dc | refs/heads/master | 2020-03-09T06:03:02.540815 | 2018-05-31T13:51:57 | 2018-05-31T13:51:57 | 128,628,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,385 | cpp | #include "presenter.h"
#include "model.h"
#include "mainwindow.h"
Presenter::Presenter(Model *model, MainWindow *view, QObject *parent) :
QObject(parent),
m_model(model),
m_view(view)
{
if (!model)
m_model = new Model(this);
if (!view)
m_view = new MainWindow();
m_view->show();
connect(m_view, SIGNAL(s_fromFile(QStringList)), this, SLOT(addRoutesFromFile(QStringList)));
connect(m_view, SIGNAL(s_fromPolyline(QString)), this, SLOT(addRouteFromPolyline(QString)));
connect(m_view, SIGNAL(s_insertRoute(int)), this, SLOT(createRoute(int)));
connect(m_view, SIGNAL(s_deleteRoute(int)), this, SLOT(removeRoute(int)));
connect(m_view, SIGNAL(s_insertCoordinate(int, int)), this, SLOT(createCoordinate(int, int)));
connect(m_view, SIGNAL(s_deleteCoordinate(int, int)), this, SLOT(removeCoordinate(int, int)));
connect(m_view, SIGNAL(s_changeCurrentRoute(int)), this, SLOT(routeChanged(int)));
connect(m_view, SIGNAL(s_changeRoute(int, QString)), this, SLOT(editRouteName(int, QString)));
connect(m_view, SIGNAL(s_changeCoordinate(int, int, int, double)), this, SLOT(editCoordinate(int, int, int, double)));
connect(m_view, SIGNAL(s_redo()), this, SLOT(redo()));
connect(m_view, SIGNAL(s_undo()), this, SLOT(undo()));
connect(m_model, SIGNAL(s_routeCreated(GeoRoute, int)), this, SLOT(insertRoute(GeoRoute, int)));
connect(m_model, SIGNAL(s_routeRemoved(int)), this, SLOT(deleteRoute(int)));
connect(m_model, SIGNAL(s_coordinateCreated(QGeoCoordinate, int, int)), this, SLOT(insertCoordinate(QGeoCoordinate, int, int)));
connect(m_model, SIGNAL(s_coordinateRemoved(int, int)), this, SLOT(deleteCoordinate(int, int)));
connect(m_model, SIGNAL(s_polylineChanged(QString)), this, SLOT(changePolyline(QString)));
connect(m_model, SIGNAL(s_chartChanged(QLineSeries*)), this, SLOT(changeChart(QLineSeries*)));
connect(m_model, SIGNAL(s_nameChanged(QString, int)), this, SLOT(changeRouteName(QString, int)));
connect(m_model, SIGNAL(s_coordinateChanged(double, int, int, int)), this, SLOT(changeCoordinate(double, int, int, int)));
connect(m_model, SIGNAL(s_lengthChanged(int, double)), this, SLOT(changeRouteLength(int, double)));
m_model->loadFromSave();
}
void Presenter::addRoutesFromFile(const QStringList files)
{
if (files.length())
m_model->addRoutesFromFiles(files);
}
void Presenter::addRouteFromPolyline(const QString polyline)
{
if (polyline.length())
m_model->addRouteFromPolyline(polyline);
}
void Presenter::createRoute(int index)
{
m_model->createRoute(index, GeoRoute());
}
void Presenter::createCoordinate(int route, int index)
{
m_model->createCoordinate(route, index);
}
void Presenter::removeCoordinate(int route, int index)
{
m_model->removeCoordinate(route, index);
}
void Presenter::removeRoute(int index)
{
m_model->removeRoute(index);
}
void Presenter::editRouteName(int index, QString name)
{
m_model->editRouteName(index, name);
}
void Presenter::editCoordinate(int route, int index, int column, double newvalue)
{
m_model->editCoordinate(route, index, column, newvalue);
}
void Presenter::insertRoute(const GeoRoute route, int index)
{
m_view->insertRoute(route, index);
}
void Presenter::deleteRoute(int index)
{
m_view->deleteRoute(index);
}
void Presenter::insertCoordinate(const QGeoCoordinate coordinate, int route, int index)
{
m_view->insertCoordinate(coordinate, route, index);
}
void Presenter::deleteCoordinate(int route, int index)
{
m_view->deleteCoordinate(route, index);
}
void Presenter::changePolyline(QString s)
{
m_view->changePolyline(s);
}
void Presenter::changeChart(QLineSeries *s)
{
m_view->changeChart(s);
}
void Presenter::changeRouteLength(int index, double l)
{
m_view->changeRouteLength(index, l);
}
void Presenter::routeChanged(int route)
{
changePolyline(m_model->getPolyline(route));
QLineSeries *s = m_model->createSeries(route);
changeChart(s);
}
void Presenter::changeRouteName(QString newname, int index)
{
m_view->changeRoute(index, newname);
}
void Presenter::changeCoordinate(double newvalue, int route, int index, int column)
{
m_view->changeCoordinate(route, index, column, newvalue);
}
void Presenter::redo()
{
m_model->redo();
}
void Presenter::undo()
{
m_model->undo();
}
| [
"zhar97@yandex.ru"
] | zhar97@yandex.ru |
793924f54678062210743cb951bde173227436b6 | 7e8a447adcf729b84027790eb40aff46aa5002f4 | /hlogicprop.cpp | a7460756ccf806e2f92b04fca47bfc74f9b5a90e | [] | no_license | rcswhuang/rule | de6abad08268a140ec1714092ed3d77f9a818459 | 27b98cdb05d4b7536dc49be5e5e0921cb1eac132 | refs/heads/master | 2021-06-05T13:43:43.672386 | 2018-10-14T13:33:11 | 2018-10-14T13:33:11 | 95,844,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include "hlogicprop.h"
#include "ui_logicprop.h"
#include "hdrawobj.h"
HLogicProp::HLogicProp(HDrawObj* drawObj,QWidget *parent) :
m_pDrawObj(drawObj),QDialog(parent),
ui(new Ui::HLogicProp)
{
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(ok_clicked()));
initLogicProp();
}
HLogicProp::~HLogicProp()
{
delete ui;
}
void HLogicProp::initLogicProp()
{
for(int i = 2; i <=30;i++)
{
QString strInput = QString("输入%1").arg(i);
ui->comboBox->addItem(strInput,i);
}
int nInputSum = m_pDrawObj->m_nInPointSum;
ui->comboBox->setCurrentIndex(ui->comboBox->findData(nInputSum));
}
void HLogicProp::ok_clicked()
{
int nSum = ui->comboBox->currentData().toInt();
if(nSum == m_pDrawObj->m_nInPointSum) return;
int oneh = m_pDrawObj->m_pointIn[1].y() - m_pDrawObj->m_pointIn[0].y();
m_pDrawObj->m_rectCurPos.setBottom(m_pDrawObj->m_rectCurPos.top() + oneh*(nSum+4));
m_pDrawObj->m_nInPointSum = nSum;
QDialog::accept();
}
| [
"rcswhuang@163.com"
] | rcswhuang@163.com |
10f40e7099913bd4dc177cdcfaaf176c00886072 | 0c02367803ca9b3eea6a3f226eb9124c4d6ea26d | /Chapter_09/dynamic_saerch.cpp | 03bfabc95759117cb2c7456f46310dcdd7137397 | [] | no_license | jerrychaolee/dsac | 370344e5459572f95f2ab7ecd4690a644969ee9e | 40420318b2ad28c67149bc150e0ceb62a44a8857 | refs/heads/master | 2020-04-04T13:22:24.834878 | 2018-12-14T15:43:47 | 2018-12-14T15:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,216 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "dynamic_search.h"
//在根指针T所指二叉树中递归地查找某关键字等于key的数组元素,
//若查找成功, 则返回指向该数据元素结点的的指针,否则返回空指针
BiTree SearchBST(BiTree T, KeyType key)
{
if (!T || EQ(key, T->data.key))
return (T); //查找结束
else if (LT(key, T->data.key))
return (SearchBST(T->lchild, key)); //在右子树中继续查找
else
return (SearchBST(T->rchild, key));
}
//在根指针T所指二叉排序树中递归地查找其中关键字等于key的数据元素,若查找成功
//则指针p指向该数据元素结点,并返回TRUE,否则p指向查找路径上访问的
//最后一个结点并返回FALSE,指针f指向T的双亲,其初始值调用为NULL
Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree &p)
{
if (!T) {
p = f;
return FALSE; //查找不成功
}
else if (EQ(key, T->data.key)) {
p = T;
return TRUE; //查找成功
}
else if (LT(key, T->data.key))
return SearchBST(T->lchild, key, T, p); //在左子树中继续查找
else
return SearchBST(T->rchild, key, T, p); //在右子树中继续查找
}
//当二叉排序树T中不存在关键字等于e.key的元素时,插入e并返回TRUE,
//否则返回FALSE
Status InsertBST(BiTree &T, ElemType e)
{
BiTree p;
BiTNode *s;
if (!SearchBST(T, e.key, NULL, p)) { //查找文件
s = (BiTNode *)malloc(sizeof(BiTNode)); //新建一个要插入的结点
s->data = e;
s->lchild = NULL;
s->rchild = NULL;
if (p == NULL) //新插入的结点为根结点
T = s;
else if (LT(e.key, p->data.key)) //插入到左子树
p->lchild = s;
else //插入到右子树
p->rchild = s;
return OK;
}
else
return ERROR;
}
//若二叉排序树T中存在关键字等于key的数据元素时,则删除该数据元素的结点
//并返回TRUE,否则返回FALSE
Status DeleteBST(BiTree &T, KeyType key)
{
if (!T)
return FALSE; //不存在关键字等于key的数据元素
else {
if (EQ(key, T->data.key)) //找到关键字等于key的数据元素
return Delete(T);
else if(LT(key, T->data.key))
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
//从二叉排序树中删除结点p,并重新接他的左右子树
Status Delete(BiTree &p)
{
BiTree q, s;
if (!p->rchild) { //右子树空则只需要重接它的左子树
q = p;
p = p->lchild;
free(q);
}
else if (!p->lchild) { //左子树为空则只需要重接它的右子树
q = p;
p = p->rchild;
free(q);
}
else { //左右子树均不空
q = p;
s = p->lchild;
while (s->rchild) {
q = s;
s = s->lchild; //左转,然后向右走到尽头
}
p->data = s->data; //s指向被删结点的“前驱”
if (q != p)
q->rchild = s->lchild; //重接*q的右子树
else
q->lchild = s->lchild; //重接*q的左子树
delete s;
}
return TRUE;
}
//对以*p为根的二叉排序树作右旋处理,处理之后p指向新的树的根结点
//即旋转处理之前的左子树的根结点
void R_Rotate(BSTree &p)
{
BSTree lc;
lc = p->lchild; //lc指向的*p的左子树根结点
p->lchild = lc->rchild; //lc的右子树挂在p的左子树下
lc->rchild = p; //p挂在lc的左子树下
p = lc; //p指向新的根结点
}
//对以*p为根的二叉排序树作左旋处理,处理之后p指向新的树的根结点
//即旋转处理之前的右子树的根结点
void L_Rotate(BSTree &p)
{
BSTree rc;
rc = p->rchild;
p->rchild = rc->lchild;
rc->lchild = p;
p = rc;
}
//算法9.11,若平衡的二叉排序树T中不存在和e有相同关键字的结点,则插入一个数据元素为e
//的结点,并返回1,否则返回0,若因此插入而使二叉排序树失去平衡,则作平衡旋转处理,
//taller指示树的深度是否增加。用递归的方法寻找要插入的位置,并检测平衡度以做出相应的
//旋转的变化,但因为旋转之后树的深度其实和插入前是没有变化的,
//所以整个递归过程中其实只有最小非平衡子树需要作旋转平衡操作,其余结点都无需作旋转操作。
Status InsertAVL(BSTree &T, ElemType e, Boolean &taller)
{
if(T == NULL){ //空树,插入结点e,树深度增加,置taller为true
T->data = e;
T->lchild = NULL;
T->rchild = NULL;
T->bf = EH;
taller = true;
}
else{
if(EQ(e.key, T->data.key)) { //树中存在该元素,则不再插入
taller = false;
return 0;
}
else if (LT(e.key, T->data.key)) { //元素小于根结点,则应在根结点左子树中继续寻找
if (InsertAVL(T->lchild, e, taller))
return 0; //左子树中有该元素,则未插入
else { //该元素插入到左子树中
if (taller) { //已插入以左子树且左子树深度增加,子树不增高的情况不需要考虑
switch (T->bf) { //检查T的平衡度
case LH: //原本左子树比右子树高,需要作左平衡处理
LeftBalance(T);
taller = false;
break;
case EH: //原本左右子树等高,现因左子树增高使树增高
T->bf = LH;
taller = true;
break;
case RH: //原本右子树高,现左右子树等高,树高不增加
T->bf = EH;
taller = false;
break;
default:
break;
}
}
}
}
else { //应在T的右子树中进行搜索
if(InsertAVL(T->rchild, e, taller))
return 0; //未插入
else {
if (taller) { //已插入到右子树且右子树长高
switch(T->bf) { //检查T的平衡度
case LH:
T->bf = EH;
taller = false;
break;
case EH:
T->bf = RH;
taller = true;
break;
case RH: //需要作右平衡处理
RightBalance(T);
taller = false;
break;
}
}
}
}
}
return 1;
}
//对以指针T所指结点为根的二叉树作左平衡处理,本算法结束时,指针T指向
//新的根结点;
//左平衡操作是指当T的左子树的深度与右子树深度之差大于2时所需要作出的操作。
void LeftBalance(BSTree &T)
{
BSTree lc, rd;
lc = T->rchild; //lc指向T的左子树根结点
switch (lc->bf) { //检查T的左子树的平衡度
case LH: //新节点插入在T的左孩子的左子树上,要做单右旋处理
T->bf = lc->bf = EH;
R_Rotate(T);
break;
case RH: //新结点插入在T的左孩子的右子树上,要作双旋处理
rd = lc->rchild; //rd指向T的左孩子的右子树的根
switch (rd->bf) { //修改T以及其左孩子的平衡因子
case LH:
T->bf = RH;
lc->bf = EH;
break;
case EH:
T->bf = EH;
lc->bf = EH;
break;
case RH:
T->bf = EH;
lc->bf = LH;
break;
}
rd->bf = EH;
L_Rotate(T->lchild);
R_Rotate(T);
}
}
//对以指针T所指结点为根的二叉树作右平衡处理,本算法结束时,指针T指向新的根结点
void RightBalance(BSTree &T)
{
BSTree rc, ld;
rc = T->rchild; //rc指向T的右子树根结点
switch (rc->bf) { //检查T的右子树的平衡度
case RH: //新结点插入在T的右孩子的右子树上,要作单左旋处理
T->bf = rc->bf = EH;
L_Rotate(T);
break;
case LH: //新结点插入在T的右孩子的左子树上,要作双旋处理
ld = rc->lchild; //ld指向T的右孩子的左子树根结点
switch (ld->bf) {
case LH:
T->bf = EH;
rc->bf = RH;
break;
case EH:
T->bf = EH;
rc->bf = EH;
break;
case RH:
T->bf = LH;
rc->bf = EH;
break;
}
ld->bf = EH;
R_Rotate(T->rchild);
L_Rotate(T);
}
}
//在m阶B-树T上查找关键字K,返回结果(pt, i, tag),若查找成功,
//则特征值tag = 1,指针pt所指结点中第i个关键字等于K,否则特征值tag = 0,
//等于K的关键字应插入在指针pt所指结点中第i和第i+1个关键字之间。
Result SearchBTree(BTree T, KeyType K)
{
int i = 0;
Result r;
BTree p = T, q = NULL; //初始化,p指向待查结点,q指向p的双亲结点
bool found = false;
while (p != NULL && !found) {
i = Search(p, K); //在p->key[1...keynum]中查找
//i使得: p->key[i] <= K < key[i + 1]
if (i > 0 && K == p->Key[i]) { //找到待查结点
found = true;
}
else {
q = p;
p = p->ptr[i];
}
}
if (found) { //查找成功
r.pt = p;
r.i = i;
r.tag = 1;
}
else { //查找失败,返回K的插入位置信息
r.pt = q;
r.i = i;
r.tag = 0;
}
return r;
}
//在p->Key[1...keynum]中查找i,使p->Key[i] <= K < p->Key[i+1],当K < p->Key[1]时,
//i = 0, 返回找到的i.
int Search(BTree p, KeyType K)
{
int i, j;
if (K < p->Key[1])
i = 0;
else if (K >= p->Key[p->keynum])
i = p->keynum;
else {
for (j = 1; j <= ((p->keynum) - 1); ++j) {
if(K >= p->Key[j] && K < p->Key[j + 1]) {
i = j;
break;
}
}
}
return i;
}
//首先查找m阶B树上是否有关键字K,有则不插入,返回0,否则在m阶B-树插入关键字K
//并返回1,若引起结点过大,则沿双亲链进行必要的结点分裂调整,使T仍是m阶B-树。
Status InsertBTree(BTree &T, KeyType K)
{
int s; //要插入父结点中关键字的位置
KeyType x = K;
BTree ap = NULL; //分裂出的结点
bool finished = false; //分裂是否完成标志
Result res;
res = SearchBTree(T, K);
int i = res.i;
BTree q = res.pt; //插入位置
if (res.tag == 1)
return 0; //结点已存,无需插入
else {
while (q != NULL && !finished) {//要插入的结点不为空且分裂还没有完成
Insert(q, i, x, ap); //插入关键字x及指针ap到q->Key[i+1], q->ptr[i+1]
if(q->keynum < m) //结点大小合适,结束分裂
finished = true;
else { //分裂结点*q
s = (int)ceil(m / 2.0); //中间结点的位置,以s为界限分裂
split(q, s, ap); //将s前的关键字保留在q中,s后面的关键字分裂出去到新的结点ap中
x = q->Key[s];
q = q->parent;
if (q != NULL)
i = Search(q, x); //在双亲结点中查找插入x的位置
}
}
if (!finished) //T是空树,或者根结点已分裂
NewRoot(T, q, x, ap); //生成含信息(T, x, ap)的新的根结点*T,原T和ap为子树指针
return 1;
}
}
//将关键字x和指针ap分别插入到p->Key[i+1]和p->ptr[i+1]中,注意结点关键字大小
//p->keynum要加1.
Status Insert(BTree p, int i, KeyType x, BTree ap)
{
for (size_t j = p->keynum; j < i + 1; j--) {
p->Key[j + 1] = p->Key[j];
p->ptr[i + 1] = p->ptr[j];
}
p->Key[i + 1] = x;
p->ptr[i + 1] = ap;
p->keynum++;
if (ap != NULL)
ap->parent = p;
return OK;
}
//分裂结点*p,以s位置为分界分裂,ap->Key[] = p->Key[s+1...m],
//ap->ptr[] = p->ptr[s...m], p->Key[] = p->Key[1...s-1],
//p->ptr[] = p->ptr[0...s-1],注意修改新建结点ap的父结点。
Status split(BTree p, int s, BTree &ap)
{
int i, j;
p->keynum = s - 1;
ap = (BTree)malloc(sizeof(BTNode)); //分配一个新结点
for (i = s + 1, j = 1; i <= m; ++i, ++j)
ap->Key[j] = p->Key[i];
for (i = s, j = 0; i <= m; ++i, ++j) {
ap->ptr[j] = p->ptr[i];
if (ap->ptr[j] != NULL) //更新结点的父结点,这一个问题debug了好久,mark一个
ap->ptr[j]->parent = ap;
}
ap->keynum = m - s;
ap->parent = p->parent;
return OK;
}
//生成新的根结点, 根结点信息为Key[1] = x, ptr[0, 1] = (q, ap)
Status NewRoot(BTree &T, BTree q, KeyType x, BTree ap)
{
BTree root;
root = (BTree)malloc(sizeof(BTNode));
root->Key[1] = x;
root->ptr[0] = T;
root->ptr[1] = ap;
root->keynum = 1;
root->parent = NULL;
if (T != NULL)
T->parent = root;
if (ap != NULL)
ap->parent = root;
T = root;
return OK;
}
//用文件filename中的信息创建B-树,假设B-树中只有关键字信息。
Status CreateBTree(BTree &T, char *filename)
{
FILE *pf;
KeyType e;
pf = fopen(filename, "r");
if (pf == NULL) {
printf_s("打开文件%s失败!", filename);
return ERROR;
}
while (fscanf(pf, "%d", &e) != EOF)
InsertBTree(T, e);
fclose(pf);
return OK;
}
//打印B-树,按先序顺序
Status DisplayBTree(BTree T)
{
if (T != NULL) {
for (size_t i = 0; i < T->keynum; i++)
{
if (i < T->keynum) {
DisplayBTree(T->ptr[i]);
printf_s("%d", T->Key[i + 1]);
}
else {
DisplayBTree(T->ptr[i]);
}
}
}
return OK;
}
//在非空双链树T中查找关键字等于K的记录, 若存在,则返回指向该关键字的指针
//否则返回空指针
Record *SearchDLTree(DLTree T, KeysType K)
{
DLTree p;
p = T->first;
int i = 0;
while (p && i < K.num) {
while (p && p->symbol != K.ch[i])
p = p->next; //查找关键字的第i位
if (p && i < K.num - 1)
p = p->first; //准备查找下一位
++i;
} //查找结束
if (!p) //查找不成功
return NULL;
else //查找成功
return p->infoptr;
}
//在键树T中查找关键字等于K的记录
Record *SearchTrie(TrieTree T, KeysType K)
{
TrieTree p = T;
for (int i = 0; p && p->kind == BRANCH && i < K.num; p = p->bh.ptr[ord(K.ch[i])], ++i);
//ord求字符在字母表中的序号
if (p && p->kind == LEAF && p->lf.K.num == K.num && p->lf.K.ch == K.ch) //查找成功
return p->lf.infoptr;
else
return NULL;
}
int ord(char ch)
{
/* a-z:97-122
A-Z:65-90
0-9:48-57*/
int ord;
if (ch == '$')
ord = 0;
else if (ch >= 'a' && ch <= 'z')
ord = (int)ch - (int)'a' + 1;
else if (ch >= 'A' && ch <= 'Z')
ord = (int)ch - (int)'A' + 1;
else
ord = -1;
return ord;
} | [
"41637553+Sepheranix@users.noreply.github.com"
] | 41637553+Sepheranix@users.noreply.github.com |
4eeab07582975edb8042b0572d917390954228af | 521cd380cc7d29c7f023966aef757dd9f3353692 | /problems/3sum/app.cpp | 386c2c03cf7c35cb2b7b008b4765339e6149260b | [] | no_license | anhdeev/algorithms | 2159eab5b1b40c7aa276789b78dab45c71e15694 | 0fa25423ea3cf161f9a767da7cb03366d61195ad | refs/heads/master | 2023-08-24T12:09:31.932349 | 2021-10-26T07:01:18 | 2021-10-26T07:01:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,606 | cpp | #include "../common/base.h"
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
map<int, int> cache;
vector< vector<int> > result;
sort(nums.begin(), nums.end());
for(auto &num: nums) {
if(cache.count(num)==0) cache[num] = 0;
cache[num] += 1;
cout << num << "=" << cache[num] << endl;
}
int lastj = 100001, lasti=100001;
for(int i=0;i<nums.size();++i) {
if(nums[i]==lasti) continue;
else lasti=nums[i];
for(int j=i+1;j<nums.size();++j) {
int sum2 = -(nums[i] +nums[j]);
vector<int> v = {nums[i], nums[j], sum2};
if(nums[j]==lastj) continue;
else lastj=nums[j];
if(sum2 == nums[j]) {
if(cache[sum2] < 1) continue;
else if(nums[i]!=nums[j] && cache[sum2] > 1) result.push_back(v);
else if(nums[i]==nums[j] && cache[sum2]>2) result.push_back(v);
else continue;
} else if (sum2 < nums[j]) {
continue;
} else if(cache[sum2] > 0) {
result.push_back(v);
}
}
}
return result;
}
};
int main() {
Solution solution;
vector<int> nums = {0,0};
vector< vector <int> > result = solution.threeSum(nums);
for(auto v:result) {
for(auto item: v) {
cout << item << ",";
}
cout << endl;
}
return 0;
}
| [
"anhdv@merchize.com"
] | anhdv@merchize.com |
070853ffa495926ca07c4322211085e10469e4df | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_open_52b.cpp | b69099172f61eee74378064044ca74c0e0b7b144 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,443 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_open_52b.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-52b.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sink: open
* BadSink : Open the file named in data using open()
* Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#define OPEN _open
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif
namespace CWE36_Absolute_Path_Traversal__char_file_open_52
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void badSink_c(char * data);
void badSink_b(char * data)
{
badSink_c(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(char * data);
void goodG2BSink_b(char * data)
{
goodG2BSink_c(data);
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
4553c3790c9a1ef79771875195fe6be1f1c30dbb | 4541d0c5153d826781ad60594549d7cf0f830c42 | /game/include/Character.h | 504ac08096958b9f9c616efc8bae861479e93117 | [] | no_license | spidamoo/rlsa | 8c2ecf9afead0ea47885da47f69cf8bd9ed5f66e | 0edf612fb10fe64ec8c20937ca7ccbebcd04a4b9 | refs/heads/master | 2021-06-21T01:53:35.911619 | 2017-08-14T18:28:31 | 2017-08-14T18:28:31 | 100,297,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | h | #ifndef CHARACTER_H
#define CHARACTER_H
#include <Lib.h>
const char CHARACTER_MOVE_DIRECTION_IDLE = 0;
const char CHARACTER_MOVE_DIRECTION_RIGHT = 1;
const char CHARACTER_MOVE_DIRECTION_RIGHTDOWN = 2;
const char CHARACTER_MOVE_DIRECTION_DOWN = 3;
const char CHARACTER_MOVE_DIRECTION_LEFTDOWN = 4;
const char CHARACTER_MOVE_DIRECTION_LEFT = 5;
const char CHARACTER_MOVE_DIRECTION_LEFTUP = 6;
const char CHARACTER_MOVE_DIRECTION_UP = 7;
const char CHARACTER_MOVE_DIRECTION_RIGHTUP = 8;
const float CHARACTER_DIRECTION_SPEED_C[9][2] = {
{ 0.000f, 0.000f},
{ 1.000f, 0.000f},
{ 0.707f, 0.707f},
{ 0.000f, 1.000f},
{-0.707f, 0.707f},
{-1.000f, 0.000f},
{-0.707f, -0.707f},
{ 0.000f, -1.000f},
{ 0.707f, -0.707f}
};
class Character {
public:
Character(Game* game);
virtual ~Character();
void Update(float dt);
void Control(float dt);
void Draw();
float GetX();
float GetY();
protected:
Game* game;
float x, y;
IMeshSceneNode* node;
private:
};
#endif // CHARACTER_H
| [
"spidamoo@spidamoo.ru"
] | spidamoo@spidamoo.ru |
6c59c1a9ab78544db9b3a5d2fd44000122f6c3ce | 1d6abe27a802d53f7fbd6eb5e59949044cbb3b98 | /tensorflow/core/profiler/rpc/profiler_server.cc | b65621450d1292798c856ad3de21231b2bde983c | [
"Apache-2.0"
] | permissive | STSjeerasak/tensorflow | 6bc8bf27fb74fd51a71150f25dc1127129f70222 | b57499d4ec0c24adc3a840a8e7e82bd4ce0d09ed | refs/heads/master | 2022-12-20T20:32:15.855563 | 2020-09-29T21:22:35 | 2020-09-29T21:29:31 | 299,743,927 | 5 | 1 | Apache-2.0 | 2020-09-29T21:38:19 | 2020-09-29T21:38:18 | null | UTF-8 | C++ | false | false | 1,979 | cc | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/rpc/profiler_server.h"
#include <memory>
#include <string>
#include "grpcpp/grpcpp.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/profiler_service.grpc.pb.h"
#include "tensorflow/core/profiler/rpc/profiler_service_impl.h"
namespace tensorflow {
namespace profiler {
void ProfilerServer::StartProfilerServer(int32 port) {
VLOG(1) << "Starting profiler server.";
std::string server_address = absl::StrCat("[::]:", port);
service_ = CreateProfilerService();
::grpc::ServerBuilder builder;
int selected_port = 0;
builder.AddListeningPort(server_address, ::grpc::InsecureServerCredentials(),
&selected_port);
builder.RegisterService(service_.get());
server_ = builder.BuildAndStart();
if (!selected_port) {
LOG(ERROR) << "Unable to bind to " << server_address
<< " selected port:" << selected_port;
} else {
LOG(INFO) << "Profiler server listening on " << server_address
<< " selected port:" << selected_port;
}
}
ProfilerServer::~ProfilerServer() {
if (server_) {
server_->Shutdown();
server_->Wait();
}
}
} // namespace profiler
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
7e03f3844f0d9637ed8f5473dd6a293613769ea7 | f4cdfd17cb593d58b4816f2d28153cdc24b27e30 | /MFC_DEMO/MFC_DEMO/bwlabel.cpp | 81e22b0a151842cb2c51565c8f09a9556f075f7d | [] | no_license | tuouren/experience | 71fa8d78eef8565b03a29154ed79a767426c2f33 | bdc759821aac1fd8a10324daf42d24862366e759 | refs/heads/master | 2021-01-10T20:22:18.083009 | 2014-08-19T01:25:42 | 2014-08-19T01:25:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,114 | cpp | #include "StdAfx.h"
#include "cv.h"
#include "highgui.h"
#include "bwlabel.h"
#define NO_OBJECT 0
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define ELEM(img, r, c) (CV_IMAGE_ELEM(img, unsigned char, r, c))
#define ONETWO(L, r, c, col) (L[(r) * (col) + c])
int find( int set[], int x )
{
int r = x;
while ( set[r] != r )
r = set[r];
return r;
}
/*
labeling scheme
+-+-+-+
|D|C|E|
+-+-+-+
|B|A| |
+-+-+-+
| | | |
+-+-+-+
A is the center pixel of a neighborhood. In the 3 versions of
connectedness:
4: A connects to B and C
6: A connects to B, C, and D
8: A connects to B, C, D, and E
*/
/////////////////////////////
//by yysdsyl
//
//input:img -- gray image
// n -- n connectedness
// labels -- label of each pixel, labels[row * col]
//output: number of connected regions
//
//
//email:yysdsyl@qq.com
int bwlabel(IplImage* img, int n, int* labels)
{
if(n != 4 && n != 8)
n = 4;
int nr = img->height;
int nc = img->width;
int total = nr * nc;
// results
memset(labels, 0, total * sizeof(int));
int nobj = 0; // number of objects found in image
// other variables
int* lset = new int[total]; // label table
memset(lset, 0, total * sizeof(int));
int ntable = 0;
for( int r = 0; r < nr; r++ )
{
for( int c = 0; c < nc; c++ )
{
if ( ELEM(img, r, c) ) // if A is an object
{
// get the neighboring pixels B, C, D, and E
int B, C, D, E;
if ( c == 0 )
B = 0;
else
B = find( lset, ONETWO(labels, r, c - 1, nc) );
if ( r == 0 )
C = 0;
else
C = find( lset, ONETWO(labels, r - 1, c, nc) );
if ( r == 0 || c == 0 )
D = 0;
else
D = find( lset, ONETWO(labels, r - 1, c - 1, nc) );
if ( r == 0 || c == nc - 1 )
E = 0;
else
E = find( lset, ONETWO(labels, r - 1, c + 1, nc) );
if ( n == 4 )
{
// apply 4 connectedness
if ( B && C )
{ // B and C are labeled
if ( B == C )
ONETWO(labels, r, c, nc) = B;
else {
lset[C] = B;
ONETWO(labels, r, c, nc) = B;
}
}
else if ( B ) // B is object but C is not
ONETWO(labels, r, c, nc) = B;
else if ( C ) // C is object but B is not
ONETWO(labels, r, c, nc) = C;
else
{ // B, C, D not object - new object
// label and put into table
ntable++;
ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable;
}
}
else if ( n == 6 )
{
// apply 6 connected ness
if ( D ) // D object, copy label and move on
ONETWO(labels, r, c, nc) = D;
else if ( B && C )
{ // B and C are labeled
if ( B == C )
ONETWO(labels, r, c, nc) = B;
else
{
int tlabel = MIN(B,C);
lset[B] = tlabel;
lset[C] = tlabel;
ONETWO(labels, r, c, nc) = tlabel;
}
}
else if ( B ) // B is object but C is not
ONETWO(labels, r, c, nc) = B;
else if ( C ) // C is object but B is not
ONETWO(labels, r, c, nc) = C;
else
{ // B, C, D not object - new object
// label and put into table
ntable++;
ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable;
}
}
else if ( n == 8 )
{
// apply 8 connectedness
if ( B || C || D || E )
{
int tlabel = B;
if ( B )
tlabel = B;
else if ( C )
tlabel = C;
else if ( D )
tlabel = D;
else if ( E )
tlabel = E;
ONETWO(labels, r, c, nc) = tlabel;
if ( B && B != tlabel )
lset[B] = tlabel;
if ( C && C != tlabel )
lset[C] = tlabel;
if ( D && D != tlabel )
lset[D] = tlabel;
if ( E && E != tlabel )
lset[E] = tlabel;
}
else
{
// label and put into table
ntable++;
ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable;
}
}
}
else
{
ONETWO(labels, r, c, nc) = NO_OBJECT; // A is not an object so leave it
}
}
}
// consolidate component table
for( int i = 0; i <= ntable; i++ )
lset[i] = find( lset, i );
// run image through the look-up table
for( int r = 0; r < nr; r++ )
for( int c = 0; c < nc; c++ )
ONETWO(labels, r, c, nc) = lset[ ONETWO(labels, r, c, nc) ];
// count up the objects in the image
for( int i = 0; i <= ntable; i++ )
lset[i] = 0;
for( int r = 0; r < nr; r++ )
for( int c = 0; c < nc; c++ )
lset[ ONETWO(labels, r, c, nc) ]++;
// number the objects from 1 through n objects
nobj = 0;
lset[0] = 0;
for( int i = 1; i <= ntable; i++ )
if ( lset[i] > 0 )
lset[i] = ++nobj;
// run through the look-up table again
for( int r = 0; r < nr; r++ )
for( int c = 0; c < nc; c++ )
ONETWO(labels, r, c, nc) = lset[ ONETWO(labels, r, c, nc) ];
//
delete[] lset;
return nobj;
}
| [
"875494817@qq.com"
] | 875494817@qq.com |
146d3f5cbec65edb712a21c212dca4ad58274a27 | 3064e4eae69e25e43ef860a1887c277b9ff9c8aa | /Program.cpp | 606cf7868cecf22a1f5e86531e7064baeee60947 | [] | no_license | ScottDavey/SFML_GameState | 60ceea859742e0eb13e86cd5e2a7019783c7d1a9 | ae9e658c10f4c899aced1e10bac77c3215e94ee1 | refs/heads/master | 2016-09-10T18:56:43.819555 | 2013-06-09T17:01:39 | 2013-06-09T17:01:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | cpp | #include "Program.h"
State BaseClass::gameState = sm_MAIN;
Program::Program(void)
: window(sf::VideoMode(1280, 720), "Finite State Machine"),
activeState(sm_MAIN)
{
window.setFramerateLimit(60);
font_FPS.loadFromFile("Content/Font/GOTHIC.TTF");
// FPS Text
text_FPS.setFont(font_FPS);
text_FPS.setCharacterSize(12);
text_FPS.setColor(sf::Color(85, 85, 85));
text_FPS.setPosition(605, 700);
fps = 0.0f;
theClass = new StartMenu(window);
theClass->setState(sm_MAIN);
}
Program::~Program(void)
{
delete theClass;
}
bool Program::Run () {
sf::Clock GameTime;
while (window.isOpen()) {
elapsedTime = GameTime.restart();
if (activeState != theClass->getState()) {
activeState = theClass->getState();
if (theClass)
delete theClass;
switch (activeState) {
case sm_MAIN:
theClass = new StartMenu(window);
break;
case sm_OPTIONS:
theClass = new StartMenu_Options(window);
break;
case GAME:
theClass = new Level(window);
break;
case gm_MAIN:
theClass = new StateThree(window);
break;
default:
theClass = new StartMenu(window);
break;
}
}
// Poll Events
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
// FPS
int FPS = static_cast<int> (1.0f / elapsedTime.asSeconds());
fps += elapsedTime.asSeconds();
if (fps >= 0.2f) {
std::ostringstream Converter;
Converter << "FPS " << FPS;
text_FPS.setString(Converter.str());
fps = 0.0f;
}
window.clear(sf::Color(34, 34, 34, 100));
theClass->Update(elapsedTime);
theClass->Draw(elapsedTime);
window.draw(text_FPS);
window.display();
}
return true;
}
| [
"scottmichaeldavey@gmail.com"
] | scottmichaeldavey@gmail.com |
13d47c8d33280c1040610f2194c5327579645cfd | c23865a5359e1eac2165a19ae4f7bf1c6da9128c | /schooldb/sesion.cpp | 8996e57ff212fdd5ad98fb33846d9a7280a19e7d | [] | no_license | airkobeju/schoolui | 87ec424b30bc934c25c1a7a6b9f03d58bc3d2dd8 | 87d2f8365f68e92e626eec9e80727cbde8e94b3c | refs/heads/master | 2020-04-13T21:56:58.596428 | 2018-12-28T23:38:50 | 2018-12-28T23:38:50 | 163,468,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | cpp | #include "sesion.h"
Sesion::Sesion()
{
}
QString Sesion::getId() const
{
return id;
}
void Sesion::setId(const QString &value)
{
id = value;
}
QString Sesion::getTitulo() const
{
return titulo;
}
void Sesion::setTitulo(const QString &value)
{
titulo = value;
}
QString Sesion::getRecursoMet() const
{
return recursoMet;
}
void Sesion::setRecursoMet(const QString &value)
{
recursoMet = value;
}
QString Sesion::getSecuenciaDid() const
{
return secuenciaDid;
}
void Sesion::setSecuenciaDid(const QString &value)
{
secuenciaDid = value;
}
QString Sesion::getCursoId() const
{
return cursoId;
}
void Sesion::setCursoId(const QString &value)
{
cursoId = value;
}
Fecha Sesion::getFecha() const
{
return fecha;
}
void Sesion::setFecha(const Fecha &value)
{
fecha = value;
}
| [
"airkobeju@gmail.com"
] | airkobeju@gmail.com |
a2ccba07802617d15b76857a5826a5c6f3648cdb | c2ad7cb821e98babe6aebf1103ad5b71e6e3940c | /Framework/Common/BaseApplication.hpp | 7c7244b672e525be6694e05259efe3148fe40220 | [] | no_license | wunianqing/GameEngineLearn | 2ae4bcc474a1d242dd25c195011bd7f1cbbccaf5 | feb8f1508da417aacd95d909753ccc24c4c55868 | refs/heads/master | 2022-11-07T11:43:02.811467 | 2020-06-19T07:08:03 | 2020-06-19T07:08:03 | 273,429,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | hpp | #pragma once
#include "IApplication.hpp"
namespace E
{
class BaseApplication: implements IApplication
{
public:
virtual int Initialize();
virtual void Finalize();
virtual void Tick();
virtual bool IsQuit();
private:
bool m_bQuit;
};
} // namespace E
| [
"wunianqing@outlook.com"
] | wunianqing@outlook.com |
cf078d92b91b8155ff6d405d2220ffe37943b00f | 084341e3b0d6925d7bdac906d9f9bb309d9d34f2 | /trees/lib/binary_search_tree.h | 2d02db78e111303124a63cbbd567e47ded04b2ee | [] | no_license | onufriievkyrylo/diploma | f9110d834c0f01d7f630a8baf26e083ad6c28f21 | ef535d54968f51cbfcc6d8122021d24b60b8290b | refs/heads/master | 2020-03-29T21:29:56.698942 | 2019-03-10T10:37:56 | 2019-03-10T10:37:56 | 150,370,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,739 | h | #ifndef BINARY_SEARCH_TREE_LIB_H_
#define BINARY_SEARCH_TREE_LIB_H_
#include <string>
#include <iostream>
typedef double data_t;
struct BinaryTreeNode {
BinaryTreeNode* left = nullptr;
BinaryTreeNode* right = nullptr;
data_t data;
BinaryTreeNode(const data_t& data) : data(data), left(nullptr), right(nullptr) {
}
};
BinaryTreeNode* bst_get_min_node(BinaryTreeNode* root) {
return root->left ? bst_get_min_node(root->left) : root;
}
BinaryTreeNode* bst_internal_add(BinaryTreeNode* root, const data_t& data) {
if (root == nullptr) {
return new BinaryTreeNode(data);
} else if (root->data > data) {
root->right = bst_internal_add(root->right, data);
} else if (root->data < data) {
root->left = bst_internal_add(root->left, data);
}
return root;
}
void bst_add(BinaryTreeNode* &root, const data_t& data) {
root = bst_internal_add(root, data);
}
BinaryTreeNode* bst_internal_remove(BinaryTreeNode* root, const data_t& data) {
if (root == nullptr) {
return root;
} else if (root->data > data) {
root->right = bst_internal_remove(root, data);
} else if (root->data < data) {
root->left = bst_internal_remove(root->left, data);
} else {
if (root->left == nullptr) {
BinaryTreeNode* temp = root->right;
delete root;
return temp;
} else if (root->right == nullptr) {
BinaryTreeNode* temp = root->left;
delete root;
return temp;
}
BinaryTreeNode* temp = bst_get_min_node(root->right);
root->data = temp->data;
root->right = bst_internal_remove(root->right, temp->data);
}
}
void bst_remove(BinaryTreeNode* &root, const data_t& data) {
root = bst_internal_remove(root, data);
}
void bst_breadth_search(BinaryTreeNode* root) {
const int max_queue_size = 500;
int queue_front = 0;
int queue_back = 0;
int* levels = new int[max_queue_size];
BinaryTreeNode** queue = new BinaryTreeNode*[max_queue_size];
levels[queue_back] = 1;
queue[queue_back++] = root;
while (queue_front != queue_back) {
int level = levels[queue_front];
BinaryTreeNode* temp = queue[queue_front++];
std::cout << std::string(level, '=') << " " << temp->data << std::endl;
if (temp->left) {
levels[queue_back] = level + 1;
queue[queue_back++] = temp->left;
}
if (temp->right) {
levels[queue_back] = level + 1;
queue[queue_back++] = temp->right;
}
}
delete[] queue;
}
void bst_depth_search(BinaryTreeNode* root, int level = 1) {
if (root->left) {
bst_depth_search(root->left, level + 1);
}
std::cout << std::string(level, '=') << " " << root->data << std::endl;
if (root->right) {
bst_depth_search(root->right, level + 1);
}
}
#endif //BINARY_SEARCH_TREE_LIB_H_
| [
"kyrylo.onufriiev@gmail.com"
] | kyrylo.onufriiev@gmail.com |
a8fa9324151f659ce28fbd2afe958a6fd327e895 | 8cd51b4885680c073566f16236cd68d3f4296399 | /src/controls/QskObjectTree.h | 9ad0457087f26109a061c04141fb50e47d21c96e | [
"BSD-3-Clause"
] | permissive | uwerat/qskinny | 0e0c6552afa020382bfa08453a5636b19ae8ff49 | bf2c2b981e3a6ea1187826645da4fab75723222c | refs/heads/master | 2023-08-21T16:27:56.371179 | 2023-08-10T17:54:06 | 2023-08-10T17:54:06 | 97,966,439 | 1,074 | 226 | BSD-3-Clause | 2023-08-10T17:12:01 | 2017-07-21T16:16:18 | C++ | UTF-8 | C++ | false | false | 3,487 | h | /******************************************************************************
* QSkinny - Copyright (C) 2016 Uwe Rathmann
* SPDX-License-Identifier: BSD-3-Clause
*****************************************************************************/
#ifndef QSK_OBJECT_TREE_H
#define QSK_OBJECT_TREE_H
#include "QskControl.h"
#include "QskWindow.h"
#include <qvariant.h>
namespace QskObjectTree
{
class Visitor
{
public:
Visitor() = default;
virtual ~Visitor() = default;
virtual bool visitDown( QObject* object ) = 0;
virtual bool visitUp( const QObject* object ) = 0;
private:
Q_DISABLE_COPY( Visitor )
};
QSK_EXPORT QObjectList childNodes( const QObject* );
QSK_EXPORT QObject* parentNode( const QObject* );
QSK_EXPORT bool isRoot( const QObject* );
void traverseDown( QObject* object, Visitor& visitor );
void traverseUp( QObject* object, Visitor& visitor );
template< class T >
class ResolveVisitor : public Visitor
{
public:
ResolveVisitor( const char* propertyName )
: m_propertyName( propertyName )
{
}
inline const T& resolveValue() const
{
return m_value;
}
void setResolveValue( const T& value )
{
m_value = value;
}
bool visitDown( QObject* object ) override final
{
if ( auto control = qobject_cast< QskControl* >( object ) )
return setImplicitValue( control, m_value );
if ( auto window = qobject_cast< QskWindow* >( object ) )
return setImplicitValue( window, m_value );
return !setProperty( object, m_propertyName.constData(), m_value );
}
bool visitUp( const QObject* object ) override final
{
if ( isRoot( object ) )
return true;
if ( auto control = qobject_cast< const QskControl* >( object ) )
{
m_value = value( control );
return true;
}
if ( auto window = qobject_cast< const QskWindow* >( object ) )
{
m_value = value( window );
return true;
}
return getProperty( object, m_propertyName, m_value );
}
private:
inline bool getProperty( const QObject* object,
const char* name, T& value ) const
{
if ( !m_propertyName.isEmpty() )
{
const QVariant v = object->property( name );
if ( v.canConvert< T >() )
{
value = qvariant_cast< T >( v );
return true;
}
}
return false;
}
inline bool setProperty( QObject* object,
const char* name, const T& value ) const
{
T oldValue;
if ( !getProperty( object, name, oldValue ) || oldValue == value )
return false;
object->setProperty( name, value );
return true;
}
virtual bool setImplicitValue( QskControl*, const T& ) = 0;
virtual bool setImplicitValue( QskWindow*, const T& ) = 0;
virtual T value( const QskControl* ) const = 0;
virtual T value( const QskWindow* ) const = 0;
private:
const QByteArray m_propertyName;
T m_value;
};
}
#endif
| [
"Uwe.Rathmann@tigertal.de"
] | Uwe.Rathmann@tigertal.de |
98b9037df35958d25ce713a74b954bae8f8cf0b7 | b4f42eed62aa7ef0e28f04c1f455f030115ec58e | /messagingfw/msgtest/targetautomation/TechviewStart/ThreadWatch.cpp | 42bcab4ae6b5059e6197872c88b39eeac7d3fd6d | [] | no_license | SymbianSource/oss.FCL.sf.mw.messagingmw | 6addffd79d854f7a670cbb5d89341b0aa6e8c849 | 7af85768c2d2bc370cbb3b95e01103f7b7577455 | refs/heads/master | 2021-01-17T16:45:41.697969 | 2010-11-03T17:11:46 | 2010-11-03T17:11:46 | 71,851,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,996 | cpp | // Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//
#include "ThreadWatch.h"
#include "Starter.h"
/**
* class CThreadWatcher
**/
CThreadWatcher::~CThreadWatcher()
{
Cancel();
}
CThreadWatcher::CThreadWatcher(TInt appType, TFullName aFullName, CStarter* aOwner, TUint32 aAppUid, TBool aViewless)
: CActive(EPriorityStandard), iAppType(appType), iFullName(aFullName), iOwner(aOwner), iAppUid(aAppUid), iViewless(aViewless)
{}
void CThreadWatcher::ConstructL(const TThreadId aThreadId)
{
iMonitoringThread = ETrue;
User::LeaveIfError(iThread.Open(aThreadId)); // Queue logon request
iThread.Logon(iStatus);
CActiveScheduler::Add(this);
SetActive(); // Tell scheduler we're active
}
CThreadWatcher* CThreadWatcher::NewL(TInt appType, const TThreadId aThreadId, TFullName aFullName, CStarter* aOwner, TUint32 aAppUid, TBool aViewless)
{
CThreadWatcher* self = new (ELeave) CThreadWatcher(appType, aFullName, aOwner, aAppUid, aViewless);
CleanupStack::PushL(self);
self->ConstructL(aThreadId);
CleanupStack::Pop(); // self;
return self;
}
void CThreadWatcher::DoCancel()
{
iThread.LogonCancel(iStatus);
iThread.Close();
}
void CThreadWatcher::RunL()
{
iThread.Close();
if(iMonitoringThread)
{
TRAPD(err, RestartThreadL()); //ignore error
}
}
void CThreadWatcher::RestartThreadL()
{
TThreadId threadId;
iOwner->RestartMonitoredThreadL(iAppType, threadId, iFullName, iAppUid, iViewless);
User::LeaveIfError(iThread.Open(threadId)); // Queue logon request
iThread.Logon(iStatus);
iStatus = KRequestPending;
SetActive(); // Tell scheduler we're active
}
| [
"none@none"
] | none@none |
c7a68ddd2f18629d61dc7748d24bee4a8ddd89d3 | 1b51fec6521c8a95b1937b3d3de489efbe2d2029 | /cubeCode/cubeCode.ino | 8cd01688d3691dd3fedfc1e70c5c78b626f26b84 | [
"MIT"
] | permissive | blinky-lite-archive/blinky-DS18B20-cube | 1a3914ccdbde4847faa6ad34c447035f3cca8077 | ab6d1f67db70fb87de33aad05897bc71e970ab56 | refs/heads/master | 2023-04-15T14:59:43.539172 | 2021-05-03T06:00:27 | 2021-05-03T06:00:27 | 357,963,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,867 | ino | #include <OneWire.h>
#define BAUD_RATE 57600
#define CHECKSUM 64
struct TransmitData
{
float tempA = 0.0;
float tempB = 0.0;
byte extraInfo[44];
};
struct ReceiveData
{
int loopDelay = 100;
byte extraInfo[52];
};
struct DS18B20
{
int signalPin;
int powerPin;
byte chipType;
byte address[8];
OneWire oneWire;
float temp = 0.0;
};
DS18B20 dS18B20_A;
DS18B20 dS18B20_B;
byte initDS18B20(byte* addr, OneWire* ow)
{
byte type_s = 0;
if ( !ow->search(addr))
{
ow->reset_search();
delay(250);
return 0;
}
// the first ROM byte indicates which chip
switch (addr[0])
{
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
return 0;
}
return type_s;
}
float getDS18B20Temperature(OneWire* ow, byte* addr, byte chipType)
{
byte i;
byte data[12];
float celsius;
ow->reset();
ow->select(addr);
ow->write(0x44, 1); // start conversion, with parasite power on at the end
delay(750); // maybe 750ms is enough, maybe not
ow->reset();
ow->select(addr);
ow->write(0xBE); // Read Scratchpad
for ( i = 0; i < 9; i++) data[i] = ow->read();
int16_t raw = (data[1] << 8) | data[0];
if (chipType)
{
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) raw = (raw & 0xFFF0) + 12 - data[6];
}
else
{
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
}
celsius = (float)raw / 16.0;
return celsius;
}
void setupPins(TransmitData* tData, ReceiveData* rData)
{
dS18B20_A.signalPin = 5;
dS18B20_A.powerPin = 3;
dS18B20_B.signalPin = 9;
dS18B20_B.powerPin = 7;
pinMode(dS18B20_A.powerPin, OUTPUT);
digitalWrite(dS18B20_A.powerPin, HIGH);
pinMode(dS18B20_B.powerPin, OUTPUT);
digitalWrite(dS18B20_B.powerPin, HIGH);
dS18B20_A.oneWire = OneWire(dS18B20_A.signalPin);
dS18B20_A.chipType = initDS18B20(dS18B20_A.address, &dS18B20_A.oneWire);
dS18B20_B.oneWire = OneWire(dS18B20_B.signalPin);
dS18B20_B.chipType = initDS18B20(dS18B20_B.address, &dS18B20_B.oneWire);
// Serial.begin(9600);
}
void processNewSetting(TransmitData* tData, ReceiveData* rData, ReceiveData* newData)
{
rData->loopDelay = newData->loopDelay;
}
boolean processData(TransmitData* tData, ReceiveData* rData)
{
digitalWrite(dS18B20_A.powerPin, LOW);
digitalWrite(dS18B20_B.powerPin, LOW);
delay(500);
digitalWrite(dS18B20_A.powerPin, HIGH);
digitalWrite(dS18B20_B.powerPin, HIGH);
delay(500);
dS18B20_A.temp = getDS18B20Temperature(&dS18B20_A.oneWire, dS18B20_A.address, dS18B20_A.chipType);
dS18B20_B.temp = getDS18B20Temperature(&dS18B20_B.oneWire, dS18B20_B.address, dS18B20_B.chipType);
// Serial.print(dS18B20_A.temp);
// Serial.print(",");
// Serial.println(dS18B20_B.temp);
tData->tempA = dS18B20_A.temp;
tData->tempB = dS18B20_B.temp;
delay(rData->loopDelay);
return true;
}
const int commLEDPin = 13;
boolean commLED = true;
struct TXinfo
{
int cubeInit = 1;
int newSettingDone = 0;
int checkSum = CHECKSUM;
};
struct RXinfo
{
int newSetting = 0;
int checkSum = CHECKSUM;
};
struct TX
{
TXinfo txInfo;
TransmitData txData;
};
struct RX
{
RXinfo rxInfo;
ReceiveData rxData;
};
TX tx;
RX rx;
ReceiveData settingsStorage;
int sizeOfTx = 0;
int sizeOfRx = 0;
void setup()
{
setupPins(&(tx.txData), &settingsStorage);
pinMode(commLEDPin, OUTPUT);
digitalWrite(commLEDPin, commLED);
sizeOfTx = sizeof(tx);
sizeOfRx = sizeof(rx);
Serial1.begin(BAUD_RATE);
delay(1000);
int sizeOfextraInfo = sizeof(tx.txData.extraInfo);
for (int ii = 0; ii < sizeOfextraInfo; ++ii) tx.txData.extraInfo[ii] = 0;
}
void loop()
{
boolean goodData = false;
goodData = processData(&(tx.txData), &settingsStorage);
if (goodData)
{
tx.txInfo.newSettingDone = 0;
if(Serial1.available() > 0)
{
commLED = !commLED;
digitalWrite(commLEDPin, commLED);
Serial1.readBytes((uint8_t*)&rx, sizeOfRx);
if (rx.rxInfo.checkSum == CHECKSUM)
{
if (rx.rxInfo.newSetting > 0)
{
processNewSetting(&(tx.txData), &settingsStorage, &(rx.rxData));
tx.txInfo.newSettingDone = 1;
tx.txInfo.cubeInit = 0;
}
}
else
{
Serial1.end();
for (int ii = 0; ii < 50; ++ii)
{
commLED = !commLED;
digitalWrite(commLEDPin, commLED);
delay(100);
}
Serial1.begin(BAUD_RATE);
tx.txInfo.newSettingDone = 0;
tx.txInfo.cubeInit = -1;
}
}
Serial1.write((uint8_t*)&tx, sizeOfTx);
Serial1.flush();
}
}
| [
"dmcginnis427@gmail.com"
] | dmcginnis427@gmail.com |
29014fa61778648d0da958919210f1c1e92c8489 | 609795ac6f379bffa752dc8c1c8e6a89dd201657 | /include/splitspace/Texture.hpp | ca85c858c8d8509be99f12617428850bdf98bc18 | [] | no_license | RostakaGmfun/splitspace | 11aa686863e6ca7ca08a1b1188453b0c10d5c85b | 27bf1af2b94e99b9ca0393394d386a06e8fd5c82 | refs/heads/master | 2021-01-10T15:32:50.621252 | 2016-05-05T09:52:54 | 2016-05-05T09:52:54 | 51,162,219 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | hpp | #ifndef TEXTURE_HPP
#define TEXTURE_HPP
#include <splitspace/Resource.hpp>
#include <splitspace/RenderManager.hpp>
namespace splitspace {
class LogManager;
struct TextureManifest: public ResourceManifest {
TextureManifest(): ResourceManifest(RES_TEXTURE)
{}
};
class Texture: public Resource {
public:
Texture(Engine *e, TextureManifest *manifest);
virtual bool load();
virtual void unload();
GLuint getGLName() const { return m_glName; }
private:
int m_width;
int m_height;
int m_numChannels;
unsigned char *m_data;
GLuint m_glName;
};
} // namespace splitspace
#endif // TEXTURE_HPP
| [
"rostawesomegd@gmail.com"
] | rostawesomegd@gmail.com |
91b514c30e0fc1a01a11e704e215ea5cfd17d361 | 7579d827cb7b50b438dfd9ef6fa80ba2797848c9 | /sources/plug_osg/src/luna/bind_osg_TriangleMesh.cpp | 35597597b0e28e7f125097f8f2bde95a1e381c78 | [] | no_license | roche-emmanuel/sgt | 809d00b056e36b7799bbb438b8099e3036377377 | ee3a550f6172c7d14179d9d171e0124306495e45 | refs/heads/master | 2021-05-01T12:51:39.983104 | 2014-09-08T03:35:15 | 2014-09-08T03:35:15 | 79,538,908 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,369 | cpp | #include <plug_common.h>
#include <luna/wrappers/wrapper_osg_TriangleMesh.h>
class luna_wrapper_osg_TriangleMesh {
public:
typedef Luna< osg::TriangleMesh > luna_t;
inline static bool _lg_typecheck_getTable(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
static int _bind_getTable(lua_State *L) {
if (!_lg_typecheck_getTable(L)) {
luaL_error(L, "luna typecheck failed in getTable function, expected prototype:\ngetTable(). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
osg::Referenced* self=(Luna< osg::Referenced >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call getTable()");
}
luna_wrapper_base* wrapper = luna_caster<osg::Referenced,luna_wrapper_base>::cast(self); //dynamic_cast<luna_wrapper_base*>(self);
if(wrapper) {
CHECK_RET(wrapper->pushTable(),0,"Cannot push table from value wrapper.");
return 1;
}
return 0;
}
inline static bool _lg_typecheck_fromVoid(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( !Luna<void>::has_uniqueid(L,1,3625364) ) return false;
return true;
}
static int _bind_fromVoid(lua_State *L) {
if (!_lg_typecheck_fromVoid(L)) {
luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nfromVoid(void*). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self= (osg::TriangleMesh*)(Luna< void >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call fromVoid(...)");
}
Luna< osg::TriangleMesh >::push(L,self,false);
return 1;
}
inline static bool _lg_typecheck_asVoid(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( !Luna<void>::has_uniqueid(L,1,50169651) ) return false;
return true;
}
static int _bind_asVoid(lua_State *L) {
if (!_lg_typecheck_asVoid(L)) {
luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nasVoid(). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
void* self= (void*)(Luna< osg::Referenced >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call asVoid(...)");
}
Luna< void >::push(L,self,false);
return 1;
}
// Derived class converters:
static int _cast_from_Referenced(lua_State *L) {
// all checked are already performed before reaching this point.
//osg::TriangleMesh* ptr= dynamic_cast< osg::TriangleMesh* >(Luna< osg::Referenced >::check(L,1));
osg::TriangleMesh* ptr= luna_caster< osg::Referenced, osg::TriangleMesh >::cast(Luna< osg::Referenced >::check(L,1));
if(!ptr)
return 0;
// Otherwise push the pointer:
Luna< osg::TriangleMesh >::push(L,ptr,false);
return 1;
};
// Constructor checkers:
inline static bool _lg_typecheck_ctor_overload_1(lua_State *L) {
if( lua_gettop(L)!=0 ) return false;
return true;
}
inline static bool _lg_typecheck_ctor_overload_2(lua_State *L) {
int luatop = lua_gettop(L);
if( luatop<1 || luatop>2 ) return false;
if( !Luna<void>::has_uniqueid(L,1,50169651) ) return false;
if( (!(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1))) ) return false;
if( luatop>1 && !Luna<void>::has_uniqueid(L,2,27134364) ) return false;
if( luatop>1 && (!(Luna< osg::CopyOp >::check(L,2))) ) return false;
return true;
}
inline static bool _lg_typecheck_ctor_overload_3(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( lua_istable(L,1)==0 ) return false;
return true;
}
inline static bool _lg_typecheck_ctor_overload_4(lua_State *L) {
int luatop = lua_gettop(L);
if( luatop<2 || luatop>3 ) return false;
if( lua_istable(L,1)==0 ) return false;
if( !Luna<void>::has_uniqueid(L,2,50169651) ) return false;
if( (!(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,2))) ) return false;
if( luatop>2 && !Luna<void>::has_uniqueid(L,3,27134364) ) return false;
if( luatop>2 && (!(Luna< osg::CopyOp >::check(L,3))) ) return false;
return true;
}
// Function checkers:
inline static bool _lg_typecheck_cloneType(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_clone(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,27134364) ) return false;
return true;
}
inline static bool _lg_typecheck_isSameKindAs(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_libraryName(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_className(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_accept_overload_1(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,36301858) ) return false;
if( (!(Luna< osg::ShapeVisitor >::check(L,2))) ) return false;
return true;
}
inline static bool _lg_typecheck_accept_overload_2(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,45826538) ) return false;
if( (!(Luna< osg::ConstShapeVisitor >::check(L,2))) ) return false;
return true;
}
inline static bool _lg_typecheck_setVertices(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_getVertices_overload_1(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_getVertices_overload_2(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_setIndices(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_getIndices_overload_1(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_getIndices_overload_2(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_setThreadSafeRefUnref(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( lua_isboolean(L,2)==0 ) return false;
return true;
}
inline static bool _lg_typecheck_base_setName(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( lua_type(L,2)!=LUA_TSTRING ) return false;
return true;
}
inline static bool _lg_typecheck_base_computeDataVariance(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_setUserData(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_base_getUserData_overload_1(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_getUserData_overload_2(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_releaseGLObjects(lua_State *L) {
int luatop = lua_gettop(L);
if( luatop<1 || luatop>2 ) return false;
if( luatop>1 && (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_base_cloneType(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_clone(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,27134364) ) return false;
return true;
}
inline static bool _lg_typecheck_base_isSameKindAs(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
inline static bool _lg_typecheck_base_libraryName(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_className(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
inline static bool _lg_typecheck_base_accept_overload_1(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,36301858) ) return false;
if( (!(Luna< osg::ShapeVisitor >::check(L,2))) ) return false;
return true;
}
inline static bool _lg_typecheck_base_accept_overload_2(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,2,45826538) ) return false;
if( (!(Luna< osg::ConstShapeVisitor >::check(L,2))) ) return false;
return true;
}
// Operator checkers:
// (found 0 valid operators)
// Constructor binds:
// osg::TriangleMesh::TriangleMesh()
static osg::TriangleMesh* _bind_ctor_overload_1(lua_State *L) {
if (!_lg_typecheck_ctor_overload_1(L)) {
luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh() function, expected prototype:\nosg::TriangleMesh::TriangleMesh()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
return new osg::TriangleMesh();
}
// osg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)
static osg::TriangleMesh* _bind_ctor_overload_2(lua_State *L) {
if (!_lg_typecheck_ctor_overload_2(L)) {
luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)\nClass arguments details:\narg 1 ID = 50169651\narg 2 ID = 27134364\n\n%s",luna_dumpStack(L).c_str());
}
int luatop = lua_gettop(L);
const osg::TriangleMesh* mesh_ptr=(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1));
if( !mesh_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg mesh in osg::TriangleMesh::TriangleMesh function");
}
const osg::TriangleMesh & mesh=*mesh_ptr;
const osg::CopyOp* copyop_ptr=luatop>1 ? (Luna< osg::CopyOp >::check(L,2)) : NULL;
if( luatop>1 && !copyop_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg copyop in osg::TriangleMesh::TriangleMesh function");
}
const osg::CopyOp & copyop=luatop>1 ? *copyop_ptr : (const osg::CopyOp&)osg::CopyOp::SHALLOW_COPY;
return new osg::TriangleMesh(mesh, copyop);
}
// osg::TriangleMesh::TriangleMesh(lua_Table * data)
static osg::TriangleMesh* _bind_ctor_overload_3(lua_State *L) {
if (!_lg_typecheck_ctor_overload_3(L)) {
luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(lua_Table * data) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(lua_Table * data)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
return new wrapper_osg_TriangleMesh(L,NULL);
}
// osg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)
static osg::TriangleMesh* _bind_ctor_overload_4(lua_State *L) {
if (!_lg_typecheck_ctor_overload_4(L)) {
luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)\nClass arguments details:\narg 2 ID = 50169651\narg 3 ID = 27134364\n\n%s",luna_dumpStack(L).c_str());
}
int luatop = lua_gettop(L);
const osg::TriangleMesh* mesh_ptr=(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,2));
if( !mesh_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg mesh in osg::TriangleMesh::TriangleMesh function");
}
const osg::TriangleMesh & mesh=*mesh_ptr;
const osg::CopyOp* copyop_ptr=luatop>2 ? (Luna< osg::CopyOp >::check(L,3)) : NULL;
if( luatop>2 && !copyop_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg copyop in osg::TriangleMesh::TriangleMesh function");
}
const osg::CopyOp & copyop=luatop>2 ? *copyop_ptr : (const osg::CopyOp&)osg::CopyOp::SHALLOW_COPY;
return new wrapper_osg_TriangleMesh(L,NULL, mesh, copyop);
}
// Overload binder for osg::TriangleMesh::TriangleMesh
static osg::TriangleMesh* _bind_ctor(lua_State *L) {
if (_lg_typecheck_ctor_overload_1(L)) return _bind_ctor_overload_1(L);
if (_lg_typecheck_ctor_overload_2(L)) return _bind_ctor_overload_2(L);
if (_lg_typecheck_ctor_overload_3(L)) return _bind_ctor_overload_3(L);
if (_lg_typecheck_ctor_overload_4(L)) return _bind_ctor_overload_4(L);
luaL_error(L, "error in function TriangleMesh, cannot match any of the overloads for function TriangleMesh:\n TriangleMesh()\n TriangleMesh(const osg::TriangleMesh &, const osg::CopyOp &)\n TriangleMesh(lua_Table *)\n TriangleMesh(lua_Table *, const osg::TriangleMesh &, const osg::CopyOp &)\n");
return NULL;
}
// Function binds:
// osg::Object * osg::TriangleMesh::cloneType() const
static int _bind_cloneType(lua_State *L) {
if (!_lg_typecheck_cloneType(L)) {
luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::cloneType() const function, expected prototype:\nosg::Object * osg::TriangleMesh::cloneType() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::cloneType() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Object * lret = self->cloneType();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Object >::push(L,lret,false);
return 1;
}
// osg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const
static int _bind_clone(lua_State *L) {
if (!_lg_typecheck_clone(L)) {
luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const function, expected prototype:\nosg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const\nClass arguments details:\narg 1 ID = 27134364\n\n%s",luna_dumpStack(L).c_str());
}
const osg::CopyOp* _arg1_ptr=(Luna< osg::CopyOp >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::clone function");
}
const osg::CopyOp & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::clone(const osg::CopyOp &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Object * lret = self->clone(_arg1);
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Object >::push(L,lret,false);
return 1;
}
// bool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const
static int _bind_isSameKindAs(lua_State *L) {
if (!_lg_typecheck_isSameKindAs(L)) {
luaL_error(L, "luna typecheck failed in bool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const function, expected prototype:\nbool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
const osg::Object* obj=(Luna< osg::Referenced >::checkSubType< osg::Object >(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call bool osg::TriangleMesh::isSameKindAs(const osg::Object *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
bool lret = self->isSameKindAs(obj);
lua_pushboolean(L,lret?1:0);
return 1;
}
// const char * osg::TriangleMesh::libraryName() const
static int _bind_libraryName(lua_State *L) {
if (!_lg_typecheck_libraryName(L)) {
luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::libraryName() const function, expected prototype:\nconst char * osg::TriangleMesh::libraryName() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::libraryName() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const char * lret = self->libraryName();
lua_pushstring(L,lret);
return 1;
}
// const char * osg::TriangleMesh::className() const
static int _bind_className(lua_State *L) {
if (!_lg_typecheck_className(L)) {
luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::className() const function, expected prototype:\nconst char * osg::TriangleMesh::className() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::className() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const char * lret = self->className();
lua_pushstring(L,lret);
return 1;
}
// void osg::TriangleMesh::accept(osg::ShapeVisitor & arg1)
static int _bind_accept_overload_1(lua_State *L) {
if (!_lg_typecheck_accept_overload_1(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::accept(osg::ShapeVisitor & arg1) function, expected prototype:\nvoid osg::TriangleMesh::accept(osg::ShapeVisitor & arg1)\nClass arguments details:\narg 1 ID = 36301858\n\n%s",luna_dumpStack(L).c_str());
}
osg::ShapeVisitor* _arg1_ptr=(Luna< osg::ShapeVisitor >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::accept function");
}
osg::ShapeVisitor & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::accept(osg::ShapeVisitor &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->accept(_arg1);
return 0;
}
// void osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const
static int _bind_accept_overload_2(lua_State *L) {
if (!_lg_typecheck_accept_overload_2(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const function, expected prototype:\nvoid osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const\nClass arguments details:\narg 1 ID = 45826538\n\n%s",luna_dumpStack(L).c_str());
}
osg::ConstShapeVisitor* _arg1_ptr=(Luna< osg::ConstShapeVisitor >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::accept function");
}
osg::ConstShapeVisitor & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::accept(osg::ConstShapeVisitor &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->accept(_arg1);
return 0;
}
// Overload binder for osg::TriangleMesh::accept
static int _bind_accept(lua_State *L) {
if (_lg_typecheck_accept_overload_1(L)) return _bind_accept_overload_1(L);
if (_lg_typecheck_accept_overload_2(L)) return _bind_accept_overload_2(L);
luaL_error(L, "error in function accept, cannot match any of the overloads for function accept:\n accept(osg::ShapeVisitor &)\n accept(osg::ConstShapeVisitor &)\n");
return 0;
}
// void osg::TriangleMesh::setVertices(osg::Vec3Array * vertices)
static int _bind_setVertices(lua_State *L) {
if (!_lg_typecheck_setVertices(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::setVertices(osg::Vec3Array * vertices) function, expected prototype:\nvoid osg::TriangleMesh::setVertices(osg::Vec3Array * vertices)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
osg::Vec3Array* vertices=(Luna< osg::Referenced >::checkSubType< osg::Vec3Array >(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::setVertices(osg::Vec3Array *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->setVertices(vertices);
return 0;
}
// osg::Vec3Array * osg::TriangleMesh::getVertices()
static int _bind_getVertices_overload_1(lua_State *L) {
if (!_lg_typecheck_getVertices_overload_1(L)) {
luaL_error(L, "luna typecheck failed in osg::Vec3Array * osg::TriangleMesh::getVertices() function, expected prototype:\nosg::Vec3Array * osg::TriangleMesh::getVertices()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Vec3Array * osg::TriangleMesh::getVertices(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Vec3Array * lret = self->getVertices();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Vec3Array >::push(L,lret,false);
return 1;
}
// const osg::Vec3Array * osg::TriangleMesh::getVertices() const
static int _bind_getVertices_overload_2(lua_State *L) {
if (!_lg_typecheck_getVertices_overload_2(L)) {
luaL_error(L, "luna typecheck failed in const osg::Vec3Array * osg::TriangleMesh::getVertices() const function, expected prototype:\nconst osg::Vec3Array * osg::TriangleMesh::getVertices() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const osg::Vec3Array * osg::TriangleMesh::getVertices() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const osg::Vec3Array * lret = self->getVertices();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Vec3Array >::push(L,lret,false);
return 1;
}
// Overload binder for osg::TriangleMesh::getVertices
static int _bind_getVertices(lua_State *L) {
if (_lg_typecheck_getVertices_overload_1(L)) return _bind_getVertices_overload_1(L);
if (_lg_typecheck_getVertices_overload_2(L)) return _bind_getVertices_overload_2(L);
luaL_error(L, "error in function getVertices, cannot match any of the overloads for function getVertices:\n getVertices()\n getVertices()\n");
return 0;
}
// void osg::TriangleMesh::setIndices(osg::IndexArray * indices)
static int _bind_setIndices(lua_State *L) {
if (!_lg_typecheck_setIndices(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::setIndices(osg::IndexArray * indices) function, expected prototype:\nvoid osg::TriangleMesh::setIndices(osg::IndexArray * indices)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
osg::IndexArray* indices=(Luna< osg::Referenced >::checkSubType< osg::IndexArray >(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::setIndices(osg::IndexArray *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->setIndices(indices);
return 0;
}
// osg::IndexArray * osg::TriangleMesh::getIndices()
static int _bind_getIndices_overload_1(lua_State *L) {
if (!_lg_typecheck_getIndices_overload_1(L)) {
luaL_error(L, "luna typecheck failed in osg::IndexArray * osg::TriangleMesh::getIndices() function, expected prototype:\nosg::IndexArray * osg::TriangleMesh::getIndices()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::IndexArray * osg::TriangleMesh::getIndices(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::IndexArray * lret = self->getIndices();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::IndexArray >::push(L,lret,false);
return 1;
}
// const osg::IndexArray * osg::TriangleMesh::getIndices() const
static int _bind_getIndices_overload_2(lua_State *L) {
if (!_lg_typecheck_getIndices_overload_2(L)) {
luaL_error(L, "luna typecheck failed in const osg::IndexArray * osg::TriangleMesh::getIndices() const function, expected prototype:\nconst osg::IndexArray * osg::TriangleMesh::getIndices() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const osg::IndexArray * osg::TriangleMesh::getIndices() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const osg::IndexArray * lret = self->getIndices();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::IndexArray >::push(L,lret,false);
return 1;
}
// Overload binder for osg::TriangleMesh::getIndices
static int _bind_getIndices(lua_State *L) {
if (_lg_typecheck_getIndices_overload_1(L)) return _bind_getIndices_overload_1(L);
if (_lg_typecheck_getIndices_overload_2(L)) return _bind_getIndices_overload_2(L);
luaL_error(L, "error in function getIndices, cannot match any of the overloads for function getIndices:\n getIndices()\n getIndices()\n");
return 0;
}
// void osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe)
static int _bind_base_setThreadSafeRefUnref(lua_State *L) {
if (!_lg_typecheck_base_setThreadSafeRefUnref(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe) function, expected prototype:\nvoid osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
bool threadSafe=(bool)(lua_toboolean(L,2)==1);
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setThreadSafeRefUnref(bool). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::setThreadSafeRefUnref(threadSafe);
return 0;
}
// void osg::TriangleMesh::base_setName(const std::string & name)
static int _bind_base_setName(lua_State *L) {
if (!_lg_typecheck_base_setName(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setName(const std::string & name) function, expected prototype:\nvoid osg::TriangleMesh::base_setName(const std::string & name)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
std::string name(lua_tostring(L,2),lua_objlen(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setName(const std::string &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::setName(name);
return 0;
}
// void osg::TriangleMesh::base_computeDataVariance()
static int _bind_base_computeDataVariance(lua_State *L) {
if (!_lg_typecheck_base_computeDataVariance(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_computeDataVariance() function, expected prototype:\nvoid osg::TriangleMesh::base_computeDataVariance()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_computeDataVariance(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::computeDataVariance();
return 0;
}
// void osg::TriangleMesh::base_setUserData(osg::Referenced * obj)
static int _bind_base_setUserData(lua_State *L) {
if (!_lg_typecheck_base_setUserData(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setUserData(osg::Referenced * obj) function, expected prototype:\nvoid osg::TriangleMesh::base_setUserData(osg::Referenced * obj)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
osg::Referenced* obj=(Luna< osg::Referenced >::check(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setUserData(osg::Referenced *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::setUserData(obj);
return 0;
}
// osg::Referenced * osg::TriangleMesh::base_getUserData()
static int _bind_base_getUserData_overload_1(lua_State *L) {
if (!_lg_typecheck_base_getUserData_overload_1(L)) {
luaL_error(L, "luna typecheck failed in osg::Referenced * osg::TriangleMesh::base_getUserData() function, expected prototype:\nosg::Referenced * osg::TriangleMesh::base_getUserData()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Referenced * osg::TriangleMesh::base_getUserData(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Referenced * lret = self->TriangleMesh::getUserData();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Referenced >::push(L,lret,false);
return 1;
}
// const osg::Referenced * osg::TriangleMesh::base_getUserData() const
static int _bind_base_getUserData_overload_2(lua_State *L) {
if (!_lg_typecheck_base_getUserData_overload_2(L)) {
luaL_error(L, "luna typecheck failed in const osg::Referenced * osg::TriangleMesh::base_getUserData() const function, expected prototype:\nconst osg::Referenced * osg::TriangleMesh::base_getUserData() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const osg::Referenced * osg::TriangleMesh::base_getUserData() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const osg::Referenced * lret = self->TriangleMesh::getUserData();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Referenced >::push(L,lret,false);
return 1;
}
// Overload binder for osg::TriangleMesh::base_getUserData
static int _bind_base_getUserData(lua_State *L) {
if (_lg_typecheck_base_getUserData_overload_1(L)) return _bind_base_getUserData_overload_1(L);
if (_lg_typecheck_base_getUserData_overload_2(L)) return _bind_base_getUserData_overload_2(L);
luaL_error(L, "error in function base_getUserData, cannot match any of the overloads for function base_getUserData:\n base_getUserData()\n base_getUserData()\n");
return 0;
}
// void osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const
static int _bind_base_releaseGLObjects(lua_State *L) {
if (!_lg_typecheck_base_releaseGLObjects(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const function, expected prototype:\nvoid osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
int luatop = lua_gettop(L);
osg::State* _arg1=luatop>1 ? (Luna< osg::Referenced >::checkSubType< osg::State >(L,2)) : (osg::State*)0;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_releaseGLObjects(osg::State *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::releaseGLObjects(_arg1);
return 0;
}
// osg::Object * osg::TriangleMesh::base_cloneType() const
static int _bind_base_cloneType(lua_State *L) {
if (!_lg_typecheck_base_cloneType(L)) {
luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::base_cloneType() const function, expected prototype:\nosg::Object * osg::TriangleMesh::base_cloneType() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::base_cloneType() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Object * lret = self->TriangleMesh::cloneType();
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Object >::push(L,lret,false);
return 1;
}
// osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const
static int _bind_base_clone(lua_State *L) {
if (!_lg_typecheck_base_clone(L)) {
luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const function, expected prototype:\nosg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const\nClass arguments details:\narg 1 ID = 27134364\n\n%s",luna_dumpStack(L).c_str());
}
const osg::CopyOp* _arg1_ptr=(Luna< osg::CopyOp >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_clone function");
}
const osg::CopyOp & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
osg::Object * lret = self->TriangleMesh::clone(_arg1);
if(!lret) return 0; // Do not write NULL pointers.
Luna< osg::Object >::push(L,lret,false);
return 1;
}
// bool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const
static int _bind_base_isSameKindAs(lua_State *L) {
if (!_lg_typecheck_base_isSameKindAs(L)) {
luaL_error(L, "luna typecheck failed in bool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const function, expected prototype:\nbool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str());
}
const osg::Object* obj=(Luna< osg::Referenced >::checkSubType< osg::Object >(L,2));
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call bool osg::TriangleMesh::base_isSameKindAs(const osg::Object *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
bool lret = self->TriangleMesh::isSameKindAs(obj);
lua_pushboolean(L,lret?1:0);
return 1;
}
// const char * osg::TriangleMesh::base_libraryName() const
static int _bind_base_libraryName(lua_State *L) {
if (!_lg_typecheck_base_libraryName(L)) {
luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::base_libraryName() const function, expected prototype:\nconst char * osg::TriangleMesh::base_libraryName() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::base_libraryName() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const char * lret = self->TriangleMesh::libraryName();
lua_pushstring(L,lret);
return 1;
}
// const char * osg::TriangleMesh::base_className() const
static int _bind_base_className(lua_State *L) {
if (!_lg_typecheck_base_className(L)) {
luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::base_className() const function, expected prototype:\nconst char * osg::TriangleMesh::base_className() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::base_className() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
const char * lret = self->TriangleMesh::className();
lua_pushstring(L,lret);
return 1;
}
// void osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1)
static int _bind_base_accept_overload_1(lua_State *L) {
if (!_lg_typecheck_base_accept_overload_1(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1) function, expected prototype:\nvoid osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1)\nClass arguments details:\narg 1 ID = 36301858\n\n%s",luna_dumpStack(L).c_str());
}
osg::ShapeVisitor* _arg1_ptr=(Luna< osg::ShapeVisitor >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_accept function");
}
osg::ShapeVisitor & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_accept(osg::ShapeVisitor &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::accept(_arg1);
return 0;
}
// void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const
static int _bind_base_accept_overload_2(lua_State *L) {
if (!_lg_typecheck_base_accept_overload_2(L)) {
luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const function, expected prototype:\nvoid osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const\nClass arguments details:\narg 1 ID = 45826538\n\n%s",luna_dumpStack(L).c_str());
}
osg::ConstShapeVisitor* _arg1_ptr=(Luna< osg::ConstShapeVisitor >::check(L,2));
if( !_arg1_ptr ) {
luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_accept function");
}
osg::ConstShapeVisitor & _arg1=*_arg1_ptr;
osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1);
if(!self) {
luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
self->TriangleMesh::accept(_arg1);
return 0;
}
// Overload binder for osg::TriangleMesh::base_accept
static int _bind_base_accept(lua_State *L) {
if (_lg_typecheck_base_accept_overload_1(L)) return _bind_base_accept_overload_1(L);
if (_lg_typecheck_base_accept_overload_2(L)) return _bind_base_accept_overload_2(L);
luaL_error(L, "error in function base_accept, cannot match any of the overloads for function base_accept:\n base_accept(osg::ShapeVisitor &)\n base_accept(osg::ConstShapeVisitor &)\n");
return 0;
}
// Operator binds:
};
osg::TriangleMesh* LunaTraits< osg::TriangleMesh >::_bind_ctor(lua_State *L) {
return luna_wrapper_osg_TriangleMesh::_bind_ctor(L);
}
void LunaTraits< osg::TriangleMesh >::_bind_dtor(osg::TriangleMesh* obj) {
osg::ref_ptr<osg::Referenced> refptr = obj;
}
const char LunaTraits< osg::TriangleMesh >::className[] = "TriangleMesh";
const char LunaTraits< osg::TriangleMesh >::fullName[] = "osg::TriangleMesh";
const char LunaTraits< osg::TriangleMesh >::moduleName[] = "osg";
const char* LunaTraits< osg::TriangleMesh >::parents[] = {"osg.Shape", 0};
const int LunaTraits< osg::TriangleMesh >::hash = 23977023;
const int LunaTraits< osg::TriangleMesh >::uniqueIDs[] = {50169651,0};
luna_RegType LunaTraits< osg::TriangleMesh >::methods[] = {
{"cloneType", &luna_wrapper_osg_TriangleMesh::_bind_cloneType},
{"clone", &luna_wrapper_osg_TriangleMesh::_bind_clone},
{"isSameKindAs", &luna_wrapper_osg_TriangleMesh::_bind_isSameKindAs},
{"libraryName", &luna_wrapper_osg_TriangleMesh::_bind_libraryName},
{"className", &luna_wrapper_osg_TriangleMesh::_bind_className},
{"accept", &luna_wrapper_osg_TriangleMesh::_bind_accept},
{"setVertices", &luna_wrapper_osg_TriangleMesh::_bind_setVertices},
{"getVertices", &luna_wrapper_osg_TriangleMesh::_bind_getVertices},
{"setIndices", &luna_wrapper_osg_TriangleMesh::_bind_setIndices},
{"getIndices", &luna_wrapper_osg_TriangleMesh::_bind_getIndices},
{"base_setThreadSafeRefUnref", &luna_wrapper_osg_TriangleMesh::_bind_base_setThreadSafeRefUnref},
{"base_setName", &luna_wrapper_osg_TriangleMesh::_bind_base_setName},
{"base_computeDataVariance", &luna_wrapper_osg_TriangleMesh::_bind_base_computeDataVariance},
{"base_setUserData", &luna_wrapper_osg_TriangleMesh::_bind_base_setUserData},
{"base_getUserData", &luna_wrapper_osg_TriangleMesh::_bind_base_getUserData},
{"base_releaseGLObjects", &luna_wrapper_osg_TriangleMesh::_bind_base_releaseGLObjects},
{"base_cloneType", &luna_wrapper_osg_TriangleMesh::_bind_base_cloneType},
{"base_clone", &luna_wrapper_osg_TriangleMesh::_bind_base_clone},
{"base_isSameKindAs", &luna_wrapper_osg_TriangleMesh::_bind_base_isSameKindAs},
{"base_libraryName", &luna_wrapper_osg_TriangleMesh::_bind_base_libraryName},
{"base_className", &luna_wrapper_osg_TriangleMesh::_bind_base_className},
{"base_accept", &luna_wrapper_osg_TriangleMesh::_bind_base_accept},
{"fromVoid", &luna_wrapper_osg_TriangleMesh::_bind_fromVoid},
{"asVoid", &luna_wrapper_osg_TriangleMesh::_bind_asVoid},
{"getTable", &luna_wrapper_osg_TriangleMesh::_bind_getTable},
{0,0}
};
luna_ConverterType LunaTraits< osg::TriangleMesh >::converters[] = {
{"osg::Referenced", &luna_wrapper_osg_TriangleMesh::_cast_from_Referenced},
{0,0}
};
luna_RegEnumType LunaTraits< osg::TriangleMesh >::enumValues[] = {
{0,0}
};
| [
"roche.emmanuel@gmail.com"
] | roche.emmanuel@gmail.com |
3f07c1f499054b73ccc7bf702526f945767abf15 | 3b424a008356da060bb0f228bdbd5566fcafa9a5 | /maincontent/controlwidget/openglcontrol/objectmodel/objectparent.cpp | 6adb57ea9c4613e3cb1a7e07b4849993ee86ef62 | [] | no_license | ylx167167/pi_ti_radar_32 | 058b0e9a1eb3a3cc17e76b69c32082844771eff2 | fbf3332289639b970bd2abe1d0816a4216b2f960 | refs/heads/main | 2023-03-08T17:06:23.139653 | 2021-02-23T17:26:12 | 2021-02-23T17:26:12 | 337,342,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,251 | cpp | /*****************************************
* 作者: YYC
* 日期: 2020-04-26
* 功能:3D模型父类,封装了模型的公共方法
* 包括模型位移,旋转
* VAO,VBO,EBO的创建,绑定,释放,销毁等
* 模型矩阵,观察矩阵,投影矩阵的设置和获取
* ***************************************/
#include "objectparent.h"
ObjectParent::ObjectParent() : m_vbo(QOpenGLBuffer::VertexBuffer), m_ebo(QOpenGLBuffer::IndexBuffer)
{
}
ObjectParent::~ObjectParent()
{
}
void ObjectParent::bind()
{
m_shaderLibrary.bind();
m_textureLibrary.bindAll();
m_vao.bind();
}
void ObjectParent::release()
{
m_textureLibrary.releaseAll();
m_shaderLibrary.release();
if (m_vao.isCreated())
{
m_vao.release();
}
}
void ObjectParent::destory()
{
if (m_vbo.isCreated())
{
m_vbo.destroy();
}
if (m_ebo.isCreated())
{
m_ebo.destroy();
}
if (m_vao.isCreated())
{
m_vao.destroy();
}
m_textureLibrary.destoryAll();
}
void ObjectParent::setupShader(const QString &vertexPath, const QString &fragmentPath)
{
bool successFlage = m_shaderLibrary.compileAndBindShaderFile(vertexPath, fragmentPath);
if(!successFlage)
{
qDebug() << "Compile shader error!";
}
}
void ObjectParent::setupTexture(const QImage &image)
{
if (nullptr != m_openGLWidget)
{
m_openGLWidget->makeCurrent();
}
m_textureLibrary.clearTexture();
m_textureLibrary.appendGlTexture(image);
if (nullptr != m_openGLWidget)
{
m_openGLWidget->doneCurrent();
}
}
void ObjectParent::setupTexture(const QString &imagePath)
{
m_textureLibrary.clearTexture();
m_textureLibrary.appendGlTexture(imagePath);
}
void ObjectParent::setupTexture(const QList<QString> &imagePathList)
{
m_textureLibrary.generateTexture(imagePathList);
}
void ObjectParent::setWindowWidth(const int &windowWidth)
{
m_windowWidth = windowWidth;
}
void ObjectParent::setWindowHeight(const int &windowHeight)
{
m_windowHeight = windowHeight;
}
void ObjectParent::setWindowSize(const int &windowWidth, const int &windowHeight)
{
m_windowWidth = windowWidth;
m_windowHeight = windowHeight;
}
void ObjectParent::translateByX(const GLfloat &valueData)
{
m_modelMat.translate(valueData, 0.0f, 0.0f);
}
void ObjectParent::translateByY(const GLfloat &valueData)
{
m_modelMat.translate(0.0f, valueData, 0.0f);
}
void ObjectParent::translateByZ(const GLfloat &valueData)
{
m_modelMat.translate(0.0f, 0.0f, valueData);
}
void ObjectParent::rotateByX(const GLfloat &angleData)
{
m_modelMat.rotate(angleData, 1.0f, 0.0f, 0.0f);
}
void ObjectParent::rotateByY(const GLfloat &angleData)
{
m_modelMat.rotate(angleData, 0.0f, 1.0f, 0.0f);
}
void ObjectParent::rotateByZ(const GLfloat &angleData)
{
m_modelMat.rotate(angleData, 0.0f, 0.0f, 1.0f);
}
void ObjectParent::setupPerspective(const GLfloat &angleData)
{
if (m_windowWidth != 0 && m_windowHeight != 0)
{
m_projMat.perspective(angleData, 1.0 * m_windowWidth / m_windowHeight, 0.1f, 100.0f);
}
}
int ObjectParent::getVertexCount()
{
return m_ebo.size() / sizeof(GLfloat);
}
void ObjectParent::setCameraLibrary(CameraLibrary *cameraLibrary)
{
m_cameraLibrary = cameraLibrary;
}
void ObjectParent::setOpenGLFunctions(QOpenGLFunctions *openGLFunctions)
{
m_openGLFunctions = openGLFunctions;
}
void ObjectParent::setOpenGLWidget(QOpenGLWidget *openGLWidget)
{
m_openGLWidget = openGLWidget;
m_textureLibrary.setOpenGLWidget(m_openGLWidget);
}
void ObjectParent::setupObjectShaderMat()
{
if (nullptr != m_cameraLibrary)
{
m_viewMat = m_cameraLibrary->getViewMat4x4();
}
m_shaderLibrary.setUniformValue("modelMat", m_modelMat);
m_shaderLibrary.setUniformValue("viewMat", m_viewMat);
m_shaderLibrary.setUniformValue("projMat", m_projMat);
}
void ObjectParent::makeObject()
{
}
void ObjectParent::drawObject()
{
if (nullptr != m_openGLFunctions)
{
this->bind();
this->setupObjectShaderMat();
m_openGLFunctions->glDrawElements(GL_TRIANGLES, this->getVertexCount(), GL_UNSIGNED_INT, nullptr);
this->release();
}
}
| [
"417838124@qq.com"
] | 417838124@qq.com |
91a4791ecb7c2fd7d8b3bade4ef77a57f8d8e26e | d3ae21e35098c1c41d78b64fe9a795674d25c8c7 | /GlebZikunov/Lab1.cpp | 5ddb66d0ee01407489b876c76c06d6291b168af0 | [] | no_license | PashaKlybik/prog-053504 | b761d2635da057c4031a1abd4209f0856f98f3fc | 47c5dffa49f2c69eb795ca5c00943f0ecd3f1fb4 | refs/heads/main | 2023-06-01T21:48:05.817632 | 2021-06-16T02:19:03 | 2021-06-16T02:19:03 | 341,505,018 | 0 | 41 | null | 2021-06-16T02:19:21 | 2021-02-23T09:49:26 | C | UTF-8 | C++ | false | false | 464 | cpp | #include <stdio.h>
int main()
{
int i;
printf("\n\n\n\t\t\t\t");
for (i = 1; i <= 1000; i++)
{
if ( i == (i * i) % 10 && i < 9)
{
printf("%d\t", i);
}
else if (i == (i * i) % 100 && i > 9 && i < 99)
{
printf("%d\t", i);
}
else if (i == (i * i) % 1000 && i > 99)
{
printf("%d\t", i);
}
}
printf("\n\n\n");
return 0;
}
| [
"noreply@github.com"
] | PashaKlybik.noreply@github.com |
33f904509374f9523fed361484b839453f86ef85 | c3007f04d2e5cdb0c4d08a6b9c23805c1e6f0fc1 | /week10/examples/example4/main.cpp | 6fcb617862811e623cc6c690e6d1d37a9cbf4290 | [] | no_license | haidao17/CPP | 17b217a468639c7e9dd1d0f9229deabc9716c9d6 | 2ceb5a24dbcd58d0539d80607b932e3066cce3a5 | refs/heads/main | 2023-09-02T21:45:48.118473 | 2021-11-21T13:22:48 | 2021-11-21T13:22:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | cpp | #include <iostream>
#include "time.hpp"
using namespace std;
int main()
{
MyTime t1(1, 20);
int minutes = t1; //implicit conversion
float f = float(t1); //explicit conversion.
std::cout << "minutes = " << minutes << std::endl;
std::cout << "minutes = " << f << std::endl;
MyTime t2 = 70;
std::cout << "t2 is " << t2 << std::endl;
MyTime t3;
t3 = 80;
std::cout << "t3 is " << t3 << std::endl;
return 0;
}
| [
"shiqi.yu@gmail.com"
] | shiqi.yu@gmail.com |
b68ffa9dc5e63aca319ea88f7ce0d91b23250c26 | aade1e73011f72554e3bd7f13b6934386daf5313 | /Contest/Opencup/XIX/Korea/H.cpp | 2ae3479cedb7e9629eb07c4af479d8dc40f64738 | [] | no_license | edisonhello/waynedisonitau123 | 3a57bc595cb6a17fc37154ed0ec246b145ab8b32 | 48658467ae94e60ef36cab51a36d784c4144b565 | refs/heads/master | 2022-09-21T04:24:11.154204 | 2022-09-18T15:23:47 | 2022-09-18T15:23:47 | 101,478,520 | 34 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,061 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
long long a, b, c, d; scanf("%lld%lld%lld%lld", &a, &b, &c, &d);
long long ans = 0;
for (int i = 1; i < 1000; ++i) {
for (int j = 1; j < 1000; ++j) {
if (i + j >= 1000) continue;
if (__gcd(i, j) != 1) continue;
// printf("i = %d j = %d\n", i, j);
long long fi = a / i;
if (i * fi < a) ++fi;
if (i * fi > b) continue;
long long fj = c / j;
if (j * fj < c) ++fj;
if (j * fj > d) continue;
// printf("fi = %lld fj = %lld\n", fi, fj);
long long si = (b + i - 1) / i;
if (i * si > b) --si;
assert(i * si <= b && i * si >= a);
long long sj = (d + j - 1) / j;
if (j * sj > d) --sj;
assert(j * sj <= d && j * sj >= c);
long long l = max(fi, fj), r = min(si, sj);
if (l > r) continue;
ans += r - l + 1;
}
}
printf("%lld\n", ans);
return 0;
}
| [
"tu.da.wei@gmail.com"
] | tu.da.wei@gmail.com |
065d0de2d8c4a16c2268da3e72925de626bd00c4 | 60d1716820a7c896da46c5816fcc4a733fec13a6 | /inference-engine/tests/functional/plugin/shared/src/single_layer_tests/rnn_sequence.cpp | 42aab9d64bef545a0dfc9c7388652d27dad26252 | [
"Apache-2.0"
] | permissive | TiredNotTear/openvino | 23290735f829cc2563d4af4fcdb617c1c504c435 | 77ecd7e17c6edce3f99e611459809a5f2353d0f1 | refs/heads/master | 2023-01-24T18:47:57.539273 | 2020-12-14T06:38:29 | 2020-12-14T06:38:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,413 | cpp | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <tuple>
#include <string>
#include <vector>
#include <memory>
#include <functional>
#include "ie_core.hpp"
#include "common_test_utils/common_utils.hpp"
#include "functional_test_utils/blob_utils.hpp"
#include "functional_test_utils/precision_utils.hpp"
#include "functional_test_utils/plugin_cache.hpp"
#include "functional_test_utils/skip_tests_config.hpp"
#include "single_layer_tests/rnn_sequence.hpp"
#include <transformations/op_conversions/bidirectional_sequences_decomposition.hpp>
#include <transformations/op_conversions/convert_sequences_to_tensor_iterator.hpp>
namespace LayerTestsDefinitions {
std::string RNNSequenceTest::getTestCaseName(const testing::TestParamInfo<RNNSequenceParams> &obj) {
ngraph::helpers::SequenceTestsMode mode;
size_t seq_lenghts;
size_t batch;
size_t hidden_size;
size_t input_size;
std::vector<std::string> activations;
std::vector<float> activations_alpha;
std::vector<float> activations_beta;
float clip;
ngraph::op::RecurrentSequenceDirection direction;
InferenceEngine::Precision netPrecision;
std::string targetDevice;
std::tie(mode, seq_lenghts, batch, hidden_size, input_size, activations, clip, direction, netPrecision,
targetDevice) = obj.param;
std::vector<std::vector<size_t>> inputShapes = {
{{batch, input_size}, {batch, hidden_size}, {batch, hidden_size}, {hidden_size, input_size},
{hidden_size, hidden_size}, {hidden_size}},
};
std::ostringstream result;
result << "mode=" << mode << "_";
result << "seq_lenghts=" << seq_lenghts << "_";
result << "batch=" << batch << "_";
result << "hidden_size=" << hidden_size << "_";
result << "input_size=" << input_size << "_";
result << "IS=" << CommonTestUtils::vec2str(inputShapes) << "_";
result << "activations=" << CommonTestUtils::vec2str(activations) << "_";
result << "direction=" << direction << "_";
result << "clip=" << clip << "_";
result << "netPRC=" << netPrecision.name() << "_";
result << "targetDevice=" << targetDevice << "_";
return result.str();
}
void RNNSequenceTest::SetUp() {
size_t seq_lenghts;
size_t batch;
size_t hidden_size;
size_t input_size;
std::vector<std::string> activations;
std::vector<float> activations_alpha;
std::vector<float> activations_beta;
float clip;
ngraph::op::RecurrentSequenceDirection direction;
InferenceEngine::Precision netPrecision;
std::tie(m_mode, seq_lenghts, batch, hidden_size, input_size, activations, clip, direction, netPrecision,
targetDevice) = this->GetParam();
size_t num_directions = direction == ngraph::op::RecurrentSequenceDirection::BIDIRECTIONAL ? 2 : 1;
std::vector<std::vector<size_t>> inputShapes = {
{{batch, seq_lenghts, input_size}, {batch, num_directions, hidden_size}, {batch},
{num_directions, hidden_size, input_size}, {num_directions, hidden_size, hidden_size},
{num_directions, hidden_size}},
};
m_max_seq_len = seq_lenghts;
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto params = ngraph::builder::makeParams(ngPrc, {inputShapes[0], inputShapes[1]});
if (m_mode == ngraph::helpers::SequenceTestsMode::CONVERT_TO_TI_MAX_SEQ_LEN_PARAM ||
m_mode == ngraph::helpers::SequenceTestsMode::CONVERT_TO_TI_RAND_SEQ_LEN_PARAM) {
auto seq_lengths = ngraph::builder::makeParams(ngraph::element::i64, {inputShapes[2]}).at(0);
seq_lengths->set_friendly_name("seq_lengths");
params.push_back(seq_lengths);
}
std::vector<ngraph::Shape> WRB = {inputShapes[3], inputShapes[4], inputShapes[5], inputShapes[2]};
auto rnn_sequence = ngraph::builder::makeRNN(ngraph::helpers::convert2OutputVector(ngraph::helpers::castOps2Nodes(params)),
WRB, hidden_size, activations, {}, {}, clip, true, direction,
m_mode);
ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(rnn_sequence->output(0)),
std::make_shared<ngraph::opset1::Result>(rnn_sequence->output(1))};
function = std::make_shared<ngraph::Function>(results, params, "rnn_sequence");
if (m_mode != ngraph::helpers::SequenceTestsMode::PURE_SEQ) {
ngraph::pass::Manager manager;
if (direction == ngraph::op::RecurrentSequenceDirection::BIDIRECTIONAL)
manager.register_pass<ngraph::pass::BidirectionalRNNSequenceDecomposition>();
manager.register_pass<ngraph::pass::ConvertRNNSequenceToTensorIterator>();
manager.run_passes(function);
bool ti_found = ngraph::helpers::is_tensor_iterator_exist(function);
EXPECT_EQ(ti_found, true);
} else {
bool ti_found = ngraph::helpers::is_tensor_iterator_exist(function);
EXPECT_EQ(ti_found, false);
}
}
void RNNSequenceTest::Infer() {
inferRequest = executableNetwork.CreateInferRequest();
inputs.clear();
for (const auto &input : executableNetwork.GetInputsInfo()) {
const auto &info = input.second;
auto blob = GenerateInput(*info);
if (input.first == "seq_lengths") {
blob = FuncTestUtils::createAndFillBlob(info->getTensorDesc(), m_max_seq_len, 0);
}
inferRequest.SetBlob(info->name(), blob);
inputs.push_back(blob);
}
if (configuration.count(InferenceEngine::PluginConfigParams::KEY_DYN_BATCH_ENABLED) &&
configuration.count(InferenceEngine::PluginConfigParams::YES)) {
auto batchSize = executableNetwork.GetInputsInfo().begin()->second->getTensorDesc().getDims()[0] / 2;
inferRequest.SetBatch(batchSize);
}
inferRequest.Infer();
}
TEST_P(RNNSequenceTest, CompareWithRefs) {
Run();
};
} // namespace LayerTestsDefinitions
| [
"noreply@github.com"
] | TiredNotTear.noreply@github.com |
c70fc1851041e2fab2acc40ad0c935df18389625 | 4903ae99e416302e5feade9f34be348297528f29 | /ImprovedLegoEditor/ComposeImageVertexShaderToon06.cpp | ae23a422b72ac828c2853a7d93af929cdb7b483c | [] | no_license | BlurEffect/LegoEditor | d334fb009490f45b43eb1d87eadc0655d4f7d257 | ff1a17ec828d01d492229e08341700b956e7a69c | refs/heads/master | 2021-01-15T23:07:39.439740 | 2015-01-11T19:11:49 | 2015-01-11T19:11:49 | 29,102,458 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,535 | cpp | /*
* Kevin Meergans, Improved Lego Editor, 2014
* ComposeImageVertexShaderToon06.cpp
* Contains the function definitions for the ComposeImageVertexShaderToon06 class.
*/
#include "ComposeImageVertexShaderToon06.h"
// The vertex input layout expected by this vertex shader
const D3D11_INPUT_ELEMENT_DESC ComposeImageVertexShaderToon06::m_sInputLayoutDescription[] =
{
// Vertex data
{ "POSITION" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
ComposeImageVertexShaderToon06::ComposeImageVertexShaderToon06( void ) : VertexShader()
{
}
//--------------------------------------------------------------------------------------
// Initialise the shader's member variables.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::Initialise( ID3D11Device* pDevice )
{
HRESULT hr;
// Create the shader
hr = pDevice -> CreateVertexShader( g_composeImageVertexShader06, sizeof( g_composeImageVertexShader06 ), nullptr, &m_pVertexShader );
if( FAILED ( hr ) )
{
return hr;
}
// Create the vertex input layout
UINT numElements = ARRAYSIZE( m_sInputLayoutDescription );
hr = pDevice -> CreateInputLayout( m_sInputLayoutDescription, numElements, g_composeImageVertexShader06, sizeof( g_composeImageVertexShader06 ), &m_pInputLayout );
if( FAILED ( hr ) )
{
return hr;
}
return S_OK;
}
//--------------------------------------------------------------------------------------
// Free all allocated resources.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::Cleanup( void )
{
return VertexShader::Cleanup();
}
//--------------------------------------------------------------------------------------
// Update the per-scene constant buffer of the shader.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::UpdatePerSceneData( ID3D11DeviceContext* pContext, const PerSceneData& perSceneData)
{
// Buffer not used in this shader
return E_FAIL;
}
//--------------------------------------------------------------------------------------
// Update the per-frame constant buffer of the shader.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::UpdatePerFrameData( ID3D11DeviceContext* pContext, const PerFrameData& perFrameData)
{
// Not used in this shader
return E_FAIL;
}
//--------------------------------------------------------------------------------------
// Update the per-object constant buffer of the shader.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::UpdatePerObjectData( ID3D11DeviceContext* pContext, const PerObjectData& perObjectData)
{
// Not used in this shader
return E_FAIL;
}
//--------------------------------------------------------------------------------------
// Update the texture and corresponding sample state being used by the shader.
//--------------------------------------------------------------------------------------
HRESULT ComposeImageVertexShaderToon06::UpdateTextureResource( int index, ID3D11DeviceContext* pContext, ID3D11ShaderResourceView* pTexture, ID3D11SamplerState* pSamplerState )
{
// Not used in this shader
return E_FAIL;
}
| [
"kevin.meergans@gmx.de"
] | kevin.meergans@gmx.de |
2eb6b0349d9b54051c7d28e758b2f3a23bb61567 | c44575cb90dfc9125c3a1c37dd333a7ebc4f022f | /raspberrypi/raspicam/src/private/private_types.h | c64333a53755a212ed65fd6ac52c73af5febb238 | [
"BSD-3-Clause"
] | permissive | abobco/Robot-Rover | 52a433126085d4b5f9e74e3053cf9802dac60f59 | dca21b3e6eeec83586f92d9dab1354cd67bd86e7 | refs/heads/main | 2023-06-29T07:07:47.507313 | 2021-07-30T06:18:55 | 2021-07-30T06:18:55 | 384,322,119 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,904 | h | /**********************************************************
Software developed by AVA ( Ava Group of the University of Cordoba, ava at uco dot es)
Main author Rafael Munoz Salinas (rmsalinas at uco dot es)
This software is released under BSD license as expressed below
-------------------------------------------------------------------
Copyright (c) 2013, AVA ( Ava Group University of Cordoba, ava at uco dot es)
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. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Ava group of the University of Cordoba.
4. Neither the name of the University 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 AVA ''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 AVA BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****************************************************************/
#ifndef _RaspiCam_private_types_H
#define _RaspiCam_private_types_H
namespace raspicam {
namespace _private{
/// struct contain camera settings
struct MMAL_PARAM_COLOURFX_T
{
int enable,u,v; /// Turn colourFX on or off, U and V to use
} ;
struct PARAM_FLOAT_RECT_T
{
double x,y,w,h;
} ;
/** Structure containing all state information for the current run
*/
struct RASPIVID_STATE
{
int sensor_mode; /// Requested width of image
int width; /// Requested width of image
int height; /// requested height of image
int framerate; /// Requested frame rate (fps)
/// the camera output or the encoder output (with compression artifacts)
MMAL_COMPONENT_T *camera_component; /// Pointer to the camera component
MMAL_POOL_T *video_pool; /// Pointer to the pool of buffers used by encoder output port
//camera params
int sharpness; /// -100 to 100
int contrast; /// -100 to 100
int brightness; /// 0 to 100
int saturation; /// -100 to 100
int ISO; /// TODO : what range?
bool videoStabilisation; /// 0 or 1 (false or true)
int exposureCompensation; /// -10 to +10 ?
int shutterSpeed;
RASPICAM_FORMAT captureFtm;
RASPICAM_EXPOSURE rpc_exposureMode;
RASPICAM_METERING rpc_exposureMeterMode;
RASPICAM_AWB rpc_awbMode;
RASPICAM_IMAGE_EFFECT rpc_imageEffect;
MMAL_PARAMETER_IMAGEFX_PARAMETERS_T imageEffectsParameters;
MMAL_PARAM_COLOURFX_T colourEffects;
int rotation; /// 0-359
int hflip; /// 0 or 1
int vflip; /// 0 or 1
PARAM_FLOAT_RECT_T roi; /// region of interest to use on the sensor. Normalised [0,1] values in the rect
float awbg_red;//white balance red and blue
float awbg_blue;
} ;
//clean buffer
template<typename T>
class membuf{
public:
membuf() {
data=0;
size=0;
}
~membuf() {
if ( data!=0 ) delete []data;
}
void resize ( size_t s ) {
if ( s!=size ) {
delete data;
size=s;
data=new T[size];
}
}
T *data;
size_t size;
};
}
}
#endif
| [
"abobco@gmail.com"
] | abobco@gmail.com |
e506d5d255a9a28616e7402716a5802486640e37 | ba9485e8ea33acee24dc7bd61049ecfe9f8b8930 | /yk/784.cpp | dbefc0e6b3cc482201f85d869108bb084125ef94 | [] | no_license | diohabara/competitive_programming | a0b90a74b0b923a636b9c82c75b690fef11fe8a4 | 1fb493eb44ce03e289d1245bf7d3dc450f513135 | refs/heads/master | 2021-12-11T22:43:40.925262 | 2021-11-06T12:56:49 | 2021-11-06T12:56:49 | 166,757,685 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
#define ll long long
#define endl '\n'
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
string s;
cin >> s;
for (int i = 0; i < s.size(); i++) {
}
return 0;
} | [
"kadoitakemaru0902@g.ecc.u-tokyo.ac.jp"
] | kadoitakemaru0902@g.ecc.u-tokyo.ac.jp |
bf431f4e0c60d0d2a97442d5cfe2bc89663dda0c | ac9b294ed1b27504f1468ff0ac7a82eb982cf8d0 | /eGENIEPaperCode/treeProducer_simulation_save.cpp | 638442a244dd4abf88853f20094ec03df47b8760 | [] | no_license | afropapp13/e4nu | d8f1073d630745e61842587891ca5fd04bc6a5e8 | 8cb00a1ee852648ac8a7ac79cde461cb2217eca5 | refs/heads/master | 2023-06-24T23:37:21.926850 | 2022-03-02T17:09:12 | 2022-03-02T17:09:12 | 198,716,604 | 0 | 0 | null | 2019-07-24T22:15:24 | 2019-07-24T22:15:24 | null | UTF-8 | C++ | false | false | 15,778 | cpp | #define treeProducer_simulation_cxx
#include "treeProducer_simulation.h"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TH1D.h>
#include <TFile.h>
#include <iomanip>
#include <TString.h>
#include <TMath.h>
#include <TVector3.h>
#include <TLorentzVector.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void treeProducer_simulation::Loop() {
if (fChain == 0) return;
Long64_t nentries = fChain->GetEntriesFast();
TH1D::SetDefaultSumw2();
TH2D::SetDefaultSumw2();
// -------------------------------------------------------------------------------
// Binding Energy
double BE = 0.02; // GeV
// -------------------------------------------------------------------------------
TString FileName = "myFiles/"+fNucleus+"_"+fEnergy+"_"+fTune+"_"+fInteraction+".root";
TFile* file = new TFile(FileName,"recreate");
std::cout << std::endl << "File " << FileName << " will be created" << std::endl << std::endl;
const double ProtonMass = .9383, MuonMass = .106, NeutronMass = 0.9396, ElectronMass = 0.000511; // [GeV]
int MissMomentumBin = 99;
// -------------------------------------------------------------------------------
// Ranges & Binning
int NBinsQ2 = 56; double MinQ2 = 0.1, MaxQ2 = 1.5; TString TitleQ2 = ";Q^{2} [GeV^{2}/c^{2}];";
int NBinsxB = 25; double MinxB = 0.7, MaxxB = 1.3; TString TitlexB = ";x_{B};";
int NBinsnu = 50; double Minnu = 0., Maxnu = 1.2; TString Titlenu = ";Energy Transfer [GeV];";
int NBinsW = 20; double MinW = 0.7, MaxW = 1.2; TString TitleW = ";W (GeV/c^{2});";
int NBinsPmiss = 40; double MinPmiss = 0., MaxPmiss = 1.; TString TitlePmiss = ";P_{T} [GeV/c];";
int NBinsPionMulti = 4; double MinPionMulti = -0.5, MaxPionMulti = 3.5; TString TitlePionMulti = ";Pion Multiplicity;";
int NBinsReso = 30; double MinReso = -50., MaxReso = 10.; TString TitleReso = ";#frac{E^{cal} - E^{beam}}{E^{beam}} (%);";
int NBinsDeltaPhiT = 18; double MinDeltaPhiT = 0., MaxDeltaPhiT = 80.; TString TitleDeltaPhiT = ";#delta#phi_{T} (degrees);";
int NBinsDeltaAlphaT = 18; double MinDeltaAlphaT = 0., MaxDeltaAlphaT = 180.; TString TitleDeltaAlphaT = ";#delta#alpha_{T} (degrees);";
TString TitleQ2Vsnu = ";Energy Transfer [GeV];Q^{2} [GeV^{2}/c^{2}];";
TString TitleQ2VsW = ";W [GeV/c^{2}];Q^{2} [GeV^{2}/c^{2}];";
// -------------------------------------------------------------------------------
// Electron
int NBinsElectronEnergy = 40; double MinElectronEnergy = 0., MaxElectronEnergy = 1.2; TString TitleElectronEnergy = ";E_{e'} (GeV);";
int NBinsElectronPhi = 45; double MinElectronPhi = 0., MaxElectronPhi = 360.; TString TitleElectronPhi = ";#phi_{e'} (degrees);";
int NBinsElectronTheta = 15; double MinElectronTheta = 15., MaxElectronTheta = 53.; TString TitleElectronTheta = ";#theta_{e'} (degrees);";
int NBinsElectronCosTheta = 40; double MinElectronCosTheta = -1, MaxElectronCosTheta = 1.; TString TitleElectronCosTheta = ";cos(#theta_{e'});";
int NBinsElectronMom = 40; double MinElectronMom = 1.7, MaxElectronMom = 4.; TString TitleElectronMom = ";P_{e'} (GeV/c);";
TString TitleElectronPhiVsTheta = ";#phi_{e'} (degrees);#theta_{e'} (degrees);";
// -------------------------------------------------------------------------------
// Proton
int NBinsEp = 40; double MinEp = 0.9, MaxEp = 2.2; TString TitleEp = ";E_{p} (GeV);";
int NBinsProtonPhi = 45; double MinProtonPhi = 0., MaxProtonPhi = 360.; TString TitleProtonPhi = ";#phi_{p} (degrees);";
int NBinsProtonTheta = 30; double MinProtonTheta = 10., MaxProtonTheta = 120.; TString TitleProtonTheta = ";#theta_{p} (degrees);";
int NBinsProtonCosTheta = 40; double MinProtonCosTheta = -0.2, MaxProtonCosTheta = 1.; TString TitleProtonCosTheta = ";cos(#theta_{p});";
TString TitleProtonEnergyVsMissMomentum = ";P_{T} (GeV/c);E_{p} (GeV);";
TString TitleQ2VsMissMomentum = ";P_{T} (GeV/c);Q^{2} (GeV^{2}/c^{2});";
// -------------------------------------------------------------------------------
TH1D* Q2Plot = new TH1D("Q2Plot",TitleQ2,NBinsQ2,MinQ2,MaxQ2);
TH1D* xBPlot = new TH1D("xBPlot",TitlexB,NBinsxB,MinxB,MaxxB);
TH1D* nuPlot = new TH1D("nuPlot",Titlenu,NBinsnu,Minnu,Maxnu);
TH1D* WPlot = new TH1D("WPlot",TitleW,NBinsW,MinW,MaxW);
TH1D* MissMomentumPlot = new TH1D("MissMomentumPlot",TitlePmiss,NBinsPmiss,MinPmiss,MaxPmiss);
TH1D* PionMultiPlot = new TH1D("PionMultiPlot",TitlePionMulti,NBinsPionMulti,MinPionMulti,MaxPionMulti);
TH1D* PionMultiQEPlot = new TH1D("PionMultiQEPlot",TitlePionMulti,NBinsPionMulti,MinPionMulti,MaxPionMulti);
TH2D* Q2VsnuPlot = new TH2D("Q2VsnuPlot",TitleQ2Vsnu,NBinsnu,Minnu,Maxnu,NBinsQ2,MinQ2,MaxQ2);
TH2D* Q2VsWPlot = new TH2D("Q2VsWPlot",TitleQ2VsW,NBinsW,MinW,MaxW,NBinsQ2,MinQ2,MaxQ2);
// Electron
TH1D* ElectronEnergyPlot = new TH1D("ElectronEnergyPlot",TitleElectronEnergy,NBinsElectronEnergy,MinElectronEnergy,MaxElectronEnergy);
TH1D* ElectronPhiPlot = new TH1D("ElectronPhiPlot",TitleElectronPhi,NBinsElectronPhi,MinElectronPhi,MaxElectronPhi);
TH1D* ElectronThetaPlot = new TH1D("ElectronThetaPlot",TitleElectronTheta,NBinsElectronTheta,MinElectronTheta,MaxElectronTheta);
TH1D* ElectronCosThetaPlot = new TH1D("ElectronCosThetaPlot",TitleElectronCosTheta,NBinsElectronCosTheta,MinElectronCosTheta,MaxElectronCosTheta);
TH2D* ElectronPhiThetaPlot = new TH2D("ElectronPhiThetaPlot",TitleElectronPhiVsTheta,NBinsElectronPhi,MinElectronPhi,MaxElectronPhi,NBinsElectronTheta,MinElectronTheta,MaxElectronTheta);
// Proton
TH1D* ProtonEnergyPlot = new TH1D("ProtonEnergyPlot",TitleEp,NBinsEp,MinEp,MaxEp);
TH1D* ProtonPhiPlot = new TH1D("ProtonPhiPlot",TitleProtonPhi,NBinsProtonPhi,MinProtonPhi,MaxProtonPhi);
TH1D* ProtonThetaPlot = new TH1D("ProtonThetaPlot",TitleProtonTheta,NBinsProtonTheta,MinProtonTheta,MaxProtonTheta);
TH1D* ProtonCosThetaPlot = new TH1D("ProtonCosThetaPlot",TitleProtonCosTheta,NBinsProtonCosTheta,MinProtonCosTheta,MaxProtonCosTheta);
TH1D* EcalResoPlot = new TH1D("EcalResoPlot",TitleReso,NBinsReso,MinReso,MaxReso);
TH2D* EpVsMissMomentumPlot = new TH2D("EpVsMissMomentumPlot",TitleProtonEnergyVsMissMomentum,NBinsPmiss,MinPmiss,MaxPmiss,NBinsEp,MinEp,MaxEp);
TH2D* Q2VsMissMomentumPlot = new TH2D("Q2VsMissMomentumPlot",TitleQ2VsMissMomentum,NBinsPmiss,MinPmiss,MaxPmiss,NBinsQ2,MinQ2,MaxQ2);
TH1D* DeltaPhiTPlot = new TH1D("DeltaPhiTPlot",TitleDeltaPhiT,NBinsDeltaPhiT,MinDeltaPhiT,MaxDeltaPhiT);
TH1D* DeltaAlphaTPlot = new TH1D("DeltaAlphaTPlot",TitleDeltaAlphaT,NBinsDeltaAlphaT,MinDeltaAlphaT,MaxDeltaAlphaT);
// -------------------------------------------------------------------------------------
int NBinsCalorimetricEnergy = 400; double MinCalorimetricEnergy = 0.,MaxCalorimetricEnergy = 6.; TString TitleCalorimetricEnergy = ";E^{cal} (GeV);";
TH1D* epRecoEnergy_slice_0Plot = new TH1D("epRecoEnergy_slice_0Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy);
TH1D* epRecoEnergy_slice_1Plot = new TH1D("epRecoEnergy_slice_1Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy);
TH1D* epRecoEnergy_slice_2Plot = new TH1D("epRecoEnergy_slice_2Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy);
TH1D* epRecoEnergy_slice_3Plot = new TH1D("epRecoEnergy_slice_3Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy);
int NBinsLeptonicEnergy = 200; double MinLeptonicEnergy = 0.,MaxLeptonicEnergy = 6.; TString TitleLeptonicEnergy = ";E^{QE} (GeV);";
TH1D* eRecoEnergy_slice_0Plot = new TH1D("eRecoEnergy_slice_0Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy);
TH1D* eRecoEnergy_slice_1Plot = new TH1D("eRecoEnergy_slice_1Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy);
TH1D* eRecoEnergy_slice_2Plot = new TH1D("eRecoEnergy_slice_2Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy);
TH1D* eRecoEnergy_slice_3Plot = new TH1D("eRecoEnergy_slice_3Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy);
// -------------------------------------------------------------------------------------------------------------
// 2D Inclusive Plots
TH2D* QE_Q0_Q3_Plot = new TH2D("QE_Q0_Q3_Plot",";q_{3} [GeV/c];q_{0} [GeV]",200,0,2.,200,0.,2.);
TH2D* MEC_Q0_Q3_Plot = new TH2D("MEC_Q0_Q3_Plot",";q_{3} [GeV/c];q_{0} [GeV]",200,0,2.,200,0.,2.);
// -------------------------------------------------------------------------------------------------------------
int countEvents = 0; Long64_t nbytes = 0, nb = 0;
// -------------------------------------------------------------------------------------------------------------
for (Long64_t jentry=0; jentry<nentries;jentry++) {
Long64_t ientry = LoadTree(jentry);
if (ientry < 0) break;
nb = fChain->GetEntry(jentry); nbytes += nb;
if (jentry%1000 == 0) std::cout << jentry/1000 << " k " << std::setprecision(3) << double(jentry)/nentries*100. << " %"<< std::endl;
// ------------------------------------------------------------------------------------------
double Ebeam = 1.161;
/*
if (W > 2) { continue; }
if (fEnergy == "1161") {
if (Q2 < 0.1) { continue; }
if (El < 0.4) { continue; }
}
if (fEnergy == "2261") {
if (Q2 < 0.4) { continue; }
if (El < 0.55) { continue; }
Ebeam = 2.261;
}
if (fEnergy == "4461") {
if (Q2 < 0.8) { continue; }
if (El < 1.1) { continue; }
Ebeam = 4.461;
}
*/
// ------------------------------------------------------------------------------------------
int ProtonTagging = 0, ChargedPionPlusTagging = 0, ChargedPionMinusTagging = 0, GammaTagging = 0, NeutralPionTagging = 0;
vector <int> ProtonID;
ProtonID.clear();
for (int i = 0; i < nf; i++) {
if (pdgf[i] == 2212 && pf[i] > 0.3) {
ProtonTagging ++;
ProtonID.push_back(i);
}
if (pdgf[i] == 211 && pf[i] > 0.15) {
ChargedPionPlusTagging ++;
}
if (pdgf[i] == -211 && pf[i] > 0.15) {
ChargedPionMinusTagging ++;
}
if (pdgf[i] == 22 && pf[i] > 0.3) { GammaTagging ++; }
if (pdgf[i] == 111 && pf[i] > 0.5) { NeutralPionTagging ++; }
}
// -------------------------------------------------------------------------------------
/*
if (ProtonTagging != 1) { continue; }
if (ChargedPionPlusTagging != 0) { continue; }
if (ChargedPionMinusTagging != 0) { continue; }
if (GammaTagging != 0) { continue; }
if (NeutralPionTagging != 0) { continue; }
*/
// -------------------------------------------------------------------------------------
TLorentzVector ProbeV4(pxv,pyv,pzv,Ev);
TLorentzVector ElectronV4(pxl,pyl,pzl,El);
double ElectronMom = ElectronV4.Rho();
double ElectronTheta = ElectronV4.Theta()*180./TMath::Pi();
if (ElectronTheta < 0) { ElectronTheta += 180.;}
if (ElectronTheta > 180) { ElectronTheta -= 180.;}
double ElectronCosTheta = ElectronV4.CosTheta();
double ElectronPhi = ElectronV4.Phi()*180./TMath::Pi();
if (ElectronPhi < 0) { ElectronPhi += 360.;}
if (ElectronPhi > 360) { ElectronPhi -= 360.;}
TLorentzVector qV4 = ProbeV4 - ElectronV4;
double nu = qV4.E();
double q3 = qV4.Rho();
// QE Energy Reconstruction
double EQE = (2*ProtonMass*BE + 2*ProtonMass*El - pow(ElectronMass,2)) / 2 / (ProtonMass - El + ElectronMom * ElectronCosTheta);
// -----------------------------------------------------------------------------------------------------
/*
// Proton
TLorentzVector ProtonV4(pxf[ProtonID[0]],pyf[ProtonID[0]],pzf[ProtonID[0]],Ef[ProtonID[0]]);
double ProtonE = ProtonV4.E();
double ProtonMom = ProtonV4.Rho();
double ProtonTheta = ProtonV4.Theta()*180./TMath::Pi();
if (ProtonTheta < 0) { ProtonTheta += 180.; }
if (ProtonTheta > 180) { ProtonTheta -= 180.; }
double ProtonCosTheta = ProtonV4.CosTheta();
double ProtonPhi = ProtonV4.Phi()*180./TMath::Pi();
if (ProtonPhi < 0) { ProtonPhi += 360; }
if (ProtonPhi > 360) { ProtonPhi -= 360; }
// Calorimetric Energy Reconstruction
double Ecal = El + ProtonE - ProtonMass + BE;
// Transverse variables
TVector3 ProtonT(ProtonV4.X(),ProtonV4.Y(),0);
double ProtonTMag = ProtonT.Mag();
TVector3 ElectronT(ElectronV4.X(),ElectronV4.Y(),0);
double ElectronTMag = ElectronT.Mag();
TVector3 MissMomentumT = ProtonT + ElectronT;
double MissMomentumTMag = MissMomentumT.Mag();
double DeltaPhiT = TMath::ACos(-ProtonT*ElectronT/ProtonTMag/ElectronTMag)*180/TMath::Pi();
double DeltaAlphaT = TMath::ACos(-MissMomentumT*ElectronT/MissMomentumTMag/ElectronTMag)*180/TMath::Pi();
*/
// -------------------------------------------------------------------------------------------------------
double Weight = 1.;
if (fInteraction == "EM+MEC") { Weight = Q2*Q2; }
if (fabs(Weight) != Weight) continue;
// -----------------------------------------------------------------------------------------------
countEvents ++; // Increase the number of the events that pass the cuts by one
// ----------------------------------------------------------------------------------------------
// Define the missing momentum bin
/*
if (MissMomentumTMag < 0.2) MissMomentumBin = 1;
if (MissMomentumTMag > 0.2 && MissMomentumTMag < 0.4) MissMomentumBin = 2;
if (MissMomentumTMag > 0.4) MissMomentumBin = 3;
*/
// ------------------------------------------------------------------------------------------------
Q2Plot->Fill(Q2,Weight);
nuPlot->Fill(nu,Weight);
WPlot->Fill(W,Weight);
xBPlot->Fill(x,Weight);
//MissMomentumPlot->Fill(MissMomentumTMag,Weight);
// 1D Electron Plots
ElectronThetaPlot->Fill(ElectronTheta,Weight);
ElectronCosThetaPlot->Fill(ElectronCosTheta,Weight);
ElectronPhiPlot->Fill(ElectronPhi,Weight);
ElectronEnergyPlot->Fill(El,Weight);
ElectronPhiThetaPlot->Fill(ElectronPhi,ElectronTheta,Weight);
// 1D Proton Plots
/*
ProtonCosThetaPlot->Fill(ProtonCosTheta,Weight);
ProtonThetaPlot->Fill(ProtonTheta,Weight);
ProtonPhiPlot->Fill(ProtonPhi,Weight);
ProtonEnergyPlot->Fill(ProtonE,Weight);
EcalResoPlot->Fill((Ecal - Ebeam) / Ebeam * 100.,Weight);
*/
// 2D Plots
Q2VsWPlot->Fill(W,Q2,Weight);
Q2VsnuPlot->Fill(nu,Q2,Weight);
if (qel == 1) { QE_Q0_Q3_Plot->Fill(q3,nu,Weight); }
if (mec == 1) { MEC_Q0_Q3_Plot->Fill(q3,nu,Weight); }
/*EpVsMissMomentumPlot->Fill(MissMomentumTMag,ProtonE,Weight);
Q2VsMissMomentumPlot->Fill(MissMomentumTMag,Q2,Weight);
DeltaPhiTPlot->Fill(DeltaPhiT,Weight);
DeltaAlphaTPlot->Fill(DeltaAlphaT,Weight);
// Reconstructed Energy Plots
epRecoEnergy_slice_0Plot->Fill(Ecal,Weight); eRecoEnergy_slice_0Plot->Fill(EQE,Weight);
if (MissMomentumBin == 1) { epRecoEnergy_slice_1Plot->Fill(Ecal,Weight); eRecoEnergy_slice_1Plot->Fill(EQE,Weight);}
if (MissMomentumBin == 2) { epRecoEnergy_slice_2Plot->Fill(Ecal,Weight); eRecoEnergy_slice_2Plot->Fill(EQE,Weight);}
if (MissMomentumBin == 3) { epRecoEnergy_slice_3Plot->Fill(Ecal,Weight); eRecoEnergy_slice_3Plot->Fill(EQE,Weight);}
*/
} // end of the loop over events
// ----------------------------------------------------------------------------------------------------------------
// Print this message after the loop over the events
std::cout << std::endl;
std::cout << "File " << FileName << " created " << std::endl;
std::cout << std::endl;
std::cout << "Efficiency = " << double(countEvents)/ double(nentries)*100. << " %" << std::endl; std::cout << std::endl;
file->Write(); file->Close();
} // End of the program
// ----------------------------------------------------------------------------------------------------------------
| [
"afropapp@yahoo.gr"
] | afropapp@yahoo.gr |
1edc8860c55f53612a98b3e0ed5f53ce261d0a1c | 30deab0afc113791f86ec71f75f0ff4113ed7f8e | /Ludo/picture demmo/PictureDemo.cpp | ec146f46d045f65fcd5a44e3ad30ae588893609a | [] | no_license | FaiyazMohammadSaif/Ludo_Game | 347643123fa2bb1d645cb11a8f69bba530342e01 | f90290a8f4e55cbbc18f1f1d00ac43c9077f74cd | refs/heads/master | 2020-08-03T23:28:30.018965 | 2019-10-07T18:15:54 | 2019-10-07T18:15:54 | 211,920,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,119 | cpp | /*
author: S. M. Shahriar Nirjon
last modified: August 8, 2008
*/
# include "iGraphics.h"
int pic_x, pic_y;
/*
function iDraw() is called again and again by the system.
*/
void iDraw()
{
//place your drawing codes here
iClear();
iShowBMP(pic_x, pic_y, "smurf.bmp");
iText(10, 10, "Use cursors to move the picture.");
}
/*
function iMouseMove() is called when the user presses and drags the mouse.
(mx, my) is the position where the mouse pointer is.
*/
void iMouseMove(int mx, int my)
{
//place your codes here
}
/*
function iMouse() is called when the user presses/releases the mouse.
(mx, my) is the position where the mouse pointer is.
*/
void iMouse(int button, int state, int mx, int my)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
//place your codes here
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
//place your codes here
}
}
/*
function iKeyboard() is called whenever the user hits a key in keyboard.
key- holds the ASCII value of the key pressed.
*/
void iKeyboard(unsigned char key)
{
if(key == 'x')
{
//do something with 'x'
exit(0);
}
//place your codes for other keys here
}
/*
function iSpecialKeyboard() is called whenver user hits special keys like-
function keys, home, end, pg up, pg down, arraows etc. you have to use
appropriate constants to detect them. A list is:
GLUT_KEY_F1, GLUT_KEY_F2, GLUT_KEY_F3, GLUT_KEY_F4, GLUT_KEY_F5, GLUT_KEY_F6,
GLUT_KEY_F7, GLUT_KEY_F8, GLUT_KEY_F9, GLUT_KEY_F10, GLUT_KEY_F11, GLUT_KEY_F12,
GLUT_KEY_LEFT, GLUT_KEY_UP, GLUT_KEY_RIGHT, GLUT_KEY_DOWN, GLUT_KEY_PAGE UP,
GLUT_KEY_PAGE DOWN, GLUT_KEY_HOME, GLUT_KEY_END, GLUT_KEY_INSERT
*/
void iSpecialKeyboard(unsigned char key)
{
if(key == GLUT_KEY_END)
{
exit(0);
}
if(key == GLUT_KEY_LEFT)
{
pic_x-=5;
}
if(key == GLUT_KEY_RIGHT)
{
pic_x+=5;
}
if(key == GLUT_KEY_UP)
{
pic_y+=5;
}
if(key == GLUT_KEY_DOWN)
{
pic_y-=5;
}
//place your codes for other keys here
}
int main()
{
//place your own initialization codes here.
pic_x = 30;
pic_y = 30;
iInitialize(400, 400, "PictureDemo");
return 0;
} | [
"faiyazsaif17@gmail.com"
] | faiyazsaif17@gmail.com |
9905bd018c94bbeb8e37272ccb89940427b514a0 | dfadd879ccc98bb99c45651a33c80c18181589d9 | /ZeroLibraries/Math/EulerOrder.hpp | a19dc4c5e0946d60d695c7448c4be8d6c6866ee7 | [
"MIT"
] | permissive | zeroengineteam/ZeroCore | f690bcea76e1040fe99268bd83a2b76e3e65fb54 | 14dc0df801b4351a2e9dfa3ce2dc27f68f8c3e28 | refs/heads/1.4.2 | 2022-02-26T04:05:51.952560 | 2021-04-09T23:27:57 | 2021-04-09T23:27:57 | 148,349,710 | 54 | 27 | MIT | 2022-02-08T18:28:30 | 2018-09-11T16:51:46 | C++ | UTF-8 | C++ | false | false | 4,553 | hpp | ///////////////////////////////////////////////////////////////////////////////
///
/// \file EulerOrder.hpp
/// Declaration of the Euler angles order as described in Graphic Gems IV,
/// EulerOrder design referenced from Insomniac Games.
///
/// Authors: Benjamin Strukus
/// Copyright 2010-2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Math
{
/*
Ken Shoemake, 1993
Order type constants, constructors, extractors
There are 24 possible conventions, designated by:
- EulAxI = axis used initially
- EulPar = parity of axis permutation
- EulRep = repetition of initial axis as last
- EulFrm = frame from which axes are taken
Axes I, J, K will be a permutation of X, Y, Z.
Axis H will be either I or K, depending on EulRep.
Frame S takes axes from initial static frame.
If ord = (AxI = X, Par = Even, Rep = No, Frm = S), then
{a, b, c, ord} means Rz(c)Ry(b)Rx(a), where Rz(c)v
rotates v around Z by c radians
*/
namespace EulerOrders
{
const uint Safe[4] = { 0, 1, 2, 0 };
const uint Next[4] = { 1, 2, 0, 1 };
///The two different types of reference frames
const uint Static = 0;
const uint Rotated = 1;
///The two different states of "is there a repeated axis?"
const uint No = 0;
const uint Yes = 1;
///Two different states of parity
const uint Even = 0;
const uint Odd = 1;
///CreateOrder creates an order value between 0 and 23 from 4-tuple choices.
#define CreateOrder(axis, parity, repeated, frame) (((((((axis) << 1) + \
(parity)) << 1) + \
(repeated)) << 1) + \
(frame))
///Bit fields to describe the different permutations of rotations, reference
///frames, repeated axes, and parity
enum Enum
{
X = 0,
Y,
Z,
//Static axes
XYZs = CreateOrder(X, Even, No, Static),
XYXs = CreateOrder(X, Even, Yes, Static),
XZYs = CreateOrder(X, Odd, No, Static),
XZXs = CreateOrder(X, Odd, Yes, Static),
YZXs = CreateOrder(Y, Even, No, Static),
YZYs = CreateOrder(Y, Even, Yes, Static),
YXZs = CreateOrder(Y, Odd, No, Static),
YXYs = CreateOrder(Y, Odd, Yes, Static),
ZXYs = CreateOrder(Z, Even, No, Static),
ZXZs = CreateOrder(Z, Even, Yes, Static),
ZYXs = CreateOrder(Z, Odd, No, Static),
ZYZs = CreateOrder(Z, Odd, Yes, Static),
//Rotating axes
ZYXr = CreateOrder(X, Even, No, Rotated),
XYXr = CreateOrder(X, Even, Yes, Rotated),
YZXr = CreateOrder(X, Odd, No, Rotated),
XZXr = CreateOrder(X, Odd, Yes, Rotated),
XZYr = CreateOrder(Y, Even, No, Rotated),
YZYr = CreateOrder(Y, Even, Yes, Rotated),
ZXYr = CreateOrder(Y, Odd, No, Rotated),
YXYr = CreateOrder(Y, Odd, Yes, Rotated),
YXZr = CreateOrder(Z, Even, No, Rotated),
ZXZr = CreateOrder(Z, Even, Yes, Rotated),
XYZr = CreateOrder(Z, Odd, No, Rotated),
ZYZr = CreateOrder(Z, Odd, Yes, Rotated)
};
#undef CreateOrder
}// namespace EulerOrders
struct EulerOrder;
typedef EulerOrder& EulerOrderRef;
typedef const EulerOrder& EulerOrderParam;
///Structure to hold the order of rotations when dealing with Euler angles,
///whether or not there are any repeating angles, and if the rotations are being
///described in a fixed or rotated frame of reference.
struct ZeroShared EulerOrder
{
EulerOrder(EulerOrders::Enum eulerOrder);
EulerOrder& operator = (EulerOrderParam rhs);
bool operator == (EulerOrderParam rhs);
bool operator != (EulerOrderParam rhs);
///Get the index of the first angle in the Euler angle rotation sequence.
uint I(void) const;
///Get the index of the second angle in the Euler angle rotation sequence.
uint J(void) const;
///Get the index of the third angle in the Euler angle rotation sequence.
uint K(void) const;
///Will be I if there are repeating angles, will be K otherwise.
uint H(void) const;
bool RepeatingAngles(void) const;
bool RotatingFrame(void) const;
bool OddParity(void) const;
///Unpacks all useful information about order simultaneously.
static void GetOrder(EulerOrder order, uint& i, uint& j, uint& k, uint& h,
uint& parity, uint& repeated, uint& frame);
EulerOrders::Enum Order;
};
}// namespace Math
| [
"arend.danielek@zeroengine.io"
] | arend.danielek@zeroengine.io |
c091f010bc589eb9c25e39726e4281ded41586d1 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/iis/admin/common/ipa.h | 174bac34e4062a244ad32ae52f11c93f1194ee4d | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 7,989 | h | /*++
Copyright (c) 1994-1998 Microsoft Corporation
Module Name :
ipa.h
Abstract:
IP Address value
Author:
Ronald Meijer (ronaldm)
Project:
Internet Services Manager
Revision History:
--*/
#ifndef _IPA_H
#define _IPA_H
//
// IP Address Conversion Macros
//
#ifdef MAKEIPADDRESS
#undef MAKEIPADDRESS
#endif // MAKEIPADDRESS
#define MAKEIPADDRESS(b1,b2,b3,b4) (((DWORD)(b1)<<24) +\
((DWORD)(b2)<<16) +\
((DWORD)(b3)<< 8) +\
((DWORD)(b4)))
#ifndef GETIP_FIRST
#define GETIP_FIRST(x) ((x>>24) & 0xff)
#define GETIP_SECOND(x) ((x>>16) & 0xff)
#define GETIP_THIRD(x) ((x>> 8) & 0xff)
#define GETIP_FOURTH(x) ((x) & 0xff)
#endif // GETIP_FIRST
//
// Some predefined IP values
//
#define NULL_IP_ADDRESS (DWORD)(0x00000000)
#define NULL_IP_MASK (DWORD)(0xFFFFFFFF)
#define BAD_IP_ADDRESS (DWORD)(0xFFFFFFFF)
class COMDLL CIPAddress : public CObjectPlus
/*++
Class Description:
IP Address classes. Winsock is required to be initialized for this
to work.
Public Interface:
CIPAddress : Various constructors
operator = : Assignment operator
operator == : Comparison operators
operator const DWORD : Cast operator
operator LPCTSTR : Cast operator
operator CString : Cast operator
CompareItem : Comparison function
QueryIPAddress : Get the ip address value
QueryNetworkOrderIPAddress : Get the ip address value (network order)
QueryHostOrderIPAddress : Get the ip address value (host order)
StringToLong : Convert ip address string to 32 bit number
LongToString : Convert 32 bit value to ip address string
--*/
{
//
// Helper Functions
//
public:
static DWORD StringToLong(
IN LPCTSTR lpstr,
IN int nLength
);
static DWORD StringToLong(
IN const CString & str
);
static DWORD StringToLong(
IN const CComBSTR & bstr
);
static LPCTSTR LongToString(
IN const DWORD dwIPAddress,
OUT CString & str
);
static LPCTSTR LongToString(
IN const DWORD dwIPAddress,
OUT CComBSTR & bstr
);
static LPTSTR LongToString(
IN const DWORD dwIPAddress,
OUT LPTSTR lpStr,
IN int cbSize
);
static LPBYTE DWORDtoLPBYTE(
IN DWORD dw,
OUT LPBYTE lpBytes
);
public:
//
// Constructors
//
CIPAddress();
//
// Construct from DWORD
//
CIPAddress(
IN DWORD dwIPValue,
IN BOOL fNetworkByteOrder = FALSE
);
//
// Construct from byte stream
//
CIPAddress(
IN LPBYTE lpBytes,
IN BOOL fNetworkByteOrder = FALSE
);
//
// Construct from octets
//
CIPAddress(
IN BYTE b1,
IN BYTE b2,
IN BYTE b3,
IN BYTE b4
);
//
// Copy constructor
//
CIPAddress(
IN const CIPAddress & ia
);
//
// Construct from string
//
CIPAddress(
IN LPCTSTR lpstr,
IN int nLength
);
//
// Construct from CString
//
CIPAddress(
IN const CString & str
);
//
// Access Functions
//
public:
int CompareItem(
IN const CIPAddress & ia
) const;
//
// Query IP address value as a dword
//
DWORD QueryIPAddress(
IN BOOL fNetworkByteOrder = FALSE
) const;
//
// Get the ip address value as a byte stream
//
LPBYTE QueryIPAddress(
OUT LPBYTE lpBytes,
IN BOOL fNetworkByteOrder = FALSE
) const;
//
// Get the ip address as a CString
//
LPCTSTR QueryIPAddress(
OUT CString & strAddress
) const;
//
// Get the ip address as a CComBSTR
//
LPCTSTR QueryIPAddress(
OUT CComBSTR & bstrAddress
) const;
//
// Get ip address in network byte order DWORD
//
DWORD QueryNetworkOrderIPAddress() const;
//
// Get the ip address in host byte order DWORD
//
DWORD QueryHostOrderIPAddress() const;
//
// Assignment operators
//
const CIPAddress & operator =(
IN const DWORD dwIPAddress
);
const CIPAddress & operator =(
IN LPCTSTR lpstr
);
const CIPAddress & operator =(
IN const CString & str
);
const CIPAddress & operator =(
IN const CIPAddress & ia
);
//
// Comparison operators
//
BOOL operator ==(
IN const CIPAddress & ia
) const;
BOOL operator ==(
IN DWORD dwIPAddress
) const;
BOOL operator !=(
IN const CIPAddress & ia
) const;
BOOL operator !=(
IN DWORD dwIPAddress
) const;
//
// Conversion operators
//
operator const DWORD() const { return m_dwIPAddress; }
operator LPCTSTR() const;
operator CString() const;
//
// Value Verification Helpers
//
void SetZeroValue();
BOOL IsZeroValue() const;
BOOL IsBadValue() const;
private:
DWORD m_dwIPAddress;
};
//
// Inline Expansion
//
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
inline /* static */ DWORD CIPAddress::StringToLong(
IN const CString & str
)
{
return CIPAddress::StringToLong(str, str.GetLength());
}
inline /* static */ DWORD CIPAddress::StringToLong(
IN const CComBSTR & bstr
)
{
return CIPAddress::StringToLong(bstr, bstr.Length());
}
inline LPCTSTR CIPAddress::QueryIPAddress(
OUT CString & strAddress
) const
{
return LongToString(m_dwIPAddress, strAddress);
}
inline LPCTSTR CIPAddress::QueryIPAddress(
OUT CComBSTR & bstrAddress
) const
{
return LongToString(m_dwIPAddress, bstrAddress);
}
inline DWORD CIPAddress::QueryNetworkOrderIPAddress() const
{
return QueryIPAddress(TRUE);
}
inline DWORD CIPAddress::QueryHostOrderIPAddress() const
{
return QueryIPAddress(FALSE);
}
inline BOOL CIPAddress::operator ==(
IN const CIPAddress & ia
) const
{
return CompareItem(ia) == 0;
}
inline BOOL CIPAddress::operator ==(
IN DWORD dwIPAddress
) const
{
return m_dwIPAddress == dwIPAddress;
}
inline BOOL CIPAddress::operator !=(
IN const CIPAddress & ia
) const
{
return CompareItem(ia) != 0;
}
inline BOOL CIPAddress::operator !=(
IN DWORD dwIPAddress
) const
{
return m_dwIPAddress != dwIPAddress;
}
inline void CIPAddress::SetZeroValue()
{
m_dwIPAddress = NULL_IP_ADDRESS;
}
inline BOOL CIPAddress::IsZeroValue() const
{
return m_dwIPAddress == NULL_IP_ADDRESS;
}
inline BOOL CIPAddress::IsBadValue() const
{
return m_dwIPAddress == BAD_IP_ADDRESS;
}
//
// Helper function to build a list of known IP addresses,
// and add them to a combo box
//
DWORD
COMDLL
PopulateComboWithKnownIpAddresses(
IN LPCTSTR lpszServer,
IN CComboBox & combo,
IN CIPAddress & iaIpAddress,
OUT CObListPlus & oblIpAddresses,
OUT int & nIpAddressSel
);
//
// Helper function to get an ip address from a combo/edit/list
// control
//
BOOL
COMDLL
FetchIpAddressFromCombo(
IN CComboBox & combo,
IN CObListPlus & oblIpAddresses,
OUT CIPAddress & ia
);
#endif // _IPA_H
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
5b72a5dcd4afae544d4564dfdd3ba79d899219ca | d89ad3f7be72e8645db979aff6d5908764f84b53 | /অ্যালগরিদম/Bfs And Dfs/shotcut---bfs(TL)/Longest path in a tree----bfs - Copy.cpp | 2fb2cfcf11069f88a13741ff640de21d58308b21 | [] | no_license | alhelal1/Contest_File | c8dbcaa18bddeeca0791564b7d3b00ccf4eedfde | 31bd164e3128de500b5c4c5beb188c86379ab40b | refs/heads/master | 2021-04-03T08:38:15.085441 | 2018-03-14T06:10:08 | 2018-03-14T06:10:08 | 125,163,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,875 | cpp | using namespace std;
#include<bits/stdc++.h>
typedef long long ll;
typedef pair<ll,ll> pii;
typedef vector< pii > vpii;
typedef vector<long long> vi;
typedef map<string,ll> msi;
typedef map<ll,ll> mii;
///Print
#define out(a) printf("%lld\n",a)
#define out2(a,b) printf("%lld %lld\n",a,b)
#define out3(a,b,c) printf("%lld %lld %lld\n",a,b,c)
#define nl printf("\n")
///Case
#define case(no) printf("Case %lld: ",++no)
#define casenl(no) printf("Case %lld:\n",++no)
#define caseh(no) printf("Case #%lld: ",++no)
#define casehnl(no) printf("Case #%lld:\n",++no)
///Scanf
#define in(n) scanf("%lld", &n)
#define in2(a,b) scanf("%lld %lld", &a, &b)
#define in3(a,b,c) scanf("%lld %lld %lld", &a, &b, &c)
///LOOP
#define rep(x,n) for(__typeof(n) x=0;x<(n);x++)
#define reps(i,x) for(int i=0;i<(x.size());i++)
#define repp(x,n) for(__typeof(n) x=1;x<=(n);x++)
#define foreach(x,n) for(__typeof(n.begin()) x=n.begin();x!=n.end();x++)
///Shortcut
#define mem(ar,value) memset(ar,value,sizeof(ar))
#define all(x) x.begin(),x.end()
#define Unique(store) store.resize(unique(store.begin(),store.end())-store.begin())
#define len(s) s.size()
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
///Min AND Max
#define min4(a,b,c,d) min(min(a,b),min(c,d))
#define max4(a,b,c,d) max(max(a,b),max(c,d))
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define maxall(v) *max_element(all(v))
#define minall(v) *min_element(all(v))
#define eps (1e-9)
#define PI acos(-1.0)
#define mod 1e9+7
#define isEq(a,b) (fabs((a)-(b))<eps)
#define Dist(x1,y1,x2,y2) (sqrt(sqr((x1)-(x2))+sqr((y1)-(y2))))
///File
#define READ freopen("input.txt","r",stdin)
#define WRITE freopen("output.txt","w",stdout)
/**Define Bitwise operation**/
#define check(n, pos) (n & (1<<(pos)))
#define biton(n, pos) (n | (1<<(pos)))
#define bitoff(n, pos) (n & ~(1<<(pos)))
#define ledzero(n) (__builtin_clz(n))
#define trailzero(n) (__builtin_ctz(n))
#define onbit(n) (__builtin_popcount(n))
///DEBUG
#define d1(x) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<endl;
#define d2(x,y) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<endl;
#define d3(x,y,z) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<" | "#z" = "<<z<<endl;
///Gcd and Lcm
template<class T>T gcd(T a,T b){return b == 0 ? a : gcd(b, a % b);}
template<typename T>T lcm(T a, T b) {return a / gcd(a,b) * b;}
///Bigmod && Pow
template<class T>T my_pow(T n,T p){if(p==0)return 1;T x=my_pow(n,p/2);x=(x*x);if(p&1)x=(x*n);return x;} ///n to the power p
template<class T>T big_mod(T n,T p,T m){if(p==0)return (T)1;T x=big_mod(n,p/2,m);x=(x*x)%m;if(p&1)x=(x*n)%m;return x;}
template<class T> inline T Mod(T n,T m) {return (n%m+m)%m;} ///For Positive Negative No.
///string to int
template <class T> T extract(string s, T ret) {stringstream ss(s); ss >> ret; return ret;}/// extract words or numbers from a line
template<class T> string itos(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}///NOTES:toString(
ll stoi(string s){ll r=0;istringstream sin(s);sin>>r;return r;}///NOTES:toInt(
double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}
//int col[8] = {0, 1, 1, 1, 0, -1, -1, -1};int row[8] = {1, 1, 0, -1, -1, -1, 0, 1};///8 Direction
//int col[4] = {1, 0, -1, 0};int row[4] = {0, 1, 0, -1};///4 Directionint
//int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};///Knight Direction
//int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2};///Hexagonal Direction
ll ar[2000005],ar1[2000005];
ll a=0,b=0,c=0,r=0,rr=0,res=0,n,m;
string s,s1;
ll vis[1000006];
vector<ll>v[100005];
ll depth=0;
ll dfs(ll i)
{
queue<ll>q;
q.push(i);
q.push(0);
vis[i]=1;
r=0;
depth=0;
while(len(q))
{
ll aa=q.front();q.pop();
ll bb=q.front();q.pop();
//r=max(bb,r);
if(r<bb)
{
depth=aa;
r=bb;
}
rep(j,len(v[aa]))
{
ll cc=v[aa][j];
if(vis[cc]==0)
{
q.push(cc);
q.push(bb+1);
vis[cc]=1;
}
}
}
}
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(false);
cin>>n;
rep(i,n-1)
{
cin>>a>>b;
v[a].pb(b);
v[b].pb(a);
}
ll dd=0;
repp(i,n)
{
if(len(v[i])>0 and vis[i]==0)
{
dfs(i);
if(rr<r)
{
rr=r;
dd=depth;
r=0;
}
}
}
mem(vis,false);
r=0;
dfs(dd);
rr=max(r,rr);
out(rr);
mem(vis,false);
return 0;
}
| [
"a.helal@bjitgroup.com"
] | a.helal@bjitgroup.com |
1d9772bc154893331ebbdea8d094fb20cd786fea | 6c10d344a25f3194506a414fc7830888b9d78b53 | /source/apps/mast/gui/dialogs/FeatureVolumesDialog.h | f610f61debef29d1a943c8d31aed47c393fd5671 | [] | no_license | vyeghiazaryan/msc | 64fb493660b06031caae126c6572a4dc33177952 | dced6bae89461578285cc24b99feab034eafc48e | refs/heads/master | 2020-12-24T13:36:11.747054 | 2013-11-05T12:28:06 | 2013-11-05T12:28:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,558 | h | /***
* millipede: FeatureVolumesDialog.h
* Copyright Stuart Golodetz, 2010. All rights reserved.
***/
#ifndef H_MILLIPEDE_FEATUREVOLUMESDIALOG
#define H_MILLIPEDE_FEATUREVOLUMESDIALOG
#include <sstream>
#include <wx/button.h>
#include <wx/dialog.h>
#include <wx/listctrl.h>
#include <wx/sizer.h>
#include <common/math/NumericUtil.h>
#include <mast/models/PartitionModel.h>
#include <mast/util/StringConversion.h>
namespace mp {
class FeatureVolumesDialog : public wxDialog
{
//#################### PRIVATE VARIABLES ####################
private:
int m_index;
wxListCtrl *m_list;
//#################### CONSTRUCTORS ####################
public:
template <typename LeafLayer, typename BranchLayer, typename Feature>
FeatureVolumesDialog(wxWindow *parent, const boost::shared_ptr<const PartitionModel<LeafLayer,BranchLayer,Feature> >& model)
: wxDialog(parent, wxID_ANY, wxT("Feature Volumes"), wxDefaultPosition, wxDefaultSize), m_index(0)
{
wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
SetSizer(sizer);
// Add a list control to show the volumes.
m_list = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxSize(300,200), wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_HRULES|wxLC_VRULES);
m_list->InsertColumn(0, wxT("Feature Name"));
m_list->InsertColumn(1, wxT("Volume (cubic cm, 3 d.p.)"));
for(Feature feature=enum_begin<Feature>(), end=enum_end<Feature>(); feature!=end; ++feature)
{
double volumeMM3 = model->active_multi_feature_selection()->voxel_count(feature) * model->dicom_volume()->voxel_size_mm3();
add_feature_volume(feature, volumeMM3);
}
m_list->SetColumnWidth(0, wxLIST_AUTOSIZE_USEHEADER);
m_list->SetColumnWidth(1, wxLIST_AUTOSIZE_USEHEADER);
sizer->Add(m_list, 0, wxALIGN_CENTRE_HORIZONTAL);
// Add an OK button.
wxButton *okButton = new wxButton(this, wxID_OK, wxT("OK"));
sizer->Add(okButton, 0, wxALIGN_CENTRE_HORIZONTAL);
okButton->SetFocus();
sizer->Fit(this);
CentreOnParent();
}
//#################### PRIVATE METHODS ####################
private:
template <typename Feature>
void add_feature_volume(const Feature& feature, double volumeMM3)
{
std::ostringstream oss;
oss.setf(std::ios::fixed, std::ios::floatfield);
oss.precision(3);
oss << (volumeMM3 / 1000.0); // the / 1000.0 converts cubic mm to cubic cm
m_list->InsertItem(m_index, string_to_wxString(feature_to_name(feature)));
m_list->SetItem(m_index, 1, string_to_wxString(oss.str()));
++m_index;
}
};
}
#endif
| [
"varduhi.yeghiazaryan@cs.ox.ac.uk"
] | varduhi.yeghiazaryan@cs.ox.ac.uk |
7f812a82447d6239c96c880e53c3b5b85d14b833 | d4c431faeff66402c8a8ef04ede205ab232b5c8f | /Cthulhu/src/RawDynamic.cpp | d30dafd61b868f6f60668bd41b6fcb07d44d13f5 | [
"MIT"
] | permissive | yahiaali/labgraph | 6a5bd10626b62adf1055250ac70de63d65a3d575 | 306d7e55a06219155303f287f91e9b6ea5dca50a | refs/heads/main | 2023-07-15T15:35:36.011835 | 2021-08-27T13:22:23 | 2021-08-27T13:22:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 616 | cpp | // Copyright 2004-present Facebook. All Rights Reserved.
#include <cthulhu/RawDynamic.h>
#include <memory>
#include <cthulhu/Framework.h>
namespace cthulhu {
template <>
CpuBuffer RawDynamic<>::getBuffer() const {
return Framework::instance().memoryPool()->getBufferFromPool("", size());
}
template <>
RawDynamic<>::RawDynamic(CpuBuffer& buf, size_t count)
: elementCount(count), elementSize(sizeof(uint8_t)) {
if (Framework::instance().memoryPool()->isBufferFromPool(buf)) {
raw = buf;
} else {
raw = getBuffer();
std::memcpy(raw.get(), buf.get(), size());
}
}
} // namespace cthulhu
| [
"jinyu.fjy@gmail.com"
] | jinyu.fjy@gmail.com |
d5b6ab248e0aeda7aa3dda4c2d2c877402381f11 | 6bec8cb6f04389c9d2c51b160dc454629f1db66d | /src/decision/subroutines/qualification/include/LineUpWithGate.h | 986293cb7765ae31976072389118c7087e1ad6a2 | [] | no_license | SoleSun/SubBots-Legacy | 9592e62836a4a75201abc2fffec05c20a4a02112 | f416e2f244ac4be4d6c95b5ea749fc38ad9ce61e | refs/heads/master | 2020-04-02T12:40:24.483562 | 2018-10-24T05:52:30 | 2018-10-24T05:52:30 | 154,445,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | h | /*
* Created By: Reid Oliveira
* Created On: March 24, 2018
* Description: Subroutine that tries to position the sub in front and
* orthogonal with the gate, ready to go through.
*/
#ifndef DECISION_LINEUPWITHGATE_H
#define DECISION_LINEUPWITHGATE_H
#include "Subroutine.h"
#include <gate_detect/gateDetectMsg.h>
#include <std_msgs/String.h>
/*
* Subroutine: LineUpWithGate
*
* Function: attempts to get into an orthogonal position with the gate
*
*/
class LineUpWithGate : public Subroutine {
public:
LineUpWithGate(int argc, char** argv, std::string node_name)
: Subroutine(argc, argv, node_name) {}
void setupSubscriptions(ros::NodeHandle nh) override;
private:
void decisionCallback(const gate_detect::gateDetectMsg::ConstPtr& msg);
void balance(const geometry_msgs::Twist::ConstPtr& msg);
};
#endif // DECISION_LINEUPWITHGATE_H
| [
"joel.ahn@alumni.ubc.ca"
] | joel.ahn@alumni.ubc.ca |
ff417bb380e6e51de4c269a5f2966d496a6b1f44 | 536226f6b5c7cf30122e1b17e1e495d42ff0e3e1 | /Calculator/Calculator.cpp | 72db1e2f56457159641ea533cb2cbb343a1a6b02 | [] | no_license | MoawazAyub/Postfix-Calculator | 64adfe9f382e27e588e5b22c803d538d548f24d2 | d8975862debea1e624213ddd13478948a1d82390 | refs/heads/master | 2020-03-21T08:07:06.345852 | 2018-06-22T15:54:51 | 2018-06-22T15:54:51 | 138,321,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,051 | cpp | # include <iostream>
# include <string>
# include "Stack.h"
using namespace std;
template <class T>
class Calculator
{
Stack<T> s;
public:
void push(const T & obj)
{
s.push(obj);
}
void pop()
{
s.pop();
}
void print()
{
s.print();
}
const T & top()
{
return s.top();
}
int size()
{
return s.size();
}
string input(string st)
{
Operator a, b,c;
b.setdiscription("(");
string temp;
int count = 0;
for (int j = 0 ; j < st.size() ; j++)
{
if(st[j] >= 48 && st[j] <= 57)
{
temp = temp + st[j];
count++;
}
else if(st[j] == ' ')
{
if (count != 0)
{
count = 0;
temp = temp + " ";
}
}
else if (st[j] == '(')
{
a.setdiscription("(");
s.push(a);
}
else if (st[j] == ')')
{
Operator a1;
a1 = s.top();
while((s.empty()) == false && a1 != b)
{
c = s.top();
temp = temp + " ";
temp = temp + c.getdiscription();
s.pop();
}
s.pop();
}
else if(st[j] == '+' || st[j] == '-' || st[j] == '*' || st[j] == '/' )
{
if (st[j] == '+' && st[j + 1] == '+')
{
a.setdiscription("++");
j++;
s.push(a);
}
else if (st[j] == '-' && st[j + 1] == '-')
{
a.setdiscription("--");
j++;
s.push(a);
}
else
{
Operator d,e,f;
a.setdiscription(st[j]);
s.push(a);
d = s.top();
e = s.top();
s.pop();
if(!(s.empty()))
{
f = s.top();
}
while (!(s.empty()) && d.getpresedence() <= f.getpresedence() && f != b)
{
temp = temp + f.getdiscription();
temp = temp + " ";
s.pop();
if(!(s.empty()))
{
f = s.top();
}
}
s.push(d);
}
}//------------
}
if ( !(s.empty()) )
{
Operator g = s.top();
while (!(s.empty()))
{
g = s.top();
temp = temp + " ";
if (g.getdiscription() != "(")
{
temp = temp + g.getdiscription();
}
s.pop();
}
}
// cout << temp;
string temp2;
int count2 = 0;
for(int z = 0 ; z < temp.size();z++ )
{
if(temp[z] == ' ' || temp[z] == '(')
{
count2++;
}
else
{
count2 = 0;
}
if(temp[z] !='(' && count2 < 2)
{
temp2 = temp2 + temp[z];
}
}
return temp2;
}
int evaluate(string & st)
{
int x=0,y=0;
Stack<string> a1;
string temp,temp2,temp3;
int i = 0;
int count = 0;
for(int j = 0 ; j < st.size() ; j++)
{
if(st[j] >= 48 && st[j] <= 57)
{
temp = temp + st[j];
count++;
}
else if(st[j] == ' ')
{
if (count != 0)
{
count = 0;
a1.push(temp);
temp = "";
}
}
else if(st[j] == '+' || st[j] == '-' || st[j] == '*' || st[j] == '/' )
{
if (st[j] == '+' && st[j + 1] == '+')
{
temp2 = a1.top();
x = stoi(temp2);
x = x + 1;
a1.pop();
a1.push(to_string(x));
j++;
}
else if (st[j] == '-' && st[j + 1] == '-')
{
temp2 = a1.top();
x = stoi(temp2);
x = x - 1;
a1.pop();
a1.push(to_string(x));
j++;
}
else if(st[j] == '+')
{
int z = 0;
temp2 = a1.top();
y = stoi(temp2);
a1.pop();
temp2 = a1.top();
x = stoi(temp2);
a1.pop();
z = x + y;
a1.push(to_string(z));
}
else if(st[j] == '-')
{
int z = 0;
temp2 = a1.top();
y = stoi(temp2);
a1.pop();
temp2 = a1.top();
x = stoi(temp2);
a1.pop();
z = x - y;
a1.push(to_string(z));
}
else if(st[j] == '*')
{
int z = 0;
temp2 = a1.top();
y = stoi(temp2);
a1.pop();
temp2 = a1.top();
x = stoi(temp2);
a1.pop();
z = x * y;
a1.push(to_string(z));
}
else if(st[j] == '/')
{
int z = 0;
temp2 = a1.top();
y = stoi(temp2);
a1.pop();
temp2 = a1.top();
x = stoi(temp2);
a1.pop();
z = x / y;
a1.push(to_string(z));
}
}//------------
}
int v = stoi(a1.top());
return v;
}
};
void main()
{
Calculator<Operator> c;
string s;
string t;
while(s != "quit")
{
cout << "enter command Remember to add spaces between digits (result is in integer)" <<endl;
getline(cin, s);
if (s == "quit")
{
break;
}
t = c.input(s);
cout <<t;
cout << endl;
cout << "answer = ";
cout << c.evaluate(t);
cout << endl;
}
//Calculator<Operator> c;
//string s = "2 + 3";
//string t;
//t = c.input(s);
////t = "18 2 * 6 /";
//cout<<c.input(s);
//
//cout << endl;
//cout<<c.evaluate(t);
//cout <<endl;
///*Operator o,t;
//o.setdiscription("/");
/*c.push(o);
o.setdiscription("+");
c.push(o);
o.setdiscription("*");
c.push(o);
c.pop();
o.setdiscription("-");
c.push(o);
c.print();
t = c.top();
int d = t.getpresedence() ;
cout << d;
*/
} | [
"moawazayubmmm@gmail.com"
] | moawazayubmmm@gmail.com |
086af70aef1493face3e3665f900ef28f0a1cace | d1aa3b1380d88a1f19620367b71982d014445d7c | /004-用户裁切平面/UserClippingIOS-Proj/UserClippingIOS/UserClipping/source/TorusModel.cpp | 07d991bf278172da0fc0d7bbff7b517ad8e1369c | [
"MIT"
] | permissive | jjzhang166/LearnThreeJSRenderingExamples | 201d7bb8aa5a290524daa45600a785f4632e62d2 | 97ecf0235ff893c576236e39bff873ed082e388e | refs/heads/master | 2022-04-27T18:19:07.280199 | 2020-04-24T05:55:31 | 2020-04-24T05:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,809 | cpp | //--------------------------------------------------------------------------------
// TorusModel.cpp
// Render a plane
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Include files
//--------------------------------------------------------------------------------
#include "TorusModel.h"
#include "matrix4.h"
#include "Geometry.h"
#include "TorusKnotGeometry.h"
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
extern float UserClipDistance;
float TorusModel::timer=0.f;
TorusModel::TorusModel() {
vao_ = 0;
vbo_ = 0;
ibo_ = 0;
// Load shader
lavaShaderState_.reset(new LavaShaderState());
TorusKnotGeometry tkg = TorusKnotGeometry();
TorusKnotGeometry::TKGVertexData tkgVdata = makeTKGVertexData(tkg);
// Create VBO
num_vertices_ = (int)tkgVdata.vData.size();
num_indices_ = (int)tkgVdata.iData.size();
vector<VertexPNX> vertices = tkgVdata.vData;
vector<unsigned short> indices = tkgVdata.iData;
geometry_.reset(new Geometry(&vertices[0],&indices[0],num_vertices_,num_indices_));
if(!vao_)
glGenVertexArrays(1, &vao_);
glBindVertexArray(vao_);
// Bind the VBO
glBindBuffer(GL_ARRAY_BUFFER, geometry_->vbo);
int32_t iStride = sizeof(VertexPNX);
// Pass the vertex data
glVertexAttribPointer(TEXTURE_ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, iStride,
BUFFER_OFFSET(0));
glEnableVertexAttribArray(TEXTURE_ATTRIB_VERTEX);
glVertexAttribPointer(TEXTURE_ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, iStride,
BUFFER_OFFSET(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(TEXTURE_ATTRIB_NORMAL);
glVertexAttribPointer(TEXTURE_ATTRIB_UV, 2, GL_FLOAT, GL_FALSE, iStride,
BUFFER_OFFSET(2* 3 * sizeof(GLfloat)));
glEnableVertexAttribArray(TEXTURE_ATTRIB_UV);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry_->ibo);
glBindVertexArray(0);
std::vector<std::string> textures = {std::string(GetBundleFileName("cloud.png"))};
texObj_ = Texture::Create(GL_TEXTURE_2D, textures);
assert(texObj_);
// texObj_->Activate(GL_TEXTURE2);
// glUniform1i(lavaShaderState_->tex1_, 2);
std::vector<std::string> textures1 = {std::string(GetBundleFileName("lavatile.jpg"))};
texObj1_ = Texture::Create(GL_TEXTURE_2D, textures1);
assert(texObj1_);
}
TorusModel::~TorusModel(){
Unload();
}
void TorusModel::Init() {
mat_model_ = Matrix4::makeTranslation(Cvec3(0.f, 0.f, 0.f));
//mat_model_ = mat_model_ * Matrix4::makeXRotation(45);
mat_view_ = Matrix4::makeTranslation(Cvec3(0,0,4.0f));
mat_view_ = inv(mat_view_);
}
void TorusModel::Unload() {
if (vbo_) {
glDeleteBuffers(1, &vbo_);
vbo_ = 0;
}
if (ibo_) {
glDeleteBuffers(1, &ibo_);
ibo_ = 0;
}
}
void TorusModel::Update(double time) {
mat_projection_ = perspectiveCamera_->projMat;
}
void TorusModel::setPerspectiveCamera(std::shared_ptr<PerspectiveCamera> camera){
this->perspectiveCamera_ = camera;
Update(0);
}
void TorusModel::Render(){
glDisable(GL_CULL_FACE);
glUseProgram(lavaShaderState_->program);
glUniform1f(lavaShaderState_->utime_, 1.0f);
glUniform3f(lavaShaderState_->fogColor_,0,0,0);
glUniform1f(lavaShaderState_->fogDensity_, 0.45);
glUniform2f(lavaShaderState_->uvScale_, 6.0, 2.0);
glUniform4f(lavaShaderState_->userClipPlane_, 0, -1, 0, UserClipDistance);
texObj_->Activate(GL_TEXTURE0);
glUniform1i(lavaShaderState_->tex1_, 0);
texObj1_->Activate(GL_TEXTURE1);
glUniform1i(lavaShaderState_->tex2_, 1);
timer+=0.025f;
if(timer>100.f)
timer=1.0f;
glUniform1f(lavaShaderState_->utime_, timer);
mat_model_ = mat_model_ * Matrix4::makeYRotation(0.0625);
mat_model_ = mat_model_ * Matrix4::makeXRotation(0.25);
// Feed Projection and Model View matrices to the shaders
Matrix4 mat_vp = mat_projection_ * mat_view_ * mat_model_;
Matrix4 mat_mv = mat_view_ * mat_model_;
GLfloat glmatrix[16];
mat_mv.writeToColumnMajorMatrix(glmatrix);
glUniformMatrix4fv(lavaShaderState_->matrix_mv_, 1, GL_FALSE,
glmatrix);
GLfloat glmatrix2[16];
mat_projection_.writeToColumnMajorMatrix(glmatrix2);
glUniformMatrix4fv(lavaShaderState_->matrix_p_, 1, GL_FALSE,
glmatrix2);
glBindVertexArray(vao_);
glDrawElements(GL_TRIANGLES, num_indices_,GL_UNSIGNED_SHORT,NULL);
glBindVertexArray(0);
}
| [
"nintymiles@icloud.com"
] | nintymiles@icloud.com |
11f7ae73d1c7412574f796881f584a92176d3392 | 581793bdd7132d99b9b74a477a3f39c41a7f619a | /src/cpp/43 this Pointer.cpp | 2a72e92713d85d054593f6db63834102e134d0eb | [] | no_license | Abhrajyoti00/Data-Structure-Algorithm-Abdul-Bari | 4db9174b920d5d717826420dd3fc2b199d6a1920 | 60f118f9954aca6ff9ef7c91210b8a7883369fa5 | refs/heads/master | 2023-02-14T00:53:53.992458 | 2020-12-19T10:54:41 | 2020-12-19T10:54:41 | 322,921,600 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | /*
Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.
*/
#include<iostream>
using namespace std;
class A{
int a;
public:
// A & setData(int a){
void setData(int a){
this->a = a;
// return *this;
}
void getData(){
cout<<"The value of a is "<<a<<endl;
}
};
int main(){
// this is a keyword which is a pointer which points to the object which invokes the member function
A a;
a.setData(4);
a.getData();
return 0;
}
| [
"noreply@github.com"
] | Abhrajyoti00.noreply@github.com |
add06df63d4a028d94ac0231ce3f0d306c8c414f | 70eb368ea25ad8767e6713ea88936642154f43ae | /workUndone/Suite15/OpenFlight_API/samples/plugins/skyscraper/buildskyscraper.cpp | 6933115b6ae6c6229d83ebe18d96b5b07706f88d | [] | no_license | CatalinaPrisacaru/Di-Java | 816cb3428d5026fb63934e14d09c422aa1537b08 | 1c35b28e0b8c8f3c25afbc7b2c0a7fe8cac96c6b | refs/heads/develop | 2021-01-18T02:23:47.759177 | 2016-04-11T19:55:35 | 2016-04-11T19:55:35 | 54,333,823 | 0 | 0 | null | 2016-03-20T18:36:51 | 2016-03-20T18:36:51 | null | UTF-8 | C++ | false | false | 3,793 | cpp | #include "buildskyscraper.h"
#include "helpers.h"
static void buildSide(const Box &i_dimensions, mgrec *i_parent,
unsigned int i_xLightCount, unsigned int i_yLightCount, const LightBuilder &i_lightBuilder)
{
i_yLightCount++;
for(unsigned int y = 1 ; y < i_yLightCount ; y++)
{
double at = (double)y / (double)i_yLightCount;
mgcoord3d end1 = interpolate3d(i_dimensions.getCloseBottomLeft(), i_dimensions.getCloseTopLeft(), at);
mgcoord3d end2 = interpolate3d(i_dimensions.getFarBottomRight(), i_dimensions.getFarTopRight(), at);
i_lightBuilder.buildLightStringExcludingEnds(end1, end2, i_xLightCount, NULL);
}
buildTriangle(i_parent, i_dimensions.getCloseBottomLeft(), i_dimensions.getFarBottomRight(), i_dimensions.getFarTopRight());
buildTriangle(i_parent, i_dimensions.getCloseBottomLeft(), i_dimensions.getFarTopRight(), i_dimensions.getCloseTopLeft());
}
void buildSkyscraper(const Box &i_dimensions, double i_antennaHeight, mgrec *i_parent,
unsigned int i_xLightCount, unsigned int i_yLightCount, unsigned int i_zLightCount, unsigned int i_antennaLightCount,
const LightBuilder &i_sides, const LightBuilder &i_verticals, const LightBuilder &i_top, const LightBuilder &i_corners, const LightBuilder &i_antenna)
{
Box dimensions = i_dimensions;
dimensions.assureCorrectness();
mgcoord3d downNormal = mgCoord3dNegativeZAxis();
// front
buildSide(Box(dimensions.getCloseBottomLeft(), dimensions.getCloseTopRight()), i_parent, i_xLightCount, i_zLightCount, i_sides);
i_top.buildLightStringExcludingEnds(dimensions.getCloseTopLeft(), dimensions.getCloseTopRight(), i_xLightCount, &downNormal);
// right
buildSide(Box(dimensions.getCloseBottomRight(), dimensions.getFarTopRight()), i_parent, i_yLightCount, i_zLightCount, i_sides);
i_top.buildLightStringExcludingEnds(dimensions.getCloseTopRight(), dimensions.getFarTopRight(), i_yLightCount, &downNormal);
// back
buildSide(Box(dimensions.getFarBottomRight(), dimensions.getFarTopLeft()), i_parent, i_xLightCount, i_zLightCount, i_sides);
i_top.buildLightStringExcludingEnds(dimensions.getFarTopRight(), dimensions.getFarTopLeft(), i_xLightCount, &downNormal);
// left
buildSide(Box(dimensions.getFarBottomLeft(), dimensions.getCloseTopLeft()), i_parent, i_yLightCount, i_zLightCount, i_sides);
i_top.buildLightStringExcludingEnds(dimensions.getFarTopLeft(), dimensions.getCloseTopLeft(), i_yLightCount, &downNormal);
// close left
i_verticals.buildLightStringExcludingEnds(dimensions.getCloseBottomLeft(), dimensions.getCloseTopLeft(), i_zLightCount, NULL);
i_corners.buildLight(dimensions.getCloseTopLeft(), NULL);
// close right
i_verticals.buildLightStringExcludingEnds(dimensions.getCloseBottomRight(), dimensions.getCloseTopRight(), i_zLightCount, NULL);
i_corners.buildLight(dimensions.getCloseTopRight(), NULL);
// far right
i_verticals.buildLightStringExcludingEnds(dimensions.getFarBottomRight(), dimensions.getFarTopRight(), i_zLightCount, NULL);
i_corners.buildLight(dimensions.getFarTopRight(), NULL);
// far left
i_verticals.buildLightStringExcludingEnds(dimensions.getFarBottomLeft(), dimensions.getFarTopLeft(), i_zLightCount, NULL);
i_corners.buildLight(dimensions.getFarTopLeft(), NULL);
// top
buildTriangle(i_parent, dimensions.getCloseTopLeft(), dimensions.getCloseTopRight(), dimensions.getFarTopRight());
buildTriangle(i_parent, dimensions.getCloseTopLeft(), dimensions.getFarTopRight(), dimensions.getFarTopLeft());
// antenna
mgcoord3d antennaBottom = dimensions.getTopCenter();
mgcoord3d antennaTop = antennaBottom;
antennaTop.z += i_antennaHeight;
i_antenna.buildLightStringIncludingEnds(antennaBottom, antennaTop, i_antennaLightCount, &downNormal);
}
| [
"albisteanu.sebastian@yahoo.com"
] | albisteanu.sebastian@yahoo.com |
b70b261a8eb27de2b911ef753dace18b5a4e5609 | 829b1fc94573cebe934f16da4d8cc1ca5218be43 | /Floyd's triangle.cpp | 068a4db5773f1a432ed4f3df039628af83749f53 | [] | no_license | sudipto21-java/CPP-Codes | 0d435f627ef65d0355e81ed92dbb9a73ad062575 | 20ea98a6e44ea4aced90d188af7feb6d253edcf2 | refs/heads/main | 2023-06-05T15:03:59.216041 | 2021-06-25T13:52:51 | 2021-06-25T13:52:51 | 380,243,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | #include<iostream>
using namespace std;
int main()
{
int n,i,j,count=0;
cout<<"enter value of n:";
cin>>n;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<++count<<"\t";
}
cout<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | sudipto21-java.noreply@github.com |
09f4b77ea1d5460a30fd54ff5042f2a93641fdfa | 001429c0a4492101b8b3c89e4e8f94ab9a45cc9f | /cameraraw.cpp | bf44cf0796c956baf5d97545f7136380160d5343 | [] | no_license | andraynada2002/Photoshop-CC-scripts | 2b003e054cb1a0f7226b093debdf380ee7bcb04a | 28fcd5e439ec5a1c2c553e66a5706a9682db5c32 | refs/heads/master | 2020-04-29T07:46:44.163299 | 2019-04-29T08:42:31 | 2019-04-29T08:42:31 | 175,964,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | cpp | name photoshopcc():
class photoshopcc();
unsigned application();
signed application();
unsigned photoshop.exe();
signed photoshop.exe
public class photoshopcc();
class cameraraw();
unsigned int 2003();
unsigned void 2003();
unsigned class cameraraw();
signed class cameraraw();
int 2003();
signed int 2003();
{
//Adobe Photoshop CC optimized filter camera raw
//Adobe Photoshop CC filter camera raw fixed quality
//Adobe Photoshop CC filter camera raw save quality
//Adobe Photoshop CC filter camera raw new techelogy
//Adobe Photoshop CC version 2019
//Adobe Photoshop CC version 20.0x
//Adobe Photoshop CC filter camera raw fixed blur
//Adobe Photoshop CC filter camera raw fixed defects
//Adobe Photoshop CC filter camera raw fixed artifacts
//Adobe Photoshop CC filter camera raw fixed sharpen
//Adobe Photoshop CC filter camera raw fixed lighting
//Adobe Photoshop CC filter camera raw clearest quality and definition
}
| [
"noreply@github.com"
] | andraynada2002.noreply@github.com |
199ba82c8591c9bcf131ed508eeb1abd4e5b47aa | 61d70c727de05e8b07e81a4cd46b22fc03b8861c | /interview_cake/reverse_linked_list.cc | f8cabb69906a06231d41f5fbb4e7815072d29a2f | [] | no_license | cmallalieu/Interview_prep | 917942ed2fc0bf1a870e049deb8d263e00287be8 | 6be7787819104e7e984d4119ca60bda38055f4db | refs/heads/master | 2020-08-24T21:25:23.753086 | 2019-10-30T18:26:07 | 2019-10-30T18:26:07 | 216,908,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 833 | cc | #include <iostream>
#include <vector>
// C++11 lest unit testing framework
#include "lest.hpp"
using namespace std;
class LinkedListNode {
public:
int intValue_;
LinkedListNode* next_;
LinkedListNode(int value) :
intValue_(value),
next_(nullptr)
{
}
};
LinkedListNode* reverse(LinkedListNode* headOfList)
{
// reverse the linked list in place
if (!headOfList)
{
cout << "List is empty" << endl;
}
LinkedListNode* currentNode = headOfList;
LinkedListNode* previousNode = nullptr;
LinkedListNode* nextNode = nullptr;
while(currentNode)
{
nextNode = currentNode->next_;
currentNode->next_ = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
| [
"christophermallalieu@Christophers-MacBook-Pro.local"
] | christophermallalieu@Christophers-MacBook-Pro.local |
b3ca5eba0e98870bca8d49a902dcf4d84fe26e16 | 13e11e1019914694d202b4acc20ea1ff14345159 | /Back-end/src/Workflow/Node.cpp | cc10923dca04e36792e3c60b374f4967193a38ed | [
"Apache-2.0",
"BSL-1.0"
] | permissive | lee-novobi/Frameworks | e5ef6afdf866bb119e41f5a627e695a89c561703 | 016efe98a42e0b6a8ee09feea08aa52343bb90e4 | refs/heads/master | 2021-05-28T19:03:02.806782 | 2014-07-19T09:14:48 | 2014-07-19T09:14:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,227 | cpp |
// #include "PrototypeConfig.h"
// #ifndef LINUX
// #include "StdAfx.h"
// #endif
#include "Node.h"
#include "../Action/Action.h"
#include "../Processor/FunctionInterface.h"
class CPingAction;
class CTelnetAction;
class CLoginWebAction;
class CLoginAppAction;
class CCheckCCUAction;
CNode::CNode(void)
{
m_nCurrentIndex = 0;
m_pAction = NULL;
m_pParentNode = NULL;
}
CNode::CNode (int iActId, MA_RESULT eResult, int iChildArraySize, METHOD_ID eMethodID, CONDITION_ID eConditionID)
{
m_nCurrentIndex = 0;
m_pAction = NULL;
m_pParentNode = NULL;
m_iActId = iActId;
m_eResult = eResult;
m_iChildArraySize = iChildArraySize;
m_eConditionID = eConditionID;
m_eMethodID = eMethodID;
}
CNode::~CNode(void)
{
cout<<"delete CNode"<<endl;
Destroy();
}
MA_RESULT CNode::Execute()
{
MA_RESULT eResult = MA_RESULT_UNKNOWN;
cout<<"CNode::Execute()"<<endl;
cout<<m_iActId<<endl;
if(m_eConditionID != -1)
eResult = CFunctionInterface::GetInstance()->CheckCondition(m_eConditionID);
else if(m_eMethodID != -1)
eResult = CFunctionInterface::GetInstance()->ExecuteFunction(m_eMethodID);
return eResult;
}
void CNode::AddChild(CNode* Child)
{
m_arrChildNode.push_back(Child);
}
void CNode::SetParent(CNode* Parent)
{
m_pParentNode = Parent;
}
CNode* CNode::GetActivatedNode()
{
CNode* pNode = NULL;
if (m_nCurrentIndex < m_iChildArraySize)
{
pNode = m_arrChildNode[m_nCurrentIndex];
cout<<"Currindex node: "<<m_nCurrentIndex<<endl;
m_nCurrentIndex++;
}
else
cout<<"RETURN NULL NODE"<<endl;
return pNode;
}
CNode* CNode::GetActivatedNode(MA_RESULT eResult)
{
CNode* pNode = NULL;
for(int i = 0; i < m_iChildArraySize; i++)
if(m_nCurrentIndex < m_iChildArraySize && eResult == m_arrChildNode[i]->GetResult())
{
cout<<"RETURN NODE"<<endl;
m_nCurrentIndex++;
return m_arrChildNode[i];
}
cout<<"RETURN NULL NODE"<<endl;
return pNode;
}
void CNode::ReTravel()
{
m_nCurrentIndex = 0;
}
void CNode::Destroy()
{
// Destroy action
if (m_pAction != NULL)
{
delete m_pAction;
}
cout<<"delete CNode"<<endl;
// Destroy child nodes
NodeArray::iterator it = m_arrChildNode.begin();
while (it != m_arrChildNode.end())
{
delete *it;
it++;
}
m_arrChildNode.clear();
} | [
"leesvr90@gmail.com"
] | leesvr90@gmail.com |
3a3a63551084692ada56744e6dd3f03e10758124 | 5fc0e828a935fefcc22fc5161e1640a8ad21d67f | /osapi/inc/osapi/Exceptions.hpp | af8af332bae8b6e95af30853d34a0732a522ad2f | [] | no_license | Berthelmaster/Projekt3 | e7374d24a42da51dc34474a5c1eebc9111f87566 | dbd6db5103f739d390ba56fdc26086ef5a57be9e | refs/heads/master | 2020-04-04T01:55:41.356297 | 2018-12-17T12:43:16 | 2018-12-17T12:43:16 | 155,682,182 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 264 | hpp | #ifndef OSAPI_EXCEPTIONS_HPP
#define OSAPI_EXCEPTIONS_HPP
#include <stdexcept>
namespace osapi
{
class SystemError : public std::runtime_error
{
public:
SystemError(const std::string& what_arg)
: std::runtime_error(what_arg)
{}
private:
};
}
#endif
| [
"apollotoby@gmail.com"
] | apollotoby@gmail.com |
334a31ee8ba2910ed080cb1699c48e0f31cabb5f | 7bd8b4933f2e78d4936d1a4455c84a86b86242fb | /Demo/DEMO.HPP | d7a939376517af06d784f58cdea33b58195d99fe | [] | no_license | dhawt/Immerse | bdbf4470fa6a79da850536efc91272abd01684db | 0f562746f9db33c41a6e047fecb0f49acb513b48 | refs/heads/master | 2016-09-15T23:57:05.086389 | 2012-05-03T19:52:14 | 2012-05-03T19:52:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 626 | hpp | #ifndef _DEMO_HPP
#define _DEMO_HPP
// Includes:
#include <stdlib.h>
#include <conio.h>
#include <stdarg.h>
#include <stdio.h>
#include <windows.h>
#include <windowsx.h>
#include <time.h>
// Libraries:
//#include "H:\Lib\Immerse\Code\Core\IMR_Interface.hpp"
#include "C:\Code\Engines\Lib\Immerse\Code\GeomMngr\IMR_GM_Interface.hpp"
#include "C:\Code\Engines\Lib\WinLayer\WinLayer.hpp"
#include "C:\Code\Engines\Lib\GfxLib\GfxLib.hpp"
// Prototypes:
void Cleanup(void);
void InitWindowApp(void);
LRESULT CALLBACK WndProc(HWND hWnd, unsigned int iMessage,
unsigned int wParam, LONG lParam);
#endif
| [
"daniel@eduschedu.com"
] | daniel@eduschedu.com |
4c3cfe78bf472a4b53828f8b9a8acfe2c1399ce0 | aa2c9edcdd4be2c3f0aaa641378cee8dabd75842 | /chp17d/part2.cpp | a0bd81b8214f5c7d3c91d810d1f59b16d59c9f73 | [] | no_license | asztalosattila007/bevprog | 46cbf73767c0407d06b33ca57596eae5423c75a0 | 8b13194926972a8d5b58d490be1c8dd18e7ea6e4 | refs/heads/master | 2023-01-23T19:30:34.421406 | 2020-12-01T21:50:51 | 2020-12-01T21:50:51 | 296,564,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,465 | cpp | #include "std_lib_facilities.h"
void print_array(ostream& os, int* a, int n)
{
for (int i= 0 ; i< n ; i++)
os << a[i] << "\n";
}
int main()
{
int init = 7; // 1 .fel inicializált változó
int* p1 = &init;
cout<<"content of p1= " << *p1 << endl; //2.
cout<<"p1= " << p1 << endl;
int* p2 = new int[7]{1,2,4,8,16,32,64}; //3.
cout<<"p2= " << p2 << endl; //4.fel
cout<<"content of p2= " << endl;
print_array(cout,p2,7);
int* p3 = p2; //5.
p2 = p1; //6.
p2 = p3; //7.
cout<<" p1= " << p1 << endl; //8.
cout<<"content of p1= " << *p1 << endl;
//print_array(cout,p1,7);
cout<<"p2= " << p2 << endl;
cout<<"content of p2= " << endl;
print_array(cout,p2,7);
//9. p2= p1 és p2=p3
delete[] p3; // p2 = p3 miatt lehet delete[] p2; is
int tomb2[10] = {1,2,4,8,16,32,64,128,256,512}; //10.
p1 = tomb2;
//cout << p1 << endl; //címet írja ki
//cout << *p1 << endl; // 0. elemét írja ki a tömbnek
int tomb3[10] ; //11.
p2 = tomb3;
cout << "content of p2[10]= " << endl;
for (int i = 0; i < 10; ++i) //12
{
p2[i]=p1[i];
}
print_array(cout,p2,10);
cout << " content of p2 vector=" << endl;
vector<int> v1 = {1,2,4,8,16,32,64,128,256,512};
vector<int> v2 ;
v2 = v1;
for (int i= 0 ; i< v2.size(); i++) {
cout << v2[i] << "\n";
}
return 0;
}
| [
"asztalosattila007@gmail.com"
] | asztalosattila007@gmail.com |
cc2d6edceb1c6e528ac1b42960314ae5b70d7348 | 88a81a1685d2f02a529e1ba8bc477a8cbdc27af4 | /src/Shin/ShinAI.cpp | 87b0af1f0cc061d547ec3f84c5a394380b4f6830 | [] | no_license | MarcBrout/HiShinUnit | 4901ae768803aab10ce66135fc60b5e28e07b9ef | acd62cb8808f1369c5abf56b1652c02068a3dc31 | refs/heads/master | 2021-08-28T07:49:24.717023 | 2017-12-11T15:17:24 | 2017-12-11T15:17:24 | 113,872,711 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,424 | cpp | //
// Created by 53818 on 04/12/2017.
//
#include <Shin/ShinHalbard.hpp>
#include <iostream>
#include "Shin/ShinCase.hpp"
#include "Shin/ShinAI.hpp"
namespace ai {
void ShinAI::initializeCases(Board const &board, std::deque<std::unique_ptr<ai::AICase>> &outCases, size_t round) {
for (uint32_t y = 0; y < board.getSize(); ++y) {
for (uint32_t x = 0; x < board.getSize(); ++x) {
if (board[y][x] == CellState::Empty) {
threadPool.addCase(std::make_unique<ai::ShinCase>(board, x, y, round, CellState::Player1));
threadPool.addCase(std::make_unique<ai::ShinCase>(board, x, y, round, CellState::Player2));
}
}
}
}
void ShinAI::resolve(std::deque<std::unique_ptr<ai::AICase>> &casesDone, Position &posOut) {
myPlays.clear();
enemyPlays.clear();
// Splitting the processed cases in their respective container
while (!casesDone.empty()) {
if ((*casesDone.front()).getPlayer() == CellState::Player1) {
const Position& pos = (*casesDone.front()).getPos();
myPlays.addCase(casesDone.front());
} else {
Position const &pos = (*casesDone.front()).getPos();
enemyPlays.addCase(casesDone.front());
}
casesDone.pop_front();
}
// Can I win ?
if (myPlays.getCount(Line::FINAL_WIN) > 0) {
simplePlay(posOut, Line::FINAL_WIN, myPlays);
return ;
}
// Can I Lose ?
if (enemyPlays.getCount(Line::FINAL_WIN) > 0) {
simplePlay(posOut, Line::FINAL_WIN, enemyPlays);
return ;
}
uint32_t myWins = myPlays.getCount(Line::WIN);
uint32_t enemyWins = enemyPlays.getCount(Line::WIN);
if (myWins >= enemyWins && myWins > 0) {
fusionPlays(posOut, Line::WIN, CellState::Player1);
} else if (enemyWins > myWins) {
fusionPlays(posOut, Line::WIN, CellState::Player2);
} else {
fusionPlays(posOut, Line::HIGH, Empty);
}
}
bool findCommonValuePosition(std::vector<Position> const &myFusion, std::vector<Position> const &enemyFusion, Position &outPos) {
for (Position const &myPos : myFusion) {
for (Position const &enemyPos : enemyFusion) {
if (myPos == enemyPos) {
outPos = myPos;
return true;
}
}
}
return false;
}
void ShinAI::fusionPlays(Position &outPos, Line::Values value, CellState priority) {
Line::Values myBestPlay;
Line::Values enemyBestPlay;
std::vector<Position> myFusion = myPlays.getMaxPositions(value, myBestPlay);
std::vector<Position> enemyFusion = enemyPlays.getMaxPositions(value, enemyBestPlay);
if (priority != CellState::Empty) {
if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(myFusion, enemyFusion, outPos)) {
return;
}
if (priority == CellState::Player1) {
outPos = myFusion.front();
} else {
outPos = enemyFusion.front();
}
} else {
if (myBestPlay > enemyBestPlay) {
if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(myFusion, enemyFusion, outPos)) {
return;
}
outPos = myFusion.front();
} else if (enemyBestPlay > myBestPlay) {
if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(enemyFusion, myFusion, outPos)) {
return;
}
outPos = enemyFusion.front();
} else {
if (enemyFusion.size() > myFusion.size()) {
outPos = enemyFusion.front();
} else {
outPos = myFusion.front();
}
}
}
}
void ShinAI::simplePlay(Position &outPos, Line::Values value, ShinHalbard &halbard) {
Line::Values best;
std::vector<Position> plays = halbard.getMaxPositions(value, best);
outPos = plays.front();
}
ShinAI::ShinAI(unsigned int threadCount, unsigned int timeLimit) : AAI(threadCount, timeLimit) {
}
} | [
"brout.marc@epitech.eu"
] | brout.marc@epitech.eu |
d114eb6ec4564b0834e8d83668564c9d42505676 | bffb5982a832677386a198732bb486b874bda302 | /ATCCSOrm/src/at60gimbalstatus-odb.hxx | 7a1d256f5c61d7ca27d9272b6cedf7672d22446f | [] | no_license | iamgeniuswei/ATCCS | 4e28b6f0063c1f4089b447fa3d00299350c1e416 | 5261b26fbf99cebd0909f06a7bb1bcf9e47cb5e2 | refs/heads/master | 2021-01-24T07:42:10.596733 | 2017-06-05T01:34:40 | 2017-06-05T01:34:40 | 93,351,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,955 | hxx | // This file was generated by ODB, object-relational mapping (ORM)
// compiler for C++.
//
#ifndef AT60GIMBALSTATUS_ODB_HXX
#define AT60GIMBALSTATUS_ODB_HXX
#include <odb/version.hxx>
#if (ODB_VERSION != 20400UL)
#error ODB runtime version mismatch
#endif
#include <odb/pre.hxx>
#include "at60gimbalstatus.h"
#include "atccsgimbalstatus-odb.hxx"
#include "atccspublicstatus-odb.hxx"
#include <memory>
#include <cstddef>
#include <utility>
#include <odb/core.hxx>
#include <odb/traits.hxx>
#include <odb/callback.hxx>
#include <odb/wrapper-traits.hxx>
#include <odb/pointer-traits.hxx>
#include <odb/container-traits.hxx>
#include <odb/session.hxx>
#include <odb/cache-traits.hxx>
#include <odb/result.hxx>
#include <odb/simple-object-result.hxx>
#include <odb/details/unused.hxx>
#include <odb/details/shared-ptr.hxx>
namespace odb
{
// at60gimbalstatus
//
template <>
struct class_traits< ::at60gimbalstatus >
{
static const class_kind kind = class_object;
};
template <>
class access::object_traits< ::at60gimbalstatus >
{
public:
typedef ::at60gimbalstatus object_type;
typedef ::at60gimbalstatus* pointer_type;
typedef odb::pointer_traits<pointer_type> pointer_traits;
static const bool polymorphic = false;
typedef object_traits< ::atccspublicstatus >::id_type id_type;
static const bool auto_id = object_traits< ::atccspublicstatus >::auto_id;
static const bool abstract = false;
static id_type
id (const object_type&);
typedef
odb::pointer_cache_traits<
pointer_type,
odb::session >
pointer_cache_traits;
typedef
odb::reference_cache_traits<
object_type,
odb::session >
reference_cache_traits;
static void
callback (database&, object_type&, callback_event);
static void
callback (database&, const object_type&, callback_event);
};
}
#include <odb/details/buffer.hxx>
#include <odb/pgsql/version.hxx>
#include <odb/pgsql/forward.hxx>
#include <odb/pgsql/binding.hxx>
#include <odb/pgsql/pgsql-types.hxx>
#include <odb/pgsql/query.hxx>
namespace odb
{
// at60gimbalstatus
//
template <typename A>
struct query_columns< ::at60gimbalstatus, id_pgsql, A >:
query_columns< ::atccsgimbalstatus, id_pgsql, A >
{
// atccsgimbalstatus
//
typedef query_columns< ::atccsgimbalstatus, id_pgsql, A > atccsgimbalstatus;
};
template <typename A>
struct pointer_query_columns< ::at60gimbalstatus, id_pgsql, A >:
query_columns< ::at60gimbalstatus, id_pgsql, A >
{
};
template <>
class access::object_traits_impl< ::at60gimbalstatus, id_pgsql >:
public access::object_traits< ::at60gimbalstatus >
{
public:
typedef object_traits_impl< ::atccspublicstatus, id_pgsql >::id_image_type id_image_type;
struct image_type: object_traits_impl< ::atccsgimbalstatus, id_pgsql >::image_type
{
std::size_t version;
};
struct extra_statement_cache_type;
using object_traits<object_type>::id;
static id_type
id (const id_image_type&);
static id_type
id (const image_type&);
static bool
grow (image_type&,
bool*);
static void
bind (pgsql::bind*,
image_type&,
pgsql::statement_kind);
static void
bind (pgsql::bind*, id_image_type&);
static bool
init (image_type&,
const object_type&,
pgsql::statement_kind);
static void
init (object_type&,
const image_type&,
database*);
static void
init (id_image_type&, const id_type&);
typedef pgsql::object_statements<object_type> statements_type;
typedef pgsql::query_base query_base_type;
static const std::size_t column_count = 79UL;
static const std::size_t id_column_count = 1UL;
static const std::size_t inverse_column_count = 0UL;
static const std::size_t readonly_column_count = 0UL;
static const std::size_t managed_optimistic_column_count = 0UL;
static const std::size_t separate_load_column_count = 0UL;
static const std::size_t separate_update_column_count = 0UL;
static const bool versioned = false;
static const char persist_statement[];
static const char find_statement[];
static const char update_statement[];
static const char erase_statement[];
static const char query_statement[];
static const char erase_query_statement[];
static const char table_name[];
static void
persist (database&, object_type&);
static pointer_type
find (database&, const id_type&);
static bool
find (database&, const id_type&, object_type&);
static bool
reload (database&, object_type&);
static void
update (database&, const object_type&);
static void
erase (database&, const id_type&);
static void
erase (database&, const object_type&);
static result<object_type>
query (database&, const query_base_type&);
static unsigned long long
erase_query (database&, const query_base_type&);
static const char persist_statement_name[];
static const char find_statement_name[];
static const char update_statement_name[];
static const char erase_statement_name[];
static const char query_statement_name[];
static const char erase_query_statement_name[];
static const unsigned int persist_statement_types[];
static const unsigned int find_statement_types[];
static const unsigned int update_statement_types[];
public:
static bool
find_ (statements_type&,
const id_type*);
static void
load_ (statements_type&,
object_type&,
bool reload);
};
template <>
class access::object_traits_impl< ::at60gimbalstatus, id_common >:
public access::object_traits_impl< ::at60gimbalstatus, id_pgsql >
{
};
// at60gimbalstatus
//
}
#include "at60gimbalstatus-odb.ixx"
#include <odb/post.hxx>
#endif // AT60GIMBALSTATUS_ODB_HXX
| [
"iamgeniuswei@sina.com"
] | iamgeniuswei@sina.com |
e4585f3eb373ba923b3d7fde51804a093ed6d755 | b6fb8cc7e66ab98a793007317717b98d72e18e11 | /io/ByteArrayInputStream.h | d3801576cf23bfcee4bc59fc462ae5864821a877 | [
"MIT"
] | permissive | gizmomogwai/cpplib | 70aee27dd04e464868e8ff72822150731cfb63cd | a09bf4d3f2a312774d3d85a5c65468099a1797b0 | refs/heads/master | 2021-10-31T10:17:51.939965 | 2021-10-08T21:57:19 | 2021-10-08T21:59:12 | 66,270,218 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,049 | h | #pragma once
#include <io/InputStream.h>
/** Klasse um auf einem Seicherbereich mit einem InputStream abzugehen.
*
* Es wird nur eine Referenz auf den Speicher gespeichert,
* nicht der Speicher des Buffers kopiert. Der Speicher wird auch nicht vom
* Stream verwaltet. Wenn man den Speicher nicht mehr braucht muss dieser
* also von der Applikation geloescht werden. Wird der Speicher geloescht,
* und weiterhin auf dem Stream abgegangen droht gefahr (der stream kann
* den speicher nicht wirklich freigeben, da er nicht weiss, was es fuer
* ein speicher ist)
*
* <p>
* Curriculum Vitae:
* <ul>
* <li> 2000-11-19, cK, Created.
* </ul>
*
* @todo Bessere Rangechecks.
*
* @version $Revision: 1.3 $, $Date: 2001/09/13 13:11:10 $
*
* @author cK, $Author: koestlin $
*/
class ByteArrayInputStream : public InputStream {
public:
/** Erzeugt einen neuen ByteArrayInputStream auf dem angegebenen
* Speicherbereich.
*
* @param _buffer Source-speicher.
* @param _offset Offset ab dem die Daten als InputStreasmangeboten
* werden sollen.
* @param _available Anzahl der Bte, die im Strom angeboten werden
* sollen.
*/
ByteArrayInputStream(DataBuffer* _buffer, int _offset, int _available);
/** Raeumt auf.
*/
virtual ~ByteArrayInputStream();
/** Liesst ein byte aus dem strom.
*
* @return int byte oder -1.
*/
virtual int read() throw (IOException);
/** Liesst eine Menge von byte aus dem strom.
*
* @param target Datenpuffer in den die Werte geschrieben werden sollen.
* @param offset Offset ab dem in die Daten geschrieben werden soll.
* @param length Maximale Anzahl zu schreibender Daten.
*
* @return int Anzahl geschriebener byte.
*/
virtual int read(DataBuffer& target, int offset, int length)
throw (IOException);
private:
/** Adresse des source-speichers. */
unsigned char* buffer;
/** Anzahl von verfuegbaren bytes. */
int available;
};
| [
"christian.koestlin@esrlabs.com"
] | christian.koestlin@esrlabs.com |
deca9e61ac21205d28f536660ca7f87fb05e00a7 | 8f6fc9656e62881533b8d85e803452116cc0305f | /Source/Quint/Assemblies/Weapons/Mallet.h | 324ed2fd609631a1ae5384292819c6023e111dd2 | [] | no_license | minogb/Quintessence | 47056597790565f454412b8c051c4b08422b4a21 | d83ea5130a199baa21407c90225023556fa31173 | refs/heads/master | 2020-03-28T10:17:10.403482 | 2019-11-06T05:08:50 | 2019-11-06T05:08:50 | 148,097,322 | 3 | 3 | null | 2018-10-14T20:09:09 | 2018-09-10T04:04:51 | C++ | UTF-8 | C++ | false | false | 1,200 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Assemblies/AssembledEquipment.h"
#include "Interfaces/WeaponInterface.h"
#include "Mallet.generated.h"
/**
*
*/
UCLASS()
class QUINT_API UMallet : public UAssembledEquipment, public IWeaponInterface
{
GENERATED_BODY()
UPROPERTY()
UItem* HammerHead;
UPROPERTY()
UItem* Binding;
UPROPERTY()
UItem* ShortHandle;
public:
UMallet();
virtual FString GetSaveJSON() override;
virtual UItem** GetComponent(EAssemblyComponentType Type);
virtual void InitWithJson(TSharedPtr<FJsonObject> JsonData) override;
virtual int GetSkillLevel_Implementation(ESkillType Skill) { return 0; }
virtual bool SetWeaponMode_Implementation(int Mode = 0);
virtual float GetWeaponRange_Implementation();
virtual float GetWeaponAttackDuration_Implementation();
virtual float GetWeaponAttackCooldown_Implementation();
virtual bool GetDamageStruct_Implementation(UPARAM(ref)FDamageStruct& Damage);
virtual bool CanUseWeapon_Implementation(AAvatar* Avatar);
virtual bool UseWeapon_Implementation(AAvatar* DamageCauser, UPARAM(ref)FDamageStruct& Damage, AActor* DamageTarget);
};
| [
"minoguebrad@rocketamil.com"
] | minoguebrad@rocketamil.com |
f1a331958ea522bf8559d378a5e52a14381e474e | e9698b61fdad8b64530f75981864768a98d6bf88 | /tp6/sia_td6/include/sphere.h | 837fb3b005e38f3f89489a1a40d8fc1561992196 | [] | no_license | Johan-David/SIA | c6abdb638a63c7d7d6d9284877ec0ff488bec88c | 660a2ba600c3e455f1bd7cfb5e27c3e933aa938b | refs/heads/master | 2021-09-03T03:55:12.894559 | 2018-01-05T10:33:56 | 2018-01-05T10:33:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | h | #ifndef _SPHERE_H
#define _SPHERE_H
#include "shape.h"
#include <vector>
class Sphere : public Shape {
public:
Sphere(float radius=1.f, int nU=40, int nV=40);
virtual ~Sphere();
void init();
void display(Shader *shader);
float radius() const { return _radius; }
private:
GLuint _vao;
GLuint _vbo[6];
std::vector<int> _indices; /** vertex indices */
std::vector<Eigen::Vector3f> _vertices; /** 3D positions */
std::vector<Eigen::Vector3f> _colors; /** colors */
std::vector<Eigen::Vector3f> _normals; /** 3D normals */
std::vector<Eigen::Vector3f> _tangents; /** 3D tangent to surface */
std::vector<Eigen::Vector2f> _texCoords; /** 2D texture coordinates */
float _radius;
};
#endif
| [
"axelwolski92@gmail.com"
] | axelwolski92@gmail.com |
84da9d25f3e5edb38aa95c7bb8eaa9ce0e37cd8e | c5f67ad3724d62c712d58144b5abea10c06a2314 | /Lab1/ece250.h | 138df16e0fa84cdc7727f4cd43ac939f7f824d87 | [] | no_license | hyc20908/ECE250 | fdd74688998475a292978574836b57488d3514d9 | 8d6d5e91b244eea8c8a684c9d8bb48a6337cbc64 | refs/heads/master | 2021-01-13T12:07:44.763902 | 2018-09-10T15:05:40 | 2018-09-10T15:05:40 | 78,052,948 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,884 | h | #ifndef ECE250
#define ECE250
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include "Exception.h"
/**************************************************************************
* ************************************************************************
* * You don't have to use the Tester classes to use this to manage your
* * memory. All you must do is include this file and then, if you ever
* * want to test if you have memory which is currently unallocated,
* * you may use ece250::allocation_table.summary();
* *
* * You must simply indicate that you want to start recording by
* * using ece250::alocation_table.summary();
* *
* ************************************************************************
**************************************************************************/
/****************************************************************************
* ece250
* Author: Douglas Wilhelm Harder
* Copyright (c) 2006-9 by Douglas Wilhelm Harder. All rights reserved.
*
* DO NOT EDIT THIS FILE
*
* This file is broken into two parts:
*
* 1. The first namespace ece250 is associated with tools used by the
* second part.
* 2. The second has globally overloaded new, delete, new[], and delete[].
*
* This tracks everything that deals with memory allocation (new and new[])
* and memory deallocation (delete and delete[]).
*
* Each time 'new' or 'new[]' is called, an appropriate entry is
* set in a hash table 'allocation_table'. The hash function of any address
* is the last log[2](array_size) bits.
*
* Each time that 'delete' or 'delete[]' is called, it is checked whether:
* 1. the memory was actually allocated,
* 2. the appropriate form of delete versus delete[] is being called, and
* 3. delete/delete[] has been called multiple times.
*
* The class also stores how much memory was allocated and how much was
* deallocated. The summary() function prints a summary indicating the
* difference. When this is called at the end of a test, the result must
* be zero (0).
*
* If there is a problem with either allocation or deallocation, two events
* occur: a warning is printed and an exception is thrown.
*
* Each throw is associated with a warning sent to the student through cout.
****************************************************************************/
namespace ece250 {
int memory_alloc_store;
const size_t PAD = 16;
class overflow {};
class invalid_deletion {};
// Each time a student calls either new or new[], the
// information about the memory allocation is stored in
// an instance of this class
class Allocation {
public:
void *address;
size_t size;
bool is_array;
bool deleted;
Allocation():
address( 0 ),
size( 0 ),
is_array( false ),
deleted( false ) {
// Empty constructor
}
Allocation( void *a, size_t s, bool i ):
address( a ),
size( s ),
is_array( i ),
deleted( false ) {
// Empty constructor
}
};
int to_int( int *ptr ) {
int result = *ptr;
if ( result < 0 ) {
result = result + (1 << (sizeof( int ) - 1));
}
return result >> 3;
}
// All instances of an allocation are stored in this chained hash table
class HashTable {
private:
int array_size;
Allocation *allocated;
int total_memory_alloc;
int total_memory_deleted;
bool record;
public:
// Initialize all of the addresses to 0
HashTable( int as ):
array_size( as ),
total_memory_alloc( 0 ),
total_memory_deleted( 0 ),
record( false ) {
allocated = new Allocation[array_size];
}
int reserve( int N ) {
// N must be a power of 2
if ( (N & ((~N) + 1)) != N ) {
throw illegal_argument();
}
delete [] allocated;
array_size = N;
allocated = new Allocation[array_size];
return 0;
}
int memory_alloc() const {
return total_memory_alloc - total_memory_deleted;
}
void memory_store() const {
memory_alloc_store = total_memory_alloc - total_memory_deleted;
}
void memory_change( int n ) const {
int memory_alloc_diff = total_memory_alloc - total_memory_deleted - memory_alloc_store;
if ( memory_alloc_diff != n ) {
std::cout << "WARNING: expecting a change in memory allocation of " << n << " bytes, but the change was " << memory_alloc_diff << std::endl;
}
}
// Insert uses the last log[2]( array_size ) bits of the address as the hash function
// It finds an unallocated entry in the array and stores the information
// about the memory allocation in that entry, including:
// The amount of memory allocated,
// Whether new or new[] was used for the allocation, and
// The address of the allocated memory.
void insert( void *ptr, size_t size, bool is_array ) {
if ( !record ) {
return;
}
// the hash function is the last log[2]( array_size ) bits
int hash = to_int( reinterpret_cast<int *>( &ptr ) ) & (array_size - 1);
for ( int i = 0; i < array_size; ++i ) {
// It may be possible that we are allocated the same memory
// location twice (if there are numerous allocations and
// deallocations of memory. Thus, the second check is necessary,
// otherwise it may introduce session dependant errors.
if ( allocated[hash].address == 0 || allocated[hash].address == ptr ) {
// Store the address, the amount of memory allocated,
// whether or not new[] was used, and set 'deleted' to false.
allocated[hash] = Allocation( ptr, size, is_array );
// Add the memory allocated to the total memory allocated.
total_memory_alloc += size;
return;
}
hash = (hash + 1) & (array_size - 1);
}
std::cout << "WARNING: allocating more memory than is allowed for this project" << std::endl;
throw overflow();
}
// Remove checks:
// If the given memory location was allocated in the first place, and
// If the appropriate form of delete was used, i.e., delete versus delete[], and
// If delete has already been called on this object
size_t remove( void *ptr, bool is_array ) {
if ( !record || ptr == 0 ) {
return 0;
}
// the hash function is the last log[2]( array_size ) bits
int hash = to_int( reinterpret_cast<int *>( &ptr ) ) & ( array_size - 1 );
// Continue searching until we've checked all bins
// or we find an empty bin.
for ( int i = 0; i < array_size && allocated[hash].address != 0; ++i ) {
if ( allocated[hash].address == ptr ) {
// First check if:
// 1. If the wrong delete was called (e.g., delete[] when new was
// used or delete when new[] was used).
// 2. If the memory has already been deallocated previously.
//
// If the deletion is successful, then:
// 1. Set the 'deleted' flag to 'true', and
// 2. Add the memory deallocated ot the total memory deallocated.
if ( allocated[hash].is_array != is_array ) {
if ( allocated[hash].is_array ) {
std::cout << "WARNING: use 'delete [] ptr;' to use memory allocated with 'ptr = new Class[array_size];'" << std::endl;
} else {
std::cout << "WARNING: use 'delete ptr;' to use memory allocated with 'ptr = new Class(...);'" << std::endl;
}
throw invalid_deletion();
} else if ( allocated[hash].deleted ) {
std::cout << "WARNING: calling delete twice on the same memory location: " << ptr << std::endl;
throw invalid_deletion();
}
allocated[hash].deleted = true;
total_memory_deleted += allocated[hash].size;
// zero the memory before it is deallocated
char *cptr = static_cast<char *>( ptr );
for ( size_t j = 0; j < allocated[hash].size; ++j ) {
cptr[j] = 0;
}
return allocated[hash].size;
}
hash = (hash + 1) & (array_size - 1);
}
// If we've gotten this far, this means that the address was
// never allocated, and therefore we are calling delete on
// something which should be deleted.
std::cout << "WARNING: deleting a pointer to which memory was never allocated: " << ptr << std::endl;
throw invalid_deletion();
}
// Print a difference between the memory allocated and the memory deallocated
void summary() {
std::cout << "Memory allocated minus memory deallocated: "
<< total_memory_alloc - total_memory_deleted << std::endl;
}
// Print the difference between total memory allocated and total memory deallocated.
void details() {
std::cout << "SUMMARY OF MEMORY ALLOCATION:" << std::endl;
std::cout << " Memory allocated: " << total_memory_alloc << std::endl;
std::cout << " Memory deallocated: " << total_memory_deleted << std::endl << std::endl;
std::cout << "INDIVIDUAL REPORT OF MEMORY ALLOCATION:" << std::endl;
std::cout << " Address Using Deleted Bytes " << std::endl;
for ( int i = 0; i < array_size; ++i ) {
if ( allocated[i].address != 0 ) {
std::cout << " " << allocated[i].address
<< ( allocated[i].is_array ? " new[] " : " new " )
<< ( allocated[i].deleted ? "Y " : "N " )
<< std::setw( 6 )
<< allocated[i].size << std::endl;
}
}
}
// Start recording memory allocations
void start_recording() {
record = true;
}
// Stop recording memory allocations
void stop_recording() {
record = false;
}
bool is_recording() {
return record;
}
};
bool asymptotic_tester( double *array, int N, int k, bool ln ) {
double *ratios = new double[N];
double *differences = new double[N- 1];
int M = 2;
for ( int i = 0; i < N; ++i ) {
ratios[i] = array[i] / (M*(ln ? std::log( static_cast<double>( M ) ) : 1.0));
M = M*(1 << k);
}
for ( int i = 0; i < N - 1; ++i ) {
differences[i] = ratios[i + 1] - ratios[i];
// std::cout << differences[i] << std::endl;
}
for ( int i = 1; i < N - 1; ++i ) {
if ( !( differences[i] < 0 ) ) {
if ( differences[i] > differences[i - 1] ) {
return false;
}
}
}
delete [] ratios;
delete [] differences;
return true;
}
HashTable allocation_table( 8192 );
std::string history[101];
int count = 0;
void initialize_array_bounds( char *ptr, size_t size ) {
for ( int i = 0; i < PAD; ++i ) {
ptr[i] = 63 + i;
ptr[size - i - 1] = 89 + i;
}
}
void check_array_bounds( char *ptr, size_t size ) {
for ( int i = 0; i < PAD; ++i ) {
if ( ptr[i] != 63 + i ) {
std::cout << "Memory before the array located at adderss "
<< static_cast<void *>( ptr + PAD ) << " was overwritten" << std::endl;
throw out_of_bounds();
}
if ( ptr[size - i - 1] != 89 + i ) {
std::cout << "Memory after the array located at adderss "
<< static_cast<void *>( ptr + PAD ) << " was overwritten" << std::endl;
throw out_of_bounds();
}
}
}
}
/****************************************************************************
* new
* Author: Douglas Wilhelm Harder
* Overloads the global operator new
*
* Use malloc to perform the allocation.
* Insert the pointer returned by malloc into the hash table.
*
* The argument 'false' indicates that this is a call
* to new (versus a call to new[]).
*
* Return the pointer to the user.
****************************************************************************/
void *operator new( size_t size ) {
void *ptr = malloc( size );
ece250::allocation_table.insert( ptr, size, false );
return static_cast<void *>( ptr );
}
/****************************************************************************
* delete
* Author: Douglas Wilhelm Harder
* Overloads the global operator delete
*
* Remove the pointer from the hash table (the entry is not truly removed,
* simply marked as removed).
*
* The argument 'false' indicates that this is a call
* to delete (versus a call to delete[]).
*
* Use free to perform the deallocation.
****************************************************************************/
void operator delete( void *ptr ) {
ece250::allocation_table.remove( ptr, false );
free( ptr );
}
/****************************************************************************
* new[]
* Author: Douglas Wilhelm Harder
* Overloads the global operator new[]
*
* Use malloc to perform the allocation.
* Insert the pointer returned by malloc into the hash table.
*
* The argument 'true' indicates that this is a call
* to new[] (versus a call to new).
*
* Return the pointer to the user.
****************************************************************************/
void *operator new[]( size_t size ) {
char *ptr = static_cast<char *>( malloc( size + 2*ece250::PAD ) );
ece250::allocation_table.insert( static_cast<void *>( ptr + ece250::PAD ), size, true );
ece250::initialize_array_bounds( ptr, size + 2*ece250::PAD );
return static_cast<void *>( ptr + ece250::PAD );
}
/****************************************************************************
* delete[]
* Author: Douglas Wilhelm Harder
* Overloads the global operator delete[]
*
* Remove the pointer from the hash table (the entry is not truly removed,
* simply marked as removed).
*
* The argument 'true' indicates that this is a call
* to delete[] (versus a call to delete).
*
* Use free to perform the deallocation.
****************************************************************************/
void operator delete[]( void *ptr ) {
size_t size = ece250::allocation_table.remove( ptr, true );
if ( ece250::allocation_table.is_recording() ) {
ece250::check_array_bounds( static_cast<char *>( ptr ) - ece250::PAD, size + 2*ece250::PAD );
}
free( static_cast<char *>( ptr ) - ece250::PAD );
}
#endif
| [
"kevin.han@coengadvisors.com"
] | kevin.han@coengadvisors.com |
8f85ff85c18495511605a75c88d90e490a8f6f5e | 047600ca8efa01dd308f4549793db97e6ddcec20 | /Src/HLSDK/dlls/weapon_shotgun.cpp | 0e24fb0465bb6a31df57aa6b7d8f871dc4b43bc2 | [] | no_license | crskycode/Mind-Team | cbb9e98322701a5d437fc9823dd4c296a132330f | ceab21c20b0b51a2652c02c04eb7ae353b82ffd0 | refs/heads/main | 2023-03-16T10:34:31.812155 | 2021-03-02T02:23:40 | 2021-03-02T02:23:40 | 343,616,799 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,833 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
***/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "weapons.h"
LINK_ENTITY_TO_CLASS(weapon_shotgun, CShotgun);
void CShotgun::Spawn(void)
{
pev->classname = MAKE_STRING("weapon_shotgun");
Precache();
CBasePlayerWeapon::Spawn();
m_iWeaponClass = WeaponClass_Shotgun;
m_iClip = m_Info.iAmmoPerMagazine;
m_iAmmo = m_Info.iMaxAmmo;
}
void CShotgun::Precache(void)
{
m_iShotgunFire = PRECACHE_EVENT(1, "events/shotgunfire.sc");
}
void CShotgun::Deploy(void)
{
m_fInSpecialReload = FALSE;
DefaultDeploy(m_Info.iszPViewModelFileName, m_Info.iszGViewModelFileName, m_Info.m_AnimSelect.iSequence, m_Info.szGViewAnimName, m_Info.m_AnimSelect.flTime);
}
void CShotgun::Reload(void)
{
if (m_iClip >= m_Info.iAmmoPerMagazine || m_iAmmo <= 0)
return;
if (m_flNextPrimaryAttack > UTIL_WeaponTimeBase())
return;
if (!m_fInSpecialReload)
{
m_pPlayer->SetAnimation(PLAYER_RELOAD);
SendWeaponAnim(m_Info.m_AnimStartReload.iSequence);
m_fInSpecialReload = 1;
m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime;
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime;
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime;
m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime;
}
else if (m_fInSpecialReload == 1)
{
if (m_flTimeWeaponIdle > UTIL_WeaponTimeBase())
return;
m_fInSpecialReload = 2;
SendWeaponAnim(m_Info.m_AnimReload.iSequence);
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimReload.flTime;
}
else
{
m_iClip++;
m_iAmmo--;
m_fInSpecialReload = 1;
}
}
void CShotgun::PrimaryAttack(void)
{
if (m_pPlayer->pev->velocity.Length2D() > 0)
ShotgunFire(m_Info.m_AccuracyRunning.flSpreadBase, m_Info.flShotIntervalTime);
else if (!FBitSet(m_pPlayer->pev->flags, FL_ONGROUND))
ShotgunFire(m_Info.m_AccuracyJumping.flSpreadBase, m_Info.flShotIntervalTime);
else if (FBitSet(m_pPlayer->pev->flags, FL_DUCKING))
ShotgunFire(m_Info.m_AccuracyDucking.flSpreadBase, m_Info.flShotIntervalTime);
else
ShotgunFire(m_Info.m_AccuracyDefault.flSpreadBase, m_Info.flShotIntervalTime);
}
void CShotgun::ShotgunFire(float flSpread, float flCycleTime)
{
if (m_iClip <= 0)
{
EMIT_SOUND_DYN(m_pPlayer->edict(), CHAN_WEAPON, "weapon/others/g_nobullet_shotgun.wav", VOL_NORM, ATTN_NORM, 0, PITCH_NORM);
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 0.2;
return;
}
m_iClip--;
m_pPlayer->SetAnimation(PLAYER_ATTACK1);
SendWeaponAnim(m_Info.m_AnimFire.iSequence);
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimFire.flTime + 0.1;
UTIL_MakeVectors(m_pPlayer->pev->v_angle + m_pPlayer->pev->punchangle * 2);
m_pPlayer->FireShotgun(m_Info.m_FireBullets.iShots, m_pPlayer->GetGunPosition(), gpGlobals->v_forward, flSpread, m_Info.m_FireBullets.flDistance, m_Info.m_FireBullets.iDamage, m_Info.m_FireBullets.flRangeModifier, m_pPlayer->pev, m_pPlayer->random_seed);
PLAYBACK_EVENT_FULL(FEV_NOTHOST, m_pPlayer->edict(), m_iShotgunFire, 0, g_vecZero, g_vecZero, flSpread, 0, (int)(m_pPlayer->pev->punchangle.x * 100), (int)(m_pPlayer->pev->punchangle.y * 100), m_pPlayer->random_seed, m_Info.iWeaponIndex);
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + flCycleTime;
m_fInSpecialReload = FALSE;
if (m_pPlayer->pev->velocity.Length2D() > 0)
m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackRunning.flUpBase;
else if (!FBitSet(m_pPlayer->pev->flags, FL_ONGROUND))
m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackJumping.flUpBase;
else if (FBitSet(m_pPlayer->pev->flags, FL_DUCKING))
m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackDucking.flUpBase;
else
m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackDefault.flUpBase;
}
void CShotgun::WeaponIdle(void)
{
if (m_flTimeWeaponIdle <= UTIL_WeaponTimeBase())
{
if (m_iClip <= 0 && !m_fInSpecialReload && m_iAmmo > 0)
{
Reload();
}
else if (m_fInSpecialReload)
{
if (m_iClip < m_Info.iAmmoPerMagazine && m_iAmmo > 0)
{
Reload();
}
else
{
SendWeaponAnim(m_Info.m_AnimEndReload.iSequence);
m_fInSpecialReload = FALSE;
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimEndReload.flTime;
}
}
}
}
float CShotgun::GetMaxSpeed(void)
{
return m_Info.flMaxMoveSpeed;
} | [
"crskycode@hotmail.com"
] | crskycode@hotmail.com |
bddfc6273cc0307ef466fffb318ce1fe985ff6f2 | 33b567f6828bbb06c22a6fdf903448bbe3b78a4f | /opencascade/VrmlData_Texture.hxx | 4ea0f61f9c6e963c4d4b8a5d9c5f23124fbc9d51 | [
"Apache-2.0"
] | permissive | CadQuery/OCP | fbee9663df7ae2c948af66a650808079575112b5 | b5cb181491c9900a40de86368006c73f169c0340 | refs/heads/master | 2023-07-10T18:35:44.225848 | 2023-06-12T18:09:07 | 2023-06-12T18:09:07 | 228,692,262 | 64 | 28 | Apache-2.0 | 2023-09-11T12:40:09 | 2019-12-17T20:02:11 | C++ | UTF-8 | C++ | false | false | 2,465 | hxx | // Created on: 2006-05-25
// Created by: Alexander GRIGORIEV
// Copyright (c) 2006-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef VrmlData_Texture_HeaderFile
#define VrmlData_Texture_HeaderFile
#include <VrmlData_Node.hxx>
/**
* Implementation of the Texture node
*/
class VrmlData_Texture : public VrmlData_Node
{
public:
// ---------- PUBLIC METHODS ----------
/**
* Empty constructor
*/
inline VrmlData_Texture ()
: myRepeatS (Standard_False),
myRepeatT (Standard_False)
{}
/**
* Constructor
*/
inline VrmlData_Texture (const VrmlData_Scene& theScene,
const char * theName,
const Standard_Boolean theRepeatS = Standard_False,
const Standard_Boolean theRepeatT = Standard_False)
: VrmlData_Node (theScene, theName),
myRepeatS (theRepeatS),
myRepeatT (theRepeatT)
{}
/**
* Query the RepeatS value
*/
inline Standard_Boolean
RepeatS () const { return myRepeatS; }
/**
* Query the RepeatT value
*/
inline Standard_Boolean
RepeatT () const { return myRepeatT; }
/**
* Set the RepeatS flag
*/
inline void SetRepeatS (const Standard_Boolean theFlag)
{ myRepeatS = theFlag; }
/**
* Set the RepeatT flag
*/
inline void SetRepeatT (const Standard_Boolean theFlag)
{ myRepeatT = theFlag; }
protected:
// ---------- PROTECTED METHODS ----------
private:
// ---------- PRIVATE FIELDS ----------
Standard_Boolean myRepeatS;
Standard_Boolean myRepeatT;
public:
// Declaration of CASCADE RTTI
DEFINE_STANDARD_RTTI_INLINE(VrmlData_Texture,VrmlData_Node)
};
// Definition of HANDLE object using Standard_DefineHandle.hxx
DEFINE_STANDARD_HANDLE (VrmlData_Texture, VrmlData_Node)
#endif
| [
"adam.jan.urbanczyk@gmail.com"
] | adam.jan.urbanczyk@gmail.com |
810883c134c479393c37b3e2aca4156d91b4fe62 | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /services/network/public/cpp/corb/orb_impl.cc | 9c888b6f9e36077814ab6c6ef172497948222a1b | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 9,089 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/public/cpp/corb/orb_impl.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_piece.h"
#include "net/url_request/url_request.h"
#include "services/network/public/cpp/corb/corb_impl.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
namespace network {
namespace corb {
namespace {
// This corresponds to "opaque-blocklisted-never-sniffed MIME type" in ORB spec.
bool IsOpaqueBlocklistedNeverSniffedMimeType(base::StringPiece mime_type) {
return CrossOriginReadBlocking::GetCanonicalMimeType(mime_type) ==
CrossOriginReadBlocking::MimeType::kNeverSniffed;
}
// ORB spec says that "An opaque-safelisted MIME type" is a JavaScript MIME type
// or a MIME type whose essence is "text/css" or "image/svg+xml".
bool IsOpaqueSafelistedMimeType(base::StringPiece mime_type) {
// Based on the spec: Is it a MIME type whose essence is "text/css" or
// "image/svg+xml"?
if (base::LowerCaseEqualsASCII(mime_type, "image/svg+xml") ||
base::LowerCaseEqualsASCII(mime_type, "text/css")) {
return true;
}
// Based on the spec: Is it a JavaScript MIME type?
if (CrossOriginReadBlocking::IsJavascriptMimeType(mime_type))
return true;
// https://github.com/annevk/orb/issues/20 tracks explicitly covering DASH
// mime type in the ORB algorithm.
if (base::LowerCaseEqualsASCII(mime_type, "application/dash+xml"))
return true;
return false;
}
// Return true for multimedia MIME types that
// 1) are not explicitly covered by ORB (e.g. that do not begin with "audio/",
// "image/", "video/" and that are not covered by
// IsOpaqueSafelistedMimeType).
// 2) would be recognized by sniffing from steps 6 or 7 of ORB:
// step 6. If the image type pattern matching algorithm ...
// step 7. If the audio or video type pattern matching algorithm ...
bool IsSniffableMultimediaType(base::StringPiece mime_type) {
if (base::LowerCaseEqualsASCII(mime_type, "application/ogg"))
return true;
return false;
}
// This corresponds to https://fetch.spec.whatwg.org/#ok-status
bool IsOkayHttpStatus(const mojom::URLResponseHead& response) {
if (!response.headers)
return false;
int code = response.headers->response_code();
return (200 <= code) && (code <= 299);
}
bool IsHttpStatus(const mojom::URLResponseHead& response,
int expected_status_code) {
if (!response.headers)
return false;
int code = response.headers->response_code();
return code == expected_status_code;
}
bool IsOpaqueResponse(const absl::optional<url::Origin>& request_initiator,
mojom::RequestMode request_mode,
const mojom::URLResponseHead& response) {
// ORB only applies to "no-cors" requests.
if (request_mode != mojom::RequestMode::kNoCors)
return false;
// Browser-initiated requests are never opaque.
if (!request_initiator.has_value())
return false;
// Requests from foo.example.com will consult foo.example.com's service worker
// first (if one has been registered). The service worker can handle requests
// initiated by foo.example.com even if they are cross-origin (e.g. requests
// for bar.example.com). This is okay, because there is no security boundary
// between foo.example.com and the service worker of foo.example.com + because
// the response data is "conjured" within the service worker of
// foo.example.com (rather than being fetched from bar.example.com).
// Therefore such responses should not be blocked by CORB, unless the
// initiator opted out of CORS / opted into receiving an opaque response. See
// also https://crbug.com/803672.
if (response.was_fetched_via_service_worker) {
switch (response.response_type) {
case network::mojom::FetchResponseType::kBasic:
case network::mojom::FetchResponseType::kCors:
case network::mojom::FetchResponseType::kDefault:
case network::mojom::FetchResponseType::kError:
// Non-opaque responses shouldn't be blocked.
return false;
case network::mojom::FetchResponseType::kOpaque:
case network::mojom::FetchResponseType::kOpaqueRedirect:
// Opaque responses are eligible for blocking. Continue on...
break;
}
}
return true;
}
ResponseHeadersHeuristicForUma CalculateResponseHeadersHeuristicForUma(
const GURL& request_url,
const absl::optional<url::Origin>& request_initiator,
mojom::RequestMode request_mode,
const mojom::URLResponseHead& response) {
// Exclude responses that ORB doesn't apply to.
if (!IsOpaqueResponse(request_initiator, request_mode, response))
return ResponseHeadersHeuristicForUma::kNonOpaqueResponse;
DCHECK(request_initiator.has_value());
// Same-origin requests are allowed (the spec doesn't explicitly deal with
// this).
url::Origin target_origin = url::Origin::Create(request_url);
if (request_initiator->IsSameOriginWith(target_origin))
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
// Presence of an "X-Content-Type-Options: nosniff" header means that ORB will
// reach a final decision in step 8, before reaching Javascript parsing in
// step 12:
// step 8. If nosniff is true, then return false.
// ...
// step 12. If response's body parses as JavaScript ...
if (CrossOriginReadBlocking::CorbResponseAnalyzer::HasNoSniff(response))
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
// If a mime type is missing then ORB will reach a final decision in step 10,
// before reaching Javascript parsing in step 12:
// step 10. If mimeType is failure, then return true.
// ...
// step 12. If response's body parses as JavaScript ...
std::string mime_type;
if (!response.headers || !response.headers->GetMimeType(&mime_type))
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
// Specific MIME types might make ORB reach a final decision before reaching
// Javascript parsing step:
// step 3.i. If mimeType is an opaque-safelisted MIME type, then return
// true.
// step 3.ii. If mimeType is an opaque-blocklisted-never-sniffed MIME
// type, then return false.
// ...
// step 11. If mimeType's essence starts with "audio/", "image/", or
// "video/", then return false.
// ...
// step 12. If response's body parses as JavaScript ...
if (IsOpaqueBlocklistedNeverSniffedMimeType(mime_type) ||
IsOpaqueSafelistedMimeType(mime_type) ||
IsSniffableMultimediaType(mime_type)) {
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
}
constexpr auto kCaseInsensitive = base::CompareCase::INSENSITIVE_ASCII;
if (base::StartsWith(mime_type, "audio/", kCaseInsensitive) ||
base::StartsWith(mime_type, "image/", kCaseInsensitive) ||
base::StartsWith(mime_type, "video/", kCaseInsensitive)) {
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
}
// If the http response indicates an error, or a 206 response, then ORB will
// reach a final decision before reaching Javascript parsing in step 12:
// step 9. If response's status is not an ok status, then return false.
// ...
// step 12. If response's body parses as JavaScript ...
if (!IsOkayHttpStatus(response) || IsHttpStatus(response, 206))
return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders;
// Otherwise we need to parse the response body as Javascript.
return ResponseHeadersHeuristicForUma::kRequiresJavascriptParsing;
}
} // namespace
void LogUmaForOpaqueResponseBlocking(
const GURL& request_url,
const absl::optional<url::Origin>& request_initiator,
mojom::RequestMode request_mode,
mojom::RequestDestination request_destination,
const mojom::URLResponseHead& response) {
ResponseHeadersHeuristicForUma response_headers_decision =
CalculateResponseHeadersHeuristicForUma(request_url, request_initiator,
request_mode, response);
base::UmaHistogramEnumeration(
"SiteIsolation.ORB.ResponseHeadersHeuristic.Decision",
response_headers_decision);
switch (response_headers_decision) {
case ResponseHeadersHeuristicForUma::kNonOpaqueResponse:
break;
case ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders:
base::UmaHistogramEnumeration(
"SiteIsolation.ORB.ResponseHeadersHeuristic.ProcessedBasedOnHeaders",
request_destination);
break;
case ResponseHeadersHeuristicForUma::kRequiresJavascriptParsing:
base::UmaHistogramEnumeration(
"SiteIsolation.ORB.ResponseHeadersHeuristic."
"RequiresJavascriptParsing",
request_destination);
break;
}
}
} // namespace corb
} // namespace network
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
276d377bc639bd527c47c17429f3c83d771d7f41 | 93a939e249c8c2f5c3c3957e1c3057ce2eda2331 | /lib/interface.cpp | 27469623cdb2d99280800d2b8ea5cc048893040a | [] | no_license | mediabuff/cpp_modules_sample | 64bdf32e70025cb82b83d58e13bb89078b04474f | 7dadf4c9b1ed080648de4df97dab1b7965c00635 | refs/heads/master | 2021-06-19T12:06:10.915820 | 2017-07-09T15:40:57 | 2017-07-09T15:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | cpp | module pets;
export module pets.pet;
export module pets.dog;
| [
"marius.elvert@googlemail.com"
] | marius.elvert@googlemail.com |
0ccd60e9ca4761a4c5c094647ce55d8d8c969c8a | 379b5265e055d4b0fc5c005974b09c2c12ede3b3 | /getting-started/hello-triangle/main.cpp | a204582e29b26b2938fa204f13c7bbd007a52333 | [] | no_license | jshuam/learn-opengl | fe69aa82ede22c86ea6061235022b7a63a4d8777 | d92c699b7db52f068dc8eaedd55bb23515a429d4 | refs/heads/master | 2022-11-16T23:41:09.786452 | 2020-07-08T11:11:07 | 2020-07-08T11:11:07 | 257,940,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,624 | cpp | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"\n"
"void main()\n"
"{\n"
" FragColor = vec4(0.416f, 0.353f, 0.804f, 1.0f);\n"
"}";
const char* fragmentShaderSource2 = "#version 330 core\n"
"out vec4 FragColor;\n"
"\n"
"void main()\n"
"{\n"
" FragColor = vec4(0.000f, 0.980f, 0.604f, 1.0f);\n"
"}";
float vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f };
float rectVertices[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f };
unsigned int indices[] = { 0, 1, 3, 1, 2, 3 };
unsigned int VAO[2];
bool drawTriangle = true;
bool wireframeMode = false;
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)
{
drawTriangle = true;
}
if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS)
{
drawTriangle = false;
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
wireframeMode = !wireframeMode;
if (wireframeMode)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
}
unsigned int createShaderProgram(const char* vertexSource, const char* fragmentSource);
int main(void)
{
if (!glfwInit())
{
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
GLFWwindow* window = glfwCreateWindow(800, 600, "Hello Window", NULL, NULL);
if (window == NULL)
{
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK)
{
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetKeyCallback(window, key_callback);
glClearColor(0.529f, 0.808f, 0.980f, 1.0f);
unsigned int buffers[3];
glGenVertexArrays(2, VAO);
glGenBuffers(3, buffers);
glBindVertexArray(VAO[0]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[2]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(VAO[1]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(rectVertices), rectVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
unsigned int shaderPrograms[2];
shaderPrograms[0] = createShaderProgram(vertexShaderSource, fragmentShaderSource);
shaderPrograms[1] = createShaderProgram(vertexShaderSource, fragmentShaderSource2);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
if (drawTriangle)
{
glUseProgram(shaderPrograms[0]);
glBindVertexArray(VAO[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
else
{
glUseProgram(shaderPrograms[1]);
glBindVertexArray(VAO[1]);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
for (auto shaderProgram : shaderPrograms)
{
glDeleteProgram(shaderProgram);
}
glDeleteVertexArrays(2, VAO);
glDeleteBuffers(3, buffers);
glfwTerminate();
return 0;
}
unsigned int createShaderProgram(const char* vertexSource, const char* fragmentSource)
{
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cerr << "Failed to compile vertex shader\n" << infoLog << std::endl;
return -1;
}
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cerr << "Failed to compile fragment shader\n" << infoLog << std::endl;
return -1;
}
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cerr << "Failed to link program\n" << infoLog << std::endl;
return -1;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
| [
"jshuam0@gmail.com"
] | jshuam0@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.